@sixb/server 0.1.20 → 0.1.21

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.
Files changed (70) hide show
  1. package/dist/artifacts/frame.d.ts +13 -0
  2. package/dist/artifacts/frame.d.ts.map +1 -0
  3. package/dist/auth/browser-origin.d.ts +5 -0
  4. package/dist/auth/browser-origin.d.ts.map +1 -1
  5. package/dist/auth/public-routes.d.ts.map +1 -1
  6. package/dist/files/content.d.ts +2 -3
  7. package/dist/files/content.d.ts.map +1 -1
  8. package/dist/index.js +3427 -2402
  9. package/dist/index.js.map +23 -17
  10. package/dist/openapi/tags.d.ts +10 -2
  11. package/dist/openapi/tags.d.ts.map +1 -1
  12. package/dist/registerRoutes.d.ts +3 -0
  13. package/dist/registerRoutes.d.ts.map +1 -1
  14. package/dist/routes/activity.d.ts +35 -0
  15. package/dist/routes/activity.d.ts.map +1 -0
  16. package/dist/routes/agents.d.ts +18 -27
  17. package/dist/routes/agents.d.ts.map +1 -1
  18. package/dist/routes/artifact-frames.d.ts +98 -0
  19. package/dist/routes/artifact-frames.d.ts.map +1 -0
  20. package/dist/routes/artifacts.d.ts +852 -0
  21. package/dist/routes/artifacts.d.ts.map +1 -0
  22. package/dist/routes/auth.d.ts +1 -1
  23. package/dist/routes/connector-connection-runs.d.ts +59 -59
  24. package/dist/routes/connector-connections.d.ts +2 -2
  25. package/dist/routes/datasets.d.ts +7 -7
  26. package/dist/routes/events.d.ts +1 -1
  27. package/dist/routes/pipelines.d.ts +31 -31
  28. package/dist/routes/projections.d.ts +10 -10
  29. package/dist/routes/share-grants.d.ts +5 -5
  30. package/dist/routes/syncs.d.ts +38 -38
  31. package/dist/routes/workflows.d.ts +30 -30
  32. package/dist/routes/ws/events.d.ts.map +1 -1
  33. package/dist/routes/ws/subscription-hub.d.ts +8 -3
  34. package/dist/routes/ws/subscription-hub.d.ts.map +1 -1
  35. package/dist/schemas/activity.d.ts +1278 -0
  36. package/dist/schemas/activity.d.ts.map +1 -0
  37. package/dist/schemas/agents.d.ts +96 -144
  38. package/dist/schemas/agents.d.ts.map +1 -1
  39. package/dist/schemas/ai-accounting.d.ts +24 -24
  40. package/dist/schemas/ai-limits.d.ts +26 -26
  41. package/dist/schemas/artifacts.d.ts +1305 -0
  42. package/dist/schemas/artifacts.d.ts.map +1 -0
  43. package/dist/schemas/auth.d.ts +6 -6
  44. package/dist/schemas/connectors.d.ts +30 -30
  45. package/dist/schemas/datasets.d.ts +10 -10
  46. package/dist/schemas/events.d.ts +6 -6
  47. package/dist/schemas/pipelines.d.ts +35 -35
  48. package/dist/schemas/projections.d.ts +40 -40
  49. package/dist/schemas/share-grants.d.ts +16 -16
  50. package/dist/schemas/syncs.d.ts +36 -36
  51. package/dist/schemas/workflows.d.ts +84 -84
  52. package/dist/server.d.ts.map +1 -1
  53. package/package.json +4 -4
  54. package/src/artifacts/frame.ts +46 -0
  55. package/src/auth/browser-origin.ts +12 -2
  56. package/src/auth/public-routes.ts +10 -0
  57. package/src/files/content.ts +9 -13
  58. package/src/openapi/tags.ts +8 -0
  59. package/src/registerRoutes.ts +9 -0
  60. package/src/routes/activity.ts +327 -0
  61. package/src/routes/agents.ts +1 -1
  62. package/src/routes/artifact-frames.ts +138 -0
  63. package/src/routes/artifacts.ts +442 -0
  64. package/src/routes/file-downloads.ts +1 -3
  65. package/src/routes/ws/events.ts +3 -2
  66. package/src/routes/ws/subscription-hub.ts +53 -20
  67. package/src/schemas/activity.ts +285 -0
  68. package/src/schemas/agents.ts +1 -2
  69. package/src/schemas/artifacts.ts +158 -0
  70. package/src/server.ts +25 -9
