@cratis/arc 22.185.1 → 22.186.1
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/commands/Command.ts +13 -20
- package/dist/cjs/commands/Command.d.ts +1 -0
- package/dist/cjs/commands/Command.d.ts.map +1 -1
- package/dist/cjs/commands/Command.js +15 -16
- package/dist/cjs/commands/Command.js.map +1 -1
- package/dist/cjs/queries/ObservableQueryFor.d.ts +2 -0
- package/dist/cjs/queries/ObservableQueryFor.d.ts.map +1 -1
- package/dist/cjs/queries/ObservableQueryFor.js +34 -27
- package/dist/cjs/queries/ObservableQueryFor.js.map +1 -1
- package/dist/cjs/queries/QueryInstanceCache.d.ts +1 -0
- package/dist/cjs/queries/QueryInstanceCache.d.ts.map +1 -1
- package/dist/cjs/queries/QueryInstanceCache.js +11 -16
- package/dist/cjs/queries/QueryInstanceCache.js.map +1 -1
- package/dist/cjs/queries/ServerSentEventHubConnection.d.ts +7 -0
- package/dist/cjs/queries/ServerSentEventHubConnection.d.ts.map +1 -1
- package/dist/cjs/queries/ServerSentEventHubConnection.js +97 -57
- package/dist/cjs/queries/ServerSentEventHubConnection.js.map +1 -1
- package/dist/cjs/queries/WebSocketHubConnection.d.ts +6 -0
- package/dist/cjs/queries/WebSocketHubConnection.d.ts.map +1 -1
- package/dist/cjs/queries/WebSocketHubConnection.js +62 -43
- package/dist/cjs/queries/WebSocketHubConnection.js.map +1 -1
- package/dist/esm/commands/Command.d.ts +1 -0
- package/dist/esm/commands/Command.d.ts.map +1 -1
- package/dist/esm/commands/Command.js +15 -16
- package/dist/esm/commands/Command.js.map +1 -1
- package/dist/esm/queries/ObservableQueryFor.d.ts +2 -0
- package/dist/esm/queries/ObservableQueryFor.d.ts.map +1 -1
- package/dist/esm/queries/ObservableQueryFor.js +35 -28
- package/dist/esm/queries/ObservableQueryFor.js.map +1 -1
- package/dist/esm/queries/QueryInstanceCache.d.ts +1 -0
- package/dist/esm/queries/QueryInstanceCache.d.ts.map +1 -1
- package/dist/esm/queries/QueryInstanceCache.js +11 -16
- package/dist/esm/queries/QueryInstanceCache.js.map +1 -1
- package/dist/esm/queries/ServerSentEventHubConnection.d.ts +7 -0
- package/dist/esm/queries/ServerSentEventHubConnection.d.ts.map +1 -1
- package/dist/esm/queries/ServerSentEventHubConnection.js +97 -57
- package/dist/esm/queries/ServerSentEventHubConnection.js.map +1 -1
- package/dist/esm/queries/WebSocketHubConnection.d.ts +6 -0
- package/dist/esm/queries/WebSocketHubConnection.d.ts.map +1 -1
- package/dist/esm/queries/WebSocketHubConnection.js +62 -43
- package/dist/esm/queries/WebSocketHubConnection.js.map +1 -1
- package/dist/esm/tsconfig.tsbuildinfo +1 -1
- package/package.json +1 -1
- package/queries/ObservableQueryFor.ts +43 -32
- package/queries/QueryInstanceCache.ts +12 -18
- package/queries/ServerSentEventHubConnection.ts +120 -113
- package/queries/WebSocketHubConnection.ts +72 -53
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"QueryInstanceCache.js","sources":["../../../queries/QueryInstanceCache.ts"],"sourcesContent":["// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nimport { QueryResultWithState } from './QueryResultWithState.js';\nimport type {\n CacheDiagnostics,\n CacheEntryDiagnostics,\n} from './ObservableQueryDiagnosticsSnapshot.js';\nimport { reconcileQueryData } from './reconcileQueryData.js';\nimport { deepEqual } from '../deepEqual.js';\n\n/**\n * Represents a key that uniquely identifies a query instance in the cache, based on the query type name and its serialized arguments.\n */\nexport type QueryCacheKey = string;\n\n/**\n * Callback invoked when the cached result for an entry changes.\n */\nexport type QueryCacheListener<TDataType> = (\n result: QueryResultWithState<TDataType>,\n) => void;\n\n/**\n * Represents a single entry in the {@link QueryInstanceCache}.\n * @template TDataType The type of data returned by the query.\n */\nexport interface QueryCacheEntry<TDataType> {\n /**\n * The cached query instance.\n */\n readonly instance: unknown;\n\n /**\n * The last result received from the query, if any.\n */\n lastResult?: QueryResultWithState<TDataType>;\n\n /**\n * The number of active subscribers holding a reference to this entry.\n */\n subscriberCount: number;\n\n /**\n * Set of listener callbacks that are notified when {@link lastResult} changes.\n */\n readonly listeners: Set<QueryCacheListener<TDataType>>;\n\n /**\n * Cleanup function returned by the first subscriber that starts the query connection.\n * Called when the last subscriber releases the entry.\n */\n teardown?: () => void;\n\n /**\n * Whether an active subscription has been established for this entry.\n */\n subscribed: boolean;\n\n /**\n * Timer handle for deferred cleanup. Allows React StrictMode re-mounts (in any build\n * environment) to cancel the pending teardown so the connection is reused instead of\n * torn down and recreated.\n */\n pendingCleanup?: ReturnType<typeof setTimeout>;\n}\n\n/**\n * Provides a cache for query instances, keyed by query type and serialized arguments.\n *\n * Two callers requesting the same query type with identical arguments receive the same\n * cached instance and immediately see the last known result — without an additional\n * round trip to the server. When the last subscriber releases its reference the entry\n * is evicted.\n */\nexport class QueryInstanceCache {\n private readonly _entries = new Map<QueryCacheKey, QueryCacheEntry<unknown>>();\n private _pendingDispose?: ReturnType<typeof setTimeout>;\n\n /**\n * Initializes a new instance of {@link QueryInstanceCache}.\n * @param retentionMs How long in milliseconds to keep a cache entry alive after the last\n * subscriber releases it before evicting the subscription and cached data. A non-zero\n * value lets users navigate away and back without losing cached data. Defaults to\n * 30 000 ms. Pass 0 for immediate eviction.\n */\n constructor(private readonly _retentionMs: number = 30_000) {}\n\n /**\n * Builds the cache key for a query.\n * @param queryTypeName The stable type name for the query. Use the instance's `queryName`\n * (a hardcoded fully-qualified string in generated proxies) rather than {@link Function.name},\n * which is unstable under minification.\n * @param args Optional arguments supplied to the query.\n * @returns A stable string key.\n */\n buildKey(queryTypeName: string, args?: object): QueryCacheKey {\n if (!args || Object.keys(args).length === 0) {\n return `${queryTypeName}::`;\n }\n\n const sorted = Object.keys(args)\n .sort()\n .reduce<Record<string, unknown>>((accumulator, key) => {\n accumulator[key] = (args as Record<string, unknown>)[key];\n return accumulator;\n }, {});\n\n return `${queryTypeName}::${JSON.stringify(sorted)}`;\n }\n\n /**\n * Returns a cached instance for the given key, or creates a new one using the provided factory.\n * The subscriber count of the entry is incremented.\n * @template TInstance The type of the query instance.\n * @param key The cache key produced by {@link buildKey}.\n * @param factory A zero-argument factory that creates a fresh query instance when one is not yet cached.\n * @returns The cached (or newly created) instance and whether it was newly created.\n */\n getOrCreate<TInstance>(\n key: QueryCacheKey,\n factory: () => TInstance,\n ): { instance: TInstance; isNew: boolean } {\n if (!this._entries.has(key)) {\n const entry: QueryCacheEntry<unknown> = {\n instance: factory(),\n lastResult: undefined,\n subscriberCount: 0,\n listeners: new Set(),\n subscribed: false,\n };\n\n this._entries.set(key, entry);\n return { instance: entry.instance as TInstance, isNew: true };\n }\n\n const entry = this._entries.get(key)!;\n return { instance: entry.instance as TInstance, isNew: false };\n }\n\n /**\n * Increments the active subscriber count for the given key.\n * If a deferred cleanup was pending (from a recent {@link release}),\n * it is cancelled so the existing subscription is reused.\n * Call from `useEffect` setup to pair with {@link release} in the cleanup.\n * @param key The cache key produced by {@link buildKey}.\n */\n acquire(key: QueryCacheKey): void {\n const entry = this._entries.get(key);\n\n if (entry) {\n if (entry.pendingCleanup !== undefined) {\n clearTimeout(entry.pendingCleanup);\n entry.pendingCleanup = undefined;\n }\n\n entry.subscriberCount++;\n }\n }\n\n /**\n * Returns the last cached result for the given key, or `undefined` if no result has been stored yet.\n * @template TDataType The type of data returned by the query.\n * @param key The cache key produced by {@link buildKey}.\n * @returns The last {@link QueryResultWithState}, or `undefined`.\n */\n getLastResult<TDataType>(\n key: QueryCacheKey,\n ): QueryResultWithState<TDataType> | undefined {\n return this._entries.get(key)?.lastResult as\n | QueryResultWithState<TDataType>\n | undefined;\n }\n\n /**\n * Stores the most recent result for the given key and notifies all registered listeners.\n * @template TDataType The type of data returned by the query.\n * @param key The cache key produced by {@link buildKey}.\n * @param result The result to store.\n */\n setLastResult<TDataType>(\n key: QueryCacheKey,\n result: QueryResultWithState<TDataType>,\n ): void {\n const entry = this._entries.get(key);\n\n if (!entry) {\n return;\n }\n\n const previousResult = entry.lastResult as\n | QueryResultWithState<TDataType>\n | undefined;\n\n // Reconcile the incoming payload against the one already held so items that did not actually\n // change keep their previous references. A full snapshot — which is what the server re-sends\n // whenever a subscription is re-established — otherwise arrives as all-new references and\n // makes every consumer treat every item as changed.\n const reconciled =\n previousResult === undefined\n ? result\n : this.withReconciledData(previousResult, result);\n\n entry.lastResult = reconciled as QueryResultWithState<unknown>;\n\n // Reconciliation returns the previous data reference when nothing changed, so identity is\n // enough to detect it. Data and result metadata affect what the user sees; changeSet is\n // ephemeral and does not independently require a notification.\n if (\n previousResult !== undefined &&\n previousResult.data === reconciled.data &&\n this.hasEquivalentMetadata(previousResult, reconciled)\n ) {\n return;\n }\n\n for (const listener of entry.listeners) {\n (listener as QueryCacheListener<TDataType>)(reconciled);\n }\n }\n\n /**\n * Returns the incoming result with its data reconciled against the previous result, or the\n * incoming result unchanged when reconciliation found nothing to carry over.\n * @template TDataType The type of data returned by the query.\n * @param previous The previously held result.\n * @param next The freshly received result.\n * @returns A result whose data preserves references for everything that did not change.\n */\n private withReconciledData<TDataType>(\n previous: QueryResultWithState<TDataType>,\n next: QueryResultWithState<TDataType>,\n ): QueryResultWithState<TDataType> {\n const reconciledData = reconcileQueryData(previous.data, next.data);\n\n if (reconciledData === next.data) {\n return next;\n }\n\n return new QueryResultWithState<TDataType>(\n reconciledData,\n next.paging,\n next.isSuccess,\n next.isAuthorized,\n next.isValid,\n next.validationResults,\n next.hasExceptions,\n next.exceptionMessages,\n next.exceptionStackTrace,\n next.isPerforming,\n next.changeSet,\n next.isReady,\n );\n }\n\n private hasEquivalentMetadata<TDataType>(result: QueryResultWithState<TDataType>, previous: QueryResultWithState<TDataType>): boolean {\n return result.isPerforming === previous.isPerforming\n && result.isSuccess === previous.isSuccess\n && result.isReady === previous.isReady\n && result.isAuthorized === previous.isAuthorized\n && result.isValid === previous.isValid\n && result.hasExceptions === previous.hasExceptions\n && result.exceptionStackTrace === previous.exceptionStackTrace\n && deepEqual(result.paging, previous.paging)\n && deepEqual(result.exceptionMessages, previous.exceptionMessages)\n && deepEqual(result.validationResults, previous.validationResults);\n }\n\n /**\n * Registers a listener that is invoked whenever the cached result for the given key changes.\n * @template TDataType The type of data returned by the query.\n * @param key The cache key produced by {@link buildKey}.\n * @param listener The callback to register.\n */\n addListener<TDataType>(\n key: QueryCacheKey,\n listener: QueryCacheListener<TDataType>,\n ): void {\n const entry = this._entries.get(key);\n\n if (entry) {\n entry.listeners.add(listener as QueryCacheListener<unknown>);\n }\n }\n\n /**\n * Removes a previously registered listener.\n * @template TDataType The type of data returned by the query.\n * @param key The cache key produced by {@link buildKey}.\n * @param listener The callback to remove.\n */\n removeListener<TDataType>(\n key: QueryCacheKey,\n listener: QueryCacheListener<TDataType>,\n ): void {\n const entry = this._entries.get(key);\n\n if (entry) {\n entry.listeners.delete(listener as QueryCacheListener<unknown>);\n }\n }\n\n /**\n * Stores a teardown function for the given key and marks the entry as subscribed.\n * Called automatically when the last subscriber releases the entry.\n * @param key The cache key produced by {@link buildKey}.\n * @param teardown Cleanup function that disconnects the underlying query subscription.\n */\n setTeardown(key: QueryCacheKey, teardown: () => void): void {\n const entry = this._entries.get(key);\n\n if (entry) {\n entry.teardown = teardown;\n entry.subscribed = true;\n }\n }\n\n /**\n * Returns whether an active subscription exists for the given key.\n * @param key The cache key to check.\n * @returns `true` if a subscription has been established; `false` otherwise.\n */\n isSubscribed(key: QueryCacheKey): boolean {\n return this._entries.get(key)?.subscribed ?? false;\n }\n\n /**\n * Decrements the subscriber count for the given key. When the count reaches zero, both teardown\n * and eviction are deferred by one microtask so that React StrictMode re-mounts — in any build\n * environment — can re-acquire the entry and cancel the cleanup before the timeout fires. This\n * prevents an unnecessary disconnect/reconnect cycle during the synthetic unmount/remount that\n * StrictMode performs.\n * @param key The cache key produced by {@link buildKey}.\n */\n release(key: QueryCacheKey): void {\n const entry = this._entries.get(key);\n\n if (entry) {\n entry.subscriberCount--;\n\n if (entry.subscriberCount <= 0) {\n // Defer both teardown and eviction. React StrictMode re-mounts can cancel by\n // calling acquire() before the timeout fires. A non-zero _retentionMs keeps the\n // entry alive so users navigating back quickly see cached data immediately.\n entry.pendingCleanup = setTimeout(() => {\n const current = this._entries.get(key);\n\n if (current && current.subscriberCount <= 0) {\n current.subscribed = false;\n current.teardown?.();\n current.teardown = undefined;\n current.pendingCleanup = undefined;\n this._entries.delete(key);\n }\n }, this._retentionMs);\n }\n }\n }\n\n /**\n * Returns whether an entry exists for the given key.\n * @param key The cache key to check.\n * @returns `true` if an entry exists; `false` otherwise.\n */\n has(key: QueryCacheKey): boolean {\n return this._entries.has(key);\n }\n\n /**\n * Tears down all active subscriptions and marks every entry as not subscribed,\n * but preserves entries, subscriber counts, and listeners. This allows\n * hooks whose effects re-run afterward to detect that the entry is no longer\n * subscribed and re-establish a fresh connection.\n *\n * Use this when the underlying transport must be replaced (e.g. after an\n * authentication change that requires new WebSocket connections with updated\n * credentials).\n */\n teardownAllSubscriptions(): void {\n for (const [, entry] of this._entries) {\n if (entry.pendingCleanup !== undefined) {\n clearTimeout(entry.pendingCleanup);\n entry.pendingCleanup = undefined;\n }\n\n entry.subscribed = false;\n entry.teardown?.();\n entry.teardown = undefined;\n }\n }\n\n /**\n * Immediately tears down all subscriptions, cancels any pending deferred cleanups,\n * and evicts all entries. Call when the owning component (e.g. the {@link Arc} provider)\n * unmounts permanently so that all query connections are closed synchronously.\n */\n dispose(): void {\n for (const [, entry] of this._entries) {\n if (entry.pendingCleanup !== undefined) {\n clearTimeout(entry.pendingCleanup);\n entry.pendingCleanup = undefined;\n }\n\n entry.subscribed = false;\n entry.teardown?.();\n entry.teardown = undefined;\n }\n\n this._entries.clear();\n }\n\n /**\n * Schedules a deferred {@link dispose} using {@code setTimeout(0)}.\n *\n * This allows React StrictMode re-mounts to call {@link cancelPendingDispose}\n * before the dispose fires, avoiding the destruction of cache entries that child\n * effects are about to re-acquire.\n *\n * If a deferred dispose is already pending, it is replaced.\n */\n deferDispose(): void {\n if (this._pendingDispose !== undefined) {\n clearTimeout(this._pendingDispose);\n }\n\n this._pendingDispose = setTimeout(() => {\n this._pendingDispose = undefined;\n this.dispose();\n }, 0);\n }\n\n /**\n * Cancels a pending deferred dispose scheduled by {@link deferDispose}.\n *\n * Call from the {@code useEffect} setup phase so that a StrictMode re-mount\n * prevents the synthetic unmount's deferred dispose from firing.\n */\n cancelPendingDispose(): void {\n if (this._pendingDispose !== undefined) {\n clearTimeout(this._pendingDispose);\n this._pendingDispose = undefined;\n }\n }\n\n /**\n * Returns a diagnostics snapshot of the current cache state.\n * @returns A {@link CacheDiagnostics} describing all entries.\n */\n getDiagnosticsSnapshot(): CacheDiagnostics {\n const entries: CacheEntryDiagnostics[] = [];\n let totalBytes = 0;\n let unhealthyCount = 0;\n\n for (const [key, entry] of this._entries) {\n const colonIndex = key.indexOf('::');\n const queryName = colonIndex >= 0 ? key.substring(0, colonIndex) : key;\n\n let estimatedBytes = 0;\n try {\n if (entry.lastResult !== undefined) {\n estimatedBytes = JSON.stringify(entry.lastResult).length;\n }\n } catch {\n // Ignore serialization errors\n }\n\n if (entry.subscriberCount > 0 && !entry.subscribed) {\n unhealthyCount++;\n }\n\n totalBytes += estimatedBytes;\n entries.push({\n key,\n queryName,\n subscriberCount: entry.subscriberCount,\n listenerCount: entry.listeners.size,\n subscribed: entry.subscribed,\n hasResult: entry.lastResult !== undefined,\n estimatedBytes,\n });\n }\n\n return {\n healthy: unhealthyCount === 0,\n entryCount: this._entries.size,\n estimatedBytes: totalBytes,\n entries,\n };\n }\n}\n"],"names":["QueryInstanceCache","_entries","Map","_pendingDispose","_retentionMs","buildKey","queryTypeName","args","Object","keys","length","sorted","sort","reduce","accumulator","key","JSON","stringify","getOrCreate","factory","has","entry","instance","lastResult","undefined","subscriberCount","listeners","Set","subscribed","set","isNew","get","acquire","pendingCleanup","clearTimeout","getLastResult","setLastResult","result","previousResult","reconciled","withReconciledData","data","hasEquivalentMetadata","listener","previous","next","reconciledData","reconcileQueryData","QueryResultWithState","paging","isSuccess","isAuthorized","isValid","validationResults","hasExceptions","exceptionMessages","exceptionStackTrace","isPerforming","changeSet","isReady","deepEqual","addListener","add","removeListener","delete","setTeardown","teardown","isSubscribed","release","setTimeout","current","teardownAllSubscriptions","dispose","clear","deferDispose","cancelPendingDispose","getDiagnosticsSnapshot","entries","totalBytes","unhealthyCount","colonIndex","indexOf","queryName","substring","estimatedBytes","push","listenerCount","size","hasResult","healthy","entryCount"],"mappings":";;;;;;AAAA;AACA;AAkEA;;;;;;;AAOC,IACM,MAAMA,kBAAAA,CAAAA;;AACQC,IAAAA,QAAAA,GAAW,IAAIC,GAAAA,EAAAA;IACxBC,eAAAA;AAER;;;;;;AAMC,QACD,WAAA,CAA6BC,YAAAA,GAAuB,MAAM,CAAE;aAA/BA,YAAAA,GAAAA,YAAAA;AAAgC,IAAA;AAE7D;;;;;;;AAOC,QACDC,QAAAA,CAASC,aAAqB,EAAEC,IAAa,EAAiB;QAC1D,IAAI,CAACA,QAAQC,MAAAA,CAAOC,IAAI,CAACF,IAAAA,CAAAA,CAAMG,MAAM,KAAK,CAAA,EAAG;YACzC,OAAO,CAAA,EAAGJ,aAAAA,CAAc,EAAE,CAAC;AAC/B,QAAA;QAEA,MAAMK,MAAAA,GAASH,MAAAA,CAAOC,IAAI,CAACF,IAAAA,CAAAA,CACtBK,IAAI,EAAA,CACJC,MAAM,CAA0B,CAACC,WAAAA,EAAaC,GAAAA,GAAAA;AAC3CD,YAAAA,WAAW,CAACC,GAAAA,CAAI,GAAG,IAAiC,CAACA,GAAAA,CAAI;YACzD,OAAOD,WAAAA;AACX,QAAA,CAAA,EAAG,EAAC,CAAA;AAER,QAAA,OAAO,GAAGR,aAAAA,CAAc,EAAE,EAAEU,IAAAA,CAAKC,SAAS,CAACN,MAAAA,CAAAA,CAAAA,CAAS;AACxD,IAAA;AAEA;;;;;;;AAOC,QACDO,WAAAA,CACIH,GAAkB,EAClBI,OAAwB,EACe;AACvC,QAA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CAAE,OAAM;;AAER,YAAA;AAEA,YAAA,IAAIW,MAAMI,eAAe,GAAG,KAAK,CAACJ,KAAAA,CAAMO,UAAU,EAAE;AAChDmD,gBAAAA,cAAAA,EAAAA;AACJ,YAAA;YAEAD,UAAAA,IAAcM,cAAAA;AACdP,YAAAA,OAAAA,CAAQQ,IAAI,CAAC;AACTtE,gBAAAA,GAAAA;AACAmE,gBAAAA,SAAAA;AACAzD,gBAAAA,eAAAA,EAAiBJ,MAAMI,eAAe;gBACtC6D,aAAAA,EAAejE,KAAAA,CAAMK,SAAS,CAAC6D,IAAI;AACnC3D,gBAAAA,UAAAA,EAAYP,MAAMO,UAAU;gBAC5B4D,SAAAA,EAAWnE,KAAAA,CAAME,UAAU,KAAKC,SAAAA;AAChC4D,gBAAAA;AACJ,aAAA,CAAA;AACJ,QAAA;QAEA,OAAO;AACHK,YAAAA,OAAAA,EAASV,cAAAA,KAAmB,CAAA;AAC5BW,YAAAA,UAAAA,EAAY,IAAI,CAACzF,QAAQ,CAACsF,IAAI;YAC9BH,cAAAA,EAAgBN,UAAAA;AAChBD,YAAAA;AACJ,SAAA;AACJ,IAAA;AACJ;;"}
|
|
1
|
+
{"version":3,"file":"QueryInstanceCache.js","sources":["../../../queries/QueryInstanceCache.ts"],"sourcesContent":["// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nimport { QueryResultWithState } from './QueryResultWithState.js';\nimport type {\n CacheDiagnostics,\n CacheEntryDiagnostics,\n} from './ObservableQueryDiagnosticsSnapshot.js';\nimport { reconcileQueryData } from './reconcileQueryData.js';\nimport { deepEqual } from '../deepEqual.js';\n\n/**\n * Represents a key that uniquely identifies a query instance in the cache, based on the query type name and its serialized arguments.\n */\nexport type QueryCacheKey = string;\n\n/**\n * Callback invoked when the cached result for an entry changes.\n */\nexport type QueryCacheListener<TDataType> = (\n result: QueryResultWithState<TDataType>,\n) => void;\n\n/**\n * Represents a single entry in the {@link QueryInstanceCache}.\n * @template TDataType The type of data returned by the query.\n */\nexport interface QueryCacheEntry<TDataType> {\n /**\n * The cached query instance.\n */\n readonly instance: unknown;\n\n /**\n * The last result received from the query, if any.\n */\n lastResult?: QueryResultWithState<TDataType>;\n\n /**\n * The number of active subscribers holding a reference to this entry.\n */\n subscriberCount: number;\n\n /**\n * Set of listener callbacks that are notified when {@link lastResult} changes.\n */\n readonly listeners: Set<QueryCacheListener<TDataType>>;\n\n /**\n * Cleanup function returned by the first subscriber that starts the query connection.\n * Called when the last subscriber releases the entry.\n */\n teardown?: () => void;\n\n /**\n * Whether an active subscription has been established for this entry.\n */\n subscribed: boolean;\n\n /**\n * Timer handle for deferred cleanup. Allows React StrictMode re-mounts (in any build\n * environment) to cancel the pending teardown so the connection is reused instead of\n * torn down and recreated.\n */\n pendingCleanup?: ReturnType<typeof setTimeout>;\n}\n\n/**\n * Provides a cache for query instances, keyed by query type and serialized arguments.\n *\n * Two callers requesting the same query type with identical arguments receive the same\n * cached instance and immediately see the last known result — without an additional\n * round trip to the server. When the last subscriber releases its reference the entry\n * is evicted.\n */\nexport class QueryInstanceCache {\n private readonly _entries = new Map<QueryCacheKey, QueryCacheEntry<unknown>>();\n private _pendingDispose?: ReturnType<typeof setTimeout>;\n\n /**\n * Initializes a new instance of {@link QueryInstanceCache}.\n * @param retentionMs How long in milliseconds to keep a cache entry alive after the last\n * subscriber releases it before evicting the subscription and cached data. A non-zero\n * value lets users navigate away and back without losing cached data. Defaults to\n * 30 000 ms. Pass 0 for immediate eviction.\n */\n constructor(private readonly _retentionMs: number = 30_000) {}\n\n /**\n * Builds the cache key for a query.\n * @param queryTypeName The stable type name for the query. Use the instance's `queryName`\n * (a hardcoded fully-qualified string in generated proxies) rather than {@link Function.name},\n * which is unstable under minification.\n * @param args Optional arguments supplied to the query.\n * @returns A stable string key.\n */\n buildKey(queryTypeName: string, args?: object): QueryCacheKey {\n if (!args || Object.keys(args).length === 0) {\n return `${queryTypeName}::`;\n }\n\n const sorted = Object.keys(args)\n .sort()\n .reduce<Record<string, unknown>>((accumulator, key) => {\n accumulator[key] = (args as Record<string, unknown>)[key];\n return accumulator;\n }, {});\n\n return `${queryTypeName}::${JSON.stringify(sorted)}`;\n }\n\n /**\n * Returns a cached instance for the given key, or creates a new one using the provided factory.\n * The subscriber count of the entry is incremented.\n * @template TInstance The type of the query instance.\n * @param key The cache key produced by {@link buildKey}.\n * @param factory A zero-argument factory that creates a fresh query instance when one is not yet cached.\n * @returns The cached (or newly created) instance and whether it was newly created.\n */\n getOrCreate<TInstance>(\n key: QueryCacheKey,\n factory: () => TInstance,\n ): { instance: TInstance; isNew: boolean } {\n if (!this._entries.has(key)) {\n const entry: QueryCacheEntry<unknown> = {\n instance: factory(),\n lastResult: undefined,\n subscriberCount: 0,\n listeners: new Set(),\n subscribed: false,\n };\n\n this._entries.set(key, entry);\n return { instance: entry.instance as TInstance, isNew: true };\n }\n\n const entry = this._entries.get(key)!;\n return { instance: entry.instance as TInstance, isNew: false };\n }\n\n /**\n * Increments the active subscriber count for the given key.\n * If a deferred cleanup was pending (from a recent {@link release}),\n * it is cancelled so the existing subscription is reused.\n * Call from `useEffect` setup to pair with {@link release} in the cleanup.\n * @param key The cache key produced by {@link buildKey}.\n */\n acquire(key: QueryCacheKey): void {\n const entry = this._entries.get(key);\n\n if (entry) {\n if (entry.pendingCleanup !== undefined) {\n clearTimeout(entry.pendingCleanup);\n entry.pendingCleanup = undefined;\n }\n\n entry.subscriberCount++;\n }\n }\n\n /**\n * Returns the last cached result for the given key, or `undefined` if no result has been stored yet.\n * @template TDataType The type of data returned by the query.\n * @param key The cache key produced by {@link buildKey}.\n * @returns The last {@link QueryResultWithState}, or `undefined`.\n */\n getLastResult<TDataType>(\n key: QueryCacheKey,\n ): QueryResultWithState<TDataType> | undefined {\n return this._entries.get(key)?.lastResult as\n | QueryResultWithState<TDataType>\n | undefined;\n }\n\n /**\n * Stores the most recent result for the given key and notifies all registered listeners.\n * @template TDataType The type of data returned by the query.\n * @param key The cache key produced by {@link buildKey}.\n * @param result The result to store.\n */\n setLastResult<TDataType>(\n key: QueryCacheKey,\n result: QueryResultWithState<TDataType>,\n ): void {\n const entry = this._entries.get(key);\n\n if (!entry) {\n return;\n }\n\n const previousResult = entry.lastResult as\n | QueryResultWithState<TDataType>\n | undefined;\n\n // Reconcile the incoming payload against the one already held so items that did not actually\n // change keep their previous references. A full snapshot — which is what the server re-sends\n // whenever a subscription is re-established — otherwise arrives as all-new references and\n // makes every consumer treat every item as changed.\n const reconciled =\n previousResult === undefined\n ? result\n : this.withReconciledData(previousResult, result);\n\n entry.lastResult = reconciled as QueryResultWithState<unknown>;\n\n // Reconciliation returns the previous data reference when nothing changed, so identity is\n // enough to detect it. Data and result metadata affect what the user sees; changeSet is\n // ephemeral and does not independently require a notification.\n if (\n previousResult !== undefined &&\n previousResult.data === reconciled.data &&\n this.hasEquivalentMetadata(previousResult, reconciled)\n ) {\n return;\n }\n\n for (const listener of entry.listeners) {\n (listener as QueryCacheListener<TDataType>)(reconciled);\n }\n }\n\n /**\n * Returns the incoming result with its data reconciled against the previous result, or the\n * incoming result unchanged when reconciliation found nothing to carry over.\n * @template TDataType The type of data returned by the query.\n * @param previous The previously held result.\n * @param next The freshly received result.\n * @returns A result whose data preserves references for everything that did not change.\n */\n private withReconciledData<TDataType>(\n previous: QueryResultWithState<TDataType>,\n next: QueryResultWithState<TDataType>,\n ): QueryResultWithState<TDataType> {\n const reconciledData = reconcileQueryData(previous.data, next.data);\n\n if (reconciledData === next.data) {\n return next;\n }\n\n return new QueryResultWithState<TDataType>(\n reconciledData,\n next.paging,\n next.isSuccess,\n next.isAuthorized,\n next.isValid,\n next.validationResults,\n next.hasExceptions,\n next.exceptionMessages,\n next.exceptionStackTrace,\n next.isPerforming,\n next.changeSet,\n next.isReady,\n );\n }\n\n private hasEquivalentMetadata<TDataType>(result: QueryResultWithState<TDataType>, previous: QueryResultWithState<TDataType>): boolean {\n return result.isPerforming === previous.isPerforming\n && result.isSuccess === previous.isSuccess\n && result.isReady === previous.isReady\n && result.isAuthorized === previous.isAuthorized\n && result.isValid === previous.isValid\n && result.hasExceptions === previous.hasExceptions\n && result.exceptionStackTrace === previous.exceptionStackTrace\n && deepEqual(result.paging, previous.paging)\n && deepEqual(result.exceptionMessages, previous.exceptionMessages)\n && deepEqual(result.validationResults, previous.validationResults);\n }\n\n /**\n * Registers a listener that is invoked whenever the cached result for the given key changes.\n * @template TDataType The type of data returned by the query.\n * @param key The cache key produced by {@link buildKey}.\n * @param listener The callback to register.\n */\n addListener<TDataType>(\n key: QueryCacheKey,\n listener: QueryCacheListener<TDataType>,\n ): void {\n const entry = this._entries.get(key);\n\n if (entry) {\n entry.listeners.add(listener as QueryCacheListener<unknown>);\n }\n }\n\n /**\n * Removes a previously registered listener.\n * @template TDataType The type of data returned by the query.\n * @param key The cache key produced by {@link buildKey}.\n * @param listener The callback to remove.\n */\n removeListener<TDataType>(\n key: QueryCacheKey,\n listener: QueryCacheListener<TDataType>,\n ): void {\n const entry = this._entries.get(key);\n\n if (entry) {\n entry.listeners.delete(listener as QueryCacheListener<unknown>);\n }\n }\n\n /**\n * Stores a teardown function for the given key and marks the entry as subscribed.\n * Called automatically when the last subscriber releases the entry.\n * @param key The cache key produced by {@link buildKey}.\n * @param teardown Cleanup function that disconnects the underlying query subscription.\n */\n setTeardown(key: QueryCacheKey, teardown: () => void): void {\n const entry = this._entries.get(key);\n\n if (entry) {\n entry.teardown = teardown;\n entry.subscribed = true;\n }\n }\n\n /**\n * Returns whether an active subscription exists for the given key.\n * @param key The cache key to check.\n * @returns `true` if a subscription has been established; `false` otherwise.\n */\n isSubscribed(key: QueryCacheKey): boolean {\n return this._entries.get(key)?.subscribed ?? false;\n }\n\n /**\n * Decrements the subscriber count for the given key. When the count reaches zero, both teardown\n * and eviction are deferred by one microtask so that React StrictMode re-mounts — in any build\n * environment — can re-acquire the entry and cancel the cleanup before the timeout fires. This\n * prevents an unnecessary disconnect/reconnect cycle during the synthetic unmount/remount that\n * StrictMode performs.\n * @param key The cache key produced by {@link buildKey}.\n */\n release(key: QueryCacheKey): void {\n const entry = this._entries.get(key);\n\n if (entry) {\n entry.subscriberCount--;\n\n if (entry.subscriberCount <= 0) {\n // Defer both teardown and eviction. React StrictMode re-mounts can cancel by\n // calling acquire() before the timeout fires. A non-zero _retentionMs keeps the\n // entry alive so users navigating back quickly see cached data immediately.\n entry.pendingCleanup = setTimeout(() => {\n const current = this._entries.get(key);\n\n if (current && current.subscriberCount <= 0) {\n current.subscribed = false;\n current.teardown?.();\n current.teardown = undefined;\n current.pendingCleanup = undefined;\n this._entries.delete(key);\n }\n }, this._retentionMs);\n }\n }\n }\n\n /**\n * Returns whether an entry exists for the given key.\n * @param key The cache key to check.\n * @returns `true` if an entry exists; `false` otherwise.\n */\n has(key: QueryCacheKey): boolean {\n return this._entries.has(key);\n }\n\n /**\n * Tears down all active subscriptions and marks every entry as not subscribed,\n * but preserves entries, subscriber counts, and listeners. This allows\n * hooks whose effects re-run afterward to detect that the entry is no longer\n * subscribed and re-establish a fresh connection.\n *\n * Use this when the underlying transport must be replaced (e.g. after an\n * authentication change that requires new WebSocket connections with updated\n * credentials).\n */\n teardownAllSubscriptions(): void {\n for (const [, entry] of this._entries) {\n this.teardownEntry(entry);\n }\n }\n\n private teardownEntry(entry: QueryCacheEntry<unknown>): void {\n if (entry.pendingCleanup !== undefined) {\n clearTimeout(entry.pendingCleanup);\n entry.pendingCleanup = undefined;\n }\n\n entry.subscribed = false;\n entry.teardown?.();\n entry.teardown = undefined;\n }\n\n /**\n * Immediately tears down all subscriptions, cancels any pending deferred cleanups,\n * and evicts all entries. Call when the owning component (e.g. the {@link Arc} provider)\n * unmounts permanently so that all query connections are closed synchronously.\n */\n dispose(): void {\n this.teardownAllSubscriptions();\n this._entries.clear();\n }\n\n /**\n * Schedules a deferred {@link dispose} using {@code setTimeout(0)}.\n *\n * This allows React StrictMode re-mounts to call {@link cancelPendingDispose}\n * before the dispose fires, avoiding the destruction of cache entries that child\n * effects are about to re-acquire.\n *\n * If a deferred dispose is already pending, it is replaced.\n */\n deferDispose(): void {\n if (this._pendingDispose !== undefined) {\n clearTimeout(this._pendingDispose);\n }\n\n this._pendingDispose = setTimeout(() => {\n this._pendingDispose = undefined;\n this.dispose();\n }, 0);\n }\n\n /**\n * Cancels a pending deferred dispose scheduled by {@link deferDispose}.\n *\n * Call from the {@code useEffect} setup phase so that a StrictMode re-mount\n * prevents the synthetic unmount's deferred dispose from firing.\n */\n cancelPendingDispose(): void {\n if (this._pendingDispose !== undefined) {\n clearTimeout(this._pendingDispose);\n this._pendingDispose = undefined;\n }\n }\n\n /**\n * Returns a diagnostics snapshot of the current cache state.\n * @returns A {@link CacheDiagnostics} describing all entries.\n */\n getDiagnosticsSnapshot(): CacheDiagnostics {\n const entries: CacheEntryDiagnostics[] = [];\n let totalBytes = 0;\n let unhealthyCount = 0;\n\n for (const [key, entry] of this._entries) {\n const colonIndex = key.indexOf('::');\n const queryName = colonIndex >= 0 ? key.substring(0, colonIndex) : key;\n\n let estimatedBytes = 0;\n try {\n if (entry.lastResult !== undefined) {\n estimatedBytes = JSON.stringify(entry.lastResult).length;\n }\n } catch {\n // Ignore serialization errors\n }\n\n if (entry.subscriberCount > 0 && !entry.subscribed) {\n unhealthyCount++;\n }\n\n totalBytes += estimatedBytes;\n entries.push({\n key,\n queryName,\n subscriberCount: entry.subscriberCount,\n listenerCount: entry.listeners.size,\n subscribed: entry.subscribed,\n hasResult: entry.lastResult !== undefined,\n estimatedBytes,\n });\n }\n\n return {\n healthy: unhealthyCount === 0,\n entryCount: this._entries.size,\n estimatedBytes: totalBytes,\n entries,\n };\n }\n}\n"],"names":["QueryInstanceCache","_entries","Map","_pendingDispose","_retentionMs","buildKey","queryTypeName","args","Object","keys","length","sorted","sort","reduce","accumulator","key","JSON","stringify","getOrCreate","factory","has","entry","instance","lastResult","undefined","subscriberCount","listeners","Set","subscribed","set","isNew","get","acquire","pendingCleanup","clearTimeout","getLastResult","setLastResult","result","previousResult","reconciled","withReconciledData","data","hasEquivalentMetadata","listener","previous","next","reconciledData","reconcileQueryData","QueryResultWithState","paging","isSuccess","isAuthorized","isValid","validationResults","hasExceptions","exceptionMessages","exceptionStackTrace","isPerforming","changeSet","isReady","deepEqual","addListener","add","removeListener","delete","setTeardown","teardown","isSubscribed","release","setTimeout","current","teardownAllSubscriptions","teardownEntry","dispose","clear","deferDispose","cancelPendingDispose","getDiagnosticsSnapshot","entries","totalBytes","unhealthyCount","colonIndex","indexOf","queryName","substring","estimatedBytes","push","listenerCount","size","hasResult","healthy","entryCount"],"mappings":";;;;;;AAAA;AACA;AAkEA;;;;;;;AAOC,IACM,MAAMA,kBAAAA,CAAAA;;AACQC,IAAAA,QAAAA,GAAW,IAAIC,GAAAA,EAAAA;IACxBC,eAAAA;AAER;;;;;;AAMC,QACD,WAAA,CAA6BC,YAAAA,GAAuB,MAAM,CAAE;aAA/BA,YAAAA,GAAAA,YAAAA;AAAgC,IAAA;AAE7D;;;;;;;AAOC,QACDC,QAAAA,CAASC,aAAqB,EAAEC,IAAa,EAAiB;QAC1D,IAAI,CAACA,QAAQC,MAAAA,CAAOC,IAAI,CAACF,IAAAA,CAAAA,CAAMG,MAAM,KAAK,CAAA,EAAG;YACzC,OAAO,CAAA,EAAGJ,aAAAA,CAAc,EAAE,CAAC;AAC/B,QAAA;QAEA,MAAMK,MAAAA,GAASH,MAAAA,CAAOC,IAAI,CAACF,IAAAA,CAAAA,CACtBK,IAAI,EAAA,CACJC,MAAM,CAA0B,CAACC,WAAAA,EAAaC,GAAAA,GAAAA;AAC3CD,YAAAA,WAAW,CAACC,GAAAA,CAAI,GAAG,IAAiC,CAACA,GAAAA,CAAI;YACzD,OAAOD,WAAAA;AACX,QAAA,CAAA,EAAG,EAAC,CAAA;AAER,QAAA,OAAO,GAAGR,aAAAA,CAAc,EAAE,EAAEU,IAAAA,CAAKC,SAAS,CAACN,MAAAA,CAAAA,CAAAA,CAAS;AACxD,IAAA;AAEA;;;;;;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,IAAI,CAAC;AACTvE,gBAAAA,GAAAA;AACAoE,gBAAAA,SAAAA;AACA1D,gBAAAA,eAAAA,EAAiBJ,MAAMI,eAAe;gBACtC8D,aAAAA,EAAelE,KAAAA,CAAMK,SAAS,CAAC8D,IAAI;AACnC5D,gBAAAA,UAAAA,EAAYP,MAAMO,UAAU;gBAC5B6D,SAAAA,EAAWpE,KAAAA,CAAME,UAAU,KAAKC,SAAAA;AAChC6D,gBAAAA;AACJ,aAAA,CAAA;AACJ,QAAA;QAEA,OAAO;AACHK,YAAAA,OAAAA,EAASV,cAAAA,KAAmB,CAAA;AAC5BW,YAAAA,UAAAA,EAAY,IAAI,CAAC1F,QAAQ,CAACuF,IAAI;YAC9BH,cAAAA,EAAgBN,UAAAA;AAChBD,YAAAA;AACJ,SAAA;AACJ,IAAA;AACJ;;"}
|
|
@@ -32,9 +32,14 @@ export declare class ServerSentEventHubConnection implements IObservableQueryHub
|
|
|
32
32
|
private ensureConnected;
|
|
33
33
|
private close;
|
|
34
34
|
private openEventSource;
|
|
35
|
+
private buildEventSourceUrl;
|
|
36
|
+
private isActiveSource;
|
|
37
|
+
private startConnectTimeout;
|
|
35
38
|
private reconnect;
|
|
36
39
|
private clearConnectTimeout;
|
|
37
40
|
private handleMessage;
|
|
41
|
+
private handleUnauthorizedMessage;
|
|
42
|
+
private handleErrorMessage;
|
|
38
43
|
private handleConnected;
|
|
39
44
|
private applyServerKeepAliveInterval;
|
|
40
45
|
private handleQueryResult;
|
|
@@ -42,6 +47,8 @@ export declare class ServerSentEventHubConnection implements IObservableQueryHub
|
|
|
42
47
|
private handleUnauthorized;
|
|
43
48
|
private deliverResult;
|
|
44
49
|
private sendSubscribe;
|
|
50
|
+
private handleSubscribeFailure;
|
|
51
|
+
private scheduleSubscribeRetry;
|
|
45
52
|
private isMessageForCurrentSubscription;
|
|
46
53
|
private isCurrentSubscription;
|
|
47
54
|
private getNextRevision;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"ServerSentEventHubConnection.d.ts","sourceRoot":"","sources":["../../../queries/ServerSentEventHubConnection.ts"],"names":[],"mappings":"AAIA,OAAO,KAAK,EAAE,6BAA6B,EAAE,MAAM,oCAAoC,CAAC;AACxF,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,gCAAgC,CAAC;AAEnE,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,uBAAuB,CAAC;AAG9D,OAAO,EAGH,KAAK,mBAAmB,EAC3B,MAAM,6BAA6B,CAAC;
|
|
1
|
+
{"version":3,"file":"ServerSentEventHubConnection.d.ts","sourceRoot":"","sources":["../../../queries/ServerSentEventHubConnection.ts"],"names":[],"mappings":"AAIA,OAAO,KAAK,EAAE,6BAA6B,EAAE,MAAM,oCAAoC,CAAC;AACxF,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,gCAAgC,CAAC;AAEnE,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,uBAAuB,CAAC;AAG9D,OAAO,EAGH,KAAK,mBAAmB,EAC3B,MAAM,6BAA6B,CAAC;AA2CrC,qBAAa,4BAA6B,YAAW,6BAA6B;IA2B1E,OAAO,CAAC,QAAQ,CAAC,OAAO;IACxB,OAAO,CAAC,QAAQ,CAAC,aAAa;IAC9B,OAAO,CAAC,QAAQ,CAAC,eAAe;IAChC,OAAO,CAAC,QAAQ,CAAC,aAAa;IAE9B,OAAO,CAAC,QAAQ,CAAC,iBAAiB;IAClC,OAAO,CAAC,QAAQ,CAAC,OAAO;IAhC5B,OAAO,CAAC,YAAY,CAAC,CAAc;IACnC,OAAO,CAAC,aAAa,CAAC,CAAS;IAC/B,OAAO,CAAC,aAAa,CAAS;IAC9B,OAAO,CAAC,cAAc,CAA8C;IACpE,OAAO,CAAC,qBAAqB,CAA8C;IAC3E,OAAO,CAAC,gBAAgB,CAAa;IACrC,OAAO,CAAC,eAAe,CAAgB;IACvC,OAAO,CAAC,oBAAoB,CAAC,CAAgC;IAC7D,OAAO,CAAC,aAAa,CAA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AAC,qBAAqB;IAY7B,OAAO,CAAC,eAAe;IAUvB,OAAO,CAAC,eAAe;IAIvB,OAAO,CAAC,eAAe;CAyB1B"}
|
|
@@ -15,6 +15,8 @@ var WebSocketHubConnection = require('./WebSocketHubConnection.js');
|
|
|
15
15
|
* It must stay above 1 — a threshold at or below the server's own cadence makes the client and
|
|
16
16
|
* server timers race, and the client tears down connections the server considers healthy.
|
|
17
17
|
*/ const IDLE_THRESHOLD_FACTOR = 2;
|
|
18
|
+
/** Maximum number of subscribe retries before falling back to a full SSE reconnect. */ const SUBSCRIBE_MAX_RETRIES = 3;
|
|
19
|
+
/** Base delay between subscribe retries; multiplied by the attempt number. */ const SUBSCRIBE_RETRY_DELAY_MS = 200;
|
|
18
20
|
/**
|
|
19
21
|
* A multiplexed SSE hub connection that uses EventSource for server→client streaming
|
|
20
22
|
* and fetch POST requests for client→server subscribe/unsubscribe commands.
|
|
@@ -166,41 +168,54 @@ var WebSocketHubConnection = require('./WebSocketHubConnection.js');
|
|
|
166
168
|
return;
|
|
167
169
|
}
|
|
168
170
|
this._policy.cancel();
|
|
169
|
-
|
|
170
|
-
if (this._microservice?.length > 0) {
|
|
171
|
-
const param = `${Globals.Globals.microserviceWSQueryArgument}=${encodeURIComponent(this._microservice)}`;
|
|
172
|
-
url += (url.includes('?') ? '&' : '?') + param;
|
|
173
|
-
}
|
|
171
|
+
const url = this.buildEventSourceUrl();
|
|
174
172
|
this._connectionId = undefined;
|
|
175
173
|
this._supportsSubscriptionRevisions = false;
|
|
176
174
|
const eventSource = Globals.Globals.eventSourceFactory ? Globals.Globals.eventSourceFactory(url) : new EventSource(url);
|
|
177
175
|
this._eventSource = eventSource;
|
|
178
176
|
eventSource.onopen = ()=>{
|
|
179
|
-
if (this.
|
|
177
|
+
if (!this.isActiveSource(eventSource)) return;
|
|
180
178
|
console.log('SSE hub connection established', url);
|
|
181
179
|
this._policy.reset();
|
|
182
180
|
this._keepAlive.start();
|
|
183
|
-
|
|
184
|
-
// connection is broken. Close and retry via the reconnect policy.
|
|
185
|
-
this.clearConnectTimeout();
|
|
186
|
-
this._connectTimeoutTimer = setTimeout(()=>{
|
|
187
|
-
if (!this._disconnected && this._eventSource === eventSource && !this._connectionId) {
|
|
188
|
-
console.warn('SSE hub: no Connected message within timeout; retrying', this._connectTimeoutMs, url);
|
|
189
|
-
this.reconnect();
|
|
190
|
-
}
|
|
191
|
-
}, this._connectTimeoutMs);
|
|
181
|
+
this.startConnectTimeout(eventSource, url);
|
|
192
182
|
};
|
|
193
183
|
eventSource.onmessage = (event)=>{
|
|
194
|
-
if (this.
|
|
184
|
+
if (!this.isActiveSource(eventSource)) return;
|
|
195
185
|
this._keepAlive.recordActivity();
|
|
196
186
|
this.handleMessage(event.data);
|
|
197
187
|
};
|
|
198
188
|
eventSource.onerror = ()=>{
|
|
199
|
-
if (this.
|
|
189
|
+
if (!this.isActiveSource(eventSource)) return;
|
|
200
190
|
console.warn('SSE hub connection error', url);
|
|
201
191
|
this.reconnect();
|
|
202
192
|
};
|
|
203
193
|
}
|
|
194
|
+
buildEventSourceUrl() {
|
|
195
|
+
let url = this._sseUrl;
|
|
196
|
+
if (this._microservice?.length > 0) {
|
|
197
|
+
const param = `${Globals.Globals.microserviceWSQueryArgument}=${encodeURIComponent(this._microservice)}`;
|
|
198
|
+
url += (url.includes('?') ? '&' : '?') + param;
|
|
199
|
+
}
|
|
200
|
+
return url;
|
|
201
|
+
}
|
|
202
|
+
isActiveSource(eventSource) {
|
|
203
|
+
return !this._disconnected && this._eventSource === eventSource;
|
|
204
|
+
}
|
|
205
|
+
/**
|
|
206
|
+
* If the server does not send a Connected message within the timeout, the
|
|
207
|
+
* connection is broken. Close and retry via the reconnect policy.
|
|
208
|
+
* @param {EventSource} eventSource The source the timeout guards.
|
|
209
|
+
* @param {string} url The URL used for diagnostics.
|
|
210
|
+
*/ startConnectTimeout(eventSource, url) {
|
|
211
|
+
this.clearConnectTimeout();
|
|
212
|
+
this._connectTimeoutTimer = setTimeout(()=>{
|
|
213
|
+
if (this.isActiveSource(eventSource) && !this._connectionId) {
|
|
214
|
+
console.warn('SSE hub: no Connected message within timeout; retrying', this._connectTimeoutMs, url);
|
|
215
|
+
this.reconnect();
|
|
216
|
+
}
|
|
217
|
+
}, this._connectTimeoutMs);
|
|
218
|
+
}
|
|
204
219
|
reconnect() {
|
|
205
220
|
this._keepAlive.stop();
|
|
206
221
|
this.clearConnectTimeout();
|
|
@@ -238,22 +253,26 @@ var WebSocketHubConnection = require('./WebSocketHubConnection.js');
|
|
|
238
253
|
case WebSocketHubConnection.HubMessageType.Ping:
|
|
239
254
|
break;
|
|
240
255
|
case WebSocketHubConnection.HubMessageType.Unauthorized:
|
|
241
|
-
|
|
242
|
-
console.warn('SSE hub: query unauthorized', message.queryId);
|
|
243
|
-
this.handleUnauthorized(message);
|
|
244
|
-
}
|
|
256
|
+
this.handleUnauthorizedMessage(message);
|
|
245
257
|
break;
|
|
246
258
|
case WebSocketHubConnection.HubMessageType.Error:
|
|
247
|
-
|
|
248
|
-
console.error('SSE hub: query error', message.queryId, message.payload);
|
|
249
|
-
this.handleError(message);
|
|
250
|
-
}
|
|
259
|
+
this.handleErrorMessage(message);
|
|
251
260
|
break;
|
|
252
261
|
}
|
|
253
262
|
} catch (error) {
|
|
254
263
|
console.error('SSE hub: error parsing message', error);
|
|
255
264
|
}
|
|
256
265
|
}
|
|
266
|
+
handleUnauthorizedMessage(message) {
|
|
267
|
+
if (!this.isMessageForCurrentSubscription(message)) return;
|
|
268
|
+
console.warn('SSE hub: query unauthorized', message.queryId);
|
|
269
|
+
this.handleUnauthorized(message);
|
|
270
|
+
}
|
|
271
|
+
handleErrorMessage(message) {
|
|
272
|
+
if (!this.isMessageForCurrentSubscription(message)) return;
|
|
273
|
+
console.error('SSE hub: query error', message.queryId, message.payload);
|
|
274
|
+
this.handleError(message);
|
|
275
|
+
}
|
|
257
276
|
handleConnected(message) {
|
|
258
277
|
const connectionId = message.payload;
|
|
259
278
|
const connectionIdChanged = this._connectionId !== connectionId;
|
|
@@ -343,14 +362,12 @@ var WebSocketHubConnection = require('./WebSocketHubConnection.js');
|
|
|
343
362
|
body.revision = subscription.revision;
|
|
344
363
|
}
|
|
345
364
|
const customHeaders = Globals.Globals.httpHeadersCallback?.() ?? {};
|
|
346
|
-
|
|
347
|
-
|
|
348
|
-
|
|
349
|
-
|
|
350
|
-
|
|
351
|
-
|
|
352
|
-
const maxRetries = 3;
|
|
353
|
-
const retryDelayMs = 200;
|
|
365
|
+
const target = {
|
|
366
|
+
queryId,
|
|
367
|
+
subscription,
|
|
368
|
+
connectionId,
|
|
369
|
+
attempt
|
|
370
|
+
};
|
|
354
371
|
fetch(this._subscribeUrl, {
|
|
355
372
|
method: 'POST',
|
|
356
373
|
headers: {
|
|
@@ -360,34 +377,57 @@ var WebSocketHubConnection = require('./WebSocketHubConnection.js');
|
|
|
360
377
|
body: JSON.stringify(body)
|
|
361
378
|
}).then((response)=>{
|
|
362
379
|
if (!response.ok) {
|
|
363
|
-
|
|
364
|
-
console.warn('SSE hub: subscribe POST returned a failure for an obsolete connection or subscription; ignoring', queryId, response.status);
|
|
365
|
-
} else if (attempt < maxRetries) {
|
|
366
|
-
setTimeout(()=>{
|
|
367
|
-
if (this.isCurrentSubscription(queryId, subscription, connectionId)) {
|
|
368
|
-
this.sendSubscribe(queryId, subscription, attempt + 1);
|
|
369
|
-
}
|
|
370
|
-
}, retryDelayMs * (attempt + 1));
|
|
371
|
-
} else {
|
|
372
|
-
console.warn('SSE hub: subscribe POST failed after retries; reconnecting', queryId, response.status, attempt + 1);
|
|
373
|
-
this.reconnect();
|
|
374
|
-
}
|
|
380
|
+
this.handleSubscribeFailure(target, console.warn, response.status);
|
|
375
381
|
}
|
|
376
382
|
}).catch((error)=>{
|
|
377
|
-
|
|
378
|
-
console.warn('SSE hub: subscribe POST failed for an obsolete connection or subscription; ignoring', queryId, error);
|
|
379
|
-
} else if (attempt < maxRetries) {
|
|
380
|
-
setTimeout(()=>{
|
|
381
|
-
if (this.isCurrentSubscription(queryId, subscription, connectionId)) {
|
|
382
|
-
this.sendSubscribe(queryId, subscription, attempt + 1);
|
|
383
|
-
}
|
|
384
|
-
}, retryDelayMs * (attempt + 1));
|
|
385
|
-
} else {
|
|
386
|
-
console.error('SSE hub: subscribe POST failed after retries; reconnecting', queryId, attempt + 1, error);
|
|
387
|
-
this.reconnect();
|
|
388
|
-
}
|
|
383
|
+
this.handleSubscribeFailure(target, console.error, undefined, error);
|
|
389
384
|
});
|
|
390
385
|
}
|
|
386
|
+
/**
|
|
387
|
+
* Decide what to do after a failed subscribe POST: ignore it when obsolete, retry with back-off,
|
|
388
|
+
* or fall back to a full reconnect once the retries are exhausted.
|
|
389
|
+
*
|
|
390
|
+
* The retry limit exists because in a round-robin load-balanced deployment the subscribe POST may
|
|
391
|
+
* land on a different backend instance than the one holding the SSE connection. Retrying gives
|
|
392
|
+
* the load balancer the chance to route a subsequent attempt to the correct instance without
|
|
393
|
+
* tearing down the SSE connection unnecessarily. With N backend instances at most N-1 retries
|
|
394
|
+
* are needed, so 3 retries covers deployments with up to 4 replicas.
|
|
395
|
+
* @param {SubscribeTarget} target The subscribe attempt that failed.
|
|
396
|
+
* @param {Function} exhaustedLog The logger used when the retries are exhausted.
|
|
397
|
+
* @param {number | undefined} status The HTTP status, when the server responded.
|
|
398
|
+
* @param {unknown} error The thrown error, when the request itself failed.
|
|
399
|
+
*/ handleSubscribeFailure(target, exhaustedLog, status, error) {
|
|
400
|
+
const { queryId, subscription, connectionId, attempt } = target;
|
|
401
|
+
const detail = error === undefined ? [
|
|
402
|
+
status
|
|
403
|
+
] : [
|
|
404
|
+
error
|
|
405
|
+
];
|
|
406
|
+
if (!this.isCurrentSubscription(queryId, subscription, connectionId)) {
|
|
407
|
+
const reason = error === undefined ? 'returned a failure' : 'failed';
|
|
408
|
+
console.warn(`SSE hub: subscribe POST ${reason} for an obsolete connection or subscription; ignoring`, queryId, ...detail);
|
|
409
|
+
} else if (attempt < SUBSCRIBE_MAX_RETRIES) {
|
|
410
|
+
this.scheduleSubscribeRetry(target);
|
|
411
|
+
} else {
|
|
412
|
+
const tail = error === undefined ? [
|
|
413
|
+
status,
|
|
414
|
+
attempt + 1
|
|
415
|
+
] : [
|
|
416
|
+
attempt + 1,
|
|
417
|
+
error
|
|
418
|
+
];
|
|
419
|
+
exhaustedLog('SSE hub: subscribe POST failed after retries; reconnecting', queryId, ...tail);
|
|
420
|
+
this.reconnect();
|
|
421
|
+
}
|
|
422
|
+
}
|
|
423
|
+
scheduleSubscribeRetry(target) {
|
|
424
|
+
const { queryId, subscription, connectionId, attempt } = target;
|
|
425
|
+
setTimeout(()=>{
|
|
426
|
+
if (this.isCurrentSubscription(queryId, subscription, connectionId)) {
|
|
427
|
+
this.sendSubscribe(queryId, subscription, attempt + 1);
|
|
428
|
+
}
|
|
429
|
+
}, SUBSCRIBE_RETRY_DELAY_MS * (attempt + 1));
|
|
430
|
+
}
|
|
391
431
|
isMessageForCurrentSubscription(message) {
|
|
392
432
|
if (!message.queryId) return false;
|
|
393
433
|
const subscription = this._subscriptions.get(message.queryId);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"ServerSentEventHubConnection.js","sources":["../../../queries/ServerSentEventHubConnection.ts"],"sourcesContent":["// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nimport { Globals } from '../Globals.js';\nimport type { IObservableQueryHubConnection } from './IObservableQueryHubConnection.js';\nimport type { DataReceived } from './ObservableQueryConnection.js';\nimport { HubConnectionKeepAlive } from './HubConnectionKeepAlive.js';\nimport type { IReconnectPolicy } from './IReconnectPolicy.js';\nimport { ReconnectPolicy } from './ReconnectPolicy.js';\nimport { QueryResult } from './QueryResult.js';\nimport {\n type HubMessage,\n HubMessageType,\n type SubscriptionRequest,\n} from './WebSocketHubConnection.js';\n\n/* eslint-disable @typescript-eslint/no-explicit-any */\n\ninterface ActiveSubscription {\n request: SubscriptionRequest;\n callback: DataReceived<any>;\n revision: number;\n}\n\n/**\n * How many keep-alive intervals of silence are tolerated before the connection is considered dead.\n *\n * The server guarantees a message every interval, so this is pure slack for latency and jitter.\n * It must stay above 1 — a threshold at or below the server's own cadence makes the client and\n * server timers race, and the client tears down connections the server considers healthy.\n */\nconst IDLE_THRESHOLD_FACTOR = 2;\n\n/**\n * A multiplexed SSE hub connection that uses EventSource for server→client streaming\n * and fetch POST requests for client→server subscribe/unsubscribe commands.\n *\n * Protocol:\n * 1. Open EventSource to the SSE hub endpoint.\n * 2. Server sends a {@link HubMessageType.Connected} message with the connection identifier.\n * 3. Client sends POST to subscribe/unsubscribe endpoints using the connection identifier.\n * 4. Server streams {@link HubMessageType.QueryResult} messages tagged with queryId.\n * 5. When EventSource closes, server cleans up all subscriptions for this connection.\n */\nexport class ServerSentEventHubConnection implements IObservableQueryHubConnection {\n private _eventSource?: EventSource;\n private _connectionId?: string;\n private _disconnected = false;\n private _subscriptions: Map<string, ActiveSubscription> = new Map();\n private _pendingSubscriptions: Map<string, ActiveSubscription> = new Map();\n private _lastPongLatency: number = 0;\n private _latencySamples: number[] = [];\n private _connectTimeoutTimer?: ReturnType<typeof setTimeout>;\n private _nextRevision = 0;\n private _supportsSubscriptionRevisions = false;\n private readonly _keepAlive: HubConnectionKeepAlive;\n\n /**\n * Initializes a new instance of {@link ServerSentEventHubConnection}.\n * @param {string} _sseUrl The SSE hub endpoint URL (e.g. `http://localhost:5000/.cratis/queries/sse`).\n * @param {string} _subscribeUrl The subscribe POST endpoint URL.\n * @param {string} _unsubscribeUrl The unsubscribe POST endpoint URL.\n * @param {string} _microservice The microservice name to pass as a query argument.\n * @param {number} keepAliveIntervalMs The keep-alive cadence to assume until the server advertises\n * its own on the {@link HubMessageType.Connected} message (default: 30 000 ms). The connection is\n * considered stale after {@link IDLE_THRESHOLD_FACTOR} times this without any server message.\n * @param {number} _connectTimeoutMs How long to wait for the {@link HubMessageType.Connected}\n * message after the HTTP connection opens before giving up and retrying (default: 15 000 ms).\n * @param {IReconnectPolicy} _policy The reconnect policy to use (default: {@link ReconnectPolicy}).\n */\n constructor(\n private readonly _sseUrl: string,\n private readonly _subscribeUrl: string,\n private readonly _unsubscribeUrl: string,\n private readonly _microservice: string,\n keepAliveIntervalMs: number = 30000,\n private readonly _connectTimeoutMs: number = 15000,\n private readonly _policy: IReconnectPolicy = new ReconnectPolicy(),\n ) {\n // SSE is server→client only: the client cannot send pings. Instead we watch for\n // inactivity — if the server stops sending messages (including its own keep-alive\n // pings) for the entire idle threshold, the connection is stale and we reconnect.\n //\n // The server guarantees a message at least every keep-alive interval, so the threshold\n // only has to absorb network latency, timer jitter and server-side scheduling hiccups.\n // A hard TCP drop surfaces immediately through `onerror`, so this watchdog only needs to\n // catch silent black-holes — that makes a generous tolerance strictly better than a tight\n // one, which would tear down healthy connections.\n //\n // The interval below is only the starting assumption; the server advertises its real\n // cadence on the Connected message and {@link handleConnected} reconfigures from it.\n this._keepAlive = new HubConnectionKeepAlive(\n keepAliveIntervalMs,\n () => {\n if (!this._disconnected && this._subscriptions.size > 0) {\n console.warn(\n 'SSE hub: no messages received; reconnecting',\n this._keepAlive.idleThresholdMs,\n this._sseUrl,\n );\n this.reconnect();\n }\n },\n keepAliveIntervalMs * IDLE_THRESHOLD_FACTOR,\n );\n }\n\n /** @inheritdoc */\n get queryCount(): number {\n return this._subscriptions.size;\n }\n\n /** @inheritdoc */\n get isConnected(): boolean {\n return (\n this._connectionId !== undefined &&\n this._eventSource?.readyState === EventSource.OPEN\n );\n }\n\n /** @inheritdoc */\n get lastPingLatency(): number {\n return this._lastPongLatency;\n }\n\n /** @inheritdoc */\n get averageLatency(): number {\n if (this._latencySamples.length === 0) return 0;\n return (\n this._latencySamples.reduce((a, b) => a + b, 0) / this._latencySamples.length\n );\n }\n\n /** @inheritdoc */\n subscribe(\n queryId: string,\n request: SubscriptionRequest,\n callback: DataReceived<any>,\n ): void {\n const sub: ActiveSubscription = {\n request,\n callback,\n revision: this.getNextRevision(),\n };\n this._subscriptions.set(queryId, sub);\n\n this.ensureConnected();\n\n if (this._connectionId) {\n this.sendSubscribe(queryId, sub);\n } else {\n // Not yet connected, queue for when Connected message arrives.\n this._pendingSubscriptions.set(queryId, sub);\n }\n }\n\n /** @inheritdoc */\n unsubscribe(queryId: string): void {\n const subscription = this._subscriptions.get(queryId);\n this._subscriptions.delete(queryId);\n this._pendingSubscriptions.delete(queryId);\n\n if (this._connectionId && subscription) {\n this.sendUnsubscribe(queryId, subscription.revision);\n }\n\n if (this._subscriptions.size === 0) {\n this.close();\n }\n }\n\n /** @inheritdoc */\n dispose(): void {\n this._disconnected = true;\n this._subscriptions.clear();\n this._pendingSubscriptions.clear();\n this._policy.cancel();\n this._keepAlive.stop();\n this.clearConnectTimeout();\n this.detachAndCloseEventSource();\n this._connectionId = undefined;\n }\n\n private detachAndCloseEventSource(): void {\n const eventSource = this._eventSource;\n if (!eventSource) return;\n\n eventSource.onopen = null;\n eventSource.onmessage = null;\n eventSource.onerror = null;\n eventSource.close();\n\n if (this._eventSource === eventSource) {\n this._eventSource = undefined;\n }\n }\n\n private ensureConnected(): void {\n if (this._disconnected) {\n this._disconnected = false;\n }\n\n if (this._eventSource && this._eventSource.readyState !== EventSource.CLOSED) {\n return;\n }\n\n // An immediate subscription can win while a back-off callback is pending. Cancel that callback before\n // opening, and let openEventSource perform the same live-source guard for already-queued callbacks.\n this._policy.cancel();\n this.openEventSource();\n }\n\n private close(): void {\n this._disconnected = true;\n this._policy.cancel();\n this._keepAlive.stop();\n this.clearConnectTimeout();\n this.detachAndCloseEventSource();\n this._connectionId = undefined;\n }\n\n private openEventSource(): void {\n if (this._eventSource && this._eventSource.readyState !== EventSource.CLOSED) {\n return;\n }\n\n this._policy.cancel();\n let url = this._sseUrl;\n if (this._microservice?.length > 0) {\n const param = `${Globals.microserviceWSQueryArgument}=${encodeURIComponent(this._microservice)}`;\n url += (url.includes('?') ? '&' : '?') + param;\n }\n\n this._connectionId = undefined;\n this._supportsSubscriptionRevisions = false;\n const eventSource = Globals.eventSourceFactory\n ? Globals.eventSourceFactory(url)\n : new EventSource(url);\n this._eventSource = eventSource;\n\n eventSource.onopen = () => {\n if (this._disconnected || this._eventSource !== eventSource) return;\n console.log('SSE hub connection established', url);\n this._policy.reset();\n this._keepAlive.start();\n\n // If the server does not send a Connected message within the timeout, the\n // connection is broken. Close and retry via the reconnect policy.\n this.clearConnectTimeout();\n this._connectTimeoutTimer = setTimeout(() => {\n if (\n !this._disconnected &&\n this._eventSource === eventSource &&\n !this._connectionId\n ) {\n console.warn(\n 'SSE hub: no Connected message within timeout; retrying',\n this._connectTimeoutMs,\n url,\n );\n this.reconnect();\n }\n }, this._connectTimeoutMs);\n };\n\n eventSource.onmessage = (event: MessageEvent) => {\n if (this._disconnected || this._eventSource !== eventSource) return;\n this._keepAlive.recordActivity();\n this.handleMessage(event.data as string);\n };\n\n eventSource.onerror = () => {\n if (this._disconnected || this._eventSource !== eventSource) return;\n console.warn('SSE hub connection error', url);\n this.reconnect();\n };\n }\n\n private reconnect(): void {\n this._keepAlive.stop();\n this.clearConnectTimeout();\n\n // Detach before closing so callbacks already queued by the retired source are inert.\n this.detachAndCloseEventSource();\n this._connectionId = undefined;\n\n // Move all active subscriptions to pending so they re-subscribe when\n // the next Connected message arrives after the managed reconnect.\n for (const [queryId, sub] of this._subscriptions) {\n this._pendingSubscriptions.set(queryId, sub);\n }\n\n if (this._subscriptions.size === 0) return;\n\n this._policy.schedule(() => {\n if (!this._disconnected && this._subscriptions.size > 0) {\n this.ensureConnected();\n }\n }, this._sseUrl);\n }\n\n private clearConnectTimeout(): void {\n if (this._connectTimeoutTimer !== undefined) {\n clearTimeout(this._connectTimeoutTimer);\n this._connectTimeoutTimer = undefined;\n }\n }\n\n private handleMessage(rawData: string): void {\n try {\n const message = JSON.parse(rawData) as HubMessage;\n\n switch (message.type) {\n case HubMessageType.Connected:\n this.handleConnected(message);\n break;\n case HubMessageType.QueryResult:\n this.handleQueryResult(message);\n break;\n case HubMessageType.Ping:\n // Server-sent keep-alive ping — activity already recorded in onmessage.\n break;\n case HubMessageType.Unauthorized:\n if (this.isMessageForCurrentSubscription(message)) {\n console.warn('SSE hub: query unauthorized', message.queryId);\n this.handleUnauthorized(message);\n }\n break;\n case HubMessageType.Error:\n if (this.isMessageForCurrentSubscription(message)) {\n console.error(\n 'SSE hub: query error',\n message.queryId,\n message.payload,\n );\n this.handleError(message);\n }\n break;\n }\n } catch (error) {\n console.error('SSE hub: error parsing message', error);\n }\n }\n\n private handleConnected(message: HubMessage): void {\n const connectionId = message.payload as string;\n const connectionIdChanged = this._connectionId !== connectionId;\n this._connectionId = connectionId;\n this._supportsSubscriptionRevisions =\n message.supportsSubscriptionRevisions === true;\n console.log('SSE hub: connected', this._connectionId);\n\n // Connected message arrived — cancel the connect timeout.\n this.clearConnectTimeout();\n\n this.applyServerKeepAliveInterval(message.keepAliveIntervalMs);\n\n // The active collection is authoritative. A previous connection's subscribe POST may\n // still be in flight, so relying only on pending subscriptions can orphan a query when\n // the server assigns a new connection ID before that POST completes.\n if (connectionIdChanged) {\n for (const [queryId, subscription] of this._subscriptions) {\n this.sendSubscribe(queryId, subscription);\n }\n }\n this._pendingSubscriptions.clear();\n }\n\n /**\n * Align the idle watchdog with the keep-alive cadence the server actually runs on.\n *\n * Without this the client assumes the default interval, so a server configured with a longer\n * interval — or with keep-alive switched off entirely — would look silent and be reconnected\n * on a loop even though it is perfectly healthy.\n * @param {number | undefined} serverIntervalMs The interval advertised by the server, if any.\n */\n private applyServerKeepAliveInterval(serverIntervalMs?: number): void {\n if (serverIntervalMs === undefined) return;\n\n // Keep-alive disabled server-side: silence is expected, so watching for it would guarantee\n // an endless reconnect loop. Hard drops still surface through `onerror`.\n if (serverIntervalMs <= 0) {\n this._keepAlive.stop();\n return;\n }\n\n this._keepAlive.reconfigure(\n serverIntervalMs,\n serverIntervalMs * IDLE_THRESHOLD_FACTOR,\n );\n }\n\n private handleQueryResult(message: HubMessage): void {\n const result = message.payload as QueryResult<any>;\n this.deliverResult(message, result, result?.isValid === false);\n }\n\n private handleError(message: HubMessage): void {\n const result = new QueryResult(\n {\n data: undefined,\n isSuccess: false,\n isReady: true,\n isAuthorized: true,\n isValid: true,\n hasExceptions: true,\n validationResults: [],\n exceptionMessages: [message.payload as string],\n exceptionStackTrace: '',\n paging: { totalItems: 0, totalPages: 0, page: 0, size: 0 },\n },\n Object,\n false,\n );\n this.deliverResult(message, result, false);\n }\n\n private handleUnauthorized(message: HubMessage): void {\n this.deliverResult(message, QueryResult.unauthorized(), true);\n }\n\n private deliverResult(message: HubMessage, result: QueryResult<any>, terminal: boolean): void {\n if (!message.queryId) return;\n\n const sub = this._subscriptions.get(message.queryId);\n if (!sub || !this.isMessageForCurrentSubscription(message)) return;\n\n if (terminal) {\n this._subscriptions.delete(message.queryId);\n this._pendingSubscriptions.delete(message.queryId);\n }\n sub.callback(result);\n }\n\n private sendSubscribe(\n queryId: string,\n subscription: ActiveSubscription,\n attempt: number = 0,\n ): void {\n if (!this._connectionId || this._disconnected) return;\n\n // Capture the connection ID and subscription instance so retries can detect whether\n // either has been replaced while this request is in flight.\n const connectionId = this._connectionId;\n\n const body: {\n connectionId: string;\n queryId: string;\n request: SubscriptionRequest;\n revision?: number;\n } = {\n connectionId,\n queryId,\n request: subscription.request,\n };\n if (this._supportsSubscriptionRevisions) {\n body.revision = subscription.revision;\n }\n\n const customHeaders = Globals.httpHeadersCallback?.() ?? {};\n\n // Maximum number of subscribe retries before falling back to a full SSE reconnect.\n // In a round-robin load-balanced deployment the subscribe POST may land on a different\n // backend instance than the one holding the SSE connection. Retrying gives the load\n // balancer the chance to route a subsequent attempt to the correct instance without\n // tearing down the SSE connection unnecessarily. With N backend instances at most\n // N-1 retries are needed, so 3 retries covers deployments with up to 4 replicas.\n const maxRetries = 3;\n const retryDelayMs = 200;\n\n fetch(this._subscribeUrl, {\n method: 'POST',\n headers: { 'Content-Type': 'application/json', ...customHeaders },\n body: JSON.stringify(body),\n })\n .then((response) => {\n if (!response.ok) {\n if (\n !this.isCurrentSubscription(queryId, subscription, connectionId)\n ) {\n console.warn(\n 'SSE hub: subscribe POST returned a failure for an obsolete connection or subscription; ignoring',\n queryId,\n response.status,\n );\n } else if (attempt < maxRetries) {\n setTimeout(\n () => {\n if (\n this.isCurrentSubscription(\n queryId,\n subscription,\n connectionId,\n )\n ) {\n this.sendSubscribe(\n queryId,\n subscription,\n attempt + 1,\n );\n }\n },\n retryDelayMs * (attempt + 1),\n );\n } else {\n console.warn(\n 'SSE hub: subscribe POST failed after retries; reconnecting',\n queryId,\n response.status,\n attempt + 1,\n );\n this.reconnect();\n }\n }\n })\n .catch((error) => {\n if (!this.isCurrentSubscription(queryId, subscription, connectionId)) {\n console.warn(\n 'SSE hub: subscribe POST failed for an obsolete connection or subscription; ignoring',\n queryId,\n error,\n );\n } else if (attempt < maxRetries) {\n setTimeout(\n () => {\n if (\n this.isCurrentSubscription(\n queryId,\n subscription,\n connectionId,\n )\n ) {\n this.sendSubscribe(queryId, subscription, attempt + 1);\n }\n },\n retryDelayMs * (attempt + 1),\n );\n } else {\n console.error(\n 'SSE hub: subscribe POST failed after retries; reconnecting',\n queryId,\n attempt + 1,\n error,\n );\n this.reconnect();\n }\n });\n }\n\n private isMessageForCurrentSubscription(message: HubMessage): boolean {\n if (!message.queryId) return false;\n\n const subscription = this._subscriptions.get(message.queryId);\n if (!subscription) return false;\n\n if (!this._supportsSubscriptionRevisions) {\n return message.revision === undefined;\n }\n\n return (\n this.isValidRevision(message.revision) &&\n message.revision === subscription.revision\n );\n }\n\n private isCurrentSubscription(\n queryId: string,\n subscription: ActiveSubscription,\n connectionId: string,\n ): boolean {\n return (\n !this._disconnected &&\n this._connectionId === connectionId &&\n this._subscriptions.get(queryId) === subscription\n );\n }\n\n private getNextRevision(): number {\n if (this._nextRevision >= Number.MAX_SAFE_INTEGER) {\n throw new RangeError(\n 'SSE hub subscription revision exhausted the safe integer range',\n );\n }\n\n return ++this._nextRevision;\n }\n\n private isValidRevision(revision: number | undefined): revision is number {\n return revision !== undefined && Number.isSafeInteger(revision) && revision > 0;\n }\n\n private sendUnsubscribe(queryId: string, revision: number): void {\n if (!this._connectionId) return;\n\n const body: {\n connectionId: string;\n queryId: string;\n revision?: number;\n } = {\n connectionId: this._connectionId,\n queryId,\n };\n if (this._supportsSubscriptionRevisions) {\n body.revision = revision;\n }\n\n const customHeaders = Globals.httpHeadersCallback?.() ?? {};\n\n fetch(this._unsubscribeUrl, {\n method: 'POST',\n headers: { 'Content-Type': 'application/json', ...customHeaders },\n body: JSON.stringify(body),\n }).catch((error) => {\n console.error('SSE hub: unsubscribe POST failed', queryId, error);\n });\n }\n}\n"],"names":["IDLE_THRESHOLD_FACTOR","ServerSentEventHubConnection","_eventSource","_connectionId","_disconnected","_subscriptions","Map","_pendingSubscriptions","_lastPongLatency","_latencySamples","_connectTimeoutTimer","_nextRevision","_supportsSubscriptionRevisions","_keepAlive","_subscribeUrl","_unsubscribeUrl","keepAliveIntervalMs","_connectTimeoutMs","_policy","ReconnectPolicy","_sseUrl","_microservice","HubConnectionKeepAlive","size","console","warn","idleThresholdMs","reconnect","queryCount","isConnected","undefined","readyState","EventSource","OPEN","lastPingLatency","averageLatency","length","reduce","a","b","subscribe","queryId","request","callback","sub","revision","getNextRevision","set","ensureConnected","sendSubscribe","unsubscribe","subscription","get","delete","sendUnsubscribe","close","dispose","clear","cancel","stop","clearConnectTimeout","detachAndCloseEventSource","eventSource","onopen","onmessage","onerror","CLOSED","openEventSource","url","param","Globals","microserviceWSQueryArgument","encodeURIComponent","includes","eventSourceFactory","log","reset","start","setTimeout","event","recordActivity","handleMessage","data","schedule","clearTimeout","rawData","message","JSON","parse","type","HubMessageType","Connected","handleConnected","QueryResult","handleQueryResult","Ping","Unauthorized","isMessageForCurrentSubscription","handleUnauthorized","Error","error","payload","handleError","connectionId","connectionIdChanged","supportsSubscriptionRevisions","applyServerKeepAliveInterval","serverIntervalMs","reconfigure","result","deliverResult","isValid","isSuccess","isReady","isAuthorized","hasExceptions","validationResults","exceptionMessages","exceptionStackTrace","paging","totalItems","totalPages","page","Object","unauthorized","terminal","attempt","body","customHeaders","httpHeadersCallback","maxRetries","retryDelayMs","fetch","method","headers","stringify","then","response","ok","isCurrentSubscription","status","catch","isValidRevision","Number","MAX_SAFE_INTEGER","RangeError","isSafeInteger"],"mappings":";;;;;;;;AAAA;AACA;AAuBA;;;;;;AAMC,IACD,MAAMA,qBAAAA,GAAwB,CAAA;AAE9B;;;;;;;;;;AAUC,IACM,MAAMC,4BAAAA,CAAAA;;;;;;;IACDC,YAAAA;IACAC,aAAAA;AACAC,IAAAA,aAAAA,GAAgB,KAAA;AAChBC,IAAAA,cAAAA,GAAkD,IAAIC,GAAAA,EAAAA;AACtDC,IAAAA,qBAAAA,GAAyD,IAAID,GAAAA,EAAAA;AAC7DE,IAAAA,gBAAAA,GAA2B,CAAA;AAC3BC,IAAAA,eAAAA,GAA4B,EAAE;IAC9BC,oBAAAA;AACAC,IAAAA,aAAAA,GAAgB,CAAA;AAChBC,IAAAA,8BAAAA,GAAiC,KAAA;IACxBC,UAAAA;AAEjB;;;;;;;;;;;;QAaA,WAAA,CACI,OAAgC,EACfC,aAAqB,EACrBC,eAAuB,EACxC,aAAsC,EACtCC,mBAAAA,GAA8B,KAAK,EAClBC,iBAAAA,GAA4B,KAAK,EAClD,OAAiBC,GAA4B,IAAIC,+BAAAA,EAAiB,CACpE;aAPmBC,OAAAA,GAAAA,OAAAA;aACAN,aAAAA,GAAAA,aAAAA;aACAC,eAAAA,GAAAA,eAAAA;aACAM,aAAAA,GAAAA,aAAAA;aAEAJ,iBAAAA,GAAAA,iBAAAA;aACAC,OAAAA,GAAAA,OAAAA;;;;;;;;;;;;;AAcjB,QAAA,IAAI,CAACL,UAAU,GAAG,IAAIS,8CAClBN,mBAAAA,EACA,IAAA;YACI,IAAI,CAAC,IAAI,CAACZ,aAAa,IAAI,IAAI,CAACC,cAAc,CAACkB,IAAI,GAAG,CAAA,EAA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Ae,EAAEI,QAAgB,EAAQ;AAC7D,QAAA,IAAI,CAAC,IAAI,CAAC1C,aAAa,EAAE;AAEzB,QAAA,MAAM4H,IAAAA,GAIF;YACAxB,YAAAA,EAAc,IAAI,CAACpG,aAAa;AAChCsC,YAAAA;AACJ,SAAA;QACA,IAAI,IAAI,CAAC7B,8BAA8B,EAAE;AACrCmH,YAAAA,IAAAA,CAAKlF,QAAQ,GAAGA,QAAAA;AACpB,QAAA;AAEA,QAAA,MAAMmF,aAAAA,GAAgB1D,eAAAA,CAAQ2D,mBAAmB,IAAA,IAAQ,EAAC;QAE1DG,KAAAA,CAAM,IAAI,CAACrH,eAAe,EAAE;YACxBsH,MAAAA,EAAQ,MAAA;YACRC,OAAAA,EAAS;gBAAE,cAAA,EAAgB,kBAAA;AAAoB,gBAAA,GAAGN;AAAc,aAAA;YAChED,IAAAA,EAAMxC,IAAAA,CAAKgD,SAAS,CAACR,IAAAA;SACzB,CAAA,CAAGc,KAAK,CAAC,CAACzC,KAAAA,GAAAA;YACN5E,OAAAA,CAAQ4E,KAAK,CAAC,kCAAA,EAAoC3D,OAAAA,EAAS2D,KAAAA,CAAAA;AAC/D,QAAA,CAAA,CAAA;AACJ,IAAA;AACJ;;"}
|
|
1
|
+
{"version":3,"file":"ServerSentEventHubConnection.js","sources":["../../../queries/ServerSentEventHubConnection.ts"],"sourcesContent":["// Copyright (c) Cratis. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nimport { Globals } from '../Globals.js';\nimport type { IObservableQueryHubConnection } from './IObservableQueryHubConnection.js';\nimport type { DataReceived } from './ObservableQueryConnection.js';\nimport { HubConnectionKeepAlive } from './HubConnectionKeepAlive.js';\nimport type { IReconnectPolicy } from './IReconnectPolicy.js';\nimport { ReconnectPolicy } from './ReconnectPolicy.js';\nimport { QueryResult } from './QueryResult.js';\nimport {\n type HubMessage,\n HubMessageType,\n type SubscriptionRequest,\n} from './WebSocketHubConnection.js';\n\n/* eslint-disable @typescript-eslint/no-explicit-any */\n\ninterface ActiveSubscription {\n request: SubscriptionRequest;\n callback: DataReceived<any>;\n revision: number;\n}\n\n/**\n * How many keep-alive intervals of silence are tolerated before the connection is considered dead.\n *\n * The server guarantees a message every interval, so this is pure slack for latency and jitter.\n * It must stay above 1 — a threshold at or below the server's own cadence makes the client and\n * server timers race, and the client tears down connections the server considers healthy.\n */\nconst IDLE_THRESHOLD_FACTOR = 2;\n\n/** Maximum number of subscribe retries before falling back to a full SSE reconnect. */\nconst SUBSCRIBE_MAX_RETRIES = 3;\n\n/** Base delay between subscribe retries; multiplied by the attempt number. */\nconst SUBSCRIBE_RETRY_DELAY_MS = 200;\n\ninterface SubscribeTarget {\n queryId: string;\n subscription: ActiveSubscription;\n connectionId: string;\n attempt: number;\n}\n\n/**\n * A multiplexed SSE hub connection that uses EventSource for server→client streaming\n * and fetch POST requests for client→server subscribe/unsubscribe commands.\n *\n * Protocol:\n * 1. Open EventSource to the SSE hub endpoint.\n * 2. Server sends a {@link HubMessageType.Connected} message with the connection identifier.\n * 3. Client sends POST to subscribe/unsubscribe endpoints using the connection identifier.\n * 4. Server streams {@link HubMessageType.QueryResult} messages tagged with queryId.\n * 5. When EventSource closes, server cleans up all subscriptions for this connection.\n */\nexport class ServerSentEventHubConnection implements IObservableQueryHubConnection {\n private _eventSource?: EventSource;\n private _connectionId?: string;\n private _disconnected = false;\n private _subscriptions: Map<string, ActiveSubscription> = new Map();\n private _pendingSubscriptions: Map<string, ActiveSubscription> = new Map();\n private _lastPongLatency: number = 0;\n private _latencySamples: number[] = [];\n private _connectTimeoutTimer?: ReturnType<typeof setTimeout>;\n private _nextRevision = 0;\n private _supportsSubscriptionRevisions = false;\n private readonly _keepAlive: HubConnectionKeepAlive;\n\n /**\n * Initializes a new instance of {@link ServerSentEventHubConnection}.\n * @param {string} _sseUrl The SSE hub endpoint URL (e.g. `http://localhost:5000/.cratis/queries/sse`).\n * @param {string} _subscribeUrl The subscribe POST endpoint URL.\n * @param {string} _unsubscribeUrl The unsubscribe POST endpoint URL.\n * @param {string} _microservice The microservice name to pass as a query argument.\n * @param {number} keepAliveIntervalMs The keep-alive cadence to assume until the server advertises\n * its own on the {@link HubMessageType.Connected} message (default: 30 000 ms). The connection is\n * considered stale after {@link IDLE_THRESHOLD_FACTOR} times this without any server message.\n * @param {number} _connectTimeoutMs How long to wait for the {@link HubMessageType.Connected}\n * message after the HTTP connection opens before giving up and retrying (default: 15 000 ms).\n * @param {IReconnectPolicy} _policy The reconnect policy to use (default: {@link ReconnectPolicy}).\n */\n constructor(\n private readonly _sseUrl: string,\n private readonly _subscribeUrl: string,\n private readonly _unsubscribeUrl: string,\n private readonly _microservice: string,\n keepAliveIntervalMs: number = 30000,\n private readonly _connectTimeoutMs: number = 15000,\n private readonly _policy: IReconnectPolicy = new ReconnectPolicy(),\n ) {\n // SSE is server→client only: the client cannot send pings. Instead we watch for\n // inactivity — if the server stops sending messages (including its own keep-alive\n // pings) for the entire idle threshold, the connection is stale and we reconnect.\n //\n // The server guarantees a message at least every keep-alive interval, so the threshold\n // only has to absorb network latency, timer jitter and server-side scheduling hiccups.\n // A hard TCP drop surfaces immediately through `onerror`, so this watchdog only needs to\n // catch silent black-holes — that makes a generous tolerance strictly better than a tight\n // one, which would tear down healthy connections.\n //\n // The interval below is only the starting assumption; the server advertises its real\n // cadence on the Connected message and {@link handleConnected} reconfigures from it.\n this._keepAlive = new HubConnectionKeepAlive(\n keepAliveIntervalMs,\n () => {\n if (!this._disconnected && this._subscriptions.size > 0) {\n console.warn(\n 'SSE hub: no messages received; reconnecting',\n this._keepAlive.idleThresholdMs,\n this._sseUrl,\n );\n this.reconnect();\n }\n },\n keepAliveIntervalMs * IDLE_THRESHOLD_FACTOR,\n );\n }\n\n /** @inheritdoc */\n get queryCount(): number {\n return this._subscriptions.size;\n }\n\n /** @inheritdoc */\n get isConnected(): boolean {\n return (\n this._connectionId !== undefined &&\n this._eventSource?.readyState === EventSource.OPEN\n );\n }\n\n /** @inheritdoc */\n get lastPingLatency(): number {\n return this._lastPongLatency;\n }\n\n /** @inheritdoc */\n get averageLatency(): number {\n if (this._latencySamples.length === 0) return 0;\n return (\n this._latencySamples.reduce((a, b) => a + b, 0) / this._latencySamples.length\n );\n }\n\n /** @inheritdoc */\n subscribe(\n queryId: string,\n request: SubscriptionRequest,\n callback: DataReceived<any>,\n ): void {\n const sub: ActiveSubscription = {\n request,\n callback,\n revision: this.getNextRevision(),\n };\n this._subscriptions.set(queryId, sub);\n\n this.ensureConnected();\n\n if (this._connectionId) {\n this.sendSubscribe(queryId, sub);\n } else {\n // Not yet connected, queue for when Connected message arrives.\n this._pendingSubscriptions.set(queryId, sub);\n }\n }\n\n /** @inheritdoc */\n unsubscribe(queryId: string): void {\n const subscription = this._subscriptions.get(queryId);\n this._subscriptions.delete(queryId);\n this._pendingSubscriptions.delete(queryId);\n\n if (this._connectionId && subscription) {\n this.sendUnsubscribe(queryId, subscription.revision);\n }\n\n if (this._subscriptions.size === 0) {\n this.close();\n }\n }\n\n /** @inheritdoc */\n dispose(): void {\n this._disconnected = true;\n this._subscriptions.clear();\n this._pendingSubscriptions.clear();\n this._policy.cancel();\n this._keepAlive.stop();\n this.clearConnectTimeout();\n this.detachAndCloseEventSource();\n this._connectionId = undefined;\n }\n\n private detachAndCloseEventSource(): void {\n const eventSource = this._eventSource;\n if (!eventSource) return;\n\n eventSource.onopen = null;\n eventSource.onmessage = null;\n eventSource.onerror = null;\n eventSource.close();\n\n if (this._eventSource === eventSource) {\n this._eventSource = undefined;\n }\n }\n\n private ensureConnected(): void {\n if (this._disconnected) {\n this._disconnected = false;\n }\n\n if (this._eventSource && this._eventSource.readyState !== EventSource.CLOSED) {\n return;\n }\n\n // An immediate subscription can win while a back-off callback is pending. Cancel that callback before\n // opening, and let openEventSource perform the same live-source guard for already-queued callbacks.\n this._policy.cancel();\n this.openEventSource();\n }\n\n private close(): void {\n this._disconnected = true;\n this._policy.cancel();\n this._keepAlive.stop();\n this.clearConnectTimeout();\n this.detachAndCloseEventSource();\n this._connectionId = undefined;\n }\n\n private openEventSource(): void {\n if (this._eventSource && this._eventSource.readyState !== EventSource.CLOSED) {\n return;\n }\n\n this._policy.cancel();\n const url = this.buildEventSourceUrl();\n\n this._connectionId = undefined;\n this._supportsSubscriptionRevisions = false;\n const eventSource = Globals.eventSourceFactory\n ? Globals.eventSourceFactory(url)\n : new EventSource(url);\n this._eventSource = eventSource;\n\n eventSource.onopen = () => {\n if (!this.isActiveSource(eventSource)) return;\n console.log('SSE hub connection established', url);\n this._policy.reset();\n this._keepAlive.start();\n this.startConnectTimeout(eventSource, url);\n };\n\n eventSource.onmessage = (event: MessageEvent) => {\n if (!this.isActiveSource(eventSource)) return;\n this._keepAlive.recordActivity();\n this.handleMessage(event.data as string);\n };\n\n eventSource.onerror = () => {\n if (!this.isActiveSource(eventSource)) return;\n console.warn('SSE hub connection error', url);\n this.reconnect();\n };\n }\n\n private buildEventSourceUrl(): string {\n let url = this._sseUrl;\n if (this._microservice?.length > 0) {\n const param = `${Globals.microserviceWSQueryArgument}=${encodeURIComponent(this._microservice)}`;\n url += (url.includes('?') ? '&' : '?') + param;\n }\n return url;\n }\n\n private isActiveSource(eventSource: EventSource): boolean {\n return !this._disconnected && this._eventSource === eventSource;\n }\n\n /**\n * If the server does not send a Connected message within the timeout, the\n * connection is broken. Close and retry via the reconnect policy.\n * @param {EventSource} eventSource The source the timeout guards.\n * @param {string} url The URL used for diagnostics.\n */\n private startConnectTimeout(eventSource: EventSource, url: string): void {\n this.clearConnectTimeout();\n this._connectTimeoutTimer = setTimeout(() => {\n if (this.isActiveSource(eventSource) && !this._connectionId) {\n console.warn(\n 'SSE hub: no Connected message within timeout; retrying',\n this._connectTimeoutMs,\n url,\n );\n this.reconnect();\n }\n }, this._connectTimeoutMs);\n }\n\n private reconnect(): void {\n this._keepAlive.stop();\n this.clearConnectTimeout();\n\n // Detach before closing so callbacks already queued by the retired source are inert.\n this.detachAndCloseEventSource();\n this._connectionId = undefined;\n\n // Move all active subscriptions to pending so they re-subscribe when\n // the next Connected message arrives after the managed reconnect.\n for (const [queryId, sub] of this._subscriptions) {\n this._pendingSubscriptions.set(queryId, sub);\n }\n\n if (this._subscriptions.size === 0) return;\n\n this._policy.schedule(() => {\n if (!this._disconnected && this._subscriptions.size > 0) {\n this.ensureConnected();\n }\n }, this._sseUrl);\n }\n\n private clearConnectTimeout(): void {\n if (this._connectTimeoutTimer !== undefined) {\n clearTimeout(this._connectTimeoutTimer);\n this._connectTimeoutTimer = undefined;\n }\n }\n\n private handleMessage(rawData: string): void {\n try {\n const message = JSON.parse(rawData) as HubMessage;\n\n switch (message.type) {\n case HubMessageType.Connected:\n this.handleConnected(message);\n break;\n case HubMessageType.QueryResult:\n this.handleQueryResult(message);\n break;\n case HubMessageType.Ping:\n // Server-sent keep-alive ping — activity already recorded in onmessage.\n break;\n case HubMessageType.Unauthorized:\n this.handleUnauthorizedMessage(message);\n break;\n case HubMessageType.Error:\n this.handleErrorMessage(message);\n break;\n }\n } catch (error) {\n console.error('SSE hub: error parsing message', error);\n }\n }\n\n private handleUnauthorizedMessage(message: HubMessage): void {\n if (!this.isMessageForCurrentSubscription(message)) return;\n console.warn('SSE hub: query unauthorized', message.queryId);\n this.handleUnauthorized(message);\n }\n\n private handleErrorMessage(message: HubMessage): void {\n if (!this.isMessageForCurrentSubscription(message)) return;\n console.error('SSE hub: query error', message.queryId, message.payload);\n this.handleError(message);\n }\n\n private handleConnected(message: HubMessage): void {\n const connectionId = message.payload as string;\n const connectionIdChanged = this._connectionId !== connectionId;\n this._connectionId = connectionId;\n this._supportsSubscriptionRevisions =\n message.supportsSubscriptionRevisions === true;\n console.log('SSE hub: connected', this._connectionId);\n\n // Connected message arrived — cancel the connect timeout.\n this.clearConnectTimeout();\n\n this.applyServerKeepAliveInterval(message.keepAliveIntervalMs);\n\n // The active collection is authoritative. A previous connection's subscribe POST may\n // still be in flight, so relying only on pending subscriptions can orphan a query when\n // the server assigns a new connection ID before that POST completes.\n if (connectionIdChanged) {\n for (const [queryId, subscription] of this._subscriptions) {\n this.sendSubscribe(queryId, subscription);\n }\n }\n this._pendingSubscriptions.clear();\n }\n\n /**\n * Align the idle watchdog with the keep-alive cadence the server actually runs on.\n *\n * Without this the client assumes the default interval, so a server configured with a longer\n * interval — or with keep-alive switched off entirely — would look silent and be reconnected\n * on a loop even though it is perfectly healthy.\n * @param {number | undefined} serverIntervalMs The interval advertised by the server, if any.\n */\n private applyServerKeepAliveInterval(serverIntervalMs?: number): void {\n if (serverIntervalMs === undefined) return;\n\n // Keep-alive disabled server-side: silence is expected, so watching for it would guarantee\n // an endless reconnect loop. Hard drops still surface through `onerror`.\n if (serverIntervalMs <= 0) {\n this._keepAlive.stop();\n return;\n }\n\n this._keepAlive.reconfigure(\n serverIntervalMs,\n serverIntervalMs * IDLE_THRESHOLD_FACTOR,\n );\n }\n\n private handleQueryResult(message: HubMessage): void {\n const result = message.payload as QueryResult<any>;\n this.deliverResult(message, result, result?.isValid === false);\n }\n\n private handleError(message: HubMessage): void {\n const result = new QueryResult(\n {\n data: undefined,\n isSuccess: false,\n isReady: true,\n isAuthorized: true,\n isValid: true,\n hasExceptions: true,\n validationResults: [],\n exceptionMessages: [message.payload as string],\n exceptionStackTrace: '',\n paging: { totalItems: 0, totalPages: 0, page: 0, size: 0 },\n },\n Object,\n false,\n );\n this.deliverResult(message, result, false);\n }\n\n private handleUnauthorized(message: HubMessage): void {\n this.deliverResult(message, QueryResult.unauthorized(), true);\n }\n\n private deliverResult(message: HubMessage, result: QueryResult<any>, terminal: boolean): void {\n if (!message.queryId) return;\n\n const sub = this._subscriptions.get(message.queryId);\n if (!sub || !this.isMessageForCurrentSubscription(message)) return;\n\n if (terminal) {\n this._subscriptions.delete(message.queryId);\n this._pendingSubscriptions.delete(message.queryId);\n }\n sub.callback(result);\n }\n\n private sendSubscribe(\n queryId: string,\n subscription: ActiveSubscription,\n attempt: number = 0,\n ): void {\n if (!this._connectionId || this._disconnected) return;\n\n // Capture the connection ID and subscription instance so retries can detect whether\n // either has been replaced while this request is in flight.\n const connectionId = this._connectionId;\n\n const body: {\n connectionId: string;\n queryId: string;\n request: SubscriptionRequest;\n revision?: number;\n } = {\n connectionId,\n queryId,\n request: subscription.request,\n };\n if (this._supportsSubscriptionRevisions) {\n body.revision = subscription.revision;\n }\n\n const customHeaders = Globals.httpHeadersCallback?.() ?? {};\n const target: SubscribeTarget = { queryId, subscription, connectionId, attempt };\n\n fetch(this._subscribeUrl, {\n method: 'POST',\n headers: { 'Content-Type': 'application/json', ...customHeaders },\n body: JSON.stringify(body),\n })\n .then((response) => {\n if (!response.ok) {\n this.handleSubscribeFailure(target, console.warn, response.status);\n }\n })\n .catch((error) => {\n this.handleSubscribeFailure(target, console.error, undefined, error);\n });\n }\n\n /**\n * Decide what to do after a failed subscribe POST: ignore it when obsolete, retry with back-off,\n * or fall back to a full reconnect once the retries are exhausted.\n *\n * The retry limit exists because in a round-robin load-balanced deployment the subscribe POST may\n * land on a different backend instance than the one holding the SSE connection. Retrying gives\n * the load balancer the chance to route a subsequent attempt to the correct instance without\n * tearing down the SSE connection unnecessarily. With N backend instances at most N-1 retries\n * are needed, so 3 retries covers deployments with up to 4 replicas.\n * @param {SubscribeTarget} target The subscribe attempt that failed.\n * @param {Function} exhaustedLog The logger used when the retries are exhausted.\n * @param {number | undefined} status The HTTP status, when the server responded.\n * @param {unknown} error The thrown error, when the request itself failed.\n */\n private handleSubscribeFailure(\n target: SubscribeTarget,\n exhaustedLog: (...data: unknown[]) => void,\n status?: number,\n error?: unknown,\n ): void {\n const { queryId, subscription, connectionId, attempt } = target;\n const detail = error === undefined ? [status] : [error];\n\n if (!this.isCurrentSubscription(queryId, subscription, connectionId)) {\n const reason = error === undefined ? 'returned a failure' : 'failed';\n console.warn(\n `SSE hub: subscribe POST ${reason} for an obsolete connection or subscription; ignoring`,\n queryId,\n ...detail,\n );\n } else if (attempt < SUBSCRIBE_MAX_RETRIES) {\n this.scheduleSubscribeRetry(target);\n } else {\n const tail = error === undefined ? [status, attempt + 1] : [attempt + 1, error];\n exhaustedLog(\n 'SSE hub: subscribe POST failed after retries; reconnecting',\n queryId,\n ...tail,\n );\n this.reconnect();\n }\n }\n\n private scheduleSubscribeRetry(target: SubscribeTarget): void {\n const { queryId, subscription, connectionId, attempt } = target;\n setTimeout(() => {\n if (this.isCurrentSubscription(queryId, subscription, connectionId)) {\n this.sendSubscribe(queryId, subscription, attempt + 1);\n }\n }, SUBSCRIBE_RETRY_DELAY_MS * (attempt + 1));\n }\n\n private isMessageForCurrentSubscription(message: HubMessage): boolean {\n if (!message.queryId) return false;\n\n const subscription = this._subscriptions.get(message.queryId);\n if (!subscription) return false;\n\n if (!this._supportsSubscriptionRevisions) {\n return message.revision === undefined;\n }\n\n return (\n this.isValidRevision(message.revision) &&\n message.revision === subscription.revision\n );\n }\n\n private isCurrentSubscription(\n queryId: string,\n subscription: ActiveSubscription,\n connectionId: string,\n ): boolean {\n return (\n !this._disconnected &&\n this._connectionId === connectionId &&\n this._subscriptions.get(queryId) === subscription\n );\n }\n\n private getNextRevision(): number {\n if (this._nextRevision >= Number.MAX_SAFE_INTEGER) {\n throw new RangeError(\n 'SSE hub subscription revision exhausted the safe integer range',\n );\n }\n\n return ++this._nextRevision;\n }\n\n private isValidRevision(revision: number | undefined): revision is number {\n return revision !== undefined && Number.isSafeInteger(revision) && revision > 0;\n }\n\n private sendUnsubscribe(queryId: string, revision: number): void {\n if (!this._connectionId) return;\n\n const body: {\n connectionId: string;\n queryId: string;\n revision?: number;\n } = {\n connectionId: this._connectionId,\n queryId,\n };\n if (this._supportsSubscriptionRevisions) {\n body.revision = revision;\n }\n\n const customHeaders = Globals.httpHeadersCallback?.() ?? {};\n\n fetch(this._unsubscribeUrl, {\n method: 'POST',\n headers: { 'Content-Type': 'application/json', ...customHeaders },\n body: JSON.stringify(body),\n }).catch((error) => {\n console.error('SSE hub: unsubscribe POST failed', queryId, error);\n });\n }\n}\n"],"names":["IDLE_THRESHOLD_FACTOR","SUBSCRIBE_MAX_RETRIES","SUBSCRIBE_RETRY_DELAY_MS","ServerSentEventHubConnection","_eventSource","_connectionId","_disconnected","_subscriptions","Map","_pendingSubscriptions","_lastPongLatency","_latencySamples","_connectTimeoutTimer","_nextRevision","_supportsSubscriptionRevisions","_keepAlive","_subscribeUrl","_unsubscribeUrl","keepAliveIntervalMs","_connectTimeoutMs","_policy","ReconnectPolicy","_sseUrl","_microservice","HubConnectionKeepAlive","size","console","warn","idleThresholdMs","reconnect","queryCount","isConnected","undefined","readyState","EventSource","OPEN","lastPingLatency","averageLatency","length","reduce","a","b","subscribe","queryId","request","callback","sub","revision","getNextRevision","set","ensureConnected","sendSubscribe","unsubscribe","subscription","get","delete","sendUnsubscribe","close","dispose","clear","cancel","stop","clearConnectTimeout","detachAndCloseEventSource","eventSource","onopen","onmessage","onerror","CLOSED","openEventSource","url","buildEventSourceUrl","Globals","eventSourceFactory","isActiveSource","log","reset","start","startConnectTimeout","event","recordActivity","handleMessage","data","param","microserviceWSQueryArgument","encodeURIComponent","includes","setTimeout","schedule","clearTimeout","rawData","message","JSON","parse","type","HubMessageType","Connected","handleConnected","QueryResult","handleQueryResult","Ping","Unauthorized","handleUnauthorizedMessage","Error","handleErrorMessage","error","isMessageForCurrentSubscription","handleUnauthorized","payload","handleError","connectionId","connectionIdChanged","supportsSubscriptionRevisions","applyServerKeepAliveInterval","serverIntervalMs","reconfigure","result","deliverResult","isValid","isSuccess","isReady","isAuthorized","hasExceptions","validationResults","exceptionMessages","exceptionStackTrace","paging","totalItems","totalPages","page","Object","unauthorized","terminal","attempt","body","customHeaders","httpHeadersCallback","target","fetch","method","headers","stringify","then","response","ok","handleSubscribeFailure","status","catch","exhaustedLog","detail","isCurrentSubscription","reason","scheduleSubscribeRetry","tail","isValidRevision","Number","MAX_SAFE_INTEGER","RangeError","isSafeInteger"],"mappings":";;;;;;;;AAAA;AACA;AAuBA;;;;;;AAMC,IACD,MAAMA,qBAAAA,GAAwB,CAAA;AAE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AA;YACN/E,OAAAA,CAAQ+E,KAAK,CAAC,kCAAA,EAAoC9D,OAAAA,EAAS8D,KAAAA,CAAAA;AAC/D,QAAA,CAAA,CAAA;AACJ,IAAA;AACJ;;"}
|
|
@@ -56,6 +56,12 @@ export declare class WebSocketHubConnection {
|
|
|
56
56
|
private ensureConnected;
|
|
57
57
|
private close;
|
|
58
58
|
private openSocket;
|
|
59
|
+
private buildSocketUrl;
|
|
60
|
+
private isSocketLive;
|
|
61
|
+
private isActiveSocket;
|
|
62
|
+
private isOpenAndReleased;
|
|
63
|
+
private handleSocketOpened;
|
|
64
|
+
private handleSocketClosed;
|
|
59
65
|
private cancelPendingReconnect;
|
|
60
66
|
private detachAndCloseSocket;
|
|
61
67
|
private resetSubscriptionRelease;
|