@syncular/server-hono 0.30.16 → 0.32.0

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,36 +1,46 @@
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
+ type SyncularErrorMapper,
22
27
  type SyncularServerEvent,
23
28
  } from '@syncular/server';
24
29
  import { Hono } from 'hono';
25
30
  import { ADMIN_CONSOLE_HTML } from './admin-page';
26
31
 
27
32
  export interface AdminAuthContext {
28
- /** 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
+ */
29
38
  readonly partition: string;
30
39
  readonly request: Request;
31
40
  }
32
41
 
33
- export interface SyncularAdminRoutesOptions {
42
+ /** The console guards, shared by the Hono and Workers `admin` options. */
43
+ export interface SyncularAdminGuards {
34
44
  /**
35
45
  * REQUIRED host guard. Return `true` (or a truthy value) to allow the
36
46
  * request, a falsy value to reject it with 401. Runs before every admin
@@ -39,236 +49,404 @@ export interface SyncularAdminRoutesOptions {
39
49
  */
40
50
  readonly authorize: (ctx: AdminAuthContext) => boolean | Promise<boolean>;
41
51
  /**
42
- * Default partition for endpoints when the request omits `?partition=`.
43
- * 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`.
44
56
  */
45
- 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>;
46
74
  /**
47
75
  * Host error reporting: receives every exception that is not a
48
76
  * `SyncError`, which answers 500 `sync.internal_error` (§10.2).
49
77
  */
50
78
  readonly onError?: SyncularErrorHandler;
79
+ /**
80
+ * Optional synchronous mapper (§10.2) for those exceptions; return a catalog
81
+ * `SyncError` to answer with it, or `undefined` for `sync.internal_error`.
82
+ */
83
+ readonly mapError?: SyncularErrorMapper;
51
84
  }
52
85
 
53
- function intParam(value: string | undefined, fallback: number): number {
54
- if (value === undefined) return fallback;
55
- const parsed = Number.parseInt(value, 10);
56
- 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);
57
100
  }
58
101
 
59
102
  /**
60
- * Build the mountable admin sub-app. Mount it under any prefix, e.g.
61
- * `app.route('/admin', createSyncularAdminRoutes(admin, { authorize }))`.
62
- * 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.
63
105
  */
64
106
  export function createSyncularAdminRoutes(
65
107
  admin: SyncularAdmin,
66
108
  options: SyncularAdminRoutesOptions,
67
- ): Hono {
109
+ ): Hono<{ Variables: { partition: string } }> {
68
110
  if (typeof options.authorize !== 'function') {
69
111
  throw new Error(
70
- 'createSyncularAdminRoutes: an `authorize` guard is required — admin never mounts default-open',
112
+ 'admin: an `authorize` guard is required — admin never mounts default-open',
71
113
  );
72
114
  }
73
- const app = new Hono();
115
+ const app = new Hono<{ Variables: { partition: string } }>();
74
116
  const jsonError = (error: unknown): Response => {
75
- const sync = adapterSyncError(error, options.onError, 'admin');
117
+ const sync = adapterSyncError(
118
+ error,
119
+ (error, context) => options.onError?.(error, context),
120
+ 'admin',
121
+ (error, context) => options.mapError?.(error, context),
122
+ );
76
123
  return Response.json(errorBody(sync), { status: sync.httpStatus });
77
124
  };
78
- // Throws outside a route's own try, such as from `authorize`.
125
+ // Every route throws its failures; this answers them as catalog errors.
79
126
  app.onError((error) => jsonError(error));
80
127
 
81
- /** Resolve the request's partition (query, else default) — required. */
82
- function partitionOf(c: {
83
- req: { query: (k: string) => string | undefined };
84
- }): string {
85
- const partition = c.req.query('partition') ?? options.defaultPartition;
86
- if (partition === undefined || partition.length === 0) {
87
- 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');
88
139
  }
89
- return partition;
90
140
  }
91
141
 
92
- // 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.
93
165
  app.use('*', async (c, next) => {
94
- let partition: string;
95
- try {
96
- partition = c.req.query('partition') ?? options.defaultPartition ?? '';
97
- } catch {
98
- 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]!;
99
180
  }
100
- const ok = await options.authorize({ partition, request: c.req.raw });
101
- if (!ok) return jsonError(new SyncError('sync.auth_required'));
181
+ await guard(c.req.raw, partition);
182
+ c.set('partition', partition);
102
183
  await next();
103
184
  });
104
185
 
105
- // The single static console page (zero framework, no build step).
106
- app.get('/', (c) =>
107
- 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
+ }),
108
208
  );
