@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.
Files changed (135) hide show
  1. package/README.md +1 -1
  2. package/dist/auth/public-routes.d.ts.map +1 -1
  3. package/dist/auth/run-token.d.ts +28 -0
  4. package/dist/auth/run-token.d.ts.map +1 -0
  5. package/dist/auth/scope.d.ts +11 -13
  6. package/dist/auth/scope.d.ts.map +1 -1
  7. package/dist/index.d.ts +1 -0
  8. package/dist/index.d.ts.map +1 -1
  9. package/dist/index.js +4999 -4151
  10. package/dist/index.js.map +47 -43
  11. package/dist/registerRoutes.d.ts.map +1 -1
  12. package/dist/routes/actions.d.ts +1 -1
  13. package/dist/routes/agent-approval-gate.d.ts +7 -4
  14. package/dist/routes/agent-approval-gate.d.ts.map +1 -1
  15. package/dist/routes/agent-approvals.d.ts +14 -5
  16. package/dist/routes/agent-approvals.d.ts.map +1 -1
  17. package/dist/routes/agent-children.d.ts +2 -2
  18. package/dist/routes/agent-computers.d.ts +338 -0
  19. package/dist/routes/agent-computers.d.ts.map +1 -0
  20. package/dist/routes/agent-runners.d.ts +74 -0
  21. package/dist/routes/agent-runners.d.ts.map +1 -0
  22. package/dist/routes/agents.d.ts +250 -16
  23. package/dist/routes/agents.d.ts.map +1 -1
  24. package/dist/routes/ai-accounting.d.ts.map +1 -1
  25. package/dist/routes/artifacts.d.ts +5 -28
  26. package/dist/routes/artifacts.d.ts.map +1 -1
  27. package/dist/routes/auth.d.ts +10 -1
  28. package/dist/routes/auth.d.ts.map +1 -1
  29. package/dist/routes/datasets.d.ts +93 -17
  30. package/dist/routes/datasets.d.ts.map +1 -1
  31. package/dist/routes/events.d.ts +1 -1
  32. package/dist/routes/links.d.ts +121 -81
  33. package/dist/routes/links.d.ts.map +1 -1
  34. package/dist/routes/logs.d.ts +3 -3
  35. package/dist/routes/objects.d.ts +149 -58
  36. package/dist/routes/objects.d.ts.map +1 -1
  37. package/dist/routes/observed-agent-threads.d.ts +25 -4
  38. package/dist/routes/observed-agent-threads.d.ts.map +1 -1
  39. package/dist/routes/pipelines.d.ts +2 -2
  40. package/dist/routes/pipelines.d.ts.map +1 -1
  41. package/dist/routes/projections.d.ts +124 -122
  42. package/dist/routes/projections.d.ts.map +1 -1
  43. package/dist/routes/rules.d.ts +2 -2
  44. package/dist/routes/shared-access.d.ts +2 -2
  45. package/dist/routes/syncs.d.ts +34 -34
  46. package/dist/routes/syncs.d.ts.map +1 -1
  47. package/dist/routes/telemetry.d.ts +0 -50
  48. package/dist/routes/telemetry.d.ts.map +1 -1
  49. package/dist/routes/users.d.ts +1 -0
  50. package/dist/routes/users.d.ts.map +1 -1
  51. package/dist/routes/webhook-runs.d.ts +1 -1
  52. package/dist/routes/workflows.d.ts +25 -14
  53. package/dist/routes/workflows.d.ts.map +1 -1
  54. package/dist/routes/ws/agents.d.ts +4 -1
  55. package/dist/routes/ws/agents.d.ts.map +1 -1
  56. package/dist/routes/ws/logs.d.ts +10 -10
  57. package/dist/schemas/actions.d.ts +3 -3
  58. package/dist/schemas/activity.d.ts +4 -4
  59. package/dist/schemas/agent-approvals.d.ts +21 -21
  60. package/dist/schemas/agents.d.ts +819 -88
  61. package/dist/schemas/agents.d.ts.map +1 -1
  62. package/dist/schemas/ai-accounting.d.ts +1114 -6
  63. package/dist/schemas/ai-accounting.d.ts.map +1 -1
  64. package/dist/schemas/auth.d.ts +49 -2
  65. package/dist/schemas/auth.d.ts.map +1 -1
  66. package/dist/schemas/datasets.d.ts +303 -60
  67. package/dist/schemas/datasets.d.ts.map +1 -1
  68. package/dist/schemas/event-payloads.d.ts +6 -6
  69. package/dist/schemas/events.d.ts +8 -8
  70. package/dist/schemas/lineage.d.ts +1272 -0
  71. package/dist/schemas/lineage.d.ts.map +1 -0
  72. package/dist/schemas/links.d.ts +4 -27
  73. package/dist/schemas/links.d.ts.map +1 -1
  74. package/dist/schemas/logs.d.ts +22 -22
  75. package/dist/schemas/objects.d.ts +7 -26
  76. package/dist/schemas/objects.d.ts.map +1 -1
  77. package/dist/schemas/pipelines.d.ts +12 -12
  78. package/dist/schemas/projections.d.ts +747 -733
  79. package/dist/schemas/projections.d.ts.map +1 -1
  80. package/dist/schemas/rules.d.ts +4 -4
  81. package/dist/schemas/shared-access.d.ts +2 -2
  82. package/dist/schemas/syncs.d.ts +24 -24
  83. package/dist/schemas/telemetry.d.ts +0 -13
  84. package/dist/schemas/telemetry.d.ts.map +1 -1
  85. package/dist/schemas/users.d.ts +8 -0
  86. package/dist/schemas/users.d.ts.map +1 -1
  87. package/dist/schemas/webhook-runs.d.ts +2 -2
  88. package/dist/schemas/workflows.d.ts +133 -44
  89. package/dist/schemas/workflows.d.ts.map +1 -1
  90. package/dist/server.d.ts +5 -0
  91. package/dist/server.d.ts.map +1 -1
  92. package/dist/utils/request-body.d.ts +5 -0
  93. package/dist/utils/request-body.d.ts.map +1 -1
  94. package/dist/utils/request-timing.d.ts +18 -0
  95. package/dist/utils/request-timing.d.ts.map +1 -0
  96. package/package.json +7 -7
  97. package/src/auth/public-routes.ts +0 -6
  98. package/src/auth/run-token.ts +327 -0
  99. package/src/auth/scope.ts +16 -37
  100. package/src/index.ts +1 -0
  101. package/src/registerRoutes.ts +4 -2
  102. package/src/routes/agent-approval-gate.ts +40 -14
  103. package/src/routes/agent-approvals.ts +3 -3
  104. package/src/routes/agent-computers.ts +348 -0
  105. package/src/routes/agent-runners.ts +205 -0
  106. package/src/routes/agents.ts +193 -26
  107. package/src/routes/ai-accounting.ts +149 -12
  108. package/src/routes/artifacts.ts +55 -11
  109. package/src/routes/auth.ts +24 -2
  110. package/src/routes/datasets.ts +60 -5
  111. package/src/routes/links.ts +43 -76
  112. package/src/routes/objects.ts +49 -42
  113. package/src/routes/observed-agent-threads.ts +2 -2
  114. package/src/routes/pipelines.ts +5 -0
  115. package/src/routes/syncs.ts +4 -0
  116. package/src/routes/telemetry.ts +1 -42
  117. package/src/routes/users.ts +15 -2
  118. package/src/routes/ws/agents.ts +10 -1
  119. package/src/schemas/agents.ts +131 -1
  120. package/src/schemas/ai-accounting.ts +78 -15
  121. package/src/schemas/artifacts.ts +1 -1
  122. package/src/schemas/auth.ts +19 -0
  123. package/src/schemas/datasets.ts +36 -0
  124. package/src/schemas/lineage.ts +115 -0
  125. package/src/schemas/links.ts +3 -11
  126. package/src/schemas/objects.ts +6 -10
  127. package/src/schemas/projections.ts +2 -0
  128. package/src/schemas/telemetry.ts +0 -6
  129. package/src/schemas/users.ts +6 -0
  130. package/src/server.ts +53 -15
  131. package/src/utils/request-body.ts +10 -4
  132. package/src/utils/request-timing.ts +136 -0
  133. package/dist/routes/agent-api-gateway.d.ts +0 -4
  134. package/dist/routes/agent-api-gateway.d.ts.map +0 -1
  135. 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 { bindAgentGatewayRequestExecution } from "@sixb/core/internal/agent-execution"
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 { consumeInternalRequestAuthState } from "./auth/scope"
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 }) => (auth.kind === "deny" ? auth.response : undefined))
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
- const cap = requestBodyCaps.get(request)
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,4 +0,0 @@
1
- import type { SixbHostView } from "@sixb/core";
2
- import type { Elysia } from "elysia";
3
- export declare function registerAgentApiGatewayRoutes(app: Elysia, host: SixbHostView): void;
4
- //# sourceMappingURL=agent-api-gateway.d.ts.map
@@ -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"}