@sixb/server 0.1.16 → 0.1.18

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 (99) hide show
  1. package/README.md +6 -0
  2. package/dist/auth/experience.d.ts +5 -1
  3. package/dist/auth/experience.d.ts.map +1 -1
  4. package/dist/auth/public-routes.d.ts.map +1 -1
  5. package/dist/auth/shared-access.d.ts.map +1 -1
  6. package/dist/files/content.d.ts +0 -1
  7. package/dist/files/content.d.ts.map +1 -1
  8. package/dist/index.js +603 -456
  9. package/dist/index.js.map +34 -33
  10. package/dist/registerRoutes.d.ts.map +1 -1
  11. package/dist/routes/agents.d.ts +56 -28
  12. package/dist/routes/agents.d.ts.map +1 -1
  13. package/dist/routes/ai-accounting.d.ts.map +1 -1
  14. package/dist/routes/auth.d.ts +4 -3
  15. package/dist/routes/auth.d.ts.map +1 -1
  16. package/dist/routes/datasets.d.ts +4 -1
  17. package/dist/routes/datasets.d.ts.map +1 -1
  18. package/dist/routes/file-downloads.d.ts +98 -0
  19. package/dist/routes/file-downloads.d.ts.map +1 -0
  20. package/dist/routes/files.d.ts.map +1 -1
  21. package/dist/routes/models.d.ts +1 -0
  22. package/dist/routes/models.d.ts.map +1 -1
  23. package/dist/routes/objects.d.ts +24 -4
  24. package/dist/routes/objects.d.ts.map +1 -1
  25. package/dist/routes/ontology.d.ts +4 -4
  26. package/dist/routes/project.d.ts +2 -0
  27. package/dist/routes/project.d.ts.map +1 -1
  28. package/dist/routes/status.d.ts +0 -4
  29. package/dist/routes/status.d.ts.map +1 -1
  30. package/dist/routes/workflows.d.ts +6 -0
  31. package/dist/routes/workflows.d.ts.map +1 -1
  32. package/dist/routes/ws/events.d.ts.map +1 -1
  33. package/dist/routes/ws/logs.d.ts +11 -0
  34. package/dist/routes/ws/logs.d.ts.map +1 -1
  35. package/dist/routes/ws/subscription-hub.d.ts +71 -0
  36. package/dist/routes/ws/subscription-hub.d.ts.map +1 -0
  37. package/dist/schemas/agents.d.ts +255 -123
  38. package/dist/schemas/agents.d.ts.map +1 -1
  39. package/dist/schemas/ai-accounting.d.ts +234 -110
  40. package/dist/schemas/ai-accounting.d.ts.map +1 -1
  41. package/dist/schemas/ai-usage.d.ts +3 -0
  42. package/dist/schemas/ai-usage.d.ts.map +1 -1
  43. package/dist/schemas/auth.d.ts +9 -2
  44. package/dist/schemas/auth.d.ts.map +1 -1
  45. package/dist/schemas/common.d.ts +8 -0
  46. package/dist/schemas/common.d.ts.map +1 -1
  47. package/dist/schemas/datasets.d.ts +18 -3
  48. package/dist/schemas/datasets.d.ts.map +1 -1
  49. package/dist/schemas/event-payloads.d.ts +39 -0
  50. package/dist/schemas/event-payloads.d.ts.map +1 -1
  51. package/dist/schemas/files.d.ts +1 -1
  52. package/dist/schemas/files.d.ts.map +1 -1
  53. package/dist/schemas/models.d.ts +10 -0
  54. package/dist/schemas/models.d.ts.map +1 -1
  55. package/dist/schemas/objects.d.ts +32 -0
  56. package/dist/schemas/objects.d.ts.map +1 -1
  57. package/dist/schemas/ontology.d.ts +18 -18
  58. package/dist/schemas/project.d.ts +8 -0
  59. package/dist/schemas/project.d.ts.map +1 -1
  60. package/dist/schemas/status.d.ts +0 -26
  61. package/dist/schemas/status.d.ts.map +1 -1
  62. package/dist/schemas/workflows.d.ts +52 -0
  63. package/dist/schemas/workflows.d.ts.map +1 -1
  64. package/dist/server.d.ts.map +1 -1
  65. package/package.json +6 -5
  66. package/src/auth/experience.ts +20 -2
  67. package/src/auth/public-routes.ts +10 -0
  68. package/src/auth/shared-access.ts +48 -6
  69. package/src/files/content.ts +43 -88
  70. package/src/registerRoutes.ts +2 -0
  71. package/src/routes/agents.ts +29 -9
  72. package/src/routes/ai-accounting.ts +1 -0
  73. package/src/routes/auth.ts +84 -19
  74. package/src/routes/datasets.ts +12 -43
  75. package/src/routes/file-downloads.ts +48 -0
  76. package/src/routes/files.ts +3 -1
  77. package/src/routes/models.ts +3 -0
  78. package/src/routes/objects.ts +25 -5
  79. package/src/routes/project.ts +2 -1
  80. package/src/routes/workflows.ts +5 -0
  81. package/src/routes/ws/events.ts +98 -133
  82. package/src/routes/ws/logs.ts +67 -5
  83. package/src/routes/ws/subscription-hub.ts +394 -0
  84. package/src/schemas/agents.ts +28 -3
  85. package/src/schemas/ai-accounting.ts +5 -0
  86. package/src/schemas/ai-usage.ts +3 -0
  87. package/src/schemas/auth.ts +5 -0
  88. package/src/schemas/common.ts +3 -0
  89. package/src/schemas/datasets.ts +23 -1
  90. package/src/schemas/event-payloads.ts +3 -1
  91. package/src/schemas/files.ts +7 -1
  92. package/src/schemas/models.ts +2 -0
  93. package/src/schemas/objects.ts +41 -2
  94. package/src/schemas/project.ts +4 -0
  95. package/src/schemas/status.ts +0 -6
  96. package/src/server.ts +7 -1
  97. package/dist/routes/ws/log-subscription-hub.d.ts +0 -50
  98. package/dist/routes/ws/log-subscription-hub.d.ts.map +0 -1
  99. package/src/routes/ws/log-subscription-hub.ts +0 -369
