@sixb/server 0.1.1 → 0.1.2

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 (166) hide show
  1. package/README.md +3 -3
  2. package/dist/auth/application-access.d.ts +2 -2
  3. package/dist/auth/application-access.d.ts.map +1 -1
  4. package/dist/auth/connector-callback-cookie.d.ts +12 -0
  5. package/dist/auth/connector-callback-cookie.d.ts.map +1 -0
  6. package/dist/auth/guard.d.ts +3 -3
  7. package/dist/auth/guard.d.ts.map +1 -1
  8. package/dist/auth/public-routes.d.ts.map +1 -1
  9. package/dist/auth/scope.d.ts +13 -27
  10. package/dist/auth/scope.d.ts.map +1 -1
  11. package/dist/auth/session-cookies.d.ts +2 -2
  12. package/dist/auth/session-cookies.d.ts.map +1 -1
  13. package/dist/connectors/http.d.ts +16 -0
  14. package/dist/connectors/http.d.ts.map +1 -0
  15. package/dist/index.js +3293 -2704
  16. package/dist/index.js.map +55 -50
  17. package/dist/openapi/tags.d.ts +11 -3
  18. package/dist/openapi/tags.d.ts.map +1 -1
  19. package/dist/registerRoutes.d.ts +6 -2
  20. package/dist/registerRoutes.d.ts.map +1 -1
  21. package/dist/routes/action-runs.d.ts +21 -31
  22. package/dist/routes/action-runs.d.ts.map +1 -1
  23. package/dist/routes/actions.d.ts +9 -8
  24. package/dist/routes/actions.d.ts.map +1 -1
  25. package/dist/routes/agent-api-gateway.d.ts +2 -2
  26. package/dist/routes/agent-api-gateway.d.ts.map +1 -1
  27. package/dist/routes/agents.d.ts +130 -131
  28. package/dist/routes/agents.d.ts.map +1 -1
  29. package/dist/routes/auth.d.ts +84 -84
  30. package/dist/routes/auth.d.ts.map +1 -1
  31. package/dist/routes/connector-connection-runs.d.ts +794 -0
  32. package/dist/routes/connector-connection-runs.d.ts.map +1 -0
  33. package/dist/routes/connector-connections.d.ts +219 -0
  34. package/dist/routes/connector-connections.d.ts.map +1 -0
  35. package/dist/routes/connectors.d.ts +10 -4
  36. package/dist/routes/connectors.d.ts.map +1 -1
  37. package/dist/routes/datasets.d.ts +8 -4
  38. package/dist/routes/datasets.d.ts.map +1 -1
  39. package/dist/routes/events.d.ts +8 -8
  40. package/dist/routes/events.d.ts.map +1 -1
  41. package/dist/routes/files.d.ts +11 -10
  42. package/dist/routes/files.d.ts.map +1 -1
  43. package/dist/routes/links.d.ts +2 -2
  44. package/dist/routes/links.d.ts.map +1 -1
  45. package/dist/routes/logs.d.ts +5 -5
  46. package/dist/routes/logs.d.ts.map +1 -1
  47. package/dist/routes/objects.d.ts +34 -34
  48. package/dist/routes/objects.d.ts.map +1 -1
  49. package/dist/routes/ontology.d.ts +50 -50
  50. package/dist/routes/ontology.d.ts.map +1 -1
  51. package/dist/routes/pipelines.d.ts +24 -34
  52. package/dist/routes/pipelines.d.ts.map +1 -1
  53. package/dist/routes/project.d.ts +2 -2
  54. package/dist/routes/project.d.ts.map +1 -1
  55. package/dist/routes/projections.d.ts +131 -83
  56. package/dist/routes/projections.d.ts.map +1 -1
  57. package/dist/routes/rules.d.ts +6 -6
  58. package/dist/routes/rules.d.ts.map +1 -1
  59. package/dist/routes/status.d.ts +2 -2
  60. package/dist/routes/status.d.ts.map +1 -1
  61. package/dist/routes/syncs.d.ts +20 -25
  62. package/dist/routes/syncs.d.ts.map +1 -1
  63. package/dist/routes/telemetry.d.ts +2 -2
  64. package/dist/routes/telemetry.d.ts.map +1 -1
  65. package/dist/routes/webhook-runs.d.ts +9 -9
  66. package/dist/routes/webhook-runs.d.ts.map +1 -1
  67. package/dist/routes/webhooks.d.ts +2 -2
  68. package/dist/routes/webhooks.d.ts.map +1 -1
  69. package/dist/routes/workflows.d.ts +74 -48
  70. package/dist/routes/workflows.d.ts.map +1 -1
  71. package/dist/routes/ws/agents.d.ts +11 -5
  72. package/dist/routes/ws/agents.d.ts.map +1 -1
  73. package/dist/routes/ws/events.d.ts +8 -8
  74. package/dist/routes/ws/events.d.ts.map +1 -1
  75. package/dist/routes/ws/log-subscription-hub.d.ts +6 -3
  76. package/dist/routes/ws/log-subscription-hub.d.ts.map +1 -1
  77. package/dist/routes/ws/logs.d.ts +10 -10
  78. package/dist/routes/ws/logs.d.ts.map +1 -1
  79. package/dist/schemas/actions.d.ts +97 -202
  80. package/dist/schemas/actions.d.ts.map +1 -1
  81. package/dist/schemas/agents.d.ts +442 -439
  82. package/dist/schemas/agents.d.ts.map +1 -1
  83. package/dist/schemas/ai-usage.d.ts +34 -0
  84. package/dist/schemas/ai-usage.d.ts.map +1 -0
  85. package/dist/schemas/auth.d.ts +142 -142
  86. package/dist/schemas/common.d.ts +37 -0
  87. package/dist/schemas/common.d.ts.map +1 -1
  88. package/dist/schemas/connectors.d.ts +713 -2
  89. package/dist/schemas/connectors.d.ts.map +1 -1
  90. package/dist/schemas/datasets.d.ts +2 -2
  91. package/dist/schemas/event-payloads.d.ts +6 -6
  92. package/dist/schemas/events.d.ts +34 -34
  93. package/dist/schemas/logs.d.ts +22 -22
  94. package/dist/schemas/objects.d.ts +10 -10
  95. package/dist/schemas/ontology.d.ts +118 -118
  96. package/dist/schemas/pipelines.d.ts +95 -190
  97. package/dist/schemas/pipelines.d.ts.map +1 -1
  98. package/dist/schemas/projections.d.ts +918 -563
  99. package/dist/schemas/projections.d.ts.map +1 -1
  100. package/dist/schemas/rules.d.ts +6 -6
  101. package/dist/schemas/status.d.ts +2 -2
  102. package/dist/schemas/syncs.d.ts +65 -108
  103. package/dist/schemas/syncs.d.ts.map +1 -1
  104. package/dist/schemas/webhook-runs.d.ts +41 -41
  105. package/dist/schemas/webhook-runs.d.ts.map +1 -1
  106. package/dist/schemas/workflows.d.ts +516 -183
  107. package/dist/schemas/workflows.d.ts.map +1 -1
  108. package/dist/server.d.ts +6 -6
  109. package/dist/server.d.ts.map +1 -1
  110. package/dist/utils/http.d.ts +2 -0
  111. package/dist/utils/http.d.ts.map +1 -1
  112. package/dist/utils/ws.d.ts +4 -3
  113. package/dist/utils/ws.d.ts.map +1 -1
  114. package/package.json +4 -4
  115. package/src/auth/access-token-boundary.ts +4 -4
  116. package/src/auth/application-access.ts +8 -9
  117. package/src/auth/connector-callback-cookie.ts +95 -0
  118. package/src/auth/guard.ts +11 -11
  119. package/src/auth/public-routes.ts +13 -0
  120. package/src/auth/scope.ts +26 -36
  121. package/src/auth/session-cookies.ts +3 -3
  122. package/src/connectors/http.ts +110 -0
  123. package/src/openapi/tags.ts +9 -1
  124. package/src/registerRoutes.ts +34 -23
  125. package/src/routes/action-runs.ts +39 -39
  126. package/src/routes/actions.ts +7 -13
  127. package/src/routes/agent-api-gateway.ts +41 -38
  128. package/src/routes/agents.ts +89 -200
  129. package/src/routes/auth.ts +87 -91
  130. package/src/routes/connector-connection-runs.ts +346 -0
  131. package/src/routes/connector-connections.ts +135 -0
  132. package/src/routes/connectors.ts +24 -12
  133. package/src/routes/datasets.ts +55 -54
  134. package/src/routes/events.ts +5 -5
  135. package/src/routes/files.ts +22 -30
  136. package/src/routes/links.ts +31 -35
  137. package/src/routes/logs.ts +6 -11
  138. package/src/routes/objects.ts +51 -114
  139. package/src/routes/ontology.ts +27 -38
  140. package/src/routes/pipelines.ts +28 -62
  141. package/src/routes/project.ts +3 -3
  142. package/src/routes/projections.ts +26 -38
  143. package/src/routes/rules.ts +11 -25
  144. package/src/routes/status.ts +5 -5
  145. package/src/routes/syncs.ts +19 -45
  146. package/src/routes/telemetry.ts +18 -29
  147. package/src/routes/webhook-runs.ts +5 -5
  148. package/src/routes/webhooks.ts +259 -341
  149. package/src/routes/workflows.ts +226 -248
  150. package/src/routes/ws/agents.ts +196 -66
  151. package/src/routes/ws/events.ts +11 -10
  152. package/src/routes/ws/log-subscription-hub.ts +6 -12
  153. package/src/routes/ws/logs.ts +13 -5
  154. package/src/schemas/actions.ts +58 -25
  155. package/src/schemas/agents.ts +19 -14
  156. package/src/schemas/ai-usage.ts +16 -0
  157. package/src/schemas/common.ts +24 -0
  158. package/src/schemas/connectors.ts +164 -0
  159. package/src/schemas/pipelines.ts +23 -15
  160. package/src/schemas/projections.ts +17 -3
  161. package/src/schemas/syncs.ts +13 -8
  162. package/src/schemas/webhook-runs.ts +10 -5
  163. package/src/schemas/workflows.ts +16 -6
  164. package/src/server.ts +65 -26
  165. package/src/utils/http.ts +34 -6
  166. package/src/utils/ws.ts +10 -5
