@sixb/server 0.1.25 → 0.2.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/README.md +1 -1
- package/dist/auth/public-routes.d.ts.map +1 -1
- package/dist/auth/run-token.d.ts +28 -0
- package/dist/auth/run-token.d.ts.map +1 -0
- package/dist/auth/scope.d.ts +11 -13
- package/dist/auth/scope.d.ts.map +1 -1
- package/dist/index.d.ts +1 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +4999 -4151
- package/dist/index.js.map +47 -43
- package/dist/registerRoutes.d.ts.map +1 -1
- package/dist/routes/actions.d.ts +1 -1
- package/dist/routes/agent-approval-gate.d.ts +7 -4
- package/dist/routes/agent-approval-gate.d.ts.map +1 -1
- package/dist/routes/agent-approvals.d.ts +14 -5
- package/dist/routes/agent-approvals.d.ts.map +1 -1
- package/dist/routes/agent-children.d.ts +2 -2
- package/dist/routes/agent-computers.d.ts +338 -0
- package/dist/routes/agent-computers.d.ts.map +1 -0
- package/dist/routes/agent-runners.d.ts +74 -0
- package/dist/routes/agent-runners.d.ts.map +1 -0
- package/dist/routes/agents.d.ts +250 -16
- package/dist/routes/agents.d.ts.map +1 -1
- package/dist/routes/ai-accounting.d.ts.map +1 -1
- package/dist/routes/artifacts.d.ts +5 -28
- package/dist/routes/artifacts.d.ts.map +1 -1
- package/dist/routes/auth.d.ts +10 -1
- package/dist/routes/auth.d.ts.map +1 -1
- package/dist/routes/datasets.d.ts +93 -17
- package/dist/routes/datasets.d.ts.map +1 -1
- package/dist/routes/events.d.ts +1 -1
- package/dist/routes/links.d.ts +121 -81
- package/dist/routes/links.d.ts.map +1 -1
- package/dist/routes/logs.d.ts +3 -3
- package/dist/routes/objects.d.ts +149 -58
- package/dist/routes/objects.d.ts.map +1 -1
- package/dist/routes/observed-agent-threads.d.ts +25 -4
- package/dist/routes/observed-agent-threads.d.ts.map +1 -1
- package/dist/routes/pipelines.d.ts +2 -2
- package/dist/routes/pipelines.d.ts.map +1 -1
- package/dist/routes/projections.d.ts +124 -122
- package/dist/routes/projections.d.ts.map +1 -1
- package/dist/routes/rules.d.ts +2 -2
- package/dist/routes/shared-access.d.ts +2 -2
- package/dist/routes/syncs.d.ts +34 -34
- package/dist/routes/syncs.d.ts.map +1 -1
- package/dist/routes/telemetry.d.ts +0 -50
- package/dist/routes/telemetry.d.ts.map +1 -1
- package/dist/routes/users.d.ts +1 -0
- package/dist/routes/users.d.ts.map +1 -1
- package/dist/routes/webhook-runs.d.ts +1 -1
- package/dist/routes/workflows.d.ts +25 -14
- package/dist/routes/workflows.d.ts.map +1 -1
- package/dist/routes/ws/agents.d.ts +4 -1
- package/dist/routes/ws/agents.d.ts.map +1 -1
- package/dist/routes/ws/logs.d.ts +10 -10
- package/dist/schemas/actions.d.ts +3 -3
- package/dist/schemas/activity.d.ts +4 -4
- package/dist/schemas/agent-approvals.d.ts +21 -21
- package/dist/schemas/agents.d.ts +819 -88
- package/dist/schemas/agents.d.ts.map +1 -1
- package/dist/schemas/ai-accounting.d.ts +1114 -6
- package/dist/schemas/ai-accounting.d.ts.map +1 -1
- package/dist/schemas/auth.d.ts +49 -2
- package/dist/schemas/auth.d.ts.map +1 -1
- package/dist/schemas/datasets.d.ts +303 -60
- package/dist/schemas/datasets.d.ts.map +1 -1
- package/dist/schemas/event-payloads.d.ts +6 -6
- package/dist/schemas/events.d.ts +8 -8
- package/dist/schemas/lineage.d.ts +1272 -0
- package/dist/schemas/lineage.d.ts.map +1 -0
- package/dist/schemas/links.d.ts +4 -27
- package/dist/schemas/links.d.ts.map +1 -1
- package/dist/schemas/logs.d.ts +22 -22
- package/dist/schemas/objects.d.ts +7 -26
- package/dist/schemas/objects.d.ts.map +1 -1
- package/dist/schemas/pipelines.d.ts +12 -12
- package/dist/schemas/projections.d.ts +747 -733
- package/dist/schemas/projections.d.ts.map +1 -1
- package/dist/schemas/rules.d.ts +4 -4
- package/dist/schemas/shared-access.d.ts +2 -2
- package/dist/schemas/syncs.d.ts +24 -24
- package/dist/schemas/telemetry.d.ts +0 -13
- package/dist/schemas/telemetry.d.ts.map +1 -1
- package/dist/schemas/users.d.ts +8 -0
- package/dist/schemas/users.d.ts.map +1 -1
- package/dist/schemas/webhook-runs.d.ts +2 -2
- package/dist/schemas/workflows.d.ts +133 -44
- package/dist/schemas/workflows.d.ts.map +1 -1
- package/dist/server.d.ts +5 -0
- package/dist/server.d.ts.map +1 -1
- package/dist/utils/request-body.d.ts +5 -0
- package/dist/utils/request-body.d.ts.map +1 -1
- package/dist/utils/request-timing.d.ts +18 -0
- package/dist/utils/request-timing.d.ts.map +1 -0
- package/package.json +7 -7
- package/src/auth/public-routes.ts +0 -6
- package/src/auth/run-token.ts +327 -0
- package/src/auth/scope.ts +16 -37
- package/src/index.ts +1 -0
- package/src/registerRoutes.ts +4 -2
- package/src/routes/agent-approval-gate.ts +40 -14
- package/src/routes/agent-approvals.ts +3 -3
- package/src/routes/agent-computers.ts +348 -0
- package/src/routes/agent-runners.ts +205 -0
- package/src/routes/agents.ts +193 -26
- package/src/routes/ai-accounting.ts +149 -12
- package/src/routes/artifacts.ts +55 -11
- package/src/routes/auth.ts +24 -2
- package/src/routes/datasets.ts +60 -5
- package/src/routes/links.ts +43 -76
- package/src/routes/objects.ts +49 -42
- package/src/routes/observed-agent-threads.ts +2 -2
- package/src/routes/pipelines.ts +5 -0
- package/src/routes/syncs.ts +4 -0
- package/src/routes/telemetry.ts +1 -42
- package/src/routes/users.ts +15 -2
- package/src/routes/ws/agents.ts +10 -1
- package/src/schemas/agents.ts +131 -1
- package/src/schemas/ai-accounting.ts +78 -15
- package/src/schemas/artifacts.ts +1 -1
- package/src/schemas/auth.ts +19 -0
- package/src/schemas/datasets.ts +36 -0
- package/src/schemas/lineage.ts +115 -0
- package/src/schemas/links.ts +3 -11
- package/src/schemas/objects.ts +6 -10
- package/src/schemas/projections.ts +2 -0
- package/src/schemas/telemetry.ts +0 -6
- package/src/schemas/users.ts +6 -0
- package/src/server.ts +53 -15
- package/src/utils/request-body.ts +10 -4
- package/src/utils/request-timing.ts +136 -0
- package/dist/routes/agent-api-gateway.d.ts +0 -4
- package/dist/routes/agent-api-gateway.d.ts.map +0 -1
- package/src/routes/agent-api-gateway.ts +0 -404
package/src/server.ts
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
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 {
|
|
4
|
+
import { bindAgentRunRequestExecution } from "@sixb/core/internal/agent-execution"
|
|
5
5
|
import { ARTIFACT_FRAME_ROUTE_PREFIX } from "@sixb/core/internal/artifacts/frames"
|
|
6
6
|
import { CSRF_HEADER_NAME, setRequestClientAddress } from "@sixb/core/internal/auth"
|
|
7
7
|
import { bindRequestExecution } from "@sixb/core/internal/request-execution"
|
|
@@ -33,7 +33,7 @@ import {
|
|
|
33
33
|
import { CSRF_TOKEN_RESPONSE_HEADER_NAME } from "./auth/csrf"
|
|
34
34
|
import type { SixbAuthExperienceOptions } from "./auth/experience"
|
|
35
35
|
import { ServerAuthGuard } from "./auth/guard"
|
|
36
|
-
import {
|
|
36
|
+
import { type RunTokenDecision, requestRunToken, resolveRunTokenRequest } from "./auth/run-token"
|
|
37
37
|
import { SESSION_ACTIVITY_HEADER_NAME } from "./auth/session-activity"
|
|
38
38
|
import { createSessionRenewalCookieHeaders } from "./auth/session-cookies"
|
|
39
39
|
import {
|
|
@@ -55,12 +55,18 @@ import {
|
|
|
55
55
|
} from "./openapi/security"
|
|
56
56
|
import { OPENAPI_TAG_METADATA } from "./openapi/tags"
|
|
57
57
|
import { registerHttpRoutes } from "./registerRoutes"
|
|
58
|
+
import { agentRunSessionHandler, startLapsedRunSweeper } from "./routes/agent-runners"
|
|
58
59
|
import { registerAuthRoutes } from "./routes/auth"
|
|
59
60
|
import { DEFAULT_SIMPLE_FILE_UPLOAD_BODY_BYTES } from "./routes/files"
|
|
60
61
|
import { registerWebhookRoutes } from "./routes/webhooks"
|
|
61
62
|
import { registerWebSocketRoutes } from "./routes/ws"
|
|
62
63
|
import { ObjectQueryOpenApiSchemas } from "./schemas/objects"
|
|
63
64
|
import { limitRequestBody, RequestBodyTooLargeError } from "./utils/request-body"
|
|
65
|
+
import {
|
|
66
|
+
markRequestAuthorized,
|
|
67
|
+
type SixbRequestTimingOptions,
|
|
68
|
+
timeRequest,
|
|
69
|
+
} from "./utils/request-timing"
|
|
64
70
|
|
|
65
71
|
// Clients send only subscription messages; Bun's default would buffer up to 16 MB for one.
|
|
66
72
|
export const MAX_WEBSOCKET_MESSAGE_BYTES = 64 * 1024
|
|
@@ -80,6 +86,8 @@ export interface SixbServerOptions {
|
|
|
80
86
|
* `"private"` for loopback, private, and link-local networks. Defaults to `["private"]`.
|
|
81
87
|
*/
|
|
82
88
|
trustedProxies?: readonly string[]
|
|
89
|
+
/** Where requests spend their time: a `Server-Timing` header and a log of slow requests. */
|
|
90
|
+
timing?: SixbRequestTimingOptions
|
|
83
91
|
}
|
|
84
92
|
|
|
85
93
|
export function createSixbServer(options: SixbServerOptions): SixbServer {
|
|
@@ -97,15 +105,18 @@ export class SixbServer {
|
|
|
97
105
|
private readonly authExperience?: SixbAuthExperienceOptions
|
|
98
106
|
private readonly sharedAccessOptions: SixbSharedAccessOptions
|
|
99
107
|
private readonly resolveClientAddress: ClientAddressResolver
|
|
108
|
+
private readonly timing: SixbRequestTimingOptions
|
|
100
109
|
private app: SixbApp | null = null
|
|
101
110
|
private bunServer: ReturnType<typeof Bun.serve> | null = null
|
|
102
111
|
private maintenance: OntologyMaintenanceHandle | null = null
|
|
112
|
+
private stopSweeper: (() => void) | null = null
|
|
103
113
|
|
|
104
114
|
constructor(options: SixbServerOptions) {
|
|
105
115
|
this.hostRuntime = options.host
|
|
106
116
|
this.port = options.port ?? 3000
|
|
107
117
|
this.hostname = options.hostname ?? "0.0.0.0"
|
|
108
118
|
this.quiet = options.quiet ?? false
|
|
119
|
+
this.timing = options.timing ?? {}
|
|
109
120
|
this.apiBrowserPolicy = resolveApiBrowserPolicy(options.browser)
|
|
110
121
|
// URLs the API hands to third parties, such as file download URLs, name this origin.
|
|
111
122
|
if (this.apiBrowserPolicy.publicOrigin) {
|
|
@@ -189,6 +200,7 @@ export class SixbServer {
|
|
|
189
200
|
host: this.hostname,
|
|
190
201
|
port: this.port,
|
|
191
202
|
resolveClientAddress: this.resolveClientAddress,
|
|
203
|
+
timing: this.timing,
|
|
192
204
|
})
|
|
193
205
|
} catch (error) {
|
|
194
206
|
this.app = null
|
|
@@ -199,6 +211,9 @@ export class SixbServer {
|
|
|
199
211
|
throw new Error(`[SixbServer] Failed to listen on ${this.hostname}:${this.port}: ${message}`)
|
|
200
212
|
}
|
|
201
213
|
|
|
214
|
+
// A runner on a computer has no worker behind it: the API ends the runs it stops renewing.
|
|
215
|
+
this.stopSweeper = startLapsedRunSweeper(this.hostRuntime)
|
|
216
|
+
|
|
202
217
|
if (!this.quiet) {
|
|
203
218
|
const base = `http://${this.hostname}:${this.getPort()}`
|
|
204
219
|
console.log(`Sixb server running at ${base}`)
|
|
@@ -207,6 +222,8 @@ export class SixbServer {
|
|
|
207
222
|
}
|
|
208
223
|
|
|
209
224
|
async stop(): Promise<void> {
|
|
225
|
+
this.stopSweeper?.()
|
|
226
|
+
this.stopSweeper = null
|
|
210
227
|
if (this.bunServer) {
|
|
211
228
|
this.bunServer.stop(true)
|
|
212
229
|
this.bunServer = null
|
|
@@ -234,6 +251,7 @@ export function createSixbApi(server: SixbServer) {
|
|
|
234
251
|
Request,
|
|
235
252
|
Awaited<ReturnType<SharedAccessBoundary["resolveRequest"]>>
|
|
236
253
|
>()
|
|
254
|
+
const preparedRunToken = new WeakMap<Request, RunTokenDecision>()
|
|
237
255
|
guard.assertCanServeHttp({ production: process.env.NODE_ENV === "production" })
|
|
238
256
|
const apiBrowserPolicy = server.getApiBrowserPolicy()
|
|
239
257
|
|
|
@@ -261,7 +279,20 @@ export function createSixbApi(server: SixbServer) {
|
|
|
261
279
|
maxAge: 600,
|
|
262
280
|
})
|
|
263
281
|
)
|
|
282
|
+
// A runner's session requests, before anything parses them: a runner token speaks only there.
|
|
283
|
+
const serveRunnerSession = agentRunSessionHandler(host)
|
|
284
|
+
app.onRequest(async ({ request }) => (await serveRunnerSession(request)) ?? undefined)
|
|
285
|
+
app.onRequest(async ({ request }) => {
|
|
286
|
+
// An Agent's commands, as their run: decided before Elysia parses the body, which the approval
|
|
287
|
+
// gate reads from a copy. No session, share or cookie speaks for such a request.
|
|
288
|
+
const runToken = requestRunToken(request)
|
|
289
|
+
if (runToken === undefined) return undefined
|
|
290
|
+
const decision = await resolveRunTokenRequest({ host, request, token: runToken })
|
|
291
|
+
preparedRunToken.set(request, decision)
|
|
292
|
+
return decision.kind === "deny" ? decision.response : undefined
|
|
293
|
+
})
|
|
264
294
|
app.onRequest(async ({ request, set }) => {
|
|
295
|
+
if (preparedRunToken.has(request)) return undefined
|
|
265
296
|
// Resolve Share intent before Elysia parses route inputs. Otherwise an unsupported route or an
|
|
266
297
|
// invalid shared session could escape through a route-specific 4xx before this boundary ran.
|
|
267
298
|
// CORS is registered first so allowed app origins can read these generic boundary responses.
|
|
@@ -286,6 +317,18 @@ export function createSixbApi(server: SixbServer) {
|
|
|
286
317
|
// never choose between a principal SDK and the ambient runtime themselves.
|
|
287
318
|
app
|
|
288
319
|
.derive(async ({ request }) => {
|
|
320
|
+
const runToken = preparedRunToken.get(request)
|
|
321
|
+
preparedRunToken.delete(request)
|
|
322
|
+
if (runToken?.kind === "allow") {
|
|
323
|
+
const { runExecution, ...agentState } = runToken.state
|
|
324
|
+
return {
|
|
325
|
+
auth: { kind: "allow" as const, session: null },
|
|
326
|
+
sharedAccessCookies: null,
|
|
327
|
+
...agentState,
|
|
328
|
+
sixb: bindAgentRunRequestExecution(host, { signal: request.signal, ...runExecution }),
|
|
329
|
+
}
|
|
330
|
+
}
|
|
331
|
+
|
|
289
332
|
const shared =
|
|
290
333
|
preparedSharedAccess.get(request) ?? (await sharedAccess.resolveRequest(request))
|
|
291
334
|
preparedSharedAccess.delete(request)
|
|
@@ -315,17 +358,6 @@ export function createSixbApi(server: SixbServer) {
|
|
|
315
358
|
}
|
|
316
359
|
}
|
|
317
360
|
|
|
318
|
-
const internalAuthState = consumeInternalRequestAuthState(request)
|
|
319
|
-
if (internalAuthState) {
|
|
320
|
-
const { runExecution, ...agentState } = internalAuthState
|
|
321
|
-
return {
|
|
322
|
-
auth: { kind: "allow" as const, session: null },
|
|
323
|
-
sharedAccessCookies: null,
|
|
324
|
-
...agentState,
|
|
325
|
-
sixb: bindAgentGatewayRequestExecution(host, { signal: request.signal, ...runExecution }),
|
|
326
|
-
}
|
|
327
|
-
}
|
|
328
|
-
|
|
329
361
|
const auth = await guard.resolve(request)
|
|
330
362
|
if (auth.kind === "deny" || !auth.session?.authenticated) {
|
|
331
363
|
return {
|
|
@@ -355,7 +387,12 @@ export function createSixbApi(server: SixbServer) {
|
|
|
355
387
|
}),
|
|
356
388
|
}
|
|
357
389
|
})
|
|
358
|
-
.onBeforeHandle(({ auth }) =>
|
|
390
|
+
.onBeforeHandle(({ auth, route }) => {
|
|
391
|
+
// A share or an Agent's run token speaks for someone who has not signed in here.
|
|
392
|
+
const signedIn = auth.kind === "allow" && auth.session?.authenticated === true
|
|
393
|
+
markRequestAuthorized(route, signedIn || (auth.kind === "allow" && !guard.isAuthEnabled()))
|
|
394
|
+
return auth.kind === "deny" ? auth.response : undefined
|
|
395
|
+
})
|
|
359
396
|
.mapResponse(({ auth, request, responseValue, set, sharedAccessCookies }) => {
|
|
360
397
|
if (sharedAccessCookies) {
|
|
361
398
|
if (sharedAccessCookies.setCookies.length > 0) {
|
|
@@ -535,6 +572,7 @@ function startApiServer(
|
|
|
535
572
|
readonly host: string
|
|
536
573
|
readonly port: number
|
|
537
574
|
readonly resolveClientAddress: ClientAddressResolver
|
|
575
|
+
readonly timing: SixbRequestTimingOptions
|
|
538
576
|
}
|
|
539
577
|
) {
|
|
540
578
|
const bunServer = Bun.serve({
|
|
@@ -551,7 +589,7 @@ function startApiServer(
|
|
|
551
589
|
const forwardedFor = request.headers.get("x-forwarded-for")
|
|
552
590
|
setRequestClientAddress(request, options.resolveClientAddress(socketAddress, forwardedFor))
|
|
553
591
|
}
|
|
554
|
-
return app.fetch(request)
|
|
592
|
+
return timeRequest(request, options.timing, () => app.fetch(request))
|
|
555
593
|
},
|
|
556
594
|
websocket: getElysiaWsHandler(app),
|
|
557
595
|
} as Parameters<typeof Bun.serve>[0])
|
|
@@ -54,6 +54,15 @@ export function limitRequestBody(request: Request): Request {
|
|
|
54
54
|
return limited
|
|
55
55
|
}
|
|
56
56
|
|
|
57
|
+
/**
|
|
58
|
+
* Lifts the server's cap for a request whose handler reads the body itself, within its own limit,
|
|
59
|
+
* once it has authenticated the caller: a runner's run session (see serveAgentRunSession).
|
|
60
|
+
*/
|
|
61
|
+
export function liftRequestBodyCap(request: Request): void {
|
|
62
|
+
const cap = requestBodyCaps.get(request)
|
|
63
|
+
if (cap) cap.lifted = true
|
|
64
|
+
}
|
|
65
|
+
|
|
57
66
|
/**
|
|
58
67
|
* Reads a request body fully into memory, failing once it passes `limitBytes`. That limit
|
|
59
68
|
* replaces the server's default cap for this request, so a route reading more than the default
|
|
@@ -66,10 +75,7 @@ export async function readRequestBodyWithLimit(
|
|
|
66
75
|
tooLargeMessage?: string
|
|
67
76
|
): Promise<Uint8Array<ArrayBuffer>> {
|
|
68
77
|
// The loop below enforces `limitBytes` in place of the server's cap.
|
|
69
|
-
|
|
70
|
-
if (cap) {
|
|
71
|
-
cap.lifted = true
|
|
72
|
-
}
|
|
78
|
+
liftRequestBodyCap(request)
|
|
73
79
|
|
|
74
80
|
const contentLength = request.headers.get("content-length")
|
|
75
81
|
if (contentLength !== null) {
|
|
@@ -0,0 +1,136 @@
|
|
|
1
|
+
import { AsyncLocalStorage } from "node:async_hooks"
|
|
2
|
+
import { runWithStorageTimer, StorageTimer } from "@sixb/core/internal/storage-operation-scope"
|
|
3
|
+
|
|
4
|
+
const DEFAULT_SLOW_REQUEST_MILLIS = 1_000
|
|
5
|
+
|
|
6
|
+
export interface SixbRequestTimingOptions {
|
|
7
|
+
/**
|
|
8
|
+
* Send a `Server-Timing` header on responses to signed-in requests, which browsers show under
|
|
9
|
+
* a request's Timing tab. Off by default, since timings reveal how the server spends its time.
|
|
10
|
+
*/
|
|
11
|
+
readonly header?: boolean
|
|
12
|
+
/** Log requests that take at least this long. Defaults to 1000; 0 turns the log off. */
|
|
13
|
+
readonly slowRequestMillis?: number
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
/** Read `SIXB_SERVER_TIMING` and `SIXB_SLOW_REQUEST_MS`. */
|
|
17
|
+
export function requestTimingOptionsFromEnv(
|
|
18
|
+
env: Readonly<Record<string, string | undefined>> = process.env
|
|
19
|
+
): SixbRequestTimingOptions {
|
|
20
|
+
const slowRequestMillis = Number(env.SIXB_SLOW_REQUEST_MS)
|
|
21
|
+
return {
|
|
22
|
+
header: env.SIXB_SERVER_TIMING === "1" || env.SIXB_SERVER_TIMING === "true",
|
|
23
|
+
...(env.SIXB_SLOW_REQUEST_MS && slowRequestMillis >= 0 ? { slowRequestMillis } : {}),
|
|
24
|
+
}
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
class RequestTiming {
|
|
28
|
+
readonly startedAt = performance.now()
|
|
29
|
+
readonly storage = new StorageTimer()
|
|
30
|
+
authorized?: {
|
|
31
|
+
readonly at: number
|
|
32
|
+
readonly storageMillis: number
|
|
33
|
+
readonly storageCalls: number
|
|
34
|
+
readonly route: string
|
|
35
|
+
readonly showTimings: boolean
|
|
36
|
+
}
|
|
37
|
+
subject?: string
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
const currentRequest = new AsyncLocalStorage<RequestTiming>()
|
|
41
|
+
|
|
42
|
+
/** The request has been authenticated and is about to run its route. */
|
|
43
|
+
export function markRequestAuthorized(route: string, showTimings: boolean): void {
|
|
44
|
+
const timing = currentRequest.getStore()
|
|
45
|
+
if (!timing) return
|
|
46
|
+
timing.authorized = {
|
|
47
|
+
at: performance.now(),
|
|
48
|
+
storageMillis: timing.storage.busyMillis,
|
|
49
|
+
storageCalls: timing.storage.calls,
|
|
50
|
+
route,
|
|
51
|
+
showTimings,
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
/** Name what a shared route is working on, so a slow request can be told from its neighbors. */
|
|
56
|
+
export function noteRequestSubject(subject: string | undefined): void {
|
|
57
|
+
const timing = currentRequest.getStore()
|
|
58
|
+
if (timing) timing.subject = subject
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
function measure(timing: RequestTiming) {
|
|
62
|
+
const totalMillis = performance.now() - timing.startedAt
|
|
63
|
+
const authMillis = timing.authorized ? timing.authorized.at - timing.startedAt : 0
|
|
64
|
+
const storageMillis = timing.storage.busyMillis - (timing.authorized?.storageMillis ?? 0)
|
|
65
|
+
return {
|
|
66
|
+
totalMillis,
|
|
67
|
+
authMillis,
|
|
68
|
+
storageMillis,
|
|
69
|
+
storageCalls: timing.storage.calls - (timing.authorized?.storageCalls ?? 0),
|
|
70
|
+
// Validating, checking permissions and building the response.
|
|
71
|
+
appMillis: Math.max(0, totalMillis - authMillis - storageMillis),
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
type RequestMeasure = ReturnType<typeof measure>
|
|
76
|
+
|
|
77
|
+
const storageCalls = (calls: number) => `${calls} ${calls === 1 ? "call" : "calls"}`
|
|
78
|
+
|
|
79
|
+
function serverTimingHeader(measured: RequestMeasure): string {
|
|
80
|
+
const metric = (name: string, millis: number, description?: string) =>
|
|
81
|
+
`${name};dur=${millis.toFixed(1)}${description ? `;desc="${description}"` : ""}`
|
|
82
|
+
return [
|
|
83
|
+
metric("auth", measured.authMillis),
|
|
84
|
+
metric("storage", measured.storageMillis, storageCalls(measured.storageCalls)),
|
|
85
|
+
metric("app", measured.appMillis),
|
|
86
|
+
metric("total", measured.totalMillis),
|
|
87
|
+
].join(", ")
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
function logSlowRequest(
|
|
91
|
+
request: Request,
|
|
92
|
+
response: Response,
|
|
93
|
+
timing: RequestTiming,
|
|
94
|
+
measured: RequestMeasure
|
|
95
|
+
): void {
|
|
96
|
+
// The route's pattern, not its URL: a path or query string can hold a token or a person's data.
|
|
97
|
+
const route = timing.authorized?.route ?? "(public route)"
|
|
98
|
+
const subject = timing.subject ? ` (${timing.subject})` : ""
|
|
99
|
+
const round = Math.round
|
|
100
|
+
console.warn(
|
|
101
|
+
`[SixbServer] Slow request: ${request.method} ${route}${subject} ${response.status} in ` +
|
|
102
|
+
`${round(measured.totalMillis)} ms: auth ${round(measured.authMillis)}, ` +
|
|
103
|
+
`storage ${round(measured.storageMillis)} in ${storageCalls(measured.storageCalls)}, ` +
|
|
104
|
+
`app ${round(measured.appMillis)}`
|
|
105
|
+
)
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
/** Run one request, then say where its time went. Time after the response starts is not counted. */
|
|
109
|
+
export async function timeRequest<TResult>(
|
|
110
|
+
request: Request,
|
|
111
|
+
options: SixbRequestTimingOptions,
|
|
112
|
+
handle: () => TResult | Promise<TResult>
|
|
113
|
+
): Promise<TResult | Response> {
|
|
114
|
+
const timing = new RequestTiming()
|
|
115
|
+
const result = await currentRequest.run(timing, () => runWithStorageTimer(timing.storage, handle))
|
|
116
|
+
// A WebSocket upgrade answers with nothing, and lasts as long as the socket.
|
|
117
|
+
if (!(result instanceof Response)) return result
|
|
118
|
+
|
|
119
|
+
const measured = measure(timing)
|
|
120
|
+
const slowRequestMillis = options.slowRequestMillis ?? DEFAULT_SLOW_REQUEST_MILLIS
|
|
121
|
+
if (slowRequestMillis > 0 && measured.totalMillis >= slowRequestMillis) {
|
|
122
|
+
logSlowRequest(request, result, timing, measured)
|
|
123
|
+
}
|
|
124
|
+
if (!options.header || !timing.authorized?.showTimings) return result
|
|
125
|
+
|
|
126
|
+
const headers = new Headers(result.headers)
|
|
127
|
+
headers.set("server-timing", serverTimingHeader(measured))
|
|
128
|
+
// The app and API are usually on different hosts, and a page only reads timings it is allowed to.
|
|
129
|
+
const origin = request.headers.get("origin")
|
|
130
|
+
if (origin) headers.set("timing-allow-origin", origin)
|
|
131
|
+
return new Response(result.body, {
|
|
132
|
+
status: result.status,
|
|
133
|
+
statusText: result.statusText,
|
|
134
|
+
headers,
|
|
135
|
+
})
|
|
136
|
+
}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"agent-api-gateway.d.ts","sourceRoot":"","sources":["../../src/routes/agent-api-gateway.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,YAAY,CAAA;AAiB9C,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,QAAQ,CAAA;AAkBpC,wBAAgB,6BAA6B,CAAC,GAAG,EAAE,MAAM,EAAE,IAAI,EAAE,YAAY,QAuB5E"}
|