@sixb/server 0.2.5 → 0.2.6
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/index.d.ts +1 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +525 -61
- package/dist/index.js.map +19 -18
- package/dist/registerRoutes.d.ts +1 -0
- package/dist/registerRoutes.d.ts.map +1 -1
- package/dist/routes/agent-approvals.d.ts +22 -0
- package/dist/routes/agent-approvals.d.ts.map +1 -1
- package/dist/routes/agent-computers.d.ts +36 -0
- package/dist/routes/agent-computers.d.ts.map +1 -1
- package/dist/routes/agent-thread-reads.d.ts +82 -0
- package/dist/routes/agent-thread-reads.d.ts.map +1 -0
- package/dist/routes/agents.d.ts +783 -1
- package/dist/routes/agents.d.ts.map +1 -1
- package/dist/routes/ai-accounting.d.ts.map +1 -1
- package/dist/routes/model-generations.d.ts +6 -0
- package/dist/routes/model-generations.d.ts.map +1 -1
- package/dist/routes/observed-agent-threads.d.ts +22 -0
- package/dist/routes/observed-agent-threads.d.ts.map +1 -1
- package/dist/routes/status.d.ts +4 -1
- package/dist/routes/status.d.ts.map +1 -1
- package/dist/routes/syncs.d.ts +175 -12
- package/dist/routes/syncs.d.ts.map +1 -1
- package/dist/routes/workflows.d.ts +6 -6
- package/dist/routes/ws/agents.d.ts.map +1 -1
- package/dist/schemas/activity.d.ts +4 -4
- package/dist/schemas/agents.d.ts +2602 -6
- package/dist/schemas/agents.d.ts.map +1 -1
- package/dist/schemas/ai-accounting.d.ts +3 -0
- package/dist/schemas/ai-accounting.d.ts.map +1 -1
- package/dist/schemas/common.d.ts.map +1 -1
- package/dist/schemas/models.d.ts +46 -0
- package/dist/schemas/models.d.ts.map +1 -1
- package/dist/schemas/syncs.d.ts +724 -25
- package/dist/schemas/syncs.d.ts.map +1 -1
- package/dist/schemas/workflows.d.ts +22 -22
- package/dist/server.d.ts +16 -1
- package/dist/server.d.ts.map +1 -1
- package/package.json +5 -5
- package/src/index.ts +6 -1
- package/src/registerRoutes.ts +4 -1
- package/src/routes/agent-computers.ts +7 -6
- package/src/routes/agent-thread-reads.ts +67 -0
- package/src/routes/agents.ts +129 -16
- package/src/routes/ai-accounting.ts +1 -0
- package/src/routes/model-generations.ts +1 -1
- package/src/routes/observed-agent-threads.ts +3 -4
- package/src/routes/status.ts +18 -1
- package/src/routes/syncs.ts +135 -8
- package/src/routes/ws/agents.ts +43 -3
- package/src/schemas/agents.ts +80 -10
- package/src/schemas/ai-accounting.ts +12 -0
- package/src/schemas/common.ts +15 -9
- package/src/schemas/models.ts +10 -0
- package/src/schemas/syncs.ts +63 -1
- package/src/server.ts +205 -13
package/src/schemas/agents.ts
CHANGED
|
@@ -167,6 +167,46 @@ export const AgentThreadParticipantSchema = z.object({
|
|
|
167
167
|
addedBy: AgentPrincipalSchema,
|
|
168
168
|
})
|
|
169
169
|
|
|
170
|
+
export const AgentRunStatusSchema = z.enum([
|
|
171
|
+
"queued",
|
|
172
|
+
"running",
|
|
173
|
+
"succeeded",
|
|
174
|
+
"failed",
|
|
175
|
+
"cancelled",
|
|
176
|
+
])
|
|
177
|
+
|
|
178
|
+
export const AgentRunFinishReasonSchema = z.enum(AGENT_RUN_FINISH_REASONS)
|
|
179
|
+
|
|
180
|
+
/** Your place in a conversation: how far your reading reached, and what is new. */
|
|
181
|
+
export const AgentThreadReadSchema = z.object({
|
|
182
|
+
threadId: z.string(),
|
|
183
|
+
/** The seq of the last message your reading reached; 0 when it reached none. */
|
|
184
|
+
throughSeq: z.number(),
|
|
185
|
+
/** The thread's newest message seq. */
|
|
186
|
+
headSeq: z.number(),
|
|
187
|
+
/** Messages past your place that someone else wrote: not yours, nor approval outcomes alone. */
|
|
188
|
+
unread: z.number(),
|
|
189
|
+
/** When you last marked it read. */
|
|
190
|
+
readAt: z.string().optional(),
|
|
191
|
+
})
|
|
192
|
+
|
|
193
|
+
/** The newest run of a thread, enough to offer Continue or Retry without reading it. */
|
|
194
|
+
export const AgentThreadLastRunSchema = z.object({
|
|
195
|
+
id: z.string(),
|
|
196
|
+
status: AgentRunStatusSchema,
|
|
197
|
+
finishReason: AgentRunFinishReasonSchema.optional(),
|
|
198
|
+
errorCode: z.enum(AGENT_RUN_FAILURE_CODES).optional(),
|
|
199
|
+
completedAt: z.string().optional(),
|
|
200
|
+
/** Who asked for it, when it ended short: only they can run it again. */
|
|
201
|
+
requestedBy: AgentAuthorizablePrincipalSchema.optional(),
|
|
202
|
+
})
|
|
203
|
+
|
|
204
|
+
export const MarkAgentThreadReadBodySchema = z
|
|
205
|
+
.object({ throughMessageId: z.string().trim().min(1).optional() })
|
|
206
|
+
.strict()
|
|
207
|
+
|
|
208
|
+
export const MarkAgentThreadReadResponseSchema = z.object({ read: AgentThreadReadSchema })
|
|
209
|
+
|
|
170
210
|
export const AgentThreadSchema = z.object({
|
|
171
211
|
sandboxState: z
|
|
172
212
|
.object({
|
|
@@ -224,6 +264,10 @@ export const AgentThreadSchema = z.object({
|
|
|
224
264
|
messageCount: z.number(),
|
|
225
265
|
createdAt: z.string(),
|
|
226
266
|
updatedAt: z.string(),
|
|
267
|
+
/** Your place in it: absent for an observer, and for code that is not a person. */
|
|
268
|
+
read: AgentThreadReadSchema.optional(),
|
|
269
|
+
/** Its newest run, so a client can offer Continue or Retry without reading it. */
|
|
270
|
+
lastRun: AgentThreadLastRunSchema.optional(),
|
|
227
271
|
/** Your mode in this thread, when the thread is read alone. */
|
|
228
272
|
approvalMode: AgentApprovalModeSchema.optional(),
|
|
229
273
|
/**
|
|
@@ -243,6 +287,7 @@ export const CreateAgentThreadResponseSchema = z.object({
|
|
|
243
287
|
thread: AgentThreadSchema,
|
|
244
288
|
})
|
|
245
289
|
|
|
290
|
+
/** The computer and folder a thread moves to, whether it runs in the cloud or elsewhere. */
|
|
246
291
|
export const MoveAgentThreadToComputerBodySchema = z
|
|
247
292
|
.object({ computer: AgentThreadComputerInputSchema })
|
|
248
293
|
.strict()
|
|
@@ -488,6 +533,24 @@ export const AgentMessageListResponseSchema = z.object({
|
|
|
488
533
|
total: z.number(),
|
|
489
534
|
})
|
|
490
535
|
|
|
536
|
+
export const EditAgentMessageBodySchema = z
|
|
537
|
+
.object({
|
|
538
|
+
/** Required unless `attachments` are the whole message. */
|
|
539
|
+
text: z.string().trim().min(1).optional(),
|
|
540
|
+
model: LanguageModelRefSchema.optional(),
|
|
541
|
+
reasoning: ModelReasoningSchema.optional(),
|
|
542
|
+
/** IANA time zone of the person asking. The Agent presents dates and times in it. */
|
|
543
|
+
timeZone: z.string().trim().min(1).max(100).optional(),
|
|
544
|
+
/** BCP 47 language of the person asking. */
|
|
545
|
+
locale: z.string().trim().min(1).max(100).optional(),
|
|
546
|
+
/** What this turn may change without asking you. Omitted: your choice in the thread. */
|
|
547
|
+
approvalMode: AgentApprovalModeSchema.optional(),
|
|
548
|
+
attachments: z.array(FileRefSchema).optional(),
|
|
549
|
+
context: z.array(AgentContextEntryInputSchema).max(MAX_AGENT_CONTEXT_ENTRIES).optional(),
|
|
550
|
+
nextMessageId: z.string().trim().min(1).optional(),
|
|
551
|
+
})
|
|
552
|
+
.strict()
|
|
553
|
+
|
|
491
554
|
export const PostAgentMessageBodySchema = z
|
|
492
555
|
.object({
|
|
493
556
|
/** Required unless `continue` is set or `attachments` are the whole message. */
|
|
@@ -522,16 +585,6 @@ export const CancelAgentRunBodySchema = z.object({
|
|
|
522
585
|
runId: z.string().trim().min(1),
|
|
523
586
|
})
|
|
524
587
|
|
|
525
|
-
export const AgentRunStatusSchema = z.enum([
|
|
526
|
-
"queued",
|
|
527
|
-
"running",
|
|
528
|
-
"succeeded",
|
|
529
|
-
"failed",
|
|
530
|
-
"cancelled",
|
|
531
|
-
])
|
|
532
|
-
|
|
533
|
-
export const AgentRunFinishReasonSchema = z.enum(AGENT_RUN_FINISH_REASONS)
|
|
534
|
-
|
|
535
588
|
export const AgentRunSchema = z.object({
|
|
536
589
|
id: z.string(),
|
|
537
590
|
projectId: z.string(),
|
|
@@ -551,6 +604,12 @@ export const AgentRunSchema = z.object({
|
|
|
551
604
|
approvalMode: AgentApprovalModeSchema.optional(),
|
|
552
605
|
/** Its owner's computer claims it; absent, the cloud runs it. */
|
|
553
606
|
runsOn: z.literal("computer").optional(),
|
|
607
|
+
/**
|
|
608
|
+
* The computer and folder it runs in, in the list of a thread's runs its owner reads: shown to
|
|
609
|
+
* them alone, as the thread's `computer` is. A turn in another place than the one before it no
|
|
610
|
+
* longer has the files that turn worked on.
|
|
611
|
+
*/
|
|
612
|
+
computer: z.object({ id: z.string(), folder: z.string() }).optional(),
|
|
554
613
|
modelId: z.string().optional(),
|
|
555
614
|
/**
|
|
556
615
|
* `awaiting_approval`: the turn succeeded and paused on calls waiting for its requester. It stays
|
|
@@ -592,6 +651,8 @@ export const AgentInboxItemSchema = z.object({
|
|
|
592
651
|
locale: z.string().optional(),
|
|
593
652
|
/** Sent now: it starts even when the turn it waited for ended without answering. */
|
|
594
653
|
immediate: z.boolean().optional(),
|
|
654
|
+
/** An edit waiting for the turn it stopped: the message it replaces once that turn ends. */
|
|
655
|
+
replacesMessageId: z.string().optional(),
|
|
595
656
|
createdAt: z.string(),
|
|
596
657
|
updatedAt: z.string(),
|
|
597
658
|
})
|
|
@@ -631,6 +692,15 @@ export const PostAgentMessageResponseSchema = z.object({
|
|
|
631
692
|
item: AgentInboxItemSchema.optional(),
|
|
632
693
|
})
|
|
633
694
|
|
|
695
|
+
/**
|
|
696
|
+
* `run` when the edit starts its turn now; `item` when it waits, sent now, for the running turn it
|
|
697
|
+
* stopped to end.
|
|
698
|
+
*/
|
|
699
|
+
export const EditAgentMessageResponseSchema = z.object({
|
|
700
|
+
run: AgentRunSchema.optional(),
|
|
701
|
+
item: AgentInboxItemSchema.optional(),
|
|
702
|
+
})
|
|
703
|
+
|
|
634
704
|
export const CancelAgentRunResponseSchema = z.object({
|
|
635
705
|
run: AgentRunSchema,
|
|
636
706
|
})
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { canonicalTimeZone } from "@sixb/core/calendar"
|
|
1
2
|
import { z } from "zod"
|
|
2
3
|
import { AiUsageSummarySchema } from "./ai-usage"
|
|
3
4
|
import { ModelReasoningSchema } from "./models"
|
|
@@ -48,8 +49,19 @@ export const AiAccountingRangeQuerySchema = z.object({
|
|
|
48
49
|
kind: ModelKindSchema.optional().describe("Calls to one kind of model"),
|
|
49
50
|
})
|
|
50
51
|
|
|
52
|
+
const TimeZoneSchema = z
|
|
53
|
+
.string()
|
|
54
|
+
.trim()
|
|
55
|
+
.min(1)
|
|
56
|
+
.refine((value) => canonicalTimeZone(value) !== undefined, {
|
|
57
|
+
message: "Use an IANA time zone such as America/New_York",
|
|
58
|
+
})
|
|
59
|
+
|
|
51
60
|
export const AiAccountingOverviewQuerySchema = AiAccountingRangeQuerySchema.extend({
|
|
52
61
|
bucket: AiAccountingBucketSchema,
|
|
62
|
+
timeZone: TimeZoneSchema.optional().describe(
|
|
63
|
+
"The IANA time zone whose days, weeks or hours the periods follow, such as America/New_York; UTC when absent"
|
|
64
|
+
),
|
|
53
65
|
})
|
|
54
66
|
|
|
55
67
|
export const AiModelCallAccountingListQuerySchema = AiAccountingRangeQuerySchema.extend({
|
package/src/schemas/common.ts
CHANGED
|
@@ -32,15 +32,21 @@ export type JsonValue =
|
|
|
32
32
|
| JsonValue[]
|
|
33
33
|
| { [key: string]: JsonValue }
|
|
34
34
|
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
z.
|
|
43
|
-
|
|
35
|
+
// Zod calls a lazy schema's getter at every value it checks: built there, the union and its array
|
|
36
|
+
// and record would be built again at each node of every JSON value, which cost a thread's messages
|
|
37
|
+
// seconds of CPU. Built once, each check only walks the value.
|
|
38
|
+
let jsonValueUnion: z.ZodType<JsonValue> | undefined
|
|
39
|
+
|
|
40
|
+
export const JsonValueSchema: z.ZodType<JsonValue> = z.lazy(
|
|
41
|
+
() =>
|
|
42
|
+
(jsonValueUnion ??= z.union([
|
|
43
|
+
z.string(),
|
|
44
|
+
z.number().finite(),
|
|
45
|
+
z.boolean(),
|
|
46
|
+
z.null(),
|
|
47
|
+
z.array(JsonValueSchema),
|
|
48
|
+
z.record(JsonValueSchema),
|
|
49
|
+
]))
|
|
44
50
|
)
|
|
45
51
|
|
|
46
52
|
/** A JSON null with an explicit runtime and generated-client type. */
|
package/src/schemas/models.ts
CHANGED
|
@@ -253,6 +253,16 @@ export const TranscriptionBodySchema = GenerationBodyBase.extend({
|
|
|
253
253
|
audio: z.union([FileRefSchema, InlineAudioSchema]),
|
|
254
254
|
})
|
|
255
255
|
|
|
256
|
+
/** One word the model timed, with who said it where the model labels voices. */
|
|
257
|
+
export const TranscriptionWordSchema = z.object({
|
|
258
|
+
text: z.string(),
|
|
259
|
+
startMs: z.number().int().nonnegative(),
|
|
260
|
+
endMs: z.number().int().nonnegative(),
|
|
261
|
+
speaker: z.string().optional(),
|
|
262
|
+
})
|
|
263
|
+
|
|
256
264
|
export const TranscriptionSchema = GenerationResultBase.extend({
|
|
257
265
|
text: z.string(),
|
|
266
|
+
/** Absent when the model returns no word timings. */
|
|
267
|
+
words: z.array(TranscriptionWordSchema).optional(),
|
|
258
268
|
})
|
package/src/schemas/syncs.ts
CHANGED
|
@@ -19,6 +19,7 @@ const SyncModeSchema = z.enum(["snapshot", "append", "merge"])
|
|
|
19
19
|
|
|
20
20
|
export const SyncRunsQuerySchema = z.object({
|
|
21
21
|
syncId: z.string().optional(),
|
|
22
|
+
connectionId: z.string().optional(),
|
|
22
23
|
datasetId: z.string().optional(),
|
|
23
24
|
status: SyncRunStatusSchema.optional(),
|
|
24
25
|
startedAfter: z.string().optional(),
|
|
@@ -29,6 +30,8 @@ export const SyncRunsQuerySchema = z.object({
|
|
|
29
30
|
})
|
|
30
31
|
|
|
31
32
|
export const RequestSyncRunBodySchema = z.object({
|
|
33
|
+
/** One connection to run, on a sync of an OAuth connector. Without it, every one you can run. */
|
|
34
|
+
connectionId: z.string().optional(),
|
|
32
35
|
expectedLatestVersionId: z.string().optional(),
|
|
33
36
|
commitMessage: z.string().optional(),
|
|
34
37
|
})
|
|
@@ -42,6 +45,8 @@ export const SyncRunSchema = z.object({
|
|
|
42
45
|
id: z.string(),
|
|
43
46
|
projectId: z.string(),
|
|
44
47
|
syncId: z.string(),
|
|
48
|
+
/** The connection the run reads, on a sync of an OAuth connector. */
|
|
49
|
+
connectionId: z.string().optional(),
|
|
45
50
|
datasetId: z.string(),
|
|
46
51
|
mode: SyncModeSchema,
|
|
47
52
|
status: SyncRunStatusSchema,
|
|
@@ -62,6 +67,45 @@ export const SyncRunSchema = z.object({
|
|
|
62
67
|
error: SyncRunFailureSchema.optional(),
|
|
63
68
|
})
|
|
64
69
|
|
|
70
|
+
const SyncAccountConnectionSchema = z.object({
|
|
71
|
+
id: z.string(),
|
|
72
|
+
owner: z.discriminatedUnion("type", [
|
|
73
|
+
z.object({ type: z.literal("project") }),
|
|
74
|
+
z.object({ type: z.literal("user"), id: z.string() }),
|
|
75
|
+
]),
|
|
76
|
+
slot: z.string(),
|
|
77
|
+
account: z.object({ id: z.string(), label: z.string() }),
|
|
78
|
+
})
|
|
79
|
+
|
|
80
|
+
/** One connected account of an OAuth connector, and the latest run of each of its syncs. */
|
|
81
|
+
export const ConnectorAccountSchema = z.object({
|
|
82
|
+
connection: SyncAccountConnectionSchema,
|
|
83
|
+
latestRuns: z.array(SyncRunSchema),
|
|
84
|
+
})
|
|
85
|
+
|
|
86
|
+
export const ConnectorAccountListResponseSchema = z.object({
|
|
87
|
+
accounts: z.array(ConnectorAccountSchema),
|
|
88
|
+
})
|
|
89
|
+
|
|
90
|
+
export const ConnectorAccountsParamsSchema = z.object({
|
|
91
|
+
connectorId: z.string().min(1),
|
|
92
|
+
})
|
|
93
|
+
|
|
94
|
+
/** Where a sync of an OAuth connector's accounts stand, by the latest run of each. */
|
|
95
|
+
const SyncAccountSummarySchema = z.object({
|
|
96
|
+
total: z.number(),
|
|
97
|
+
/** Their latest run is queued or running. */
|
|
98
|
+
running: z.number(),
|
|
99
|
+
/** Their latest run failed because the account needs reconnecting. */
|
|
100
|
+
needsReconnecting: z.number(),
|
|
101
|
+
/** Their latest run failed for any other reason. */
|
|
102
|
+
failing: z.number(),
|
|
103
|
+
/** Their latest run succeeded. */
|
|
104
|
+
synced: z.number(),
|
|
105
|
+
/** When the most recent of those successful runs finished. */
|
|
106
|
+
lastSyncedAt: z.string().optional(),
|
|
107
|
+
})
|
|
108
|
+
|
|
65
109
|
export const SyncSchema = z.object({
|
|
66
110
|
id: z.string(),
|
|
67
111
|
mode: SyncModeSchema,
|
|
@@ -75,6 +119,17 @@ export const SyncSchema = z.object({
|
|
|
75
119
|
}),
|
|
76
120
|
triggers: z.array(SyncTriggerSchema),
|
|
77
121
|
latestRun: SyncRunSchema.nullable(),
|
|
122
|
+
/** On a sync of an OAuth connector: the accounts the caller may see. */
|
|
123
|
+
accounts: SyncAccountSummarySchema.optional(),
|
|
124
|
+
})
|
|
125
|
+
|
|
126
|
+
export const ConnectionSyncRunsParamsSchema = z.object({
|
|
127
|
+
connectorId: z.string().min(1),
|
|
128
|
+
connectionId: z.string().min(1),
|
|
129
|
+
})
|
|
130
|
+
|
|
131
|
+
export const ConnectionSyncRunsResponseSchema = z.object({
|
|
132
|
+
runs: z.array(SyncRunSchema),
|
|
78
133
|
})
|
|
79
134
|
|
|
80
135
|
export const SyncRunListResponseSchema = z.object({
|
|
@@ -83,9 +138,16 @@ export const SyncRunListResponseSchema = z.object({
|
|
|
83
138
|
total: z.number(),
|
|
84
139
|
})
|
|
85
140
|
|
|
86
|
-
|
|
141
|
+
const RequestedSyncRunSchema = z.object({
|
|
87
142
|
runId: z.string(),
|
|
88
143
|
jobId: z.string(),
|
|
89
144
|
syncId: z.string(),
|
|
145
|
+
/** The connection the run reads, on a sync of an OAuth connector. */
|
|
146
|
+
connectionId: z.string().optional(),
|
|
90
147
|
queuedAt: z.string(),
|
|
91
148
|
})
|
|
149
|
+
|
|
150
|
+
/** One run for a static connector's sync; one per connection for an OAuth connector's sync. */
|
|
151
|
+
export const RequestSyncRunResponseSchema = z.object({
|
|
152
|
+
runs: z.array(RequestedSyncRunSchema),
|
|
153
|
+
})
|
package/src/server.ts
CHANGED
|
@@ -1,13 +1,14 @@
|
|
|
1
1
|
import { cors } from "@elysiajs/cors"
|
|
2
2
|
import { openapi } from "@elysiajs/openapi"
|
|
3
3
|
import type { OntologyMaintenanceHandle, SixbHostView } from "@sixb/core"
|
|
4
|
+
import { ACTION_RUN_DRAIN_TIMEOUT_MS } from "@sixb/core/internal/actions"
|
|
4
5
|
import { bindAgentRunRequestExecution } from "@sixb/core/internal/agent-execution"
|
|
5
6
|
import { ARTIFACT_FRAME_ROUTE_PREFIX } from "@sixb/core/internal/artifacts/frames"
|
|
6
7
|
import { CSRF_HEADER_NAME, setRequestClientAddress } from "@sixb/core/internal/auth"
|
|
7
8
|
import { bindRequestExecution } from "@sixb/core/internal/request-execution"
|
|
8
9
|
import { findDatasetIngestRuntime, setApiPublicOrigin } from "@sixb/core/internal/runtime"
|
|
9
10
|
import { checkPipelineMarkings, warmAppliedMarkings } from "@sixb/core/internal/security"
|
|
10
|
-
import type { Server } from "bun"
|
|
11
|
+
import type { Server, ServerWebSocket } from "bun"
|
|
11
12
|
import { Elysia, ParseError } from "elysia"
|
|
12
13
|
import { websocket as elysiaWebSocket } from "elysia/ws"
|
|
13
14
|
import {
|
|
@@ -70,6 +71,8 @@ import {
|
|
|
70
71
|
|
|
71
72
|
// Clients send only subscription messages; Bun's default would buffer up to 16 MB for one.
|
|
72
73
|
export const MAX_WEBSOCKET_MESSAGE_BYTES = 64 * 1024
|
|
74
|
+
/** RFC 6455 Service Restart: tells clients to hand off immediately to the new release. */
|
|
75
|
+
const SERVICE_RESTART_CLOSE_CODE = 1012
|
|
73
76
|
|
|
74
77
|
export interface SixbServerOptions {
|
|
75
78
|
host: SixbHostView
|
|
@@ -100,6 +103,15 @@ export interface SixbServerOptions {
|
|
|
100
103
|
ingestFlush?: boolean
|
|
101
104
|
}
|
|
102
105
|
|
|
106
|
+
export interface SixbServerStopOptions {
|
|
107
|
+
/**
|
|
108
|
+
* How long in-flight HTTP requests may take to finish before remaining connections are closed.
|
|
109
|
+
* Defaults to 65 seconds, matching the Action drain window; `0` closes them at once. A stop
|
|
110
|
+
* called while another one drains joins it, and a shorter timeout brings its deadline closer.
|
|
111
|
+
*/
|
|
112
|
+
readonly timeoutMs?: number
|
|
113
|
+
}
|
|
114
|
+
|
|
103
115
|
export function createSixbServer(options: SixbServerOptions): SixbServer {
|
|
104
116
|
return new SixbServer(options)
|
|
105
117
|
}
|
|
@@ -118,10 +130,13 @@ export class SixbServer {
|
|
|
118
130
|
private readonly timing: SixbRequestTimingOptions
|
|
119
131
|
private app: SixbApp | null = null
|
|
120
132
|
private bunServer: ReturnType<typeof Bun.serve> | null = null
|
|
133
|
+
private closeWebSockets: (() => void) | null = null
|
|
134
|
+
private stopping = false
|
|
121
135
|
private readonly hostsOntologyMaintenance: boolean
|
|
122
136
|
private readonly flushesIngestion: boolean
|
|
123
137
|
private maintenance: OntologyMaintenanceHandle | null = null
|
|
124
138
|
private stopSweeper: (() => void) | null = null
|
|
139
|
+
private inProgressStop: InProgressStop | null = null
|
|
125
140
|
|
|
126
141
|
constructor(options: SixbServerOptions) {
|
|
127
142
|
this.hostRuntime = options.host
|
|
@@ -190,10 +205,20 @@ export class SixbServer {
|
|
|
190
205
|
return this.sharedAccessOptions
|
|
191
206
|
}
|
|
192
207
|
|
|
208
|
+
/** Marks the server as stopping so `/ready` answers `503` before connections close. */
|
|
209
|
+
markStopping(): void {
|
|
210
|
+
this.stopping = true
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
isStopping(): boolean {
|
|
214
|
+
return this.stopping
|
|
215
|
+
}
|
|
216
|
+
|
|
193
217
|
async start(): Promise<void> {
|
|
194
218
|
if (this.app !== null || this.bunServer !== null || this.maintenance !== null) {
|
|
195
219
|
throw new Error("[SixbServer] Server is already running.")
|
|
196
220
|
}
|
|
221
|
+
this.stopping = false
|
|
197
222
|
|
|
198
223
|
// Startup cannot see through SQL steps: check what they derive before serving any request.
|
|
199
224
|
await checkPipelineMarkings({
|
|
@@ -215,15 +240,18 @@ export class SixbServer {
|
|
|
215
240
|
|
|
216
241
|
try {
|
|
217
242
|
this.app = createSixbApi(this)
|
|
218
|
-
|
|
243
|
+
const started = startApiServer(this.app, {
|
|
219
244
|
host: this.hostname,
|
|
220
245
|
port: this.port,
|
|
221
246
|
resolveClientAddress: this.resolveClientAddress,
|
|
222
247
|
timing: this.timing,
|
|
223
248
|
})
|
|
249
|
+
this.bunServer = started.bunServer
|
|
250
|
+
this.closeWebSockets = started.closeWebSockets
|
|
224
251
|
} catch (error) {
|
|
225
252
|
this.app = null
|
|
226
253
|
this.bunServer = null
|
|
254
|
+
this.closeWebSockets = null
|
|
227
255
|
this.maintenance = null
|
|
228
256
|
await maintenance?.stop()
|
|
229
257
|
const message = error instanceof Error ? error.message : String(error)
|
|
@@ -245,18 +273,49 @@ export class SixbServer {
|
|
|
245
273
|
if (ingest) ingest.writesInline = inline
|
|
246
274
|
}
|
|
247
275
|
|
|
248
|
-
async stop(): Promise<void> {
|
|
276
|
+
async stop(options: SixbServerStopOptions = {}): Promise<void> {
|
|
277
|
+
const timeoutMs = resolveStopTimeoutMs(options.timeoutMs, ACTION_RUN_DRAIN_TIMEOUT_MS)
|
|
278
|
+
|
|
279
|
+
// A stop that arrives while another one drains joins it, and can only bring its deadline
|
|
280
|
+
// closer: `sixb api` passes `timeoutMs: 0` when SIGINT follows SIGTERM.
|
|
281
|
+
if (this.inProgressStop) {
|
|
282
|
+
this.inProgressStop.deadline.bringForward(timeoutMs)
|
|
283
|
+
return this.inProgressStop.done
|
|
284
|
+
}
|
|
285
|
+
|
|
286
|
+
const deadline = new StopDeadline(timeoutMs)
|
|
287
|
+
const done = this.stopUntil(deadline).finally(() => {
|
|
288
|
+
this.inProgressStop = null
|
|
289
|
+
})
|
|
290
|
+
this.inProgressStop = { deadline, done }
|
|
291
|
+
return done
|
|
292
|
+
}
|
|
293
|
+
|
|
294
|
+
private async stopUntil(deadline: StopDeadline): Promise<void> {
|
|
295
|
+
this.stopping = true
|
|
249
296
|
this.setIngestFlush(false)
|
|
250
297
|
this.stopSweeper?.()
|
|
251
298
|
this.stopSweeper = null
|
|
252
|
-
|
|
253
|
-
|
|
254
|
-
|
|
299
|
+
|
|
300
|
+
const bunServer = this.bunServer
|
|
301
|
+
const closeWebSockets = this.closeWebSockets
|
|
302
|
+
const app = this.app
|
|
303
|
+
this.bunServer = null
|
|
304
|
+
this.closeWebSockets = null
|
|
305
|
+
this.app = null
|
|
306
|
+
|
|
307
|
+
const stopAppAndSockets = async () => {
|
|
308
|
+
try {
|
|
309
|
+
if (app) await stopElysiaHooks(app)
|
|
310
|
+
} finally {
|
|
311
|
+
closeWebSockets?.()
|
|
312
|
+
}
|
|
255
313
|
}
|
|
256
314
|
|
|
257
|
-
if (
|
|
258
|
-
await
|
|
259
|
-
|
|
315
|
+
if (bunServer) {
|
|
316
|
+
await drainBunServer(bunServer, deadline, stopAppAndSockets)
|
|
317
|
+
} else {
|
|
318
|
+
await stopAppAndSockets()
|
|
260
319
|
}
|
|
261
320
|
|
|
262
321
|
const maintenance = this.maintenance
|
|
@@ -517,6 +576,7 @@ export function createSixbApi(server: SixbServer) {
|
|
|
517
576
|
registerHttpRoutes(app, host, {
|
|
518
577
|
sharedAccess,
|
|
519
578
|
browserPolicy: apiBrowserPolicy,
|
|
579
|
+
isStopping: () => server.isStopping(),
|
|
520
580
|
connectorConnections: {
|
|
521
581
|
resolveReturnTo: (request, returnTo) =>
|
|
522
582
|
server.resolveAuthRedirectContext(request, { returnTo }).returnTo,
|
|
@@ -608,6 +668,7 @@ function startApiServer(
|
|
|
608
668
|
readonly timing: SixbRequestTimingOptions
|
|
609
669
|
}
|
|
610
670
|
) {
|
|
671
|
+
const openSockets = new Set<ServerWebSocket<unknown>>()
|
|
611
672
|
const bunServer = Bun.serve({
|
|
612
673
|
port: options.port,
|
|
613
674
|
hostname: options.host,
|
|
@@ -624,22 +685,153 @@ function startApiServer(
|
|
|
624
685
|
}
|
|
625
686
|
return timeRequest(request, options.timing, () => app.fetch(request))
|
|
626
687
|
},
|
|
627
|
-
websocket: getElysiaWsHandler(app),
|
|
688
|
+
websocket: getElysiaWsHandler(app, openSockets),
|
|
628
689
|
} as Parameters<typeof Bun.serve>[0])
|
|
629
690
|
|
|
630
691
|
attachBunServer(app, bunServer)
|
|
631
|
-
return
|
|
692
|
+
return {
|
|
693
|
+
bunServer,
|
|
694
|
+
closeWebSockets: () => {
|
|
695
|
+
for (const ws of [...openSockets]) {
|
|
696
|
+
try {
|
|
697
|
+
ws.close(SERVICE_RESTART_CLOSE_CODE, "Service Restart")
|
|
698
|
+
} catch {
|
|
699
|
+
// Already closed.
|
|
700
|
+
}
|
|
701
|
+
}
|
|
702
|
+
openSockets.clear()
|
|
703
|
+
},
|
|
704
|
+
}
|
|
632
705
|
}
|
|
633
706
|
|
|
634
|
-
function getElysiaWsHandler(app: SixbApp) {
|
|
707
|
+
function getElysiaWsHandler(app: SixbApp, openSockets: Set<ServerWebSocket<unknown>>) {
|
|
635
708
|
const cfg = (app as unknown as { config?: { websocket?: Record<string, unknown> } }).config
|
|
636
|
-
|
|
709
|
+
const base = {
|
|
637
710
|
...elysiaWebSocket,
|
|
638
711
|
...(cfg?.websocket ?? {}),
|
|
712
|
+
} as NonNullable<Parameters<typeof Bun.serve>[0]["websocket"]>
|
|
713
|
+
return {
|
|
714
|
+
...base,
|
|
639
715
|
maxPayloadLength: MAX_WEBSOCKET_MESSAGE_BYTES,
|
|
716
|
+
open(ws: ServerWebSocket<unknown>) {
|
|
717
|
+
openSockets.add(ws)
|
|
718
|
+
return base.open?.(ws)
|
|
719
|
+
},
|
|
720
|
+
close(ws: ServerWebSocket<unknown>, code: number, reason: string) {
|
|
721
|
+
openSockets.delete(ws)
|
|
722
|
+
return base.close?.(ws, code, reason)
|
|
723
|
+
},
|
|
640
724
|
} as Parameters<typeof Bun.serve>[0]["websocket"]
|
|
641
725
|
}
|
|
642
726
|
|
|
727
|
+
function resolveStopTimeoutMs(timeoutMs: number | undefined, fallbackMs: number): number {
|
|
728
|
+
const resolved = timeoutMs ?? fallbackMs
|
|
729
|
+
if (!Number.isFinite(resolved) || resolved < 0) {
|
|
730
|
+
throw new Error("[SixbServer] Stop timeout must be a non-negative finite number.")
|
|
731
|
+
}
|
|
732
|
+
return resolved
|
|
733
|
+
}
|
|
734
|
+
|
|
735
|
+
/** A stop under way: a later `stop()` joins `done` and may bring `deadline` closer. */
|
|
736
|
+
interface InProgressStop {
|
|
737
|
+
readonly deadline: StopDeadline
|
|
738
|
+
readonly done: Promise<void>
|
|
739
|
+
}
|
|
740
|
+
|
|
741
|
+
/** When a stopping server gives up on in-flight requests. A later `stop()` can only bring it closer. */
|
|
742
|
+
class StopDeadline {
|
|
743
|
+
private at: number
|
|
744
|
+
|
|
745
|
+
constructor(timeoutMs: number) {
|
|
746
|
+
this.at = Date.now() + timeoutMs
|
|
747
|
+
}
|
|
748
|
+
|
|
749
|
+
remainingMs(): number {
|
|
750
|
+
return this.at - Date.now()
|
|
751
|
+
}
|
|
752
|
+
|
|
753
|
+
bringForward(timeoutMs: number): void {
|
|
754
|
+
this.at = Math.min(this.at, Date.now() + timeoutMs)
|
|
755
|
+
}
|
|
756
|
+
}
|
|
757
|
+
|
|
758
|
+
async function drainBunServer(
|
|
759
|
+
server: ReturnType<typeof Bun.serve>,
|
|
760
|
+
deadline: StopDeadline,
|
|
761
|
+
beforeWait: () => Promise<void>
|
|
762
|
+
): Promise<void> {
|
|
763
|
+
if (deadline.remainingMs() <= 0) {
|
|
764
|
+
try {
|
|
765
|
+
await beforeWait()
|
|
766
|
+
} finally {
|
|
767
|
+
await server.stop(true)
|
|
768
|
+
}
|
|
769
|
+
return
|
|
770
|
+
}
|
|
771
|
+
|
|
772
|
+
const draining = server.stop(false)
|
|
773
|
+
try {
|
|
774
|
+
await beforeWait()
|
|
775
|
+
} catch (error) {
|
|
776
|
+
await server.stop(true)
|
|
777
|
+
await draining
|
|
778
|
+
throw error
|
|
779
|
+
}
|
|
780
|
+
|
|
781
|
+
// Bun's `stop(false)` can stay pending on an already-answered 413 socket whose unread upload
|
|
782
|
+
// body has not hit its idle timeout yet, even though `pendingRequests` is already 0.
|
|
783
|
+
await waitUntilIdleOrTimeout(server, draining, deadline)
|
|
784
|
+
await server.stop(true)
|
|
785
|
+
await draining
|
|
786
|
+
}
|
|
787
|
+
|
|
788
|
+
/** Polls every 25 ms, so a deadline brought forward takes effect within one poll. */
|
|
789
|
+
async function waitUntilIdleOrTimeout(
|
|
790
|
+
server: ReturnType<typeof Bun.serve>,
|
|
791
|
+
draining: Promise<void>,
|
|
792
|
+
deadline: StopDeadline
|
|
793
|
+
): Promise<void> {
|
|
794
|
+
let settled = false
|
|
795
|
+
void draining.then(
|
|
796
|
+
() => {
|
|
797
|
+
settled = true
|
|
798
|
+
},
|
|
799
|
+
() => {
|
|
800
|
+
settled = true
|
|
801
|
+
}
|
|
802
|
+
)
|
|
803
|
+
|
|
804
|
+
while (!settled && (server.pendingRequests > 0 || server.pendingWebSockets > 0)) {
|
|
805
|
+
const remaining = deadline.remainingMs()
|
|
806
|
+
if (remaining <= 0) return
|
|
807
|
+
let timer: ReturnType<typeof setTimeout> | undefined
|
|
808
|
+
try {
|
|
809
|
+
await Promise.race([
|
|
810
|
+
draining,
|
|
811
|
+
new Promise<void>((resolve) => {
|
|
812
|
+
timer = setTimeout(resolve, Math.min(remaining, 25))
|
|
813
|
+
}),
|
|
814
|
+
])
|
|
815
|
+
} finally {
|
|
816
|
+
if (timer !== undefined) clearTimeout(timer)
|
|
817
|
+
}
|
|
818
|
+
}
|
|
819
|
+
}
|
|
820
|
+
|
|
643
821
|
function attachBunServer(app: SixbApp, bunServer: ReturnType<typeof Bun.serve>) {
|
|
644
822
|
;(app as unknown as { server: typeof bunServer }).server = bunServer
|
|
645
823
|
}
|
|
824
|
+
|
|
825
|
+
/**
|
|
826
|
+
* Runs Elysia's `onStop` hooks (such as `LiveRooms.close()`) and awaits their promises without
|
|
827
|
+
* waiting on `bunServer.stop(false)` first, which stays pending while WebSockets are still open.
|
|
828
|
+
*/
|
|
829
|
+
async function stopElysiaHooks(app: SixbApp): Promise<void> {
|
|
830
|
+
const internal = app as unknown as {
|
|
831
|
+
server: unknown
|
|
832
|
+
event?: { stop?: ReadonlyArray<{ fn: (instance: SixbApp) => unknown }> }
|
|
833
|
+
}
|
|
834
|
+
const hooks = internal.event?.stop ?? []
|
|
835
|
+
internal.server = null
|
|
836
|
+
await Promise.all(hooks.map((hook) => Promise.resolve(hook.fn(app))))
|
|
837
|
+
}
|