@syncular/server-hono 0.31.0 → 0.32.1

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/src/admin.ts CHANGED
@@ -1,21 +1,25 @@
1
1
  /**
2
2
  * Admin / console HTTP surface: a mountable Hono sub-app over a
3
- * `SyncularAdmin`. JSON endpoints mirror the read surface; a single static
3
+ * `SyncularAdmin`. JSON endpoints mirror the admin surface; a single static
4
4
  * HTML page (zero framework, no build step) at `GET /` renders them.
5
+ * Hosts mount it through `createSyncularHono({ admin })` or
6
+ * `createWorkersFetchHandler({ admin })`; this module is their shared
7
+ * implementation.
5
8
  *
6
9
  * The auth seam is REQUIRED. There is NO default-open admin: the factory
7
10
  * refuses to mount without a host-provided `authorize` guard (it throws at
8
11
  * construction). Every request runs the guard first; a falsy result is a
9
12
  * 401. Admin is a privileged surface (it reads every partition's clients,
10
- * commit metadata, scope activity, and reactions) and authorization is
11
- * entirely the host's and mandatory.
13
+ * rows, commits, scope activity, and reactions) and authorization is
14
+ * entirely the host's and mandatory. The operator actions (`POST` routes)
15
+ * additionally require `authorizeActions`; without it they answer 403.
12
16
  */
