cli-setu 0.3.2 → 0.3.3

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.
@@ -0,0 +1,155 @@
1
+ // Provider-specific connection framing. Azure Web PubSub needs NONE of
2
+ // this - a plain WebSocket, opened with a URL that already carries a
3
+ // scoped access token, is immediately ready to send/receive. Ably's own
4
+ // raw WebSocket endpoint (confirmed real and working via direct
5
+ // research, see ablyAdapter.js's own header comment on the backend)
6
+ // needs one extra step: after the socket opens, the client must wait
7
+ // for Ably's CONNECTED handshake, then send one ATTACH ProtocolMessage
8
+ // to join the channel, then wait for ATTACHED before the connection is
9
+ // actually ready to receive anything - Azure's groups need no
10
+ // equivalent client-side step at all (group membership is entirely
11
+ // server-side there).
12
+ //
13
+ // This module exists so that difference lives in ONE place, not
14
+ // scattered through supervisor.js's existing message-handling code
15
+ // (which stays completely untouched for the Azure case - see
16
+ // supervisor.js's own call site for how this wraps around the existing
17
+ // `new WebSocket(...)` + `ws.on('open'/'message')` pattern rather than
18
+ // replacing it).
19
+ //
20
+ // Wire format confirmed via direct research cross-checking TWO
21
+ // independent sources (Ably's own published protocol spec AND the
22
+ // ably-js SDK's literal source code for the numeric action constants -
23
+ // both agreed field-for-field, number-for-number):
24
+ // CONNECTED = 4, ERROR = 9, ATTACH = 10, ATTACHED = 11, MESSAGE = 15
25
+ // A real published message arrives as
26
+ // { action: 15, channel, messages: [{ data, ... }, ...] }
27
+ // - note `messages` is an ARRAY (a single publish can batch several
28
+ // messages), so every one must be delivered to the caller, not just the
29
+ // first.
30
+ const ABLY_ACTION = {
31
+ CONNECTED: 4,
32
+ ERROR: 9,
33
+ ATTACH: 10,
34
+ ATTACHED: 11,
35
+ MESSAGE: 15,
36
+ };
37
+
38
+ // Azure Web PubSub's own wssUrl looks like
39
+ // wss://<name>.webpubsub.azure.com/client/hubs/<hub>?access_token=...
40
+ // Ably's raw endpoint (see ablyAdapter.js) is always exactly
41
+ // wss://realtime.ably.io/?access_token=...&v=6&format=json - checking
42
+ // the hostname is simpler and more robust than parsing query params,
43
+ // and matches exactly how the backend actually mints each provider's
44
+ // URL today (never guessing at a shape neither provider actually uses).
45
+ function detectProvider(wssUrl) {
46
+ try {
47
+ const host = new URL(wssUrl).hostname;
48
+ if (host === 'realtime.ably.io') return 'ably';
49
+ return 'azure';
50
+ } catch {
51
+ return 'azure'; // malformed URL - let the existing Azure path's own error handling surface this, same as before this module existed
52
+ }
53
+ }
54
+
55
+ // Wraps a freshly-constructed `ws` WebSocket instance (already
56
+ // `new WebSocket(wssUrl)`-created by the caller, not yet opened) so that
57
+ // for Ably, the caller's own `onReady` callback only fires once the
58
+ // ATTACH/ATTACHED handshake has actually completed - not just on the
59
+ // raw socket's own 'open' event, which for Ably is NOT yet enough to
60
+ // safely assume messages will be delivered. For Azure, onReady fires
61
+ // exactly where it always did (immediately on 'open'), so existing
62
+ // Azure behavior is completely unchanged.
63
+ //
64
+ // onMessage(payload) is called once per real application-level message
65
+ // (already unwrapped from Ably's own `messages[]` envelope, or passed
66
+ // straight through unchanged for Azure) - the caller's existing
67
+ // `JSON.parse` + `msg.type === ...` handling needs no changes at all for
68
+ // either provider.
69
+ function attachProviderProtocol(ws, wssUrl, groupName, { onReady, onMessage, log = () => {} }) {
70
+ const provider = detectProvider(wssUrl);
71
+
72
+ if (provider === 'azure') {
73
+ // Unchanged from before this module existed.
74
+ ws.on('open', onReady);
75
+ ws.on('message', (raw) => {
76
+ let msg;
77
+ try {
78
+ msg = JSON.parse(raw.toString());
79
+ } catch {
80
+ return;
81
+ }
82
+ onMessage(msg);
83
+ });
84
+ return { provider };
85
+ }
86
+
87
+ // provider === 'ably'
88
+ let attached = false;
89
+ ws.on('open', () => {
90
+ log('[supervisor] Ably socket open - waiting for CONNECTED handshake...');
91
+ });
92
+ ws.on('message', (raw) => {
93
+ let frame;
94
+ try {
95
+ frame = JSON.parse(raw.toString());
96
+ } catch {
97
+ return;
98
+ }
99
+ switch (frame.action) {
100
+ case ABLY_ACTION.CONNECTED:
101
+ log('[supervisor] Ably CONNECTED - sending ATTACH for channel:', groupName);
102
+ ws.send(JSON.stringify({ action: ABLY_ACTION.ATTACH, channel: groupName }));
103
+ break;
104
+ case ABLY_ACTION.ATTACHED:
105
+ if (frame.channel === groupName && !attached) {
106
+ attached = true;
107
+ log('[supervisor] Ably ATTACHED - channel ready.');
108
+ onReady();
109
+ }
110
+ break;
111
+ case ABLY_ACTION.MESSAGE:
112
+ if (frame.channel === groupName) {
113
+ // A single publish can batch multiple messages - deliver every
114
+ // one, not just the first (see this file's own header comment).
115
+ //
116
+ // Real bug caught live (2026-10-24): the backend's
117
+ // channel.publish() call (ablyAdapter.js's broadcastToGroup)
118
+ // passes a plain JS object, but Ably's own client library
119
+ // serializes that to a JSON STRING before sending (encoding:
120
+ // "json" in the real wire frame) - it does NOT arrive
121
+ // pre-parsed the way Azure's raw JSON frames do. Every
122
+ // onMessage(m.data) caller downstream (supervisor.js) does
123
+ // `msg.type === ...` checks that silently never match against
124
+ // a raw string, so every single message would be dropped with
125
+ // no error at all. Parse here, once, so onMessage's contract
126
+ // ("already-parsed object, same shape for both providers") is
127
+ // actually true for Ably too.
128
+ for (const m of frame.messages || []) {
129
+ let data = m.data;
130
+ if (typeof data === 'string') {
131
+ try {
132
+ data = JSON.parse(data);
133
+ } catch {
134
+ log('[supervisor] Ably message data was a string but not valid JSON - dropping:', data);
135
+ continue;
136
+ }
137
+ }
138
+ onMessage(data);
139
+ }
140
+ }
141
+ break;
142
+ case ABLY_ACTION.ERROR:
143
+ log('[supervisor] Ably protocol ERROR:', frame.error?.message || JSON.stringify(frame.error));
144
+ break;
145
+ default:
146
+ // HEARTBEAT, ACK, NACK, DISCONNECTED, etc. - no action needed for
147
+ // this relay's purposes.
148
+ break;
149
+ }
150
+ });
151
+
152
+ return { provider };
153
+ }
154
+
155
+ module.exports = { detectProvider, attachProviderProtocol, ABLY_ACTION };
@@ -0,0 +1,94 @@
1
+ // Exponential backoff with jitter for the laptop's own reconnection to
2
+ // the backend/Azure Web PubSub - used by supervisor.js's connectToAzure
3
+ // retry paths (both the /device/connect HTTP retry and the WebSocket's
4
+ // own onclose reconnect).
5
+ //
6
+ // Real gap this fixes (confirmed by direct investigation of the actual
7
+ // code, see docs/SESSION_MONITORING_ARCHITECTURE.md): both retry paths
8
+ // used a FIXED interval (3s / 2s) with NO retry counter, NO backoff, and
9
+ // NO cap - they retry silently and identically forever. This exact shape
10
+ // - "stopped working, then quietly started working again hours later" -
11
+ // produces ZERO distinguishing evidence between "a transient blip that
12
+ // self-healed on attempt #2" and "a real outage that self-healed on
13
+ // attempt #400," which is precisely the ambiguity a PM got upset about
14
+ // from a real production incident. A visible, bounded, backed-off retry
15
+ // makes that distinction a fact instead of a guess - after enough
16
+ // attempts, this surfaces a clear "still trying, something is wrong"
17
+ // state instead of silence.
18
+ //
19
+ // A fixed-interval retry across MANY simultaneously-reconnecting clients
20
+ // (e.g. a brief Azure blip affecting every connected laptop at once) also
21
+ // creates a reconnect storm - all of them retry at the exact same cadence,
22
+ // hammering the backend in lockstep the moment it recovers. Jitter
23
+ // (randomizing each client's actual wait within a range) spreads that
24
+ // load out instead of synchronizing it.
25
+
26
+ // Tunable via env vars so this can be dialed differently without a code
27
+ // change (e.g. a much more patient cap when running inside a CI/test
28
+ // harness that expects provider blips).
29
+ const BASE_DELAY_MS = Number(process.env.CLI_SETU_RECONNECT_BASE_MS) || 1000;
30
+ const MAX_DELAY_MS = Number(process.env.CLI_SETU_RECONNECT_MAX_MS) || 60_000;
31
+ // After this many consecutive failures, stop silently retrying forever -
32
+ // surface a clear, visible "still down" message instead. Not a hard
33
+ // stop (the caller decides what "give up" actually means - for
34
+ // supervisor.js, that's printing a loud status line and CONTINUING to
35
+ // retry at the max interval, not exiting, since this failure could still
36
+ // self-heal) - this constant is just the point past which staying quiet
37
+ // stops being reasonable.
38
+ const WARN_AFTER_ATTEMPTS = Number(process.env.CLI_SETU_RECONNECT_WARN_AFTER) || 5;
39
+
40
+ // Full jitter (AWS's own documented strategy for this exact problem,
41
+ // see their "Exponential Backoff And Jitter" architecture blog) - the
42
+ // delay is a random value between 0 and the capped exponential delay,
43
+ // not a fixed delay plus a small random offset. This is the strategy
44
+ // with the best-documented reconnect-storm-avoidance properties of the
45
+ // common options (full jitter / equal jitter / decorrelated jitter).
46
+ function computeDelayMs(attemptNumber) {
47
+ const exponential = Math.min(MAX_DELAY_MS, BASE_DELAY_MS * 2 ** (attemptNumber - 1));
48
+ return Math.floor(Math.random() * exponential);
49
+ }
50
+
51
+ // Tracks one logical reconnection loop's attempt count + timer handle.
52
+ // A fresh instance per "thing that reconnects" (this process has
53
+ // exactly one - the Azure WebSocket/device-connect pair share the same
54
+ // logical retry loop since a /device/connect failure and a WebSocket
55
+ // close are the same underlying "not connected right now" condition) -
56
+ // not a singleton, so a future multi-session-per-process design (if
57
+ // that ever happens) wouldn't need this rewritten.
58
+ function createReconnectManager({ onAttempt, onWarn, log = console.log }) {
59
+ let attemptNumber = 0;
60
+ let timer = null;
61
+ let stopped = false;
62
+
63
+ function reset() {
64
+ attemptNumber = 0;
65
+ }
66
+
67
+ function scheduleRetry() {
68
+ if (stopped) return;
69
+ attemptNumber += 1;
70
+ const delayMs = computeDelayMs(attemptNumber);
71
+ if (attemptNumber === WARN_AFTER_ATTEMPTS) {
72
+ // Fires exactly once per outage (not every attempt past the
73
+ // threshold) - a single clear escalation, not repeated noise.
74
+ onWarn?.(attemptNumber);
75
+ }
76
+ log(`[reconnect] Retry ${attemptNumber} in ${(delayMs / 1000).toFixed(1)}s`);
77
+ timer = setTimeout(() => {
78
+ timer = null;
79
+ onAttempt(attemptNumber);
80
+ }, delayMs);
81
+ }
82
+
83
+ function stop() {
84
+ stopped = true;
85
+ if (timer) {
86
+ clearTimeout(timer);
87
+ timer = null;
88
+ }
89
+ }
90
+
91
+ return { scheduleRetry, reset, stop, getAttemptNumber: () => attemptNumber };
92
+ }
93
+
94
+ module.exports = { createReconnectManager, computeDelayMs, BASE_DELAY_MS, MAX_DELAY_MS, WARN_AFTER_ATTEMPTS };