109
209
 
110
210
  app.get('/clients', async (c) => {
111
- try {
112
- const clients = await admin.listClients(partitionOf(c));
113
- return Response.json({ clients });
114
- } catch (error) {
115
- 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
+ );
116
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
+ });
117
254
  });
118
255
 
119
256
  app.get('/clients/:clientId', async (c) => {
120
- try {
121
- const detail = await admin.clientDetail(
122
- partitionOf(c),
123
- c.req.param('clientId'),
124
- { eventLimit: intParam(c.req.query('eventLimit'), 100) },
125
- );
126
- return Response.json({ detail });
127
- } catch (error) {
128
- return jsonError(error);
129
- }
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 });
130
264
  });
131
265
 
132
- app.get('/metrics', async (c) => {
133
- try {
134
- const metrics = admin.metrics(partitionOf(c), {
135
- windowMs: intParam(c.req.query('windowMs'), 5 * 60 * 1000),
136
- });
137
- return Response.json({ metrics, hasEventStream: admin.hasEventStream });
138
- } catch (error) {
139
- return jsonError(error);
140
- }
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 });
141
273
  });
142
274
 
143
- // Cross-partition fleet view: the ONE endpoint that is not partition-
144
- // scoped (the guard still runs, with `partition` empty unless passed).
145
- app.get('/partitions', async () => {
146
- try {
147
- const partitions = await admin.partitionsOverview();
148
- return Response.json({ partitions });
149
- } catch (error) {
150
- return jsonError(error);
151
- }
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 });
152
282
  });
153
283
 
154
284
  app.get('/commits', async (c) => {
155
- try {
156
- const table = c.req.query('table');
157
- const commits = await admin.listCommits(partitionOf(c), {
158
- afterSeq: intParam(c.req.query('afterSeq'), 0),
159
- limit: intParam(c.req.query('limit'), 50),
160
- ...(table !== undefined ? { table } : {}),
161
- });
162
- return Response.json({ commits });
163
- } catch (error) {
164
- return jsonError(error);
165
- }
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 });
166
306
  });
167
307
 
168
308
  app.get('/reactions', async (c) => {
169
- try {
170
- const status = c.req.query('status');
171
- const type = c.req.query('type');
172
- const allowed = new Set<ReactionStatus>([
173
- 'pending',
174
- 'leased',
175
- 'completed',
176
- 'dead-letter',
177
- ]);
178
- if (status !== undefined && !allowed.has(status as ReactionStatus)) {
179
- throw new SyncError('sync.invalid_request', 'invalid reaction status');
180
- }
181
- const reactions = await admin.listReactions(partitionOf(c), {
182
- ...(status !== undefined
183
- ? { statuses: [status as ReactionStatus] }
184
- : {}),
185
- ...(type !== undefined ? { types: [type] } : {}),
186
- limit: intParam(c.req.query('limit'), 100),
187
- });
188
- return Response.json({ reactions });
189
- } catch (error) {
190
- 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');
191
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 });
192
327
  });
193
328
 
194
- app.get('/rows/:table/:rowId', async (c) => {
195
- try {
196
- const row = await admin.inspectRow(
197
- 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'),
198
364
  c.req.param('table'),
199
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',
200
389
  );
201
- return Response.json({ row });
202
- } catch (error) {
203
- return jsonError(error);
204
390
  }
391
+ const trace = await admin.traceRow(c.get('partition'), {
392
+ table,
393
+ rowId,
394
+ clientId,
395
+ });
396
+ return Response.json({ trace });
205
397
  });
206
398
 
207
399
  app.get('/scope-activity', async (c) => {
208
- try {
209
- const variable = c.req.query('variable');
210
- const value = c.req.query('value');
211
- if (variable === undefined || value === undefined) {
212
- throw new SyncError(
213
- 'sync.invalid_request',
214
- 'variable and value are required',
215
- );
216
- }
217
- const activity = await admin.scopeActivity(
218
- partitionOf(c),
219
- { variable, value },
220
- { 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',
221
406
  );
222
- return Response.json({ activity });
223
- } catch (error) {
224
- return jsonError(error);
225
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 });
226
415
  });
227
416
 
228
- app.get('/horizon', async (c) => {
229
- try {
230
- const status = await admin.horizonStatus(partitionOf(c));
231
- return Response.json({ horizon: status });
232
- } catch (error) {
233
- return jsonError(error);
234
- }
235
- });
417
+ app.get('/horizon', async (c) =>
418
+ Response.json({ horizon: await admin.horizonStatus(c.get('partition')) }),
419
+ );
236
420
 