@@ -0,0 +1,442 @@
1
+ import {
2
+ type ArtifactContentInput,
3
+ type ArtifactRecord,
4
+ ArtifactRequestError,
5
+ type ArtifactVersionRecord,
6
+ isFileRef,
7
+ type PublishedArtifact,
8
+ type SixbHostView,
9
+ } from "@sixb/core"
10
+ import { createArtifactFrame } from "@sixb/core/internal/artifacts/frames"
11
+ import type { Elysia } from "elysia"
12
+ import { ZodError } from "zod"
13
+ import { accessTokenSecurityRequirement } from "../auth/access-token-boundary"
14
+ import { requireRequestSixb } from "../auth/scope"
15
+ import {
16
+ createFileContentResponse,
17
+ fileContentGetResponses,
18
+ fileContentHeadResponses,
19
+ } from "../files/content"
20
+ import { OPENAPI_TAGS } from "../openapi/tags"
21
+ import {
22
+ ArtifactErrorResponseSchema,
23
+ ArtifactFrameResponseSchema,
24
+ ArtifactListQuerySchema,
25
+ ArtifactListResponseSchema,
26
+ ArtifactParamsSchema,
27
+ ArtifactResponseSchema,
28
+ ArtifactVersionParamsSchema,
29
+ ArtifactVersionSchema,
30
+ DeleteArtifactResponseSchema,
31
+ PublishArtifactBodySchema,
32
+ PublishedArtifactResponseSchema,
33
+ } from "../schemas/artifacts"
34
+ import { FileContentQuerySchema } from "../schemas/files"
35
+ import { handleRouteError, parseOptionalInt, toIsoString } from "../utils/http"
36
+
37
+ type RouteSet = { status?: number | string }
38
+
39
+ // The two below build response bodies; each route parses its whole response once.
40
+ function artifactBody(artifact: ArtifactRecord) {
41
+ return {
42
+ id: artifact.id,
43
+ projectId: artifact.projectId,
44
+ kind: artifact.kind,
45
+ title: artifact.title,
46
+ owner: artifact.owner,
47
+ latestVersion: artifact.latestVersion,
48
+ createdAt: toIsoString(artifact.createdAt),
49
+ updatedAt: toIsoString(artifact.updatedAt),
50
+ }
51
+ }
52
+
53
+ function versionBody(version: ArtifactVersionRecord) {
54
+ return {
55
+ artifactId: version.artifactId,
56
+ version: version.version,
57
+ title: version.title,
58
+ entry: version.entry,
59
+ files: version.files,
60
+ outline: version.outline,
61
+ references: version.references,
62
+ author: version.author,
63
+ origin: version.origin,
64
+ createdAt: toIsoString(version.createdAt),
65
+ }
66
+ }
67
+
68
+ function serializePublished(published: PublishedArtifact) {
69
+ return PublishedArtifactResponseSchema.parse({
70
+ artifact: artifactBody(published.artifact),
71
+ version: versionBody(published.version),
72
+ warnings: published.warnings,
73
+ })
74
+ }
75
+
76
+ /** The body's file references narrowed to stored-file references; core checks each one. */
77
+ function contentInput(body: {
78
+ readonly kind: ArtifactContentInput["kind"]
79
+ readonly title: string
80
+ readonly files: readonly { readonly path: string; readonly file: unknown }[]
81
+ }): ArtifactContentInput {
82
+ return {
83
+ kind: body.kind,
84
+ title: body.title,
85
+ files: body.files.map(({ path, file }) => {
86
+ if (!isFileRef(file)) {
87
+ throw new ArtifactRequestError(
88
+ "invalid_artifact",
89
+ `[SixbServer] '${path}' does not have a valid file reference.`
90
+ )
91
+ }
92
+ return { path, file }
93
+ }),
94
+ }
95
+ }
96
+
97
+ function versionParam(value: string): number | "latest" {
98
+ return value === "latest" ? "latest" : Number(value)
99
+ }
100
+
101
+ function notFound(set: RouteSet) {
102
+ set.status = 404
103
+ return { error: "Artifact not found", code: "artifact_not_found" as const }
104
+ }
105
+
106
+ function handleArtifactRouteError(error: unknown, set: RouteSet) {
107
+ if (error instanceof ArtifactRequestError) {
108
+ switch (error.code) {
109
+ case "artifact_not_found":
110
+ set.status = 404
111
+ break
112
+ case "artifact_kind_mismatch":
113
+ set.status = 409
114
+ break
115
+ case "invalid_artifact":
116
+ set.status = 400
117
+ break
118
+ case "not_allowed":
119
+ set.status = 403
120
+ break
121
+ case "storage_unavailable":
122
+ set.status = 501
123
+ break
124
+ }
125
+ return { error: error.message, code: error.code }
126
+ }
127
+ if (error instanceof ZodError) {
128
+ set.status = 400
129
+ return { error: "Invalid artifact request" }
130
+ }
131
+ return handleRouteError(error, set)
132
+ }
133
+
134
+ const publishResponses = {
135
+ 201: PublishedArtifactResponseSchema,
136
+ 400: ArtifactErrorResponseSchema,
137
+ 403: ArtifactErrorResponseSchema,
138
+ 404: ArtifactErrorResponseSchema,
139
+ 409: ArtifactErrorResponseSchema,
140
+ 501: ArtifactErrorResponseSchema,
141
+ }
142
+
143
+ async function artifactFileContentResponse(
144
+ host: SixbHostView,
145
+ context: {
146
+ readonly params: { readonly artifactId: string; readonly version: string }
147
+ readonly query: unknown
148
+ readonly request: Request
149
+ readonly set: RouteSet
150
+ },
151
+ options: { readonly head?: boolean } = {}
152
+ ) {
153
+ try {
154
+ const query = FileContentQuerySchema.parse(context.query)
155
+ const version = await requireRequestSixb(context).artifacts.getVersion(
156
+ context.params.artifactId,
157
+ versionParam(context.params.version)
158
+ )
159
+ const file = version?.files.find((candidate) => candidate.path === query.path)
160
+ const response =
161
+ file &&
162
+ (await createFileContentResponse({
163
+ blobStorage: host.blobStorage,
164
+ fileRef: file.file,
165
+ disposition: query.disposition,
166
+ head: options.head,
167
+ request: context.request,
168
+ }))
169
+ if (!response) {
170
+ context.set.status = 404
171
+ return { error: "File not found" }
172
+ }
173
+ return response
174
+ } catch (error) {
175
+ if (error instanceof ZodError) {
176
+ context.set.status = 400
177
+ return { error: "Invalid file content query" }
178
+ }
179
+ return handleArtifactRouteError(error, context.set)
180
+ }
181
+ }
182
+
183
+ export function registerArtifactRoutes(app: Elysia, host: SixbHostView) {
184
+ return app
185
+ .get(
186
+ "/api/artifacts",
187
+ async (context) => {
188
+ try {
189
+ const query = ArtifactListQuerySchema.parse(context.query)
190
+ const limit = parseOptionalInt(query.limit)
191
+ const offset = parseOptionalInt(query.offset)
192
+ const result = await requireRequestSixb(context).artifacts.list({
193
+ ...(query.thread === undefined ? {} : { threadId: query.thread }),
194
+ ...(query.kind === undefined ? {} : { kind: query.kind }),
195
+ ...(limit === undefined ? {} : { limit }),
196
+ ...(offset === undefined ? {} : { offset }),
197
+ })
198
+ return ArtifactListResponseSchema.parse({
199
+ artifacts: result.artifacts.map(artifactBody),
200
+ hasMore: result.hasMore,
201
+ total: result.total,
202
+ })
203
+ } catch (error) {
204
+ return handleArtifactRouteError(error, context.set)
205
+ }
206
+ },
207
+ {
208
+ query: ArtifactListQuerySchema,
209
+ response: {
210
+ 200: ArtifactListResponseSchema,
211
+ 400: ArtifactErrorResponseSchema,
212
+ 501: ArtifactErrorResponseSchema,
213
+ },
214
+ detail: {
215
+ summary: "List artifacts",
216
+ description: "The caller's artifacts, most recently updated first.",
217
+ tags: [OPENAPI_TAGS.artifacts.name],
218
+ operationId: "listArtifacts",
219
+ security: accessTokenSecurityRequirement("listArtifacts"),
220
+ },
221
+ }
222
+ )
223
+ .post(
224
+ "/api/artifacts",
225
+ async (context) => {
226
+ try {
227
+ const body = PublishArtifactBodySchema.parse(context.body)
228
+ const published = await requireRequestSixb(context).artifacts.create(contentInput(body))
229
+ context.set.status = 201
230
+ return serializePublished(published)
231
+ } catch (error) {
232
+ return handleArtifactRouteError(error, context.set)
233
+ }
234
+ },
235
+ {
236
+ body: PublishArtifactBodySchema,
237
+ response: publishResponses,
238
+ detail: {
239
+ summary: "Create an artifact",
240
+ description:
241
+ "Creates an artifact owned by the caller, with its first version. Store each file with POST /api/files first.",
242
+ tags: [OPENAPI_TAGS.artifacts.name],
243
+ operationId: "createArtifact",
244
+ security: accessTokenSecurityRequirement("createArtifact"),
245
+ },
246
+ }
247
+ )
248
+ .get(
249
+ "/api/artifacts/:artifactId",
250
+ async (context) => {
251
+ try {
252
+ const sixb = requireRequestSixb(context)
253
+ const artifact = await sixb.artifacts.get(context.params.artifactId)
254
+ const versions = artifact && (await sixb.artifacts.listVersions(artifact.id))
255
+ if (!artifact || !versions) return notFound(context.set)
256
+ return ArtifactResponseSchema.parse({
257
+ artifact: artifactBody(artifact),
258
+ versions: versions.versions.map(versionBody),
259
+ })
260
+ } catch (error) {
261
+ return handleArtifactRouteError(error, context.set)
262
+ }
263
+ },
264
+ {
265
+ params: ArtifactParamsSchema,
266
+ response: {
267
+ 200: ArtifactResponseSchema,
268
+ 404: ArtifactErrorResponseSchema,
269
+ 501: ArtifactErrorResponseSchema,
270
+ },
271
+ detail: {
272
+ summary: "Get an artifact and its versions",
273
+ tags: [OPENAPI_TAGS.artifacts.name],
274
+ operationId: "getArtifact",
275
+ security: accessTokenSecurityRequirement("getArtifact"),
276
+ },
277
+ }
278
+ )
279
+ .delete(
280
+ "/api/artifacts/:artifactId",
281
+ async (context) => {
282
+ try {
283
+ const deleted = await requireRequestSixb(context).artifacts.delete(
284
+ context.params.artifactId
285
+ )
286
+ if (!deleted) return notFound(context.set)
287
+ return DeleteArtifactResponseSchema.parse({ deleted: true })
288
+ } catch (error) {
289
+ return handleArtifactRouteError(error, context.set)
290
+ }
291
+ },
292
+ {
293
+ params: ArtifactParamsSchema,
294
+ response: {
295
+ 200: DeleteArtifactResponseSchema,
296
+ 404: ArtifactErrorResponseSchema,
297
+ 501: ArtifactErrorResponseSchema,
298
+ },
299
+ detail: {
300
+ summary: "Delete an artifact",
301
+ description: "Deletes the artifact with every version.",
302
+ tags: [OPENAPI_TAGS.artifacts.name],
303
+ operationId: "deleteArtifact",
304
+ security: accessTokenSecurityRequirement("deleteArtifact"),
305
+ },
306
+ }
307
+ )
308
+ .post(
309
+ "/api/artifacts/:artifactId/versions",
310
+ async (context) => {
311
+ try {
312
+ const body = PublishArtifactBodySchema.parse(context.body)
313
+ const published = await requireRequestSixb(context).artifacts.publish(
314
+ context.params.artifactId,
315
+ contentInput(body)
316
+ )
317
+ context.set.status = 201
318
+ return serializePublished(published)
319
+ } catch (error) {
320
+ return handleArtifactRouteError(error, context.set)
321
+ }
322
+ },
323
+ {
324
+ params: ArtifactParamsSchema,
325
+ body: PublishArtifactBodySchema,
326
+ response: publishResponses,
327
+ detail: {
328
+ summary: "Publish an artifact's next version",
329
+ description: "The kind must be the artifact's. The new version becomes the latest.",
330
+ tags: [OPENAPI_TAGS.artifacts.name],
331
+ operationId: "publishArtifactVersion",
332
+ security: accessTokenSecurityRequirement("publishArtifactVersion"),
333
+ },
334
+ }
335
+ )
336
+ .post(
337
+ "/api/artifacts/:artifactId/versions/:version/frame",
338
+ async (context) => {
339
+ try {
340
+ const storage = host.storage.artifacts
341
+ // Reading the version as the caller is the check: whoever may read it may frame it, with
342
+ // the files it embeds from artifacts the caller may read too.
343
+ const artifacts = requireRequestSixb(context).artifacts
344
+ const version = await artifacts.getVersion(
345
+ context.params.artifactId,
346
+ versionParam(context.params.version)
347
+ )
348
+ if (!version || !storage) return notFound(context.set)
349
+ // Any kind but a deck is refused as `artifact_kind_mismatch`.
350
+ const frame = await createArtifactFrame({
351
+ projectId: host.id,
352
+ storage,
353
+ version,
354
+ read: (id, number) => artifacts.getVersion(id, number),
355
+ })
356
+ return ArtifactFrameResponseSchema.parse({
357
+ path: frame.path,
358
+ expiresAt: frame.expiresAt.toISOString(),
359
+ })
360
+ } catch (error) {
361
+ return handleArtifactRouteError(error, context.set)
362
+ }
363
+ },
364
+ {
365
+ params: ArtifactVersionParamsSchema,
366
+ response: {
367
+ 200: ArtifactFrameResponseSchema,
368
+ 404: ArtifactErrorResponseSchema,
369
+ 409: ArtifactErrorResponseSchema,
370
+ 501: ArtifactErrorResponseSchema,
371
+ },
372
+ detail: {
373
+ summary: "Open a deck's version in a frame",
374
+ description:
375
+ "A short-lived path that serves a slides version's files to a sandboxed frame. It expires within an hour. Any other kind is refused with 409 artifact_kind_mismatch.",
376
+ tags: [OPENAPI_TAGS.artifacts.name],
377
+ operationId: "createArtifactFrame",
378
+ security: accessTokenSecurityRequirement("createArtifactFrame"),
379
+ },
380
+ }
381
+ )
382
+ .get(
383
+ "/api/artifacts/:artifactId/versions/:version",
384
+ async (context) => {
385
+ try {
386
+ const version = await requireRequestSixb(context).artifacts.getVersion(
387
+ context.params.artifactId,
388
+ versionParam(context.params.version)
389
+ )
390
+ if (!version) return notFound(context.set)
391
+ return ArtifactVersionSchema.parse(versionBody(version))
392
+ } catch (error) {
393
+ return handleArtifactRouteError(error, context.set)
394
+ }
395
+ },
396
+ {
397
+ params: ArtifactVersionParamsSchema,
398
+ response: {
399
+ 200: ArtifactVersionSchema,
400
+ 404: ArtifactErrorResponseSchema,
401
+ 501: ArtifactErrorResponseSchema,
402
+ },
403
+ detail: {
404
+ summary: "Get an artifact version",
405
+ description: 'Its files, outline, and references. Use "latest" for the newest version.',
406
+ tags: [OPENAPI_TAGS.artifacts.name],
407
+ operationId: "getArtifactVersion",
408
+ security: accessTokenSecurityRequirement("getArtifactVersion"),
409
+ },
410
+ }
411
+ )
412
+ .get(
413
+ "/api/artifacts/:artifactId/versions/:version/content",
414
+ async (context) => artifactFileContentResponse(host, context),
415
+ {
416
+ params: ArtifactVersionParamsSchema,
417
+ query: FileContentQuerySchema,
418
+ detail: {
419
+ summary: "Get a file of an artifact version",
420
+ tags: [OPENAPI_TAGS.artifacts.name],
421
+ operationId: "getArtifactFileContent",
422
+ security: accessTokenSecurityRequirement("getArtifactFileContent"),
423
+ responses: fileContentGetResponses({ optionalStorage: true }),
424
+ },
425
+ }
426
+ )
427
+ .head(
428
+ "/api/artifacts/:artifactId/versions/:version/content",
429
+ async (context) => artifactFileContentResponse(host, context, { head: true }),
430
+ {
431
+ params: ArtifactVersionParamsSchema,
432
+ query: FileContentQuerySchema,
433
+ detail: {
434
+ summary: "Head a file of an artifact version",
435
+ tags: [OPENAPI_TAGS.artifacts.name],
436
+ operationId: "headArtifactFileContent",
437
+ security: accessTokenSecurityRequirement("headArtifactFileContent"),
438
+ responses: fileContentHeadResponses({ optionalStorage: true }),
439
+ },
440
+ }
441
+ )
442
+ }
@@ -36,9 +36,7 @@ async function fileDownloadResponse(
36
36
  blobStorage: host.blobStorage,
37
37
  fileRef,
38
38
  head: options.head,
39
- rangeHeader: request.headers.get("range"),
40
- ifNoneMatchHeader: request.headers.get("if-none-match"),
41
- ifRangeHeader: request.headers.get("if-range"),
39
+ request,
42
40
  }))