@@ -5,6 +5,7 @@ import {
5
5
  AiUsageLimitErrorResponseSchema,
6
6
  JsonValueSchema,
7
7
  jsonValueOpenApiOverride,
8
+ RedactionsSchema,
8
9
  } from "./common"
9
10
 
10
11
  type OpenApiSchema = NonNullable<
@@ -239,6 +240,13 @@ export const ObjectQuerySchema: z.ZodType<unknown> = z.lazy(() =>
239
240
  k: z.number().int().positive(),
240
241
  })
241
242
  .strict(),
243
+ z
244
+ .object({
245
+ kind: z.literal("rerank"),
246
+ input: ObjectQuerySchema,
247
+ model: z.object({ provider: z.string().min(1), modelId: z.string().min(1) }).strict(),
248
+ })
249
+ .strict(),
242
250
  z
243
251
  .object({
244
252
  kind: z.literal("traverse"),
@@ -343,6 +351,7 @@ export const TwinObjectSchema = z.object({
343
351
  primaryId: z.string(),
344
352
  objectTypeId: z.string(),
345
353
  properties: z.record(z.unknown()),
354
+ redactions: RedactionsSchema.optional(),
346
355
  createdAt: z.string(),
347
356
  updatedAt: z.string(),
348
357
  })
@@ -378,6 +387,16 @@ export const ObjectQueryOpenApiSchemas: OpenApiSchemas = {
378
387
  error: { type: "string" },
379
388
  },
380
389
  },
390
+ // Values omitted because the caller lacks a clearance for their markings.
391
+ Redactions: {
392
+ type: "object",
393
+ additionalProperties: {
394
+ type: "object",
395
+ required: ["reason"],
396
+ additionalProperties: false,
397
+ properties: { reason: { type: "string", enum: ["missing_clearance"] } },
398
+ },
399
+ },
381
400
  ObjectQueryObject: {
382
401
  type: "object",
383
402
  required: ["primaryId", "objectTypeId", "properties", "createdAt", "updatedAt"],
@@ -387,6 +406,7 @@ export const ObjectQueryOpenApiSchemas: OpenApiSchemas = {
387
406
  primaryId: { type: "string" },
388
407
  objectTypeId: { type: "string" },
389
408
  properties: { type: "object", additionalProperties: true },
409
+ redactions: { $ref: "#/components/schemas/Redactions" },
390
410
  createdAt: { type: "string" },
391
411
  updatedAt: { type: "string" },
392
412
  // Populated only on the query route, by an `expand` node: linked objects
@@ -424,7 +444,7 @@ export const ObjectQueryOpenApiSchemas: OpenApiSchemas = {
424
444
  required: ["mode", "providerIssues", "fallbackIssues", "issues"],
425
445
  additionalProperties: false,
426
446
  properties: {
427
- mode: { type: "string", enum: ["pushdown", "fallback", "rejected"] },
447
+ mode: { type: "string", enum: ["pushdown", "fallback", "pipeline", "rejected"] },
428
448
  providerIssues: {
429
449
  type: "array",
430
450
  items: { $ref: "#/components/schemas/ObjectQueryIssue" },
@@ -504,9 +524,10 @@ export const ObjectQueryOpenApiSchemas: OpenApiSchemas = {
504
524
  },
505
525
  ObjectQueryFacetsResponse: {
506
526
  type: "object",
507
- required: ["facets", "plan"],
527
+ required: ["total", "facets", "plan"],
508
528
  additionalProperties: false,
509
529
  properties: {
530
+ total: { type: "number" },
510
531
  facets: {
511
532
  type: "array",
512
533
  items: { $ref: "#/components/schemas/ObjectQueryFacetResult" },
@@ -702,6 +723,24 @@ export const ObjectQueryOpenApiSchemas: OpenApiSchemas = {
702
723
  k: { type: "integer", minimum: 1 },
703
724
  },
704
725
  },
726
+ {
727
+ type: "object",
728
+ required: ["kind", "input", "model"],
729
+ additionalProperties: false,
730
+ properties: {
731
+ kind: { type: "string", enum: ["rerank"] },
732
+ input: objectQueryRef,
733
+ model: {
734
+ type: "object",
735
+ required: ["provider", "modelId"],
736
+ additionalProperties: false,
737
+ properties: {
738
+ provider: { type: "string", minLength: 1 },
739
+ modelId: { type: "string", minLength: 1 },
740
+ },
741
+ },
742
+ },
743
+ },
705
744
  {
706
745
  type: "object",
707
746
  required: ["kind", "input", "linkId", "direction"],
@@ -2,4 +2,8 @@ import { z } from "zod"
2
2
 
3
3
  export const ProjectInfoResponseSchema = z.object({
4
4
  id: z.string(),
5
+ /** Canonical BCP 47 language of the project, `"en"` unless configured. */
6
+ locale: z.string(),
7
+ /** Canonical IANA time zone of the project, `"UTC"` unless configured. */
8
+ timeZone: z.string(),
5
9
  })
@@ -29,12 +29,6 @@ const MaintenanceSummarySchema = z.object({
29
29
  maxAttempts: z.number().int().nonnegative(),
30
30
  })
31
31
  .nullable(),
32
- terminalSources: z
33
- .object({
34
- count: z.number().int().nonnegative(),
35
- oldestTerminalAt: z.string().nullable(),
36
- })
37
- .nullable(),
38
32
  cleanup: z
39
33
  .object({
40
34
  publishedOutboxRowsDeleted: z.number().int().nonnegative(),
package/src/server.ts CHANGED
@@ -3,6 +3,7 @@ import { openapi } from "@elysiajs/openapi"
3
3
  import type { OntologyMaintenanceHandle, SixbHostView } from "@sixb/core"
4
4
  import { CSRF_HEADER_NAME, setRequestClientAddress } from "@sixb/core/internal/auth"
5
5
  import { bindRequestExecution } from "@sixb/core/internal/request-execution"
6
+ import { setApiPublicOrigin } from "@sixb/core/internal/runtime"
6
7
  import type { Server } from "bun"
7
8
  import { Elysia } from "elysia"
8
9
  import { websocket as elysiaWebSocket } from "elysia/ws"
@@ -102,6 +103,10 @@ export class SixbServer {
102
103
  this.hostname = options.hostname ?? "0.0.0.0"
103
104
  this.quiet = options.quiet ?? false
104
105
  this.apiBrowserPolicy = resolveApiBrowserPolicy(options.browser)
106
+ // URLs the API hands to third parties, such as file download URLs, name this origin.
107
+ if (this.apiBrowserPolicy.publicOrigin) {
108
+ setApiPublicOrigin(this.hostRuntime, this.apiBrowserPolicy.publicOrigin)
109
+ }
105
110
  this.authContextResolver = createApiBrowserAuthContextResolver(this.apiBrowserPolicy)
106
111
  this.authRedirectContextResolver = createApiBrowserAuthRedirectContextResolver(
107
112
  this.apiBrowserPolicy
@@ -420,13 +425,14 @@ export function createSixbApi(server: SixbServer) {
420
425
  })
421
426
  )
422
427
 
428
+ const authExperience = server.getAuthExperience()
423
429
  registerAuthRoutes(app, host, {
424
430
  resolveAuthContext: (request) => server.resolveAuthContext(request),
425
431
  resolveAuthRedirectContext: (request, input) =>
426
432
  server.resolveAuthRedirectContext(request, input),
427
433
  getInvitationDestinationOptions: (request) => server.getInvitationDestinationOptions(request),
428
434
  resolveAuthRequestOrigin: (request) => server.resolveAuthRequestOrigin(request),
429
- authExperience: server.getAuthExperience(),
435
+ authExperience: authExperience && { ...authExperience, locale: host.locale },
430
436
  resolveInvitationRedirectContext: (request, input) =>
431
437
  server.resolveInvitationRedirectContext(request, input),
432
438
  })
@@ -1,50 +0,0 @@
1
- import type { LogLevel, LogRunRef, SixbRunKind } from "@sixb/core";
2
- import type { LoggingService } from "@sixb/core/internal/logging";
3
- interface LogSocket {
4
- send(message: string): unknown;
5
- close(code?: number, reason?: string): unknown;
6
- readonly raw?: unknown;
7
- }
8
- export interface LogSubscriptionFilter {
9
- readonly kinds?: readonly SixbRunKind[];
10
- readonly levels?: readonly LogLevel[];
11
- readonly run?: LogRunRef;
12
- readonly afterCursor?: string;
13
- }
14
- /**
15
- * One broker subscription per server/project, multiplexed to all connected
16
- * clients. Each client has a bounded queue so a slow socket cannot retain an
17
- * unbounded portion of the process heap.
18
- */
19
- export declare class LogSubscriptionHub {
20
- private readonly host;
21
- private readonly clients;
22
- private readonly subscriptionGenerations;
23
- private startPromise;
24
- private unsubscribeBroker;
25
- private closed;
26
- constructor(host: {
27
- readonly logging: LoggingService;
28
- });
29
- subscribe(key: object, ws: LogSocket, filter: LogSubscriptionFilter, onSubscribed: () => void): Promise<void>;
30
- unsubscribe(key: object): void;
31
- private removeClient;
32
- private nextSubscriptionGeneration;
33
- private isCurrentSubscription;
34
- close(): Promise<void>;
35
- private ensureStarted;
36
- private deliverLive;
37
- private catchUp;
38
- private enqueue;
39
- private enqueueReplay;
40
- private pushQueuedLine;
41
- private enqueuePendingLive;
42
- private scheduleFlush;
43
- private flush;
44
- private waitForQueueProgress;
45
- private notifyQueueProgress;
46
- private send;
47
- private fail;
48
- }
49
- export {};
50
- //# sourceMappingURL=log-subscription-hub.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"log-subscription-hub.d.ts","sourceRoot":"","sources":["../../../src/routes/ws/log-subscription-hub.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,QAAQ,EAAE,SAAS,EAAE,WAAW,EAAiB,MAAM,YAAY,CAAA;AAEjF,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,6BAA6B,CAAA;AASjE,UAAU,SAAS;IACjB,IAAI,CAAC,OAAO,EAAE,MAAM,GAAG,OAAO,CAAA;IAC9B,KAAK,CAAC,IAAI,CAAC,EAAE,MAAM,EAAE,MAAM,CAAC,EAAE,MAAM,GAAG,OAAO,CAAA;IAC9C,QAAQ,CAAC,GAAG,CAAC,EAAE,OAAO,CAAA;CACvB;AAED,MAAM,WAAW,qBAAqB;IACpC,QAAQ,CAAC,KAAK,CAAC,EAAE,SAAS,WAAW,EAAE,CAAA;IACvC,QAAQ,CAAC,MAAM,CAAC,EAAE,SAAS,QAAQ,EAAE,CAAA;IACrC,QAAQ,CAAC,GAAG,CAAC,EAAE,SAAS,CAAA;IACxB,QAAQ,CAAC,WAAW,CAAC,EAAE,MAAM,CAAA;CAC9B;AAkBD;;;;GAIG;AACH,qBAAa,kBAAkB;IAOjB,OAAO,CAAC,QAAQ,CAAC,IAAI;IANjC,OAAO,CAAC,QAAQ,CAAC,OAAO,CAAiC;IACzD,OAAO,CAAC,QAAQ,CAAC,uBAAuB,CAAgC;IACxE,OAAO,CAAC,YAAY,CAA6B;IACjD,OAAO,CAAC,iBAAiB,CAA4B;IACrD,OAAO,CAAC,MAAM,CAAQ;gBAEO,IAAI,EAAE;QAAE,QAAQ,CAAC,OAAO,EAAE,cAAc,CAAA;KAAE;IAEjE,SAAS,CACb,GAAG,EAAE,MAAM,EACX,EAAE,EAAE,SAAS,EACb,MAAM,EAAE,qBAAqB,EAC7B,YAAY,EAAE,MAAM,IAAI,GACvB,OAAO,CAAC,IAAI,CAAC;IAoChB,WAAW,CAAC,GAAG,EAAE,MAAM,GAAG,IAAI;IAK9B,OAAO,CAAC,YAAY;IASpB,OAAO,CAAC,0BAA0B;IAMlC,OAAO,CAAC,qBAAqB;IAIvB,KAAK,IAAI,OAAO,CAAC,IAAI,CAAC;YAOd,aAAa;IAiB3B,OAAO,CAAC,WAAW;YAUL,OAAO;IAoErB,OAAO,CAAC,OAAO;YAWD,aAAa;IAsB3B,OAAO,CAAC,cAAc;IAOtB,OAAO,CAAC,kBAAkB;IAY1B,OAAO,CAAC,aAAa;IAQrB,OAAO,CAAC,KAAK;IAiBb,OAAO,CAAC,oBAAoB;IAI5B,OAAO,CAAC,mBAAmB;IAM3B,OAAO,CAAC,IAAI;IASZ,OAAO,CAAC,IAAI;CAsBb"}
@@ -1,369 +0,0 @@
1
- import type { LogLevel, LogRunRef, SixbRunKind, StoredLogLine } from "@sixb/core"
2
- import { BrokerCursorExpiredError } from "@sixb/core/broker"
3
- import type { LoggingService } from "@sixb/core/internal/logging"
4
-
5
- const MAX_CLIENT_RECORDS = 1_000
6
- const MAX_CLIENT_BYTES = 1_048_576
7
- const MAX_SOCKET_BUFFERED_BYTES = 1_048_576
8
- const MAX_BATCH_RECORDS = 100
9
- const FLUSH_DELAY_MS = 10
10
- const READ_PAGE_SIZE = 500
11
-
12
- interface LogSocket {
13
- send(message: string): unknown
14
- close(code?: number, reason?: string): unknown
15
- readonly raw?: unknown
16
- }
17
-
18
- export interface LogSubscriptionFilter {
19
- readonly kinds?: readonly SixbRunKind[]
20
- readonly levels?: readonly LogLevel[]
21
- readonly run?: LogRunRef
22
- readonly afterCursor?: string
23
- }
24
-
25
- interface ClientState {
26
- readonly ws: LogSocket
27
- readonly filter: LogSubscriptionFilter
28
- readonly queue: StoredLogLine[]
29
- readonly queuedCursors: Set<string>
30
- readonly pendingLive: StoredLogLine[]
31
- readonly pendingCursors: Set<string>
32
- readonly replayedPendingCursors: Set<string>
33
- queuedBytes: number
34
- pendingBytes: number
35
- flushTimer: ReturnType<typeof setTimeout> | null
36
- readonly queueProgressWaiters: Set<() => void>
37
- catchingUp: boolean
38
- closed: boolean
39
- }
40
-
41
- /**
42
- * One broker subscription per server/project, multiplexed to all connected
43
- * clients. Each client has a bounded queue so a slow socket cannot retain an
44
- * unbounded portion of the process heap.
45
- */
46
- export class LogSubscriptionHub {
47
- private readonly clients = new Map<object, ClientState>()
48
- private readonly subscriptionGenerations = new WeakMap<object, number>()
49
- private startPromise: Promise<void> | null = null
50
- private unsubscribeBroker: (() => void) | null = null
51
- private closed = false
52
-
53
- constructor(private readonly host: { readonly logging: LoggingService }) {}
54
-
55
- async subscribe(
56
- key: object,
57
- ws: LogSocket,
58
- filter: LogSubscriptionFilter,
59
- onSubscribed: () => void
60
- ): Promise<void> {
61
- if (this.closed) throw new Error("Log subscription hub is closed")
62
- const generation = this.nextSubscriptionGeneration(key)
63
- this.removeClient(key)
64
-
65
- try {
66
- await this.ensureStarted()
67
- } catch (error) {
68
- if (this.closed || !this.isCurrentSubscription(key, generation)) return
69
- throw error
70
- }
71
- if (this.closed || !this.isCurrentSubscription(key, generation)) return
72
-
73
- const state: ClientState = {
74
- ws,
75
- filter,
76
- queue: [],
77
- queuedCursors: new Set(),
78
- pendingLive: [],
79
- pendingCursors: new Set(),
80
- replayedPendingCursors: new Set(),
81
- queuedBytes: 0,
82
- pendingBytes: 0,
83
- flushTimer: null,
84
- queueProgressWaiters: new Set(),
85
- catchingUp: filter.afterCursor !== undefined,
86
- closed: false,
87
- }
88
- this.clients.set(key, state)
89
- onSubscribed()
90
-
91
- if (state.catchingUp) {
92
- void this.catchUp(key, state)
93
- }
94
- }
95
-
96
- unsubscribe(key: object): void {
97
- this.nextSubscriptionGeneration(key)
98
- this.removeClient(key)
99
- }
100
-
101
- private removeClient(key: object): void {
102
- const state = this.clients.get(key)
103
- if (!state) return
104
- state.closed = true
105
- if (state.flushTimer) clearTimeout(state.flushTimer)
106
- this.notifyQueueProgress(state)
107
- this.clients.delete(key)
108
- }
109
-
110
- private nextSubscriptionGeneration(key: object): number {
111
- const generation = (this.subscriptionGenerations.get(key) ?? 0) + 1
112
- this.subscriptionGenerations.set(key, generation)
113
- return generation
114
- }
115
-
116
- private isCurrentSubscription(key: object, generation: number): boolean {
117
- return this.subscriptionGenerations.get(key) === generation
118
- }
119
-
120
- async close(): Promise<void> {
121
- this.closed = true
122
- this.unsubscribeBroker?.()
123
- this.unsubscribeBroker = null
124
- for (const key of this.clients.keys()) this.unsubscribe(key)
125
- }
126
-
127
- private async ensureStarted(): Promise<void> {
128
- if (this.closed) throw new Error("Log subscription hub is closed")
129
- if (!this.startPromise) {
130
- this.startPromise = this.host.logging
131
- .subscribe({ from: "latest" }, (lines) => this.deliverLive(lines))
132
- .then((unsubscribe) => {
133
- if (this.closed) unsubscribe()
134
- else this.unsubscribeBroker = unsubscribe
135
- })
136
- .catch((error) => {
137
- this.startPromise = null
138
- throw error
139
- })
140
- }
141
- await this.startPromise
142
- }
143
-
144
- private deliverLive(lines: readonly StoredLogLine[]): void {
145
- for (const state of this.clients.values()) {
146
- for (const line of lines) {
147
- if (!matches(line, state.filter)) continue
148
- if (state.catchingUp) this.enqueuePendingLive(state, line)
149
- else this.enqueue(state, line)
150
- }
151
- }
152
- }
153
-
154
- private async catchUp(key: object, state: ClientState): Promise<void> {
155
- let afterCursor = state.filter.afterCursor
156
- try {
157
- let hasMore = true
158
- while (hasMore) {
159
- const page = await this.host.logging.read({
160
- afterCursor,
161
- limit: READ_PAGE_SIZE,
162
- kinds: state.filter.kinds,
163
- levels: state.filter.levels,
164
- run: state.filter.run,
165
- })
166
- if (state.closed || this.clients.get(key) !== state) return
167
-
168
- for (const line of page.lines) {
169
- if (state.pendingCursors.has(line.cursor)) {
170
- state.replayedPendingCursors.add(line.cursor)
171
- }
172
- if (!(await this.enqueueReplay(state, line))) return
173
- }
174
- if (state.closed) return
175
- afterCursor = page.cursor ?? afterCursor
176
- hasMore = page.hasMore
177
- if (hasMore && !page.cursor) {
178
- throw new Error("Log broker returned hasMore without a cursor")
179
- }
180
- }
181
-
182
- state.catchingUp = false
183
- const pendingLive = [...state.pendingLive]
184
- const replayedPendingCursors = new Set(state.replayedPendingCursors)
185
- state.pendingLive.length = 0
186
- state.pendingCursors.clear()
187
- state.replayedPendingCursors.clear()
188
- state.pendingBytes = 0
189
- for (const line of pendingLive) {
190
- if (!replayedPendingCursors.has(line.cursor)) this.enqueue(state, line)
191
- }
192
- } catch (error) {
193
- if (state.closed || this.clients.get(key) !== state) return
194
- state.catchingUp = false
195
- state.pendingLive.length = 0
196
- state.pendingCursors.clear()
197
- state.replayedPendingCursors.clear()
198
- state.pendingBytes = 0
199
-
200
- if (error instanceof BrokerCursorExpiredError) {
201
- try {
202
- const latest = await this.host.logging.tail({ limit: 1 })
203
- this.send(state, {
204
- type: "reset",
205
- reason: "cursor_expired",
206
- cursor: latest.lines.at(-1)?.cursor ?? latest.cursor,
207
- })
208
- } catch (resetError) {
209
- this.fail(
210
- state,
211
- resetError instanceof Error ? resetError.message : String(resetError),
212
- 1011
213
- )
214
- }
215
- return
216
- }
217
-
218
- this.fail(state, error instanceof Error ? error.message : String(error), 1011)
219
- }
220
- }
221
-
222
- private enqueue(state: ClientState, line: StoredLogLine): void {
223
- if (state.closed || state.queuedCursors.has(line.cursor)) return
224
- const bytes = encodedBytes(line)
225
- if (!hasQueueCapacity(state, bytes)) {
226
- this.fail(state, "Log stream client is too slow; reconnect from the last cursor.", 1013)
227
- return
228
- }
229
-
230
- this.pushQueuedLine(state, line, bytes)
231
- }
232
-
233
- private async enqueueReplay(state: ClientState, line: StoredLogLine): Promise<boolean> {
234
- if (state.closed) return false
235
- if (state.queuedCursors.has(line.cursor)) return true
236
- const bytes = encodedBytes(line)
237
-
238
- while (!hasQueueCapacity(state, bytes)) {
239
- // Replay is an internal producer and can pause while already-queued replay
240
- // batches drain. Pending live records cannot drain until replay finishes,
241
- // so a queue containing only pending live records has no forward progress.
242
- if (state.queue.length === 0 || socketBufferedAmount(state.ws) > MAX_SOCKET_BUFFERED_BYTES) {
243
- this.fail(state, "Log stream client is too slow; reconnect from the last cursor.", 1013)
244
- return false
245
- }
246
- this.scheduleFlush(state)
247
- await this.waitForQueueProgress(state)
248
- if (state.closed) return false
249
- }
250
-
251
- this.pushQueuedLine(state, line, bytes)
252
- return !state.closed
253
- }
254
-
255
- private pushQueuedLine(state: ClientState, line: StoredLogLine, bytes: number): void {
256
- state.queue.push(line)
257
- state.queuedCursors.add(line.cursor)
258
- state.queuedBytes += bytes
259
- this.scheduleFlush(state)
260
- }
261
-
262
- private enqueuePendingLive(state: ClientState, line: StoredLogLine): void {
263
- if (state.closed || state.pendingCursors.has(line.cursor)) return
264
- const bytes = encodedBytes(line)
265
- if (!hasQueueCapacity(state, bytes)) {
266
- this.fail(state, "Log stream client is too slow; reconnect from the last cursor.", 1013)
267
- return
268
- }
269
- state.pendingLive.push(line)
270
- state.pendingCursors.add(line.cursor)
271
- state.pendingBytes += bytes
272
- }
273
-
274
- private scheduleFlush(state: ClientState): void {
275
- if (state.closed || state.flushTimer) return
276
- state.flushTimer = setTimeout(() => {
277
- state.flushTimer = null
278
- this.flush(state)
279
- }, FLUSH_DELAY_MS)
280
- }
281
-
282
- private flush(state: ClientState): void {
283
- if (state.closed || state.queue.length === 0) return
284
- if (socketBufferedAmount(state.ws) > MAX_SOCKET_BUFFERED_BYTES) {
285
- this.scheduleFlush(state)
286
- return
287
- }
288
-
289
- const lines = state.queue.splice(0, MAX_BATCH_RECORDS)
290
- for (const line of lines) {
291
- state.queuedCursors.delete(line.cursor)
292
- state.queuedBytes -= encodedBytes(line)
293
- }
294
- this.notifyQueueProgress(state)
295
- this.send(state, { type: "logs", logs: lines })
296
- if (state.queue.length > 0) this.scheduleFlush(state)
297
- }
298
-
299
- private waitForQueueProgress(state: ClientState): Promise<void> {
300
- return new Promise((resolve) => state.queueProgressWaiters.add(resolve))
301
- }
302
-
303
- private notifyQueueProgress(state: ClientState): void {
304
- const waiters = [...state.queueProgressWaiters]
305
- state.queueProgressWaiters.clear()
306
- for (const resolve of waiters) resolve()
307
- }
308
-
309
- private send(state: ClientState, payload: unknown): void {
310
- if (state.closed) return
311
- try {
312
- state.ws.send(JSON.stringify(payload))
313
- } catch (error) {
314
- this.fail(state, error instanceof Error ? error.message : String(error), 1011)
315
- }
316
- }
317
-
318
- private fail(state: ClientState, message: string, closeCode: number): void {
319
- if (state.closed) return
320
- try {
321
- state.ws.send(JSON.stringify({ type: "error", message }))
322
- } catch {
323
- // The close below is still required when the error frame cannot be sent.
324
- }
325
- state.closed = true
326
- if (state.flushTimer) clearTimeout(state.flushTimer)
327
- this.notifyQueueProgress(state)
328
- for (const [key, candidate] of this.clients) {
329
- if (candidate === state) this.clients.delete(key)
330
- }
331
- try {
332
- state.ws.close(
333
- closeCode,
334
- closeCode === 1013 ? "Log stream backpressure" : "Log stream failure"
335
- )
336
- } catch {
337
- // Socket is already gone.
338
- }
339
- }
340
- }
341
-
342
- function hasQueueCapacity(state: ClientState, bytes: number): boolean {
343
- return (
344
- state.queue.length + state.pendingLive.length < MAX_CLIENT_RECORDS &&
345
- state.queuedBytes + state.pendingBytes + bytes <= MAX_CLIENT_BYTES
346
- )
347
- }
348
-
349
- function matches(line: StoredLogLine, filter: LogSubscriptionFilter): boolean {
350
- if (filter.run) {
351
- if (line.context.run.kind !== filter.run.kind || line.context.run.id !== filter.run.id) {
352
- return false
353
- }
354
- }
355
- if (filter.kinds && !filter.kinds.includes(line.context.run.kind)) return false
356
- if (filter.levels && !filter.levels.includes(line.level)) return false
357
- return true
358
- }
359
-
360
- function encodedBytes(value: unknown): number {
361
- return new TextEncoder().encode(JSON.stringify(value)).byteLength
362
- }
363
-
364
- function socketBufferedAmount(ws: LogSocket): number {
365
- const raw = ws.raw
366
- if (!raw || typeof raw !== "object" || !("bufferedAmount" in raw)) return 0
367
- const bufferedAmount = (raw as { bufferedAmount?: unknown }).bufferedAmount
368
- return typeof bufferedAmount === "number" ? bufferedAmount : 0
369
- }