/*! * Copyright (c) Microsoft Corporation and contributors. All rights reserved. * Licensed under the MIT License. */ import type { IContainerRuntime, IContainerRuntimeInternal, } from "@fluidframework/container-runtime-definitions/internal"; import { fluidHandleSymbol, type IFluidHandle, type IFluidHandleErased, } from "@fluidframework/core-interfaces"; import type { IFluidHandleInternal, IFluidHandleInternalPayloadPending, IFluidHandlePayloadPending, ILocalFluidHandle, } from "@fluidframework/core-interfaces/internal"; import type { IContainerRuntimeBase, IContainerRuntimeBaseInternal, PackagePath, } from "@fluidframework/runtime-definitions/internal"; /** * JSON serialized form of an IFluidHandle * @internal */ export interface ISerializedHandle { // Marker to indicate to JSON.parse that the object is a Fluid handle type: "__fluid_handle__"; // URL to the object. Relative URLs are relative to the handle context passed to the stringify. url: string; /** * The handle may have a pending payload, as determined by and resolvable by the subsystem that * the handle relates to. For instance, the BlobManager uses this to distinguish blob handles * which may not yet have an attached blob yet. * * @remarks * Will only exist if the handle was created with a pending payload, will be omitted entirely from * the serialized format if the handle was created with an already-shared payload. */ readonly payloadPending?: true; } /** * Narrow a value to {@link ISerializedHandle} by checking its type property. * @internal */ export const isSerializedHandle = (value: unknown): value is ISerializedHandle => // Type assertion is safe as we're only checking for the existence of the type property (value as { type?: string } | undefined)?.type === "__fluid_handle__"; /** * Checks if a Fluid handle's internal payload is pending. * @internal */ export const isFluidHandleInternalPayloadPending = ( fluidHandleInternal: IFluidHandleInternal, ): fluidHandleInternal is IFluidHandleInternalPayloadPending => "payloadPending" in fluidHandleInternal && fluidHandleInternal.payloadPending === true; /** * Check if the handle is an IFluidHandlePayloadPending. * @privateRemarks * This should be true for locally-created BlobHandles currently. When IFluidHandlePayloadPending is merged * to IFluidHandle, this type guard will no longer be necessary. * @legacy @beta */ export const isFluidHandlePayloadPending = ( handle: IFluidHandle, ): handle is IFluidHandlePayloadPending => "payloadState" in handle && (handle.payloadState === "shared" || handle.payloadState === "pending"); /** * Check if the handle is an ILocalFluidHandle. * @legacy @beta */ export const isLocalFluidHandle = ( handle: IFluidHandle, ): handle is ILocalFluidHandle => isFluidHandlePayloadPending(handle) && "payloadShareError" in handle; /** * Encodes the given IFluidHandle into a JSON-serializable form, * @param handle - The IFluidHandle to serialize. * @returns The serialized handle. * * @internal */ export function encodeHandleForSerialization(handle: IFluidHandleInternal): ISerializedHandle { return isFluidHandleInternalPayloadPending(handle) ? { type: "__fluid_handle__", url: handle.absolutePath, payloadPending: true, } : { type: "__fluid_handle__", url: handle.absolutePath, }; } /** * Check if a value is an {@link @fluidframework/core-interfaces#IFluidHandle}. * @public */ export function isFluidHandle(value: unknown): value is IFluidHandle { return typeof value === "object" && value !== null && fluidHandleSymbol in value; } /** * Compare two {@link @fluidframework/core-interfaces#IFluidHandle|IFluidHandles}. * @remarks * Returns true iff both handles have the same internal `absolutePath`. * @public */ export function compareFluidHandles(a: IFluidHandle, b: IFluidHandle): boolean { const aInternal = toFluidHandleInternal(a); const bInternal = toFluidHandleInternal(b); return aInternal.absolutePath === bInternal.absolutePath; } function hasDataStorePackagePath( runtime: IContainerRuntimeBase, ): runtime is IContainerRuntimeBase & Pick { return ( "getDataStorePackagePath" in runtime && typeof runtime.getDataStorePackagePath === "function" ); } /** * Returns the package path of the data store containing the object referenced by a handle. * * @remarks * Use this path in telemetry to identify the containing data store package, for example, when a component * takes a long time to load. The path is diagnostic information; it cannot be used to configure the runtime. * This function does not measure load time. If the data store's snapshot details are not yet available, the * lookup may fetch an omitted snapshot and read its attributes blob. It can therefore take time and affect * the timing of other operations. A completed data store load has already read these details, so a lookup * after loading normally reuses them. Avoid awaiting the lookup on a latency-sensitive load path. * * The handle must belong to the supplied container runtime's container. This function does not verify that * relationship or resolve the handle. It does not check whether a descendant object exists or return a DDS * package path. An invalid handle or a runtime without the internal package-path lookup causes a TypeError. * * @param containerRuntime - The runtime of the container containing the handle. * @param handle - A handle to a data store or an object within one. * @returns The containing data store's package path, or undefined if the handle's path is not within a known data store. * @legacy @beta */ export async function getDataStorePackagePath( containerRuntime: IContainerRuntimeBase, handle: IFluidHandle, ): Promise { const nodePath = toFluidHandleInternal(handle).absolutePath; if (!hasDataStorePackagePath(containerRuntime)) { throw new TypeError("Container runtime does not support data store package path lookup"); } return containerRuntime.getDataStorePackagePath(nodePath); } /** * Downcast an IFluidHandle to an IFluidHandleInternal. * @legacy @beta */ export function toFluidHandleInternal(handle: IFluidHandle): IFluidHandleInternal { if (!(fluidHandleSymbol in handle) || !(fluidHandleSymbol in handle[fluidHandleSymbol])) { throw new TypeError("Invalid IFluidHandle"); } // This casts the IFluidHandleErased from the symbol instead of `handle` to ensure that if someone // implements their own IFluidHandle in terms of an existing handle, it won't break anything. // Type assertion is safe as fluidHandleSymbol is guaranteed to contain an IFluidHandleInternal return handle[fluidHandleSymbol] as unknown as IFluidHandleInternal; } /** * Type erase IFluidHandleInternal for use with {@link @fluidframework/core-interfaces#fluidHandleSymbol}. * @legacy @beta */ export function toFluidHandleErased( handle: IFluidHandleInternal, ): IFluidHandleErased { // Type assertion is safe as we're intentionally erasing internal type information return handle as unknown as IFluidHandleErased; } /** * Base class which can be uses to assist implementing IFluidHandleInternal. * @legacy @beta */ export abstract class FluidHandleBase implements IFluidHandleInternal { public abstract absolutePath: string; public abstract attachGraph(): void; public abstract readonly isAttached: boolean; public abstract get(): Promise; /** * {@inheritDoc @fluidframework/core-interfaces#IProvideFluidHandle.IFluidHandle} */ public get IFluidHandle(): IFluidHandleInternal { return this; } public get [fluidHandleSymbol](): IFluidHandleErased { return toFluidHandleErased(this); } } /** * Lookup the blob storage ID for a blob handle. * @param containerRuntime - The container runtime instance * @param handle - The blob handle to lookup the storage ID for * @returns The storage ID if found and the blob is not pending, undefined otherwise * @remarks * This is a legacy+alpha helper function that provides access to blob storage IDs. * For blobs with pending payloads (localId exists but upload hasn't finished), this is expected to return undefined. * Consumers should use the observability APIs on the handle (handle.payloadState, payloadShared event) * to understand/wait for storage ID availability. * Similarly, when the runtime is detached, this will return undefined as no blobs have been uploaded to storage. * * Warning: the returned blob URL may expire and does not support permalinks. * This API is intended for temporary integration scenarios only. * @legacy * @alpha */ export function lookupTemporaryBlobStorageId( containerRuntime: IContainerRuntime, handle: IFluidHandle, ): string | undefined { // Verify that the handle points to a blob by checking its path format const absolutePath: string | undefined = toFluidHandleInternal(handle).absolutePath; // Blob handles have paths in the format "/_blobs/{localId}" if (!absolutePath?.startsWith("/_blobs/")) { throw new Error( "Handle does not point to a blob - expected path to start with '/_blobs/'", ); } // Extract the local ID from the path const pathParts = absolutePath.split("/"); if ( pathParts.length !== 3 || pathParts[1] !== "_blobs" || pathParts[2] === undefined || pathParts[2] === "" ) { throw new Error("Invalid blob handle path format"); } const localId = pathParts[2]; // Cast the runtime to the internal interface and call the lookup method const internalRuntime = containerRuntime as IContainerRuntimeInternal; return internalRuntime.lookupTemporaryBlobStorageId(localId); }