237
- app.get('/stats', async (c) => {
238
- try {
239
- const stats = await admin.stats(partitionOf(c));
240
- return Response.json({ stats });
241
- } catch (error) {
242
- return jsonError(error);
243
- }
244
- });
421
+ app.get('/stats', async (c) =>
422
+ Response.json({ stats: await admin.stats(c.get('partition')) }),
423
+ );
245
424
 
246
425
  /** The ring filters shared by the polled tail and the SSE stream. */
247
- function eventFilterOf(c: {
248
- req: { query: (k: string) => string | undefined };
249
- }): Omit<RingEventQuery, 'limit' | 'sinceMs'> {
426
+ function eventFilterOf(
427
+ c: QueryContext & { get: (key: 'partition') => string },
428
+ ): Omit<RingEventQuery, 'limit' | 'sinceMs'> {
250
429
  const type = c.req.query('type') as RingEventQuery['type'];
251
430
  const clientId = c.req.query('clientId');
252
431
  const actorId = c.req.query('actorId');
432
+ const requestId = c.req.query('requestId');
253
433
  return {
434
+ partition: c.get('partition'),
435
+ ...(requestId !== undefined ? { requestId } : {}),
254
436
  ...(type !== undefined ? { type } : {}),
255
437
  ...(clientId !== undefined ? { clientId } : {}),
256
438
  ...(actorId !== undefined ? { actorId } : {}),
257
439
  };
258
440
  }
259
441
 
260
- app.get('/events', async (c) => {
261
- try {
262
- const sinceMs = c.req.query('sinceMs');
263
- const events = admin.events({
264
- ...eventFilterOf(c),
265
- ...(sinceMs !== undefined ? { sinceMs: intParam(sinceMs, 0) } : {}),
266
- limit: intParam(c.req.query('limit'), 200),
267
- });
268
- return Response.json({ events, hasEventStream: admin.hasEventStream });
269
- } catch (error) {
270
- return jsonError(error);
271
- }
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 });
272
450
  });
273
451
 
274
452
  // Live event tail over SSE, fed by the ring's subscribe hook. Plain
@@ -278,65 +456,83 @@ export function createSyncularAdminRoutes(
278
456
  // keeps the connection under runtime idle timeouts (Bun.serve drops an
279
457
  // idle response after 10 s by default) and intermediaries alive.
280
458
  app.get('/events/stream', (c) => {
281
- try {
282
- if (!admin.hasEventStream) {
283
- throw new SyncError(
284
- 'sync.invalid_request',
285
- 'no RingBufferEvents wired on this admin — the event stream is off',
286
- );
287
- }
288
- const filter = eventFilterOf(c);
289
- const backlogLimit = intParam(c.req.query('limit'), 50);
290
- const encoder = new TextEncoder();
291
- let unsubscribe: (() => void) | undefined;
292
- let heartbeat: ReturnType<typeof setInterval> | undefined;
293
- const stop = (): void => {
294
- unsubscribe?.();
295
- unsubscribe = undefined;
296
- if (heartbeat !== undefined) clearInterval(heartbeat);
297
- heartbeat = undefined;
298
- };
299
- const stream = new ReadableStream<Uint8Array>({
300
- start(controller) {
301
- const send = (event: SyncularServerEvent): void => {
302
- try {
303
- controller.enqueue(
304
- encoder.encode(`data: ${JSON.stringify(event)}\n\n`),
305
- );
306
- } catch {
307
- stop(); // the consumer went away mid-enqueue
308
- }
309
- };
310
- controller.enqueue(encoder.encode('retry: 2000\n\n'));
311
- for (const event of admin
312
- .events({ ...filter, limit: backlogLimit })
313
- .reverse()) {
314
- send(event);
315
- }
316
- unsubscribe = admin.subscribeEvents((event) => {
317
- if (matchesRingQuery(event, filter)) send(event);
318
- });
319
- heartbeat = setInterval(() => {
320
- try {
321
- controller.enqueue(encoder.encode(': ping\n\n'));
322
- } catch {
323
- stop();
324
- }
325
- }, 5_000);
326
- },
327
- cancel() {
328
- stop();
329
- },
330
- });
331
- return new Response(stream, {
332
- headers: {
333
- 'Content-Type': 'text/event-stream',
334
- 'Cache-Control': 'no-store',
335
- },
336
- });
337
- } catch (error) {
338
- 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
+ );
339
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 });
340
536
  });
341
537
 
342
538
  return app;