@syncular/server-hono 0.31.0 → 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/dist/admin.d.ts CHANGED
@@ -1,23 +1,32 @@
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 { type SyncularAdmin, type SyncularErrorHandler, type SyncularErrorMapper } from '@syncular/server';
14
18
  import { Hono } from 'hono';
15
19
  export interface AdminAuthContext {
16
- /** The partition the request targets (from the query string / route). */
20
+ /**
21
+ * The partition the request targets: `?partition=`, else the only
22
+ * partition of the deployment. Empty for the page without `?partition=`
23
+ * and for `GET /partitions`, which spans every partition.
24
+ */
17
25
  readonly partition: string;
18
26
  readonly request: Request;
19
27
  }
20
- export interface SyncularAdminRoutesOptions {
28
+ /** The console guards, shared by the Hono and Workers `admin` options. */
29
+ export interface SyncularAdminGuards {
21
30
  /**
22
31
  * REQUIRED host guard. Return `true` (or a truthy value) to allow the
23
32
  * request, a falsy value to reject it with 401. Runs before every admin
@@ -26,10 +35,25 @@ export interface SyncularAdminRoutesOptions {
26
35
  */
27
36
  readonly authorize: (ctx: AdminAuthContext) => boolean | Promise<boolean>;
28
37
  /**
29
- * Default partition for endpoints when the request omits `?partition=`.
30
- * When unset, `partition` is required on every data endpoint.
38
+ * Guard for the operator actions (retry a dead-lettered reaction, prune,
39
+ * revoke a lease), run after `authorize`. A falsy result answers 403
40
+ * `sync.forbidden`. Omitted ⇒ every action answers 403 and `GET /info`
41
+ * reports `actions: false`.
42
+ */
43
+ readonly authorizeActions?: (ctx: AdminAuthContext) => boolean | Promise<boolean>;
44
+ }
45
+ /** @internal The adapters' route options; hosts use their `admin` option. */
46
+ export interface SyncularAdminRoutesOptions extends SyncularAdminGuards {
47
+ /**
48
+ * Serve every partition-scoped request elsewhere once the guards pass.
49
+ * The page and `GET /partitions` stay local. The Workers adapter forwards
50
+ * to the partition's Durable Object, whose event ring sees that
51
+ * partition's sync rounds.
31
52
  */
32
- readonly defaultPartition?: string;
53
+ readonly forward?: (request: Request, target: {
54
+ readonly partition: string;
55
+ readonly actions: boolean;
56
+ }) => Promise<Response>;
33
57
  /**
34
58
  * Host error reporting: receives every exception that is not a
35
59
  * `SyncError`, which answers 500 `sync.internal_error` (§10.2).
@@ -42,8 +66,11 @@ export interface SyncularAdminRoutesOptions {
42
66
  readonly mapError?: SyncularErrorMapper;
43
67
  }
44
68
  /**
45
- * Build the mountable admin sub-app. Mount it under any prefix, e.g.
46
- * `app.route('/admin', createSyncularAdminRoutes(admin, { authorize }))`.
47
- * Throws if `authorize` is missing — admin never mounts default-open.
69
+ * @internal Build the admin sub-app the adapters mount. Throws if
70
+ * `authorize` is missing — admin never mounts default-open.
48
71
  */
49
- export declare function createSyncularAdminRoutes(admin: SyncularAdmin, options: SyncularAdminRoutesOptions): Hono;
72
+ export declare function createSyncularAdminRoutes(admin: SyncularAdmin, options: SyncularAdminRoutesOptions): Hono<{
73
+ Variables: {
74
+ partition: string;
75
+ };
76
+ }>;
package/dist/admin.js CHANGED
@@ -1,209 +1,269 @@
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
- import { adapterSyncError, errorBody, matchesRingQuery, SyncError, } from '@syncular/server';
17
+ import { errorBody, adapterSyncError, matchesRingQuery, SyncError, } from '@syncular/server';
14
18
  import { Hono } from 'hono';
15
19
  import { ADMIN_CONSOLE_HTML } from './admin-page.js';
16
- function intParam(value, fallback) {
20
+ /** An optional integer query parameter; a malformed value is a 400. */
21
+ function intParam(c, name) {
22
+ const value = c.req.query(name);
17
23
  if (value === undefined)
18
- return fallback;
19
- const parsed = Number.parseInt(value, 10);
20
- return Number.isFinite(parsed) ? parsed : fallback;
24
+ return undefined;
25
+ if (!/^-?\d+$/.test(value)) {
26
+ throw new SyncError('sync.invalid_request', 'query parameter must be an integer', JSON.stringify({ parameter: name }));
27
+ }
28
+ return Number.parseInt(value, 10);
21
29
  }
22
30
  /**
23
- * Build the mountable admin sub-app. Mount it under any prefix, e.g.
24
- * `app.route('/admin', createSyncularAdminRoutes(admin, { authorize }))`.
25
- * Throws if `authorize` is missing — admin never mounts default-open.
31
+ * @internal Build the admin sub-app the adapters mount. Throws if
32
+ * `authorize` is missing — admin never mounts default-open.
26
33
  */
27
34
  export function createSyncularAdminRoutes(admin, options) {
28
35
  if (typeof options.authorize !== 'function') {
29
- throw new Error('createSyncularAdminRoutes: an `authorize` guard is required — admin never mounts default-open');
36
+ throw new Error('admin: an `authorize` guard is required — admin never mounts default-open');
30
37
  }
31
38
  const app = new Hono();
32
39
  const jsonError = (error) => {
33
40
  const sync = adapterSyncError(error, (error, context) => options.onError?.(error, context), 'admin', (error, context) => options.mapError?.(error, context));
34
41
  return Response.json(errorBody(sync), { status: sync.httpStatus });
35
42
  };
36
- // Throws outside a route's own try, such as from `authorize`.
43
+ // Every route throws its failures; this answers them as catalog errors.
37
44
  app.onError((error) => jsonError(error));
38
- /** Resolve the request's partition (query, else default) — required. */
39
- function partitionOf(c) {
40
- const partition = c.req.query('partition') ?? options.defaultPartition;
41
- if (partition === undefined || partition.length === 0) {
42
- throw new SyncError('sync.invalid_request', 'partition is required');
45
+ /** Run the host guards; actions also need `authorizeActions`. */
46
+ async function guard(request, partition) {
47
+ const context = { partition, request };
48
+ if (!(await options.authorize(context))) {
49
+ throw new SyncError('sync.auth_required');
50
+ }
51
+ if (request.method === 'POST' &&
52
+ !(await options.authorizeActions?.(context))) {
53
+ throw new SyncError('sync.forbidden', 'admin actions are not authorized');
43
54
  }
44
- return partition;
45
55
  }
46
- // Guard every route (page + data) up front.
56
+ // The single static console page (zero framework, no build step).
57
+ app.get('/', async (c) => {
58
+ await guard(c.req.raw, c.req.query('partition') ?? '');
59
+ return c.html(ADMIN_CONSOLE_HTML, 200, { 'Cache-Control': 'no-store' });
60
+ });
61
+ // Cross-partition fleet view: the ONE endpoint that is not partition-
62
+ // scoped. Its guard sees no partition, so a guard that grants single
63
+ // partitions never grants the whole fleet.
64
+ app.get('/partitions', async (c) => {
65
+ await guard(c.req.raw, '');
66
+ const limit = intParam(c, 'limit');
67
+ const offset = intParam(c, 'offset');
68
+ return Response.json(await admin.partitionsOverview({
69
+ ...(limit !== undefined ? { limit } : {}),
70
+ ...(offset !== undefined ? { offset } : {}),
71
+ }));
72
+ });
73
+ // Every other route is partition-scoped: `?partition=`, else the
74
+ // deployment's only partition. The guards run on the resolved partition.
47
75
  app.use('*', async (c, next) => {
48
- let partition;
49
- try {
50
- partition = c.req.query('partition') ?? options.defaultPartition ?? '';
51
- }
52
- catch {
53
- partition = '';
76
+ let partition = c.req.query('partition') ?? '';
77
+ if (partition === '') {
78
+ const partitions = await admin.listPartitions();
79
+ if (partitions.length !== 1) {
80
+ // The registry size is fleet knowledge: only the fleet guard may
81
+ // learn that the partition is ambiguous.
82
+ await guard(c.req.raw, '');
83
+ throw new SyncError('sync.invalid_request', 'partition is required', JSON.stringify({ parameter: 'partition' }));
84
+ }
85
+ partition = partitions[0];
54
86
  }
55
- const ok = await options.authorize({ partition, request: c.req.raw });
56
- if (!ok)
57
- return jsonError(new SyncError('sync.auth_required'));
87
+ await guard(c.req.raw, partition);
88
+ c.set('partition', partition);
58
89
  await next();
59
90
  });
60
- // The single static console page (zero framework, no build step).
61
- app.get('/', (c) => c.html(ADMIN_CONSOLE_HTML, 200, { 'Cache-Control': 'no-store' }));
91
+ const forward = options.forward;
92
+ if (forward !== undefined) {
93
+ app.all('*', (c) => forward(c.req.raw, {
94
+ partition: c.get('partition'),
95
+ actions: options.authorizeActions !== undefined,
96
+ }));
97
+ return app;
98
+ }
99
+ app.get('/info', (c) => Response.json({
100
+ partition: c.get('partition'),
101
+ hasEventStream: admin.hasEventStream,
102
+ actions: options.authorizeActions !== undefined,
103
+ realtime: admin.hasRealtime,
104
+ ...(admin.schemaVersion !== undefined
105
+ ? { schemaVersion: admin.schemaVersion }
106
+ : {}),
107
+ tables: admin.tables(),
108
+ }));
62
109
  app.get('/clients', async (c) => {
63
- try {
64
- const clients = await admin.listClients(partitionOf(c));
65
- return Response.json({ clients });
66
- }
67
- catch (error) {
68
- return jsonError(error);
110
+ const sort = c.req.query('sort');
111
+ if (sort !== undefined && sort !== 'seen' && sort !== 'lag') {
112
+ throw new SyncError('sync.invalid_request', 'sort must be seen or lag', JSON.stringify({ sort }));
69
113
  }
114
+ const limit = intParam(c, 'limit');
115
+ return Response.json(await admin.listClients(c.get('partition'), {
116
+ ...(limit !== undefined ? { limit } : {}),
117
+ ...(sort !== undefined ? { sort } : {}),
118
+ }));
119
+ });
120
+ app.get('/actors', async (c) => Response.json({ actors: await admin.actors(c.get('partition')) }));
121
+ app.get('/search', async (c) => Response.json({
122
+ search: await admin.search(c.get('partition'), c.req.query('q') ?? ''),
123
+ }));
124
+ app.get('/writes/:clientCommitId', async (c) => Response.json({
125
+ write: await admin.findWrite(c.get('partition'), c.req.param('clientCommitId')),
126
+ }));
127
+ app.get('/tables', async (c) => {
128
+ const counts = await admin.tableCounts(c.get('partition'));
129
+ return Response.json({
130
+ tables: admin
131
+ .tables()
132
+ .map((table) => ({ ...table, rowCount: counts[table.name] ?? 0 })),
133
+ });
70
134
  });
71
135
  app.get('/clients/:clientId', async (c) => {
72
- try {
73
- const detail = await admin.clientDetail(partitionOf(c), c.req.param('clientId'), { eventLimit: intParam(c.req.query('eventLimit'), 100) });
74
- return Response.json({ detail });
75
- }
76
- catch (error) {
77
- return jsonError(error);
78
- }
136
+ const eventLimit = intParam(c, 'eventLimit');
137
+ const detail = await admin.clientDetail(c.get('partition'), c.req.param('clientId'), eventLimit !== undefined ? { eventLimit } : {});
138
+ return Response.json({ detail });
79
139
  });
80
- app.get('/metrics', async (c) => {
81
- try {
82
- const metrics = admin.metrics(partitionOf(c), {
83
- windowMs: intParam(c.req.query('windowMs'), 5 * 60 * 1000),
84
- });
85
- return Response.json({ metrics, hasEventStream: admin.hasEventStream });
86
- }
87
- catch (error) {
88
- return jsonError(error);
89
- }
140
+ app.get('/metrics', (c) => {
141
+ const windowMs = intParam(c, 'windowMs');
142
+ const metrics = admin.metrics(c.get('partition'), windowMs !== undefined ? { windowMs } : {});
143
+ return Response.json({ metrics });
90
144
  });
91
- // Cross-partition fleet view: the ONE endpoint that is not partition-
92
- // scoped (the guard still runs, with `partition` empty unless passed).
93
- app.get('/partitions', async () => {
94
- try {
95
- const partitions = await admin.partitionsOverview();
96
- return Response.json({ partitions });
97
- }
98
- catch (error) {
99
- return jsonError(error);
100
- }
145
+ app.get('/errors', (c) => {
146
+ const windowMs = intParam(c, 'windowMs');
147
+ const errors = admin.errors(c.get('partition'), windowMs !== undefined ? { windowMs } : {});
148
+ return Response.json({ errors });
101
149
  });
102
150
  app.get('/commits', async (c) => {
103
- try {
104
- const table = c.req.query('table');
105
- const commits = await admin.listCommits(partitionOf(c), {
106
- afterSeq: intParam(c.req.query('afterSeq'), 0),
107
- limit: intParam(c.req.query('limit'), 50),
108
- ...(table !== undefined ? { table } : {}),
109
- });
110
- return Response.json({ commits });
111
- }
112
- catch (error) {
113
- return jsonError(error);
114
- }
151
+ const table = c.req.query('table');
152
+ const afterSeq = intParam(c, 'afterSeq');
153
+ const beforeSeq = intParam(c, 'beforeSeq');
154
+ const limit = intParam(c, 'limit');
155
+ const changeSample = intParam(c, 'sample');
156
+ const commits = await admin.listCommits(c.get('partition'), {
157
+ ...(changeSample !== undefined ? { changeSample } : {}),
158
+ ...(afterSeq !== undefined ? { afterSeq } : {}),
159
+ ...(beforeSeq !== undefined ? { beforeSeq } : {}),
160
+ ...(limit !== undefined ? { limit } : {}),
161
+ ...(table !== undefined ? { table } : {}),
162
+ });
163
+ return Response.json({ commits });
164
+ });
165
+ app.get('/commits/:commitSeq{[0-9]+}', async (c) => {
166
+ const commit = await admin.commitDetail(c.get('partition'), Number.parseInt(c.req.param('commitSeq'), 10));
167
+ return Response.json({ commit });
115
168
  });
116
169
  app.get('/reactions', async (c) => {
117
- try {
118
- const status = c.req.query('status');
119
- const type = c.req.query('type');
120
- const allowed = new Set([
121
- 'pending',
122
- 'leased',
123
- 'completed',
124
- 'dead-letter',
125
- ]);
126
- if (status !== undefined && !allowed.has(status)) {
127
- throw new SyncError('sync.invalid_request', 'invalid reaction status');
128
- }
129
- const reactions = await admin.listReactions(partitionOf(c), {
130
- ...(status !== undefined
131
- ? { statuses: [status] }
132
- : {}),
133
- ...(type !== undefined ? { types: [type] } : {}),
134
- limit: intParam(c.req.query('limit'), 100),
135
- });
136
- return Response.json({ reactions });
137
- }
138
- catch (error) {
139
- return jsonError(error);
170
+ const status = c.req.query('status');
171
+ const type = c.req.query('type');
172
+ const allowed = new Set([
173
+ 'pending',
174
+ 'leased',
175
+ 'completed',
176
+ 'dead-letter',
177
+ ]);
178
+ if (status !== undefined && !allowed.has(status)) {
179
+ throw new SyncError('sync.invalid_request', 'invalid reaction status');
140
180
  }
181
+ const limit = intParam(c, 'limit');
182
+ const reactions = await admin.listReactions(c.get('partition'), {
183
+ ...(status !== undefined ? { statuses: [status] } : {}),
184
+ ...(type !== undefined ? { types: [type] } : {}),
185
+ ...(limit !== undefined ? { limit } : {}),
186
+ });
187
+ return Response.json({ reactions });
141
188
  });
142
- app.get('/rows/:table/:rowId', async (c) => {
143
- try {
144
- const row = await admin.inspectRow(partitionOf(c), c.req.param('table'), c.req.param('rowId'));
145
- return Response.json({ row });
146
- }
147
- catch (error) {
148
- return jsonError(error);
189
+ app.get('/rows/:table', async (c) => {
190
+ const scope = c.req.query('scope');
191
+ const separator = scope?.indexOf(':') ?? -1;
192
+ if (scope !== undefined && separator <= 0) {
193
+ throw new SyncError('sync.invalid_request', 'scope must be variable:value', JSON.stringify({ scope }));
149
194
  }
195
+ const afterRowId = c.req.query('afterRowId');
196
+ const limit = intParam(c, 'limit');
197
+ const page = await admin.listRows(c.get('partition'), c.req.param('table'), {
198
+ ...(afterRowId !== undefined ? { afterRowId } : {}),
199
+ ...(limit !== undefined ? { limit } : {}),
200
+ ...(scope !== undefined
201
+ ? {
202
+ scope: {
203
+ variable: scope.slice(0, separator),
204
+ value: scope.slice(separator + 1),
205
+ },
206
+ }
207
+ : {}),
208
+ });
209
+ return Response.json({ page });
150
210
  });
151
- app.get('/scope-activity', async (c) => {
152
- try {
153
- const variable = c.req.query('variable');
154
- const value = c.req.query('value');
155
- if (variable === undefined || value === undefined) {
156
- throw new SyncError('sync.invalid_request', 'variable and value are required');
157
- }
158
- const activity = await admin.scopeActivity(partitionOf(c), { variable, value }, { limit: intParam(c.req.query('limit'), 50) });
159
- return Response.json({ activity });
160
- }
161
- catch (error) {
162
- return jsonError(error);
163
- }
211
+ app.get('/rows/:table/:rowId/delivery', async (c) => Response.json({
212
+ delivery: await admin.rowDelivery(c.get('partition'), c.req.param('table'), c.req.param('rowId')),
213
+ }));
214
+ app.get('/rows/:table/:rowId', async (c) => {
215
+ const historyLimit = intParam(c, 'historyLimit');
216
+ const row = await admin.inspectRow(c.get('partition'), c.req.param('table'), c.req.param('rowId'), historyLimit !== undefined ? { historyLimit } : {});
217
+ return Response.json({ row });
164
218
  });
165
- app.get('/horizon', async (c) => {
166
- try {
167
- const status = await admin.horizonStatus(partitionOf(c));
168
- return Response.json({ horizon: status });
169
- }
170
- catch (error) {
171
- return jsonError(error);
219
+ app.get('/trace', async (c) => {
220
+ const table = c.req.query('table');
221
+ const rowId = c.req.query('rowId');
222
+ const clientId = c.req.query('clientId');
223
+ if (table === undefined || rowId === undefined || clientId === undefined) {
224
+ throw new SyncError('sync.invalid_request', 'table, rowId and clientId are required');
172
225
  }
226
+ const trace = await admin.traceRow(c.get('partition'), {
227
+ table,
228
+ rowId,
229
+ clientId,
230
+ });
231
+ return Response.json({ trace });
173
232
  });
174
- app.get('/stats', async (c) => {
175
- try {
176
- const stats = await admin.stats(partitionOf(c));
177
- return Response.json({ stats });
178
- }
179
- catch (error) {
180
- return jsonError(error);
233
+ app.get('/scope-activity', async (c) => {
234
+ const variable = c.req.query('variable');
235
+ const value = c.req.query('value');
236
+ if (variable === undefined || value === undefined) {
237
+ throw new SyncError('sync.invalid_request', 'variable and value are required');
181
238
  }
239
+ const limit = intParam(c, 'limit');
240
+ const activity = await admin.scopeActivity(c.get('partition'), { variable, value }, limit !== undefined ? { limit } : {});
241
+ return Response.json({ activity });
182
242
  });
243
+ app.get('/horizon', async (c) => Response.json({ horizon: await admin.horizonStatus(c.get('partition')) }));
244
+ app.get('/stats', async (c) => Response.json({ stats: await admin.stats(c.get('partition')) }));
183
245
  /** The ring filters shared by the polled tail and the SSE stream. */
184
246
  function eventFilterOf(c) {
185
247
  const type = c.req.query('type');
186
248
  const clientId = c.req.query('clientId');
187
249
  const actorId = c.req.query('actorId');
250
+ const requestId = c.req.query('requestId');
188
251
  return {
252
+ partition: c.get('partition'),
253
+ ...(requestId !== undefined ? { requestId } : {}),
189
254
  ...(type !== undefined ? { type } : {}),
190
255
  ...(clientId !== undefined ? { clientId } : {}),
191
256
  ...(actorId !== undefined ? { actorId } : {}),
192
257
  };
193
258
  }
194
- app.get('/events', async (c) => {
195
- try {
196
- const sinceMs = c.req.query('sinceMs');
197
- const events = admin.events({
198
- ...eventFilterOf(c),
199
- ...(sinceMs !== undefined ? { sinceMs: intParam(sinceMs, 0) } : {}),
200
- limit: intParam(c.req.query('limit'), 200),
201
- });
202
- return Response.json({ events, hasEventStream: admin.hasEventStream });
203
- }
204
- catch (error) {
205
- return jsonError(error);
206
- }
259
+ app.get('/events', (c) => {
260
+ const sinceMs = intParam(c, 'sinceMs');
261
+ const events = admin.events({
262
+ ...eventFilterOf(c),
263
+ ...(sinceMs !== undefined ? { sinceMs } : {}),
264
+ limit: intParam(c, 'limit') ?? 200,
265
+ });
266
+ return Response.json({ events });
207
267
  });
208
268
  // Live event tail over SSE, fed by the ring's subscribe hook. Plain
209
269
  // web-streams (no filesystem, no Node API), so it serves identically on
@@ -212,65 +272,70 @@ export function createSyncularAdminRoutes(admin, options) {
212
272
  // keeps the connection under runtime idle timeouts (Bun.serve drops an
213
273
  // idle response after 10 s by default) and intermediaries alive.
214
274
  app.get('/events/stream', (c) => {
215
- try {
216
- if (!admin.hasEventStream) {
217
- throw new SyncError('sync.invalid_request', 'no RingBufferEvents wired on this admin — the event stream is off');
218
- }
219
- const filter = eventFilterOf(c);
220
- const backlogLimit = intParam(c.req.query('limit'), 50);
221
- const encoder = new TextEncoder();
222
- let unsubscribe;
223
- let heartbeat;
224
- const stop = () => {
225
- unsubscribe?.();
226
- unsubscribe = undefined;
227
- if (heartbeat !== undefined)
228
- clearInterval(heartbeat);
229
- heartbeat = undefined;
230
- };
231
- const stream = new ReadableStream({
232
- start(controller) {
233
- const send = (event) => {
234
- try {
235
- controller.enqueue(encoder.encode(`data: ${JSON.stringify(event)}\n\n`));
236
- }
237
- catch {
238
- stop(); // the consumer went away mid-enqueue
239
- }
240
- };
241
- controller.enqueue(encoder.encode('retry: 2000\n\n'));
242
- for (const event of admin
243
- .events({ ...filter, limit: backlogLimit })
244
- .reverse()) {
275
+ if (!admin.hasEventStream) {
276
+ throw new SyncError('sync.invalid_request', 'no RingBufferEvents wired on this admin — the event stream is off');
277
+ }
278
+ const filter = eventFilterOf(c);
279
+ const backlogLimit = intParam(c, 'limit') ?? 50;
280
+ const encoder = new TextEncoder();
281
+ let unsubscribe;
282
+ let heartbeat;
283
+ const stop = () => {
284
+ unsubscribe?.();
285
+ unsubscribe = undefined;
286
+ if (heartbeat !== undefined)
287
+ clearInterval(heartbeat);
288
+ heartbeat = undefined;
289
+ };
290
+ const stream = new ReadableStream({
291
+ start(controller) {
292
+ const send = (event) => {
293
+ try {
294
+ controller.enqueue(encoder.encode(`data: ${JSON.stringify(event)}\n\n`));
295
+ }
296
+ catch {
297
+ stop(); // the consumer went away mid-enqueue
298
+ }
299
+ };
300
+ controller.enqueue(encoder.encode('retry: 2000\n\n'));
301
+ for (const event of admin
302
+ .events({ ...filter, limit: backlogLimit })
303
+ .reverse()) {
304
+ send(event);
305
+ }
306
+ unsubscribe = admin.subscribeEvents((event) => {
307
+ if (matchesRingQuery(event, filter))
245
308
  send(event);
309
+ });
310
+ heartbeat = setInterval(() => {
311
+ try {
312
+ controller.enqueue(encoder.encode(': ping\n\n'));
246
313
  }
247
- unsubscribe = admin.subscribeEvents((event) => {
248
- if (matchesRingQuery(event, filter))
249
- send(event);
250
- });
251
- heartbeat = setInterval(() => {
252
- try {
253
- controller.enqueue(encoder.encode(': ping\n\n'));
254
- }
255
- catch {
256
- stop();
257
- }
258
- }, 5_000);
259
- },
260
- cancel() {
261
- stop();
262
- },
263
- });
264
- return new Response(stream, {
265
- headers: {
266
- 'Content-Type': 'text/event-stream',
267
- 'Cache-Control': 'no-store',
268
- },
269
- });
270
- }
271
- catch (error) {
272
- return jsonError(error);
273
- }
314
+ catch {
315
+ stop();
316
+ }
317
+ }, 5_000);
318
+ },
319
+ cancel() {
320
+ stop();
321
+ },
322
+ });
323
+ return new Response(stream, {
324
+ headers: {
325
+ 'Content-Type': 'text/event-stream',
326
+ 'Cache-Control': 'no-store',
327
+ },
328
+ });
329
+ });
330
+ // -- operator actions (authorizeActions) ----------------------------------
331
+ app.post('/reactions/:idempotencyKey/retry', async (c) => {
332
+ const reaction = await admin.retryReaction(c.get('partition'), c.req.param('idempotencyKey'));
333
+ return Response.json({ reaction });
334
+ });
335
+ app.post('/prune', async (c) => Response.json({ prune: await admin.prune(c.get('partition')) }));
336
+ app.post('/clients/:clientId/revoke-lease', async (c) => {
337
+ const lease = await admin.revokeLease(c.get('partition'), c.req.param('clientId'));
338
+ return Response.json({ lease });
274
339
  });
275
340
  return app;
276
341
  }