/*! * Copyright (c) Microsoft Corporation and contributors. All rights reserved. * Licensed under the MIT License. */ import type { IAudience } from "@fluidframework/container-definitions"; import { AttachState, type IContainer } from "@fluidframework/container-definitions/internal"; import type { IRequest } from "@fluidframework/core-interfaces"; import { ErasedTypeImplementation } from "@fluidframework/core-interfaces/internal"; import { assert } from "@fluidframework/core-utils/internal"; import { type DataStoreKey, type DataStoreKind, type DataStoreRegistry, type FluidContainerAttached, type FluidContainerWithService, lookupInRegistry, } from "@fluidframework/driver-definitions/internal"; import type { IContainerRuntimeBase, IFluidDataStoreChannel, IFluidDataStoreContext, IFluidDataStoreFactory, IFluidDataStoreRegistry, IProvideFluidDataStoreRegistry, } from "@fluidframework/runtime-definitions/internal"; import { UsageError } from "@fluidframework/telemetry-utils/internal"; /* * This file provides common implementation logic for ServiceClient implementations. */ /** * Implementation of `DataStoreKind`. * @internal */ export class DataStoreKindImplementation extends ErasedTypeImplementation> implements DataStoreKind, IFluidDataStoreFactory { /** * Type guard for narrowing unions which contain DataStoreKind to DataStoreKind. */ public static guard( value: T, ): value is DataStoreKindImplementation ? T2 : never> & T { return value instanceof DataStoreKindImplementation; } /** * Type guard for narrowing unions which contain DataStoreKind to DataStoreKind. */ public static narrowGeneric( value: T, ): asserts value is DataStoreKindImplementation< T extends DataStoreKind ? T2 : never > & T { if (!DataStoreKindImplementation.guard(value)) { throw new Error("Invalid DataStoreKindImplementation"); } } public readonly type: string; public readonly createDataStore?: (context: IFluidDataStoreContext) => { readonly runtime: IFluidDataStoreChannel; }; public constructor( private readonly factory: Pick< DataStoreKindImplementation, "type" | "instantiateDataStore" | "createDataStore" > & Partial> & { readonly IFluidDataStoreRegistry?: IFluidDataStoreRegistry | undefined; }, ) { super(); this.type = factory.type; if (factory.createDataStore !== undefined) { this.createDataStore = factory.createDataStore.bind(factory); } } public async instantiateDataStore( context: IFluidDataStoreContext, existing: boolean, ): Promise { return this.factory.instantiateDataStore(context, existing); } public get IFluidDataStoreFactory(): IFluidDataStoreFactory { // Legacy creation must see the original factory identity and receiver, not the kind wrapper. return this.factory.IFluidDataStoreFactory ?? this; } public get IFluidDataStoreRegistry(): IFluidDataStoreRegistry | undefined { return this.factory.IFluidDataStoreRegistry; } public async adapt(value: Promise): Promise> { const input = await value; if (input === this) { return this; } if (input.type === this.type) { throw new UsageError(`Conflicting DataStoreKinds with same type: ${this.type}`); } throw new UsageError( `Mismatched DataStoreKind type. Expected: ${this.type}, got: ${input.type}`, ); } } /** * Cache for {@link dataStoreKindFromFactory}. */ const legacyKinds = new WeakMap(); /** * Adapt an {@link @fluidframework/runtime-definitions#IFluidDataStoreFactory} into a {@link @fluidframework/driver-definitions#DataStoreKind}. * @remarks * This allows use of some of the `@legacy` API surface with the new {@link @fluidframework/driver-definitions#ServiceClient} APIs, * helping enable incremental migration to the new API surface. * * Repeated calls with the same factory return the same kind. * Different factories remain different kinds, even if they have the same type identifier. * * The caller must ensure that the factory's entry point is a `T`. * Legacy factories do not encode that type, so this function cannot check it. * * This does not change root discovery: {@link @fluidframework/driver-definitions#ServiceClient} currently expects the `root` data-store alias. * For other conventions, load and resolve the root with your existing legacy APIs, then use {@link fluidContainerFromLegacy}. * @typeParam T - The value type returned by the legacy factory's * {@link @fluidframework/runtime-definitions#IFluidDataStoreChannel.entryPoint | entry-point handle}. * @param factory - The existing data-store factory. * @returns The kind for the factory, with the caller-specified entry-point type. * @legacy * @alpha */ export function dataStoreKindFromFactory( factory: IFluidDataStoreFactory, ): DataStoreKind { let kind = legacyKinds.get(factory); if (kind === undefined) { kind = new DataStoreKindImplementation(factory); legacyKinds.set(factory, kind); } // Legacy factories erase their entry-point type; the caller supplies it at this boundary. return kind as DataStoreKind; } /** * Shared base class for all `ServiceClient` container implementations. * * @remarks * Extends `ErasedTypeImplementation` so that * {@link getContainerAudience} can narrow via `ServiceContainerBase.narrow()`. * * @internal */ export abstract class ServiceContainerBase extends ErasedTypeImplementation> implements FluidContainerWithService { /** * True if an attempt to attach has been started. This is used to prevent multiple concurrent attach attempts. */ private startedAttach = false; protected constructor( public readonly registry: DataStoreRegistry, public readonly options: TOptions, public readonly container: IContainer, public readonly data: TData, public id: string | undefined, ) { super(); } /** * Creates the service-specific request used to attach this container. * @remarks * Called by {@link ServiceContainerBase.attach} after validating that no attach is already in progress. */ protected abstract createAttachRequest(): IRequest; /** * Extracts the container ID from {@link ServiceContainerBase.container}'s resolved URL after attachment. * @remarks * Override when the service's resolved URL stores the id in a non-standard field. */ protected getContainerId(): string { if (this.container.resolvedUrl === undefined) { throw new Error("Resolved URL unexpectedly missing!"); } return this.container.resolvedUrl.id; } public async attach(): Promise> { if (this.id !== undefined) { throw new UsageError("Container already attached"); } if (this.startedAttach) { throw new UsageError("Container attach already in progress"); } assert( this.container.attachState === AttachState.Detached, 0xd15 /* Container not detached */, ); this.startedAttach = true; // TODO: support setting where attach can fail, and leave the container in a valid (non-closed) state. // Likely the best way to support this is by adding a `tryAttach(request): Promise | undefined>`. await this.container.attach(this.createAttachRequest()); // This type cast is needed to work around the fact that TypeScript assumes the "attach" methods can't modify "attachState". assert( this.container.attachState === (AttachState.Attached as AttachState), 0xd16 /* Container failed to attach */, ); this.id = this.getContainerId(); return this as typeof this & { id: string }; } public get audience(): IAudience { return this.container.audience; } public getRuntime(): IContainerRuntimeBase { // The runtime is not part of the public IContainer surface, so it is reached via a structural cast. // This relies on an implementation detail of the containers produced by the loader // (createDetachedContainer / loadExistingContainer): they carry a `runtime` property. // The undefined guard below turns an incompatible container implementation into a clear error // instead of a confusing failure later when the missing runtime is used. // This is extra risky since IContainer is not marked sealed. // TODO: Replace this with a supported, type-safe accessor once the loader exposes one. interface IContainerWithRuntime extends IContainer { readonly runtime?: IContainerRuntimeBase; } const container = this.container as IContainerWithRuntime; if (container.runtime === undefined) { throw new Error( "Container does not expose a runtime: incompatible container implementation.", ); } return container.runtime; } public close(): void { // TODO: `container.close()` cancels the container runtime's GC timers, but a couple of // container-level timers are only bounded `setTimeout`s that survive close (they are not // cancelled here, nor even on `dispose`): // - The container-loader `NoopHeuristic` timer (~2s), which has no disposal hook. // - The container-runtime `SummaryManager` "delay before creating summarizer" timer, whose // pending timeout is not cleared when the SummaryManager is torn down. // These self-expire, so they do not cause indefinite hangs, but until they fire they keep the // Node.js event loop alive, delaying a clean process exit after close. That is a common reason // tests resort to Mocha's `--exit` flag. Ideally close() (via the runtime's close path) would // cancel these too so that closing a single container is sufficient to release all its timers. this.container.close(); } public async createDataStore(key: DataStoreKey): Promise { const kind = await lookupInRegistry(this.registry, key); DataStoreKindImplementation.narrowGeneric(kind); const containerRuntime: IContainerRuntimeBase & Partial = this.getRuntime(); const registry = containerRuntime.IFluidDataStoreRegistry; if (registry === undefined) { throw new UsageError("The container runtime does not expose a data-store registry"); } // Look up the runtime's registered factory to check it matches the requested kind. // Prefer synchronous lookup, falling back to async lookup if unavailable or no entry is returned. const registered = registry.getSync?.(kind.type) ?? (await registry.get(kind.type)); if (registered?.IFluidDataStoreFactory !== kind.IFluidDataStoreFactory) { throw new UsageError( "The data-store kind does not match the factory registered in the container runtime", ); } // Use the runtime's creation API rather than invoking the factory and attaching its runtime directly. // This initializes the context's child registry before the factory runs, so it can create child stores. const dataStore = await containerRuntime.createDataStore(kind.type); const entryPoint = await dataStore.entryPoint.get(); // The data store's entry point type is erased at the registry boundary; // the DataStoreKind used to create it guarantees the entry point is a T. return entryPoint as T; } } /** * Exposes an attached legacy container through the alpha container API. * @remarks * Resolve the application's root using its existing legacy APIs and pass that value as `data`. * No root alias, named channel, handle, or document content is changed. * Closing the returned container closes the original container. * @param container - The attached legacy container. * @param data - The application-facing root value selected using legacy APIs. * @param registry - Kinds whose factories are already registered in the existing runtime; use {@link dataStoreKindFromFactory} to adapt legacy factories. * Used by {@link @fluidframework/driver-definitions#DataStoreCreator.createDataStore}; does not install factories in that runtime. * @param id - The service-facing ID used to reopen this document. * This need not equal `container.resolvedUrl.id`: for example, ODSP uses an item ID to reopen a document, while its resolved URL ID is a hash. * @returns An alpha view of the same attached container. * @throws If the container is not attached. * @legacy * @alpha */ export function fluidContainerFromLegacy( container: IContainer, data: T, registry: DataStoreRegistry, id: string, ): FluidContainerAttached { if (container.attachState !== AttachState.Attached) { throw new UsageError("The legacy container must be attached"); } return new LegacyServiceContainer(registry, container, data, id); } class LegacyServiceContainer extends ServiceContainerBase { public constructor( registry: DataStoreRegistry, container: IContainer, data: T, public override readonly id: string, ) { super(registry, undefined, container, data, id); } protected createAttachRequest(): IRequest { throw new UsageError("The legacy container is already attached"); } } /** * All clients connected to the op stream, both read-only and read/write. * @remarks * Currently just {@link @fluidframework/container-definitions#IAudience}, but may diverge before stabilizing. * @privateRemarks * This is currently just an alias for IAudience, but it is defined separately to allow for: * 1. Following the no I prefix naming convention. * 2. The possibility of diverging from IAudience in the future if desired. * 3. Make it easy for the reexport from fluid-framework to be `@alpha` so the name is not locked down prematurely. * @sealed @alpha */ export type Audience = IAudience; /** * Gets the {@link Audience} from a Fluid container * created by any {@link @fluidframework/driver-definitions#ServiceClient}. * @privateRemarks * This is exposed via a free function rather than as a property of FluidContainerAttached * for a few minor reasons: * 1. This allows stabilizing the FluidContainerAttached API independently committing to how we want to expose the audience. * 2. This demonstrates the pattern of how we can have possible less stable APIs to expose service specific features without them being part of the core FluidContainer API. * This will be important for both new feature stabilization, and also exposing anything needed for legacy interop. * @alpha */ export function getContainerAudience(container: FluidContainerAttached): Audience { ServiceContainerBase.narrow(container); return container.audience; }