@cratis/arc 20.60.0 → 20.60.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cjs/queries/HubConnectionKeepAlive.js +24 -4
- package/dist/cjs/queries/HubConnectionKeepAlive.js.map +1 -1
- package/dist/cjs/queries/NullObservableQueryConnection.js +7 -2
- package/dist/cjs/queries/NullObservableQueryConnection.js.map +1 -1
- package/dist/cjs/queries/ObservableQueryFor.js +11 -1
- package/dist/cjs/queries/ObservableQueryFor.js.map +1 -1
- package/dist/cjs/queries/QueryFor.js +1 -21
- package/dist/cjs/queries/QueryFor.js.map +1 -1
- package/dist/cjs/queries/QueryInstanceCache.js +35 -12
- package/dist/cjs/queries/QueryInstanceCache.js.map +1 -1
- package/dist/cjs/queries/QueryResult.js +30 -0
- package/dist/cjs/queries/QueryResult.js.map +1 -1
- package/dist/cjs/queries/ServerSentEventHubConnection.js +38 -10
- package/dist/cjs/queries/ServerSentEventHubConnection.js.map +1 -1
- package/dist/cjs/queries/WebSocketHubConnection.js.map +1 -1
- package/dist/cjs/queries/index.js +2 -0
- package/dist/cjs/queries/index.js.map +1 -1
- package/dist/cjs/queries/reconcileQueryData.js +84 -0
- package/dist/cjs/queries/reconcileQueryData.js.map +1 -0
- package/dist/esm/queries/HubConnectionKeepAlive.d.ts +5 -3
- package/dist/esm/queries/HubConnectionKeepAlive.d.ts.map +1 -1
- package/dist/esm/queries/HubConnectionKeepAlive.js +24 -4
- package/dist/esm/queries/HubConnectionKeepAlive.js.map +1 -1
- package/dist/esm/queries/NullObservableQueryConnection.d.ts +3 -1
- package/dist/esm/queries/NullObservableQueryConnection.d.ts.map +1 -1
- package/dist/esm/queries/NullObservableQueryConnection.js +7 -2
- package/dist/esm/queries/NullObservableQueryConnection.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 +11 -1
- package/dist/esm/queries/ObservableQueryFor.js.map +1 -1
- package/dist/esm/queries/QueryFor.d.ts.map +1 -1
- package/dist/esm/queries/QueryFor.js +1 -21
- package/dist/esm/queries/QueryFor.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 +35 -12
- package/dist/esm/queries/QueryInstanceCache.js.map +1 -1
- package/dist/esm/queries/QueryResult.d.ts +5 -0
- package/dist/esm/queries/QueryResult.d.ts.map +1 -1
- package/dist/esm/queries/QueryResult.js +30 -0
- package/dist/esm/queries/QueryResult.js.map +1 -1
- package/dist/esm/queries/ServerSentEventHubConnection.d.ts +1 -0
- package/dist/esm/queries/ServerSentEventHubConnection.d.ts.map +1 -1
- package/dist/esm/queries/ServerSentEventHubConnection.js +38 -10
- package/dist/esm/queries/ServerSentEventHubConnection.js.map +1 -1
- package/dist/esm/queries/WebSocketHubConnection.d.ts +1 -0
- package/dist/esm/queries/WebSocketHubConnection.d.ts.map +1 -1
- package/dist/esm/queries/WebSocketHubConnection.js.map +1 -1
- package/dist/esm/queries/for_HubConnectionKeepAlive/when_reconfiguring/while_running.d.ts +2 -0
- package/dist/esm/queries/for_HubConnectionKeepAlive/when_reconfiguring/while_running.d.ts.map +1 -0
- package/dist/esm/queries/for_HubConnectionKeepAlive/when_reconfiguring/while_running.js +37 -0
- package/dist/esm/queries/for_HubConnectionKeepAlive/when_reconfiguring/while_running.js.map +1 -0
- package/dist/esm/queries/for_HubConnectionKeepAlive/when_reconfiguring/while_stopped.d.ts +2 -0
- package/dist/esm/queries/for_HubConnectionKeepAlive/when_reconfiguring/while_stopped.d.ts.map +1 -0
- package/dist/esm/queries/for_HubConnectionKeepAlive/when_reconfiguring/while_stopped.js +22 -0
- package/dist/esm/queries/for_HubConnectionKeepAlive/when_reconfiguring/while_stopped.js.map +1 -0
- package/dist/esm/queries/for_ObservableQueryFor/given/an_observable_query_with_validator.d.ts +23 -0
- package/dist/esm/queries/for_ObservableQueryFor/given/an_observable_query_with_validator.d.ts.map +1 -0
- package/dist/esm/queries/for_ObservableQueryFor/given/an_observable_query_with_validator.js +28 -0
- package/dist/esm/queries/for_ObservableQueryFor/given/an_observable_query_with_validator.js.map +1 -0
- package/dist/esm/queries/for_ObservableQueryFor/when_performing/with_client_validation_failing.d.ts +2 -0
- package/dist/esm/queries/for_ObservableQueryFor/when_performing/with_client_validation_failing.d.ts.map +1 -0
- package/dist/esm/queries/for_ObservableQueryFor/when_performing/with_client_validation_failing.js +21 -0
- package/dist/esm/queries/for_ObservableQueryFor/when_performing/with_client_validation_failing.js.map +1 -0
- package/dist/esm/queries/for_ObservableQueryFor/when_subscribing/with_client_validation_failing.d.ts +2 -0
- package/dist/esm/queries/for_ObservableQueryFor/when_subscribing/with_client_validation_failing.d.ts.map +1 -0
- package/dist/esm/queries/for_ObservableQueryFor/when_subscribing/with_client_validation_failing.js +18 -0
- package/dist/esm/queries/for_ObservableQueryFor/when_subscribing/with_client_validation_failing.js.map +1 -0
- package/dist/esm/queries/for_ObservableQueryFor/when_subscribing/with_client_validation_passing.d.ts +2 -0
- package/dist/esm/queries/for_ObservableQueryFor/when_subscribing/with_client_validation_passing.d.ts.map +1 -0
- package/dist/esm/queries/for_ObservableQueryFor/when_subscribing/with_client_validation_passing.js +21 -0
- package/dist/esm/queries/for_ObservableQueryFor/when_subscribing/with_client_validation_passing.js.map +1 -0
- package/dist/esm/queries/for_QueryInstanceCache/when_setting_last_result/with_a_partially_changed_result.d.ts +2 -0
- package/dist/esm/queries/for_QueryInstanceCache/when_setting_last_result/with_a_partially_changed_result.d.ts.map +1 -0
- package/dist/esm/queries/for_QueryInstanceCache/when_setting_last_result/with_a_partially_changed_result.js +32 -0
- package/dist/esm/queries/for_QueryInstanceCache/when_setting_last_result/with_a_partially_changed_result.js.map +1 -0
- package/dist/esm/queries/for_QueryInstanceCache/when_setting_last_result/with_a_re_delivered_identical_result.d.ts +2 -0
- package/dist/esm/queries/for_QueryInstanceCache/when_setting_last_result/with_a_re_delivered_identical_result.d.ts.map +1 -0
- package/dist/esm/queries/for_QueryInstanceCache/when_setting_last_result/with_a_re_delivered_identical_result.js +22 -0
- package/dist/esm/queries/for_QueryInstanceCache/when_setting_last_result/with_a_re_delivered_identical_result.js.map +1 -0
- package/dist/esm/queries/for_ServerSentEventHubConnection/when_server_advertises_a_longer_keep_alive_interval/does_not_reconnect_at_the_assumed_threshold.d.ts +2 -0
- package/dist/esm/queries/for_ServerSentEventHubConnection/when_server_advertises_a_longer_keep_alive_interval/does_not_reconnect_at_the_assumed_threshold.d.ts.map +1 -0
- package/dist/esm/queries/for_ServerSentEventHubConnection/when_server_advertises_a_longer_keep_alive_interval/does_not_reconnect_at_the_assumed_threshold.js +39 -0
- package/dist/esm/queries/for_ServerSentEventHubConnection/when_server_advertises_a_longer_keep_alive_interval/does_not_reconnect_at_the_assumed_threshold.js.map +1 -0
- package/dist/esm/queries/for_ServerSentEventHubConnection/when_server_reports_keep_alive_disabled/never_reconnects_from_idle.d.ts +2 -0
- package/dist/esm/queries/for_ServerSentEventHubConnection/when_server_reports_keep_alive_disabled/never_reconnects_from_idle.d.ts.map +1 -0
- package/dist/esm/queries/for_ServerSentEventHubConnection/when_server_reports_keep_alive_disabled/never_reconnects_from_idle.js +28 -0
- package/dist/esm/queries/for_ServerSentEventHubConnection/when_server_reports_keep_alive_disabled/never_reconnects_from_idle.js.map +1 -0
- package/dist/esm/queries/for_reconcileQueryData/when_items_are_added_or_removed/reuses_the_surviving_items.d.ts +2 -0
- package/dist/esm/queries/for_reconcileQueryData/when_items_are_added_or_removed/reuses_the_surviving_items.d.ts.map +1 -0
- package/dist/esm/queries/for_reconcileQueryData/when_items_are_added_or_removed/reuses_the_surviving_items.js +36 -0
- package/dist/esm/queries/for_reconcileQueryData/when_items_are_added_or_removed/reuses_the_surviving_items.js.map +1 -0
- package/dist/esm/queries/for_reconcileQueryData/when_one_item_changed/only_the_changed_item_gets_a_new_reference.d.ts +2 -0
- package/dist/esm/queries/for_reconcileQueryData/when_one_item_changed/only_the_changed_item_gets_a_new_reference.d.ts.map +1 -0
- package/dist/esm/queries/for_reconcileQueryData/when_one_item_changed/only_the_changed_item_gets_a_new_reference.js +20 -0
- package/dist/esm/queries/for_reconcileQueryData/when_one_item_changed/only_the_changed_item_gets_a_new_reference.js.map +1 -0
- package/dist/esm/queries/for_reconcileQueryData/when_reconciling_an_unchanged_collection/preserves_all_references.d.ts +2 -0
- package/dist/esm/queries/for_reconcileQueryData/when_reconciling_an_unchanged_collection/preserves_all_references.d.ts.map +1 -0
- package/dist/esm/queries/for_reconcileQueryData/when_reconciling_an_unchanged_collection/preserves_all_references.js +15 -0
- package/dist/esm/queries/for_reconcileQueryData/when_reconciling_an_unchanged_collection/preserves_all_references.js.map +1 -0
- package/dist/esm/queries/for_reconcileQueryData/when_reconciling_non_collection_payloads/compares_by_value.d.ts +2 -0
- package/dist/esm/queries/for_reconcileQueryData/when_reconciling_non_collection_payloads/compares_by_value.d.ts.map +1 -0
- package/dist/esm/queries/for_reconcileQueryData/when_reconciling_non_collection_payloads/compares_by_value.js +20 -0
- package/dist/esm/queries/for_reconcileQueryData/when_reconciling_non_collection_payloads/compares_by_value.js.map +1 -0
- package/dist/esm/queries/index.d.ts +1 -0
- package/dist/esm/queries/index.d.ts.map +1 -1
- package/dist/esm/queries/index.js +1 -0
- package/dist/esm/queries/index.js.map +1 -1
- package/dist/esm/queries/reconcileQueryData.d.ts +2 -0
- package/dist/esm/queries/reconcileQueryData.d.ts.map +1 -0
- package/dist/esm/queries/reconcileQueryData.js +82 -0
- package/dist/esm/queries/reconcileQueryData.js.map +1 -0
- package/dist/esm/tsconfig.tsbuildinfo +1 -1
- package/package.json +1 -1
- package/queries/HubConnectionKeepAlive.ts +30 -3
- package/queries/NullObservableQueryConnection.ts +5 -2
- package/queries/ObservableQueryFor.ts +15 -1
- package/queries/QueryFor.ts +1 -21
- package/queries/QueryInstanceCache.ts +61 -17
- package/queries/QueryResult.ts +34 -0
- package/queries/ServerSentEventHubConnection.ts +45 -10
- package/queries/WebSocketHubConnection.ts +6 -0
- package/queries/for_HubConnectionKeepAlive/when_reconfiguring/while_running.ts +50 -0
- package/queries/for_HubConnectionKeepAlive/when_reconfiguring/while_stopped.ts +28 -0
- package/queries/for_ObservableQueryFor/given/an_observable_query_with_validator.ts +41 -0
- package/queries/for_ObservableQueryFor/when_performing/with_client_validation_failing.ts +30 -0
- package/queries/for_ObservableQueryFor/when_subscribing/with_client_validation_failing.ts +26 -0
- package/queries/for_ObservableQueryFor/when_subscribing/with_client_validation_passing.ts +32 -0
- package/queries/for_QueryInstanceCache/when_setting_last_result/with_a_partially_changed_result.ts +43 -0
- package/queries/for_QueryInstanceCache/when_setting_last_result/with_a_re_delivered_identical_result.ts +34 -0
- package/queries/for_ServerSentEventHubConnection/when_keep_alive_is_idle/triggers_reconnect.ts +4 -4
- package/queries/for_ServerSentEventHubConnection/when_server_advertises_a_longer_keep_alive_interval/does_not_reconnect_at_the_assumed_threshold.ts +64 -0
- package/queries/for_ServerSentEventHubConnection/when_server_reports_keep_alive_disabled/never_reconnects_from_idle.ts +50 -0
- package/queries/for_reconcileQueryData/when_items_are_added_or_removed/reuses_the_surviving_items.ts +46 -0
- package/queries/for_reconcileQueryData/when_one_item_changed/only_the_changed_item_gets_a_new_reference.ts +26 -0
- package/queries/for_reconcileQueryData/when_reconciling_an_unchanged_collection/preserves_all_references.ts +22 -0
- package/queries/for_reconcileQueryData/when_reconciling_non_collection_payloads/compares_by_value.ts +31 -0
- package/queries/index.ts +1 -0
- package/queries/reconcileQueryData.ts +98 -0
|
@@ -8,6 +8,13 @@ var WebSocketHubConnection = require('./WebSocketHubConnection.js');
|
|
|
8
8
|
|
|
9
9
|
// Copyright (c) Cratis. All rights reserved.
|
|
10
10
|
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
|
|
11
|
+
/**
|
|
12
|
+
* How many keep-alive intervals of silence are tolerated before the connection is considered dead.
|
|
13
|
+
*
|
|
14
|
+
* The server guarantees a message every interval, so this is pure slack for latency and jitter.
|
|
15
|
+
* It must stay above 1 — a threshold at or below the server's own cadence makes the client and
|
|
16
|
+
* server timers race, and the client tears down connections the server considers healthy.
|
|
17
|
+
*/ const IDLE_THRESHOLD_FACTOR = 2;
|
|
11
18
|
/**
|
|
12
19
|
* A multiplexed SSE hub connection that uses EventSource for server→client streaming
|
|
13
20
|
* and fetch POST requests for client→server subscribe/unsubscribe commands.
|
|
@@ -40,8 +47,9 @@ var WebSocketHubConnection = require('./WebSocketHubConnection.js');
|
|
|
40
47
|
* @param {string} _subscribeUrl The subscribe POST endpoint URL.
|
|
41
48
|
* @param {string} _unsubscribeUrl The unsubscribe POST endpoint URL.
|
|
42
49
|
* @param {string} _microservice The microservice name to pass as a query argument.
|
|
43
|
-
* @param {number} keepAliveIntervalMs
|
|
44
|
-
*
|
|
50
|
+
* @param {number} keepAliveIntervalMs The keep-alive cadence to assume until the server advertises
|
|
51
|
+
* its own on the {@link HubMessageType.Connected} message (default: 30 000 ms). The connection is
|
|
52
|
+
* considered stale after {@link IDLE_THRESHOLD_FACTOR} times this without any server message.
|
|
45
53
|
* @param {number} connectTimeoutMs How long to wait for the {@link HubMessageType.Connected}
|
|
46
54
|
* message after the HTTP connection opens before giving up and retrying (default: 15 000 ms).
|
|
47
55
|
* @param {IReconnectPolicy} _policy The reconnect policy to use (default: {@link ReconnectPolicy}).
|
|
@@ -56,18 +64,20 @@ var WebSocketHubConnection = require('./WebSocketHubConnection.js');
|
|
|
56
64
|
// inactivity — if the server stops sending messages (including its own keep-alive
|
|
57
65
|
// pings) for the entire idle threshold, the connection is stale and we reconnect.
|
|
58
66
|
//
|
|
59
|
-
// The
|
|
60
|
-
//
|
|
61
|
-
//
|
|
62
|
-
//
|
|
63
|
-
//
|
|
64
|
-
|
|
67
|
+
// The server guarantees a message at least every keep-alive interval, so the threshold
|
|
68
|
+
// only has to absorb network latency, timer jitter and server-side scheduling hiccups.
|
|
69
|
+
// A hard TCP drop surfaces immediately through `onerror`, so this watchdog only needs to
|
|
70
|
+
// catch silent black-holes — that makes a generous tolerance strictly better than a tight
|
|
71
|
+
// one, which would tear down healthy connections.
|
|
72
|
+
//
|
|
73
|
+
// The interval below is only the starting assumption; the server advertises its real
|
|
74
|
+
// cadence on the Connected message and {@link handleConnected} reconfigures from it.
|
|
65
75
|
this._keepAlive = new HubConnectionKeepAlive.HubConnectionKeepAlive(keepAliveIntervalMs, ()=>{
|
|
66
76
|
if (!this._disconnected && this._subscriptions.size > 0) {
|
|
67
|
-
console.warn(`SSE hub: no messages received for ${idleThresholdMs}ms, reconnecting '${this._sseUrl}'`);
|
|
77
|
+
console.warn(`SSE hub: no messages received for ${this._keepAlive.idleThresholdMs}ms, reconnecting '${this._sseUrl}'`);
|
|
68
78
|
this.reconnect();
|
|
69
79
|
}
|
|
70
|
-
},
|
|
80
|
+
}, keepAliveIntervalMs * IDLE_THRESHOLD_FACTOR);
|
|
71
81
|
}
|
|
72
82
|
/** @inheritdoc */ get queryCount() {
|
|
73
83
|
return this._subscriptions.size;
|
|
@@ -232,12 +242,30 @@ var WebSocketHubConnection = require('./WebSocketHubConnection.js');
|
|
|
232
242
|
console.log(`SSE hub: connected with id '${this._connectionId}'`);
|
|
233
243
|
// Connected message arrived — cancel the connect timeout.
|
|
234
244
|
this.clearConnectTimeout();
|
|
245
|
+
this.applyServerKeepAliveInterval(message.keepAliveIntervalMs);
|
|
235
246
|
// Send all pending subscriptions now that we have a connection ID.
|
|
236
247
|
for (const [queryId, sub] of this._pendingSubscriptions){
|
|
237
248
|
this.sendSubscribe(queryId, sub.request);
|
|
238
249
|
}
|
|
239
250
|
this._pendingSubscriptions.clear();
|
|
240
251
|
}
|
|
252
|
+
/**
|
|
253
|
+
* Align the idle watchdog with the keep-alive cadence the server actually runs on.
|
|
254
|
+
*
|
|
255
|
+
* Without this the client assumes the default interval, so a server configured with a longer
|
|
256
|
+
* interval — or with keep-alive switched off entirely — would look silent and be reconnected
|
|
257
|
+
* on a loop even though it is perfectly healthy.
|
|
258
|
+
* @param {number | undefined} serverIntervalMs The interval advertised by the server, if any.
|
|
259
|
+
*/ applyServerKeepAliveInterval(serverIntervalMs) {
|
|
260
|
+
if (serverIntervalMs === undefined) return;
|
|
261
|
+
// Keep-alive disabled server-side: silence is expected, so watching for it would guarantee
|
|
262
|
+
// an endless reconnect loop. Hard drops still surface through `onerror`.
|
|
263
|
+
if (serverIntervalMs <= 0) {
|
|
264
|
+
this._keepAlive.stop();
|
|
265
|
+
return;
|
|
266
|
+
}
|
|
267
|
+
this._keepAlive.reconfigure(serverIntervalMs, serverIntervalMs * IDLE_THRESHOLD_FACTOR);
|
|
268
|
+
}
|
|
241
269
|
handleQueryResult(message) {
|
|
242
270
|
if (!message.queryId) return;
|
|
243
271
|
const sub = 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';\nimport { IObservableQueryHubConnection } from './IObservableQueryHubConnection';\nimport { DataReceived } from './ObservableQueryConnection';\nimport { HubConnectionKeepAlive } from './HubConnectionKeepAlive';\nimport { IReconnectPolicy } from './IReconnectPolicy';\nimport { ReconnectPolicy } from './ReconnectPolicy';\nimport { QueryResult } from './QueryResult';\nimport { HubMessage, HubMessageType, SubscriptionRequest } from './WebSocketHubConnection';\n\n/* eslint-disable @typescript-eslint/no-explicit-any */\n\ninterface ActiveSubscription {\n request: SubscriptionRequest;\n callback: DataReceived<any>;\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 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 How long without any server message before the connection\n * is considered stale and a reconnect is forced (default: 30 000 ms).\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 idle threshold is set to 1.5× the check interval so the server's keep-alive\n // ping (which fires on the same cadence) has time to arrive over the network before\n // the client declares the connection dead. Without this tolerance the client's timer\n // and the server's timer race — the client often fires first and reconnects\n // unnecessarily.\n const idleThresholdMs = Math.round(keepAliveIntervalMs * 1.5);\n this._keepAlive = new HubConnectionKeepAlive(keepAliveIntervalMs, () => {\n if (!this._disconnected && this._subscriptions.size > 0) {\n console.warn(`SSE hub: no messages received for ${idleThresholdMs}ms, reconnecting '${this._sseUrl}'`);\n this.reconnect();\n }\n }, idleThresholdMs);\n }\n\n /** @inheritdoc */\n get queryCount(): number {\n return this._subscriptions.size;\n }\n\n /** @inheritdoc */\n get isConnected(): boolean {\n return this._connectionId !== undefined && this._eventSource?.readyState === EventSource.OPEN;\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 this._latencySamples.reduce((a, b) => a + b, 0) / this._latencySamples.length;\n }\n\n /** @inheritdoc */\n subscribe(queryId: string, request: SubscriptionRequest, callback: DataReceived<any>): void {\n const sub: ActiveSubscription = { request, callback };\n this._subscriptions.set(queryId, sub);\n\n this.ensureConnected();\n\n if (this._connectionId) {\n this.sendSubscribe(queryId, request);\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 this._subscriptions.delete(queryId);\n this._pendingSubscriptions.delete(queryId);\n\n if (this._connectionId) {\n this.sendUnsubscribe(queryId);\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._eventSource?.close();\n this._eventSource = undefined;\n this._connectionId = undefined;\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 this.openEventSource();\n }\n\n private close(): void {\n this._disconnected = true;\n this._policy.cancel();\n this._keepAlive.stop();\n this.clearConnectTimeout();\n if (this._eventSource) {\n // Detach all handlers BEFORE closing so that the async onerror / onmessage\n // events that fire after close() cannot observe the new _disconnected=false\n // state set by an immediately following ensureConnected() call. Without this,\n // a stale onerror triggers an unintended reconnect with exponential back-off.\n this._eventSource.onopen = null;\n this._eventSource.onmessage = null;\n this._eventSource.onerror = null;\n this._eventSource.close();\n }\n this._eventSource = undefined;\n this._connectionId = undefined;\n }\n\n private openEventSource(): void {\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._eventSource = new EventSource(url);\n\n this._eventSource.onopen = () => {\n if (this._disconnected) 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 (!this._disconnected && !this._connectionId) {\n console.warn(`SSE hub: no Connected message within ${this._connectTimeoutMs}ms, retrying '${url}'`);\n this.reconnect();\n }\n }, this._connectTimeoutMs);\n };\n\n this._eventSource.onmessage = (event: MessageEvent) => {\n if (this._disconnected) return;\n this._keepAlive.recordActivity();\n this.handleMessage(event.data as string);\n };\n\n this._eventSource.onerror = () => {\n if (this._disconnected) 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 // Close the EventSource so the reconnect policy manages the schedule.\n this._eventSource?.close();\n this._eventSource = undefined;\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.openEventSource();\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 console.warn(`SSE hub: query '${message.queryId}' unauthorized`);\n this.handleUnauthorized(message);\n break;\n case HubMessageType.Error:\n console.error(`SSE hub: query '${message.queryId}' error:`, message.payload);\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 this._connectionId = message.payload as string;\n console.log(`SSE hub: connected with id '${this._connectionId}'`);\n\n // Connected message arrived — cancel the connect timeout.\n this.clearConnectTimeout();\n\n // Send all pending subscriptions now that we have a connection ID.\n for (const [queryId, sub] of this._pendingSubscriptions) {\n this.sendSubscribe(queryId, sub.request);\n }\n this._pendingSubscriptions.clear();\n }\n\n private handleQueryResult(message: HubMessage): void {\n if (!message.queryId) return;\n\n const sub = this._subscriptions.get(message.queryId);\n if (!sub) return;\n\n const result = message.payload as QueryResult<any>;\n sub.callback(result);\n }\n\n private handleUnauthorized(message: HubMessage): void {\n if (!message.queryId) return;\n\n const sub = this._subscriptions.get(message.queryId);\n if (!sub) return;\n\n this._subscriptions.delete(message.queryId);\n this._pendingSubscriptions.delete(message.queryId);\n sub.callback(QueryResult.unauthorized());\n }\n\n private sendSubscribe(queryId: string, request: SubscriptionRequest, attempt: number = 0): void {\n if (!this._connectionId || this._disconnected) return;\n\n // Capture the connection ID so retries can detect if a reconnect has already fired\n // for a different reason and made this retry obsolete.\n const connectionId = this._connectionId;\n\n const body = {\n connectionId,\n queryId,\n request,\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 }).then(response => {\n if (!response.ok) {\n if (attempt < maxRetries && this._connectionId === connectionId && !this._disconnected) {\n setTimeout(() => this.sendSubscribe(queryId, request, attempt + 1), retryDelayMs * (attempt + 1));\n } else if (this._connectionId === connectionId && !this._disconnected) {\n console.warn(`SSE hub: subscribe POST for '${queryId}' returned ${response.status} after ${attempt + 1} attempt(s), reconnecting`);\n this.reconnect();\n }\n }\n }).catch(error => {\n if (attempt < maxRetries && this._connectionId === connectionId && !this._disconnected) {\n setTimeout(() => this.sendSubscribe(queryId, request, attempt + 1), retryDelayMs * (attempt + 1));\n } else if (this._connectionId === connectionId && !this._disconnected) {\n console.error(`SSE hub: subscribe POST failed for '${queryId}' after ${attempt + 1} attempt(s), reconnecting`, error);\n this.reconnect();\n }\n });\n }\n\n private sendUnsubscribe(queryId: string): void {\n if (!this._connectionId) return;\n\n const body = {\n connectionId: this._connectionId,\n queryId,\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 for '${queryId}'`, error);\n });\n }\n}\n"],"names":["ServerSentEventHubConnection","_eventSource","_connectionId","_disconnected","_subscriptions","Map","_pendingSubscriptions","_lastPongLatency","_latencySamples","_connectTimeoutTimer","_keepAlive","_subscribeUrl","_unsubscribeUrl","keepAliveIntervalMs","_connectTimeoutMs","_policy","ReconnectPolicy","_sseUrl","_microservice","idleThresholdMs","Math","round","HubConnectionKeepAlive","size","console","warn","reconnect","queryCount","isConnected","undefined","readyState","EventSource","OPEN","lastPingLatency","averageLatency","length","reduce","a","b","subscribe","queryId","request","callback","sub","set","ensureConnected","sendSubscribe","unsubscribe","delete","sendUnsubscribe","close","dispose","clear","cancel","stop","clearConnectTimeout","CLOSED","openEventSource","onopen","onmessage","onerror","url","param","Globals","microserviceWSQueryArgument","encodeURIComponent","includes","log","reset","start","setTimeout","event","recordActivity","handleMessage","data","schedule","clearTimeout","rawData","message","JSON","parse","type","HubMessageType","Connected","handleConnected","QueryResult","handleQueryResult","Ping","Unauthorized","handleUnauthorized","Error","error","payload","get","result","unauthorized","attempt","connectionId","body","customHeaders","httpHeadersCallback","maxRetries","retryDelayMs","fetch","method","headers","stringify","then","response","ok","status","catch"],"mappings":";;;;;;;;AAAA;AACA;AAkBA;;;;;;;;;;AAUC,IACM,MAAMA,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;IACSC,UAAAA;AAEjB;;;;;;;;;;;QAYA,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,aAAA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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';\nimport { IObservableQueryHubConnection } from './IObservableQueryHubConnection';\nimport { DataReceived } from './ObservableQueryConnection';\nimport { HubConnectionKeepAlive } from './HubConnectionKeepAlive';\nimport { IReconnectPolicy } from './IReconnectPolicy';\nimport { ReconnectPolicy } from './ReconnectPolicy';\nimport { QueryResult } from './QueryResult';\nimport { HubMessage, HubMessageType, SubscriptionRequest } from './WebSocketHubConnection';\n\n/* eslint-disable @typescript-eslint/no-explicit-any */\n\ninterface ActiveSubscription {\n request: SubscriptionRequest;\n callback: DataReceived<any>;\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 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(keepAliveIntervalMs, () => {\n if (!this._disconnected && this._subscriptions.size > 0) {\n console.warn(`SSE hub: no messages received for ${this._keepAlive.idleThresholdMs}ms, reconnecting '${this._sseUrl}'`);\n this.reconnect();\n }\n }, keepAliveIntervalMs * IDLE_THRESHOLD_FACTOR);\n }\n\n /** @inheritdoc */\n get queryCount(): number {\n return this._subscriptions.size;\n }\n\n /** @inheritdoc */\n get isConnected(): boolean {\n return this._connectionId !== undefined && this._eventSource?.readyState === EventSource.OPEN;\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 this._latencySamples.reduce((a, b) => a + b, 0) / this._latencySamples.length;\n }\n\n /** @inheritdoc */\n subscribe(queryId: string, request: SubscriptionRequest, callback: DataReceived<any>): void {\n const sub: ActiveSubscription = { request, callback };\n this._subscriptions.set(queryId, sub);\n\n this.ensureConnected();\n\n if (this._connectionId) {\n this.sendSubscribe(queryId, request);\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 this._subscriptions.delete(queryId);\n this._pendingSubscriptions.delete(queryId);\n\n if (this._connectionId) {\n this.sendUnsubscribe(queryId);\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._eventSource?.close();\n this._eventSource = undefined;\n this._connectionId = undefined;\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 this.openEventSource();\n }\n\n private close(): void {\n this._disconnected = true;\n this._policy.cancel();\n this._keepAlive.stop();\n this.clearConnectTimeout();\n if (this._eventSource) {\n // Detach all handlers BEFORE closing so that the async onerror / onmessage\n // events that fire after close() cannot observe the new _disconnected=false\n // state set by an immediately following ensureConnected() call. Without this,\n // a stale onerror triggers an unintended reconnect with exponential back-off.\n this._eventSource.onopen = null;\n this._eventSource.onmessage = null;\n this._eventSource.onerror = null;\n this._eventSource.close();\n }\n this._eventSource = undefined;\n this._connectionId = undefined;\n }\n\n private openEventSource(): void {\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._eventSource = new EventSource(url);\n\n this._eventSource.onopen = () => {\n if (this._disconnected) 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 (!this._disconnected && !this._connectionId) {\n console.warn(`SSE hub: no Connected message within ${this._connectTimeoutMs}ms, retrying '${url}'`);\n this.reconnect();\n }\n }, this._connectTimeoutMs);\n };\n\n this._eventSource.onmessage = (event: MessageEvent) => {\n if (this._disconnected) return;\n this._keepAlive.recordActivity();\n this.handleMessage(event.data as string);\n };\n\n this._eventSource.onerror = () => {\n if (this._disconnected) 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 // Close the EventSource so the reconnect policy manages the schedule.\n this._eventSource?.close();\n this._eventSource = undefined;\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.openEventSource();\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 console.warn(`SSE hub: query '${message.queryId}' unauthorized`);\n this.handleUnauthorized(message);\n break;\n case HubMessageType.Error:\n console.error(`SSE hub: query '${message.queryId}' error:`, message.payload);\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 this._connectionId = message.payload as string;\n console.log(`SSE hub: connected with id '${this._connectionId}'`);\n\n // Connected message arrived — cancel the connect timeout.\n this.clearConnectTimeout();\n\n this.applyServerKeepAliveInterval(message.keepAliveIntervalMs);\n\n // Send all pending subscriptions now that we have a connection ID.\n for (const [queryId, sub] of this._pendingSubscriptions) {\n this.sendSubscribe(queryId, sub.request);\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(serverIntervalMs, serverIntervalMs * IDLE_THRESHOLD_FACTOR);\n }\n\n private handleQueryResult(message: HubMessage): void {\n if (!message.queryId) return;\n\n const sub = this._subscriptions.get(message.queryId);\n if (!sub) return;\n\n const result = message.payload as QueryResult<any>;\n sub.callback(result);\n }\n\n private handleUnauthorized(message: HubMessage): void {\n if (!message.queryId) return;\n\n const sub = this._subscriptions.get(message.queryId);\n if (!sub) return;\n\n this._subscriptions.delete(message.queryId);\n this._pendingSubscriptions.delete(message.queryId);\n sub.callback(QueryResult.unauthorized());\n }\n\n private sendSubscribe(queryId: string, request: SubscriptionRequest, attempt: number = 0): void {\n if (!this._connectionId || this._disconnected) return;\n\n // Capture the connection ID so retries can detect if a reconnect has already fired\n // for a different reason and made this retry obsolete.\n const connectionId = this._connectionId;\n\n const body = {\n connectionId,\n queryId,\n request,\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 }).then(response => {\n if (!response.ok) {\n if (attempt < maxRetries && this._connectionId === connectionId && !this._disconnected) {\n setTimeout(() => this.sendSubscribe(queryId, request, attempt + 1), retryDelayMs * (attempt + 1));\n } else if (this._connectionId === connectionId && !this._disconnected) {\n console.warn(`SSE hub: subscribe POST for '${queryId}' returned ${response.status} after ${attempt + 1} attempt(s), reconnecting`);\n this.reconnect();\n }\n }\n }).catch(error => {\n if (attempt < maxRetries && this._connectionId === connectionId && !this._disconnected) {\n setTimeout(() => this.sendSubscribe(queryId, request, attempt + 1), retryDelayMs * (attempt + 1));\n } else if (this._connectionId === connectionId && !this._disconnected) {\n console.error(`SSE hub: subscribe POST failed for '${queryId}' after ${attempt + 1} attempt(s), reconnecting`, error);\n this.reconnect();\n }\n });\n }\n\n private sendUnsubscribe(queryId: string): void {\n if (!this._connectionId) return;\n\n const body = {\n connectionId: this._connectionId,\n queryId,\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 for '${queryId}'`, error);\n });\n }\n}\n"],"names":["IDLE_THRESHOLD_FACTOR","ServerSentEventHubConnection","_eventSource","_connectionId","_disconnected","_subscriptions","Map","_pendingSubscriptions","_lastPongLatency","_latencySamples","_connectTimeoutTimer","_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","set","ensureConnected","sendSubscribe","unsubscribe","delete","sendUnsubscribe","close","dispose","clear","cancel","stop","clearConnectTimeout","CLOSED","openEventSource","onopen","onmessage","onerror","url","param","Globals","microserviceWSQueryArgument","encodeURIComponent","includes","log","reset","start","setTimeout","event","recordActivity","handleMessage","data","schedule","clearTimeout","rawData","message","JSON","parse","type","HubMessageType","Connected","handleConnected","QueryResult","handleQueryResult","Ping","Unauthorized","handleUnauthorized","Error","error","payload","applyServerKeepAliveInterval","serverIntervalMs","reconfigure","get","result","unauthorized","attempt","connectionId","body","customHeaders","httpHeadersCallback","maxRetries","retryDelayMs","fetch","method","headers","stringify","then","response","ok","status","catch"],"mappings":";;;;;;;;AAAA;AACA;AAkBA;;;;;;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,g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AI,CAAC,IAAI,CAACpC,aAAa,EAAE;AAEzB,QAAA,MAAMiG,IAAAA,GAAO;YACTD,YAAAA,EAAc,IAAI,CAAChG,aAAa;AAChCoC,YAAAA;AACJ,SAAA;AAEA,QAAA,MAAM8D,aAAAA,GAAgBvC,eAAAA,CAAQwC,mBAAmB,IAAA,IAAQ,EAAC;QAE1DG,KAAAA,CAAM,IAAI,CAAC5F,eAAe,EAAE;YACxB6F,MAAAA,EAAQ,MAAA;YACRC,OAAAA,EAAS;gBAAE,cAAA,EAAgB,kBAAA;AAAoB,gBAAA,GAAGN;AAAc,aAAA;YAChED,IAAAA,EAAMtB,IAAAA,CAAK8B,SAAS,CAACR,IAAAA;SACzB,CAAA,CAAGa,KAAK,CAACvB,CAAAA,KAAAA,GAAAA;YACLpE,OAAAA,CAAQoE,KAAK,CAAC,CAAC,sCAAsC,EAAEnD,OAAAA,CAAQ,CAAC,CAAC,EAAEmD,KAAAA,CAAAA;AACvE,QAAA,CAAA,CAAA;AACJ,IAAA;AACJ;;;;"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"WebSocketHubConnection.js","sources":["../../../queries/WebSocketHubConnection.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';\nimport { DataReceived } from './ObservableQueryConnection';\nimport { HubConnectionKeepAlive } from './HubConnectionKeepAlive';\nimport { IReconnectPolicy } from './IReconnectPolicy';\nimport { ReconnectPolicy } from './ReconnectPolicy';\nimport { QueryResult } from './QueryResult';\n\n/* eslint-disable @typescript-eslint/no-explicit-any */\n\n/**\n * Message types matching the backend {@link ObservableQueryHubMessageType} enum.\n * Serialized as strings by the JsonStringEnumConverter on the server.\n */\nexport enum HubMessageType {\n Subscribe = 'Subscribe',\n Unsubscribe = 'Unsubscribe',\n QueryResult = 'QueryResult',\n Unauthorized = 'Unauthorized',\n Error = 'Error',\n Ping = 'Ping',\n Pong = 'Pong',\n Connected = 'Connected',\n}\n\n/**\n * Wire format for messages exchanged over the {@link WebSocketHubConnection}.\n */\nexport interface HubMessage {\n type: HubMessageType;\n queryId?: string;\n payload?: any;\n timestamp?: number;\n}\n\n/**\n * Matches the backend {@link ObservableQuerySubscriptionRequest} record.\n */\nexport interface SubscriptionRequest {\n queryName: string;\n arguments?: Record<string, string | null>;\n page?: number;\n pageSize?: number;\n sortBy?: string;\n sortDirection?: string;\n transferMode?: string;\n}\n\ninterface ActiveSubscription {\n request: SubscriptionRequest;\n callback: DataReceived<any>;\n}\n\n/**\n * Represents a single multiplexed WebSocket connection to the observable query hub\n * at {@code /.cratis/queries/ws}.\n *\n * Multiple query subscriptions are carried over the same physical WebSocket. Each subscription\n * is identified by a client-generated {@code queryId}; the server tags every result message with\n * the same id so responses can be routed to the correct callback.\n */\nexport class WebSocketHubConnection {\n private _socket?: WebSocket;\n private _disconnected = false;\n private _subscriptions: Map<string, ActiveSubscription> = new Map();\n private readonly _keepAlive: HubConnectionKeepAlive;\n private _lastPingSentTime?: number;\n private _lastPongLatency: number = 0;\n private _latencySamples: number[] = [];\n\n /**\n * Initializes a new instance of {@link WebSocketHubConnection}.\n * @param {string} url The WebSocket URL of the hub endpoint (e.g. {@code ws://localhost:5000/.cratis/queries/ws}).\n * @param {string} microservice The microservice name to pass as a query argument.\n * @param {number} pingIntervalMs How often to send keep-alive pings when the connection is idle (default: 10 000 ms).\n * @param {IReconnectPolicy} reconnectPolicy The reconnect policy to use (default: {@link ReconnectPolicy}).\n */\n constructor(\n private readonly _url: string,\n private readonly _microservice: string,\n pingIntervalMs: number = 10000,\n private readonly _policy: IReconnectPolicy = new ReconnectPolicy()\n ) {\n this._keepAlive = new HubConnectionKeepAlive(pingIntervalMs, () => {\n if (this._socket?.readyState === WebSocket.OPEN) {\n this._lastPingSentTime = Date.now();\n this.sendMessage({ type: HubMessageType.Ping, timestamp: this._lastPingSentTime });\n }\n });\n }\n\n /**\n * Gets the number of active query subscriptions on this connection.\n */\n get queryCount(): number {\n return this._subscriptions.size;\n }\n\n /**\n * Gets whether the WebSocket connection is currently open.\n */\n get isConnected(): boolean {\n return this._socket?.readyState === WebSocket.OPEN;\n }\n\n /**\n * Gets the latency of the last ping/pong sequence in milliseconds.\n */\n get lastPingLatency(): number {\n return this._lastPongLatency;\n }\n\n /**\n * Gets the rolling average latency in milliseconds.\n */\n get averageLatency(): number {\n if (this._latencySamples.length === 0) return 0;\n return this._latencySamples.reduce((a, b) => a + b, 0) / this._latencySamples.length;\n }\n\n /**\n * Subscribe to a query on this hub connection.\n * If the WebSocket is not yet open, the subscribe message will be sent once the connection is established.\n * @param {string} queryId Client-generated unique identifier for this subscription.\n * @param {SubscriptionRequest} request The subscription request payload.\n * @param {DataReceived<any>} callback Callback invoked whenever the server pushes a result for this query.\n */\n subscribe(queryId: string, request: SubscriptionRequest, callback: DataReceived<any>): void {\n this._subscriptions.set(queryId, { request, callback });\n this.ensureConnected();\n\n if (this._socket?.readyState === WebSocket.OPEN) {\n this.sendSubscribeMessage(queryId, request);\n }\n // If not yet open, sendAllSubscriptions will fire in onopen.\n }\n\n /**\n * Unsubscribe from a query on this hub connection.\n * @param {string} queryId The identifier of the subscription to cancel.\n */\n unsubscribe(queryId: string): void {\n this._subscriptions.delete(queryId);\n\n if (this._socket?.readyState === WebSocket.OPEN) {\n this.sendMessage({ type: HubMessageType.Unsubscribe, queryId });\n }\n\n // If no subscriptions remain, close the connection to free resources.\n if (this._subscriptions.size === 0) {\n this.close();\n }\n }\n\n /**\n * Permanently close this hub connection and clean up all subscriptions.\n */\n dispose(): void {\n this._disconnected = true;\n this._subscriptions.clear();\n this._keepAlive.stop();\n this._policy.cancel();\n this._socket?.close();\n this._socket = undefined;\n }\n\n private ensureConnected(): void {\n if (this._disconnected) {\n // Reset disconnected flag when a new subscription comes in\n this._disconnected = false;\n }\n\n if (this._socket && (this._socket.readyState === WebSocket.OPEN || this._socket.readyState === WebSocket.CONNECTING)) {\n return;\n }\n\n this.openSocket();\n }\n\n private close(): void {\n this._disconnected = true;\n this._keepAlive.stop();\n this._policy.cancel();\n if (this._socket) {\n // Detach all handlers BEFORE closing so that the async onclose event cannot\n // fire after a new subscription has reset _disconnected to false and opened a\n // fresh socket. Without this, the stale onclose triggers an unintended\n // reconnect via the back-off policy, causing a 1-10 second delay before the\n // new page's queries receive their first data.\n this._socket.onopen = null;\n this._socket.onclose = null;\n this._socket.onerror = null;\n this._socket.onmessage = null;\n this._socket.close();\n }\n this._socket = undefined;\n }\n\n private openSocket(): void {\n let url = this._url;\n if (this._microservice?.length > 0) {\n const param = `${Globals.microserviceWSQueryArgument}=${encodeURIComponent(this._microservice)}`;\n url += (url.includes('?') ? '&' : '?') + param;\n }\n\n this._socket = new WebSocket(url);\n\n this._socket.onopen = () => {\n if (this._disconnected) return;\n console.log(`Hub connection established: '${url}'`);\n this._policy.reset();\n this._keepAlive.start();\n this.sendAllSubscriptions();\n };\n\n this._socket.onclose = () => {\n if (this._disconnected) return;\n console.log(`Hub connection closed: '${url}'`);\n this._keepAlive.stop();\n if (this._subscriptions.size === 0) return;\n this._policy.schedule(() => {\n if (!this._disconnected && this._subscriptions.size > 0) {\n this.openSocket();\n }\n }, this._url);\n };\n\n this._socket.onerror = (error) => {\n if (this._disconnected) return;\n console.error(`Hub connection error: '${url}'`, error);\n this._keepAlive.stop();\n // onclose will fire after onerror, triggering reconnect\n };\n\n this._socket.onmessage = (ev) => {\n if (this._disconnected) return;\n this.handleMessage(ev.data as string);\n };\n }\n\n private sendAllSubscriptions(): void {\n for (const [queryId, sub] of this._subscriptions) {\n this.sendSubscribeMessage(queryId, sub.request);\n }\n }\n\n private sendSubscribeMessage(queryId: string, request: SubscriptionRequest): void {\n this.sendMessage({\n type: HubMessageType.Subscribe,\n queryId,\n payload: request,\n });\n }\n\n private sendMessage(message: HubMessage): void {\n if (this._socket?.readyState === WebSocket.OPEN) {\n this._socket.send(JSON.stringify(message));\n }\n }\n\n private handleMessage(rawData: string): void {\n try {\n const message = JSON.parse(rawData) as HubMessage;\n\n // Every received message is activity — skip keep-alive ping if data is flowing.\n this._keepAlive.recordActivity();\n\n switch (message.type) {\n case HubMessageType.QueryResult:\n this.handleQueryResult(message);\n break;\n case HubMessageType.Pong:\n this.handlePong(message);\n break;\n case HubMessageType.Unauthorized:\n console.warn(`Hub: query '${message.queryId}' unauthorized`);\n this.handleUnauthorized(message);\n break;\n case HubMessageType.Error:\n console.error(`Hub: query '${message.queryId}' error:`, message.payload);\n break;\n }\n } catch (error) {\n console.error('Hub: error parsing message', error);\n }\n }\n\n private handleQueryResult(message: HubMessage): void {\n if (!message.queryId) return;\n\n const sub = this._subscriptions.get(message.queryId);\n if (!sub) return;\n\n const result = message.payload as QueryResult<any>;\n sub.callback(result);\n }\n\n private handleUnauthorized(message: HubMessage): void {\n if (!message.queryId) return;\n\n const sub = this._subscriptions.get(message.queryId);\n if (!sub) return;\n\n this._subscriptions.delete(message.queryId);\n sub.callback(QueryResult.unauthorized());\n }\n\n private handlePong(message: HubMessage): void {\n if (message.timestamp && this._lastPingSentTime) {\n const latency = Date.now() - message.timestamp;\n this._lastPongLatency = latency;\n this._latencySamples.push(latency);\n\n if (this._latencySamples.length > 100) {\n this._latencySamples.shift();\n }\n }\n }\n}\n"],"names":["HubMessageType","WebSocketHubConnection","_socket","_disconnected","_subscriptions","Map","_keepAlive","_lastPingSentTime","_lastPongLatency","_latencySamples","_url","pingIntervalMs","_policy","ReconnectPolicy","_microservice","HubConnectionKeepAlive","readyState","WebSocket","OPEN","Date","now","sendMessage","type","timestamp","queryCount","size","isConnected","lastPingLatency","averageLatency","length","reduce","a","b","subscribe","queryId","request","callback","set","ensureConnected","sendSubscribeMessage","unsubscribe","delete","close","dispose","clear","stop","cancel","undefined","CONNECTING","openSocket","onopen","onclose","onerror","onmessage","url","param","Globals","microserviceWSQueryArgument","encodeURIComponent","includes","console","log","reset","start","sendAllSubscriptions","schedule","error","ev","handleMessage","data","sub","payload","message","send","JSON","stringify","rawData","parse","recordActivity","handleQueryResult","handlePong","warn","handleUnauthorized","get","result","QueryResult","unauthorized","latency","push","shift"],"mappings":";;;;;;;AAAA;AACA;AASA;;;IAMO,IAAKA,cAAAA,iBAAAA,SAAAA,cAAAA,EAAAA;;;;;;;;;AAAAA,IAAAA,OAAAA,cAAAA;AASX,CAAA,CAAA,EAAA;AA8BD;;;;;;;AAOC,IACM,MAAMC,sBAAAA,CAAAA;;;;IACDC,OAAAA;AACAC,IAAAA,aAAAA,GAAgB,KAAA;AAChBC,IAAAA,cAAAA,GAAkD,IAAIC,GAAAA,EAAAA;IAC7CC,UAAAA;IACTC,iBAAAA;AACAC,IAAAA,gBAAAA,GAA2B,CAAA;AAC3BC,IAAAA,eAAAA,GAA4B,EAAE;AAEtC;;;;;;AAMC,QACD,WAAA,CACqBC,IAAY,EAC7B,aAAsC,EACtCC,cAAAA,GAAyB,KAAK,EACbC,OAAAA,GAA4B,IAAIC,iCAAiB,CACpE;aAJmBH,IAAAA,GAAAA,IAAAA;aACAI,aAAAA,GAAAA,aAAAA;aAEAF,OAAAA,GAAAA,OAAAA;AAEjB,QAAA,IAAI,CAACN,UAAU,GAAG,IAAIS,8CAAuBJ,cAAAA,EAAgB,IAAA;AACzD,YAAA,IAAI,IAAI,CAACT,OAAO,EAAEc,UAAAA,KAAeC,SAAAA,CAAUC,IAAI,EAAE;AAC7C,gBAAA,IAAI,CAACX,iBAAiB,GAAGY,IAAAA,CAAKC,GAAG,EAAA;gBACjC,IAAI,CAACC,WAAW,CAAC;oBAAEC,IAAI,EAAA,MAAA;oBAAuBC,SAAAA,EAAW,IAAI,CAAChB;AAAkB,iBAAA,CAAA;AACpF,YAAA;AACJ,QAAA,CAAA,CAAA;AACJ,IAAA;AAEA;;AAEC,QACD,IAAIiB,UAAAA,GAAqB;AACrB,QAAA,OAAO,IAAI,CAACpB,cAAc,CAACqB,IAAI;AACnC,IAAA;AAEA;;AAEC,QACD,IAAIC,WAAAA,GAAuB;AACvB,QAAA,OAAO,I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EQF,IAAAA,kBAAAA,CAAmBV,OAAmB,EAAQ;QAClD,IAAI,CAACA,OAAAA,CAAQtC,OAAO,EAAE;QAEtB,MAAMoC,GAAAA,GAAM,IAAI,CAAClE,cAAc,CAAC+E,GAAG,CAACX,QAAQtC,OAAO,CAAA;AACnD,QAAA,IAAI,CAACoC,GAAAA,EAAK;AAEV,QAAA,IAAI,CAAClE,cAAc,CAACqC,MAAM,CAAC+B,QAAQtC,OAAO,CAAA;QAC1CoC,GAAAA,CAAIlC,QAAQ,CAACiD,uBAAAA,CAAYC,YAAY,EAAA,CAAA;AACzC,IAAA;AAEQN,IAAAA,UAAAA,CAAWR,OAAmB,EAAQ;AAC1C,QAAA,IAAIA,QAAQjD,SAAS,IAAI,IAAI,CAAChB,iBAAiB,EAAE;AAC7C,YAAA,MAAMgF,OAAAA,GAAUpE,IAAAA,CAAKC,GAAG,EAAA,GAAKoD,QAAQjD,SAAS;YAC9C,IAAI,CAACf,gBAAgB,GAAG+E,OAAAA;AACxB,YAAA,IAAI,CAAC9E,eAAe,CAAC+E,IAAI,CAACD,OAAAA,CAAAA;AAE1B,YAAA,IAAI,IAAI,CAAC9E,eAAe,CAACoB,MAAM,GAAG,GAAA,EAAK;gBACnC,IAAI,CAACpB,eAAe,CAACgF,KAAK,EAAA;AAC9B,YAAA;AACJ,QAAA;AACJ,IAAA;AACJ;;;;;"}
|
|
1
|
+
{"version":3,"file":"WebSocketHubConnection.js","sources":["../../../queries/WebSocketHubConnection.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';\nimport { DataReceived } from './ObservableQueryConnection';\nimport { HubConnectionKeepAlive } from './HubConnectionKeepAlive';\nimport { IReconnectPolicy } from './IReconnectPolicy';\nimport { ReconnectPolicy } from './ReconnectPolicy';\nimport { QueryResult } from './QueryResult';\n\n/* eslint-disable @typescript-eslint/no-explicit-any */\n\n/**\n * Message types matching the backend {@link ObservableQueryHubMessageType} enum.\n * Serialized as strings by the JsonStringEnumConverter on the server.\n */\nexport enum HubMessageType {\n Subscribe = 'Subscribe',\n Unsubscribe = 'Unsubscribe',\n QueryResult = 'QueryResult',\n Unauthorized = 'Unauthorized',\n Error = 'Error',\n Ping = 'Ping',\n Pong = 'Pong',\n Connected = 'Connected',\n}\n\n/**\n * Wire format for messages exchanged over the {@link WebSocketHubConnection}.\n */\nexport interface HubMessage {\n type: HubMessageType;\n queryId?: string;\n payload?: any;\n timestamp?: number;\n\n /**\n * The server's keep-alive interval in milliseconds, or 0 when keep-alive is disabled.\n * Only present on {@link HubMessageType.Connected} messages.\n */\n keepAliveIntervalMs?: number;\n}\n\n/**\n * Matches the backend {@link ObservableQuerySubscriptionRequest} record.\n */\nexport interface SubscriptionRequest {\n queryName: string;\n arguments?: Record<string, string | null>;\n page?: number;\n pageSize?: number;\n sortBy?: string;\n sortDirection?: string;\n transferMode?: string;\n}\n\ninterface ActiveSubscription {\n request: SubscriptionRequest;\n callback: DataReceived<any>;\n}\n\n/**\n * Represents a single multiplexed WebSocket connection to the observable query hub\n * at {@code /.cratis/queries/ws}.\n *\n * Multiple query subscriptions are carried over the same physical WebSocket. Each subscription\n * is identified by a client-generated {@code queryId}; the server tags every result message with\n * the same id so responses can be routed to the correct callback.\n */\nexport class WebSocketHubConnection {\n private _socket?: WebSocket;\n private _disconnected = false;\n private _subscriptions: Map<string, ActiveSubscription> = new Map();\n private readonly _keepAlive: HubConnectionKeepAlive;\n private _lastPingSentTime?: number;\n private _lastPongLatency: number = 0;\n private _latencySamples: number[] = [];\n\n /**\n * Initializes a new instance of {@link WebSocketHubConnection}.\n * @param {string} url The WebSocket URL of the hub endpoint (e.g. {@code ws://localhost:5000/.cratis/queries/ws}).\n * @param {string} microservice The microservice name to pass as a query argument.\n * @param {number} pingIntervalMs How often to send keep-alive pings when the connection is idle (default: 10 000 ms).\n * @param {IReconnectPolicy} reconnectPolicy The reconnect policy to use (default: {@link ReconnectPolicy}).\n */\n constructor(\n private readonly _url: string,\n private readonly _microservice: string,\n pingIntervalMs: number = 10000,\n private readonly _policy: IReconnectPolicy = new ReconnectPolicy()\n ) {\n this._keepAlive = new HubConnectionKeepAlive(pingIntervalMs, () => {\n if (this._socket?.readyState === WebSocket.OPEN) {\n this._lastPingSentTime = Date.now();\n this.sendMessage({ type: HubMessageType.Ping, timestamp: this._lastPingSentTime });\n }\n });\n }\n\n /**\n * Gets the number of active query subscriptions on this connection.\n */\n get queryCount(): number {\n return this._subscriptions.size;\n }\n\n /**\n * Gets whether the WebSocket connection is currently open.\n */\n get isConnected(): boolean {\n return this._socket?.readyState === WebSocket.OPEN;\n }\n\n /**\n * Gets the latency of the last ping/pong sequence in milliseconds.\n */\n get lastPingLatency(): number {\n return this._lastPongLatency;\n }\n\n /**\n * Gets the rolling average latency in milliseconds.\n */\n get averageLatency(): number {\n if (this._latencySamples.length === 0) return 0;\n return this._latencySamples.reduce((a, b) => a + b, 0) / this._latencySamples.length;\n }\n\n /**\n * Subscribe to a query on this hub connection.\n * If the WebSocket is not yet open, the subscribe message will be sent once the connection is established.\n * @param {string} queryId Client-generated unique identifier for this subscription.\n * @param {SubscriptionRequest} request The subscription request payload.\n * @param {DataReceived<any>} callback Callback invoked whenever the server pushes a result for this query.\n */\n subscribe(queryId: string, request: SubscriptionRequest, callback: DataReceived<any>): void {\n this._subscriptions.set(queryId, { request, callback });\n this.ensureConnected();\n\n if (this._socket?.readyState === WebSocket.OPEN) {\n this.sendSubscribeMessage(queryId, request);\n }\n // If not yet open, sendAllSubscriptions will fire in onopen.\n }\n\n /**\n * Unsubscribe from a query on this hub connection.\n * @param {string} queryId The identifier of the subscription to cancel.\n */\n unsubscribe(queryId: string): void {\n this._subscriptions.delete(queryId);\n\n if (this._socket?.readyState === WebSocket.OPEN) {\n this.sendMessage({ type: HubMessageType.Unsubscribe, queryId });\n }\n\n // If no subscriptions remain, close the connection to free resources.\n if (this._subscriptions.size === 0) {\n this.close();\n }\n }\n\n /**\n * Permanently close this hub connection and clean up all subscriptions.\n */\n dispose(): void {\n this._disconnected = true;\n this._subscriptions.clear();\n this._keepAlive.stop();\n this._policy.cancel();\n this._socket?.close();\n this._socket = undefined;\n }\n\n private ensureConnected(): void {\n if (this._disconnected) {\n // Reset disconnected flag when a new subscription comes in\n this._disconnected = false;\n }\n\n if (this._socket && (this._socket.readyState === WebSocket.OPEN || this._socket.readyState === WebSocket.CONNECTING)) {\n return;\n }\n\n this.openSocket();\n }\n\n private close(): void {\n this._disconnected = true;\n this._keepAlive.stop();\n this._policy.cancel();\n if (this._socket) {\n // Detach all handlers BEFORE closing so that the async onclose event cannot\n // fire after a new subscription has reset _disconnected to false and opened a\n // fresh socket. Without this, the stale onclose triggers an unintended\n // reconnect via the back-off policy, causing a 1-10 second delay before the\n // new page's queries receive their first data.\n this._socket.onopen = null;\n this._socket.onclose = null;\n this._socket.onerror = null;\n this._socket.onmessage = null;\n this._socket.close();\n }\n this._socket = undefined;\n }\n\n private openSocket(): void {\n let url = this._url;\n if (this._microservice?.length > 0) {\n const param = `${Globals.microserviceWSQueryArgument}=${encodeURIComponent(this._microservice)}`;\n url += (url.includes('?') ? '&' : '?') + param;\n }\n\n this._socket = new WebSocket(url);\n\n this._socket.onopen = () => {\n if (this._disconnected) return;\n console.log(`Hub connection established: '${url}'`);\n this._policy.reset();\n this._keepAlive.start();\n this.sendAllSubscriptions();\n };\n\n this._socket.onclose = () => {\n if (this._disconnected) return;\n console.log(`Hub connection closed: '${url}'`);\n this._keepAlive.stop();\n if (this._subscriptions.size === 0) return;\n this._policy.schedule(() => {\n if (!this._disconnected && this._subscriptions.size > 0) {\n this.openSocket();\n }\n }, this._url);\n };\n\n this._socket.onerror = (error) => {\n if (this._disconnected) return;\n console.error(`Hub connection error: '${url}'`, error);\n this._keepAlive.stop();\n // onclose will fire after onerror, triggering reconnect\n };\n\n this._socket.onmessage = (ev) => {\n if (this._disconnected) return;\n this.handleMessage(ev.data as string);\n };\n }\n\n private sendAllSubscriptions(): void {\n for (const [queryId, sub] of this._subscriptions) {\n this.sendSubscribeMessage(queryId, sub.request);\n }\n }\n\n private sendSubscribeMessage(queryId: string, request: SubscriptionRequest): void {\n this.sendMessage({\n type: HubMessageType.Subscribe,\n queryId,\n payload: request,\n });\n }\n\n private sendMessage(message: HubMessage): void {\n if (this._socket?.readyState === WebSocket.OPEN) {\n this._socket.send(JSON.stringify(message));\n }\n }\n\n private handleMessage(rawData: string): void {\n try {\n const message = JSON.parse(rawData) as HubMessage;\n\n // Every received message is activity — skip keep-alive ping if data is flowing.\n this._keepAlive.recordActivity();\n\n switch (message.type) {\n case HubMessageType.QueryResult:\n this.handleQueryResult(message);\n break;\n case HubMessageType.Pong:\n this.handlePong(message);\n break;\n case HubMessageType.Unauthorized:\n console.warn(`Hub: query '${message.queryId}' unauthorized`);\n this.handleUnauthorized(message);\n break;\n case HubMessageType.Error:\n console.error(`Hub: query '${message.queryId}' error:`, message.payload);\n break;\n }\n } catch (error) {\n console.error('Hub: error parsing message', error);\n }\n }\n\n private handleQueryResult(message: HubMessage): void {\n if (!message.queryId) return;\n\n const sub = this._subscriptions.get(message.queryId);\n if (!sub) return;\n\n const result = message.payload as QueryResult<any>;\n sub.callback(result);\n }\n\n private handleUnauthorized(message: HubMessage): void {\n if (!message.queryId) return;\n\n const sub = this._subscriptions.get(message.queryId);\n if (!sub) return;\n\n this._subscriptions.delete(message.queryId);\n sub.callback(QueryResult.unauthorized());\n }\n\n private handlePong(message: HubMessage): void {\n if (message.timestamp && this._lastPingSentTime) {\n const latency = Date.now() - message.timestamp;\n this._lastPongLatency = latency;\n this._latencySamples.push(latency);\n\n if (this._latencySamples.length > 100) {\n this._latencySamples.shift();\n }\n }\n }\n}\n"],"names":["HubMessageType","WebSocketHubConnection","_socket","_disconnected","_subscriptions","Map","_keepAlive","_lastPingSentTime","_lastPongLatency","_latencySamples","_url","pingIntervalMs","_policy","ReconnectPolicy","_microservice","HubConnectionKeepAlive","readyState","WebSocket","OPEN","Date","now","sendMessage","type","timestamp","queryCount","size","isConnected","lastPingLatency","averageLatency","length","reduce","a","b","subscribe","queryId","request","callback","set","ensureConnected","sendSubscribeMessage","unsubscribe","delete","close","dispose","clear","stop","cancel","undefined","CONNECTING","openSocket","onopen","onclose","onerror","onmessage","url","param","Globals","microserviceWSQueryArgument","encodeURIComponent","includes","console","log","reset","start","sendAllSubscriptions","schedule","error","ev","handleMessage","data","sub","payload","message","send","JSON","stringify","rawData","parse","recordActivity","handleQueryResult","handlePong","warn","handleUnauthorized","get","result","QueryResult","unauthorized","latency","push","shift"],"mappings":";;;;;;;AAAA;AACA;AASA;;;IAMO,IAAKA,cAAAA,iBAAAA,SAAAA,cAAAA,EAAAA;;;;;;;;;AAAAA,IAAAA,OAAAA,cAAAA;AASX,CAAA,CAAA,EAAA;AAoCD;;;;;;;AAOC,IACM,MAAMC,sBAAAA,CAAAA;;;;IACDC,OAAAA;AACAC,IAAAA,aAAAA,GAAgB,KAAA;AAChBC,IAAAA,cAAAA,GAAkD,IAAIC,GAAAA,EAAAA;IAC7CC,UAAAA;IACTC,iBAAAA;AACAC,IAAAA,gBAAAA,GAA2B,CAAA;AAC3BC,IAAAA,eAAAA,GAA4B,EAAE;AAEtC;;;;;;AAMC,QACD,WAAA,CACqBC,IAAY,EAC7B,aAAsC,EACtCC,cAAAA,GAAyB,KAAK,EACbC,OAAAA,GAA4B,IAAIC,iCAAiB,CACpE;aAJmBH,IAAAA,GAAAA,IAAAA;aACAI,aAAAA,GAAAA,aAAAA;aAEAF,OAAAA,GAAAA,OAAAA;AAEjB,QAAA,IAAI,CAACN,UAAU,GAAG,IAAIS,8CAAuBJ,cAAAA,EAAgB,IAAA;AACzD,YAAA,IAAI,IAAI,CAACT,OAAO,EAAEc,UAAAA,KAAeC,SAAAA,CAAUC,IAAI,EAAE;AAC7C,gBAAA,IAAI,CAACX,iBAAiB,GAAGY,IAAAA,CAAKC,GAAG,EAAA;gBACjC,IAAI,CAACC,WAAW,CAAC;o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= require('./WebSocketMessage.js');
|
|
27
27
|
var QueryTransportMethod = require('./QueryTransportMethod.js');
|
|
28
28
|
var QueryInstanceCache = require('./QueryInstanceCache.js');
|
|
29
|
+
var reconcileQueryData = require('./reconcileQueryData.js');
|
|
29
30
|
var IQueryProvider = require('./IQueryProvider.js');
|
|
30
31
|
var QueryProvider = require('./QueryProvider.js');
|
|
31
32
|
var QueryValidator = require('./QueryValidator.js');
|
|
@@ -73,6 +74,7 @@ exports.ObservableQuerySubscription = ObservableQuerySubscription.ObservableQuer
|
|
|
73
74
|
exports.WebSocketMessageType = WebSocketMessage.WebSocketMessageType;
|
|
74
75
|
exports.QueryTransportMethod = QueryTransportMethod.QueryTransportMethod;
|
|
75
76
|
exports.QueryInstanceCache = QueryInstanceCache.QueryInstanceCache;
|
|
77
|
+
exports.reconcileQueryData = reconcileQueryData.reconcileQueryData;
|
|
76
78
|
exports.IQueryProvider = IQueryProvider.IQueryProvider;
|
|
77
79
|
exports.QueryProvider = QueryProvider.QueryProvider;
|
|
78
80
|
exports.QueryValidator = QueryValidator.QueryValidator;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","sources":["../../../queries/index.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\nexport * from './ChangeSet';\nexport * from './IChangeStreamFor';\nexport * from './IQuery';\nexport * from './IQueryFor';\nexport * from './Paging';\nexport * from './Sorting';\nexport * from './SortDirection';\nexport * from './SortingActions';\nexport * from './SortingActionsForQuery';\nexport * from './SortingActionsForObservableQuery';\nexport * from './QueryFor';\nexport * from './QueryHttpMethod';\nexport * from './QueryHttpMethodResolver';\nexport * from './QueryHttpRequest';\nexport * from './QueryResult';\nexport * from './QueryResultWithState';\nexport * from './IObservableQueryFor';\nexport * from './ObservableQueryFor';\nexport * from './IObservableQueryConnection';\nexport * from './IObservableQueryHubConnection';\nexport * from './IReconnectPolicy';\nexport * from './ReconnectPolicy';\nexport * from './HubConnectionKeepAlive';\nexport * from './ObservableQueryConnection';\nexport * from './ObservableQueryConnectionFactory';\nexport * from './ObservableQueryConnectionPool';\nexport * from './ServerSentEventQueryConnection';\nexport * from './ServerSentEventHubConnection';\nexport * from './WebSocketHubConnection';\nexport * from './ObservableQueryMultiplexer';\nexport * from './ObservableQuerySubscription';\nexport * from './WebSocketMessage';\nexport * from './QueryTransportMethod';\nexport * from './QueryInstanceCache';\nexport * from './IQueryProvider';\nexport * from './QueryProvider';\nexport * from './QueryValidator';\nexport * from './IObservableQueryDiagnostics';\nexport * from './ObservableQueryDiagnostics';\nexport * from './ObservableQueryDiagnosticsSnapshot';\nimport '../validation';"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"index.js","sources":["../../../queries/index.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\nexport * from './ChangeSet';\nexport * from './IChangeStreamFor';\nexport * from './IQuery';\nexport * from './IQueryFor';\nexport * from './Paging';\nexport * from './Sorting';\nexport * from './SortDirection';\nexport * from './SortingActions';\nexport * from './SortingActionsForQuery';\nexport * from './SortingActionsForObservableQuery';\nexport * from './QueryFor';\nexport * from './QueryHttpMethod';\nexport * from './QueryHttpMethodResolver';\nexport * from './QueryHttpRequest';\nexport * from './QueryResult';\nexport * from './QueryResultWithState';\nexport * from './IObservableQueryFor';\nexport * from './ObservableQueryFor';\nexport * from './IObservableQueryConnection';\nexport * from './IObservableQueryHubConnection';\nexport * from './IReconnectPolicy';\nexport * from './ReconnectPolicy';\nexport * from './HubConnectionKeepAlive';\nexport * from './ObservableQueryConnection';\nexport * from './ObservableQueryConnectionFactory';\nexport * from './ObservableQueryConnectionPool';\nexport * from './ServerSentEventQueryConnection';\nexport * from './ServerSentEventHubConnection';\nexport * from './WebSocketHubConnection';\nexport * from './ObservableQueryMultiplexer';\nexport * from './ObservableQuerySubscription';\nexport * from './WebSocketMessage';\nexport * from './QueryTransportMethod';\nexport * from './QueryInstanceCache';\nexport * from './reconcileQueryData';\nexport * from './IQueryProvider';\nexport * from './QueryProvider';\nexport * from './QueryValidator';\nexport * from './IObservableQueryDiagnostics';\nexport * from './ObservableQueryDiagnostics';\nexport * from './ObservableQueryDiagnosticsSnapshot';\nimport '../validation';"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AACA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;"}
|
|
@@ -0,0 +1,84 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
var deepEqual = require('../deepEqual.js');
|
|
4
|
+
|
|
5
|
+
// Copyright (c) Cratis. All rights reserved.
|
|
6
|
+
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
|
|
7
|
+
/**
|
|
8
|
+
* Resolves the conventional identity of an item so it can be matched against its previous version.
|
|
9
|
+
*
|
|
10
|
+
* Uses the `id` property, the same strategy the server-side change-set computation applies, and
|
|
11
|
+
* reduces concept-style identities (objects with a meaningful `toString()`) to a comparable value.
|
|
12
|
+
* @param {unknown} item The item to resolve identity for.
|
|
13
|
+
* @returns {unknown} The identity value, or `undefined` when the item carries no usable identity.
|
|
14
|
+
*/ function getIdentity(item) {
|
|
15
|
+
const id = item?.id;
|
|
16
|
+
if (id === null || id === undefined) {
|
|
17
|
+
return undefined;
|
|
18
|
+
}
|
|
19
|
+
if (typeof id === 'object') {
|
|
20
|
+
const stringValue = id.toString();
|
|
21
|
+
return stringValue !== '[object Object]' ? stringValue : JSON.stringify(id);
|
|
22
|
+
}
|
|
23
|
+
return id;
|
|
24
|
+
}
|
|
25
|
+
/**
|
|
26
|
+
* Reconciles a full payload against the previous one, carrying over the previous object references
|
|
27
|
+
* for every item that did not actually change.
|
|
28
|
+
*
|
|
29
|
+
* Observable queries re-deliver a complete snapshot whenever a subscription is (re-)established.
|
|
30
|
+
* Deserializing that snapshot produces entirely new object references, so consumers that compare by
|
|
31
|
+
* reference — memoized components, effect dependencies — treat every item as changed even when the
|
|
32
|
+
* payload is identical to what they already display. Reconciling restores referential stability:
|
|
33
|
+
* unchanged items keep their previous reference, and when nothing changed at all the previous
|
|
34
|
+
* payload itself is returned so callers can detect "no change" with a single `===`.
|
|
35
|
+
*
|
|
36
|
+
* Items are matched by their `id` when present, falling back to position for identity-less items.
|
|
37
|
+
* @template T The payload type.
|
|
38
|
+
* @param {T} previous The payload currently held.
|
|
39
|
+
* @param {T} next The freshly received payload.
|
|
40
|
+
* @returns {T} `previous` when nothing changed; otherwise the new payload with unchanged items carried over by reference.
|
|
41
|
+
*/ function reconcileQueryData(previous, next) {
|
|
42
|
+
if (previous === next) {
|
|
43
|
+
return previous;
|
|
44
|
+
}
|
|
45
|
+
if (Array.isArray(previous) && Array.isArray(next)) {
|
|
46
|
+
return reconcileArray(previous, next);
|
|
47
|
+
}
|
|
48
|
+
return deepEqual.deepEqual(previous, next) ? previous : next;
|
|
49
|
+
}
|
|
50
|
+
/**
|
|
51
|
+
* Reconciles two arrays element by element, preserving previous references for unchanged items.
|
|
52
|
+
* @param {unknown[]} previous The array currently held.
|
|
53
|
+
* @param {unknown[]} next The freshly received array.
|
|
54
|
+
* @returns {unknown[]} `previous` when the arrays are equivalent; otherwise a new array reusing unchanged items.
|
|
55
|
+
*/ function reconcileArray(previous, next) {
|
|
56
|
+
const previousByIdentity = new Map();
|
|
57
|
+
for (const item of previous){
|
|
58
|
+
const identity = getIdentity(item);
|
|
59
|
+
// Keep the first occurrence — duplicate identities are not a shape we can reconcile
|
|
60
|
+
// meaningfully, and preferring the first keeps the result deterministic.
|
|
61
|
+
if (identity !== undefined && !previousByIdentity.has(identity)) {
|
|
62
|
+
previousByIdentity.set(identity, item);
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
let changed = previous.length !== next.length;
|
|
66
|
+
const reconciled = next.map((item, index)=>{
|
|
67
|
+
const identity = getIdentity(item);
|
|
68
|
+
const candidate = identity !== undefined ? previousByIdentity.get(identity) : previous[index];
|
|
69
|
+
if (candidate !== undefined && deepEqual.deepEqual(candidate, item)) {
|
|
70
|
+
// An unchanged item that moved still leaves the collection changed as a whole, but the
|
|
71
|
+
// item itself keeps its reference so only the ordering re-renders, not its content.
|
|
72
|
+
if (candidate !== previous[index]) {
|
|
73
|
+
changed = true;
|
|
74
|
+
}
|
|
75
|
+
return candidate;
|
|
76
|
+
}
|
|
77
|
+
changed = true;
|
|
78
|
+
return item;
|
|
79
|
+
});
|
|
80
|
+
return changed ? reconciled : previous;
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
exports.reconcileQueryData = reconcileQueryData;
|
|
84
|
+
//# sourceMappingURL=reconcileQueryData.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"reconcileQueryData.js","sources":["../../../queries/reconcileQueryData.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 { deepEqual } from '../deepEqual';\n\n/**\n * Resolves the conventional identity of an item so it can be matched against its previous version.\n *\n * Uses the `id` property, the same strategy the server-side change-set computation applies, and\n * reduces concept-style identities (objects with a meaningful `toString()`) to a comparable value.\n * @param {unknown} item The item to resolve identity for.\n * @returns {unknown} The identity value, or `undefined` when the item carries no usable identity.\n */\nfunction getIdentity(item: unknown): unknown {\n const id = (item as Record<string, unknown>)?.id;\n\n if (id === null || id === undefined) {\n return undefined;\n }\n\n if (typeof id === 'object') {\n const stringValue = id.toString();\n return stringValue !== '[object Object]' ? stringValue : JSON.stringify(id);\n }\n\n return id;\n}\n\n/**\n * Reconciles a full payload against the previous one, carrying over the previous object references\n * for every item that did not actually change.\n *\n * Observable queries re-deliver a complete snapshot whenever a subscription is (re-)established.\n * Deserializing that snapshot produces entirely new object references, so consumers that compare by\n * reference — memoized components, effect dependencies — treat every item as changed even when the\n * payload is identical to what they already display. Reconciling restores referential stability:\n * unchanged items keep their previous reference, and when nothing changed at all the previous\n * payload itself is returned so callers can detect \"no change\" with a single `===`.\n *\n * Items are matched by their `id` when present, falling back to position for identity-less items.\n * @template T The payload type.\n * @param {T} previous The payload currently held.\n * @param {T} next The freshly received payload.\n * @returns {T} `previous` when nothing changed; otherwise the new payload with unchanged items carried over by reference.\n */\nexport function reconcileQueryData<T>(previous: T, next: T): T {\n if (previous === next) {\n return previous;\n }\n\n if (Array.isArray(previous) && Array.isArray(next)) {\n return reconcileArray(previous, next) as T;\n }\n\n return deepEqual(previous, next) ? previous : next;\n}\n\n/**\n * Reconciles two arrays element by element, preserving previous references for unchanged items.\n * @param {unknown[]} previous The array currently held.\n * @param {unknown[]} next The freshly received array.\n * @returns {unknown[]} `previous` when the arrays are equivalent; otherwise a new array reusing unchanged items.\n */\nfunction reconcileArray(previous: unknown[], next: unknown[]): unknown[] {\n const previousByIdentity = new Map<unknown, unknown>();\n\n for (const item of previous) {\n const identity = getIdentity(item);\n\n // Keep the first occurrence — duplicate identities are not a shape we can reconcile\n // meaningfully, and preferring the first keeps the result deterministic.\n if (identity !== undefined && !previousByIdentity.has(identity)) {\n previousByIdentity.set(identity, item);\n }\n }\n\n let changed = previous.length !== next.length;\n\n const reconciled = next.map((item, index) => {\n const identity = getIdentity(item);\n const candidate = identity !== undefined ? previousByIdentity.get(identity) : previous[index];\n\n if (candidate !== undefined && deepEqual(candidate, item)) {\n // An unchanged item that moved still leaves the collection changed as a whole, but the\n // item itself keeps its reference so only the ordering re-renders, not its content.\n if (candidate !== previous[index]) {\n changed = true;\n }\n\n return candidate;\n }\n\n changed = true;\n return item;\n });\n\n return changed ? reconciled : previous;\n}\n"],"names":["getIdentity","item","id","undefined","stringValue","toString","JSON","stringify","reconcileQueryData","previous","next","Array","isArray","reconcileArray","deepEqual","previousByIdentity","Map","identity","has","set","changed","length","reconciled","map","index","candidate","get"],"mappings":";;;;AAAA;AACA;AAIA;;;;;;;IAQA,SAASA,YAAYC,IAAa,EAAA;AAC9B,IAAA,MAAMC,KAAMD,IAAAA,EA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AAE7C,IAAA,MAAMC,UAAAA,GAAaZ,IAAAA,CAAKa,GAAG,CAAC,CAACtB,IAAAA,EAAMuB,KAAAA,GAAAA;AAC/B,QAAA,MAAMP,WAAWjB,WAAAA,CAAYC,IAAAA,CAAAA;QAC7B,MAAMwB,SAAAA,GAAYR,aAAad,SAAAA,GAAYY,kBAAAA,CAAmBW,GAAG,CAACT,QAAAA,CAAAA,GAAYR,QAAQ,CAACe,KAAAA,CAAM;AAE7F,QAAA,IAAIC,SAAAA,KAActB,SAAAA,IAAaW,mBAAAA,CAAUW,SAAAA,EAAWxB,IAAAA,CAAAA,EAAO;;;AAGvD,YAAA,IAAIwB,SAAAA,KAAchB,QAAQ,CAACe,KAAAA,CAAM,EAAE;gBAC/BJ,OAAAA,GAAU,IAAA;AACd,YAAA;YAEA,OAAOK,SAAAA;AACX,QAAA;QAEAL,OAAAA,GAAU,IAAA;QACV,OAAOnB,IAAAA;AACX,IAAA,CAAA,CAAA;AAEA,IAAA,OAAOmB,UAAUE,UAAAA,GAAab,QAAAA;AAClC;;;;"}
|
|
@@ -1,10 +1,12 @@
|
|
|
1
1
|
export declare class HubConnectionKeepAlive {
|
|
2
|
-
private readonly _intervalMs;
|
|
3
2
|
private readonly _onIdle;
|
|
4
3
|
private _lastActivityTime;
|
|
5
4
|
private _timer?;
|
|
6
|
-
private
|
|
7
|
-
|
|
5
|
+
private _intervalMs;
|
|
6
|
+
private _idleThresholdMs;
|
|
7
|
+
constructor(intervalMs: number, _onIdle: () => void, idleThresholdMs?: number);
|
|
8
|
+
get idleThresholdMs(): number;
|
|
9
|
+
reconfigure(intervalMs: number, idleThresholdMs: number): void;
|
|
8
10
|
start(): void;
|
|
9
11
|
stop(): void;
|
|
10
12
|
recordActivity(): void;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"HubConnectionKeepAlive.d.ts","sourceRoot":"","sources":["../../../queries/HubConnectionKeepAlive.ts"],"names":[],"mappings":"AAqBA,qBAAa,sBAAsB;
|
|
1
|
+
{"version":3,"file":"HubConnectionKeepAlive.d.ts","sourceRoot":"","sources":["../../../queries/HubConnectionKeepAlive.ts"],"names":[],"mappings":"AAqBA,qBAAa,sBAAsB;IAkB3B,OAAO,CAAC,QAAQ,CAAC,OAAO;IAjB5B,OAAO,CAAC,iBAAiB,CAAc;IACvC,OAAO,CAAC,MAAM,CAAC,CAAiC;IAChD,OAAO,CAAC,WAAW,CAAS;IAC5B,OAAO,CAAC,gBAAgB,CAAS;IAYjC,YACI,UAAU,EAAE,MAAM,EACD,OAAO,EAAE,MAAM,IAAI,EACpC,eAAe,CAAC,EAAE,MAAM,EAI3B;IAKD,IAAI,eAAe,IAAI,MAAM,CAE5B;IAUD,WAAW,CAAC,UAAU,EAAE,MAAM,EAAE,eAAe,EAAE,MAAM,GAAG,IAAI,CAQ7D;IAKD,KAAK,IAAI,IAAI,CAQZ;IAKD,IAAI,IAAI,IAAI,CAKX;IAMD,cAAc,IAAI,IAAI,CAErB;CACJ"}
|
|
@@ -18,10 +18,10 @@
|
|
|
18
18
|
* of this class so the keep-alive logic is written once and behaves identically for both
|
|
19
19
|
* transports.
|
|
20
20
|
*/ class HubConnectionKeepAlive {
|
|
21
|
-
_intervalMs;
|
|
22
21
|
_onIdle;
|
|
23
22
|
_lastActivityTime = Date.now();
|
|
24
23
|
_timer;
|
|
24
|
+
_intervalMs;
|
|
25
25
|
_idleThresholdMs;
|
|
26
26
|
/**
|
|
27
27
|
* Initializes a new instance of {@link HubConnectionKeepAlive}.
|
|
@@ -32,10 +32,30 @@
|
|
|
32
32
|
* before the connection is considered idle. Defaults to {@link intervalMs}. Set this
|
|
33
33
|
* higher than {@link intervalMs} when the peer sends keep-alive messages on a similar
|
|
34
34
|
* cadence to account for network latency and timer jitter.
|
|
35
|
-
*/ constructor(
|
|
36
|
-
this._intervalMs = _intervalMs;
|
|
35
|
+
*/ constructor(intervalMs, _onIdle, idleThresholdMs){
|
|
37
36
|
this._onIdle = _onIdle;
|
|
38
|
-
this.
|
|
37
|
+
this._intervalMs = intervalMs;
|
|
38
|
+
this._idleThresholdMs = idleThresholdMs ?? intervalMs;
|
|
39
|
+
}
|
|
40
|
+
/**
|
|
41
|
+
* Gets how long (in milliseconds) without activity before the connection is considered idle.
|
|
42
|
+
*/ get idleThresholdMs() {
|
|
43
|
+
return this._idleThresholdMs;
|
|
44
|
+
}
|
|
45
|
+
/**
|
|
46
|
+
* Change the check interval and idle threshold, restarting the timer when it is already running.
|
|
47
|
+
*
|
|
48
|
+
* Used when the peer advertises its actual keep-alive cadence after connecting, so the client
|
|
49
|
+
* stops relying on an assumed default that may not match the server's configuration.
|
|
50
|
+
* @param {number} intervalMs How often (in milliseconds) to check for idle connections.
|
|
51
|
+
* @param {number} idleThresholdMs How long (in milliseconds) without activity before the connection is considered idle.
|
|
52
|
+
*/ reconfigure(intervalMs, idleThresholdMs) {
|
|
53
|
+
const wasRunning = this._timer !== undefined;
|
|
54
|
+
this._intervalMs = intervalMs;
|
|
55
|
+
this._idleThresholdMs = idleThresholdMs;
|
|
56
|
+
if (wasRunning) {
|
|
57
|
+
this.start();
|
|
58
|
+
}
|
|
39
59
|
}
|
|
40
60
|
/**
|
|
41
61
|
* Start the keep-alive timer. Safe to call multiple times — a running timer is stopped first.
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"HubConnectionKeepAlive.js","sources":["../../../queries/HubConnectionKeepAlive.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\n/**\n * Manages keep-alive behavior for hub connections (both WebSocket and Server-Sent Events).\n *\n * Records connection activity (any message received or sent). An interval fires every\n * {@link intervalMs} milliseconds; if no activity has been recorded since the last\n * {@link idleThresholdMs} milliseconds the provided {@link onIdle} callback is invoked —\n * the caller decides whether to send a ping, trigger a reconnect, or take some other action.\n *\n * The idle threshold defaults to the check interval but can be set higher to tolerate\n * network latency between the server's keep-alive ping and the client's idle check.\n * For SSE connections, where the idle callback triggers a reconnect, a tolerance of\n * 1.5× the server's keep-alive interval prevents spurious reconnects caused by the\n * client's timer firing just before the server's ping arrives.\n *\n * Both {@link WebSocketHubConnection} and {@link ServerSentEventHubConnection} own one instance\n * of this class so the keep-alive logic is written once and behaves identically for both\n * transports.\n */\nexport class HubConnectionKeepAlive {\n private _lastActivityTime = Date.now();\n private _timer?: ReturnType<typeof setInterval>;\n private
|
|
1
|
+
{"version":3,"file":"HubConnectionKeepAlive.js","sources":["../../../queries/HubConnectionKeepAlive.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\n/**\n * Manages keep-alive behavior for hub connections (both WebSocket and Server-Sent Events).\n *\n * Records connection activity (any message received or sent). An interval fires every\n * {@link intervalMs} milliseconds; if no activity has been recorded since the last\n * {@link idleThresholdMs} milliseconds the provided {@link onIdle} callback is invoked —\n * the caller decides whether to send a ping, trigger a reconnect, or take some other action.\n *\n * The idle threshold defaults to the check interval but can be set higher to tolerate\n * network latency between the server's keep-alive ping and the client's idle check.\n * For SSE connections, where the idle callback triggers a reconnect, a tolerance of\n * 1.5× the server's keep-alive interval prevents spurious reconnects caused by the\n * client's timer firing just before the server's ping arrives.\n *\n * Both {@link WebSocketHubConnection} and {@link ServerSentEventHubConnection} own one instance\n * of this class so the keep-alive logic is written once and behaves identically for both\n * transports.\n */\nexport class HubConnectionKeepAlive {\n private _lastActivityTime = Date.now();\n private _timer?: ReturnType<typeof setInterval>;\n private _intervalMs: number;\n private _idleThresholdMs: number;\n\n /**\n * Initializes a new instance of {@link HubConnectionKeepAlive}.\n * @param {number} intervalMs How often (in milliseconds) to check for idle connections.\n * @param {() => void} onIdle Callback invoked when the interval fires and no activity has\n * been recorded within the idle threshold.\n * @param {number} idleThresholdMs Optional. How long (in milliseconds) without activity\n * before the connection is considered idle. Defaults to {@link intervalMs}. Set this\n * higher than {@link intervalMs} when the peer sends keep-alive messages on a similar\n * cadence to account for network latency and timer jitter.\n */\n constructor(\n intervalMs: number,\n private readonly _onIdle: () => void,\n idleThresholdMs?: number,\n ) {\n this._intervalMs = intervalMs;\n this._idleThresholdMs = idleThresholdMs ?? intervalMs;\n }\n\n /**\n * Gets how long (in milliseconds) without activity before the connection is considered idle.\n */\n get idleThresholdMs(): number {\n return this._idleThresholdMs;\n }\n\n /**\n * Change the check interval and idle threshold, restarting the timer when it is already running.\n *\n * Used when the peer advertises its actual keep-alive cadence after connecting, so the client\n * stops relying on an assumed default that may not match the server's configuration.\n * @param {number} intervalMs How often (in milliseconds) to check for idle connections.\n * @param {number} idleThresholdMs How long (in milliseconds) without activity before the connection is considered idle.\n */\n reconfigure(intervalMs: number, idleThresholdMs: number): void {\n const wasRunning = this._timer !== undefined;\n this._intervalMs = intervalMs;\n this._idleThresholdMs = idleThresholdMs;\n\n if (wasRunning) {\n this.start();\n }\n }\n\n /**\n * Start the keep-alive timer. Safe to call multiple times — a running timer is stopped first.\n */\n start(): void {\n this.stop();\n this._lastActivityTime = Date.now();\n this._timer = setInterval(() => {\n if (Date.now() - this._lastActivityTime >= this._idleThresholdMs) {\n this._onIdle();\n }\n }, this._intervalMs);\n }\n\n /**\n * Stop the keep-alive timer.\n */\n stop(): void {\n if (this._timer !== undefined) {\n clearInterval(this._timer);\n this._timer = undefined;\n }\n }\n\n /**\n * Record that the connection has been active (message sent or received).\n * Resets the idle timer so that a keep-alive is not sent while data is already flowing.\n */\n recordActivity(): void {\n this._lastActivityTime = Date.now();\n }\n}\n"],"names":["HubConnectionKeepAlive","_lastActivityTime","Date","now","_timer","_intervalMs","_idleThresholdMs","intervalMs","idleThresholdMs","_onIdle","reconfigure","wasRunning","undefined","start","stop","setInterval","clearInterval","recordActivity"],"mappings":"AAAA;AACA;AAEA;;;;;;;;;;;;;;;;;AAiBC,IACM,MAAMA,sBAAAA,CAAAA;;IACDC,iBAAAA,GAAoBC,IAAAA,CAAKC,GAAG,EAAA;IAC5BC,MAAAA;IACAC,WAAAA;IACAC,g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B;AACnB,QAAA,IAAI,CAAChB,iBAAiB,GAAGC,IAAAA,CAAKC,GAAG,EAAA;AACrC,IAAA;AACJ;;;;"}
|
|
@@ -1,8 +1,10 @@
|
|
|
1
1
|
import { DataReceived } from './ObservableQueryConnection';
|
|
2
2
|
import { IObservableQueryConnection } from './IObservableQueryConnection';
|
|
3
|
+
import { QueryResult } from './QueryResult';
|
|
3
4
|
export declare class NullObservableQueryConnection<TDataType> implements IObservableQueryConnection<TDataType> {
|
|
4
5
|
readonly defaultValue: TDataType;
|
|
5
|
-
|
|
6
|
+
readonly result?: QueryResult<TDataType> | undefined;
|
|
7
|
+
constructor(defaultValue: TDataType, result?: QueryResult<TDataType> | undefined);
|
|
6
8
|
get lastPingLatency(): number;
|
|
7
9
|
get averageLatency(): number;
|
|
8
10
|
connect(dataReceived: DataReceived<TDataType>): void;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"NullObservableQueryConnection.d.ts","sourceRoot":"","sources":["../../../queries/NullObservableQueryConnection.ts"],"names":[],"mappings":"AAGA,OAAO,EAAE,YAAY,EAAE,MAAM,6BAA6B,CAAC;AAC3D,OAAO,EAAE,0BAA0B,EAAE,MAAM,8BAA8B,CAAC;
|
|
1
|
+
{"version":3,"file":"NullObservableQueryConnection.d.ts","sourceRoot":"","sources":["../../../queries/NullObservableQueryConnection.ts"],"names":[],"mappings":"AAGA,OAAO,EAAE,YAAY,EAAE,MAAM,6BAA6B,CAAC;AAC3D,OAAO,EAAE,0BAA0B,EAAE,MAAM,8BAA8B,CAAC;AAC1E,OAAO,EAAE,WAAW,EAAE,MAAM,eAAe,CAAC;AAM5C,qBAAa,6BAA6B,CAAC,SAAS,CAAE,YAAW,0BAA0B,CAAC,SAAS,CAAC;IAQtF,QAAQ,CAAC,YAAY,EAAE,SAAS;IAAE,QAAQ,CAAC,MAAM,CAAC,EAAE,WAAW,CAAC,SAAS,CAAC;IAAtF,YAAqB,YAAY,EAAE,SAAS,EAAW,MAAM,CAAC,EAAE,WAAW,CAAC,SAAS,CAAC,YAAA,EACrF;IAGD,IAAI,eAAe,IAAI,MAAM,CAE5B;IAGD,IAAI,cAAc,IAAI,MAAM,CAE3B;IAGD,OAAO,CAAC,YAAY,EAAE,YAAY,CAAC,SAAS,CAAC,QAE5C;IAID,UAAU,SACT;CACJ"}
|