43
41
  if (!response) {
44
42
  set.status = 404
@@ -156,8 +156,9 @@ export function registerEventStreamRoutes(app: Elysia, server: SixbServer) {
156
156
  (!filter.types?.length || filter.types.includes(event.type)) &&
157
157
  eventMatchesScope(event, filter),
158
158
  // The execution facade owns per-event visibility: it withholds events the caller
159
- // cannot view and omits marked properties the caller is not cleared for.
160
- view: (event) => sixb.events.readable(event),
159
+ // cannot view and omits marked properties the caller is not cleared for, as markings
160
+ // are when each batch is sent.
161
+ view: (batch) => sixb.events.visible(batch),
161
162
  replay: replayFrom
162
163
  ? {
163
164
  afterCursor: replayFrom.afterCursor,
@@ -30,10 +30,13 @@ export interface HubSource<T extends HubRecord> {
30
30
  export interface HubSubscription<T extends HubRecord> {
31
31
  matches(record: T): boolean
32
32
  /**
33
- * The matching record as this socket may read it, or `undefined` to withhold it. It keeps the
34
- * record's cursor. Omit to deliver matching records unchanged.
33
+ * The matching records of one outgoing batch as this socket may read them, in order: withheld
34
+ * records are left out, the others keep their cursor. It is applied as the batch is sent, so it
35
+ * reflects what the socket may read then, and may wait for what decides it. A batch it fails on
36
+ * is never sent unviewed: the stream closes there, so the client resumes from the last cursor it
37
+ * received. Omit to deliver matching records unchanged.
35
38
  */
36
- view?(record: T): T | undefined
39
+ view?(records: readonly T[]): readonly T[] | Promise<readonly T[]>
37
40
  /** Replays retained records after `afterCursor` (or from the oldest) before live ones. */
38
41
  readonly replay?: {
39
42
  readonly afterCursor: string | undefined
@@ -56,6 +59,8 @@ interface ClientState<T extends HubRecord> {
56
59
  queuedBytes: number
57
60
  pendingBytes: number
58
61
  flushTimer: ReturnType<typeof setTimeout> | null
62
+ /** A batch is waiting for its view: the next one is sent after it, never before. */
63
+ sending: boolean
59
64
  readonly queueProgressWaiters: Set<() => void>
60
65
  catchingUp: boolean
61
66
  closed: boolean
@@ -108,6 +113,7 @@ export class SubscriptionHub<T extends HubRecord> {
108
113
  queuedBytes: 0,
109
114
  pendingBytes: 0,
110
115
  flushTimer: null,
116
+ sending: false,
111
117
  queueProgressWaiters: new Set(),
112
118
  catchingUp: subscription.replay !== undefined,
113
119
  closed: false,
@@ -179,10 +185,9 @@ export class SubscriptionHub<T extends HubRecord> {
179
185
  private deliverLive(records: readonly T[]): void {
180
186
  for (const state of this.clients.values()) {
181
187
  for (const record of records) {
182
- const visible = visibleRecord(state.subscription, record)
183
- if (!visible) continue
184
- if (state.catchingUp) this.enqueuePendingLive(state, visible)
185
- else this.enqueue(state, visible)
188
+ if (!state.subscription.matches(record)) continue
189
+ if (state.catchingUp) this.enqueuePendingLive(state, record)
190
+ else this.enqueue(state, record)
186
191
  }
187
192
  }
188
193
  }
@@ -203,9 +208,8 @@ export class SubscriptionHub<T extends HubRecord> {
203
208
  if (state.pendingCursors.has(record.cursor)) {
204
209
  state.replayedPendingCursors.add(record.cursor)
205
210
  }
206
- const visible = visibleRecord(state.subscription, record)
207
- if (!visible) continue
208
- if (!(await this.enqueueReplay(state, visible))) return
211
+ if (!state.subscription.matches(record)) continue
212
+ if (!(await this.enqueueReplay(state, record))) return
209
213
  }
210
214
  if (state.closed) return
211
215
  afterCursor = page.cursor ?? afterCursor
@@ -311,7 +315,7 @@ export class SubscriptionHub<T extends HubRecord> {
311
315
  }
312
316
 
313
317
  private flush(state: ClientState<T>): void {
314
- if (state.closed || state.queue.length === 0) return
318
+ if (state.closed || state.sending || state.queue.length === 0) return
315
319
  if (socketBufferedAmount(state.ws) > MAX_SOCKET_BUFFERED_BYTES) {
316
320
  this.scheduleFlush(state)
317
321
  return
@@ -323,8 +327,45 @@ export class SubscriptionHub<T extends HubRecord> {
323
327
  state.queuedBytes -= encodedBytes(record)
324
328
  }
325
329
  this.notifyQueueProgress(state)
330
+
331
+ const view = state.subscription.view
332
+ if (!view) {
333
+ this.sendFrames(state, records)
334
+ if (state.queue.length > 0) this.scheduleFlush(state)
335
+ return
336
+ }
337
+
338
+ state.sending = true
339
+ void this.sendViewed(state, records, view).finally(() => {
340
+ state.sending = false
341
+ if (state.queue.length > 0) this.scheduleFlush(state)
342
+ })
343
+ }
344
+
345
+ private async sendViewed(
346
+ state: ClientState<T>,
347
+ records: readonly T[],
348
+ view: NonNullable<HubSubscription<T>["view"]>
349
+ ): Promise<void> {
350
+ let visible: readonly T[]
351
+ try {
352
+ visible = await view(records)
353
+ } catch (error) {
354
+ // Fail closed, and close: a client resumes after the last cursor it received, so delivering
355
+ // later batches would skip this one for good. Reconnecting reads it again.
356
+ const message = error instanceof Error ? error.message : String(error)
357
+ console.warn(
358
+ `[SixbServer] Closed a stream subscription at cursor '${records[0]?.cursor}': ${records.length} record(s) could not be viewed: ${message}`
359
+ )
360
+ this.fail(state, "Stream records could not be viewed; reconnect from the last cursor.", 1011)
361
+ return
362
+ }
363
+
364
+ if (visible.length > 0) this.sendFrames(state, visible)
365
+ }
366
+
367
+ private sendFrames(state: ClientState<T>, records: readonly T[]): void {
326
368
  for (const frame of this.source.frames(records)) this.send(state, frame)
327
- if (state.queue.length > 0) this.scheduleFlush(state)
328
369
  }
329
370
 
330
371
  private waitForQueueProgress(state: ClientState<T>): Promise<void> {
@@ -367,14 +408,6 @@ export class SubscriptionHub<T extends HubRecord> {
367
408
  }
368
409
  }
369
410
 
370
- function visibleRecord<T extends HubRecord>(
371
- subscription: HubSubscription<T>,
372
- record: T
373
- ): T | undefined {
374
- if (!subscription.matches(record)) return undefined
375
- return subscription.view ? subscription.view(record) : record
376
- }
377
-
378
411
  function hasQueueCapacity(state: ClientState<HubRecord>, bytes: number): boolean {
379
412
  return (
380
413
  state.queue.length + state.pendingLive.length < MAX_CLIENT_RECORDS &&