@@ -1,22 +1,22 @@
1
- import { randomUUID } from "node:crypto"
1
+ import { createHash, randomUUID } from "node:crypto"
2
2
  import type {
3
3
  ConnectorAdapter,
4
4
  ConnectorClient,
5
- ConnectorDefinition,
6
5
  Logger,
7
- OntologySource,
8
6
  RegisteredWebhook,
9
- Sixb,
7
+ SixbFailure,
8
+ SixbHostView,
9
+ StaticConnectorDefinition,
10
10
  WebhookDefinition,
11
11
  WebhookMetadata,
12
12
  WebhookResponse,
13
13
  } from "@sixb/core"
14
14
  import { reportRunFailure } from "@sixb/core/internal/error-reporting"
15
- import type {
16
- FinishWebhookRunStatus,
17
- WebhookDeliveryClaimResult,
18
- WebhookDeliveryKey,
19
- } from "@sixb/core/storage"
15
+ import { captureSixbFailure, createSixbError, toSixbFailure } from "@sixb/core/internal/errors"
16
+ import { bindDurablePrimitiveExecution } from "@sixb/core/internal/primitive-execution"
17
+ import { type AdmitWebhookRunResult, admitWebhookRun } from "@sixb/core/internal/webhooks"
18
+ import type { WebhookRunFailureCode } from "@sixb/core/storage"
19
+ import { WEBHOOK_RUN_FAILURE_CODES, WebhookRunError } from "@sixb/core/storage"
20
20
  import type { Elysia } from "elysia"