13
17
  import {
14
- adapterSyncError,
15
18
  errorBody,
19
+ adapterSyncError,
16
20
  matchesRingQuery,
17
- type RingEventQuery,
18
21
  type ReactionStatus,
22
+ type RingEventQuery,
19
23
  SyncError,
20
24
  type SyncularAdmin,
21
25
  type SyncularErrorHandler,
@@ -26,12 +30,17 @@ import { Hono } from 'hono';
26
30
  import { ADMIN_CONSOLE_HTML } from './admin-page';
27
31
 
28
32
  export interface AdminAuthContext {
29
- /** The partition the request targets (from the query string / route). */
33
+ /**
34
+ * The partition the request targets: `?partition=`, else the only
35
+ * partition of the deployment. Empty for the page without `?partition=`
36
+ * and for `GET /partitions`, which spans every partition.
37
+ */
30
38
  readonly partition: string;
31
39
  readonly request: Request;
32
40
  }
33
41
 
34
- export interface SyncularAdminRoutesOptions {
42
+ /** The console guards, shared by the Hono and Workers `admin` options. */
43
+ export interface SyncularAdminGuards {
35
44
  /**
36
45
  * REQUIRED host guard. Return `true` (or a truthy value) to allow the
37
46
  * request, a falsy value to reject it with 401. Runs before every admin
@@ -40,10 +49,28 @@ export interface SyncularAdminRoutesOptions {
40
49
  */
41
50
  readonly authorize: (ctx: AdminAuthContext) => boolean | Promise<boolean>;
42
51
  /**
43
- * Default partition for endpoints when the request omits `?partition=`.
44
- * When unset, `partition` is required on every data endpoint.
52
+ * Guard for the operator actions (retry a dead-lettered reaction, prune,
53
+ * revoke a lease), run after `authorize`. A falsy result answers 403
54
+ * `sync.forbidden`. Omitted ⇒ every action answers 403 and `GET /info`
55
+ * reports `actions: false`.
45
56
  */
46
- readonly defaultPartition?: string;
57
+ readonly authorizeActions?: (
58
+ ctx: AdminAuthContext,
59
+ ) => boolean | Promise<boolean>;
60
+ }
61
+
62
+ /** @internal The adapters' route options; hosts use their `admin` option. */
63
+ export interface SyncularAdminRoutesOptions extends SyncularAdminGuards {
64
+ /**
65
+ * Serve every partition-scoped request elsewhere once the guards pass.
66
+ * The page and `GET /partitions` stay local. The Workers adapter forwards
67
+ * to the partition's Durable Object, whose event ring sees that
68
+ * partition's sync rounds.
69
+ */
70
+ readonly forward?: (
71
+ request: Request,
72
+ target: { readonly partition: string; readonly actions: boolean },
73
+ ) => Promise<Response>;
47
74
  /**
48
75
  * Host error reporting: receives every exception that is not a
49
76
  * `SyncError`, which answers 500 `sync.internal_error` (§10.2).
@@ -56,27 +83,36 @@ export interface SyncularAdminRoutesOptions {
56
83
  readonly mapError?: SyncularErrorMapper;
57
84
  }
58
85
 
59
- function intParam(value: string | undefined, fallback: number): number {
60
- if (value === undefined) return fallback;
61
- const parsed = Number.parseInt(value, 10);
62
- return Number.isFinite(parsed) ? parsed : fallback;
86
+ type QueryContext = { req: { query: (k: string) => string | undefined } };
87
+
88
+ /** An optional integer query parameter; a malformed value is a 400. */
89
+ function intParam(c: QueryContext, name: string): number | undefined {
90
+ const value = c.req.query(name);
91
+ if (value === undefined) return undefined;
92
+ if (!/^-?\d+$/.test(value)) {
93
+ throw new SyncError(
94
+ 'sync.invalid_request',
95
+ 'query parameter must be an integer',
96
+ JSON.stringify({ parameter: name }),
97
+ );
98
+ }
99
+ return Number.parseInt(value, 10);
63
100
  }
64
101
 
65
102
  /**
66
- * Build the mountable admin sub-app. Mount it under any prefix, e.g.
67
- * `app.route('/admin', createSyncularAdminRoutes(admin, { authorize }))`.
68
- * Throws if `authorize` is missing — admin never mounts default-open.
103
+ * @internal Build the admin sub-app the adapters mount. Throws if
104
+ * `authorize` is missing — admin never mounts default-open.
69
105
  */
70
106
  export function createSyncularAdminRoutes(
71
107
  admin: SyncularAdmin,
72
108
  options: SyncularAdminRoutesOptions,
73
- ): Hono {
109
+ ): Hono<{ Variables: { partition: string } }> {
74
110
  if (typeof options.authorize !== 'function') {
75
111
  throw new Error(
76
- 'createSyncularAdminRoutes: an `authorize` guard is required — admin never mounts default-open',
112
+ 'admin: an `authorize` guard is required — admin never mounts default-open',
77
113
  );
78
114
  }
79
- const app = new Hono();
115
+ const app = new Hono<{ Variables: { partition: string } }>();
80
116
  const jsonError = (error: unknown): Response => {
81
117
  const sync = adapterSyncError(
82
118
  error,
@@ -86,200 +122,331 @@ export function createSyncularAdminRoutes(
86
122
  );
87
123
  return Response.json(errorBody(sync), { status: sync.httpStatus });
88
124
  };
89
- // Throws outside a route's own try, such as from `authorize`.
125
+ // Every route throws its failures; this answers them as catalog errors.
90
126
  app.onError((error) => jsonError(error));
91
127
 
92
- /** Resolve the request's partition (query, else default) — required. */
93
- function partitionOf(c: {
94
- req: { query: (k: string) => string | undefined };
95
- }): string {
96
- const partition = c.req.query('partition') ?? options.defaultPartition;
97
- if (partition === undefined || partition.length === 0) {
98
- throw new SyncError('sync.invalid_request', 'partition is required');
128
+ /** Run the host guards; actions also need `authorizeActions`. */
129
+ async function guard(request: Request, partition: string): Promise<void> {
130
+ const context = { partition, request };
131
+ if (!(await options.authorize(context))) {
132
+ throw new SyncError('sync.auth_required');
133
+ }
134
+ if (
135
+ request.method === 'POST' &&
136
+ !(await options.authorizeActions?.(context))
137
+ ) {
138
+ throw new SyncError('sync.forbidden', 'admin actions are not authorized');
99
139
  }
100
- return partition;
101
140
  }
102
141
 
103
- // Guard every route (page + data) up front.
142
+ // The single static console page (zero framework, no build step).
143
+ app.get('/', async (c) => {
144
+ await guard(c.req.raw, c.req.query('partition') ?? '');
145
+ return c.html(ADMIN_CONSOLE_HTML, 200, { 'Cache-Control': 'no-store' });
146
+ });
147
+
148
+ // Cross-partition fleet view: the ONE endpoint that is not partition-
149
+ // scoped. Its guard sees no partition, so a guard that grants single
150
+ // partitions never grants the whole fleet.
151
+ app.get('/partitions', async (c) => {
152
+ await guard(c.req.raw, '');
153
+ const limit = intParam(c, 'limit');
154
+ const offset = intParam(c, 'offset');
155
+ return Response.json(
156
+ await admin.partitionsOverview({
157
+ ...(limit !== undefined ? { limit } : {}),
158
+ ...(offset !== undefined ? { offset } : {}),
159
+ }),
160
+ );
161
+ });
162
+
163
+ // Every other route is partition-scoped: `?partition=`, else the
164
+ // deployment's only partition. The guards run on the resolved partition.
104
165
  app.use('*', async (c, next) => {
105
- let partition: string;
106
- try {
107
- partition = c.req.query('partition') ?? options.defaultPartition ?? '';
108
- } catch {
109
- partition = '';
166
+ let partition = c.req.query('partition') ?? '';
167
+ if (partition === '') {
168
+ const partitions = await admin.listPartitions();
169
+ if (partitions.length !== 1) {
170
+ // The registry size is fleet knowledge: only the fleet guard may
171
+ // learn that the partition is ambiguous.
172
+ await guard(c.req.raw, '');
173
+ throw new SyncError(
174
+ 'sync.invalid_request',
175
+ 'partition is required',
176
+ JSON.stringify({ parameter: 'partition' }),
177
+ );
178
+ }
179
+ partition = partitions[0]!;
110
180
  }
111
- const ok = await options.authorize({ partition, request: c.req.raw });
112
- if (!ok) return jsonError(new SyncError('sync.auth_required'));
181
+ await guard(c.req.raw, partition);
182
+ c.set('partition', partition);
113
183
  await next();
114
184
  });
115
185
 
116
- // The single static console page (zero framework, no build step).
117
- app.get('/', (c) =>
118
- c.html(ADMIN_CONSOLE_HTML, 200, { 'Cache-Control': 'no-store' }),
186
+ const forward = options.forward;
187
+ if (forward !== undefined) {
188
+ app.all('*', (c) =>
189
+ forward(c.req.raw, {
190
+ partition: c.get('partition'),
191
+ actions: options.authorizeActions !== undefined,
192
+ }),
193
+ );
194
+ return app;
195
+ }
196
+
197
+ app.get('/info', (c) =>
198
+ Response.json({
199
+ partition: c.get('partition'),
200
+ hasEventStream: admin.hasEventStream,
201
+ actions: options.authorizeActions !== undefined,
202
+ realtime: admin.hasRealtime,
203
+ ...(admin.schemaVersion !== undefined
204
+ ? { schemaVersion: admin.schemaVersion }
205
+ : {}),
206
+ tables: admin.tables(),
207
+ }),
119
208
  );
120
209
 
121
210
  app.get('/clients', async (c) => {
122
- try {
123
- const clients = await admin.listClients(partitionOf(c));
124
- return Response.json({ clients });
125
- } catch (error) {
126
- return jsonError(error);
211
+ const sort = c.req.query('sort');
212
+ if (sort !== undefined && sort !== 'seen' && sort !== 'lag') {
213
+ throw new SyncError(
214
+ 'sync.invalid_request',
215
+ 'sort must be seen or lag',
216
+ JSON.stringify({ sort }),
217
+ );
127
218
  }
219
+ const limit = intParam(c, 'limit');
220
+ return Response.json(
221
+ await admin.listClients(c.get('partition'), {
222
+ ...(limit !== undefined ? { limit } : {}),
223
+ ...(sort !== undefined ? { sort } : {}),
224
+ }),
225
+ );
226
+ });
227
+
228
+ app.get('/actors', async (c) =>
229
+ Response.json({ actors: await admin.actors(c.get('partition')) }),
230
+ );
231
+
232
+ app.get('/search', async (c) =>
233
+ Response.json({
234
+ search: await admin.search(c.get('partition'), c.req.query('q') ?? ''),
235
+ }),
236
+ );
237
+
238
+ app.get('/writes/:clientCommitId', async (c) =>
239
+ Response.json({
240
+ write: await admin.findWrite(
241
+ c.get('partition'),
242
+ c.req.param('clientCommitId'),
243
+ ),
244
+ }),
245
+ );
246
+
247
+ app.get('/tables', async (c) => {
248
+ const counts = await admin.tableCounts(c.get('partition'));
249
+ return Response.json({
250
+ tables: admin
251
+ .tables()
252
+ .map((table) => ({ ...table, rowCount: counts[table.name] ?? 0 })),
253
+ });
128
254
  });
129
255
 
130
256
  app.get('/clients/:clientId', async (c) => {
131
- try {
132
- const detail = await admin.clientDetail(
133
- partitionOf(c),
134
- c.req.param('clientId'),
135
- { eventLimit: intParam(c.req.query('eventLimit'), 100) },
136
- );
137
- return Response.json({ detail });
138
- } catch (error) {
139
- return jsonError(error);
140
- }
257
+ const eventLimit = intParam(c, 'eventLimit');
258
+ const detail = await admin.clientDetail(
259
+ c.get('partition'),
260
+ c.req.param('clientId'),
261
+ eventLimit !== undefined ? { eventLimit } : {},
262
+ );
263
+ return Response.json({ detail });
141
264
  });
142
265
 
143
- app.get('/metrics', async (c) => {
144
- try {
145
- const metrics = admin.metrics(partitionOf(c), {
146
- windowMs: intParam(c.req.query('windowMs'), 5 * 60 * 1000),
147
- });
148
- return Response.json({ metrics, hasEventStream: admin.hasEventStream });
149
- } catch (error) {
150
- return jsonError(error);
151
- }
266
+ app.get('/metrics', (c) => {
267
+ const windowMs = intParam(c, 'windowMs');
268
+ const metrics = admin.metrics(
269
+ c.get('partition'),
270
+ windowMs !== undefined ? { windowMs } : {},
271
+ );
272
+ return Response.json({ metrics });
152
273
  });
153
274
 
154
- // Cross-partition fleet view: the ONE endpoint that is not partition-
155
- // scoped (the guard still runs, with `partition` empty unless passed).
156
- app.get('/partitions', async () => {
157
- try {
158
- const partitions = await admin.partitionsOverview();
159
- return Response.json({ partitions });
160
- } catch (error) {
161
- return jsonError(error);
162
- }
275
+ app.get('/errors', (c) => {
276
+ const windowMs = intParam(c, 'windowMs');
277
+ const errors = admin.errors(
278
+ c.get('partition'),
279
+ windowMs !== undefined ? { windowMs } : {},
280
+ );
281
+ return Response.json({ errors });
163
282
  });
164
283
 
165
284
  app.get('/commits', async (c) => {
166
- try {
167
- const table = c.req.query('table');
168
- const commits = await admin.listCommits(partitionOf(c), {
169
- afterSeq: intParam(c.req.query('afterSeq'), 0),
170
- limit: intParam(c.req.query('limit'), 50),
171
- ...(table !== undefined ? { table } : {}),
172
- });
173
- return Response.json({ commits });
174
- } catch (error) {
175
- return jsonError(error);
176
- }
285
+ const table = c.req.query('table');
286
+ const afterSeq = intParam(c, 'afterSeq');
287
+ const beforeSeq = intParam(c, 'beforeSeq');
288
+ const limit = intParam(c, 'limit');
289
+ const changeSample = intParam(c, 'sample');
290
+ const commits = await admin.listCommits(c.get('partition'), {
291
+ ...(changeSample !== undefined ? { changeSample } : {}),
292
+ ...(afterSeq !== undefined ? { afterSeq } : {}),
293
+ ...(beforeSeq !== undefined ? { beforeSeq } : {}),
294
+ ...(limit !== undefined ? { limit } : {}),
295
+ ...(table !== undefined ? { table } : {}),
296
+ });
297
+ return Response.json({ commits });
298
+ });
299
+
300
+ app.get('/commits/:commitSeq{[0-9]+}', async (c) => {
301
+ const commit = await admin.commitDetail(
302
+ c.get('partition'),
303
+ Number.parseInt(c.req.param('commitSeq'), 10),
304
+ );
305
+ return Response.json({ commit });
177
306
  });
178
307
 
179
308
  app.get('/reactions', async (c) => {
180
- try {
181
- const status = c.req.query('status');
182
- const type = c.req.query('type');
183
- const allowed = new Set<ReactionStatus>([
184
- 'pending',
185
- 'leased',
186
- 'completed',
187
- 'dead-letter',
188
- ]);
189
- if (status !== undefined && !allowed.has(status as ReactionStatus)) {
190
- throw new SyncError('sync.invalid_request', 'invalid reaction status');
191
- }
192
- const reactions = await admin.listReactions(partitionOf(c), {
193
- ...(status !== undefined
194
- ? { statuses: [status as ReactionStatus] }
195
- : {}),
196
- ...(type !== undefined ? { types: [type] } : {}),
197
- limit: intParam(c.req.query('limit'), 100),
198
- });
199
- return Response.json({ reactions });
200
- } catch (error) {
201
- return jsonError(error);
309
+ const status = c.req.query('status');
310
+ const type = c.req.query('type');
311
+ const allowed = new Set<string>([
312
+ 'pending',
313
+ 'leased',
314
+ 'completed',
315
+ 'dead-letter',
316
+ ]);
317
+ if (status !== undefined && !allowed.has(status)) {
318
+ throw new SyncError('sync.invalid_request', 'invalid reaction status');
202
319
  }
320
+ const limit = intParam(c, 'limit');
321
+ const reactions = await admin.listReactions(c.get('partition'), {
322
+ ...(status !== undefined ? { statuses: [status as ReactionStatus] } : {}),
323
+ ...(type !== undefined ? { types: [type] } : {}),
324
+ ...(limit !== undefined ? { limit } : {}),
325
+ });
326
+ return Response.json({ reactions });
203
327
  });
204
328
 
205
- app.get('/rows/:table/:rowId', async (c) => {
206
- try {
207
- const row = await admin.inspectRow(
208
- partitionOf(c),
329
+ app.get('/rows/:table', async (c) => {
330
+ const scope = c.req.query('scope');
331
+ const separator = scope?.indexOf(':') ?? -1;
332
+ if (scope !== undefined && separator <= 0) {
333
+ throw new SyncError(
334
+ 'sync.invalid_request',
335
+ 'scope must be variable:value',
336
+ JSON.stringify({ scope }),
337
+ );
338
+ }
339
+ const afterRowId = c.req.query('afterRowId');
340
+ const limit = intParam(c, 'limit');
341
+ const page = await admin.listRows(
342
+ c.get('partition'),
343
+ c.req.param('table'),
344
+ {
345
+ ...(afterRowId !== undefined ? { afterRowId } : {}),
346
+ ...(limit !== undefined ? { limit } : {}),
347
+ ...(scope !== undefined
348
+ ? {
349
+ scope: {
350
+ variable: scope.slice(0, separator),
351
+ value: scope.slice(separator + 1),
352
+ },
353
+ }
354
+ : {}),
355
+ },
356
+ );
357
+ return Response.json({ page });
358
+ });
359
+
360
+ app.get('/rows/:table/:rowId/delivery', async (c) =>
361
+ Response.json({
362
+ delivery: await admin.rowDelivery(
363
+ c.get('partition'),
209
364
  c.req.param('table'),
210
365
  c.req.param('rowId'),
366
+ ),
367
+ }),
368
+ );
369
+
370
+ app.get('/rows/:table/:rowId', async (c) => {
371
+ const historyLimit = intParam(c, 'historyLimit');
372
+ const row = await admin.inspectRow(
373
+ c.get('partition'),
374
+ c.req.param('table'),
375
+ c.req.param('rowId'),
376
+ historyLimit !== undefined ? { historyLimit } : {},
377
+ );
378
+ return Response.json({ row });
379
+ });
380
+
381
+ app.get('/trace', async (c) => {
382
+ const table = c.req.query('table');
383
+ const rowId = c.req.query('rowId');
384
+ const clientId = c.req.query('clientId');
385
+ if (table === undefined || rowId === undefined || clientId === undefined) {
386
+ throw new SyncError(
387
+ 'sync.invalid_request',
388
+ 'table, rowId and clientId are required',
211
389
  );
212
- return Response.json({ row });
213
- } catch (error) {
214
- return jsonError(error);
215
390
  }
391
+ const trace = await admin.traceRow(c.get('partition'), {
392
+ table,
393
+ rowId,
394
+ clientId,
395
+ });
396
+ return Response.json({ trace });
216
397
  });
217
398
 
218
399
  app.get('/scope-activity', async (c) => {
219
- try {
220
- const variable = c.req.query('variable');
221
- const value = c.req.query('value');
222
- if (variable === undefined || value === undefined) {
223
- throw new SyncError(
224
- 'sync.invalid_request',
225
- 'variable and value are required',
226
- );
227
- }
228
- const activity = await admin.scopeActivity(
229
- partitionOf(c),
230
- { variable, value },
231
- { limit: intParam(c.req.query('limit'), 50) },
400
+ const variable = c.req.query('variable');
401
+ const value = c.req.query('value');
402
+ if (variable === undefined || value === undefined) {
403
+ throw new SyncError(
404
+ 'sync.invalid_request',
405
+ 'variable and value are required',
232
406
  );
233
- return Response.json({ activity });
234
- } catch (error) {
235
- return jsonError(error);
236
407
  }
408
+ const limit = intParam(c, 'limit');
409
+ const activity = await admin.scopeActivity(
410
+ c.get('partition'),
411
+ { variable, value },
412
+ limit !== undefined ? { limit } : {},
413
+ );
414
+ return Response.json({ activity });
237
415
  });
238
416
 
239
- app.get('/horizon', async (c) => {
240
- try {
241
- const status = await admin.horizonStatus(partitionOf(c));
242
- return Response.json({ horizon: status });
243
- } catch (error) {
244
- return jsonError(error);
245
- }
246
- });
417
+ app.get('/horizon', async (c) =>
418
+ Response.json({ horizon: await admin.horizonStatus(c.get('partition')) }),
419
+ );
247
420
 
248
- app.get('/stats', async (c) => {
249
- try {
250
- const stats = await admin.stats(partitionOf(c));
251
- return Response.json({ stats });
252
- } catch (error) {
253
- return jsonError(error);
254
- }
255
- });
421
+ app.get('/stats', async (c) =>
422
+ Response.json({ stats: await admin.stats(c.get('partition')) }),
423
+ );
256
424
 
257
425
  /** The ring filters shared by the polled tail and the SSE stream. */
258
- function eventFilterOf(c: {
259
- req: { query: (k: string) => string | undefined };
260
- }): Omit<RingEventQuery, 'limit' | 'sinceMs'> {
426
+ function eventFilterOf(
427
+ c: QueryContext & { get: (key: 'partition') => string },
428
+ ): Omit<RingEventQuery, 'limit' | 'sinceMs'> {
261
429
  const type = c.req.query('type') as RingEventQuery['type'];
262
430
  const clientId = c.req.query('clientId');
263
431
  const actorId = c.req.query('actorId');
432
+ const requestId = c.req.query('requestId');
264
433
  return {
434
+ partition: c.get('partition'),
435
+ ...(requestId !== undefined ? { requestId } : {}),
265
436
  ...(type !== undefined ? { type } : {}),
266
437
  ...(clientId !== undefined ? { clientId } : {}),
267
438
  ...(actorId !== undefined ? { actorId } : {}),
268
439
  };
269
440
  }
270
441
 
271
- app.get('/events', async (c) => {
272
- try {
273
- const sinceMs = c.req.query('sinceMs');
274
- const events = admin.events({
275
- ...eventFilterOf(c),
276
- ...(sinceMs !== undefined ? { sinceMs: intParam(sinceMs, 0) } : {}),
277
- limit: intParam(c.req.query('limit'), 200),
278
- });
279
- return Response.json({ events, hasEventStream: admin.hasEventStream });
280
- } catch (error) {
281
- return jsonError(error);
282
- }
442
+ app.get('/events', (c) => {
443
+ const sinceMs = intParam(c, 'sinceMs');
444
+ const events = admin.events({
445
+ ...eventFilterOf(c),
446
+ ...(sinceMs !== undefined ? { sinceMs } : {}),
447
+ limit: intParam(c, 'limit') ?? 200,
448
+ });
449
+ return Response.json({ events });
283
450
  });
284
451
 
285
452
  // Live event tail over SSE, fed by the ring's subscribe hook. Plain
@@ -289,65 +456,83 @@ export function createSyncularAdminRoutes(
289
456
  // keeps the connection under runtime idle timeouts (Bun.serve drops an
290
457
  // idle response after 10 s by default) and intermediaries alive.
291
458
  app.get('/events/stream', (c) => {
292
- try {
293
- if (!admin.hasEventStream) {
294
- throw new SyncError(
295
- 'sync.invalid_request',
296
- 'no RingBufferEvents wired on this admin — the event stream is off',
297
- );
298
- }
299
- const filter = eventFilterOf(c);
300
- const backlogLimit = intParam(c.req.query('limit'), 50);
301
- const encoder = new TextEncoder();
302
- let unsubscribe: (() => void) | undefined;
303
- let heartbeat: ReturnType<typeof setInterval> | undefined;
304
- const stop = (): void => {
305
- unsubscribe?.();
306
- unsubscribe = undefined;
307
- if (heartbeat !== undefined) clearInterval(heartbeat);
308
- heartbeat = undefined;
309
- };
310
- const stream = new ReadableStream<Uint8Array>({
311
- start(controller) {
312
- const send = (event: SyncularServerEvent): void => {
313
- try {
314
- controller.enqueue(
315
- encoder.encode(`data: ${JSON.stringify(event)}\n\n`),
316
- );
317
- } catch {
318
- stop(); // the consumer went away mid-enqueue
319
- }
320
- };
321
- controller.enqueue(encoder.encode('retry: 2000\n\n'));
322
- for (const event of admin
323
- .events({ ...filter, limit: backlogLimit })
324
- .reverse()) {
325
- send(event);
326
- }
327
- unsubscribe = admin.subscribeEvents((event) => {
328
- if (matchesRingQuery(event, filter)) send(event);
329
- });
330
- heartbeat = setInterval(() => {
331
- try {
332
- controller.enqueue(encoder.encode(': ping\n\n'));
333
- } catch {
334
- stop();
335
- }
336
- }, 5_000);
337
- },
338
- cancel() {
339
- stop();
340
- },
341
- });
342
- return new Response(stream, {
343
- headers: {
344
- 'Content-Type': 'text/event-stream',
345
- 'Cache-Control': 'no-store',
346
- },
347
- });
348
- } catch (error) {
349
- return jsonError(error);
459
+ if (!admin.hasEventStream) {
460
+ throw new SyncError(
461
+ 'sync.invalid_request',
462
+ 'no RingBufferEvents wired on this admin — the event stream is off',
463
+ );
350
464
  }
465
+ const filter = eventFilterOf(c);
466
+ const backlogLimit = intParam(c, 'limit') ?? 50;
467
+ const encoder = new TextEncoder();
468
+ let unsubscribe: (() => void) | undefined;
469
+ let heartbeat: ReturnType<typeof setInterval> | undefined;
470
+ const stop = (): void => {
471
+ unsubscribe?.();
472
+ unsubscribe = undefined;
473
+ if (heartbeat !== undefined) clearInterval(heartbeat);
474
+ heartbeat = undefined;
475
+ };
476
+ const stream = new ReadableStream<Uint8Array>({
477
+ start(controller) {
478
+ const send = (event: SyncularServerEvent): void => {
479
+ try {
480
+ controller.enqueue(
481
+ encoder.encode(`data: ${JSON.stringify(event)}\n\n`),
482
+ );
483
+ } catch {
484
+ stop(); // the consumer went away mid-enqueue
485
+ }
486
+ };
487
+ controller.enqueue(encoder.encode('retry: 2000\n\n'));
488
+ for (const event of admin
489
+ .events({ ...filter, limit: backlogLimit })
490
+ .reverse()) {
491
+ send(event);
492
+ }
493
+ unsubscribe = admin.subscribeEvents((event) => {
494
+ if (matchesRingQuery(event, filter)) send(event);
495
+ });
496
+ heartbeat = setInterval(() => {
497
+ try {
498
+ controller.enqueue(encoder.encode(': ping\n\n'));
499
+ } catch {
500
+ stop();
501
+ }
502
+ }, 5_000);
503
+ },
504
+ cancel() {
505
+ stop();
506
+ },
507
+ });
508
+ return new Response(stream, {
509
+ headers: {
510
+ 'Content-Type': 'text/event-stream',
511
+ 'Cache-Control': 'no-store',
512
+ },
513
+ });
514
+ });
515
+
516
+ // -- operator actions (authorizeActions) ----------------------------------
517
+
518
+ app.post('/reactions/:idempotencyKey/retry', async (c) => {
519
+ const reaction = await admin.retryReaction(
520
+ c.get('partition'),
521
+ c.req.param('idempotencyKey'),
522
+ );
523
+ return Response.json({ reaction });
524
+ });
525
+
526
+ app.post('/prune', async (c) =>
527
+ Response.json({ prune: await admin.prune(c.get('partition')) }),
528
+ );
529
+
530
+ app.post('/clients/:clientId/revoke-lease', async (c) => {
531
+ const lease = await admin.revokeLease(
532
+ c.get('partition'),
533
+ c.req.param('clientId'),
534
+ );
535
+ return Response.json({ lease });
351
536
  });
352
537
 
353
538
  return app;