@volter/teams 0.1.63 → 0.1.64

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.
Files changed (2) hide show
  1. package/package.json +1 -1
  2. package/session-follow.mjs +48 -16
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@volter/teams",
3
- "version": "0.1.63",
3
+ "version": "0.1.64",
4
4
  "type": "module",
5
5
  "description": "Volter Teams, the neutral team plane: machine identity and daemon core, the local door and server link, admission from machine grants, product doors, and the Teams server's neutral routes (company RFC 0008).",
6
6
  "license": "MIT",
@@ -15,29 +15,41 @@
15
15
  */
16
16
  export function followTeamSession({ origin, teamId, sessionId, token, tail = 300, onSnapshot, onLive = () => {}, onError = () => {}, onDeleted = () => {}, fetchImpl = globalThis.fetch, retryMs = 2000 }) {
17
17
  const base = `${origin}/api/v1/teams/${encodeURIComponent(teamId)}/sessions/${encodeURIComponent(sessionId)}`;
18
- const decoder = new TextDecoder();
19
18
  const controller = new AbortController();
20
19
  const headers = async () => ({ Authorization: `Bearer ${await token()}` });
21
20
  const failure = (stage, status, message) => Object.assign(new Error(message), { stage, status });
22
- let reading = null;
23
- const read = () => (reading ??= (async () => {
24
- try {
25
- const response = await fetchImpl(`${base}/messages?tail=${tail}`, { headers: await headers(), signal: controller.signal });
26
- if (!response.ok) throw failure('read', response.status, `reading the session failed (${response.status})`);
27
- const body = await response.json();
28
- onSnapshot(body.data ?? body);
29
- return body.data ?? body;
30
- } finally { reading = null; }
31
- })());
21
+ let reading = null, requested = false;
22
+ const read = () => {
23
+ requested = true;
24
+ return reading ??= (async () => {
25
+ let snapshot;
26
+ do {
27
+ requested = false;
28
+ const response = await fetchImpl(`${base}/messages?tail=${tail}`, { headers: await headers(), signal: AbortSignal.any([controller.signal, AbortSignal.timeout(15000)]) });
29
+ if (!response.ok) throw failure('read', response.status, `reading the session failed (${response.status})`);
30
+ const body = await response.json();
31
+ if (controller.signal.aborted) throw new DOMException('Session follow stopped', 'AbortError');
32
+ snapshot = body.data ?? body;
33
+ onSnapshot(snapshot);
34
+ // A change during the HTTP read may be newer than the capture it
35
+ // returned. Coalesce the callers, but do not drop that invalidation.
36
+ } while (requested);
37
+ return snapshot;
38
+ })().finally(() => { reading = null; });
39
+ };
32
40
  (async () => {
33
- let cursor = null;
41
+ let cursor = null, following = null, watched = null;
34
42
  while (!controller.signal.aborted) {
43
+ const connection = new AbortController();
44
+ following = connection;
45
+ let reader;
35
46
  try {
36
47
  if (!cursor) cursor = String((await read()).event_cursor ?? '') || null;
37
- const response = await fetchImpl(`${base}/events?${cursor ? `after=${encodeURIComponent(cursor)}` : 'tail=1'}`, { headers: await headers(), signal: controller.signal });
48
+ const response = await fetchImpl(`${base}/events?${cursor ? `after=${encodeURIComponent(cursor)}` : 'tail=1'}`, { headers: await headers(), signal: AbortSignal.any([controller.signal, connection.signal]) });
38
49
  if (!response.ok) throw failure('follow', response.status, `following the session failed (${response.status})`);
39
50
  onLive(true);
40
- const reader = response.body.getReader();
51
+ reader = response.body.getReader();
52
+ const decoder = new TextDecoder();
41
53
  let buffer = '';
42
54
  for (;;) {
43
55
  const { value, done } = await reader.read();
@@ -54,13 +66,33 @@ export function followTeamSession({ origin, teamId, sessionId, token, tail = 300
54
66
  // The server ends a stream it can no longer resume (a slow reader, a retired cursor): start from a snapshot.
55
67
  if (event.terminal && event.type === 'resync_required') cursor = null;
56
68
  if (event.type === 'snapshot') onSnapshot(event.data);
57
- else if (event.type === 'session_changed') read().catch((error) => { if (!controller.signal.aborted) onError({ stage: error.stage ?? 'read', status: error.status ?? null, message: error.message }); });
69
+ else if (event.type === 'session_changed') {
70
+ const refresh = read();
71
+ // One recovery handler per coalesced read, including when a
72
+ // token-expiry reconnect overtakes the unfinished HTTP read.
73
+ if (watched !== refresh) {
74
+ watched = refresh;
75
+ void refresh.then(() => { if (watched === refresh) watched = null; }, (error) => {
76
+ if (watched === refresh) watched = null;
77
+ if (controller.signal.aborted) return;
78
+ // Its event cursor advanced, but its snapshot was not read.
79
+ // Recover even if no further message arrives.
80
+ cursor = null;
81
+ following?.abort();
82
+ onError({ stage: error.stage ?? 'read', status: error.status ?? null, message: error.message, snapshot: true });
83
+ });
84
+ }
85
+ }
58
86
  else if (event.type === 'session_deleted') { onLive(false); onDeleted(); return; }
59
87
  }
60
88
  }
61
89
  } catch (error) {
62
90
  if (controller.signal.aborted) return;
63
- onError({ stage: error.stage ?? 'follow', status: error.status ?? null, message: error.message, snapshot: Boolean(cursor) });
91
+ if (!connection.signal.aborted) onError({ stage: error.stage ?? 'follow', status: error.status ?? null, message: error.message, snapshot: Boolean(cursor) });
92
+ } finally {
93
+ if (following === connection) following = null;
94
+ connection.abort();
95
+ await reader?.cancel().catch(() => {});
64
96
  }
65
97
  onLive(false);
66
98
  await new Promise((resolve) => setTimeout(resolve, retryMs));