-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathprotocol.ts
More file actions
394 lines (346 loc) · 14.2 KB
/
Copy pathprotocol.ts
File metadata and controls
394 lines (346 loc) · 14.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
/**
* Shared wire protocol for `@reactor-team/queue`.
*
* Both the PartyKit server (`@reactor-team/queue/server`) and the browser
* client (`@reactor-team/queue`) import these types so the messages they
* exchange over the WebSocket stay in lockstep. Nothing here depends on
* PartyKit, the Reactor SDK, React, or the DOM — it is plain data.
*/
/** Current protocol version. Bumped only on breaking wire changes. */
export const PROTOCOL_VERSION = 2 as const;
/** Default PartyKit room id. A single room is the source of truth for one queue. */
export const DEFAULT_ROOM = "reactor-queue";
/** Query-string key used to carry the stable per-browser id on connect. */
export const CLIENT_ID_QUERY_KEY = "rqClientId";
/** Set to `1` on the WebSocket URL to open an admin connection (not queued). */
export const ADMIN_MODE_QUERY_KEY = "rqAdmin";
/**
* Default tunables. Every one of these is overridable from server config and/or
* environment variables (see `@reactor-team/queue/server`).
*/
export const DEFAULTS = {
/** Max concurrent Reactor sessions (GPU ceiling). */
maxSessions: 1,
/** Members per session (default 1 = today's behavior; >1 when platform allows N). */
usersPerSession: 1,
/** Full session budget once a user has `claim()`ed their slot. */
sessionDurationMs: 120_000,
/**
* Grace window an admitted user gets to actually start (claim) their session
* before the slot is reclaimed. Prevents an idle admit from wasting a slot.
*/
admissionGraceMs: 45_000,
/** How long before expiry to emit a `time_warning`. */
warningBeforeMs: 30_000,
/** Lifetime requested for each minted Reactor JWT. Deliberately short. */
tokenTtlSeconds: 60,
/**
* How often the server re-checks tracked live sessions against the Reactor
* API to catch sessions that ended without a clean `session_ended`/close.
*/
pollIntervalMs: 15_000,
/** Client-side skew: refresh the JWT this long before it actually expires. */
tokenSkewMs: 10_000,
} as const;
/** Reactor session states that mean "the slot is free again". */
export const TERMINAL_SESSION_STATES = ["CLOSED", "INACTIVE"] as const;
// ─────────────────────────────────────────────────────────────────────────────
// Server → Client messages
// ─────────────────────────────────────────────────────────────────────────────
/** You are waiting in line. `position` is 1-based. */
export interface QueuePositionMessage {
type: "queue_position";
position: number;
total: number;
active: number;
capacity: number;
}
/**
* You reached the front and a capacity slot is reserved for you. No Reactor
* session exists yet — the server creates it only when you `claim()`, so an
* abandoned grace never leaves an orphaned GPU session. You have until the
* admission grace expires to `claim()`.
*/
export interface AdmittedMessage {
type: "admitted";
active: number;
/** Total live users = maxSessions * usersPerSession. */
capacity: number;
/** ms the client has to `claim()` before the slot is reclaimed. */
graceMs: number;
/** Full session budget (ms) the client receives once it `claim()`s. For countdown UI. */
sessionDurationMs: number;
}
/**
* Sent after `claim()`: the server has created (or reused) the Reactor session
* and minted a WebRTC connection under it for this member. Attach with
* `connect({ sessionId, connectionId })` — the server owns both, so the client
* never creates or stops anything.
*/
export interface SessionReadyMessage {
type: "session_ready";
/** Reactor session id created by the server — pass to connect({ sessionId }). */
sessionId: string;
/**
* Server-minted WebRTC connection id for this member — pass to
* connect({ connectionId }). The server registered it under `sessionId`, so
* the client adopts it instead of registering its own.
*/
connectionId: number;
/** Full session budget (ms). */
sessionDurationMs: number;
/** Unix epoch ms when the session ends. */
expiresAt: number;
}
/** A freshly minted, short-lived Reactor JWT. Sent on admission and on each `request_token`. */
export interface TokenMessage {
type: "token";
jwt: string;
/** Unix epoch seconds at which the JWT expires. */
expiresAt: number;
}
/** Your session is about to end. */
export interface TimeWarningMessage {
type: "time_warning";
secondsLeft: number;
/** Unix epoch ms when the session ends. */
expiresAt: number;
}
/** Your session ended (time ran out, or the server reclaimed the slot). */
export interface ExpiredMessage {
type: "expired";
reason: "timeout" | "grace_timeout" | "server";
}
/** You were refused entry. */
export interface RejectedMessage {
type: "rejected";
reason: "already_connected" | "server_error" | "forbidden_origin" | string;
}
/** A non-fatal error (e.g. token mint failed); the client may retry. */
export interface ErrorMessage {
type: "error";
message: string;
}
export type ServerMessage =
| QueuePositionMessage
| AdmittedMessage
| SessionReadyMessage
| TokenMessage
| TimeWarningMessage
| ExpiredMessage
| RejectedMessage
| ErrorMessage;
// ─────────────────────────────────────────────────────────────────────────────
// Client → Server messages
// ─────────────────────────────────────────────────────────────────────────────
/** "I'm actually entering the demo" — upgrades the grace window to the full session. */
export interface ClaimMessage {
type: "claim";
}
/** Ask for a fresh JWT. The server only answers if you currently hold a slot. */
export interface RequestTokenMessage {
type: "request_token";
}
/** The user ended the Reactor session from the client; free the slot now. */
export interface SessionEndedMessage {
type: "session_ended";
}
/** Leave the queue / release the slot without intending to rejoin. */
export interface LeaveMessage {
type: "leave";
}
export type ClientMessage = ClaimMessage | RequestTokenMessage | SessionEndedMessage | LeaveMessage;
// ─────────────────────────────────────────────────────────────────────────────
// Admin mode (server → admin client)
// ─────────────────────────────────────────────────────────────────────────────
/** Read-only server tunables included in every admin snapshot. */
export interface AdminConfigSnapshot {
maxSessions: number;
usersPerSession: number;
capacity: number;
model: string;
webrtcVersion: string;
sessionDurationMs: number;
admissionGraceMs: number;
warningBeforeMs: number;
tokenTtlSeconds: number;
pollIntervalMs: number;
coordinatorUrl: string;
apiVersion: number;
stopSessionsOnExpiry: boolean;
allowDuplicateConnections: boolean;
/** "default" = queue creates/stops sessions; "custom" = acquire/release overridden. */
sessionSource: "default" | "custom";
}
/** One person waiting in the FIFO queue. */
export interface AdminQueuedUserSnapshot {
connId: string;
/** 1-based position in line. */
position: number;
clientId: string | null;
}
/** One admitted member (may or may not have claimed yet). */
export interface AdminMemberSnapshot {
connId: string;
/** Reactor session id once claimed; null while still in grace (no session yet). */
sessionId: string | null;
/** Server-minted WebRTC connection id once claimed; null while still in grace. */
connectionId: number | null;
clientId: string | null;
claimed: boolean;
expiresAt: number;
msLeft: number;
}
/** One capacity slot and its member connection ids. */
export interface AdminSessionSnapshot {
/** Reactor session id, or null while the slot is reserved but unclaimed (no GPU session yet). */
sessionId: string | null;
members: string[];
createdAt: number;
msSinceCreated: number;
}
/** Full room state pushed to authenticated admin connections. */
export interface AdminSnapshotMessage {
type: "admin_snapshot";
at: number;
activeCount: number;
sessionCount: number;
config: AdminConfigSnapshot;
queue: AdminQueuedUserSnapshot[];
sessions: AdminSessionSnapshot[];
members: AdminMemberSnapshot[];
}
/** Admin WebSocket authenticated; snapshots follow on changes. */
export interface AdminReadyMessage {
type: "admin_ready";
}
export interface AdminRejectedMessage {
type: "admin_rejected";
reason: "admin_disabled" | "invalid_password" | "auth_required" | "forbidden_origin";
}
export interface AdminActionResultMessage {
type: "admin_action_result";
action: "kick_member" | "kick_queued" | "close_session";
ok: boolean;
message?: string;
}
/** Severity of an {@link AdminLogEntry}. Mirrors `console.log`/`warn`/`error`. */
export type AdminLogLevel = "info" | "warn" | "error";
/**
* One structured server event. The queue server emits these for every notable
* thing that happens in a room — a user joining, an admission, a session being
* created or closed, and crucially the **reason an API call failed** (e.g. a
* Coordinator quota rejection, with its HTTP status and body in `data`). They
* are streamed live to admins and kept in a bounded server-side ring buffer so
* a freshly-connected admin sees recent history.
*/
export interface AdminLogEntry {
/** Stable unique id (also usable as a React key). */
id: string;
/** Unix epoch ms when the event happened. */
at: number;
level: AdminLogLevel;
/** Machine-readable event code, e.g. `"user_admitted"`, `"session_create_failed"`. */
event: string;
/** Human-readable, already-formatted summary line. */
message: string;
/** The connection this event concerns, when applicable. */
connId?: string;
/** The Reactor session this event concerns, when applicable. */
sessionId?: string;
/** Extra structured context (HTTP status, response body, reason, …). */
data?: Record<string, unknown>;
}
/** A single new log line, pushed live to authenticated admins as it happens. */
export interface AdminLogMessage {
type: "admin_log";
entry: AdminLogEntry;
}
/** Recent log history (oldest → newest), sent once right after admin auth. */
export interface AdminLogHistoryMessage {
type: "admin_log_history";
entries: AdminLogEntry[];
}
export type AdminServerMessage =
| AdminReadyMessage
| AdminRejectedMessage
| AdminSnapshotMessage
| AdminActionResultMessage
| AdminLogMessage
| AdminLogHistoryMessage;
// ─────────────────────────────────────────────────────────────────────────────
// Admin mode (admin client → server)
// ─────────────────────────────────────────────────────────────────────────────
/** First message on an admin connection; password must match `RQ_ADMIN_PASSWORD`. */
export interface AdminAuthMessage {
type: "admin_auth";
password: string;
}
/** Remove a member from their session and free capacity (same as forced expiry). */
export interface AdminKickMemberMessage {
type: "admin_kick_member";
connId: string;
}
/** Drop a still-waiting connection from the queue and close its socket. */
export interface AdminKickQueuedMessage {
type: "admin_kick_queued";
connId: string;
}
/** Stop the Reactor session and evict all members. */
export interface AdminCloseSessionMessage {
type: "admin_close_session";
sessionId: string;
}
/** Request a fresh snapshot (also sent automatically on room changes). */
export interface AdminRefreshMessage {
type: "admin_refresh";
}
export type AdminClientMessage =
| AdminAuthMessage
| AdminKickMemberMessage
| AdminKickQueuedMessage
| AdminCloseSessionMessage
| AdminRefreshMessage;
// ─────────────────────────────────────────────────────────────────────────────
// Helpers
// ─────────────────────────────────────────────────────────────────────────────
/** Narrowing parse for an inbound server message. Returns null on garbage. */
export function parseServerMessage(raw: string): ServerMessage | null {
try {
const msg = JSON.parse(raw) as ServerMessage;
return typeof msg?.type === "string" ? msg : null;
} catch {
return null;
}
}
/** Narrowing parse for an inbound client message. Returns null on garbage. */
export function parseClientMessage(raw: string): ClientMessage | null {
try {
const msg = JSON.parse(raw) as ClientMessage;
if (typeof msg?.type !== "string") return null;
if (msg.type.startsWith("admin_")) return null;
return msg;
} catch {
return null;
}
}
/** Parse an admin client message. Returns null on garbage or non-admin types. */
export function parseAdminClientMessage(raw: string): AdminClientMessage | null {
try {
const msg = JSON.parse(raw) as AdminClientMessage;
if (typeof msg?.type !== "string" || !msg.type.startsWith("admin_")) return null;
return msg;
} catch {
return null;
}
}
/** Parse a server message sent to an admin connection. */
export function parseAdminServerMessage(raw: string): AdminServerMessage | null {
try {
const msg = JSON.parse(raw) as AdminServerMessage;
if (typeof msg?.type !== "string" || !msg.type.startsWith("admin_")) return null;
return msg;
} catch {
return null;
}
}