21
21
  import { RequestBodyTooLargeError, readRequestBodyWithLimit } from "../utils/request-body"
22
22
 
@@ -28,372 +28,347 @@ interface ElysiaSet {
28
28
  }
29
29
 
30
30
  interface DispatchWebhookOptions {
31
- readonly sixb: Sixb<readonly OntologySource[]>
31
+ readonly host: SixbHostView
32
32
  readonly registered: RegisteredWebhook
33
33
  readonly request: Request
34
34
  readonly set: ElysiaSet
35
35
  readonly bodyLimitBytes?: number
36
36
  }
37
37
 
38
- interface WebhookRunFinishInput {
39
- readonly sixb: Sixb<readonly OntologySource[]>
40
- readonly runId: string
41
- readonly status: FinishWebhookRunStatus
42
- readonly requestBodyBytes?: number
43
- readonly responseStatus?: number
38
+ interface PreparedWebhookRequest {
39
+ readonly rawBody: Uint8Array
40
+ readonly body: unknown
41
+ readonly metadata: WebhookMetadata
44
42
  readonly idempotencyKey?: string
45
- readonly deliveryClaimResult?: WebhookDeliveryClaimResult
46
- readonly error?: string
47
43
  }
48
44
 
49
- type DeliveryClaimResult =
45
+ type PreparedWebhookResult =
46
+ | { readonly status: "ready"; readonly request: PreparedWebhookRequest }
47
+ | { readonly status: "responded"; readonly response: unknown }
48
+
49
+ type WebhookAdmissionResult =
50
+ | AdmitWebhookRunResult
51
+ | { readonly status: "responded"; readonly response: unknown }
52
+
53
+ type WebhookRunFailure = SixbFailure<WebhookRunFailureCode>
54
+
55
+ type FinishWebhookRunInput =
50
56
  | {
51
- readonly status: "run"
52
- readonly key: WebhookDeliveryKey | null
53
- readonly idempotencyKey?: string
54
- readonly claimResult?: WebhookDeliveryClaimResult
57
+ readonly runId: string
58
+ readonly status: "succeeded"
59
+ readonly responseStatus: number
55
60
  }
56
61
  | {
57
- readonly status: "skip"
58
- readonly idempotencyKey: string
59
- readonly claimResult: WebhookDeliveryClaimResult
62
+ readonly runId: string
63
+ readonly status: "failed"
64
+ readonly responseStatus: number
65
+ readonly failure: WebhookRunFailure
60
66
  }
61
67
 
62
- export function registerWebhookRoutes(app: Elysia, sixb: Sixb<readonly OntologySource[]>) {
68
+ export function registerWebhookRoutes(app: Elysia, host: SixbHostView) {
63
69
  return app.all(
64
70
  "/api/webhooks/:connectorId/:webhookId",
65
71
  async ({ params, request, set }) => {
66
- const registered = sixb.getWebhookById(params.connectorId, params.webhookId)
67
-
72
+ const registered = host.getWebhookById(params.connectorId, params.webhookId)
68
73
  if (!registered) {
69
74
  set.status = 404
70
75
  return { error: "Webhook not found" }
71
76
  }
72
-
73
- return dispatchWebhook({ sixb, registered, request, set })
77
+ return dispatchWebhook({ host, registered, request, set })
74
78
  },
75
- {
76
- detail: {
77
- hide: true,
78
- },
79
- }
79
+ { detail: { hide: true } }
80
80
  )
81
81
  }
82
82
 
83
83
  async function dispatchWebhook(options: DispatchWebhookOptions): Promise<unknown> {
84
- const runId = `webhookrun_${randomUUID()}`
85
- const { sixb, registered } = options
86
- const logSession = sixb.logs.startExecution({ kind: "webhook", id: runId })
87
- let failureReported = false
88
- const reportFailure = (error: unknown) => {
89
- if (failureReported) return
90
-
91
- failureReported = true
92
- reportRunFailure(sixb, error, {
93
- projectId: sixb.id,
94
- run: {
95
- kind: "webhook",
96
- runId,
97
- connectorId: registered.connector.id,
98
- webhookId: registered.webhook.id,
99
- },
100
- })
101
- }
84
+ const candidateRunId = `webhookrun_${randomUUID()}`
85
+ const prepared = await prepareWebhookRequest(options)
86
+ if (prepared.status === "responded") return prepared.response
102
87
 
103
- await startWebhookRun(sixb, registered, options.request, runId)
88
+ const admission = await admitPreparedWebhook(options, candidateRunId, prepared.request)
89
+ if (admission.status === "responded") return admission.response
90
+ if (admission.status !== "admitted") return accepted(options.set)
104
91
 
92
+ const executionLogs = options.host.logging.startExecution({
93
+ kind: "webhook",
94
+ id: admission.run.id,
95
+ })
105
96
  try {
106
- return await dispatchWebhookRun(
97
+ return await executeWebhookHandler(
107
98
  options,
108
- runId,
109
- (phase) => logSession.withContext({ phase }),
110
- reportFailure
99
+ prepared.request,
100
+ admission,
101
+ executionLogs.withContext({ phase: "handle" })
111
102
  )
112
- } catch (error) {
113
- await finishWebhookRun({
114
- sixb,
115
- runId,
116
- status: "failed",
117
- responseStatus: 500,
118
- error: error instanceof Error ? error.message : String(error),
119
- })
120
- reportFailure(error)
121
- throw error
122
103
  } finally {
123
- await logSession.flush()
104
+ await executionLogs.flush()
124
105
  }
125
106
  }
126
107
 
127
- async function dispatchWebhookRun(
128
- options: DispatchWebhookOptions,
129
- runId: string,
130
- loggerForPhase: (phase: string) => Logger,
131
- reportFailure: (error: unknown) => void
132
- ): Promise<unknown> {
133
- const { sixb, registered, request, set } = options
134
- const { connector, webhook, route } = registered
135
- const requestMethod = request.method.toUpperCase()
136
-
108
+ async function prepareWebhookRequest(
109
+ options: DispatchWebhookOptions
110
+ ): Promise<PreparedWebhookResult> {
111
+ const { connector, webhook, route } = options.registered
112
+ const requestMethod = options.request.method.toUpperCase()
137
113
  if (requestMethod !== webhook.method) {
138
- set.status = 405
139
- setHeader(set, "allow", webhook.method)
140
- await finishWebhookRun({
141
- sixb,
142
- runId,
143
- status: "failed",
144
- responseStatus: 405,
145
- error: "Method not allowed",
146
- })
147
- return { error: "Method not allowed" }
114
+ options.set.status = 405
115
+ setHeader(options.set, "allow", webhook.method)
116
+ return { status: "responded", response: { error: "Method not allowed" } }
148
117
  }
149
118
 
150
119
  let rawBody: Uint8Array
151
120
  try {
152
- rawBody = await readRawBody(request, options.bodyLimitBytes ?? DEFAULT_WEBHOOK_BODY_LIMIT_BYTES)
121
+ rawBody = await readRequestBodyWithLimit(
122
+ options.request,
123
+ options.bodyLimitBytes ?? DEFAULT_WEBHOOK_BODY_LIMIT_BYTES,
124
+ `Webhook body exceeds ${options.bodyLimitBytes ?? DEFAULT_WEBHOOK_BODY_LIMIT_BYTES} bytes.`
125
+ )
153
126
  } catch (error) {
154
127
  const responseStatus = error instanceof RequestBodyTooLargeError ? 413 : 400
155
- const message = error instanceof Error ? error.message : String(error)
156
- set.status = responseStatus
157
- await finishWebhookRun({
158
- sixb,
159
- runId,
160
- status: "failed",
161
- responseStatus,
162
- error: message,
163
- })
164
- return { error: message }
128
+ options.set.status = responseStatus
129
+ return {
130
+ status: "responded",
131
+ response: { error: error instanceof Error ? error.message : String(error) },
132
+ }
165
133
  }
166
134
 
167
135
  const metadata = toWebhookMetadata(webhook, route)
168
136
  const baseContext = {
169
- sixb,
170
137
  connector,
171
138
  webhook: metadata,
172
- request,
139
+ request: options.request,
173
140
  rawBody,
174
141
  }
175
- const verifyContext = {
176
- ...baseContext,
177
- logger: loggerForPhase("verify"),
178
- }
179
-
180
142
  try {
181
- await webhook.verify?.(verifyContext)
143
+ await webhook.verify?.(baseContext)
182
144
  } catch {
183
- set.status = 401
184
- await finishWebhookRun({
185
- sixb,
186
- runId,
187
- status: "failed",
188
- requestBodyBytes: rawBody.byteLength,
189
- responseStatus: 401,
190
- error: "Webhook verification failed",
191
- })
192
- return { error: "Webhook verification failed" }
145
+ options.set.status = 401
146
+ return { status: "responded", response: { error: "Webhook verification failed" } }
193
147
  }
194
148
 
195
149
  let body: unknown
196
150
  try {
197
151
  body = parseWebhookBody(webhook, rawBody)
198
152
  } catch (error) {
199
- const message = error instanceof Error ? error.message : String(error)
200
- set.status = 400
201
- await finishWebhookRun({
202
- sixb,
203
- runId,
204
- status: "failed",
205
- requestBodyBytes: rawBody.byteLength,
206
- responseStatus: 400,
207
- error: message,
208
- })
209
- return { error: message }
153
+ options.set.status = 400
154
+ return {
155
+ status: "responded",
156
+ response: { error: error instanceof Error ? error.message : String(error) },
157
+ }
210
158
  }
211
159
 
212
- const handlerContext = {
213
- ...baseContext,
214
- logger: loggerForPhase("handle"),
215
- body,
216
- client: createClientResolver(sixb, connector),
217
- }
218
- const idempotencyContext = {
219
- ...handlerContext,
220
- logger: loggerForPhase("idempotency"),
160
+ try {
161
+ const idempotencyKey = await webhook.idempotencyKey?.({
162
+ ...baseContext,
163
+ body,
164
+ })
165
+ return {
166
+ status: "ready",
167
+ request: {
168
+ rawBody,
169
+ body,
170
+ metadata,
171
+ ...(idempotencyKey === null || idempotencyKey === undefined ? {} : { idempotencyKey }),
172
+ },
173
+ }
174
+ } catch {
175
+ options.set.status = 500
176
+ return { status: "responded", response: { error: "Webhook admission failed" } }
221
177
  }
178
+ }
222
179
 
223
- // Claim before running the handler so duplicate and concurrent provider
224
- // retries can be acknowledged without repeating side effects.
225
- let deliveryKey: WebhookDeliveryKey | null = null
226
- let idempotencyKey: string | undefined
227
- let deliveryClaimResult: WebhookDeliveryClaimResult | undefined
180
+ async function admitPreparedWebhook(
181
+ options: DispatchWebhookOptions,
182
+ runId: string,
183
+ prepared: PreparedWebhookRequest
184
+ ): Promise<WebhookAdmissionResult> {
228
185
  try {
229
- const claim = await claimDeliveryKey(sixb, webhook, idempotencyContext)
230
- idempotencyKey = claim.idempotencyKey
231
- deliveryClaimResult = claim.claimResult
232
- if (claim.status === "skip") {
233
- const result = accepted(set)
234
- await finishWebhookRun({
235
- sixb,
236
- runId,
237
- status: "skipped",
238
- requestBodyBytes: rawBody.byteLength,
239
- responseStatus: 202,
240
- idempotencyKey: claim.idempotencyKey,
241
- deliveryClaimResult: claim.claimResult,
242
- })
243
- return result
244
- }
245
- deliveryKey = claim.key
246
- } catch (error) {
247
- reportFailure(error)
248
- set.status = 500
249
- await finishWebhookRun({
250
- sixb,
186
+ return await admitWebhookRun({
187
+ projectId: options.host.id,
188
+ storage: options.host.storage,
251
189
  runId,
252
- status: "failed",
253
- requestBodyBytes: rawBody.byteLength,
254
- responseStatus: 500,
255
- error: "Webhook delivery claim failed",
190
+ connectorId: options.registered.connector.id,
191
+ webhookId: options.registered.webhook.id,
192
+ method: options.request.method.toUpperCase(),
193
+ route: options.registered.route,
194
+ requestBodyBytes: prepared.rawBody.byteLength,
195
+ requestBodySha256: createHash("sha256").update(prepared.rawBody).digest("hex"),
196
+ idempotencyKey: prepared.idempotencyKey,
256
197
  })
257
- return { error: "Webhook delivery claim failed" }
198
+ } catch (error) {
199
+ if (error instanceof WebhookRunError && error.code === "delivery_conflict") {
200
+ options.set.status = 409
201
+ return { status: "responded", response: { error: "Webhook delivery conflict" } }
202
+ }
203
+ options.set.status = 500
204
+ return { status: "responded", response: { error: "Webhook admission failed" } }
258
205
  }
206
+ }
207
+
208
+ async function executeWebhookHandler(
209
+ options: DispatchWebhookOptions,
210
+ prepared: PreparedWebhookRequest,
211
+ admission: Extract<AdmitWebhookRunResult, { readonly status: "admitted" }>,
212
+ logger: Logger
213
+ ): Promise<unknown> {
214
+ const { host, registered, request, set } = options
215
+ const { connector, webhook } = registered
216
+ const runId = admission.run.id
217
+ const reportFailure = createFailureReporter(host, registered, runId)
259
218
 
260
219
  let response: unknown
261
220
  try {
262
- response = await webhook.handle(handlerContext as never)
221
+ const execution = bindDurablePrimitiveExecution(host, {
222
+ execution: admission.execution,
223
+ primitive: { kind: "webhook", id: registered.route, runId },
224
+ })
225
+ response = await webhook.handle({
226
+ sixb: execution.sixb,
227
+ connector,
228
+ webhook: prepared.metadata,
229
+ request,
230
+ rawBody: prepared.rawBody,
231
+ body: prepared.body,
232
+ logger,
233
+ client: createClientResolver(execution.sixb, connector),
234
+ })
263
235
  } catch (error) {
264
- reportFailure(error)
265
- // Handler failures mark the key failed so the provider's next retry can
266
- // attempt the delivery again.
267
- if (deliveryKey) {
268
- await sixb.storage.webhookDeliveries?.fail({
269
- ...deliveryKey,
270
- failedAt: new Date().toISOString(),
271
- error: error instanceof Error ? error.message : String(error),
272
- })
273
- }
274
-
275
- set.status = 500
276
- await finishWebhookRun({
277
- sixb,
236
+ const failed = createWebhookRunFailure({
237
+ registered,
278
238
  runId,
279
- status: "failed",
280
- requestBodyBytes: rawBody.byteLength,
239
+ idempotencyKey: prepared.idempotencyKey,
281
240
  responseStatus: 500,
282
- idempotencyKey,
283
- deliveryClaimResult,
284
- error: "Webhook handler failed",
241
+ message: "Webhook handler failed",
242
+ cause: error,
285
243
  })
244
+ reportFailure(failed.error, failed.failure)
245
+ try {
246
+ await finishWebhookRun(host, {
247
+ runId,
248
+ status: "failed",
249
+ responseStatus: 500,
250
+ failure: failed.failure,
251
+ })
252
+ } catch (_finalizationError) {
253
+ // The original failure remains the actionable cause. A terminal write failure leaves the
254
+ // durable run visibly running instead of pretending that its outcome was recorded.
255
+ }
256
+ set.status = 500
286
257
  return { error: "Webhook handler failed" }
287
258
  }
288
259
 
289
260
  const responseStatus = getWebhookResponseStatus(response)
290
- const runStatus = responseStatus >= 200 && responseStatus <= 299 ? "succeeded" : "failed"
291
- const failureMessage = `Webhook handler returned HTTP ${responseStatus}`
292
- const responseError = runStatus === "failed" ? failureMessage : undefined
293
- const shouldRetryDelivery =
294
- runStatus === "failed" && (responseStatus < 400 || responseStatus >= 500)
295
-
261
+ const succeeded = responseStatus >= 200 && responseStatus <= 299
262
+ const failed = succeeded
263
+ ? undefined
264
+ : createWebhookRunFailure({
265
+ registered,
266
+ runId,
267
+ idempotencyKey: prepared.idempotencyKey,
268
+ responseStatus,
269
+ message: `Webhook handler returned HTTP ${responseStatus}`,
270
+ })
296
271
  try {
297
- if (deliveryKey) {
298
- const finalizedAt = new Date().toISOString()
299
- if (shouldRetryDelivery) {
300
- await sixb.storage.webhookDeliveries?.fail({
301
- ...deliveryKey,
302
- failedAt: finalizedAt,
303
- error: failureMessage,
304
- })
305
- } else {
306
- await sixb.storage.webhookDeliveries?.complete({
307
- ...deliveryKey,
308
- completedAt: finalizedAt,
309
- })
310
- }
311
- }
272
+ await finishWebhookRun(
273
+ host,
274
+ failed
275
+ ? { runId, status: "failed", responseStatus, failure: failed.failure }
276
+ : { runId, status: "succeeded", responseStatus }
277
+ )
312
278
  } catch (error) {
313
- reportFailure(error)
314
- set.status = 500
315
- await finishWebhookRun({
316
- sixb,
317
- runId,
318
- status: "failed",
319
- requestBodyBytes: rawBody.byteLength,
320
- responseStatus: 500,
321
- idempotencyKey,
322
- deliveryClaimResult,
323
- error: "Webhook delivery completion failed",
279
+ const failure = captureSixbFailure(error, {
280
+ allowedCodes: WEBHOOK_RUN_FAILURE_CODES,
281
+ defaultCode: "internal.unexpected",
282
+ details: {
283
+ connectorId: registered.connector.id,
284
+ webhookId: registered.webhook.id,
285
+ runId,
286
+ phase: "finalize",
287
+ },
324
288
  })
325
- return { error: "Webhook delivery completion failed" }
289
+ reportFailure(error, failure)
290
+ set.status = 500
291
+ return { error: "Webhook run finalization failed" }
326
292
  }
327
-
328
- if (shouldRetryDelivery) {
329
- reportFailure(new Error(failureMessage))
293
+ if (failed?.failure.retryable) {
294
+ reportFailure(failed.error, failed.failure)
330
295
  }
331
- await finishWebhookRun({
332
- sixb,
333
- runId,
334
- status: runStatus,
335
- requestBodyBytes: rawBody.byteLength,
336
- responseStatus,
337
- idempotencyKey,
338
- deliveryClaimResult,
339
- error: responseError,
340
- })
341
-
342
296
  return applyWebhookResponse(set, response)
343
297
  }
344
298
 
345
- async function startWebhookRun(
346
- sixb: Sixb<readonly OntologySource[]>,
299
+ function createFailureReporter(
300
+ host: SixbHostView,
347
301
  registered: RegisteredWebhook,
348
- request: Request,
349
302
  runId: string
350
- ): Promise<void> {
351
- const storage = sixb.storage.webhookRuns
352
- if (!storage) {
353
- return
354
- }
355
-
356
- try {
357
- await storage.start({
358
- id: runId,
359
- projectId: sixb.id,
360
- connectorId: registered.connector.id,
361
- webhookId: registered.webhook.id,
362
- method: request.method.toUpperCase(),
363
- route: registered.route,
303
+ ): (error: unknown, failure: WebhookRunFailure) => void {
304
+ let reported = false
305
+ return (error, failure) => {
306
+ if (reported) return
307
+ reported = true
308
+ reportRunFailure(host, error, {
309
+ projectId: host.id,
310
+ runKind: "webhook",
311
+ run: {
312
+ runId,
313
+ connectorId: registered.connector.id,
314
+ webhookId: registered.webhook.id,
315
+ },
316
+ failure,
364
317
  })
365
- } catch {
366
- // Webhook run history is observability-only. Logging and dispatch continue
367
- // even when history storage is unavailable or temporarily failing.
368
318
  }
369
319
  }
370
320
 
371
- async function finishWebhookRun(input: WebhookRunFinishInput): Promise<void> {
372
- const storage = input.sixb.storage.webhookRuns
321
+ async function finishWebhookRun(host: SixbHostView, input: FinishWebhookRunInput): Promise<void> {
322
+ const storage = host.storage.webhookRuns
373
323
  if (!storage) {
374
- return
324
+ throw createSixbError(
325
+ "internal.unexpected",
326
+ "[SixbServer] Webhook run storage is not configured."
327
+ )
375
328
  }
376
-
377
- try {
378
- await storage.finish({
379
- id: input.runId,
380
- projectId: input.sixb.id,
381
- status: input.status,
382
- finishedAt: new Date(),
383
- requestBodyBytes: input.requestBodyBytes,
384
- responseStatus: input.responseStatus,
385
- idempotencyKey: input.idempotencyKey,
386
- deliveryClaimResult: input.deliveryClaimResult,
387
- error: input.error,
388
- })
389
- } catch {
390
- // Webhook run history is observability-only. Do not change provider responses
391
- // when history storage is unavailable or temporarily failing.
329
+ const terminal = {
330
+ id: input.runId,
331
+ projectId: host.id,
332
+ responseStatus: input.responseStatus,
392
333
  }
334
+ await storage.finish(
335
+ input.status === "failed"
336
+ ? {
337
+ ...terminal,
338
+ status: "failed",
339
+ finishedAt: new Date(input.failure.at),
340
+ error: input.failure,
341
+ }
342
+ : { ...terminal, status: "succeeded", finishedAt: new Date() }
343
+ )
393
344
  }
394
345
 
395
- function readRawBody(request: Request, limitBytes: number): Promise<Uint8Array> {
396
- return readRequestBodyWithLimit(request, limitBytes, `Webhook body exceeds ${limitBytes} bytes.`)
346
+ function createWebhookRunFailure(input: {
347
+ readonly registered: RegisteredWebhook
348
+ readonly runId: string
349
+ readonly idempotencyKey?: string
350
+ readonly responseStatus: number
351
+ readonly message: string
352
+ readonly cause?: unknown
353
+ }): { readonly error: Error; readonly failure: WebhookRunFailure } {
354
+ const code =
355
+ input.responseStatus < 400 || input.responseStatus >= 500
356
+ ? "webhook.delivery_failed"
357
+ : "webhook.delivery_rejected"
358
+ const error = createSixbError(code, input.message, {
359
+ ...(input.cause === undefined ? {} : { cause: input.cause }),
360
+ details: {
361
+ connectorId: input.registered.connector.id,
362
+ webhookId: input.registered.webhook.id,
363
+ runId: input.runId,
364
+ responseStatus: input.responseStatus,
365
+ ...(input.idempotencyKey === undefined ? {} : { idempotencyKey: input.idempotencyKey }),
366
+ },
367
+ })
368
+ return {
369
+ error,
370
+ failure: toSixbFailure(error, { allowedCodes: WEBHOOK_RUN_FAILURE_CODES }),
371
+ }
397
372
  }
398
373
 
399
374
  function parseWebhookBody(webhook: WebhookDefinition, rawBody: Uint8Array): unknown {
@@ -403,91 +378,35 @@ function parseWebhookBody(webhook: WebhookDefinition, rawBody: Uint8Array): unkn
403
378
  : webhook.body.format === "text"
404
379
  ? new TextDecoder().decode(rawBody)
405
380
  : JSON.parse(new TextDecoder().decode(rawBody))
406
-
407
381
  return webhook.body.parse(decoded)
408
382
  }
409
383
 
410
- async function claimDeliveryKey(
411
- sixb: Sixb<readonly OntologySource[]>,
412
- webhook: WebhookDefinition,
413
- context: Parameters<NonNullable<WebhookDefinition["idempotencyKey"]>>[0]
414
- ): Promise<DeliveryClaimResult> {
415
- if (!webhook.idempotencyKey) {
416
- return { status: "run", key: null }
417
- }
418
-
419
- const idempotencyKey = await webhook.idempotencyKey(context)
420
- if (idempotencyKey === null || idempotencyKey === undefined) {
421
- return { status: "run", key: null }
422
- }
423
-
424
- const storage = sixb.storage.webhookDeliveries
425
- if (!storage) {
426
- throw new Error("Webhook delivery storage is not configured.")
427
- }
428
-
429
- const deliveryKey = {
430
- projectId: sixb.id,
431
- connectorId: context.connector.id,
432
- webhookId: webhook.id,
433
- idempotencyKey,
434
- }
435
-
436
- const result = await storage.claim({
437
- ...deliveryKey,
438
- receivedAt: new Date().toISOString(),
439
- })
440
-
441
- if (result.claimResult === "duplicate" || result.claimResult === "in_progress") {
442
- return { status: "skip", idempotencyKey, claimResult: result.claimResult }
443
- }
444
-
445
- if (result.claimResult !== "claimed") {
446
- throw new Error(`Unknown webhook delivery claim result: ${result.claimResult}`)
447
- }
448
-
449
- return { status: "run", key: deliveryKey, idempotencyKey, claimResult: result.claimResult }
450
- }
451
-
452
384
  function createClientResolver(
453
- sixb: Sixb<readonly OntologySource[]>,
454
- connector: ConnectorDefinition
385
+ sixb: ReturnType<typeof bindDurablePrimitiveExecution>["sixb"],
386
+ connector: StaticConnectorDefinition
455
387
  ): () => Promise<ConnectorClient<ConnectorAdapter>> {
456
388
  let clientPromise: Promise<ConnectorClient<ConnectorAdapter>> | null = null
457
-
458
389
  return () => {
459
- // Avoid connecting inbound-only handlers or handlers that never need the
460
- // outbound client, while still reusing one connection within the request.
461
390
  clientPromise ??= sixb.connector(connector)
462
391
  return clientPromise
463
392
  }
464
393
  }
465
394
 
466
395
  function toWebhookMetadata(webhook: WebhookDefinition, route: string): WebhookMetadata {
467
- return {
468
- id: webhook.id,
469
- method: webhook.method,
470
- route,
471
- bodyFormat: webhook.body.format,
472
- }
396
+ return { id: webhook.id, method: webhook.method, route, bodyFormat: webhook.body.format }
473
397
  }
474
398
 
475
399
  function applyWebhookResponse(set: ElysiaSet, response: unknown): unknown {
476
400
  const webhookResponse = isWebhookResponse(response) ? response : undefined
477
401
  set.status = getWebhookResponseStatus(response)
478
-
479
402
  if (webhookResponse?.headers) {
480
- for (const [key, value] of new Headers(webhookResponse.headers)) {
481
- setHeader(set, key, value)
482
- }
403
+ for (const [key, value] of new Headers(webhookResponse.headers)) setHeader(set, key, value)
483
404
  }
484
-
485
405
  return webhookResponse?.body
486
406
  }
487
407
 
488
408
  function getWebhookResponseStatus(response: unknown): number {
489
- const webhookResponse = isWebhookResponse(response) ? response : undefined
490
- return webhookResponse?.status ?? 202
409
+ return isWebhookResponse(response) ? (response.status ?? 202) : 202
491
410
  }
492
411
 
493
412
  function accepted(set: ElysiaSet): undefined {
@@ -499,7 +418,6 @@ function setHeader(set: ElysiaSet, key: string, value: string): void {
499
418
  if (!set.headers || typeof set.headers !== "object" || Array.isArray(set.headers)) {
500
419
  set.headers = {}
501
420
  }
502
-
503
421
  ;(set.headers as Record<string, string>)[key] = value
504
422
  }
505
423