viber-channel 0.8.47 → 0.8.49
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/lib/ack_retry.ts +73 -0
- package/lib/bridge_core.ts +214 -21
- package/lib/control_stream.ts +49 -21
- package/lib/dm_stream.ts +276 -60
- package/lib/launch_confirm.ts +69 -0
- package/lib/main_catchup.ts +264 -0
- package/lib/messages.ts +65 -2
- package/lib/runner_registry.ts +44 -10
- package/lib/runner_relaunch.ts +6 -1
- package/lib/runner_roster.ts +5 -3
- package/lib/runner_stream.ts +47 -37
- package/lib/server_events.ts +144 -0
- package/lib/sse_idle.ts +136 -0
- package/lib/stream_log.ts +69 -0
- package/package.json +1 -1
- package/viber-channel.ts +100 -18
- package/viber-codex-bridge.ts +3 -0
|
@@ -0,0 +1,264 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Catch-up for the Claude channel's MAIN conversation stream (#751 step-02).
|
|
3
|
+
*
|
|
4
|
+
* The conversation SSE has no replay: a message saved while the stream was down
|
|
5
|
+
* (server restart, idle-timeout reconnect) was never delivered to the agent, and
|
|
6
|
+
* nothing said so. DM streams already re-read the message list on every
|
|
7
|
+
* (re)connect (#291/#427); this gives the main conversation the same guarantee.
|
|
8
|
+
*
|
|
9
|
+
* FLOOR (fixed, never "the highest id seen live" — a missed 101 below a live 102
|
|
10
|
+
* would be lost, Codex review):
|
|
11
|
+
* - primed BEFORE the first SSE open with `?tail=1`: the Worker's own newest id,
|
|
12
|
+
* no clock comparison at all. Nothing older is ever replayed (startup
|
|
13
|
+
* unchanged). Every connect then catches up from the floor — the first one too,
|
|
14
|
+
* which covers the prime→open gap and any failed live delivery;
|
|
15
|
+
* - if that prime failed, the next successful one uses `?tail=1&before_ts=` the
|
|
16
|
+
* SERVER time of the first connect (its `Date` header) minus
|
|
17
|
+
* {@link PRIME_MARGIN_S}. The margin biases toward REPLAY: at worst the last
|
|
18
|
+
* minute before the first connect is delivered once more; a message of the
|
|
19
|
+
* outage is never put under the floor by clock skew (Opus review).
|
|
20
|
+
*
|
|
21
|
+
* DELIVERY: in id order, through `?after=` pages (the legacy listing returns the
|
|
22
|
+
* OLDEST 500 rows only). An id is marked delivered only AFTER the delivery
|
|
23
|
+
* succeeded, so a failed model notification is retried on the next reconnect.
|
|
24
|
+
* Live delivery shares the same set. Messages posted by any instance id this
|
|
25
|
+
* process has carried are skipped (self-echo across a re-registration).
|
|
26
|
+
*
|
|
27
|
+
* OLDER WORKER (no `window` echo): prime from the listing only if it is not
|
|
28
|
+
* truncated; otherwise catch-up is DISABLED for the session and said in the log
|
|
29
|
+
* — never replay an unbounded history.
|
|
30
|
+
*/
|
|
31
|
+
|
|
32
|
+
export const PRIME_MARGIN_S = 60;
|
|
33
|
+
/** Bound of the pre-open prime, on its own guard: it must not delay the SSE long. */
|
|
34
|
+
export const CATCHUP_PRIME_TIMEOUT_MS = 10_000;
|
|
35
|
+
const MAX_PAGES = 10;
|
|
36
|
+
|
|
37
|
+
export interface CatchUpMessage {
|
|
38
|
+
id?: unknown;
|
|
39
|
+
timestamp?: unknown;
|
|
40
|
+
sender_instance_id?: unknown;
|
|
41
|
+
[k: string]: unknown;
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
export interface WindowQuery {
|
|
45
|
+
after?: number;
|
|
46
|
+
tail?: number;
|
|
47
|
+
beforeTs?: number;
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
export interface WindowResult {
|
|
51
|
+
messages: CatchUpMessage[];
|
|
52
|
+
window: { max: number } | null;
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
function numericId(raw: unknown): number | null {
|
|
56
|
+
if (raw === undefined || raw === null || raw === "") return null;
|
|
57
|
+
const n = Number(raw);
|
|
58
|
+
return Number.isSafeInteger(n) && n > 0 ? n : null;
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
const LEGACY_MAX = 500;
|
|
62
|
+
|
|
63
|
+
export class MainConversationCatchUp {
|
|
64
|
+
private connects = 0;
|
|
65
|
+
private firstConnectServerTs: number | undefined;
|
|
66
|
+
private primed = false;
|
|
67
|
+
private disabled = false;
|
|
68
|
+
private floor = 0;
|
|
69
|
+
/** Ids at or below this are pruned from `delivered` at the NEXT connect. */
|
|
70
|
+
private pruneBelow = 0;
|
|
71
|
+
private readonly delivered = new Set<number>();
|
|
72
|
+
|
|
73
|
+
/** Record a successful SSE connect and the server time it carried (seconds). */
|
|
74
|
+
noteConnect(serverTs: number | undefined): void {
|
|
75
|
+
this.connects += 1;
|
|
76
|
+
if (this.connects === 1) this.firstConnectServerTs = serverTs;
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
/**
|
|
80
|
+
* Only what was actually delivered — never inferred from the floor: a message
|
|
81
|
+
* published between the SSE open and the prime's `tail` answer sits under the
|
|
82
|
+
* floor AND in the live buffer, and must still be delivered live (Codex).
|
|
83
|
+
*/
|
|
84
|
+
isDelivered(rawId: unknown): boolean {
|
|
85
|
+
const id = numericId(rawId);
|
|
86
|
+
return id !== null && this.delivered.has(id);
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
/** Mark AFTER a successful delivery (live or catch-up). */
|
|
90
|
+
markDelivered(rawId: unknown): void {
|
|
91
|
+
const id = numericId(rawId);
|
|
92
|
+
if (id !== null) this.delivered.add(id);
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
/**
|
|
96
|
+
* Run on every successful (re)connect, BEFORE reading live events, after
|
|
97
|
+
* {@link noteConnect}. Never throws. Returns how many messages were delivered.
|
|
98
|
+
*/
|
|
99
|
+
async onConnected(
|
|
100
|
+
fetchWindow: (q: WindowQuery) => Promise<WindowResult>,
|
|
101
|
+
deliver: (msg: CatchUpMessage) => Promise<void>,
|
|
102
|
+
isOwn: (senderInstanceId: unknown) => boolean,
|
|
103
|
+
log: (line: string) => void = () => {},
|
|
104
|
+
): Promise<number> {
|
|
105
|
+
if (this.disabled) return 0;
|
|
106
|
+
// Prune what the PREVIOUS connection settled: its live buffer is gone, so
|
|
107
|
+
// those ids can no longer come back live and need no dedup entry.
|
|
108
|
+
for (const id of this.delivered) if (id <= this.pruneBelow) this.delivered.delete(id);
|
|
109
|
+
try {
|
|
110
|
+
// Normally primed BEFORE the SSE opened (primeBeforeOpen). If that failed,
|
|
111
|
+
// prime now from the first connect's server time (biased to replay).
|
|
112
|
+
if (!this.primed) {
|
|
113
|
+
const ok = await this.prime(fetchWindow, false, log);
|
|
114
|
+
if (!ok) return 0;
|
|
115
|
+
}
|
|
116
|
+
// Always catch up — on the first connect too: it covers what was saved
|
|
117
|
+
// between the prime and the SSE open, and a live delivery that failed is
|
|
118
|
+
// still above the floor, so the next connect retries it (Codex).
|
|
119
|
+
return await this.catchUp(fetchWindow, deliver, isOwn, log);
|
|
120
|
+
} catch (err) {
|
|
121
|
+
log(`[viber-channel] main catch-up failed: ${err instanceof Error ? err.message : String(err)}\n`);
|
|
122
|
+
return 0;
|
|
123
|
+
}
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
/**
|
|
127
|
+
* Prime the floor BEFORE the very first SSE open, at the Worker's tail (no
|
|
128
|
+
* clock involved). Everything saved after it — including a message that
|
|
129
|
+
* arrives in the live buffer of the first connection — is then above the
|
|
130
|
+
* floor, so a failed live delivery is retried by the next catch-up. No-op once
|
|
131
|
+
* primed, or after the first connect (onConnected then primes from the bound).
|
|
132
|
+
* Never throws.
|
|
133
|
+
*/
|
|
134
|
+
async primeBeforeOpen(fetchWindow: (q: WindowQuery) => Promise<WindowResult>, log: (line: string) => void = () => {}): Promise<void> {
|
|
135
|
+
if (this.primed || this.disabled || this.connects > 0) return;
|
|
136
|
+
try {
|
|
137
|
+
await this.prime(fetchWindow, true, log);
|
|
138
|
+
} catch (err) {
|
|
139
|
+
log(`[viber-channel] main catch-up prime failed: ${err instanceof Error ? err.message : String(err)}\n`);
|
|
140
|
+
}
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
private async prime(
|
|
144
|
+
fetchWindow: (q: WindowQuery) => Promise<WindowResult>,
|
|
145
|
+
isFirst: boolean,
|
|
146
|
+
log: (line: string) => void,
|
|
147
|
+
): Promise<boolean> {
|
|
148
|
+
const bound =
|
|
149
|
+
!isFirst && this.firstConnectServerTs !== undefined ? this.firstConnectServerTs - PRIME_MARGIN_S : undefined;
|
|
150
|
+
if (!isFirst && bound === undefined) {
|
|
151
|
+
log("[viber-channel] main catch-up: no server time from the first connect — priming at the current tail\n");
|
|
152
|
+
}
|
|
153
|
+
const res = await fetchWindow(bound !== undefined ? { tail: 1, beforeTs: bound } : { tail: 1 });
|
|
154
|
+
let ids = res.messages.map((m) => numericId(m.id)).filter((n): n is number => n !== null);
|
|
155
|
+
if (!res.window) {
|
|
156
|
+
// Older Worker: the legacy listing (oldest 500, query ignored).
|
|
157
|
+
if (res.messages.length >= LEGACY_MAX) {
|
|
158
|
+
this.disabled = true;
|
|
159
|
+
log("[viber-channel] main catch-up DISABLED: this server ignores the window and the history exceeds one page\n");
|
|
160
|
+
return false;
|
|
161
|
+
}
|
|
162
|
+
if (bound !== undefined) {
|
|
163
|
+
ids = res.messages
|
|
164
|
+
.filter((m) => typeof m.timestamp === "number" && (m.timestamp as number) < bound)
|
|
165
|
+
.map((m) => numericId(m.id))
|
|
166
|
+
.filter((n): n is number => n !== null);
|
|
167
|
+
}
|
|
168
|
+
}
|
|
169
|
+
this.floor = ids.length > 0 ? Math.max(...ids) : 0;
|
|
170
|
+
this.primed = true;
|
|
171
|
+
return true;
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
private async catchUp(
|
|
175
|
+
fetchWindow: (q: WindowQuery) => Promise<WindowResult>,
|
|
176
|
+
deliver: (msg: CatchUpMessage) => Promise<void>,
|
|
177
|
+
isOwn: (senderInstanceId: unknown) => boolean,
|
|
178
|
+
log: (line: string) => void,
|
|
179
|
+
): Promise<number> {
|
|
180
|
+
let cursor = this.floor;
|
|
181
|
+
let delivered = 0;
|
|
182
|
+
for (let page = 0; page < MAX_PAGES; page++) {
|
|
183
|
+
const res = await fetchWindow({ after: cursor });
|
|
184
|
+
const rows = res.messages
|
|
185
|
+
.map((m) => ({ m, id: numericId(m.id) }))
|
|
186
|
+
.filter((x): x is { m: CatchUpMessage; id: number } => x.id !== null && x.id > cursor)
|
|
187
|
+
.sort((a, b) => a.id - b.id);
|
|
188
|
+
for (const { m, id } of rows) {
|
|
189
|
+
cursor = id;
|
|
190
|
+
if (this.delivered.has(id) || isOwn(m.sender_instance_id)) continue;
|
|
191
|
+
try {
|
|
192
|
+
await deliver(m);
|
|
193
|
+
this.delivered.add(id);
|
|
194
|
+
delivered += 1;
|
|
195
|
+
} catch (err) {
|
|
196
|
+
// Keep order: stop here, the next reconnect retries from the floor.
|
|
197
|
+
log(
|
|
198
|
+
`[viber-channel] main catch-up: delivery of ${id} failed (${err instanceof Error ? err.message : String(err)}) — retried on next reconnect\n`,
|
|
199
|
+
);
|
|
200
|
+
return delivered;
|
|
201
|
+
}
|
|
202
|
+
}
|
|
203
|
+
// The whole page is delivered or skipped: advance the floor NOW, so a
|
|
204
|
+
// catch-up cut at MAX_PAGES resumes after it instead of re-reading the same
|
|
205
|
+
// pages on every reconnect (Codex). Never derived from live ids.
|
|
206
|
+
if (cursor > this.floor) this.floor = cursor;
|
|
207
|
+
const max = res.window ? res.window.max : LEGACY_MAX;
|
|
208
|
+
if (!res.window) {
|
|
209
|
+
if (res.messages.length >= LEGACY_MAX) {
|
|
210
|
+
log("[viber-channel] main catch-up INCOMPLETE: this server ignores the window (legacy page of 500)\n");
|
|
211
|
+
}
|
|
212
|
+
break;
|
|
213
|
+
}
|
|
214
|
+
if (res.messages.length < max) break;
|
|
215
|
+
if (page === MAX_PAGES - 1) {
|
|
216
|
+
log(`[viber-channel] main catch-up stopped after ${MAX_PAGES} pages — the rest arrives on the next reconnect\n`);
|
|
217
|
+
}
|
|
218
|
+
}
|
|
219
|
+
// Bounded memory: ids under the floor are pruned at the next connect.
|
|
220
|
+
this.pruneBelow = this.floor;
|
|
221
|
+
if (delivered > 0) log(`[viber-channel] main catch-up delivered ${delivered} missed message(s)\n`);
|
|
222
|
+
return delivered;
|
|
223
|
+
}
|
|
224
|
+
}
|
|
225
|
+
|
|
226
|
+
/**
|
|
227
|
+
* The main stream's connect sequence (#751), extracted so the REAL ordering is
|
|
228
|
+
* testable: prime (own guard) → open the SSE (stream guard) → catch-up (own
|
|
229
|
+
* guard) → hand back the response for the live read. The two REST phases never
|
|
230
|
+
* touch the stream guard: a frozen Worker delays the live read by at most
|
|
231
|
+
* `restTimeoutMs` per phase and never aborts a healthy stream (Codex review).
|
|
232
|
+
*/
|
|
233
|
+
export async function openWithCatchUp(opts: {
|
|
234
|
+
catchUp: MainConversationCatchUp;
|
|
235
|
+
/** The stream's idle guard (bounds the SSE open and, later, each read). */
|
|
236
|
+
streamGuard: { race<T>(p: Promise<T>): Promise<T>; readonly signal: AbortSignal };
|
|
237
|
+
open: (signal: AbortSignal) => Promise<Response>;
|
|
238
|
+
fetchWindow: (q: WindowQuery, signal: AbortSignal) => Promise<WindowResult>;
|
|
239
|
+
deliver: (msg: CatchUpMessage) => Promise<void>;
|
|
240
|
+
isOwn: (senderInstanceId: unknown) => boolean;
|
|
241
|
+
makeRestGuard: () => { race<T>(p: Promise<T>): Promise<T>; readonly signal: AbortSignal; dispose(): void };
|
|
242
|
+
log?: (line: string) => void;
|
|
243
|
+
/** Called with the open response before the catch-up (status checks, logging). */
|
|
244
|
+
onOpen?: (resp: Response) => Promise<void> | void;
|
|
245
|
+
}): Promise<Response> {
|
|
246
|
+
const log = opts.log ?? (() => {});
|
|
247
|
+
const prime = opts.makeRestGuard();
|
|
248
|
+
try {
|
|
249
|
+
await opts.catchUp.primeBeforeOpen((q) => prime.race(opts.fetchWindow(q, prime.signal)), log);
|
|
250
|
+
} finally {
|
|
251
|
+
prime.dispose();
|
|
252
|
+
}
|
|
253
|
+
const resp = await opts.streamGuard.race(opts.open(opts.streamGuard.signal));
|
|
254
|
+
await opts.onOpen?.(resp);
|
|
255
|
+
const serverDate = Date.parse(resp.headers.get("date") ?? "");
|
|
256
|
+
opts.catchUp.noteConnect(Number.isFinite(serverDate) ? serverDate / 1000 : undefined);
|
|
257
|
+
const rest = opts.makeRestGuard();
|
|
258
|
+
try {
|
|
259
|
+
await opts.catchUp.onConnected((q) => rest.race(opts.fetchWindow(q, rest.signal)), opts.deliver, opts.isOwn, log);
|
|
260
|
+
} finally {
|
|
261
|
+
rest.dispose();
|
|
262
|
+
}
|
|
263
|
+
return resp;
|
|
264
|
+
}
|
package/lib/messages.ts
CHANGED
|
@@ -84,10 +84,12 @@ export async function fetchMessages(
|
|
|
84
84
|
baseUrl: string,
|
|
85
85
|
conversationId: string,
|
|
86
86
|
conversationToken: string,
|
|
87
|
+
signal?: AbortSignal,
|
|
87
88
|
): Promise<Array<Record<string, unknown>>> {
|
|
88
89
|
const resp = await fetch(`${baseUrl}/api/conversations/${conversationId}/messages`, {
|
|
89
90
|
method: "GET",
|
|
90
91
|
headers: { Authorization: `Bearer ${conversationToken}`, ...cfAccessHeaders() },
|
|
92
|
+
signal,
|
|
91
93
|
});
|
|
92
94
|
if (resp.status === 401) throw new ConversationTokenExpiredError();
|
|
93
95
|
if (!resp.ok) throw new Error(`fetchMessages failed: HTTP ${resp.status}`);
|
|
@@ -95,6 +97,48 @@ export async function fetchMessages(
|
|
|
95
97
|
return Array.isArray(body.messages) ? body.messages : [];
|
|
96
98
|
}
|
|
97
99
|
|
|
100
|
+
/** A catch-up window query (#751); see viber-api `listMessagesWindow`. */
|
|
101
|
+
export interface MessageWindowQuery {
|
|
102
|
+
after?: number;
|
|
103
|
+
tail?: number;
|
|
104
|
+
beforeTs?: number;
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
export interface MessageWindowResult {
|
|
108
|
+
messages: Array<Record<string, unknown>>;
|
|
109
|
+
/** The server's echo of the applied window; null = an older Worker ignored it. */
|
|
110
|
+
window: { max: number } | null;
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
/**
|
|
114
|
+
* GET /api/conversations/:id/messages with a catch-up window (#751), ordered by
|
|
115
|
+
* id. An older Worker ignores the query and returns the legacy listing (oldest
|
|
116
|
+
* 500) WITHOUT a `window` echo — the caller must then not trust it as a window.
|
|
117
|
+
*/
|
|
118
|
+
export async function fetchMessageWindow(
|
|
119
|
+
baseUrl: string,
|
|
120
|
+
conversationId: string,
|
|
121
|
+
conversationToken: string,
|
|
122
|
+
q: MessageWindowQuery,
|
|
123
|
+
signal?: AbortSignal,
|
|
124
|
+
fetchImpl: typeof fetch = fetch,
|
|
125
|
+
): Promise<MessageWindowResult> {
|
|
126
|
+
const params = new URLSearchParams();
|
|
127
|
+
if (q.after !== undefined) params.set("after", String(q.after));
|
|
128
|
+
if (q.tail !== undefined) params.set("tail", String(q.tail));
|
|
129
|
+
if (q.beforeTs !== undefined) params.set("before_ts", String(q.beforeTs));
|
|
130
|
+
const resp = await fetchImpl(`${baseUrl}/api/conversations/${conversationId}/messages?${params}`, {
|
|
131
|
+
method: "GET",
|
|
132
|
+
headers: { Authorization: `Bearer ${conversationToken}`, ...cfAccessHeaders() },
|
|
133
|
+
signal,
|
|
134
|
+
});
|
|
135
|
+
if (resp.status === 401) throw new ConversationTokenExpiredError();
|
|
136
|
+
if (!resp.ok) throw new Error(`fetchMessageWindow failed: HTTP ${resp.status}`);
|
|
137
|
+
const body = (await resp.json()) as { messages?: Array<Record<string, unknown>>; window?: { max?: number } };
|
|
138
|
+
const w = body.window && typeof body.window === "object" ? { max: Number(body.window.max) || 500 } : null;
|
|
139
|
+
return { messages: Array.isArray(body.messages) ? body.messages : [], window: w };
|
|
140
|
+
}
|
|
141
|
+
|
|
98
142
|
/**
|
|
99
143
|
* POST /api/conversations/:id/messages/:messageId/ack — read-acknowledgement (#346).
|
|
100
144
|
*
|
|
@@ -114,6 +158,23 @@ export async function ackMessage(
|
|
|
114
158
|
signal?: AbortSignal,
|
|
115
159
|
fetchImpl: typeof fetch = fetch,
|
|
116
160
|
): Promise<boolean> {
|
|
161
|
+
return (await ackMessageResult(baseUrl, conversationId, conversationToken, messageId, signal, fetchImpl)) === "ok";
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
/**
|
|
165
|
+
* Outcome of one ACK attempt (#751): `ok`; `rejected` — a 4xx other than 408/429,
|
|
166
|
+
* i.e. the Worker will never accept this ACK (message not ackable for this
|
|
167
|
+
* instance, e.g. an agent message in a non-DM room), so retrying is pointless;
|
|
168
|
+
* `failed` — network error, 5xx, 408 or 429: worth retrying. Never throws.
|
|
169
|
+
*/
|
|
170
|
+
export async function ackMessageResult(
|
|
171
|
+
baseUrl: string,
|
|
172
|
+
conversationId: string,
|
|
173
|
+
conversationToken: string,
|
|
174
|
+
messageId: string | number,
|
|
175
|
+
signal?: AbortSignal,
|
|
176
|
+
fetchImpl: typeof fetch = fetch,
|
|
177
|
+
): Promise<"ok" | "rejected" | "failed"> {
|
|
117
178
|
const url = `${baseUrl}/api/conversations/${conversationId}/messages/${messageId}/ack`;
|
|
118
179
|
try {
|
|
119
180
|
const resp = await fetchImpl(url, {
|
|
@@ -121,9 +182,11 @@ export async function ackMessage(
|
|
|
121
182
|
headers: { Authorization: `Bearer ${conversationToken}`, ...cfAccessHeaders() },
|
|
122
183
|
signal,
|
|
123
184
|
});
|
|
124
|
-
|
|
185
|
+
if (resp.ok) return "ok";
|
|
186
|
+
const s = resp.status;
|
|
187
|
+
return s >= 400 && s < 500 && s !== 408 && s !== 429 ? "rejected" : "failed";
|
|
125
188
|
} catch {
|
|
126
|
-
return
|
|
189
|
+
return "failed";
|
|
127
190
|
}
|
|
128
191
|
}
|
|
129
192
|
|
package/lib/runner_registry.ts
CHANGED
|
@@ -41,9 +41,6 @@ export const REGISTRY_SCHEMA_VERSION = 1;
|
|
|
41
41
|
/** Closed entries older than this are dropped, so the file cannot grow forever. */
|
|
42
42
|
export const CLOSED_ENTRY_TTL_MS = 30 * 24 * 60 * 60 * 1000;
|
|
43
43
|
|
|
44
|
-
/** #737 (JP): an active entry whose agent has been seen nowhere for this long is closed. */
|
|
45
|
-
export const ABSENT_CLOSE_AFTER_MS = 7 * 24 * 60 * 60 * 1000;
|
|
46
|
-
|
|
47
44
|
/**
|
|
48
45
|
* The gateway's launch id of one member of one command — a COPY of
|
|
49
46
|
* `attemptLaunchId` (`viber-gateway/lib/team_derivation.ts`): `launch-` + the first 32
|
|
@@ -328,9 +325,19 @@ export function recordSpawn(registry: Registry, spawn: SpawnForRegistry, now: nu
|
|
|
328
325
|
}
|
|
329
326
|
}
|
|
330
327
|
|
|
331
|
-
/**
|
|
328
|
+
/**
|
|
329
|
+
* Drop closed entries past `CLOSED_ENTRY_TTL_MS`.
|
|
330
|
+
*
|
|
331
|
+
* #755: NOT an entry still carrying `absent_since`. Every close this release makes clears it
|
|
332
|
+
* (`markClosed`, `closeAbsent`), so a closed entry that keeps one was closed by an OLDER release's
|
|
333
|
+
* 7-day absence rule — the server may still show that agent, and its settings are what a relaunch
|
|
334
|
+
* needs. It stays until the server confirms the agent is over (`closeAbsent` then clears the clock).
|
|
335
|
+
* ⚠ Such an entry with no `instance_id` can never be asked about, so it is kept for good: a few
|
|
336
|
+
* hundred bytes, against losing an agent the browser still offers to relaunch.
|
|
337
|
+
*/
|
|
332
338
|
export function pruneClosed(registry: Registry, now: number): void {
|
|
333
339
|
for (const [key, entry] of Object.entries(registry.entries)) {
|
|
340
|
+
if (entry.absent_since !== undefined && entry.absent_since !== null) continue;
|
|
334
341
|
if (entry.state === "closed" && entry.closed_at !== null && now - entry.closed_at > CLOSED_ENTRY_TTL_MS) {
|
|
335
342
|
delete registry.entries[key];
|
|
336
343
|
}
|
|
@@ -431,6 +438,8 @@ export function markClosed(registry: Registry, instanceIds: readonly string[], n
|
|
|
431
438
|
if (entry.state === "active" && entry.instance_id !== null && ids.has(entry.instance_id)) {
|
|
432
439
|
entry.state = "closed";
|
|
433
440
|
entry.closed_at = now;
|
|
441
|
+
// #755: a close the server acknowledged is final — no absence clock keeps it from pruning.
|
|
442
|
+
entry.absent_since = null;
|
|
434
443
|
changed = true;
|
|
435
444
|
}
|
|
436
445
|
}
|
|
@@ -464,31 +473,56 @@ export function markAbsence(registry: Registry, alive: ReadonlySet<string>, now:
|
|
|
464
473
|
return changed;
|
|
465
474
|
}
|
|
466
475
|
|
|
467
|
-
/**
|
|
476
|
+
/**
|
|
477
|
+
* Entries whose agent is absent: the ids worth asking the server about. #755: a CLOSED entry that
|
|
478
|
+
* still carries `absent_since` (closed by an older release's 7-day rule) is asked about too — the
|
|
479
|
+
* server's answer is what lets `pruneClosed` drop it.
|
|
480
|
+
*/
|
|
468
481
|
export function absentInstanceIds(registry: Registry): string[] {
|
|
469
482
|
return Object.values(registry.entries)
|
|
470
|
-
.filter((e) => e.
|
|
483
|
+
.filter((e) => e.instance_id !== null && e.absent_since !== undefined && e.absent_since !== null)
|
|
471
484
|
.map((e) => e.instance_id as string);
|
|
472
485
|
}
|
|
473
486
|
|
|
474
487
|
/**
|
|
475
|
-
* #737 (JP): close an ABSENT entry
|
|
476
|
-
*
|
|
477
|
-
*
|
|
488
|
+
* #737 (JP): close an ABSENT entry when the server says its instance is over (revoked, or no row at
|
|
489
|
+
* all). Never an entry whose agent runs: `absent_since` is only set by `markAbsence` from an observed
|
|
490
|
+
* machine.
|
|
491
|
+
*
|
|
492
|
+
* #755 (JP): NEVER on absence alone. An agent the browser still shows is relaunchable — its terminal
|
|
493
|
+
* closed to free memory, or the machine rebooted — however long ago. The 7-day close this replaced
|
|
494
|
+
* left the server offering a Relaunch the runner then refused.
|
|
478
495
|
*/
|
|
479
496
|
export function closeAbsent(registry: Registry, overOnServer: ReadonlySet<string>, now: number): string[] {
|
|
480
497
|
const closed: string[] = [];
|
|
481
498
|
for (const [key, entry] of Object.entries(registry.entries)) {
|
|
482
499
|
if (entry.state !== "active" || entry.absent_since === undefined || entry.absent_since === null) continue;
|
|
483
500
|
const over = entry.instance_id !== null && overOnServer.has(entry.instance_id);
|
|
484
|
-
if (!over
|
|
501
|
+
if (!over) continue;
|
|
485
502
|
entry.state = "closed";
|
|
486
503
|
entry.closed_at = now;
|
|
504
|
+
// #755: the server confirmed the end — no absence clock keeps it from pruning.
|
|
505
|
+
entry.absent_since = null;
|
|
487
506
|
closed.push(key);
|
|
488
507
|
}
|
|
489
508
|
return closed;
|
|
490
509
|
}
|
|
491
510
|
|
|
511
|
+
/**
|
|
512
|
+
* #755: an entry an OLDER release closed after 7 days of absence (closed, `absent_since` still set)
|
|
513
|
+
* becomes prunable only once the server says its instance is over. Returns whether anything changed.
|
|
514
|
+
*/
|
|
515
|
+
export function confirmLegacyClosed(registry: Registry, overOnServer: ReadonlySet<string>): boolean {
|
|
516
|
+
let changed = false;
|
|
517
|
+
for (const entry of Object.values(registry.entries)) {
|
|
518
|
+
if (entry.state !== "closed" || entry.absent_since === undefined || entry.absent_since === null) continue;
|
|
519
|
+
if (entry.instance_id === null || !overOnServer.has(entry.instance_id)) continue;
|
|
520
|
+
entry.absent_since = null;
|
|
521
|
+
changed = true;
|
|
522
|
+
}
|
|
523
|
+
return changed;
|
|
524
|
+
}
|
|
525
|
+
|
|
492
526
|
// ── #687: close requests — the runner stays the ONLY writer of its registry ──────────────────
|
|
493
527
|
//
|
|
494
528
|
// A dissolve kills, THEN revokes: by then the runner has reported the agent `down` (ambiguous:
|
package/lib/runner_relaunch.ts
CHANGED
|
@@ -119,7 +119,11 @@ export async function relaunchInstance(requestedId: string, deps: RelaunchDeps):
|
|
|
119
119
|
return { kind: "refused", error: "this runner has no saved settings for that agent — only an agent it launched can be relaunched" };
|
|
120
120
|
}
|
|
121
121
|
const [key, entry] = found;
|
|
122
|
-
|
|
122
|
+
// #755 (JP: "as long as it is not revoked, it must be relaunchable"): a LOCAL `closed` does not
|
|
123
|
+
// refuse — WHATEVER closed it: an older release's 7-day absence rule, or even a revocation the
|
|
124
|
+
// server acknowledged. By design the server is the only judge: `createRelaunchCommand` refuses a
|
|
125
|
+
// revoked or closed instance BEFORE any command reaches a runner (its test pins that refusal), so
|
|
126
|
+
// a command arriving here is one the server holds relaunchable. The entry is reopened below.
|
|
123
127
|
|
|
124
128
|
// Alive? The record, when it still exists, is checked like the roster checks it.
|
|
125
129
|
const rec = readPresenceRecord(presenceRecordPath(deps.identity, instanceId, deps.lockDir));
|
|
@@ -163,6 +167,7 @@ export async function relaunchInstance(requestedId: string, deps: RelaunchDeps):
|
|
|
163
167
|
e.instance_id = null;
|
|
164
168
|
e.launched_at = now;
|
|
165
169
|
e.state = "active";
|
|
170
|
+
e.closed_at = null;
|
|
166
171
|
// #737: the absence clock belongs to the OLD agent; the new one starts with none.
|
|
167
172
|
e.absent_since = null;
|
|
168
173
|
// This relaunch has no gateway job name: the old launch id must not let an old
|
package/lib/runner_roster.ts
CHANGED
|
@@ -576,11 +576,13 @@ async function rosterBeatOnce(auth: RosterBeatAuth, deps: RosterBeatDeps): Promi
|
|
|
576
576
|
// #737: only from a machine the runner SAW — a failed enumeration starts no absence clock.
|
|
577
577
|
const absence = collected.observed && reg.markAbsence(r, alive, now());
|
|
578
578
|
const closedAbsent = collected.observed ? reg.closeAbsent(r, overOnServer, now()) : [];
|
|
579
|
-
if (closedAbsent.length > 0) log(`[runner] registry: closed ${closedAbsent.length} absent agent(s) (revoked on the server
|
|
579
|
+
if (closedAbsent.length > 0) log(`[runner] registry: closed ${closedAbsent.length} absent agent(s) (revoked on the server)`);
|
|
580
|
+
// #755: an older release's 7-day close is released for pruning only once the server confirms.
|
|
581
|
+
const confirmed = collected.observed && reg.confirmLegacyClosed(r, overOnServer);
|
|
580
582
|
const before = Object.keys(r.entries).length;
|
|
581
583
|
reg.pruneClosed(r, now());
|
|
582
584
|
const pruned = Object.keys(r.entries).length !== before;
|
|
583
|
-
let cleared = absence || closedAbsent.length > 0 || pruned;
|
|
585
|
+
let cleared = absence || closedAbsent.length > 0 || confirmed || pruned;
|
|
584
586
|
if (ack.presence_applied) {
|
|
585
587
|
for (const e of Object.values(r.entries)) {
|
|
586
588
|
// An older predecessor (handover_from) is done once the server no longer
|
|
@@ -660,7 +662,7 @@ export async function fetchEndedInstances(
|
|
|
660
662
|
} catch (err) {
|
|
661
663
|
return { error: String(err) };
|
|
662
664
|
}
|
|
663
|
-
// A server older than #737 answers 404: nothing
|
|
665
|
+
// A server older than #737 answers 404: nothing is closed, every absent entry is kept (#755).
|
|
664
666
|
if (!resp.ok) return { error: `HTTP ${resp.status}` };
|
|
665
667
|
const body = (await resp.json().catch(() => null)) as { revoked?: unknown; missing?: unknown } | null;
|
|
666
668
|
if (body === null || !Array.isArray(body.revoked) || !Array.isArray(body.missing)) return { error: "malformed answer" };
|
package/lib/runner_stream.ts
CHANGED
|
@@ -18,6 +18,7 @@ import { readFileSync, rmSync } from "node:fs";
|
|
|
18
18
|
import { randomBytes } from "node:crypto";
|
|
19
19
|
import { join } from "node:path";
|
|
20
20
|
import { cfAccessHeaders } from "./cfAccess.js";
|
|
21
|
+
import { createIdleGuard } from "./sse_idle.js";
|
|
21
22
|
import { isTrustedViberOrigin } from "./urls.js";
|
|
22
23
|
import { type ExecDeps, reconcileOnce, runnerIdentity } from "./runner_exec.js";
|
|
23
24
|
import { requestPresenceResync, runRosterBeat } from "./runner_roster.js";
|
|
@@ -271,45 +272,54 @@ async function streamOnce(
|
|
|
271
272
|
deps: ExecDeps = {},
|
|
272
273
|
hooks: RunnerHooks = {},
|
|
273
274
|
): Promise<boolean> {
|
|
274
|
-
|
|
275
|
-
|
|
276
|
-
|
|
277
|
-
|
|
278
|
-
|
|
279
|
-
|
|
280
|
-
|
|
281
|
-
|
|
282
|
-
|
|
283
|
-
|
|
284
|
-
|
|
285
|
-
|
|
286
|
-
|
|
287
|
-
|
|
288
|
-
|
|
289
|
-
|
|
275
|
+
// #751: the server pings every ~15 s; a longer wait for bytes (fetch or read)
|
|
276
|
+
// means a dead connection — throw so the loop reconnects instead of parking.
|
|
277
|
+
const guard = createIdleGuard({ signal });
|
|
278
|
+
try {
|
|
279
|
+
const resp = await guard.race(
|
|
280
|
+
fetch(`${auth.base_url}/api/runners/${auth.runner_id}/events`, {
|
|
281
|
+
method: "GET",
|
|
282
|
+
redirect: "error", // never follow a redirect carrying the bearer (Codex review)
|
|
283
|
+
signal: guard.signal,
|
|
284
|
+
headers: {
|
|
285
|
+
Authorization: `Bearer ${auth.runner_token}`,
|
|
286
|
+
Accept: "text/event-stream",
|
|
287
|
+
"Cache-Control": "no-cache",
|
|
288
|
+
...cfAccessHeaders(),
|
|
289
|
+
},
|
|
290
|
+
}),
|
|
291
|
+
);
|
|
292
|
+
if (resp.status === 401) return true; // revoked — terminal
|
|
293
|
+
if (!resp.ok || !resp.body) {
|
|
294
|
+
throw new Error(`control stream HTTP ${resp.status}`);
|
|
295
|
+
}
|
|
296
|
+
hooks.onConnection?.(true);
|
|
290
297
|
|
|
291
|
-
|
|
292
|
-
|
|
293
|
-
|
|
294
|
-
|
|
295
|
-
|
|
296
|
-
|
|
297
|
-
|
|
298
|
-
|
|
299
|
-
|
|
300
|
-
|
|
301
|
-
|
|
302
|
-
|
|
303
|
-
|
|
304
|
-
|
|
305
|
-
|
|
306
|
-
|
|
307
|
-
|
|
308
|
-
|
|
309
|
-
|
|
310
|
-
|
|
311
|
-
|
|
298
|
+
const reader = resp.body.getReader();
|
|
299
|
+
const decoder = new TextDecoder();
|
|
300
|
+
let buffer = "";
|
|
301
|
+
while (true) {
|
|
302
|
+
const { value, done } = await guard.read(reader);
|
|
303
|
+
if (done) return false; // server closed — recoverable, reconnect
|
|
304
|
+
buffer += decoder.decode(value, { stream: true });
|
|
305
|
+
// Parse complete SSE frames (blank-line separated).
|
|
306
|
+
let sep: number;
|
|
307
|
+
// biome-ignore lint/suspicious/noAssignInExpressions: standard SSE frame split
|
|
308
|
+
while ((sep = buffer.indexOf("\n\n")) !== -1) {
|
|
309
|
+
const frame = buffer.slice(0, sep);
|
|
310
|
+
buffer = buffer.slice(sep + 2);
|
|
311
|
+
const eventLine = frame.split("\n").find((l) => l.startsWith("event:"));
|
|
312
|
+
const event = eventLine?.slice("event:".length).trim();
|
|
313
|
+
if (event === "stop") return false; // server asked us to unwind
|
|
314
|
+
// Any wake-poke ("spawn_pending" etc.) or reconnect → reconcile-pull. The
|
|
315
|
+
// event is a HINT; the durable table is the truth. safeReconcile is
|
|
316
|
+
// coalesced + self-contained (never throws into this stream).
|
|
317
|
+
if (event && event !== "ping" && event !== "connected") {
|
|
318
|
+
await safeReconcile(auth, deps);
|
|
319
|
+
}
|
|
312
320
|
}
|
|
313
321
|
}
|
|
322
|
+
} finally {
|
|
323
|
+
guard.dispose();
|
|
314
324
|
}
|
|
315
325
|
}
|