@sssb/kit 0.0.0 → 0.3.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/LICENSE +21 -0
- package/dist/core/webhook-hmac.d.ts +69 -0
- package/dist/release.json +1 -0
- package/dist/testing/e2e.d.ts +15 -0
- package/dist/testing/e2e.js +195 -0
- package/package.json +212 -5
- package/src/adapters/README.md +6 -0
- package/src/adapters/dev-server.ts +21 -0
- package/src/adapters/fake/agreements.ts +81 -0
- package/src/adapters/fake/analytics.ts +93 -0
- package/src/adapters/fake/atomic-write.ts +161 -0
- package/src/adapters/fake/audit.ts +58 -0
- package/src/adapters/fake/auth.ts +313 -0
- package/src/adapters/fake/clock.ts +54 -0
- package/src/adapters/fake/data-dir.ts +27 -0
- package/src/adapters/fake/db.ts +88 -0
- package/src/adapters/fake/email.ts +46 -0
- package/src/adapters/fake/jobs.ts +248 -0
- package/src/adapters/fake/llm.ts +230 -0
- package/src/adapters/fake/pglite-dialect.ts +124 -0
- package/src/adapters/fake/service-auth.ts +145 -0
- package/src/adapters/fake/simulator-admin.ts +203 -0
- package/src/adapters/fake/simulator.ts +93 -0
- package/src/adapters/fake/sms.ts +43 -0
- package/src/adapters/fake/storage.ts +288 -0
- package/src/adapters/fake/webhooks.ts +98 -0
- package/src/adapters/index.ts +142 -0
- package/src/adapters/lazy-jobs.ts +25 -0
- package/src/adapters/proxy.ts +34 -0
- package/src/adapters/real/absent.ts +41 -0
- package/src/adapters/real/accept-invite-form.tsx +77 -0
- package/src/adapters/real/analytics.ts +28 -0
- package/src/adapters/real/auth.ts +216 -0
- package/src/adapters/real/clerk-proxy.ts +111 -0
- package/src/adapters/real/contract-data-api.ts +104 -0
- package/src/adapters/real/contract-postgres.ts +167 -0
- package/src/adapters/real/database-transport.ts +34 -0
- package/src/adapters/real/db-data-api.ts +61 -0
- package/src/adapters/real/db-port.ts +26 -0
- package/src/adapters/real/db.ts +69 -0
- package/src/adapters/real/email.ts +22 -0
- package/src/adapters/real/index.ts +139 -0
- package/src/adapters/real/jobs-in-process.ts +118 -0
- package/src/adapters/real/jobs.ts +33 -0
- package/src/adapters/real/llm.ts +108 -0
- package/src/adapters/real/migrate-handler.ts +66 -0
- package/src/adapters/real/optional-ports.ts +78 -0
- package/src/adapters/real/providers.tsx +12 -0
- package/src/adapters/real/rds-data-codec.ts +508 -0
- package/src/adapters/real/rds-data-dialect.ts +470 -0
- package/src/adapters/real/rds-data-emulator.ts +351 -0
- package/src/adapters/real/s3-storage.ts +233 -0
- package/src/adapters/real/sign-in-form.tsx +59 -0
- package/src/adapters/real/storage.ts +10 -0
- package/src/adapters/run-mode.ts +11 -0
- package/src/adapters/sentry/baseline.ts +90 -0
- package/src/adapters/sentry/client.ts +17 -0
- package/src/adapters/sentry/init.ts +17 -0
- package/src/authz/app-exemptions.ts +226 -0
- package/src/authz/authorize.ts +214 -0
- package/src/authz/route-policy.ts +153 -0
- package/src/authz/route-scan.ts +1516 -0
- package/src/components/agreements/acceptances-section.tsx +55 -0
- package/src/components/agreements/agreement-advisory-banner.tsx +33 -0
- package/src/components/agreements/agreement-body.tsx +34 -0
- package/src/components/agreements/agreement-gate.tsx +45 -0
- package/src/components/app-header.tsx +45 -0
- package/src/components/auth/accept-invite-screen.tsx +126 -0
- package/src/components/auth/auth-icons.tsx +68 -0
- package/src/components/auth/org-switcher.tsx +76 -0
- package/src/components/auth/people-picker.tsx +50 -0
- package/src/components/auth/preview-row.tsx +64 -0
- package/src/components/auth/sign-in-screen.tsx +24 -0
- package/src/components/auth/user-menu.tsx +64 -0
- package/src/components/demo-badge.tsx +20 -0
- package/src/components/demo-banner.tsx +14 -0
- package/src/components/gates/gate-interstitial.tsx +23 -0
- package/src/components/job-timeline.tsx +64 -0
- package/src/components/notifications/notification-bell.tsx +120 -0
- package/src/components/notifications/notification-prefs-section.tsx +112 -0
- package/src/components/org-screen.tsx +197 -0
- package/src/components/profile-screen.tsx +100 -0
- package/src/components/simulator/actor-runtime.ts +180 -0
- package/src/components/simulator/actor-shell.tsx +275 -0
- package/src/components/simulator/actors-app.tsx +119 -0
- package/src/components/simulator/errors-app.tsx +84 -0
- package/src/components/simulator/events-app.tsx +210 -0
- package/src/components/simulator/format-when.ts +20 -0
- package/src/components/simulator/hooks-app.tsx +319 -0
- package/src/components/simulator/inbound-app.tsx +210 -0
- package/src/components/simulator/jobs-app.tsx +471 -0
- package/src/components/simulator/mail-app.tsx +290 -0
- package/src/components/simulator/messages-app.tsx +64 -0
- package/src/components/simulator/people-app.tsx +140 -0
- package/src/components/simulator/people-dimensions.ts +16 -0
- package/src/components/simulator/simulator-host.tsx +335 -0
- package/src/components/simulator/simulator-panel.tsx +704 -0
- package/src/components/simulator/snapshots-app.tsx +398 -0
- package/src/components/simulator/tab-mount.ts +25 -0
- package/src/components/simulator/tours-app.tsx +105 -0
- package/src/components/webhook-endpoints-card.tsx +172 -0
- package/src/core/abilities.ts +464 -0
- package/src/core/agreements.ts +139 -0
- package/src/core/gates.ts +157 -0
- package/src/core/greeting.ts +11 -0
- package/src/core/inbound-email.ts +129 -0
- package/src/core/jobs.ts +51 -0
- package/src/core/keyset.ts +227 -0
- package/src/core/llm-models.ts +10 -0
- package/src/core/locale.ts +3 -0
- package/src/core/notifications.ts +182 -0
- package/src/core/presets.ts +456 -0
- package/src/core/roles.ts +47 -0
- package/src/core/same-origin-path.ts +20 -0
- package/src/core/schedules.ts +147 -0
- package/src/core/standard-schema.ts +56 -0
- package/src/core/state-machine.ts +43 -0
- package/src/core/webhook-events.ts +86 -0
- package/src/core/webhook-hmac.ts +248 -0
- package/src/core/webhook-signing.ts +27 -0
- package/src/cutover/rows.json +101 -0
- package/src/db/agreements.ts +176 -0
- package/src/db/app-roles.ts +197 -0
- package/src/db/audit.ts +356 -0
- package/src/db/inbound-email.ts +145 -0
- package/src/db/jobs.ts +300 -0
- package/src/db/jsonb.ts +18 -0
- package/src/db/keyset.ts +179 -0
- package/src/db/migrate.ts +73 -0
- package/src/db/migrations/0001_tenants.ts +25 -0
- package/src/db/migrations/0003_organizations.ts +27 -0
- package/src/db/migrations/0004_jobs.ts +64 -0
- package/src/db/migrations/0005_service_keys.ts +33 -0
- package/src/db/migrations/0008_audit_events.ts +51 -0
- package/src/db/migrations/0009_job_schedules.ts +52 -0
- package/src/db/migrations/0010_webhooks.ts +100 -0
- package/src/db/migrations/0011_notifications.ts +98 -0
- package/src/db/migrations/0012_inbound_email.ts +74 -0
- package/src/db/migrations/0013_agreements.ts +98 -0
- package/src/db/migrations/0014_audit_credential.ts +29 -0
- package/src/db/migrations/0015_app_user_grant.ts +67 -0
- package/src/db/migrations/0016_audit_detail.ts +26 -0
- package/src/db/migrations/index.ts +49 -0
- package/src/db/notifications.ts +185 -0
- package/src/db/org-lookup.ts +104 -0
- package/src/db/owner-pass.ts +252 -0
- package/src/db/rls-coverage.ts +259 -0
- package/src/db/rls-proof-runner.ts +94 -0
- package/src/db/rls-proofs.ts +1176 -0
- package/src/db/schedules.ts +187 -0
- package/src/db/schema.ts +235 -0
- package/src/db/seed.ts +176 -0
- package/src/db/service-keys.ts +50 -0
- package/src/db/tenant-lookup.ts +13 -0
- package/src/db/webhooks.ts +483 -0
- package/src/db/with-tenant.ts +26 -0
- package/src/demo-static/actor-drivers.ts +161 -0
- package/src/demo-static/assistant-replay.ts +61 -0
- package/src/demo-static/contracts.ts +282 -0
- package/src/demo-static/email-html.ts +58 -0
- package/src/demo-static/hash-route.ts +24 -0
- package/src/demo-static/rows.ts +105 -0
- package/src/demo-static/shell.tsx +440 -0
- package/src/demo-static/tour/contracts.ts +97 -0
- package/src/demo-static/tour/driver.ts +320 -0
- package/src/demo-static/tour/tour-overlay.tsx +226 -0
- package/src/demo-static/tour/use-tours.tsx +394 -0
- package/src/demo-static/world.ts +1480 -0
- package/src/email/send.ts +12 -0
- package/src/email/templates/digest-email.tsx +61 -0
- package/src/email/templates/invite-email.tsx +57 -0
- package/src/email/templates/notification-email.tsx +39 -0
- package/src/guide.md +132 -0
- package/src/i18n/messages/en.json +373 -0
- package/src/i18n/messages/es.json +373 -0
- package/src/i18n/messages.ts +34 -0
- package/src/i18n/namespaces.ts +32 -0
- package/src/i18n/request.ts +34 -0
- package/src/i18n/routing.ts +7 -0
- package/src/inbound-email/handlers.ts +67 -0
- package/src/inbound-email/intake.ts +180 -0
- package/src/jobs/digest-email.ts +112 -0
- package/src/jobs/run-in-process.ts +82 -0
- package/src/observability/scrub.ts +44 -0
- package/src/ports/README.md +8 -0
- package/src/ports/analytics.ts +8 -0
- package/src/ports/auth.ts +87 -0
- package/src/ports/db.ts +27 -0
- package/src/ports/email.ts +14 -0
- package/src/ports/errors.ts +46 -0
- package/src/ports/jobs.ts +69 -0
- package/src/ports/llm.ts +85 -0
- package/src/ports/storage.ts +132 -0
- package/src/seed/contracts.ts +129 -0
- package/src/server-lib/assistant.ts +45 -0
- package/src/server-lib/defer.ts +57 -0
- package/src/server-lib/demo-presets.ts +85 -0
- package/src/server-lib/invite.ts +92 -0
- package/src/server-lib/notify-deps.ts +15 -0
- package/src/server-lib/notify.ts +252 -0
- package/src/server-lib/preset-operations.ts +121 -0
- package/src/server-lib/scheduled-tick.ts +48 -0
- package/src/server-lib/simulator-api.ts +311 -0
- package/src/server-lib/sms.ts +43 -0
- package/src/server-lib/webhook-dispatch.ts +75 -0
- package/src/service-auth/credential.ts +20 -0
- package/src/service-auth/mailgun.ts +70 -0
- package/src/service-auth/verify.ts +80 -0
- package/src/service-auth/webhook.ts +69 -0
- package/src/testing/checks.json +103 -0
- package/src/testing/conformance/authz.ts +46 -0
- package/src/testing/conformance/db.ts +258 -0
- package/src/testing/conformance/demo-presets.ts +295 -0
- package/src/testing/conformance/i18n.ts +80 -0
- package/src/testing/conformance/register.ts +200 -0
- package/src/testing/conformance/seam-map.ts +205 -0
- package/src/testing/conformance/suite.ts +59 -0
- package/src/testing/conformance/types.ts +18 -0
- package/src/testing/contract.ts +200 -0
- package/src/testing/e2e.ts +15 -0
- package/src/testing/index.ts +6 -0
- package/src/testing/seam-specifiers.json +22 -0
- package/src/testing/tmp-dir-marker.d.mts +4 -0
- package/src/testing/tmp-dir-marker.mjs +5 -0
- package/src/testing/tmp-dir.ts +182 -0
- package/src/theme.ts +28 -0
- package/README.md +0 -3
|
@@ -0,0 +1,483 @@
|
|
|
1
|
+
import {
|
|
2
|
+
type WebhookEnvelope,
|
|
3
|
+
type WebhookEventKind,
|
|
4
|
+
type WebhookEventPayload,
|
|
5
|
+
backoffDelayMs,
|
|
6
|
+
isDeliveryDead,
|
|
7
|
+
} from '../core/webhook-events'
|
|
8
|
+
import {
|
|
9
|
+
WEBHOOK_DELIVERY_HEADER,
|
|
10
|
+
WEBHOOK_EVENT_HEADER,
|
|
11
|
+
WEBHOOK_SIGNATURE_HEADER,
|
|
12
|
+
webhookSignatureHeader,
|
|
13
|
+
} from '../core/webhook-signing'
|
|
14
|
+
import type { DbPort } from '../ports/db'
|
|
15
|
+
// TYPE-ONLY import (erased): keeps packages/kit/src/db free of a runtime @/adapters dependency — see WebhookDispatch.
|
|
16
|
+
import type { WebhookDispatch } from '../server-lib/webhook-dispatch'
|
|
17
|
+
import { recordAuditEvent } from './audit'
|
|
18
|
+
import { jsonb } from './jsonb'
|
|
19
|
+
|
|
20
|
+
/** timestamptz comes back from both engines as a Date; local (avoids a jobs.ts import cycle since
|
|
21
|
+
* jobs.ts imports enqueueWebhookEvent from here). */
|
|
22
|
+
function iso(value: unknown): string {
|
|
23
|
+
return value instanceof Date ? value.toISOString() : String(value)
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
// ---------------------------------------------------------------------------
|
|
27
|
+
// Emission — cheap: enqueue a delivery row per matching enabled endpoint. NO dispatch here; the drain
|
|
28
|
+
// (runDueDeliveries) does the network effect on the next tick. Called from the existing mutation
|
|
29
|
+
// choke points (recordJobStatus, the app's own mutation routes) after their own write commits.
|
|
30
|
+
// ---------------------------------------------------------------------------
|
|
31
|
+
|
|
32
|
+
/**
|
|
33
|
+
* Fan an event out to durable delivery rows: one per enabled endpoint in `orgId` subscribed to `kind`.
|
|
34
|
+
* Endpoints are few per org, so the subscription filter is a JS `.includes` over the parsed
|
|
35
|
+
* `event_kinds` array rather than a jsonb-operator predicate (portable across pglite/pg without the
|
|
36
|
+
* `?`/`@>` operator-vs-placeholder ambiguity). `next_attempt_at` is `now`, so the very next drain
|
|
37
|
+
* attempts delivery immediately. Returns how many deliveries were enqueued (0 = no matching endpoint).
|
|
38
|
+
*/
|
|
39
|
+
export async function enqueueWebhookEvent(
|
|
40
|
+
db: DbPort,
|
|
41
|
+
input: { tenantId: string; orgId: string; kind: WebhookEventKind; payload: WebhookEventPayload },
|
|
42
|
+
now: Date = new Date(),
|
|
43
|
+
): Promise<number> {
|
|
44
|
+
return db.withTenant(input.tenantId, async (trx) => {
|
|
45
|
+
const endpoints = await trx
|
|
46
|
+
.selectFrom('webhook_endpoints')
|
|
47
|
+
.select(['id', 'event_kinds'])
|
|
48
|
+
.where('org_id', '=', input.orgId)
|
|
49
|
+
.where('enabled', '=', true)
|
|
50
|
+
.execute()
|
|
51
|
+
const matching = endpoints.filter((e) => (e.event_kinds as string[]).includes(input.kind))
|
|
52
|
+
if (matching.length === 0) return 0
|
|
53
|
+
await trx
|
|
54
|
+
.insertInto('webhook_deliveries')
|
|
55
|
+
.values(
|
|
56
|
+
matching.map((endpoint) => ({
|
|
57
|
+
tenant_id: input.tenantId,
|
|
58
|
+
endpoint_id: endpoint.id,
|
|
59
|
+
event_kind: input.kind,
|
|
60
|
+
payload: jsonb(input.payload),
|
|
61
|
+
next_attempt_at: now,
|
|
62
|
+
})),
|
|
63
|
+
)
|
|
64
|
+
.execute()
|
|
65
|
+
return matching.length
|
|
66
|
+
})
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
// ---------------------------------------------------------------------------
|
|
70
|
+
// The delivery drain — the outbound twin of runDueSchedules. Same per-tenant
|
|
71
|
+
// (tenants × withTenant) shape and per-item fault isolation, because job_schedules/webhook_deliveries
|
|
72
|
+
// are both FORCE-RLS and a raw cross-tenant scan only *appears* to work on pglite (build-notes).
|
|
73
|
+
// ---------------------------------------------------------------------------
|
|
74
|
+
|
|
75
|
+
export interface DrainResult {
|
|
76
|
+
delivered: number
|
|
77
|
+
failed: number
|
|
78
|
+
dead: number
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
/**
|
|
82
|
+
* Drains every retryable delivery (`pending`/`failed`) whose next_attempt_at is due at `now`, per
|
|
83
|
+
* tenant, in three phases per delivery so a non-idempotent network POST is never held inside a DB
|
|
84
|
+
* transaction and concurrent ticks can't double-send:
|
|
85
|
+
*
|
|
86
|
+
* 1. CLAIM (txn) — lock the delivery FOR UPDATE, re-check it's still due, bump attempt_count and
|
|
87
|
+
* PESSIMISTICALLY arm next_attempt_at with the backoff (assume failure). Committing the claim
|
|
88
|
+
* advances next_attempt_at into the future, so a racing tick sees "not due" and skips.
|
|
89
|
+
* 2. DISPATCH (no txn) — sign the envelope and POST it through the dispatch seam.
|
|
90
|
+
* 3. RECORD (txn) — write the real outcome: delivered, or failed/dead.
|
|
91
|
+
*
|
|
92
|
+
* Delivery is therefore AT-LEAST-ONCE (a crash between claim and record re-sends at the backoff time);
|
|
93
|
+
* the envelope carries the delivery id so consumers dedupe. An audit event is written on first success
|
|
94
|
+
* (webhook.delivered) and on death (webhook.dead) — the durable, append-only webhook record.
|
|
95
|
+
*/
|
|
96
|
+
export async function runDueDeliveries(db: DbPort, now: Date, dispatch: WebhookDispatch): Promise<DrainResult> {
|
|
97
|
+
await db.ready()
|
|
98
|
+
const tenants = await db.getDb().selectFrom('tenants').select('id').execute()
|
|
99
|
+
const due: { id: string; tenant_id: string }[] = []
|
|
100
|
+
for (const tenant of tenants) {
|
|
101
|
+
const rows = await db.withTenant(tenant.id, (trx) =>
|
|
102
|
+
trx
|
|
103
|
+
.selectFrom('webhook_deliveries')
|
|
104
|
+
.select('id')
|
|
105
|
+
.where('status', 'in', ['pending', 'failed'])
|
|
106
|
+
.where('next_attempt_at', '<=', now)
|
|
107
|
+
.orderBy('next_attempt_at', 'asc')
|
|
108
|
+
.execute(),
|
|
109
|
+
)
|
|
110
|
+
due.push(...rows.map((r) => ({ id: r.id, tenant_id: tenant.id })))
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
const result: DrainResult = { delivered: 0, failed: 0, dead: 0 }
|
|
114
|
+
for (const delivery of due) {
|
|
115
|
+
try {
|
|
116
|
+
const outcome = await deliverOne(db, now, delivery, dispatch)
|
|
117
|
+
if (outcome === 'delivered') result.delivered += 1
|
|
118
|
+
else if (outcome === 'failed') result.failed += 1
|
|
119
|
+
else if (outcome === 'dead') result.dead += 1
|
|
120
|
+
} catch {
|
|
121
|
+
// A bad row must not stall the rest — its next_attempt_at may not have advanced, so it's
|
|
122
|
+
// retried on the next tick (the runDueSchedules fault-isolation precedent).
|
|
123
|
+
result.failed += 1
|
|
124
|
+
}
|
|
125
|
+
}
|
|
126
|
+
return result
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
interface Claim {
|
|
130
|
+
attempt: number
|
|
131
|
+
endpointId: string
|
|
132
|
+
orgId: string
|
|
133
|
+
url: string
|
|
134
|
+
secret: string
|
|
135
|
+
kind: WebhookEventKind
|
|
136
|
+
payload: WebhookEventPayload
|
|
137
|
+
createdAt: string
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
async function deliverOne(
|
|
141
|
+
db: DbPort,
|
|
142
|
+
now: Date,
|
|
143
|
+
delivery: { id: string; tenant_id: string },
|
|
144
|
+
dispatch: WebhookDispatch,
|
|
145
|
+
): Promise<'delivered' | 'failed' | 'dead' | 'skipped'> {
|
|
146
|
+
// Phase 1: claim under the row lock.
|
|
147
|
+
const claim = await db.withTenant(
|
|
148
|
+
delivery.tenant_id,
|
|
149
|
+
async (trx): Promise<Claim | 'skip' | { disabledOrgId: string }> => {
|
|
150
|
+
const row = await trx
|
|
151
|
+
.selectFrom('webhook_deliveries as d')
|
|
152
|
+
.innerJoin('webhook_endpoints as e', 'e.id', 'd.endpoint_id')
|
|
153
|
+
.select([
|
|
154
|
+
'd.status as status',
|
|
155
|
+
'd.event_kind as event_kind',
|
|
156
|
+
'd.payload as payload',
|
|
157
|
+
'd.attempt_count as attempt_count',
|
|
158
|
+
'd.next_attempt_at as next_attempt_at',
|
|
159
|
+
'd.created_at as created_at',
|
|
160
|
+
'e.id as endpoint_id',
|
|
161
|
+
'e.org_id as org_id',
|
|
162
|
+
'e.url as url',
|
|
163
|
+
'e.secret as secret',
|
|
164
|
+
'e.enabled as enabled',
|
|
165
|
+
])
|
|
166
|
+
.where('d.id', '=', delivery.id)
|
|
167
|
+
.forUpdate()
|
|
168
|
+
.executeTakeFirst()
|
|
169
|
+
// Re-check under the lock: a concurrent tick may have delivered it, killed it, or advanced its
|
|
170
|
+
// next_attempt_at past `now`.
|
|
171
|
+
if (!row || !['pending', 'failed'].includes(row.status) || new Date(row.next_attempt_at) > now)
|
|
172
|
+
return 'skip'
|
|
173
|
+
|
|
174
|
+
const attempt = row.attempt_count + 1
|
|
175
|
+
if (!row.enabled) {
|
|
176
|
+
// The endpoint was disabled after enqueue — stop retrying.
|
|
177
|
+
await trx
|
|
178
|
+
.updateTable('webhook_deliveries')
|
|
179
|
+
.set({ status: 'dead', attempt_count: attempt, last_error: 'endpoint disabled' })
|
|
180
|
+
.where('id', '=', delivery.id)
|
|
181
|
+
.execute()
|
|
182
|
+
return { disabledOrgId: row.org_id }
|
|
183
|
+
}
|
|
184
|
+
// Pessimistic claim: bump the attempt and arm the next retry NOW (assume this attempt fails).
|
|
185
|
+
// Phase 3 overwrites status on success. Even the would-be-final attempt arms a future
|
|
186
|
+
// next_attempt_at so a crash before phase 3 doesn't hot-loop; phase 3 sets 'dead'.
|
|
187
|
+
await trx
|
|
188
|
+
.updateTable('webhook_deliveries')
|
|
189
|
+
.set({
|
|
190
|
+
status: 'failed',
|
|
191
|
+
attempt_count: attempt,
|
|
192
|
+
next_attempt_at: new Date(now.getTime() + backoffDelayMs(attempt)),
|
|
193
|
+
})
|
|
194
|
+
.where('id', '=', delivery.id)
|
|
195
|
+
.execute()
|
|
196
|
+
return {
|
|
197
|
+
attempt,
|
|
198
|
+
endpointId: row.endpoint_id,
|
|
199
|
+
orgId: row.org_id,
|
|
200
|
+
url: row.url,
|
|
201
|
+
secret: row.secret,
|
|
202
|
+
kind: row.event_kind as WebhookEventKind,
|
|
203
|
+
payload: row.payload as WebhookEventPayload,
|
|
204
|
+
createdAt: iso(row.created_at),
|
|
205
|
+
}
|
|
206
|
+
},
|
|
207
|
+
)
|
|
208
|
+
|
|
209
|
+
if (claim === 'skip') return 'skipped'
|
|
210
|
+
if ('disabledOrgId' in claim) {
|
|
211
|
+
// Death by disabled endpoint is still a death: same durable audit record as a backoff death,
|
|
212
|
+
// written outside the claim transaction like every other audit (the house precedent).
|
|
213
|
+
await recordAuditEvent(db, {
|
|
214
|
+
tenantId: delivery.tenant_id,
|
|
215
|
+
orgId: claim.disabledOrgId,
|
|
216
|
+
actorUserId: 'system:webhooks',
|
|
217
|
+
action: 'webhook.dead',
|
|
218
|
+
subjectType: 'WebhookDelivery',
|
|
219
|
+
subjectId: delivery.id,
|
|
220
|
+
})
|
|
221
|
+
return 'dead'
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
// Phase 2: sign + dispatch OUTSIDE the transaction. Build the body string ONCE so the bytes signed
|
|
225
|
+
// are byte-identical to the bytes sent (and recorded by the fake for the counterparty to verify).
|
|
226
|
+
const timestampSec = Math.floor(now.getTime() / 1000)
|
|
227
|
+
const envelope: WebhookEnvelope = {
|
|
228
|
+
id: delivery.id,
|
|
229
|
+
kind: claim.kind,
|
|
230
|
+
createdAt: claim.createdAt,
|
|
231
|
+
data: claim.payload,
|
|
232
|
+
}
|
|
233
|
+
const body = JSON.stringify(envelope)
|
|
234
|
+
const headers = {
|
|
235
|
+
'content-type': 'application/json',
|
|
236
|
+
[WEBHOOK_SIGNATURE_HEADER]: webhookSignatureHeader(claim.secret, body, timestampSec),
|
|
237
|
+
[WEBHOOK_EVENT_HEADER]: claim.kind,
|
|
238
|
+
[WEBHOOK_DELIVERY_HEADER]: delivery.id,
|
|
239
|
+
}
|
|
240
|
+
const dispatchResult = await dispatch({
|
|
241
|
+
deliveryId: delivery.id,
|
|
242
|
+
endpointId: claim.endpointId,
|
|
243
|
+
url: claim.url,
|
|
244
|
+
headers,
|
|
245
|
+
body,
|
|
246
|
+
})
|
|
247
|
+
|
|
248
|
+
// Phase 3: record the real outcome.
|
|
249
|
+
const outcome = await db.withTenant(delivery.tenant_id, async (trx): Promise<'delivered' | 'failed' | 'dead'> => {
|
|
250
|
+
if (dispatchResult.delivered) {
|
|
251
|
+
await trx
|
|
252
|
+
.updateTable('webhook_deliveries')
|
|
253
|
+
.set({ status: 'delivered', last_error: null, delivered_at: now })
|
|
254
|
+
.where('id', '=', delivery.id)
|
|
255
|
+
.execute()
|
|
256
|
+
return 'delivered'
|
|
257
|
+
}
|
|
258
|
+
const dead = isDeliveryDead(claim.attempt)
|
|
259
|
+
await trx
|
|
260
|
+
.updateTable('webhook_deliveries')
|
|
261
|
+
.set({ status: dead ? 'dead' : 'failed', last_error: dispatchResult.error ?? 'delivery failed' })
|
|
262
|
+
.where('id', '=', delivery.id)
|
|
263
|
+
.execute()
|
|
264
|
+
return dead ? 'dead' : 'failed'
|
|
265
|
+
})
|
|
266
|
+
|
|
267
|
+
// Audit on first success and on death — the durable record (own transaction, the audit precedent).
|
|
268
|
+
if (outcome === 'delivered') {
|
|
269
|
+
await recordAuditEvent(db, {
|
|
270
|
+
tenantId: delivery.tenant_id,
|
|
271
|
+
orgId: claim.orgId,
|
|
272
|
+
actorUserId: 'system:webhooks',
|
|
273
|
+
action: 'webhook.delivered',
|
|
274
|
+
subjectType: 'WebhookDelivery',
|
|
275
|
+
subjectId: delivery.id,
|
|
276
|
+
})
|
|
277
|
+
} else if (outcome === 'dead') {
|
|
278
|
+
await recordAuditEvent(db, {
|
|
279
|
+
tenantId: delivery.tenant_id,
|
|
280
|
+
orgId: claim.orgId,
|
|
281
|
+
actorUserId: 'system:webhooks',
|
|
282
|
+
action: 'webhook.dead',
|
|
283
|
+
subjectType: 'WebhookDelivery',
|
|
284
|
+
subjectId: delivery.id,
|
|
285
|
+
})
|
|
286
|
+
}
|
|
287
|
+
return outcome
|
|
288
|
+
}
|
|
289
|
+
|
|
290
|
+
// ---------------------------------------------------------------------------
|
|
291
|
+
// Org-facing endpoint management (the org-admin card, all authorize()-gated at the route).
|
|
292
|
+
// ---------------------------------------------------------------------------
|
|
293
|
+
|
|
294
|
+
export interface EndpointView {
|
|
295
|
+
id: string
|
|
296
|
+
url: string
|
|
297
|
+
eventKinds: string[]
|
|
298
|
+
enabled: boolean
|
|
299
|
+
createdAt: string
|
|
300
|
+
}
|
|
301
|
+
|
|
302
|
+
/** The active org's endpoints, newest-first. Never returns the secret (shown once on create only). */
|
|
303
|
+
export async function listEndpointsForOrg(db: DbPort, tenantId: string, orgId: string): Promise<EndpointView[]> {
|
|
304
|
+
return db.withTenant(tenantId, async (trx) => {
|
|
305
|
+
const rows = await trx
|
|
306
|
+
.selectFrom('webhook_endpoints')
|
|
307
|
+
.select(['id', 'url', 'event_kinds', 'enabled', 'created_at'])
|
|
308
|
+
.where('org_id', '=', orgId)
|
|
309
|
+
.orderBy('created_at', 'desc')
|
|
310
|
+
.execute()
|
|
311
|
+
return rows.map((r) => ({
|
|
312
|
+
id: r.id,
|
|
313
|
+
url: r.url,
|
|
314
|
+
eventKinds: r.event_kinds as string[],
|
|
315
|
+
enabled: r.enabled,
|
|
316
|
+
createdAt: iso(r.created_at),
|
|
317
|
+
}))
|
|
318
|
+
})
|
|
319
|
+
}
|
|
320
|
+
|
|
321
|
+
/** Creates an endpoint for the active org. The secret is generated by the caller (route) and shown once. */
|
|
322
|
+
export async function createEndpoint(
|
|
323
|
+
db: DbPort,
|
|
324
|
+
input: {
|
|
325
|
+
tenantId: string
|
|
326
|
+
orgId: string
|
|
327
|
+
url: string
|
|
328
|
+
eventKinds: WebhookEventKind[]
|
|
329
|
+
secret: string
|
|
330
|
+
createdBy: string
|
|
331
|
+
},
|
|
332
|
+
): Promise<{ id: string }> {
|
|
333
|
+
return db.withTenant(input.tenantId, (trx) =>
|
|
334
|
+
trx
|
|
335
|
+
.insertInto('webhook_endpoints')
|
|
336
|
+
.values({
|
|
337
|
+
tenant_id: input.tenantId,
|
|
338
|
+
org_id: input.orgId,
|
|
339
|
+
url: input.url,
|
|
340
|
+
secret: input.secret,
|
|
341
|
+
event_kinds: jsonb(input.eventKinds),
|
|
342
|
+
created_by: input.createdBy,
|
|
343
|
+
})
|
|
344
|
+
.returning('id')
|
|
345
|
+
.executeTakeFirstOrThrow(),
|
|
346
|
+
)
|
|
347
|
+
}
|
|
348
|
+
|
|
349
|
+
/**
|
|
350
|
+
* Resolves an endpoint id to its owning org ONLY when it belongs to `orgId` within `tenantId` — null
|
|
351
|
+
* both when absent and when it belongs to another org (a foreign endpoint is indistinguishable from a
|
|
352
|
+
* missing one, so ids can't be probed; the same doctrine as jobForOrg). The route uses
|
|
353
|
+
* this to 404 before authorize().
|
|
354
|
+
*/
|
|
355
|
+
export async function endpointForOrg(
|
|
356
|
+
db: DbPort,
|
|
357
|
+
tenantId: string,
|
|
358
|
+
orgId: string,
|
|
359
|
+
endpointId: string,
|
|
360
|
+
): Promise<{ id: string } | null> {
|
|
361
|
+
return db.withTenant(tenantId, async (trx) => {
|
|
362
|
+
const row = await trx
|
|
363
|
+
.selectFrom('webhook_endpoints')
|
|
364
|
+
.select('id')
|
|
365
|
+
.where('id', '=', endpointId)
|
|
366
|
+
.where('org_id', '=', orgId)
|
|
367
|
+
.executeTakeFirst()
|
|
368
|
+
return row ? { id: row.id } : null
|
|
369
|
+
})
|
|
370
|
+
}
|
|
371
|
+
|
|
372
|
+
/** Enable/disable an endpoint (scoped to the active org by the caller's prior endpointForOrg check). */
|
|
373
|
+
export async function setEndpointEnabled(
|
|
374
|
+
db: DbPort,
|
|
375
|
+
tenantId: string,
|
|
376
|
+
endpointId: string,
|
|
377
|
+
enabled: boolean,
|
|
378
|
+
): Promise<void> {
|
|
379
|
+
await db.withTenant(tenantId, (trx) =>
|
|
380
|
+
trx.updateTable('webhook_endpoints').set({ enabled }).where('id', '=', endpointId).execute(),
|
|
381
|
+
)
|
|
382
|
+
}
|
|
383
|
+
|
|
384
|
+
/** Delete an endpoint (its deliveries cascade — migration 0010). */
|
|
385
|
+
export async function deleteEndpoint(db: DbPort, tenantId: string, endpointId: string): Promise<void> {
|
|
386
|
+
await db.withTenant(tenantId, (trx) => trx.deleteFrom('webhook_endpoints').where('id', '=', endpointId).execute())
|
|
387
|
+
}
|
|
388
|
+
|
|
389
|
+
// ---------------------------------------------------------------------------
|
|
390
|
+
// Simulator world views — cross-tenant reads (simulated-mode-only; the route gates them), the
|
|
391
|
+
// listSchedulesForWorld precedent: reach past the tenant RLS scope on purpose via the raw handle.
|
|
392
|
+
// ---------------------------------------------------------------------------
|
|
393
|
+
|
|
394
|
+
export interface WorldEndpoint {
|
|
395
|
+
id: string
|
|
396
|
+
url: string
|
|
397
|
+
eventKinds: string[]
|
|
398
|
+
enabled: boolean
|
|
399
|
+
tenantSlug: string
|
|
400
|
+
orgSlug: string
|
|
401
|
+
}
|
|
402
|
+
|
|
403
|
+
export async function listEndpointsForWorld(db: DbPort): Promise<WorldEndpoint[]> {
|
|
404
|
+
await db.ready()
|
|
405
|
+
const rows = await db
|
|
406
|
+
.getDb()
|
|
407
|
+
.selectFrom('webhook_endpoints')
|
|
408
|
+
.innerJoin('tenants', 'tenants.id', 'webhook_endpoints.tenant_id')
|
|
409
|
+
.innerJoin('organizations', 'organizations.id', 'webhook_endpoints.org_id')
|
|
410
|
+
.select([
|
|
411
|
+
'webhook_endpoints.id as id',
|
|
412
|
+
'webhook_endpoints.url as url',
|
|
413
|
+
'webhook_endpoints.event_kinds as event_kinds',
|
|
414
|
+
'webhook_endpoints.enabled as enabled',
|
|
415
|
+
'tenants.slug as tenant_slug',
|
|
416
|
+
'organizations.slug as org_slug',
|
|
417
|
+
])
|
|
418
|
+
.orderBy('webhook_endpoints.created_at', 'desc')
|
|
419
|
+
.execute()
|
|
420
|
+
return rows.map((r) => ({
|
|
421
|
+
id: r.id,
|
|
422
|
+
url: r.url,
|
|
423
|
+
eventKinds: r.event_kinds as string[],
|
|
424
|
+
enabled: r.enabled,
|
|
425
|
+
tenantSlug: r.tenant_slug,
|
|
426
|
+
orgSlug: r.org_slug,
|
|
427
|
+
}))
|
|
428
|
+
}
|
|
429
|
+
|
|
430
|
+
export interface WorldDelivery {
|
|
431
|
+
id: string
|
|
432
|
+
endpointId: string
|
|
433
|
+
endpointUrl: string
|
|
434
|
+
eventKind: string
|
|
435
|
+
status: string
|
|
436
|
+
attemptCount: number
|
|
437
|
+
nextAttemptAt: string
|
|
438
|
+
lastError: string | null
|
|
439
|
+
createdAt: string
|
|
440
|
+
deliveredAt: string | null
|
|
441
|
+
tenantSlug: string
|
|
442
|
+
orgSlug: string
|
|
443
|
+
}
|
|
444
|
+
|
|
445
|
+
export async function listDeliveriesForWorld(db: DbPort): Promise<WorldDelivery[]> {
|
|
446
|
+
await db.ready()
|
|
447
|
+
const rows = await db
|
|
448
|
+
.getDb()
|
|
449
|
+
.selectFrom('webhook_deliveries as d')
|
|
450
|
+
.innerJoin('webhook_endpoints as e', 'e.id', 'd.endpoint_id')
|
|
451
|
+
.innerJoin('tenants', 'tenants.id', 'd.tenant_id')
|
|
452
|
+
.innerJoin('organizations', 'organizations.id', 'e.org_id')
|
|
453
|
+
.select([
|
|
454
|
+
'd.id as id',
|
|
455
|
+
'd.endpoint_id as endpoint_id',
|
|
456
|
+
'e.url as endpoint_url',
|
|
457
|
+
'd.event_kind as event_kind',
|
|
458
|
+
'd.status as status',
|
|
459
|
+
'd.attempt_count as attempt_count',
|
|
460
|
+
'd.next_attempt_at as next_attempt_at',
|
|
461
|
+
'd.last_error as last_error',
|
|
462
|
+
'd.created_at as created_at',
|
|
463
|
+
'd.delivered_at as delivered_at',
|
|
464
|
+
'tenants.slug as tenant_slug',
|
|
465
|
+
'organizations.slug as org_slug',
|
|
466
|
+
])
|
|
467
|
+
.orderBy('d.created_at', 'desc')
|
|
468
|
+
.execute()
|
|
469
|
+
return rows.map((r) => ({
|
|
470
|
+
id: r.id,
|
|
471
|
+
endpointId: r.endpoint_id,
|
|
472
|
+
endpointUrl: r.endpoint_url,
|
|
473
|
+
eventKind: r.event_kind,
|
|
474
|
+
status: r.status,
|
|
475
|
+
attemptCount: r.attempt_count,
|
|
476
|
+
nextAttemptAt: iso(r.next_attempt_at),
|
|
477
|
+
lastError: r.last_error,
|
|
478
|
+
createdAt: iso(r.created_at),
|
|
479
|
+
deliveredAt: r.delivered_at ? iso(r.delivered_at) : null,
|
|
480
|
+
tenantSlug: r.tenant_slug,
|
|
481
|
+
orgSlug: r.org_slug,
|
|
482
|
+
}))
|
|
483
|
+
}
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
import { sql, type Kysely, type Transaction } from 'kysely'
|
|
2
|
+
import type { DB } from './schema'
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* The tenant scope helper every db transport shares (proven in spikes/kysely-pglite; ADR-0004).
|
|
6
|
+
*
|
|
7
|
+
* ONE statement sets both halves of the scope, transaction-locally: `set_config('role', 'app_user', true)`
|
|
8
|
+
* is `SET LOCAL ROLE app_user` (same GUC, same check that the session user is a member) and the tenant id goes through
|
|
9
|
+
* set_config() as a real parameter — never string interpolation. One statement rather than two because
|
|
10
|
+
* on the RDS Data API every statement is its own HTTPS call (ADR-0004, addendum 2026-11-16); on `pg` and
|
|
11
|
+
* pglite it is simply one round trip fewer. Transaction-scoped, so it is safe under pooling, required
|
|
12
|
+
* under pglite (whose default user bypasses RLS), and the only shape that survives the Data API's
|
|
13
|
+
* connection reset between transactions.
|
|
14
|
+
*/
|
|
15
|
+
export async function runWithTenant<T>(
|
|
16
|
+
db: Kysely<DB>,
|
|
17
|
+
tenantId: string,
|
|
18
|
+
fn: (trx: Transaction<DB>) => Promise<T>,
|
|
19
|
+
): Promise<T> {
|
|
20
|
+
return db.transaction().execute(async (trx) => {
|
|
21
|
+
await sql`SELECT set_config('role', 'app_user', true), set_config('app.current_tenant', ${tenantId}, true)`.execute(
|
|
22
|
+
trx,
|
|
23
|
+
)
|
|
24
|
+
return fn(trx)
|
|
25
|
+
})
|
|
26
|
+
}
|
|
@@ -0,0 +1,161 @@
|
|
|
1
|
+
import type { Dispatch, RefObject, SetStateAction } from 'react'
|
|
2
|
+
import type {
|
|
3
|
+
ActorLog,
|
|
4
|
+
BuilderDriver,
|
|
5
|
+
ServiceDriver,
|
|
6
|
+
HopOutcome,
|
|
7
|
+
PendingBuildLike,
|
|
8
|
+
ServiceJobLike,
|
|
9
|
+
} from '../components/simulator/actor-runtime'
|
|
10
|
+
import type { DemoJob } from './rows'
|
|
11
|
+
|
|
12
|
+
/**
|
|
13
|
+
* The static twin's actor drivers (ADR-0006: FULL parity, no server). Same ServiceDriver/BuilderDriver
|
|
14
|
+
* contracts the real fetch drivers implement (src/app/[locale]/simulator/actors/[actor]/drivers.ts),
|
|
15
|
+
* so the SAME serviceTick/builderTick from ../components/simulator/actor-runtime.ts drive both hosts
|
|
16
|
+
* verbatim — only the transport differs. There is no token/secret to mint here (no server to talk to),
|
|
17
|
+
* so unlike the real drivers these never produce an `unauthorized` outcome.
|
|
18
|
+
*
|
|
19
|
+
* WHICH team each actor serves is app vocabulary (@sssb/app-config/actors, @sssb/app-config/jobs), so it arrives
|
|
20
|
+
* as a scope argument rather than being read here — the drivers themselves only know jobs, which the
|
|
21
|
+
* framework owns.
|
|
22
|
+
*
|
|
23
|
+
* DEGRADE (documented like the export twin's own note in ./world.ts): completing a job here can't
|
|
24
|
+
* produce a downloadable artifact — the static shell has no server to serve CSV bytes from — so the
|
|
25
|
+
* completed timeline entry carries no resultKey/downloadUrl. The `POST /api/simulator/actors/artifact`
|
|
26
|
+
* call the real driver makes before completing is mirrored as an in-memory log line only.
|
|
27
|
+
*/
|
|
28
|
+
interface DemoDriverDeps {
|
|
29
|
+
/** Always-current mirror of the world's jobs (an effect-synced ref) — reading through a ref rather
|
|
30
|
+
* than a stale closure over the state value lets these drivers stay valid across ticks without
|
|
31
|
+
* being reconstructed. */
|
|
32
|
+
jobsRef: RefObject<DemoJob[]>
|
|
33
|
+
setJobs: Dispatch<SetStateAction<DemoJob[]>>
|
|
34
|
+
log: ActorLog
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
/** The one team a service actor is scoped to — the twin of its minted token's tenant/org claims. */
|
|
38
|
+
export interface DemoServiceScope {
|
|
39
|
+
tenantSlug: string
|
|
40
|
+
orgSlug: string
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
export function createDemoServiceDriver(
|
|
44
|
+
{ jobsRef, setJobs, log }: DemoDriverDeps,
|
|
45
|
+
scope: DemoServiceScope,
|
|
46
|
+
): ServiceDriver {
|
|
47
|
+
return {
|
|
48
|
+
async listJobs(): Promise<ServiceJobLike[]> {
|
|
49
|
+
// Mirrors GET /api/service/jobs scoped to a token minted for this team — the token's own
|
|
50
|
+
// claims are what narrow it server-side, so the twin filters by the same two slugs.
|
|
51
|
+
return jobsRef.current
|
|
52
|
+
.filter((job) => job.tenantSlug === scope.tenantSlug && job.orgSlug === scope.orgSlug)
|
|
53
|
+
.map((job) => ({
|
|
54
|
+
id: job.id,
|
|
55
|
+
kind: job.kind,
|
|
56
|
+
status: job.status as ServiceJobLike['status'],
|
|
57
|
+
createdAt: job.createdAt,
|
|
58
|
+
}))
|
|
59
|
+
},
|
|
60
|
+
async claim(jobId: string): Promise<HopOutcome> {
|
|
61
|
+
const job = jobsRef.current.find((j) => j.id === jobId)
|
|
62
|
+
if (!job) return 'gone'
|
|
63
|
+
if (job.status !== 'queued') return 'conflict'
|
|
64
|
+
const at = new Date().toISOString()
|
|
65
|
+
setJobs((prev) =>
|
|
66
|
+
prev.map((j) =>
|
|
67
|
+
j.id === jobId && j.status === 'queued'
|
|
68
|
+
? {
|
|
69
|
+
...j,
|
|
70
|
+
status: 'running',
|
|
71
|
+
timeline: [...j.timeline, { status: 'running', at, message: null }],
|
|
72
|
+
}
|
|
73
|
+
: j,
|
|
74
|
+
),
|
|
75
|
+
)
|
|
76
|
+
return 'applied'
|
|
77
|
+
},
|
|
78
|
+
async complete(jobId: string): Promise<HopOutcome> {
|
|
79
|
+
const job = jobsRef.current.find((j) => j.id === jobId)
|
|
80
|
+
if (!job) return 'gone'
|
|
81
|
+
if (job.status !== 'running') return 'conflict'
|
|
82
|
+
// The real driver logs the artifact-production POST before reporting completion — this
|
|
83
|
+
// is that same call shape, adapted for a host with no storage to write to (see DEGRADE
|
|
84
|
+
// note above).
|
|
85
|
+
log({ line: 'POST /api/simulator/actors/artifact → 200 (in-memory, no file)' })
|
|
86
|
+
const at = new Date().toISOString()
|
|
87
|
+
setJobs((prev) =>
|
|
88
|
+
prev.map((j) =>
|
|
89
|
+
j.id === jobId && j.status === 'running'
|
|
90
|
+
? {
|
|
91
|
+
...j,
|
|
92
|
+
status: 'completed',
|
|
93
|
+
timeline: [...j.timeline, { status: 'completed', at, message: null }],
|
|
94
|
+
}
|
|
95
|
+
: j,
|
|
96
|
+
),
|
|
97
|
+
)
|
|
98
|
+
return 'applied'
|
|
99
|
+
},
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
export function createDemoBuilderDriver(
|
|
104
|
+
{ jobsRef, setJobs, log }: DemoDriverDeps,
|
|
105
|
+
/** Teams already served by a dedicated service actor (@sssb/app-config/jobs' serviceManagedOrgSlugs) —
|
|
106
|
+
* excluded so the two actors' job pools stay disjoint, exactly like listPendingBuilds. */
|
|
107
|
+
serviceManagedOrgSlugs: readonly string[],
|
|
108
|
+
): BuilderDriver {
|
|
109
|
+
return {
|
|
110
|
+
async listBuilds(): Promise<PendingBuildLike[]> {
|
|
111
|
+
// Mirrors GET /api/simulator/actors/builds: every non-terminal job whose org is NOT
|
|
112
|
+
// service-managed (or has none) — the builder-console's disjoint pool.
|
|
113
|
+
const builds = jobsRef.current
|
|
114
|
+
.filter(
|
|
115
|
+
(job) =>
|
|
116
|
+
(job.status === 'queued' || job.status === 'running') &&
|
|
117
|
+
!serviceManagedOrgSlugs.includes(job.orgSlug ?? ''),
|
|
118
|
+
)
|
|
119
|
+
.map((job) => ({
|
|
120
|
+
jobId: job.id,
|
|
121
|
+
// The twin has no real tenant ids (a seed package only carries slugs) — the
|
|
122
|
+
// interface field is structural here, never dereferenced against real storage.
|
|
123
|
+
tenantId: job.tenantSlug,
|
|
124
|
+
tenantSlug: job.tenantSlug,
|
|
125
|
+
orgSlug: job.orgSlug,
|
|
126
|
+
kind: job.kind,
|
|
127
|
+
status: job.status as 'queued' | 'running',
|
|
128
|
+
createdAt: job.createdAt,
|
|
129
|
+
}))
|
|
130
|
+
return builds
|
|
131
|
+
},
|
|
132
|
+
async deliver(build: PendingBuildLike) {
|
|
133
|
+
const job = jobsRef.current.find((j) => j.id === build.jobId)
|
|
134
|
+
if (!job) return 'gone'
|
|
135
|
+
if (job.status !== 'queued' && job.status !== 'running' && job.status !== 'completed') return 'conflict'
|
|
136
|
+
// Real webhook delivery always re-runs the artifact handler first, even for an already-
|
|
137
|
+
// terminal (idempotent) job — mirror that call shape unconditionally too.
|
|
138
|
+
log({ line: 'POST /api/simulator/actors/artifact → 200 (in-memory, no file)' })
|
|
139
|
+
if (job.status === 'completed') return 'idempotent'
|
|
140
|
+
const now = Date.now()
|
|
141
|
+
setJobs((prev) =>
|
|
142
|
+
prev.map((j) => {
|
|
143
|
+
if (j.id !== build.jobId || j.status === 'completed') return j
|
|
144
|
+
const timeline = [...j.timeline]
|
|
145
|
+
// Same single-POST double-hop the real webhook route performs (../db/jobs.ts):
|
|
146
|
+
// a still-queued job walks through running (message 'completion webhook') first.
|
|
147
|
+
if (j.status === 'queued') {
|
|
148
|
+
timeline.push({
|
|
149
|
+
status: 'running',
|
|
150
|
+
at: new Date(now).toISOString(),
|
|
151
|
+
message: 'completion webhook',
|
|
152
|
+
})
|
|
153
|
+
}
|
|
154
|
+
timeline.push({ status: 'completed', at: new Date(now + 50).toISOString(), message: null })
|
|
155
|
+
return { ...j, status: 'completed', timeline }
|
|
156
|
+
}),
|
|
157
|
+
)
|
|
158
|
+
return 'applied'
|
|
159
|
+
},
|
|
160
|
+
}
|
|
161
|
+
}
|