@fluidframework/odsp-driver 1.0.1 → 1.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/compactSnapshotParser.d.ts +1 -1
- package/dist/compactSnapshotParser.d.ts.map +1 -1
- package/dist/compactSnapshotParser.js +7 -4
- package/dist/compactSnapshotParser.js.map +1 -1
- package/dist/compactSnapshotWriter.d.ts +1 -1
- package/dist/compactSnapshotWriter.d.ts.map +1 -1
- package/dist/compactSnapshotWriter.js +4 -3
- package/dist/compactSnapshotWriter.js.map +1 -1
- package/dist/contracts.d.ts +1 -1
- package/dist/contracts.d.ts.map +1 -1
- package/dist/contracts.js.map +1 -1
- package/dist/createFile.d.ts.map +1 -1
- package/dist/createFile.js.map +1 -1
- package/dist/createNewUtils.d.ts +1 -1
- package/dist/createNewUtils.d.ts.map +1 -1
- package/dist/createNewUtils.js +1 -0
- package/dist/createNewUtils.js.map +1 -1
- package/dist/fetchSnapshot.d.ts +7 -6
- package/dist/fetchSnapshot.d.ts.map +1 -1
- package/dist/fetchSnapshot.js +57 -31
- package/dist/fetchSnapshot.js.map +1 -1
- package/dist/index.d.ts +2 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +3 -0
- package/dist/index.js.map +1 -1
- package/dist/odspDocumentDeltaConnection.d.ts.map +1 -1
- package/dist/odspDocumentDeltaConnection.js +17 -17
- package/dist/odspDocumentDeltaConnection.js.map +1 -1
- package/dist/odspDocumentService.d.ts.map +1 -1
- package/dist/odspDocumentService.js +8 -4
- package/dist/odspDocumentService.js.map +1 -1
- package/dist/odspDocumentStorageManager.d.ts +2 -2
- package/dist/odspDocumentStorageManager.d.ts.map +1 -1
- package/dist/odspDocumentStorageManager.js +13 -13
- package/dist/odspDocumentStorageManager.js.map +1 -1
- package/dist/odspError.d.ts +3 -1
- package/dist/odspError.d.ts.map +1 -1
- package/dist/odspError.js +14 -5
- package/dist/odspError.js.map +1 -1
- package/dist/odspPublicUtils.d.ts +14 -0
- package/dist/odspPublicUtils.d.ts.map +1 -1
- package/dist/odspPublicUtils.js.map +1 -1
- package/dist/odspSnapshotParser.d.ts +2 -2
- package/dist/odspSnapshotParser.d.ts.map +1 -1
- package/dist/odspSnapshotParser.js +7 -4
- package/dist/odspSnapshotParser.js.map +1 -1
- package/dist/odspUtils.d.ts +0 -7
- package/dist/odspUtils.d.ts.map +1 -1
- package/dist/odspUtils.js +4 -3
- package/dist/odspUtils.js.map +1 -1
- package/dist/packageVersion.d.ts +1 -1
- package/dist/packageVersion.js +1 -1
- package/dist/packageVersion.js.map +1 -1
- package/lib/compactSnapshotParser.d.ts +1 -1
- package/lib/compactSnapshotParser.d.ts.map +1 -1
- package/lib/compactSnapshotParser.js +7 -4
- package/lib/compactSnapshotParser.js.map +1 -1
- package/lib/compactSnapshotWriter.d.ts +1 -1
- package/lib/compactSnapshotWriter.d.ts.map +1 -1
- package/lib/compactSnapshotWriter.js +4 -3
- package/lib/compactSnapshotWriter.js.map +1 -1
- package/lib/contracts.d.ts +1 -1
- package/lib/contracts.d.ts.map +1 -1
- package/lib/contracts.js.map +1 -1
- package/lib/createFile.d.ts.map +1 -1
- package/lib/createFile.js.map +1 -1
- package/lib/createNewUtils.d.ts +1 -1
- package/lib/createNewUtils.d.ts.map +1 -1
- package/lib/createNewUtils.js +1 -0
- package/lib/createNewUtils.js.map +1 -1
- package/lib/fetchSnapshot.d.ts +7 -6
- package/lib/fetchSnapshot.d.ts.map +1 -1
- package/lib/fetchSnapshot.js +58 -33
- package/lib/fetchSnapshot.js.map +1 -1
- package/lib/index.d.ts +2 -0
- package/lib/index.d.ts.map +1 -1
- package/lib/index.js +3 -0
- package/lib/index.js.map +1 -1
- package/lib/odspDocumentDeltaConnection.d.ts.map +1 -1
- package/lib/odspDocumentDeltaConnection.js +17 -17
- package/lib/odspDocumentDeltaConnection.js.map +1 -1
- package/lib/odspDocumentService.d.ts.map +1 -1
- package/lib/odspDocumentService.js +9 -5
- package/lib/odspDocumentService.js.map +1 -1
- package/lib/odspDocumentStorageManager.d.ts +2 -2
- package/lib/odspDocumentStorageManager.d.ts.map +1 -1
- package/lib/odspDocumentStorageManager.js +13 -13
- package/lib/odspDocumentStorageManager.js.map +1 -1
- package/lib/odspError.d.ts +3 -1
- package/lib/odspError.d.ts.map +1 -1
- package/lib/odspError.js +14 -5
- package/lib/odspError.js.map +1 -1
- package/lib/odspPublicUtils.d.ts +14 -0
- package/lib/odspPublicUtils.d.ts.map +1 -1
- package/lib/odspPublicUtils.js.map +1 -1
- package/lib/odspSnapshotParser.d.ts +2 -2
- package/lib/odspSnapshotParser.d.ts.map +1 -1
- package/lib/odspSnapshotParser.js +5 -2
- package/lib/odspSnapshotParser.js.map +1 -1
- package/lib/odspUtils.d.ts +0 -7
- package/lib/odspUtils.d.ts.map +1 -1
- package/lib/odspUtils.js +4 -3
- package/lib/odspUtils.js.map +1 -1
- package/lib/packageVersion.d.ts +1 -1
- package/lib/packageVersion.js +1 -1
- package/lib/packageVersion.js.map +1 -1
- package/package.json +15 -15
- package/src/compactSnapshotParser.ts +10 -4
- package/src/compactSnapshotWriter.ts +7 -4
- package/src/contracts.ts +1 -1
- package/src/createFile.ts +2 -2
- package/src/createNewUtils.ts +2 -1
- package/src/fetchSnapshot.ts +113 -67
- package/src/index.ts +4 -0
- package/src/odspDocumentDeltaConnection.ts +17 -18
- package/src/odspDocumentService.ts +7 -3
- package/src/odspDocumentStorageManager.ts +18 -15
- package/src/odspError.ts +23 -10
- package/src/odspPublicUtils.ts +17 -0
- package/src/odspSnapshotParser.ts +8 -3
- package/src/odspUtils.ts +4 -11
- package/src/packageVersion.ts +1 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"odspDocumentDeltaConnection.js","sourceRoot":"","sources":["../src/odspDocumentDeltaConnection.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAGH,OAAO,EAAE,MAAM,EAAE,WAAW,EAAE,QAAQ,EAAE,iBAAiB,EAAE,MAAM,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AAE,MAAM,CAAC,CAAC;IACpC,CAAC;CACJ","sourcesContent":["/*!\n * Copyright (c) Microsoft Corporation and contributors. All rights reserved.\n * Licensed under the MIT License.\n */\n\nimport { ITelemetryLogger, IEvent } from \"@fluidframework/common-definitions\";\nimport { assert, performance, Deferred, TypedEventEmitter } from \"@fluidframework/common-utils\";\nimport { DocumentDeltaConnection } from \"@fluidframework/driver-base\";\nimport { OdspError } from \"@fluidframework/odsp-driver-definitions\";\nimport { IAnyDriverError } from \"@fluidframework/driver-utils\";\nimport { IFluidErrorBase, loggerToMonitoringContext } from \"@fluidframework/telemetry-utils\";\nimport {\n IClient,\n IConnect,\n INack,\n ISequencedDocumentMessage,\n ISignalMessage,\n} from \"@fluidframework/protocol-definitions\";\nimport type { Socket, io as SocketIOClientStatic } from \"socket.io-client\";\nimport { v4 as uuid } from \"uuid\";\nimport { IOdspSocketError, IGetOpsResponse, IFlushOpsResponse } from \"./contracts\";\nimport { EpochTracker } from \"./epochTracker\";\nimport { errorObjectFromSocketError } from \"./odspError\";\nimport { pkgVersion } from \"./packageVersion\";\n\nconst protocolVersions = [\"^0.4.0\", \"^0.3.0\", \"^0.2.0\", \"^0.1.0\"];\nconst feature_get_ops = \"api_get_ops\";\nconst feature_flush_ops = \"api_flush_ops\";\n\nexport interface FlushResult {\n lastPersistedSequenceNumber?: number;\n retryAfter?: number;\n}\n\n// How long to wait before disconnecting the socket after the last reference is removed\n// This allows reconnection after receiving a nack to be smooth\nconst socketReferenceBufferTime = 2000;\n\nexport interface ISocketEvents extends IEvent {\n (event: \"server_disconnect\", listener: (error: IFluidErrorBase & OdspError) => void);\n}\n\nclass SocketReference extends TypedEventEmitter<ISocketEvents> {\n private references: number = 1;\n private delayDeleteTimeout: ReturnType<typeof setTimeout> | undefined;\n private _socket: Socket | undefined;\n\n // When making decisions about socket reuse, we do not reuse disconnected socket.\n // But we want to differentiate the following case from disconnected case:\n // Socket that never connected and never failed, it's in \"attempting to connect\" mode\n // such sockets should be reused, despite socket.disconnected === true\n private isPendingInitialConnection = true;\n\n // Map of all existing socket io sockets. [url, tenantId, documentId] -> socket\n private static readonly socketIoSockets: Map<string, SocketReference> = new Map();\n\n public static find(key: string, logger: ITelemetryLogger) {\n const socketReference = SocketReference.socketIoSockets.get(key);\n\n // Verify the socket is healthy before reusing it\n if (socketReference?.disconnected) {\n // The socket is in a bad state. fully remove the reference\n socketReference.closeSocket();\n return undefined;\n }\n\n if (socketReference) {\n // Clear the pending deletion if there is one\n socketReference.clearTimer();\n socketReference.references++;\n }\n\n return socketReference;\n }\n\n /**\n * Removes a reference for the given key\n * Once the ref count hits 0, the socket is disconnected and removed\n * @param key - socket reference key\n * @param isFatalError - true if the socket reference should be removed immediately due to a fatal error\n */\n public removeSocketIoReference(isFatalError: boolean) {\n assert(this.references > 0, 0x09f /* \"No more socketIO refs to remove!\" */);\n this.references--;\n\n // see comment in disconnected() getter\n this.isPendingInitialConnection = false;\n\n if (isFatalError || this.disconnected) {\n this.closeSocket();\n return;\n }\n\n if (this.references === 0 && this.delayDeleteTimeout === undefined) {\n this.delayDeleteTimeout = setTimeout(() => {\n // We should not get here with active users.\n assert(this.references === 0, 0x0a0 /* \"Unexpected socketIO references on timeout\" */);\n this.closeSocket();\n }, socketReferenceBufferTime);\n }\n }\n\n public get socket() {\n if (!this._socket) {\n throw new Error(`Invalid socket for key \"${this.key}`);\n }\n return this._socket;\n }\n\n public constructor(public readonly key: string, socket: Socket) {\n super();\n\n this._socket = socket;\n assert(!SocketReference.socketIoSockets.has(key), 0x220 /* \"socket key collision\" */);\n SocketReference.socketIoSockets.set(key, this);\n\n // The server always closes the socket after sending this message\n // fully remove the socket reference now\n socket.on(\"server_disconnect\", (socketError: IOdspSocketError) => {\n // Treat all errors as recoverable, and rely on joinSession / reconnection flow to\n // filter out retryable vs. non-retryable cases.\n const error = errorObjectFromSocketError(socketError, \"server_disconnect\");\n error.canRetry = true;\n\n // see comment in disconnected() getter\n // Setting it here to ensure socket reuse does not happen if new request to connect\n // comes in from \"disconnect\" listener below, before we close socket.\n this.isPendingInitialConnection = false;\n\n // Explicitly cast error to the specified event args type to ensure type compatibility\n this.emit(\"server_disconnect\", error as IFluidErrorBase & OdspError);\n this.closeSocket();\n });\n }\n\n private clearTimer() {\n if (this.delayDeleteTimeout !== undefined) {\n clearTimeout(this.delayDeleteTimeout);\n this.delayDeleteTimeout = undefined;\n }\n }\n\n private closeSocket() {\n if (!this._socket) { return; }\n\n this.clearTimer();\n\n assert(SocketReference.socketIoSockets.get(this.key) === this,\n 0x0a1 /* \"Socket reference set unexpectedly does not point to this socket!\" */);\n SocketReference.socketIoSockets.delete(this.key);\n\n const socket = this._socket;\n this._socket = undefined;\n\n // Delay closing socket, to make sure all users of socket observe the same event that causes\n // this instance to close, and thus properly record reason for closure.\n // All event raising is synchronous, so clients will have a chance to react before socket is\n // closed without any extra data on why it was closed.\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\n Promise.resolve().then(() => { socket.disconnect(); });\n }\n\n private get disconnected() {\n if (this._socket === undefined) { return true; }\n if (this.socket.connected) { return false; }\n\n // We have a socket that is not connected. Possible cases:\n // 1) It was connected some time ago and lost connection. We do not want to reuse it.\n // 2) It failed to connect (was never connected).\n // 3) It was just created and never had a chance to connect - connection is in process.\n // We have to differentiate 1 from 2-3 (specifically 1 & 3) in order to be able to reuse socket in #3.\n // We will use the fact that socket had some activity. I.e. if socket disconnected, or client stopped using\n // socket, then removeSocketIoReference() will be called for it, and it will be the indiction that it's not #3.\n return !this.isPendingInitialConnection;\n }\n}\n\n/**\n * Represents a connection to a stream of delta updates\n */\nexport class OdspDocumentDeltaConnection extends DocumentDeltaConnection {\n /**\n * Create a OdspDocumentDeltaConnection\n * If url #1 fails to connect, will try url #2 if applicable.\n *\n * @param tenantId - the ID of the tenant\n * @param documentId - document ID\n * @param token - authorization token for storage service\n * @param io - websocket library\n * @param client - information about the client\n * @param mode - mode of the client\n * @param url - websocket URL\n * @param telemetryLogger - optional telemetry logger\n * @param timeoutMs - time limit on making the connection\n * @param epochTracker - track epoch changes\n * @param socketReferenceKeyPrefix - (optional) prefix to isolate socket reuse cache\n */\n public static async create(\n tenantId: string,\n documentId: string,\n token: string | null,\n io: typeof SocketIOClientStatic,\n client: IClient,\n url: string,\n telemetryLogger: ITelemetryLogger,\n timeoutMs: number,\n epochTracker: EpochTracker,\n socketReferenceKeyPrefix: string | undefined): Promise<OdspDocumentDeltaConnection> {\n const mc = loggerToMonitoringContext(telemetryLogger);\n\n // enable multiplexing when the websocket url does not include the tenant/document id\n const parsedUrl = new URL(url);\n const enableMultiplexing = !parsedUrl.searchParams.has(\"documentId\") && !parsedUrl.searchParams.has(\"tenantId\");\n\n // do not include the specific tenant/doc id in the ref key when multiplexing\n // this will allow multiple documents to share the same websocket connection\n const key = socketReferenceKeyPrefix ? `${socketReferenceKeyPrefix},${url}` : url;\n const socketReferenceKey = enableMultiplexing ? key : `${key},${tenantId},${documentId}`;\n\n const socketReference = OdspDocumentDeltaConnection.getOrCreateSocketIoReference(\n io, timeoutMs, socketReferenceKey, url, enableMultiplexing, tenantId, documentId, telemetryLogger);\n\n const socket = socketReference.socket;\n\n const connectMessage: IConnect = {\n client,\n id: documentId,\n mode: client.mode,\n tenantId,\n token, // Token is going to indicate tenant level information, etc...\n versions: protocolVersions,\n nonce: uuid(),\n epoch: epochTracker.fluidEpoch,\n relayUserAgent: [client.details.environment, ` driverVersion:${pkgVersion}`].join(\";\"),\n };\n\n // Reference to this client supporting get_ops flow.\n connectMessage.supportedFeatures = { };\n if (mc.config.getBoolean(\"Fluid.Driver.Odsp.GetOpsEnabled\") !== false) {\n connectMessage.supportedFeatures[feature_get_ops] = true;\n }\n\n const deltaConnection = new OdspDocumentDeltaConnection(\n socket,\n documentId,\n socketReference,\n telemetryLogger,\n enableMultiplexing);\n\n try {\n await deltaConnection.initialize(connectMessage, timeoutMs);\n await epochTracker.validateEpochFromPush(deltaConnection.details);\n } catch (errorObject: any) {\n if (errorObject !== null && typeof errorObject === \"object\") {\n // We have to special-case error types here in terms of what is re-triable.\n // These errors have to re-retried, we just need new joinSession result to connect to right server:\n // 400: Invalid tenant or document id. The WebSocket is connected to a different document\n // Document is full (with retryAfter)\n // 404: Invalid document. The document \\\"local/w1-...\\\" does not exist\n // But this has to stay not-retriable:\n // 406: Unsupported client protocol. This path is the only gatekeeper, have to fail!\n // 409: Epoch Version Mismatch. Client epoch and server epoch does not match, so app needs\n // to be refreshed.\n // This one is fine either way\n // 401/403: Code will retry once with new token either way, then it becomes fatal - on this path\n // and on join Session path.\n // 501: (Fluid not enabled): this is fine either way, as joinSession is gatekeeper\n if (errorObject.statusCode === 400 || errorObject.statusCode === 404) {\n errorObject.canRetry = true;\n }\n }\n throw errorObject;\n }\n\n return deltaConnection;\n }\n\n private socketReference: SocketReference | undefined;\n\n private readonly requestOpsNoncePrefix: string;\n private pushCallCounter = 0;\n private readonly getOpsMap: Map<string, { start: number; from: number; to: number; }> = new Map();\n private flushOpNonce: string | undefined;\n private flushDeferred: Deferred<FlushResult> | undefined;\n\n /**\n * Error raising for socket.io issues\n */\n protected createErrorObject(handler: string, error?: any, canRetry = true): IAnyDriverError {\n // Note: we suspect the incoming error object is either:\n // - a socketError: add it to the OdspError object for driver to be able to parse it and reason over it.\n // - anything else: let base class handle it\n if (canRetry && Number.isInteger(error?.code) && typeof error?.message === \"string\") {\n return errorObjectFromSocketError(error as IOdspSocketError, handler);\n } else {\n return super.createErrorObject(handler, error, canRetry);\n }\n }\n\n /**\n * Gets or create a socket io connection for the given key\n */\n private static getOrCreateSocketIoReference(\n io: typeof SocketIOClientStatic,\n timeoutMs: number,\n key: string,\n url: string,\n enableMultiplexing: boolean,\n tenantId: string,\n documentId: string,\n logger: ITelemetryLogger,\n ): SocketReference {\n const existingSocketReference = SocketReference.find(key, logger);\n if (existingSocketReference) {\n return existingSocketReference;\n }\n\n const query = enableMultiplexing ? undefined : { documentId, tenantId };\n\n const socket = io(\n url,\n {\n multiplex: false, // Don't rely on socket.io built-in multiplexing\n query,\n reconnection: false,\n transports: [\"websocket\"],\n timeout: timeoutMs,\n });\n\n return new SocketReference(key, socket);\n }\n\n /**\n * @param socket - websocket to be used\n * @param documentId - ID of the document\n * @param details - details of the websocket connection\n * @param socketReferenceKey - socket reference key\n * @param enableMultiplexing - If the websocket is multiplexing multiple documents\n */\n private constructor(\n socket: Socket,\n documentId: string,\n socketReference: SocketReference,\n logger: ITelemetryLogger,\n private readonly enableMultiplexing?: boolean,\n ) {\n super(socket, documentId, logger);\n this.socketReference = socketReference;\n this.requestOpsNoncePrefix = `${uuid()}-`;\n }\n\n /**\n * Retrieves ops from PUSH\n * @param from - inclusive\n * @param to - exclusive\n * @returns ops retrieved\n */\n public requestOps(from: number, to: number) {\n // Given that to is exclusive, we should be asking for at least something!\n assert(to > from, 0x272 /* \"empty request\" */);\n\n // PUSH may disable this functionality\n // back-compat: remove cast to any once latest version of IConnected is consumed\n if ((this.details as any).supportedFeatures?.[feature_get_ops] !== true) {\n return;\n }\n\n this.pushCallCounter++;\n const nonce = `${this.requestOpsNoncePrefix}${this.pushCallCounter}`;\n const start = performance.now();\n\n // We may keep keep accumulating memory for nothing, if we are not getting responses.\n // Note that we should not have overlapping requests, as DeltaManager allows only one\n // outstanding request to storage, and that's the only way to get here.\n // But requests could be cancelled, and thus overlapping requests might be in the picture\n // If it happens, we do not care about stale requests.\n // So track some number of requests, but log if we get too many in flight - that likely\n // indicates an error somewhere.\n if (this.getOpsMap.size >= 5) {\n let time = start;\n let key: string | undefined;\n for (const [keyCandidate, value] of this.getOpsMap.entries()) {\n if (value.start <= time || key === undefined) {\n time = value.start;\n key = keyCandidate;\n }\n }\n const payloadToDelete = this.getOpsMap.get(key!)!;\n this.logger.sendErrorEvent({\n eventName: \"GetOpsTooMany\",\n nonce,\n from: payloadToDelete.from,\n to: payloadToDelete.to,\n length: payloadToDelete.to - payloadToDelete.from,\n duration: performance.now() - payloadToDelete.start,\n });\n this.getOpsMap.delete(key!);\n }\n this.getOpsMap.set(\n nonce,\n {\n start,\n from,\n to,\n },\n );\n this.socket.emit(\"get_ops\", this.clientId, {\n nonce,\n from,\n to: to - 1,\n });\n }\n\n public async flush(): Promise<FlushResult> {\n // back-compat: remove cast to any once latest version of IConnected is consumed\n if ((this.details as any).supportedFeatures?.[feature_flush_ops] !== true) {\n // Once single-commit summary is enabled end-to-end, flush support is a must!\n // The only alternative is change in design where SPO fetches ops from PUSH OR\n // summary includes required ops and SPO has some validation mechanism to ensure\n // they are not forged by client.\n // If design changes, we can reconsider it, but right now it's non-recoverable failure.\n this.logger.sendErrorEvent({ eventName: \"FlushOpsNotSupported\" });\n throw new Error(\"flush() API is not supported by PUSH, required for single-commit summaries\");\n }\n\n this.pushCallCounter++;\n const nonce = `${this.requestOpsNoncePrefix}${this.pushCallCounter}`;\n // There should be only one flush ops in flight, kicked out by upload summary workflow\n // That said, it could timeout and request could be repeated, so theoretically we can\n // get overlapping requests, but it should be very rare\n if (this.flushDeferred !== undefined) {\n this.logger.sendErrorEvent({ eventName: \"FlushOpsTooMany\" });\n this.flushDeferred.reject(\"process involving flush() was cancelled OR unsupported concurrency\");\n }\n this.socket.emit(\"flush_ops\", this.clientId, { nonce });\n\n this.flushOpNonce = nonce;\n this.flushDeferred = new Deferred<FlushResult>();\n return this.flushDeferred.promise;\n }\n\n protected serverDisconnectHandler = (error: IFluidErrorBase & OdspError) => {\n this.logger.sendTelemetryEvent({ eventName: \"ServerDisconnect\", clientId: this.clientId }, error);\n this.disposeCore(true, error);\n };\n\n protected async initialize(connectMessage: IConnect, timeout: number) {\n if (this.enableMultiplexing) {\n // multiplex compatible early handlers\n this.earlyOpHandler = (messageDocumentId: string, msgs: ISequencedDocumentMessage[]) => {\n if (this.documentId === messageDocumentId) {\n this.queuedMessages.push(...msgs);\n }\n };\n\n this.earlySignalHandler = (msg: ISignalMessage, messageDocumentId?: string) => {\n if (messageDocumentId === undefined || messageDocumentId === this.documentId) {\n this.queuedSignals.push(msg);\n }\n };\n }\n\n this.socketReference!.once(\"server_disconnect\", this.serverDisconnectHandler);\n\n this.socket.on(\"get_ops_response\", (result: IGetOpsResponse) => {\n const messages = result.messages;\n const data = this.getOpsMap.get(result.nonce);\n // Due to socket multiplexing, this client may not have asked for any data\n // If so, there it most likely does not need these ops (otherwise it already asked for them)\n // Also we may have deleted entry in this.getOpsMap due to too many requests and too slow response.\n // But not processing such result may push us into infinite loop of fast requests and dropping all responses\n if (data !== undefined || result.nonce.indexOf(this.requestOpsNoncePrefix) === 0) {\n this.getOpsMap.delete(result.nonce);\n const common = {\n eventName: \"GetOps\",\n // We need nonce only to pair with GetOpsTooMany events, i.e. when record was deleted\n nonce: data === undefined ? result.nonce : undefined,\n code: result.code,\n from: data?.from,\n to: data?.to,\n duration: data === undefined ? undefined : performance.now() - data.start,\n };\n if (messages !== undefined && messages.length > 0) {\n this.logger.sendPerformanceEvent({\n ...common,\n first: messages[0].sequenceNumber,\n last: messages[messages.length - 1].sequenceNumber,\n length: messages.length,\n });\n this.emit(\"op\", this.documentId, messages);\n } else {\n this.logger.sendPerformanceEvent({\n ...common,\n length: 0,\n });\n }\n }\n });\n\n this.socket.on(\"flush_ops_response\", (result: IFlushOpsResponse) => {\n if (this.flushOpNonce === result.nonce) {\n const seq = result.lastPersistedSequenceNumber;\n let category: \"generic\" | \"error\" = \"generic\";\n if (result.lastPersistedSequenceNumber === undefined || result.code !== 200) {\n switch (result.code) {\n case 409:\n case 429:\n category = \"error\";\n break;\n case 204:\n break;\n default:\n category = \"error\";\n break;\n }\n }\n this.logger.sendTelemetryEvent({\n eventName: \"FlushResult\",\n code: result.code,\n sequenceNumber: seq,\n category,\n });\n this.flushDeferred!.resolve(result);\n this.flushDeferred = undefined;\n this.flushOpNonce = undefined;\n }\n });\n\n await super.initialize(connectMessage, timeout);\n }\n\n protected addTrackedListener(event: string, listener: (...args: any[]) => void) {\n // override some event listeners in order to support multiple documents/clients over the same websocket\n switch (event) {\n case \"op\":\n // per document op handling\n super.addTrackedListener(event, (documentId: string, msgs: ISequencedDocumentMessage[]) => {\n if (!this.enableMultiplexing || this.documentId === documentId) {\n listener(documentId, msgs);\n }\n });\n break;\n\n case \"signal\":\n // per document signal handling\n super.addTrackedListener(event, (msg: ISignalMessage, documentId?: string) => {\n if (!this.enableMultiplexing || !documentId || documentId === this.documentId) {\n listener(msg, documentId);\n }\n });\n break;\n\n case \"nack\":\n // per client / document nack handling\n super.addTrackedListener(event, (clientIdOrDocumentId: string, nacks: INack[]) => {\n if (clientIdOrDocumentId.length === 0 ||\n clientIdOrDocumentId === this.documentId ||\n (this.hasDetails && clientIdOrDocumentId === this.clientId)) {\n const nackContent = nacks[0]?.content;\n if (nackContent !== undefined) {\n const { code, type, message, retryAfter } = nackContent;\n this.logger.sendTelemetryEvent({\n eventName: \"ServerNack\",\n code,\n type,\n message,\n retryAfterSeconds: retryAfter,\n clientId: this.clientId,\n });\n }\n this.emit(\"nack\", clientIdOrDocumentId, nacks);\n }\n });\n break;\n\n default:\n super.addTrackedListener(event, listener);\n break;\n }\n }\n\n /**\n * Disconnect from the websocket\n */\n protected disconnect(socketProtocolError: boolean, reason: IAnyDriverError) {\n const socket = this.socketReference;\n assert(socket !== undefined, 0x0a2 /* \"reentrancy not supported!\" */);\n this.socketReference = undefined;\n\n this.socket.off(\"server_disconnect\", this.serverDisconnectHandler);\n\n if (!socketProtocolError && this.hasDetails) {\n // tell the server we are disconnecting this client from the document\n this.socket.emit(\"disconnect_document\", this.clientId, this.documentId);\n }\n\n socket.removeSocketIoReference(socketProtocolError);\n this.emit(\"disconnect\", reason);\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"odspDocumentDeltaConnection.js","sourceRoot":"","sources":["../src/odspDocumentDeltaConnection.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAGH,OAAO,EAAE,MAAM,EAAE,WAAW,EAAE,QAAQ,EAAE,iBAAiB,EAAE,MAAM,8BAA8B,CAAC;AAChG,OAAO,EAAE,uBAAuB,EAAE,MAAM,6BAA6B,CAAC;AA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under the MIT License.\n */\n\nimport { ITelemetryLogger, IEvent } from \"@fluidframework/common-definitions\";\nimport { assert, performance, Deferred, TypedEventEmitter } from \"@fluidframework/common-utils\";\nimport { DocumentDeltaConnection } from \"@fluidframework/driver-base\";\nimport { OdspError } from \"@fluidframework/odsp-driver-definitions\";\nimport { IAnyDriverError } from \"@fluidframework/driver-utils\";\nimport { IFluidErrorBase, loggerToMonitoringContext } from \"@fluidframework/telemetry-utils\";\nimport {\n IClient,\n IConnect,\n INack,\n ISequencedDocumentMessage,\n ISignalMessage,\n} from \"@fluidframework/protocol-definitions\";\nimport type { Socket, io as SocketIOClientStatic } from \"socket.io-client\";\nimport { v4 as uuid } from \"uuid\";\nimport { IOdspSocketError, IGetOpsResponse, IFlushOpsResponse } from \"./contracts\";\nimport { EpochTracker } from \"./epochTracker\";\nimport { errorObjectFromSocketError } from \"./odspError\";\nimport { pkgVersion } from \"./packageVersion\";\n\nconst protocolVersions = [\"^0.4.0\", \"^0.3.0\", \"^0.2.0\", \"^0.1.0\"];\nconst feature_get_ops = \"api_get_ops\";\nconst feature_flush_ops = \"api_flush_ops\";\n\nexport interface FlushResult {\n lastPersistedSequenceNumber?: number;\n retryAfter?: number;\n}\n\n// How long to wait before disconnecting the socket after the last reference is removed\n// This allows reconnection after receiving a nack to be smooth\nconst socketReferenceBufferTime = 2000;\n\nexport interface ISocketEvents extends IEvent {\n (event: \"server_disconnect\", listener: (error: IFluidErrorBase & OdspError) => void);\n}\n\nclass SocketReference extends TypedEventEmitter<ISocketEvents> {\n private references: number = 1;\n private delayDeleteTimeout: ReturnType<typeof setTimeout> | undefined;\n private _socket: Socket | undefined;\n\n // When making decisions about socket reuse, we do not reuse disconnected socket.\n // But we want to differentiate the following case from disconnected case:\n // Socket that never connected and never failed, it's in \"attempting to connect\" mode\n // such sockets should be reused, despite socket.disconnected === true\n private isPendingInitialConnection = true;\n\n // Map of all existing socket io sockets. [url, tenantId, documentId] -> socket\n private static readonly socketIoSockets: Map<string, SocketReference> = new Map();\n\n public static find(key: string, logger: ITelemetryLogger) {\n const socketReference = SocketReference.socketIoSockets.get(key);\n\n // Verify the socket is healthy before reusing it\n if (socketReference?.disconnected) {\n // The socket is in a bad state. fully remove the reference\n socketReference.closeSocket();\n return undefined;\n }\n\n if (socketReference) {\n // Clear the pending deletion if there is one\n socketReference.clearTimer();\n socketReference.references++;\n }\n\n return socketReference;\n }\n\n /**\n * Removes a reference for the given key\n * Once the ref count hits 0, the socket is disconnected and removed\n * @param key - socket reference key\n * @param isFatalError - true if the socket reference should be removed immediately due to a fatal error\n */\n public removeSocketIoReference(isFatalError: boolean) {\n assert(this.references > 0, 0x09f /* \"No more socketIO refs to remove!\" */);\n this.references--;\n\n // see comment in disconnected() getter\n this.isPendingInitialConnection = false;\n\n if (isFatalError || this.disconnected) {\n this.closeSocket();\n return;\n }\n\n if (this.references === 0 && this.delayDeleteTimeout === undefined) {\n this.delayDeleteTimeout = setTimeout(() => {\n // We should not get here with active users.\n assert(this.references === 0, 0x0a0 /* \"Unexpected socketIO references on timeout\" */);\n this.closeSocket();\n }, socketReferenceBufferTime);\n }\n }\n\n public get socket() {\n if (!this._socket) {\n throw new Error(`Invalid socket for key \"${this.key}`);\n }\n return this._socket;\n }\n\n public constructor(public readonly key: string, socket: Socket) {\n super();\n\n this._socket = socket;\n assert(!SocketReference.socketIoSockets.has(key), 0x220 /* \"socket key collision\" */);\n SocketReference.socketIoSockets.set(key, this);\n\n // The server always closes the socket after sending this message\n // fully remove the socket reference now\n socket.on(\"server_disconnect\", (socketError: IOdspSocketError) => {\n // Treat all errors as recoverable, and rely on joinSession / reconnection flow to\n // filter out retryable vs. non-retryable cases.\n const error = errorObjectFromSocketError(socketError, \"server_disconnect\");\n error.canRetry = true;\n\n // see comment in disconnected() getter\n // Setting it here to ensure socket reuse does not happen if new request to connect\n // comes in from \"disconnect\" listener below, before we close socket.\n this.isPendingInitialConnection = false;\n\n // Explicitly cast error to the specified event args type to ensure type compatibility\n this.emit(\"server_disconnect\", error);\n this.closeSocket();\n });\n }\n\n private clearTimer() {\n if (this.delayDeleteTimeout !== undefined) {\n clearTimeout(this.delayDeleteTimeout);\n this.delayDeleteTimeout = undefined;\n }\n }\n\n private closeSocket() {\n if (!this._socket) { return; }\n\n this.clearTimer();\n\n assert(SocketReference.socketIoSockets.get(this.key) === this,\n 0x0a1 /* \"Socket reference set unexpectedly does not point to this socket!\" */);\n SocketReference.socketIoSockets.delete(this.key);\n\n const socket = this._socket;\n this._socket = undefined;\n\n // Delay closing socket, to make sure all users of socket observe the same event that causes\n // this instance to close, and thus properly record reason for closure.\n // All event raising is synchronous, so clients will have a chance to react before socket is\n // closed without any extra data on why it was closed.\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\n Promise.resolve().then(() => { socket.disconnect(); });\n }\n\n private get disconnected() {\n if (this._socket === undefined) { return true; }\n if (this.socket.connected) { return false; }\n\n // We have a socket that is not connected. Possible cases:\n // 1) It was connected some time ago and lost connection. We do not want to reuse it.\n // 2) It failed to connect (was never connected).\n // 3) It was just created and never had a chance to connect - connection is in process.\n // We have to differentiate 1 from 2-3 (specifically 1 & 3) in order to be able to reuse socket in #3.\n // We will use the fact that socket had some activity. I.e. if socket disconnected, or client stopped using\n // socket, then removeSocketIoReference() will be called for it, and it will be the indiction that it's not #3.\n return !this.isPendingInitialConnection;\n }\n}\n\n/**\n * Represents a connection to a stream of delta updates\n */\nexport class OdspDocumentDeltaConnection extends DocumentDeltaConnection {\n /**\n * Create a OdspDocumentDeltaConnection\n * If url #1 fails to connect, will try url #2 if applicable.\n *\n * @param tenantId - the ID of the tenant\n * @param documentId - document ID\n * @param token - authorization token for storage service\n * @param io - websocket library\n * @param client - information about the client\n * @param mode - mode of the client\n * @param url - websocket URL\n * @param telemetryLogger - optional telemetry logger\n * @param timeoutMs - time limit on making the connection\n * @param epochTracker - track epoch changes\n * @param socketReferenceKeyPrefix - (optional) prefix to isolate socket reuse cache\n */\n public static async create(\n tenantId: string,\n documentId: string,\n token: string | null,\n io: typeof SocketIOClientStatic,\n client: IClient,\n url: string,\n telemetryLogger: ITelemetryLogger,\n timeoutMs: number,\n epochTracker: EpochTracker,\n socketReferenceKeyPrefix: string | undefined): Promise<OdspDocumentDeltaConnection> {\n const mc = loggerToMonitoringContext(telemetryLogger);\n\n // enable multiplexing when the websocket url does not include the tenant/document id\n const parsedUrl = new URL(url);\n const enableMultiplexing = !parsedUrl.searchParams.has(\"documentId\") && !parsedUrl.searchParams.has(\"tenantId\");\n\n // do not include the specific tenant/doc id in the ref key when multiplexing\n // this will allow multiple documents to share the same websocket connection\n const key = socketReferenceKeyPrefix ? `${socketReferenceKeyPrefix},${url}` : url;\n const socketReferenceKey = enableMultiplexing ? key : `${key},${tenantId},${documentId}`;\n\n const socketReference = OdspDocumentDeltaConnection.getOrCreateSocketIoReference(\n io, timeoutMs, socketReferenceKey, url, enableMultiplexing, tenantId, documentId, telemetryLogger);\n\n const socket = socketReference.socket;\n\n const connectMessage: IConnect = {\n client,\n id: documentId,\n mode: client.mode,\n tenantId,\n token, // Token is going to indicate tenant level information, etc...\n versions: protocolVersions,\n nonce: uuid(),\n epoch: epochTracker.fluidEpoch,\n relayUserAgent: [client.details.environment, ` driverVersion:${pkgVersion}`].join(\";\"),\n };\n\n // Reference to this client supporting get_ops flow.\n connectMessage.supportedFeatures = { };\n if (mc.config.getBoolean(\"Fluid.Driver.Odsp.GetOpsEnabled\") !== false) {\n connectMessage.supportedFeatures[feature_get_ops] = true;\n }\n\n const deltaConnection = new OdspDocumentDeltaConnection(\n socket,\n documentId,\n socketReference,\n telemetryLogger,\n enableMultiplexing);\n\n try {\n await deltaConnection.initialize(connectMessage, timeoutMs);\n await epochTracker.validateEpochFromPush(deltaConnection.details);\n } catch (errorObject: any) {\n if (errorObject !== null && typeof errorObject === \"object\") {\n // We have to special-case error types here in terms of what is re-triable.\n // These errors have to re-retried, we just need new joinSession result to connect to right server:\n // 400: Invalid tenant or document id. The WebSocket is connected to a different document\n // Document is full (with retryAfter)\n // 404: Invalid document. The document \\\"local/w1-...\\\" does not exist\n // But this has to stay not-retriable:\n // 406: Unsupported client protocol. This path is the only gatekeeper, have to fail!\n // 409: Epoch Version Mismatch. Client epoch and server epoch does not match, so app needs\n // to be refreshed.\n // This one is fine either way\n // 401/403: Code will retry once with new token either way, then it becomes fatal - on this path\n // and on join Session path.\n // 501: (Fluid not enabled): this is fine either way, as joinSession is gatekeeper\n if (errorObject.statusCode === 400 || errorObject.statusCode === 404) {\n errorObject.canRetry = true;\n }\n }\n throw errorObject;\n }\n\n return deltaConnection;\n }\n\n private socketReference: SocketReference | undefined;\n\n private readonly requestOpsNoncePrefix: string;\n private pushCallCounter = 0;\n private readonly getOpsMap: Map<string, { start: number; from: number; to: number; }> = new Map();\n private flushOpNonce: string | undefined;\n private flushDeferred: Deferred<FlushResult> | undefined;\n\n /**\n * Error raising for socket.io issues\n */\n protected createErrorObject(handler: string, error?: any, canRetry = true): IAnyDriverError {\n // Note: we suspect the incoming error object is either:\n // - a socketError: add it to the OdspError object for driver to be able to parse it and reason over it.\n // - anything else: let base class handle it\n if (canRetry && Number.isInteger(error?.code) && typeof error?.message === \"string\") {\n return errorObjectFromSocketError(error as IOdspSocketError, handler);\n } else {\n return super.createErrorObject(handler, error, canRetry);\n }\n }\n\n /**\n * Gets or create a socket io connection for the given key\n */\n private static getOrCreateSocketIoReference(\n io: typeof SocketIOClientStatic,\n timeoutMs: number,\n key: string,\n url: string,\n enableMultiplexing: boolean,\n tenantId: string,\n documentId: string,\n logger: ITelemetryLogger,\n ): SocketReference {\n const existingSocketReference = SocketReference.find(key, logger);\n if (existingSocketReference) {\n return existingSocketReference;\n }\n\n const query = enableMultiplexing ? undefined : { documentId, tenantId };\n\n const socket = io(\n url,\n {\n multiplex: false, // Don't rely on socket.io built-in multiplexing\n query,\n reconnection: false,\n transports: [\"websocket\"],\n timeout: timeoutMs,\n });\n\n return new SocketReference(key, socket);\n }\n\n /**\n * @param socket - websocket to be used\n * @param documentId - ID of the document\n * @param details - details of the websocket connection\n * @param socketReferenceKey - socket reference key\n * @param enableMultiplexing - If the websocket is multiplexing multiple documents\n */\n private constructor(\n socket: Socket,\n documentId: string,\n socketReference: SocketReference,\n logger: ITelemetryLogger,\n private readonly enableMultiplexing?: boolean,\n ) {\n super(socket, documentId, logger);\n this.socketReference = socketReference;\n this.requestOpsNoncePrefix = `${uuid()}-`;\n }\n\n /**\n * Retrieves ops from PUSH\n * @param from - inclusive\n * @param to - exclusive\n * @returns ops retrieved\n */\n public requestOps(from: number, to: number) {\n // Given that to is exclusive, we should be asking for at least something!\n assert(to > from, 0x272 /* \"empty request\" */);\n\n // PUSH may disable this functionality\n // back-compat: remove cast to any once latest version of IConnected is consumed\n if ((this.details as any).supportedFeatures?.[feature_get_ops] !== true) {\n return;\n }\n\n this.pushCallCounter++;\n const nonce = `${this.requestOpsNoncePrefix}${this.pushCallCounter}`;\n const start = performance.now();\n\n // We may keep keep accumulating memory for nothing, if we are not getting responses.\n // Note that we should not have overlapping requests, as DeltaManager allows only one\n // outstanding request to storage, and that's the only way to get here.\n // But requests could be cancelled, and thus overlapping requests might be in the picture\n // If it happens, we do not care about stale requests.\n // So track some number of requests, but log if we get too many in flight - that likely\n // indicates an error somewhere.\n if (this.getOpsMap.size >= 5) {\n let time = start;\n let key: string | undefined;\n for (const [keyCandidate, value] of this.getOpsMap.entries()) {\n if (value.start <= time || key === undefined) {\n time = value.start;\n key = keyCandidate;\n }\n }\n const payloadToDelete = this.getOpsMap.get(key!)!;\n this.logger.sendErrorEvent({\n eventName: \"GetOpsTooMany\",\n nonce,\n from: payloadToDelete.from,\n to: payloadToDelete.to,\n length: payloadToDelete.to - payloadToDelete.from,\n duration: performance.now() - payloadToDelete.start,\n });\n this.getOpsMap.delete(key!);\n }\n this.getOpsMap.set(\n nonce,\n {\n start,\n from,\n to,\n },\n );\n this.socket.emit(\"get_ops\", this.clientId, {\n nonce,\n from,\n to: to - 1,\n });\n }\n\n public async flush(): Promise<FlushResult> {\n // back-compat: remove cast to any once latest version of IConnected is consumed\n if ((this.details as any).supportedFeatures?.[feature_flush_ops] !== true) {\n // Once single-commit summary is enabled end-to-end, flush support is a must!\n // The only alternative is change in design where SPO fetches ops from PUSH OR\n // summary includes required ops and SPO has some validation mechanism to ensure\n // they are not forged by client.\n // If design changes, we can reconsider it, but right now it's non-recoverable failure.\n this.logger.sendErrorEvent({ eventName: \"FlushOpsNotSupported\" });\n throw new Error(\"flush() API is not supported by PUSH, required for single-commit summaries\");\n }\n\n this.pushCallCounter++;\n const nonce = `${this.requestOpsNoncePrefix}${this.pushCallCounter}`;\n // There should be only one flush ops in flight, kicked out by upload summary workflow\n // That said, it could timeout and request could be repeated, so theoretically we can\n // get overlapping requests, but it should be very rare\n if (this.flushDeferred !== undefined) {\n this.logger.sendErrorEvent({ eventName: \"FlushOpsTooMany\" });\n this.flushDeferred.reject(\"process involving flush() was cancelled OR unsupported concurrency\");\n }\n this.socket.emit(\"flush_ops\", this.clientId, { nonce });\n\n this.flushOpNonce = nonce;\n this.flushDeferred = new Deferred<FlushResult>();\n return this.flushDeferred.promise;\n }\n\n protected serverDisconnectHandler = (error: IFluidErrorBase & OdspError) => {\n this.logger.sendTelemetryEvent({ eventName: \"ServerDisconnect\", clientId: this.clientId }, error);\n this.disposeCore(true, error);\n };\n\n protected async initialize(connectMessage: IConnect, timeout: number) {\n if (this.enableMultiplexing) {\n // multiplex compatible early handlers\n this.earlyOpHandler = (messageDocumentId: string, msgs: ISequencedDocumentMessage[]) => {\n if (this.documentId === messageDocumentId) {\n this.queuedMessages.push(...msgs);\n }\n };\n\n this.earlySignalHandler = (msg: ISignalMessage, messageDocumentId?: string) => {\n if (messageDocumentId === undefined || messageDocumentId === this.documentId) {\n this.queuedSignals.push(msg);\n }\n };\n }\n\n this.socketReference!.on(\"server_disconnect\", this.serverDisconnectHandler);\n\n this.socket.on(\"get_ops_response\", (result: IGetOpsResponse) => {\n const messages = result.messages;\n const data = this.getOpsMap.get(result.nonce);\n // Due to socket multiplexing, this client may not have asked for any data\n // If so, there it most likely does not need these ops (otherwise it already asked for them)\n // Also we may have deleted entry in this.getOpsMap due to too many requests and too slow response.\n // But not processing such result may push us into infinite loop of fast requests and dropping all responses\n if (data !== undefined || result.nonce.indexOf(this.requestOpsNoncePrefix) === 0) {\n this.getOpsMap.delete(result.nonce);\n const common = {\n eventName: \"GetOps\",\n // We need nonce only to pair with GetOpsTooMany events, i.e. when record was deleted\n nonce: data === undefined ? result.nonce : undefined,\n code: result.code,\n from: data?.from,\n to: data?.to,\n duration: data === undefined ? undefined : performance.now() - data.start,\n };\n if (messages !== undefined && messages.length > 0) {\n this.logger.sendPerformanceEvent({\n ...common,\n first: messages[0].sequenceNumber,\n last: messages[messages.length - 1].sequenceNumber,\n length: messages.length,\n });\n this.emit(\"op\", this.documentId, messages);\n } else {\n this.logger.sendPerformanceEvent({\n ...common,\n length: 0,\n });\n }\n }\n });\n\n this.socket.on(\"flush_ops_response\", (result: IFlushOpsResponse) => {\n if (this.flushOpNonce === result.nonce) {\n const seq = result.lastPersistedSequenceNumber;\n let category: \"generic\" | \"error\" = \"generic\";\n if (result.lastPersistedSequenceNumber === undefined || result.code !== 200) {\n switch (result.code) {\n case 409:\n case 429:\n category = \"error\";\n break;\n case 204:\n break;\n default:\n category = \"error\";\n break;\n }\n }\n this.logger.sendTelemetryEvent({\n eventName: \"FlushResult\",\n code: result.code,\n sequenceNumber: seq,\n category,\n });\n this.flushDeferred!.resolve(result);\n this.flushDeferred = undefined;\n this.flushOpNonce = undefined;\n }\n });\n\n await super.initialize(connectMessage, timeout);\n }\n\n protected addTrackedListener(event: string, listener: (...args: any[]) => void) {\n // override some event listeners in order to support multiple documents/clients over the same websocket\n switch (event) {\n case \"op\":\n // per document op handling\n super.addTrackedListener(event, (documentId: string, msgs: ISequencedDocumentMessage[]) => {\n if (!this.enableMultiplexing || this.documentId === documentId) {\n listener(documentId, msgs);\n }\n });\n break;\n\n case \"signal\":\n // per document signal handling\n super.addTrackedListener(event, (msg: ISignalMessage, documentId?: string) => {\n if (!this.enableMultiplexing || !documentId || documentId === this.documentId) {\n listener(msg, documentId);\n }\n });\n break;\n\n case \"nack\":\n // per client / document nack handling\n super.addTrackedListener(event, (clientIdOrDocumentId: string, nacks: INack[]) => {\n const handle = clientIdOrDocumentId.length === 0 ||\n clientIdOrDocumentId === this.documentId ||\n (clientIdOrDocumentId === this.clientId);\n const { code, type, message, retryAfter } = nacks[0]?.content ?? {};\n this.logger.sendTelemetryEvent({\n eventName: \"ServerNack\",\n code,\n type,\n message,\n retryAfterSeconds: retryAfter,\n clientId: this.clientId,\n handle,\n });\n if (handle) {\n this.emit(\"nack\", clientIdOrDocumentId, nacks);\n }\n });\n break;\n\n default:\n super.addTrackedListener(event, listener);\n break;\n }\n }\n\n /**\n * Disconnect from the websocket\n */\n protected disconnect(socketProtocolError: boolean, reason: IAnyDriverError) {\n const socket = this.socketReference;\n assert(socket !== undefined, 0x0a2 /* \"reentrancy not supported!\" */);\n\n this.socketReference?.off(\"server_disconnect\", this.serverDisconnectHandler);\n this.socketReference = undefined;\n\n if (!socketProtocolError && this.hasDetails) {\n // tell the server we are disconnecting this client from the document\n this.socket.emit(\"disconnect_document\", this.clientId, this.documentId);\n }\n\n socket.removeSocketIoReference(socketProtocolError);\n this.emit(\"disconnect\", reason);\n }\n}\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"odspDocumentService.d.ts","sourceRoot":"","sources":["../src/odspDocumentService.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAEH,OAAO,EAAE,gBAAgB,EAAE,MAAM,oCAAoC,CAAC;AAStE,OAAO,EACH,wBAAwB,EACxB,4BAA4B,EAC5B,gBAAgB,EAChB,YAAY,EACZ,uBAAuB,EACvB,wBAAwB,EAE3B,MAAM,oCAAoC,CAAC;AAG5C,OAAO,EACH,OAAO,EACP,yBAAyB,EAC5B,MAAM,sCAAsC,CAAC;AAC9C,OAAO,EACH,gBAAgB,EAChB,i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aG;IACH,OAAO;IAiCP,IAAW,WAAW,IAAI,YAAY,CAErC;IACD,IAAW,QAAQ,6BAElB;IAED;;;;OAIG;IACU,gBAAgB,IAAI,OAAO,CAAC,uBAAuB,CAAC;IAwBjE;;;;OAIG;IACU,qBAAqB,IAAI,OAAO,CAAC,4BAA4B,CAAC;IA+B3E,uEAAuE;IACvE,OAAO,CAAC,uBAAuB;IAW/B;;;;OAIG;IACU,oBAAoB,CAAC,MAAM,EAAE,OAAO,GAAG,OAAO,CAAC,wBAAwB,CAAC;IAuErF,OAAO,CAAC,qBAAqB;YAOf,0BAA0B;YAa1B,WAAW;YA0BX,eAAe;IA2E7B,OAAO,CAAC,gCAAgC;IAKxC;;;;;;;;;OASG;YACW,qBAAqB;IAkC5B,OAAO,CAAC,KAAK,CAAC,EAAE,GAAG;IAa1B,SAAS,KAAK,QAAQ,yBA8BrB;IAID,SAAS,CAAC,WAAW,CAAC,GAAG,EAAE,yBAAyB,EAAE;CAQzD"}
|
|
@@ -5,7 +5,7 @@
|
|
|
5
5
|
import { performance } from "@fluidframework/common-utils";
|
|
6
6
|
import { ChildLogger, loggerToMonitoringContext, normalizeError, } from "@fluidframework/telemetry-utils";
|
|
7
7
|
import { DriverErrorType, } from "@fluidframework/driver-definitions";
|
|
8
|
-
import { DeltaStreamConnectionForbiddenError, NonRetryableError } from "@fluidframework/driver-utils";
|
|
8
|
+
import { canRetryOnError, DeltaStreamConnectionForbiddenError, NonRetryableError } from "@fluidframework/driver-utils";
|
|
9
9
|
import { OdspErrorType, } from "@fluidframework/odsp-driver-definitions";
|
|
10
10
|
import { OdspDeltaStorageService, OdspDeltaStorageWithCache } from "./odspDeltaStorageService";
|
|
11
11
|
import { OdspDocumentDeltaConnection } from "./odspDocumentDeltaConnection";
|
|
@@ -259,10 +259,14 @@ export class OdspDocumentService {
|
|
|
259
259
|
if (response.refreshAfterDeltaMs > 0) {
|
|
260
260
|
this.scheduleJoinSessionRefresh(response.refreshAfterDeltaMs)
|
|
261
261
|
.catch((error) => {
|
|
262
|
-
|
|
263
|
-
|
|
264
|
-
|
|
265
|
-
|
|
262
|
+
const canRetry = canRetryOnError(error);
|
|
263
|
+
// Only record error event in case it is non retriable.
|
|
264
|
+
if (!canRetry) {
|
|
265
|
+
this.mc.logger.sendErrorEvent({
|
|
266
|
+
eventName: "JoinSessionRefreshError",
|
|
267
|
+
details: JSON.stringify(props),
|
|
268
|
+
}, error);
|
|
269
|
+
}
|
|
266
270
|
});
|
|
267
271
|
}
|
|
268
272
|
else {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"odspDocumentService.js","sourceRoot":"","sources":["../src/odspDocumentService.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAGH,OAAO,EAAE,WAAW,EAAE,MAAM,8BAA8B,CAAC;AAC3D,OAAO,EACH,WAAW,EAEX,yBAAyB,EAEzB,cAAc,GACjB,MAAM,iCAAiC,CAAC;AACzC,OAAO,EAOH,eAAe,GAClB,MAAM,oCAAoC,CAAC;AAC5C,OAAO,EAAE,mCAAmC,EAAE,iBAAiB,EAAE,MAAM,8BAA8B,CAAC;AAMtG,OAAO,EAMH,aAAa,GAChB,MAAM,yCAAyC,CAAC;AAIjD,OAAO,EAAE,uBAAuB,EAAE,yBAAyB,EAAE,MAAM,2BAA2B,CAAC;AAC/F,OAAO,EAAE,2BAA2B,EAAE,MAAM,+BAA+B,CAAC;AAC5E,OAAO,EAAE,0BAA0B,EAAE,MAAM,8BAA8B,CAAC;AAC1E,OAAO,EAAE,2BAA2B,EAAE,kBAAkB,EAAuB,MAAM,aAAa,CAAC;AACnG,OAAO,EAAE,gBAAgB,EAAE,MAAM,SAAS,CAAC;AAC3C,OAAO,EAAE,WAAW,EAAE,MAAM,iBAAiB,CAAC;AAE9C,OAAO,EAAE,QAAQ,EAAE,MAAM,cAAc,CAAC;AACxC,OAAO,EAAE,yBAAyB,EAAE,MAAM,6BAA6B,CAAC;AACxE,OAAO,EAAE,UAAU,IAAI,aAAa,EAA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AE,gBAAgB,mCAAI,IAAI,EACpD,MAAA,MAAA,IAAI,CAAC,UAAU,CAAC,UAAU,0CAAE,eAAe,mCAAI,IAAI,CACtD,CAAC;QACF,OAAO,IAAI,CAAC,SAAS,CAAC;IAC1B,CAAC;IAED,mHAAmH;IACnH,8EAA8E;IACpE,WAAW,CAAC,GAAgC;;QAClD,2CAA2C;QAC3C,IAAI,GAAG,CAAC,MAAM,KAAK,CAAC,IAAI,IAAI,CAAC,eAAe,CAAC,UAAU,EAAE;YACrD,OAAO;SACV;QAED,MAAA,IAAI,CAAC,QAAQ,0CAAE,MAAM,CAAC,GAAG,CAAC,CAAC;IAC/B,CAAC;CACJ","sourcesContent":["/*!\n * Copyright (c) Microsoft Corporation and contributors. All rights reserved.\n * Licensed under the MIT License.\n */\n\nimport { ITelemetryLogger } from \"@fluidframework/common-definitions\";\nimport { performance } from \"@fluidframework/common-utils\";\nimport {\n ChildLogger,\n IFluidErrorBase,\n loggerToMonitoringContext,\n MonitoringContext,\n normalizeError,\n} from \"@fluidframework/telemetry-utils\";\nimport {\n IDocumentDeltaConnection,\n IDocumentDeltaStorageService,\n IDocumentService,\n IResolvedUrl,\n IDocumentStorageService,\n IDocumentServicePolicies,\n DriverErrorType,\n} from \"@fluidframework/driver-definitions\";\nimport { DeltaStreamConnectionForbiddenError, NonRetryableError } from \"@fluidframework/driver-utils\";\nimport { IFacetCodes } from \"@fluidframework/odsp-doclib-utils\";\nimport {\n IClient,\n ISequencedDocumentMessage,\n} from \"@fluidframework/protocol-definitions\";\nimport {\n IOdspResolvedUrl,\n TokenFetchOptions,\n IEntry,\n HostStoragePolicy,\n InstrumentedStorageTokenFetcher,\n OdspErrorType,\n} from \"@fluidframework/odsp-driver-definitions\";\nimport type { io as SocketIOClientStatic } from \"socket.io-client\";\nimport { HostStoragePolicyInternal, ISocketStorageDiscovery } from \"./contracts\";\nimport { IOdspCache } from \"./odspCache\";\nimport { OdspDeltaStorageService, OdspDeltaStorageWithCache } from \"./odspDeltaStorageService\";\nimport { OdspDocumentDeltaConnection } from \"./odspDocumentDeltaConnection\";\nimport { OdspDocumentStorageService } from \"./odspDocumentStorageManager\";\nimport { getWithRetryForTokenRefresh, getOdspResolvedUrl, TokenFetchOptionsEx } from \"./odspUtils\";\nimport { fetchJoinSession } from \"./vroom\";\nimport { isOdcOrigin } from \"./odspUrlHelper\";\nimport { EpochTracker } from \"./epochTracker\";\nimport { OpsCache } from \"./opsCaching\";\nimport { RetryErrorsStorageAdapter } from \"./retryErrorsStorageAdapter\";\nimport { pkgVersion as driverVersion } from \"./packageVersion\";\n\n/**\n * The DocumentService manages the Socket.IO connection and manages routing requests to connected\n * clients\n */\nexport class OdspDocumentService implements IDocumentService {\n private _policies: IDocumentServicePolicies;\n // Timer which runs and executes the join session call after intervals.\n private joinSessionRefreshTimer: ReturnType<typeof setTimeout> | undefined;\n /**\n * @param resolvedUrl - resolved url identifying document that will be managed by returned service instance.\n * @param getStorageToken - function that can provide the storage token. This is is also referred to as\n * the \"Vroom\" token in SPO.\n * @param getWebsocketToken - function that can provide a token for accessing the web socket. This is also referred\n * to as the \"Push\" token in SPO. If undefined then websocket token is expected to be returned with joinSession\n * response payload.\n * @param logger - a logger that can capture performance and diagnostic information\n * @param socketIoClientFactory - A factory that returns a promise to the socket io library required by the driver\n * @param cache - This caches response for joinSession.\n * @param hostPolicy - This host constructed policy which customizes service behavior.\n * @param epochTracker - This helper class which adds epoch to backend calls made by returned service instance.\n * @param socketReferenceKeyPrefix - (optional) prefix to isolate socket reuse cache\n */\n public static async create(\n resolvedUrl: IResolvedUrl,\n getStorageToken: InstrumentedStorageTokenFetcher,\n getWebsocketToken: ((options: TokenFetchOptions) => Promise<string | null>) | undefined,\n logger: ITelemetryLogger,\n socketIoClientFactory: () => Promise<typeof SocketIOClientStatic>,\n cache: IOdspCache,\n hostPolicy: HostStoragePolicy,\n epochTracker: EpochTracker,\n socketReferenceKeyPrefix?: string,\n clientIsSummarizer?: boolean,\n ): Promise<IDocumentService> {\n return new OdspDocumentService(\n getOdspResolvedUrl(resolvedUrl),\n getStorageToken,\n getWebsocketToken,\n logger,\n socketIoClientFactory,\n cache,\n hostPolicy,\n epochTracker,\n socketReferenceKeyPrefix,\n clientIsSummarizer,\n );\n }\n\n private storageManager?: OdspDocumentStorageService;\n\n private readonly mc: MonitoringContext;\n\n private readonly joinSessionKey: string;\n\n private readonly hostPolicy: HostStoragePolicyInternal;\n\n private _opsCache?: OpsCache;\n\n private currentConnection?: OdspDocumentDeltaConnection;\n\n /**\n * @param odspResolvedUrl - resolved url identifying document that will be managed by this service instance.\n * @param getStorageToken - function that can provide the storage token. This is is also referred to as\n * the \"Vroom\" token in SPO.\n * @param getWebsocketToken - function that can provide a token for accessing the web socket. This is also referred\n * to as the \"Push\" token in SPO. If undefined then websocket token is expected to be returned with joinSession\n * response payload.\n * @param logger - a logger that can capture performance and diagnostic information\n * @param socketIoClientFactory - A factory that returns a promise to the socket io library required by the driver\n * @param cache - This caches response for joinSession.\n * @param hostPolicy - host constructed policy which customizes service behavior.\n * @param epochTracker - This helper class which adds epoch to backend calls made by this service instance.\n * @param socketReferenceKeyPrefix - (optional) prefix to isolate socket reuse cache\n */\n private constructor(\n public readonly odspResolvedUrl: IOdspResolvedUrl,\n private readonly getStorageToken: InstrumentedStorageTokenFetcher,\n private readonly getWebsocketToken: ((options: TokenFetchOptions) => Promise<string | null>) | undefined,\n logger: ITelemetryLogger,\n private readonly socketIoClientFactory: () => Promise<typeof SocketIOClientStatic>,\n private readonly cache: IOdspCache,\n hostPolicy: HostStoragePolicy,\n private readonly epochTracker: EpochTracker,\n private readonly socketReferenceKeyPrefix?: string,\n private readonly clientIsSummarizer?: boolean,\n ) {\n this._policies = {\n // load in storage-only mode if a file version is specified\n storageOnly: odspResolvedUrl.fileVersion !== undefined,\n };\n\n this.joinSessionKey = `${this.odspResolvedUrl.hashedDocumentId}/joinsession`;\n this.mc = loggerToMonitoringContext(\n ChildLogger.create(logger,\n undefined,\n {\n all: {\n odc: isOdcOrigin(new URL(this.odspResolvedUrl.endpoints.snapshotStorageUrl).origin),\n },\n }));\n\n this.hostPolicy = hostPolicy;\n if (this.clientIsSummarizer) {\n this.hostPolicy = { ...this.hostPolicy, summarizerClient: true };\n }\n }\n\n public get resolvedUrl(): IResolvedUrl {\n return this.odspResolvedUrl;\n }\n public get policies() {\n return this._policies;\n }\n\n /**\n * Connects to a storage endpoint for snapshot service.\n *\n * @returns returns the document storage service for sharepoint driver.\n */\n public async connectToStorage(): Promise<IDocumentStorageService> {\n if (!this.storageManager) {\n this.storageManager = new OdspDocumentStorageService(\n this.odspResolvedUrl,\n this.getStorageToken,\n this.mc.logger,\n true,\n this.cache,\n this.hostPolicy,\n this.epochTracker,\n // flushCallback\n async () => {\n if (this.currentConnection !== undefined && !this.currentConnection.disposed) {\n return this.currentConnection.flush();\n }\n throw new Error(\"Disconnected while uploading summary (attempt to perform flush())\");\n },\n this.mc.config.getNumber(\"Fluid.Driver.Odsp.snapshotFormatFetchType\"),\n );\n }\n\n return new RetryErrorsStorageAdapter(this.storageManager, this.mc.logger);\n }\n\n /**\n * Connects to a delta storage endpoint for getting ops between a range.\n *\n * @returns returns the document delta storage service for sharepoint driver.\n */\n public async connectToDeltaStorage(): Promise<IDocumentDeltaStorageService> {\n const snapshotOps = this.storageManager?.ops ?? [];\n const service = new OdspDeltaStorageService(\n this.odspResolvedUrl.endpoints.deltaStorageUrl,\n this.getStorageToken,\n this.epochTracker,\n this.mc.logger,\n );\n\n // batch size, please see issue #5211 for data around batch sizing\n const batchSize = this.hostPolicy.opsBatchSize ?? 5000;\n const concurrency = this.hostPolicy.concurrentOpsBatches ?? 1;\n return new OdspDeltaStorageWithCache(\n snapshotOps,\n this.mc.logger,\n batchSize,\n concurrency,\n async (from, to, telemetryProps, fetchReason) => service.get(from, to, telemetryProps, fetchReason),\n async (from, to) => {\n const res = await this.opsCache?.get(from, to);\n return res as ISequencedDocumentMessage[] ?? [];\n },\n (from, to) => {\n if (this.currentConnection !== undefined && !this.currentConnection.disposed) {\n this.currentConnection.requestOps(from, to);\n }\n },\n (ops: ISequencedDocumentMessage[]) => this.opsReceived(ops),\n );\n }\n\n /** Annotate the given error indicating which connection step failed */\n private annotateConnectionError(\n error: any,\n failedConnectionStep: string,\n separateTokenRequest: boolean,\n ): IFluidErrorBase {\n return normalizeError(error, { props: {\n failedConnectionStep,\n separateTokenRequest,\n } });\n }\n\n /**\n * Connects to a delta stream endpoint for emitting ops.\n *\n * @returns returns the document delta stream service for onedrive/sharepoint driver.\n */\n public async connectToDeltaStream(client: IClient): Promise<IDocumentDeltaConnection> {\n // Attempt to connect twice, in case we used expired token.\n return getWithRetryForTokenRefresh<IDocumentDeltaConnection>(async (options) => {\n // Presence of getWebsocketToken callback dictates whether callback is used for fetching\n // websocket token or whether it is returned with joinSession response payload\n const requestWebsocketTokenFromJoinSession = this.getWebsocketToken === undefined;\n const websocketTokenPromise = requestWebsocketTokenFromJoinSession\n ? Promise.resolve(null)\n : this.getWebsocketToken!(options);\n\n const annotateAndRethrowConnectionError = (step: string) => (error: any) => {\n throw this.annotateConnectionError(error, step, !requestWebsocketTokenFromJoinSession);\n };\n\n const joinSessionPromise = this.joinSession(requestWebsocketTokenFromJoinSession, options);\n const [websocketEndpoint, websocketToken, io] =\n await Promise.all([\n joinSessionPromise.catch(annotateAndRethrowConnectionError(\"joinSession\")),\n websocketTokenPromise.catch(annotateAndRethrowConnectionError(\"getWebsocketToken\")),\n this.socketIoClientFactory().catch(annotateAndRethrowConnectionError(\"socketIoClientFactory\")),\n ]);\n\n const finalWebsocketToken = websocketToken ?? (websocketEndpoint.socketToken || null);\n if (finalWebsocketToken === null) {\n throw this.annotateConnectionError(\n new NonRetryableError(\n \"Websocket token is null\",\n OdspErrorType.fetchTokenError,\n { driverVersion },\n ),\n \"getWebsocketToken\",\n !requestWebsocketTokenFromJoinSession);\n }\n try {\n const connection = await this.createDeltaConnection(\n websocketEndpoint.tenantId,\n websocketEndpoint.id,\n finalWebsocketToken,\n io,\n client,\n websocketEndpoint.deltaStreamSocketUrl);\n connection.on(\"op\", (documentId, ops: ISequencedDocumentMessage[]) => {\n this.opsReceived(ops);\n });\n // On disconnect with 401/403 error code, we can just clear the joinSession cache as we will again\n // get the auth error on reconnecting and face latency.\n connection.on(\"disconnect\", (error: any) => {\n // Clear the join session refresh timer so that it can be restarted on reconnection.\n this.clearJoinSessionTimer();\n if (typeof error === \"object\" && error !== null\n && error.errorType === DriverErrorType.authorizationError) {\n this.cache.sessionJoinCache.remove(this.joinSessionKey);\n }\n });\n this.currentConnection = connection;\n return connection;\n } catch (error) {\n this.cache.sessionJoinCache.remove(this.joinSessionKey);\n\n const normalizedError = this.annotateConnectionError(\n error,\n \"createDeltaConnection\",\n !requestWebsocketTokenFromJoinSession);\n if (typeof error === \"object\" && error !== null) {\n normalizedError.addTelemetryProperties({ socketDocumentId: websocketEndpoint.id });\n }\n throw normalizedError;\n }\n });\n }\n\n private clearJoinSessionTimer() {\n if (this.joinSessionRefreshTimer !== undefined) {\n clearTimeout(this.joinSessionRefreshTimer);\n this.joinSessionRefreshTimer = undefined;\n }\n }\n\n private async scheduleJoinSessionRefresh(delta: number) {\n await new Promise<void>((resolve, reject) => {\n this.joinSessionRefreshTimer = setTimeout(() => {\n getWithRetryForTokenRefresh(async (options) => {\n await this.joinSession(false, options);\n resolve();\n }).catch((error) => {\n reject(error);\n });\n }, delta);\n });\n }\n\n private async joinSession(\n requestSocketToken: boolean,\n options: TokenFetchOptionsEx,\n ) {\n return this.joinSessionCore(requestSocketToken, options).catch((e) => {\n const likelyFacetCodes = e as IFacetCodes;\n if (Array.isArray(likelyFacetCodes.facetCodes)) {\n for (const code of likelyFacetCodes.facetCodes) {\n switch (code) {\n case \"sessionForbiddenOnPreservedFiles\":\n case \"sessionForbiddenOnModerationEnabledLibrary\":\n case \"sessionForbiddenOnRequireCheckout\":\n // This document can only be opened in storage-only mode.\n // DeltaManager will recognize this error\n // and load without a delta stream connection.\n this._policies = { ...this._policies, storageOnly: true };\n throw new DeltaStreamConnectionForbiddenError(code, { driverVersion });\n default:\n continue;\n }\n }\n }\n throw e;\n });\n }\n\n private async joinSessionCore(\n requestSocketToken: boolean,\n options: TokenFetchOptionsEx,\n ): Promise<ISocketStorageDiscovery> {\n const disableJoinSessionRefresh = this.mc.config.getBoolean(\"Fluid.Driver.Odsp.disableJoinSessionRefresh\");\n const executeFetch = async () => {\n const joinSessionResponse = await fetchJoinSession(\n this.odspResolvedUrl,\n \"opStream/joinSession\",\n \"POST\",\n this.mc.logger,\n this.getStorageToken,\n this.epochTracker,\n requestSocketToken,\n options,\n disableJoinSessionRefresh,\n this.hostPolicy.sessionOptions?.unauthenticatedUserDisplayName,\n );\n return {\n entryTime: Date.now(),\n joinSessionResponse,\n };\n };\n\n const getResponseAndRefreshAfterDeltaMs = async () => {\n const _response = await this.cache.sessionJoinCache.addOrGet(this.joinSessionKey, executeFetch);\n // If the response does not contain refreshSessionDurationSeconds, then treat it as old flow and let the\n // cache entry to be treated as expired after 1 hour.\n _response.joinSessionResponse.refreshSessionDurationSeconds =\n _response.joinSessionResponse.refreshSessionDurationSeconds ?? 3600;\n return {\n ..._response,\n refreshAfterDeltaMs: this.calculateJoinSessionRefreshDelta(\n _response.entryTime, _response.joinSessionResponse.refreshSessionDurationSeconds),\n };\n };\n let response = await getResponseAndRefreshAfterDeltaMs();\n // This means that the cached entry has expired(This should not be possible if the response is fetched\n // from the network call). In this case we remove the cached entry and fetch the new response.\n if (response.refreshAfterDeltaMs <= 0) {\n this.cache.sessionJoinCache.remove(this.joinSessionKey);\n response = await getResponseAndRefreshAfterDeltaMs();\n }\n if (!disableJoinSessionRefresh) {\n const props = {\n entryTime: response.entryTime,\n refreshSessionDurationSeconds:\n response.joinSessionResponse.refreshSessionDurationSeconds,\n refreshAfterDeltaMs: response.refreshAfterDeltaMs,\n };\n if (response.refreshAfterDeltaMs > 0) {\n this.scheduleJoinSessionRefresh(response.refreshAfterDeltaMs)\n .catch((error) => {\n this.mc.logger.sendErrorEvent({\n eventName: \"JoinSessionRefreshError\",\n details: JSON.stringify(props),\n },\n error,\n );\n });\n } else {\n // Logging just for informational purposes to help with debugging as this is a new feature.\n this.mc.logger.sendTelemetryEvent({\n eventName: \"JoinSessionRefreshNotScheduled\",\n details: JSON.stringify(props),\n });\n }\n }\n return response.joinSessionResponse;\n }\n\n private calculateJoinSessionRefreshDelta(responseFetchTime: number, refreshSessionDurationSeconds: number) {\n // 30 seconds is buffer time to refresh the session.\n return responseFetchTime + ((refreshSessionDurationSeconds * 1000) - 30000) - Date.now();\n }\n\n /**\n * Creats a connection to the given delta stream endpoint\n *\n * @param tenantId - the ID of the tenant\n * @param documentId - document ID\n * @param token - authorization token for delta service\n * @param io - websocket library\n * @param client - information about the client\n * @param webSocketUrl - websocket URL\n */\n private async createDeltaConnection(\n tenantId: string,\n documentId: string,\n token: string | null,\n io: typeof SocketIOClientStatic,\n client: IClient,\n webSocketUrl: string,\n ): Promise<OdspDocumentDeltaConnection> {\n const startTime = performance.now();\n const connection = await OdspDocumentDeltaConnection.create(\n tenantId,\n documentId,\n token,\n io,\n client,\n webSocketUrl,\n this.mc.logger,\n 60000,\n this.epochTracker,\n this.socketReferenceKeyPrefix,\n );\n const duration = performance.now() - startTime;\n // This event happens rather often, so it adds up to cost of telemetry.\n // Given that most reconnects result in reusing socket and happen very quickly,\n // report event only if it took longer than threshold.\n if (duration >= 2000) {\n this.mc.logger.sendPerformanceEvent({\n eventName: \"ConnectionSuccess\",\n duration,\n });\n }\n return connection;\n }\n\n public dispose(error?: any) {\n // Error might indicate mismatch between client & server knowlege about file\n // (DriverErrorType.fileOverwrittenInStorage).\n // For example, file might have been overwritten in storage without generating new epoch\n // In such case client cached info is stale and has to be removed.\n if (error !== undefined) {\n this.epochTracker.removeEntries().catch(() => {});\n } else {\n this._opsCache?.flushOps();\n }\n this._opsCache?.dispose();\n }\n\n protected get opsCache() {\n if (this._opsCache) {\n return this._opsCache;\n }\n\n const seqNumber = this.storageManager?.snapshotSequenceNumber;\n const batchSize = this.hostPolicy.opsCaching?.batchSize ?? 100;\n if (seqNumber === undefined || batchSize < 1) {\n return;\n }\n\n const opsKey: Omit<IEntry, \"key\"> = {\n type: \"ops\",\n };\n this._opsCache = new OpsCache(\n seqNumber,\n this.mc.logger,\n // ICache\n {\n write: async (key: string, opsData: string) => {\n return this.cache.persistedCache.put({ ...opsKey, key }, opsData);\n },\n read: async (key: string) => this.cache.persistedCache.get({ ...opsKey, key }),\n remove: () => { this.cache.persistedCache.removeEntries().catch(() => {}); },\n },\n batchSize,\n this.hostPolicy.opsCaching?.timerGranularity ?? 5000,\n this.hostPolicy.opsCaching?.totalOpsToCache ?? 5000,\n );\n return this._opsCache;\n }\n\n // Called whenever re receive ops through any channel for this document (snapshot, delta connection, delta storage)\n // We use it to notify caching layer of how stale is snapshot stored in cache.\n protected opsReceived(ops: ISequencedDocumentMessage[]) {\n // No need for two clients to save same ops\n if (ops.length === 0 || this.odspResolvedUrl.summarizer) {\n return;\n }\n\n this.opsCache?.addOps(ops);\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"odspDocumentService.js","sourceRoot":"","sources":["../src/odspDocumentService.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAGH,OAAO,EAAE,WAAW,EAAE,MAAM,8BAA8B,CAAC;AAC3D,OAAO,EACH,WAAW,EAEX,yBAAyB,EAEzB,cAAc,GACjB,MAAM,iCAAiC,CAAC;AACzC,OAAO,EAOH,eAAe,GAClB,MAAM,oCAAoC,CAAC;AAC5C,OAAO,EAAE,eAAe,EAAE,mCAAmC,EAAE,iBAAiB,EAAE,MAAM,8BAA8B,CAAC;AAMvH,OAAO,EAMH,aAAa,GAChB,MAAM,yCAAyC,CAAC;AAIjD,OAAO,EAAE,uBAAuB,EAAE,yBAAyB,EAAE,MAAM,2BAA2B,CAAC;AAC/F,OAAO,EAAE,2BAA2B,EAAE,MAAM,+BAA+B,CAAC;AAC5E,OAAO,EAAE,0BAA0B,EAAE,MA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AAC,KAAK,CAAC,cAAc,CAAC,GAAG,iCAAM,MAAM,KAAE,GAAG,KAAI,OAAO,CAAC,CAAC;YACtE,CAAC;YACD,IAAI,EAAE,KAAK,EAAE,GAAW,EAAE,EAAE,CAAC,IAAI,CAAC,KAAK,CAAC,cAAc,CAAC,GAAG,iCAAM,MAAM,KAAE,GAAG,IAAG;YAC9E,MAAM,EAAE,GAAG,EAAE,GAAG,IAAI,CAAC,KAAK,CAAC,cAAc,CAAC,aAAa,EAAE,CAAC,KAAK,CAAC,GAAG,EAAE,GAAE,CAAC,CAAC,CAAC,CAAC,CAAC;SAC/E,EACD,SAAS,EACT,MAAA,MAAA,IAAI,CAAC,UAAU,CAAC,UAAU,0CAAE,gBAAgB,mCAAI,IAAI,EACpD,MAAA,MAAA,IAAI,CAAC,UAAU,CAAC,UAAU,0CAAE,eAAe,mCAAI,IAAI,CACtD,CAAC;QACF,OAAO,IAAI,CAAC,SAAS,CAAC;IAC1B,CAAC;IAED,mHAAmH;IACnH,8EAA8E;IACpE,WAAW,CAAC,GAAgC;;QAClD,2CAA2C;QAC3C,IAAI,GAAG,CAAC,MAAM,KAAK,CAAC,IAAI,IAAI,CAAC,eAAe,CAAC,UAAU,EAAE;YACrD,OAAO;SACV;QAED,MAAA,IAAI,CAAC,QAAQ,0CAAE,MAAM,CAAC,GAAG,CAAC,CAAC;IAC/B,CAAC;CACJ","sourcesContent":["/*!\n * Copyright (c) Microsoft Corporation and contributors. All rights reserved.\n * Licensed under the MIT License.\n */\n\nimport { ITelemetryLogger } from \"@fluidframework/common-definitions\";\nimport { performance } from \"@fluidframework/common-utils\";\nimport {\n ChildLogger,\n IFluidErrorBase,\n loggerToMonitoringContext,\n MonitoringContext,\n normalizeError,\n} from \"@fluidframework/telemetry-utils\";\nimport {\n IDocumentDeltaConnection,\n IDocumentDeltaStorageService,\n IDocumentService,\n IResolvedUrl,\n IDocumentStorageService,\n IDocumentServicePolicies,\n DriverErrorType,\n} from \"@fluidframework/driver-definitions\";\nimport { canRetryOnError, DeltaStreamConnectionForbiddenError, NonRetryableError } from \"@fluidframework/driver-utils\";\nimport { IFacetCodes } from \"@fluidframework/odsp-doclib-utils\";\nimport {\n IClient,\n ISequencedDocumentMessage,\n} from \"@fluidframework/protocol-definitions\";\nimport {\n IOdspResolvedUrl,\n TokenFetchOptions,\n IEntry,\n HostStoragePolicy,\n InstrumentedStorageTokenFetcher,\n OdspErrorType,\n} from \"@fluidframework/odsp-driver-definitions\";\nimport type { io as SocketIOClientStatic } from \"socket.io-client\";\nimport { HostStoragePolicyInternal, ISocketStorageDiscovery } from \"./contracts\";\nimport { IOdspCache } from \"./odspCache\";\nimport { OdspDeltaStorageService, OdspDeltaStorageWithCache } from \"./odspDeltaStorageService\";\nimport { OdspDocumentDeltaConnection } from \"./odspDocumentDeltaConnection\";\nimport { OdspDocumentStorageService } from \"./odspDocumentStorageManager\";\nimport { getWithRetryForTokenRefresh, getOdspResolvedUrl, TokenFetchOptionsEx } from \"./odspUtils\";\nimport { fetchJoinSession } from \"./vroom\";\nimport { isOdcOrigin } from \"./odspUrlHelper\";\nimport { EpochTracker } from \"./epochTracker\";\nimport { OpsCache } from \"./opsCaching\";\nimport { RetryErrorsStorageAdapter } from \"./retryErrorsStorageAdapter\";\nimport { pkgVersion as driverVersion } from \"./packageVersion\";\n\n/**\n * The DocumentService manages the Socket.IO connection and manages routing requests to connected\n * clients\n */\nexport class OdspDocumentService implements IDocumentService {\n private _policies: IDocumentServicePolicies;\n // Timer which runs and executes the join session call after intervals.\n private joinSessionRefreshTimer: ReturnType<typeof setTimeout> | undefined;\n /**\n * @param resolvedUrl - resolved url identifying document that will be managed by returned service instance.\n * @param getStorageToken - function that can provide the storage token. This is is also referred to as\n * the \"Vroom\" token in SPO.\n * @param getWebsocketToken - function that can provide a token for accessing the web socket. This is also referred\n * to as the \"Push\" token in SPO. If undefined then websocket token is expected to be returned with joinSession\n * response payload.\n * @param logger - a logger that can capture performance and diagnostic information\n * @param socketIoClientFactory - A factory that returns a promise to the socket io library required by the driver\n * @param cache - This caches response for joinSession.\n * @param hostPolicy - This host constructed policy which customizes service behavior.\n * @param epochTracker - This helper class which adds epoch to backend calls made by returned service instance.\n * @param socketReferenceKeyPrefix - (optional) prefix to isolate socket reuse cache\n */\n public static async create(\n resolvedUrl: IResolvedUrl,\n getStorageToken: InstrumentedStorageTokenFetcher,\n getWebsocketToken: ((options: TokenFetchOptions) => Promise<string | null>) | undefined,\n logger: ITelemetryLogger,\n socketIoClientFactory: () => Promise<typeof SocketIOClientStatic>,\n cache: IOdspCache,\n hostPolicy: HostStoragePolicy,\n epochTracker: EpochTracker,\n socketReferenceKeyPrefix?: string,\n clientIsSummarizer?: boolean,\n ): Promise<IDocumentService> {\n return new OdspDocumentService(\n getOdspResolvedUrl(resolvedUrl),\n getStorageToken,\n getWebsocketToken,\n logger,\n socketIoClientFactory,\n cache,\n hostPolicy,\n epochTracker,\n socketReferenceKeyPrefix,\n clientIsSummarizer,\n );\n }\n\n private storageManager?: OdspDocumentStorageService;\n\n private readonly mc: MonitoringContext;\n\n private readonly joinSessionKey: string;\n\n private readonly hostPolicy: HostStoragePolicyInternal;\n\n private _opsCache?: OpsCache;\n\n private currentConnection?: OdspDocumentDeltaConnection;\n\n /**\n * @param odspResolvedUrl - resolved url identifying document that will be managed by this service instance.\n * @param getStorageToken - function that can provide the storage token. This is is also referred to as\n * the \"Vroom\" token in SPO.\n * @param getWebsocketToken - function that can provide a token for accessing the web socket. This is also referred\n * to as the \"Push\" token in SPO. If undefined then websocket token is expected to be returned with joinSession\n * response payload.\n * @param logger - a logger that can capture performance and diagnostic information\n * @param socketIoClientFactory - A factory that returns a promise to the socket io library required by the driver\n * @param cache - This caches response for joinSession.\n * @param hostPolicy - host constructed policy which customizes service behavior.\n * @param epochTracker - This helper class which adds epoch to backend calls made by this service instance.\n * @param socketReferenceKeyPrefix - (optional) prefix to isolate socket reuse cache\n */\n private constructor(\n public readonly odspResolvedUrl: IOdspResolvedUrl,\n private readonly getStorageToken: InstrumentedStorageTokenFetcher,\n private readonly getWebsocketToken: ((options: TokenFetchOptions) => Promise<string | null>) | undefined,\n logger: ITelemetryLogger,\n private readonly socketIoClientFactory: () => Promise<typeof SocketIOClientStatic>,\n private readonly cache: IOdspCache,\n hostPolicy: HostStoragePolicy,\n private readonly epochTracker: EpochTracker,\n private readonly socketReferenceKeyPrefix?: string,\n private readonly clientIsSummarizer?: boolean,\n ) {\n this._policies = {\n // load in storage-only mode if a file version is specified\n storageOnly: odspResolvedUrl.fileVersion !== undefined,\n };\n\n this.joinSessionKey = `${this.odspResolvedUrl.hashedDocumentId}/joinsession`;\n this.mc = loggerToMonitoringContext(\n ChildLogger.create(logger,\n undefined,\n {\n all: {\n odc: isOdcOrigin(new URL(this.odspResolvedUrl.endpoints.snapshotStorageUrl).origin),\n },\n }));\n\n this.hostPolicy = hostPolicy;\n if (this.clientIsSummarizer) {\n this.hostPolicy = { ...this.hostPolicy, summarizerClient: true };\n }\n }\n\n public get resolvedUrl(): IResolvedUrl {\n return this.odspResolvedUrl;\n }\n public get policies() {\n return this._policies;\n }\n\n /**\n * Connects to a storage endpoint for snapshot service.\n *\n * @returns returns the document storage service for sharepoint driver.\n */\n public async connectToStorage(): Promise<IDocumentStorageService> {\n if (!this.storageManager) {\n this.storageManager = new OdspDocumentStorageService(\n this.odspResolvedUrl,\n this.getStorageToken,\n this.mc.logger,\n true,\n this.cache,\n this.hostPolicy,\n this.epochTracker,\n // flushCallback\n async () => {\n if (this.currentConnection !== undefined && !this.currentConnection.disposed) {\n return this.currentConnection.flush();\n }\n throw new Error(\"Disconnected while uploading summary (attempt to perform flush())\");\n },\n this.mc.config.getNumber(\"Fluid.Driver.Odsp.snapshotFormatFetchType\"),\n );\n }\n\n return new RetryErrorsStorageAdapter(this.storageManager, this.mc.logger);\n }\n\n /**\n * Connects to a delta storage endpoint for getting ops between a range.\n *\n * @returns returns the document delta storage service for sharepoint driver.\n */\n public async connectToDeltaStorage(): Promise<IDocumentDeltaStorageService> {\n const snapshotOps = this.storageManager?.ops ?? [];\n const service = new OdspDeltaStorageService(\n this.odspResolvedUrl.endpoints.deltaStorageUrl,\n this.getStorageToken,\n this.epochTracker,\n this.mc.logger,\n );\n\n // batch size, please see issue #5211 for data around batch sizing\n const batchSize = this.hostPolicy.opsBatchSize ?? 5000;\n const concurrency = this.hostPolicy.concurrentOpsBatches ?? 1;\n return new OdspDeltaStorageWithCache(\n snapshotOps,\n this.mc.logger,\n batchSize,\n concurrency,\n async (from, to, telemetryProps, fetchReason) => service.get(from, to, telemetryProps, fetchReason),\n async (from, to) => {\n const res = await this.opsCache?.get(from, to);\n return res as ISequencedDocumentMessage[] ?? [];\n },\n (from, to) => {\n if (this.currentConnection !== undefined && !this.currentConnection.disposed) {\n this.currentConnection.requestOps(from, to);\n }\n },\n (ops: ISequencedDocumentMessage[]) => this.opsReceived(ops),\n );\n }\n\n /** Annotate the given error indicating which connection step failed */\n private annotateConnectionError(\n error: any,\n failedConnectionStep: string,\n separateTokenRequest: boolean,\n ): IFluidErrorBase {\n return normalizeError(error, { props: {\n failedConnectionStep,\n separateTokenRequest,\n } });\n }\n\n /**\n * Connects to a delta stream endpoint for emitting ops.\n *\n * @returns returns the document delta stream service for onedrive/sharepoint driver.\n */\n public async connectToDeltaStream(client: IClient): Promise<IDocumentDeltaConnection> {\n // Attempt to connect twice, in case we used expired token.\n return getWithRetryForTokenRefresh<IDocumentDeltaConnection>(async (options) => {\n // Presence of getWebsocketToken callback dictates whether callback is used for fetching\n // websocket token or whether it is returned with joinSession response payload\n const requestWebsocketTokenFromJoinSession = this.getWebsocketToken === undefined;\n const websocketTokenPromise = requestWebsocketTokenFromJoinSession\n ? Promise.resolve(null)\n : this.getWebsocketToken!(options);\n\n const annotateAndRethrowConnectionError = (step: string) => (error: any) => {\n throw this.annotateConnectionError(error, step, !requestWebsocketTokenFromJoinSession);\n };\n\n const joinSessionPromise = this.joinSession(requestWebsocketTokenFromJoinSession, options);\n const [websocketEndpoint, websocketToken, io] =\n await Promise.all([\n joinSessionPromise.catch(annotateAndRethrowConnectionError(\"joinSession\")),\n websocketTokenPromise.catch(annotateAndRethrowConnectionError(\"getWebsocketToken\")),\n this.socketIoClientFactory().catch(annotateAndRethrowConnectionError(\"socketIoClientFactory\")),\n ]);\n\n const finalWebsocketToken = websocketToken ?? (websocketEndpoint.socketToken || null);\n if (finalWebsocketToken === null) {\n throw this.annotateConnectionError(\n new NonRetryableError(\n \"Websocket token is null\",\n OdspErrorType.fetchTokenError,\n { driverVersion },\n ),\n \"getWebsocketToken\",\n !requestWebsocketTokenFromJoinSession);\n }\n try {\n const connection = await this.createDeltaConnection(\n websocketEndpoint.tenantId,\n websocketEndpoint.id,\n finalWebsocketToken,\n io,\n client,\n websocketEndpoint.deltaStreamSocketUrl);\n connection.on(\"op\", (documentId, ops: ISequencedDocumentMessage[]) => {\n this.opsReceived(ops);\n });\n // On disconnect with 401/403 error code, we can just clear the joinSession cache as we will again\n // get the auth error on reconnecting and face latency.\n connection.on(\"disconnect\", (error: any) => {\n // Clear the join session refresh timer so that it can be restarted on reconnection.\n this.clearJoinSessionTimer();\n if (typeof error === \"object\" && error !== null\n && error.errorType === DriverErrorType.authorizationError) {\n this.cache.sessionJoinCache.remove(this.joinSessionKey);\n }\n });\n this.currentConnection = connection;\n return connection;\n } catch (error) {\n this.cache.sessionJoinCache.remove(this.joinSessionKey);\n\n const normalizedError = this.annotateConnectionError(\n error,\n \"createDeltaConnection\",\n !requestWebsocketTokenFromJoinSession);\n if (typeof error === \"object\" && error !== null) {\n normalizedError.addTelemetryProperties({ socketDocumentId: websocketEndpoint.id });\n }\n throw normalizedError;\n }\n });\n }\n\n private clearJoinSessionTimer() {\n if (this.joinSessionRefreshTimer !== undefined) {\n clearTimeout(this.joinSessionRefreshTimer);\n this.joinSessionRefreshTimer = undefined;\n }\n }\n\n private async scheduleJoinSessionRefresh(delta: number) {\n await new Promise<void>((resolve, reject) => {\n this.joinSessionRefreshTimer = setTimeout(() => {\n getWithRetryForTokenRefresh(async (options) => {\n await this.joinSession(false, options);\n resolve();\n }).catch((error) => {\n reject(error);\n });\n }, delta);\n });\n }\n\n private async joinSession(\n requestSocketToken: boolean,\n options: TokenFetchOptionsEx,\n ) {\n return this.joinSessionCore(requestSocketToken, options).catch((e) => {\n const likelyFacetCodes = e as IFacetCodes;\n if (Array.isArray(likelyFacetCodes.facetCodes)) {\n for (const code of likelyFacetCodes.facetCodes) {\n switch (code) {\n case \"sessionForbiddenOnPreservedFiles\":\n case \"sessionForbiddenOnModerationEnabledLibrary\":\n case \"sessionForbiddenOnRequireCheckout\":\n // This document can only be opened in storage-only mode.\n // DeltaManager will recognize this error\n // and load without a delta stream connection.\n this._policies = { ...this._policies, storageOnly: true };\n throw new DeltaStreamConnectionForbiddenError(code, { driverVersion });\n default:\n continue;\n }\n }\n }\n throw e;\n });\n }\n\n private async joinSessionCore(\n requestSocketToken: boolean,\n options: TokenFetchOptionsEx,\n ): Promise<ISocketStorageDiscovery> {\n const disableJoinSessionRefresh = this.mc.config.getBoolean(\"Fluid.Driver.Odsp.disableJoinSessionRefresh\");\n const executeFetch = async () => {\n const joinSessionResponse = await fetchJoinSession(\n this.odspResolvedUrl,\n \"opStream/joinSession\",\n \"POST\",\n this.mc.logger,\n this.getStorageToken,\n this.epochTracker,\n requestSocketToken,\n options,\n disableJoinSessionRefresh,\n this.hostPolicy.sessionOptions?.unauthenticatedUserDisplayName,\n );\n return {\n entryTime: Date.now(),\n joinSessionResponse,\n };\n };\n\n const getResponseAndRefreshAfterDeltaMs = async () => {\n const _response = await this.cache.sessionJoinCache.addOrGet(this.joinSessionKey, executeFetch);\n // If the response does not contain refreshSessionDurationSeconds, then treat it as old flow and let the\n // cache entry to be treated as expired after 1 hour.\n _response.joinSessionResponse.refreshSessionDurationSeconds =\n _response.joinSessionResponse.refreshSessionDurationSeconds ?? 3600;\n return {\n ..._response,\n refreshAfterDeltaMs: this.calculateJoinSessionRefreshDelta(\n _response.entryTime, _response.joinSessionResponse.refreshSessionDurationSeconds),\n };\n };\n let response = await getResponseAndRefreshAfterDeltaMs();\n // This means that the cached entry has expired(This should not be possible if the response is fetched\n // from the network call). In this case we remove the cached entry and fetch the new response.\n if (response.refreshAfterDeltaMs <= 0) {\n this.cache.sessionJoinCache.remove(this.joinSessionKey);\n response = await getResponseAndRefreshAfterDeltaMs();\n }\n if (!disableJoinSessionRefresh) {\n const props = {\n entryTime: response.entryTime,\n refreshSessionDurationSeconds:\n response.joinSessionResponse.refreshSessionDurationSeconds,\n refreshAfterDeltaMs: response.refreshAfterDeltaMs,\n };\n if (response.refreshAfterDeltaMs > 0) {\n this.scheduleJoinSessionRefresh(response.refreshAfterDeltaMs)\n .catch((error) => {\n const canRetry = canRetryOnError(error);\n // Only record error event in case it is non retriable.\n if (!canRetry) {\n this.mc.logger.sendErrorEvent({\n eventName: \"JoinSessionRefreshError\",\n details: JSON.stringify(props),\n },\n error,\n );\n }\n });\n } else {\n // Logging just for informational purposes to help with debugging as this is a new feature.\n this.mc.logger.sendTelemetryEvent({\n eventName: \"JoinSessionRefreshNotScheduled\",\n details: JSON.stringify(props),\n });\n }\n }\n return response.joinSessionResponse;\n }\n\n private calculateJoinSessionRefreshDelta(responseFetchTime: number, refreshSessionDurationSeconds: number) {\n // 30 seconds is buffer time to refresh the session.\n return responseFetchTime + ((refreshSessionDurationSeconds * 1000) - 30000) - Date.now();\n }\n\n /**\n * Creats a connection to the given delta stream endpoint\n *\n * @param tenantId - the ID of the tenant\n * @param documentId - document ID\n * @param token - authorization token for delta service\n * @param io - websocket library\n * @param client - information about the client\n * @param webSocketUrl - websocket URL\n */\n private async createDeltaConnection(\n tenantId: string,\n documentId: string,\n token: string | null,\n io: typeof SocketIOClientStatic,\n client: IClient,\n webSocketUrl: string,\n ): Promise<OdspDocumentDeltaConnection> {\n const startTime = performance.now();\n const connection = await OdspDocumentDeltaConnection.create(\n tenantId,\n documentId,\n token,\n io,\n client,\n webSocketUrl,\n this.mc.logger,\n 60000,\n this.epochTracker,\n this.socketReferenceKeyPrefix,\n );\n const duration = performance.now() - startTime;\n // This event happens rather often, so it adds up to cost of telemetry.\n // Given that most reconnects result in reusing socket and happen very quickly,\n // report event only if it took longer than threshold.\n if (duration >= 2000) {\n this.mc.logger.sendPerformanceEvent({\n eventName: \"ConnectionSuccess\",\n duration,\n });\n }\n return connection;\n }\n\n public dispose(error?: any) {\n // Error might indicate mismatch between client & server knowlege about file\n // (DriverErrorType.fileOverwrittenInStorage).\n // For example, file might have been overwritten in storage without generating new epoch\n // In such case client cached info is stale and has to be removed.\n if (error !== undefined) {\n this.epochTracker.removeEntries().catch(() => {});\n } else {\n this._opsCache?.flushOps();\n }\n this._opsCache?.dispose();\n }\n\n protected get opsCache() {\n if (this._opsCache) {\n return this._opsCache;\n }\n\n const seqNumber = this.storageManager?.snapshotSequenceNumber;\n const batchSize = this.hostPolicy.opsCaching?.batchSize ?? 100;\n if (seqNumber === undefined || batchSize < 1) {\n return;\n }\n\n const opsKey: Omit<IEntry, \"key\"> = {\n type: \"ops\",\n };\n this._opsCache = new OpsCache(\n seqNumber,\n this.mc.logger,\n // ICache\n {\n write: async (key: string, opsData: string) => {\n return this.cache.persistedCache.put({ ...opsKey, key }, opsData);\n },\n read: async (key: string) => this.cache.persistedCache.get({ ...opsKey, key }),\n remove: () => { this.cache.persistedCache.removeEntries().catch(() => {}); },\n },\n batchSize,\n this.hostPolicy.opsCaching?.timerGranularity ?? 5000,\n this.hostPolicy.opsCaching?.totalOpsToCache ?? 5000,\n );\n return this._opsCache;\n }\n\n // Called whenever re receive ops through any channel for this document (snapshot, delta connection, delta storage)\n // We use it to notify caching layer of how stale is snapshot stored in cache.\n protected opsReceived(ops: ISequencedDocumentMessage[]) {\n // No need for two clients to save same ops\n if (ops.length === 0 || this.odspResolvedUrl.summarizer) {\n return;\n }\n\n this.opsCache?.addOps(ops);\n }\n}\n"]}
|
|
@@ -54,8 +54,8 @@ export declare class OdspDocumentStorageService implements IDocumentStorageServi
|
|
|
54
54
|
createBlob(file: ArrayBufferLike): Promise<api.ICreateBlobResponse>;
|
|
55
55
|
private readBlobCore;
|
|
56
56
|
readBlob(blobId: string): Promise<ArrayBufferLike>;
|
|
57
|
-
getSnapshotTree(version?: api.IVersion): Promise<api.ISnapshotTree | null>;
|
|
58
|
-
getVersions(blobid: string | null, count: number): Promise<api.IVersion[]>;
|
|
57
|
+
getSnapshotTree(version?: api.IVersion, scenarioName?: string): Promise<api.ISnapshotTree | null>;
|
|
58
|
+
getVersions(blobid: string | null, count: number, scenarioName?: string): Promise<api.IVersion[]>;
|
|
59
59
|
private fetchSnapshot;
|
|
60
60
|
private fetchSnapshotCore;
|
|
61
61
|
uploadSummaryWithContext(summary: api.ISummaryTree, context: ISummaryContext): Promise<string>;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"odspDocumentStorageManager.d.ts","sourceRoot":"","sources":["../src/odspDocumentStorageManager.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAGH,OAAO,EAAE,gBAAgB,EAAE,MAAM,oCAAoC,CAAC;AAQtE,OAAO,KAAK,GAAG,MAAM,sCAAsC,CAAC;AAC5D,OAAO,EACH,eAAe,EACf,uBAAuB,EACvB,mBAAmB,EAEtB,MAAM,oCAAoC,CAAC;AAE5C,OAAO,EACH,gBAAgB,EAGhB,+BAA+B,EAClC,MAAM,yCAAyC,CAAC;AACjD,OAAO,EAEH,yBAAyB,EAG5B,MAAM,aAAa,CAAC;AACrB,OAAO,EAA4D,yBAAyB,EAAE,MAAM,iBAAiB,CAAC;AAEtH,OAAO,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AAMzC,OAAO,EAA+B,YAAY,EAAE,MAAM,gBAAgB,CAAC;AAE3E,OAAO,EAAE,WAAW,EAAE,MAAM,+BAA+B,CAAC;AAG5D,eAAO,MAAM,mCAAmC,EAAE,MAAkB,CAAC;AAiHrE,qBAAa,0BAA2B,YAAW,uBAAuB;IA6DlE,OAAO,CAAC,QAAQ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233
|
-
async getSnapshotTree(version) {
|
|
233
|
+
async getSnapshotTree(version, scenarioName) {
|
|
234
234
|
if (!this.snapshotUrl) {
|
|
235
235
|
return null;
|
|
236
236
|
}
|
|
237
237
|
let id;
|
|
238
238
|
if (!version || !version.id) {
|
|
239
|
-
const versions = await this.getVersions(null, 1);
|
|
239
|
+
const versions = await this.getVersions(null, 1, scenarioName);
|
|
240
240
|
if (!versions || versions.length === 0) {
|
|
241
241
|
return null;
|
|
242
242
|
}
|
|
@@ -245,7 +245,7 @@ export class OdspDocumentStorageService {
|
|
|
245
245
|
else {
|
|
246
246
|
id = version.id;
|
|
247
247
|
}
|
|
248
|
-
const snapshotTree = await this.readTree(id);
|
|
248
|
+
const snapshotTree = await this.readTree(id, scenarioName);
|
|
249
249
|
if (!snapshotTree) {
|
|
250
250
|
return null;
|
|
251
251
|
}
|
|
@@ -261,7 +261,7 @@ export class OdspDocumentStorageService {
|
|
|
261
261
|
const protocolTree = snapshotTree.trees[".protocol"];
|
|
262
262
|
return this.combineProtocolAndAppSnapshotTree(appTree, protocolTree);
|
|
263
263
|
}
|
|
264
|
-
async getVersions(blobid, count) {
|
|
264
|
+
async getVersions(blobid, count, scenarioName) {
|
|
265
265
|
// Regular load workflow uses blobId === documentID to indicate "latest".
|
|
266
266
|
if (blobid !== this.documentId && blobid) {
|
|
267
267
|
// FluidFetch & FluidDebugger tools use empty sting to query for versions
|
|
@@ -317,7 +317,7 @@ export class OdspDocumentStorageService {
|
|
|
317
317
|
// or grab the cache value and then the network value if the cache value returns undefined.
|
|
318
318
|
let method;
|
|
319
319
|
if (this.hostPolicy.concurrentSnapshotFetch && !this.hostPolicy.summarizerClient) {
|
|
320
|
-
const networkSnapshotP = this.fetchSnapshot(hostSnapshotOptions);
|
|
320
|
+
const networkSnapshotP = this.fetchSnapshot(hostSnapshotOptions, scenarioName);
|
|
321
321
|
// Ensure that failures on both paths are ignored initially.
|
|
322
322
|
// I.e. if cache fails for some reason, we will proceed with network result.
|
|
323
323
|
// And vice versa - if (for example) client is offline and network request fails first, we
|
|
@@ -347,7 +347,7 @@ export class OdspDocumentStorageService {
|
|
|
347
347
|
retrievedSnapshot = await cachedSnapshotP;
|
|
348
348
|
method = retrievedSnapshot !== undefined ? "cache" : "network";
|
|
349
349
|
if (retrievedSnapshot === undefined) {
|
|
350
|
-
retrievedSnapshot = await this.fetchSnapshot(hostSnapshotOptions);
|
|
350
|
+
retrievedSnapshot = await this.fetchSnapshot(hostSnapshotOptions, scenarioName);
|
|
351
351
|
}
|
|
352
352
|
}
|
|
353
353
|
if (method === "network") {
|
|
@@ -381,7 +381,7 @@ export class OdspDocumentStorageService {
|
|
|
381
381
|
const response = await PerformanceEvent.timedExecAsync(this.logger, {
|
|
382
382
|
eventName: "getVersions",
|
|
383
383
|
headers: Object.keys(headers).length !== 0 ? true : undefined,
|
|
384
|
-
}, async () => this.epochTracker.fetchAndParseAsJSON(url, { headers }, "versions"));
|
|
384
|
+
}, async () => this.epochTracker.fetchAndParseAsJSON(url, { headers }, "versions", undefined, scenarioName));
|
|
385
385
|
const versionsResponse = response.content;
|
|
386
386
|
if (!versionsResponse) {
|
|
387
387
|
throw new NonRetryableError("No response from /versions endpoint", DriverErrorType.genericNetworkError, { driverVersion });
|
|
@@ -397,8 +397,8 @@ export class OdspDocumentStorageService {
|
|
|
397
397
|
});
|
|
398
398
|
});
|
|
399
399
|
}
|
|
400
|
-
async fetchSnapshot(hostSnapshotOptions) {
|
|
401
|
-
return this.fetchSnapshotCore(hostSnapshotOptions).catch((error) => {
|
|
400
|
+
async fetchSnapshot(hostSnapshotOptions, scenarioName) {
|
|
401
|
+
return this.fetchSnapshotCore(hostSnapshotOptions, scenarioName).catch((error) => {
|
|
402
402
|
// Issue #5895:
|
|
403
403
|
// If we are offline, this error is retryable. But that means that RetriableDocumentStorageService
|
|
404
404
|
// will run in circles calling getSnapshotTree, which would result in OdspDocumentStorageService class
|
|
@@ -410,7 +410,7 @@ export class OdspDocumentStorageService {
|
|
|
410
410
|
throw error;
|
|
411
411
|
});
|
|
412
412
|
}
|
|
413
|
-
async fetchSnapshotCore(hostSnapshotOptions) {
|
|
413
|
+
async fetchSnapshotCore(hostSnapshotOptions, scenarioName) {
|
|
414
414
|
var _a, _b;
|
|
415
415
|
const snapshotOptions = Object.assign(Object.assign({ mds: this.maxSnapshotSizeLimit }, hostSnapshotOptions), { timeout: (hostSnapshotOptions === null || hostSnapshotOptions === void 0 ? void 0 : hostSnapshotOptions.timeout) ? Math.min(hostSnapshotOptions.timeout, this.maxSnapshotFetchTimeout) : this.maxSnapshotFetchTimeout });
|
|
416
416
|
// No limit on size of snapshot or time to fetch, as otherwise we fail all clients to summarize
|
|
@@ -419,7 +419,7 @@ export class OdspDocumentStorageService {
|
|
|
419
419
|
snapshotOptions.timeout = undefined;
|
|
420
420
|
}
|
|
421
421
|
const snapshotDownloader = async (finalOdspResolvedUrl, storageToken, options, controller) => {
|
|
422
|
-
return downloadSnapshot(finalOdspResolvedUrl, storageToken, this.logger, options, this.snapshotFormatFetchType, controller, this.epochTracker);
|
|
422
|
+
return downloadSnapshot(finalOdspResolvedUrl, storageToken, this.logger, options, this.snapshotFormatFetchType, controller, this.epochTracker, scenarioName);
|
|
423
423
|
};
|
|
424
424
|
const putInCache = async (valueWithEpoch) => {
|
|
425
425
|
return this.cache.persistedCache.put(createCacheSnapshotKey(this.odspResolvedUrl),
|
|
@@ -498,7 +498,7 @@ export class OdspDocumentStorageService {
|
|
|
498
498
|
throw new NonRetryableError("Method failed because no attachment GET url was available", DriverErrorType.genericError, { driverVersion });
|
|
499
499
|
}
|
|
500
500
|
}
|
|
501
|
-
async readTree(id) {
|
|
501
|
+
async readTree(id, scenarioName) {
|
|
502
502
|
if (!this.snapshotUrl) {
|
|
503
503
|
return null;
|
|
504
504
|
}
|
|
@@ -508,7 +508,7 @@ export class OdspDocumentStorageService {
|
|
|
508
508
|
var _a, _b;
|
|
509
509
|
const storageToken = await this.getStorageToken(options, "ReadCommit");
|
|
510
510
|
const snapshotDownloader = async (url, fetchOptions) => {
|
|
511
|
-
return this.epochTracker.fetchAndParseAsJSON(url, fetchOptions, "snapshotTree");
|
|
511
|
+
return this.epochTracker.fetchAndParseAsJSON(url, fetchOptions, "snapshotTree", undefined, scenarioName);
|
|
512
512
|
};
|
|
513
513
|
const snapshot = await fetchSnapshot(this.snapshotUrl, storageToken, id, this.fetchFullSnapshot, !!((_a = this.hostPolicy.sessionOptions) === null || _a === void 0 ? void 0 : _a.forceAccessTokenViaAuthorizationHeader), this.logger, snapshotDownloader);
|
|
514
514
|
let treeId = "";
|