Skip to content
Source
Sign inSign up
samwillis/neon-durable-streams
Open History to see the last commit

subscription-store.ts

599 lines49.1 KB

1import { createHash, randomBytes, randomInt, randomUUID, timingSafeEqual } from 'node:crypto'
2import type { Pool, PoolClient } from 'pg'
3import { StorageCompatibilityError, StreamError } from './errors.js'
4import { parseOffset, ZERO_OFFSET } from './offset.js'
5import { validateSchema } from './path.js'
6import type { AuthorizationContext, Operation, Principal } from './server.js'
7import type { PostgresStreamStore } from './store.js'
8import { SubscriptionCipher, SubscriptionSigner } from './subscription-crypto.js'
9import { globMatches, normalizeSubscription, relativeStreamPath } from './subscription-protocol.js'
10import type { ControlRoute, SubscriptionConfig } from './subscription-protocol.js'
11import type { SubscriptionOptions } from './subscriptions.js'
12import { deliverWebhook, webhookTarget } from './webhook.js'
13import { WakeTokens } from './wake-token.js'
14import type { WakeTokenClaims } from './wake-token.js'
15​
16interface Sub {
17 id: string; tenant_id: string; name: string; config: SubscriptionConfig; config_hash: string; pattern_regex: string | null
18 public_base_url: string; generation: string; current_wake: string | null; holder: string | null; lease_until: Date | null
19 retry_count: number; retry_at: Date | null; next_work_at: Date | null; member_count: number; blocked_members: number
20 created_at: Date; deleted_at: Date | null; lease_valid?: boolean
22interface Member {
23 path: string; stream_id: string | null; explicit_link: boolean; glob_link: boolean; acked_offset: string; tail_offset: string
25interface Snapshot { path: string; stream_id: string | null; link_type: 'explicit' | 'glob'; acked_offset: string; tail_offset: string }
26interface Wake {
27 id: string; subscription_id: string; tenant_id: string; generation: string; kind: 'webhook' | 'pull-wake'
28 token_hash: Buffer | null; token_cipher: Buffer | null; state: string; delivery_claim: string | null; delivery_until: Date | null; pull_published: boolean; created_at: Date
30interface WebhookJob { sub: Sub; wake: Wake; streams: readonly Snapshot[]; claim: string }
31interface Change { stream_id: string; version: string; before_offset: string; after_offset: string; kind: string; fanout_after: string | null; tenant_id: string; path: string; active_stream_id: string | null }
32const fenced = () => new StreamError(409, 'FENCED', 'Wake generation is stale')
33const jsonBody = (bytes: Buffer): Record<string, unknown> => {
34 try { const value: unknown = JSON.parse(new TextDecoder('utf-8', { fatal: true }).decode(bytes)); if (!value || typeof value !== 'object' || Array.isArray(value)) throw new Error(); return value as Record<string, unknown> }
35 catch { throw new StreamError(400, 'INVALID_JSON', 'Expected a JSON object') }
37const hashToken = (token: string) => createHash('sha256').update(token).digest()
38​
39export class PostgresSubscriptions {
40 private readonly schema: string
41 private readonly cipher: SubscriptionCipher
42 private readonly signer: SubscriptionSigner
43 private readonly tokens: WakeTokens
44 private signedTokens = false
45 private readonly maxStreams: number
46 private readonly maxSubscriptions: number
47 private readonly webhookTimeout: number
48 private installationId?: string
49 private ready: Promise<void> | undefined
50 private readonly shutdown = new AbortController()
51 constructor(private readonly pool: Pool, schema: string, private readonly streams: PostgresStreamStore,
52 private readonly options: SubscriptionOptions, private readonly report: (error: unknown) => void) {
53 this.schema = validateSchema(schema)
54 this.cipher = new SubscriptionCipher(options.keyring)
55 this.signer = new SubscriptionSigner(pool, schema, options.keyring)
56 this.tokens = new WakeTokens(options.keyring)
57 this.maxStreams = options.maxStreams ?? 1000
58 this.maxSubscriptions = options.maxSubscriptionsPerTenant ?? 10_000
59 this.webhookTimeout = options.webhookTimeoutMs ?? 5000
60 for (const [n, min, max] of [[this.maxStreams, 1, 10_000], [this.maxSubscriptions, 1, 100_000], [this.webhookTimeout, 100, 60_000]]) {
61 if (!Number.isSafeInteger(n) || n! < min! || n! > max!) throw new RangeError('Invalid subscription limits')
62 }
63 }
64 async assertReady(): Promise<void> {
65 this.ready ??= (async () => {
66 await this.streams.assertReady()
67 this.signedTokens = this.streams.schemaVersion === 6
68 const result = await this.pool.query<{ id: string }>(`SELECT id FROM ${this.schema}.installation`)
69 if (result.rows.length !== 1) throw new StorageCompatibilityError('Missing installation identity')
70 this.installationId = result.rows[0]!.id
71 await this.signer.active()
72 await this.signer.signature(Buffer.alloc(0))
73 })().catch((error: unknown) => { this.ready = undefined; throw error })
74 await this.ready
75 }
76 private registry(client: PoolClient, tenant: string, exclusive: boolean) {
77 return client.query(`SELECT pg_advisory_xact_lock${exclusive ? '' : '_shared'}(hashtextextended($1, 0))`, [`durable-streams:subscription-registry:${this.schema}:${tenant}`])
78 }
79 private async find(client: PoolClient, tenant: string, name: string): Promise<Sub> {
80 const result = await client.query<Sub>(`WITH locked AS MATERIALIZED (SELECT * FROM ${this.schema}.subscriptions WHERE tenant_id = $1 AND name = $2 AND deleted_at IS NULL FOR UPDATE)
81 SELECT *, lease_until > clock_timestamp() AS lease_valid FROM locked`, [tenant, name])
82 if (!result.rows[0]) throw new StreamError(404, 'SUBSCRIPTION_NOT_FOUND', 'Subscription not found')
83 return result.rows[0]
84 }
85 private async infos(client: PoolClient, sub: Sub): Promise<readonly Member[]> {
86 const result = await client.query<Member>(`SELECT m.*, CASE WHEN p.active_stream_id = s.id AND s.deleted_at IS NULL
87 AND (s.expires_at IS NULL OR s.expires_at > clock_timestamp()) AND (s.ttl_seconds IS NULL OR s.accessed_at + s.ttl_seconds * interval '1 second' > clock_timestamp())
88 THEN s.tail_offset ELSE m.acked_offset END AS tail_offset FROM ${this.schema}.subscription_members m
89 LEFT JOIN ${this.schema}.streams s ON s.id = m.stream_id LEFT JOIN ${this.schema}.paths p ON p.tenant_id = m.tenant_id AND p.path = m.path
90 WHERE m.subscription_id = $1 ORDER BY m.path LIMIT $2`, [sub.id, this.maxStreams + 1])
91 if (result.rows.length > this.maxStreams) throw new StreamError(503, 'SUBSCRIPTION_CAPACITY', 'Configured stream capacity is below existing subscription membership')
92 return result.rows
93 }
94 private snapshot(members: readonly Member[]): readonly Snapshot[] {
95 return members.map((member) => ({ path: member.path, stream_id: member.stream_id, link_type: member.explicit_link ? 'explicit' : 'glob', acked_offset: member.acked_offset, tail_offset: member.tail_offset }))
96 }
97 private async pending(client: PoolClient, sub: Sub): Promise<boolean> {
98 return (await this.infos(client, sub)).some((member) => member.tail_offset > member.acked_offset)
99 }
100 private async invalidate(client: PoolClient, sub: Sub, state: 'completed' | 'expired' | 'fenced'): Promise<void> {
101 if (sub.current_wake) await client.query(`UPDATE ${this.schema}.subscription_wakes SET state = $2, delivery_claim = NULL, delivery_until = NULL WHERE id = $1`, [sub.current_wake, state])
102 await client.query(`UPDATE ${this.schema}.subscriptions SET current_wake = NULL, holder = NULL, lease_until = NULL WHERE id = $1`, [sub.id])
103 sub.current_wake = null; sub.holder = null; sub.lease_until = null; sub.lease_valid = false
104 }
105 private async queue(client: PoolClient, sub: Sub): Promise<boolean> {
106 const pending = await this.pending(client, sub)
107 await client.query(`UPDATE ${this.schema}.subscriptions SET next_work_at = CASE WHEN $2 THEN COALESCE(retry_at, clock_timestamp()) ELSE NULL END WHERE id = $1`, [sub.id, pending])
108 return pending
109 }
110 private async insertMember(client: PoolClient, sub: Sub, path: string, streamId: string | null, offset: string, explicit: boolean, glob: boolean): Promise<void> {
111 const queued = streamId ? (await client.query<{ before_offset: string }>(`SELECT before_offset FROM ${this.schema}.subscription_pending_links WHERE subscription_id = $1 AND stream_id = $2`, [sub.id, streamId])).rows[0] : undefined
112 const baseline = queued && queued.before_offset < offset ? queued.before_offset : offset
113 await client.query(`INSERT INTO ${this.schema}.subscription_members (subscription_id, tenant_id, path, stream_id, explicit_link, glob_link, acked_offset)
114 VALUES ($1,$2,$3,$4,$5,$6,$7)`, [sub.id, sub.tenant_id, path, streamId, explicit, glob, baseline])
115 await client.query(`UPDATE ${this.schema}.subscriptions SET member_count = member_count + 1 WHERE id = $1`, [sub.id])
116 sub.member_count++
117 if (queued) {
118 await client.query(`DELETE FROM ${this.schema}.subscription_pending_links WHERE subscription_id = $1 AND stream_id = $2`, [sub.id, streamId])
119 await client.query(`UPDATE ${this.schema}.subscriptions SET blocked_members = blocked_members - 1 WHERE id = $1`, [sub.id])
120 }
121 }
122 private async activePath(client: PoolClient, tenant: string, path: string): Promise<{ id: string; tail_offset: string } | undefined> {
123 const result = await client.query<{ id: string; tail_offset: string }>(`SELECT s.id, s.tail_offset FROM ${this.schema}.paths p JOIN ${this.schema}.streams s ON s.id = p.active_stream_id
124 WHERE p.tenant_id = $1 AND p.path = $2 AND s.deleted_at IS NULL AND (s.expires_at IS NULL OR s.expires_at > clock_timestamp())
125 AND (s.ttl_seconds IS NULL OR s.accessed_at + s.ttl_seconds * interval '1 second' > clock_timestamp())`, [tenant, path])
126 return result.rows[0]
127 }
128 async jwks(): Promise<Response> {
129 await this.assertReady()
130 await this.streams.guard.check()
131 return Response.json(await this.signer.jwks(), { headers: { 'Content-Type': 'application/jwk-set+json', 'Cache-Control': 'public, max-age=300' } })
132 }
133 async handle(request: Request, route: ControlRoute, principal: Principal, authorize: (context: AuthorizationContext) => boolean | Promise<boolean>, readBody: () => Promise<Buffer>, publicBase: string): Promise<Response> {
134 const allowed = async (operation: Operation, selector?: { pattern?: string; streams: readonly string[] }, subscription?: SubscriptionConfig) => {
135 if (!await authorize({ principal, operation, path: route.path, request, ...(selector ? { selector } : {}), ...(subscription ? { subscription } : {}) })) throw new StreamError(403, 'FORBIDDEN', 'Subscription operation is not authorized')
136 }
137 if (route.action === 'subscription' && request.method === 'PUT') {
138 const normalized = normalizeSubscription(jsonBody(await readBody()))
139 const { config } = normalized
140 if (config.streams.length > this.maxStreams) throw new StreamError(413, 'SUBSCRIPTION_CAPACITY', 'Too many explicit subscription streams')
141 await allowed('subscribe', { ...(config.pattern ? { pattern: config.pattern } : {}), streams: config.streams }, config)
142 if (config.wake_stream && !await authorize({ principal, operation: 'append', path: config.wake_stream, request })) throw new StreamError(403, 'FORBIDDEN', 'Wake-stream writes are not authorized')
143 if (config.webhook) await webhookTarget(config.webhook.url, this.options.allowLocalhostWebhooks ?? false)
144 await this.assertReady()
145 const created = await this.streams.transaction({}, async (client) => {
146 await this.registry(client, principal.tenantId, true)
147 const existing = await client.query<Sub>(`SELECT * FROM ${this.schema}.subscriptions WHERE tenant_id = $1 AND name = $2 AND deleted_at IS NULL FOR UPDATE`, [principal.tenantId, route.name])
148 if (existing.rows[0]) {
149 if (existing.rows[0].config_hash !== normalized.hash) throw new StreamError(409, 'CONFIGURATION_MISMATCH', 'Subscription configuration differs')
150 return false
151 }
152 const count = await client.query<{ count: string; generation: string }>(`SELECT count(*) FILTER (WHERE deleted_at IS NULL) AS count, COALESCE(max(generation) FILTER (WHERE name = $2),0) AS generation
153 FROM ${this.schema}.subscriptions WHERE tenant_id = $1`, [principal.tenantId, route.name])
154 if (Number(count.rows[0]!.count) >= this.maxSubscriptions) throw new StreamError(429, 'SUBSCRIPTION_CAPACITY', 'Tenant subscription capacity reached')
155 const result = await client.query<Sub>(`INSERT INTO ${this.schema}.subscriptions (id, tenant_id, name, config, config_hash, pattern_regex, public_base_url, generation)
156 VALUES ($1,$2,$3,$4,$5,$6,$7,$8) RETURNING *`, [randomUUID(), principal.tenantId, route.name, config, normalized.hash, normalized.regex, publicBase, count.rows[0]!.generation])
157 const sub = result.rows[0]!
158 const existingStreams = await client.query<{ path: string; id: string; tail_offset: string }>(`SELECT s.path, s.id, s.tail_offset FROM ${this.schema}.streams s JOIN ${this.schema}.paths p ON p.active_stream_id = s.id
159 WHERE s.tenant_id = $1 AND s.deleted_at IS NULL AND (s.expires_at IS NULL OR s.expires_at > clock_timestamp())
160 AND (s.ttl_seconds IS NULL OR s.accessed_at + s.ttl_seconds * interval '1 second' > clock_timestamp())
161 AND (($2::text IS NOT NULL AND s.path ~ $2) OR s.path = ANY($3::text[])) ORDER BY s.path LIMIT $4`, [principal.tenantId, normalized.regex, config.streams, this.maxStreams + 1])
162 const paths = new Map(existingStreams.rows.map((row) => [row.path, row]))
163 const members = [...new Set([...paths.keys(), ...config.streams])]
164 if (members.length > this.maxStreams) throw new StreamError(413, 'SUBSCRIPTION_CAPACITY', 'Subscription matches too many streams')
165 // One bounded insert, preserving an at-tail baseline captured while the
166 // exclusive registry barrier prevents dispatch from overtaking backfill.
167 const rows = members.map((path) => ({ path, stream_id: paths.get(path)?.id ?? null, acked_offset: paths.get(path)?.tail_offset ?? ZERO_OFFSET,
168 explicit_link: config.streams.includes(path), glob_link: config.pattern !== null && globMatches(config.pattern, path) }))
169 if (rows.length) await client.query(`INSERT INTO ${this.schema}.subscription_members (subscription_id, tenant_id, path, stream_id, acked_offset, explicit_link, glob_link)
170 SELECT $1,$2,x.path,x.stream_id,x.acked_offset,x.explicit_link,x.glob_link FROM jsonb_to_recordset($3::jsonb) x(path text,stream_id uuid,acked_offset text,explicit_link boolean,glob_link boolean)`, [sub.id, sub.tenant_id, JSON.stringify(rows)])
171 await client.query(`UPDATE ${this.schema}.subscriptions SET member_count = $2 WHERE id = $1`, [sub.id, rows.length])
172 return true
173 })
174 return this.serialize(principal.tenantId, route.name!, created ? 201 : 200)
175 }
176 if (route.action === 'subscription' && request.method === 'GET') { await allowed('read'); await this.assertReady(); return this.serialize(principal.tenantId, route.name!) }
177 if (route.action === 'subscription' && request.method === 'DELETE') {
178 await allowed('delete')
179 await this.assertReady()
180 await this.streams.transaction({}, async (client) => {
181 const sub = await this.find(client, principal.tenantId, route.name!)
182 await this.invalidate(client, sub, 'fenced')
183 await client.query(`DELETE FROM ${this.schema}.subscription_pending_links WHERE subscription_id = $1`, [sub.id])
184 await client.query(`DELETE FROM ${this.schema}.subscription_members WHERE subscription_id = $1`, [sub.id])
185 await client.query(`UPDATE ${this.schema}.subscriptions SET deleted_at = clock_timestamp(), next_work_at = NULL, blocked_members = 0, member_count = 0 WHERE id = $1`, [sub.id])
186 })
187 return new Response(null, { status: 204 })
188 }
189 if ((route.action === 'streams' && request.method === 'POST') || (route.action === 'member' && request.method === 'DELETE')) {
190 const body = route.action === 'streams' ? jsonBody(await readBody()) : null
191 if (body && !Array.isArray(body.streams)) throw new StreamError(400, 'INVALID_STREAMS', 'Expected a streams array')
192 const paths = route.action === 'member' ? [route.member!] : [...new Set((body!.streams as unknown[]).map(relativeStreamPath))]
193 if (paths.length > this.maxStreams) throw new StreamError(413, 'SUBSCRIPTION_CAPACITY', 'Too many explicit streams')
194 await allowed('subscribe', { streams: paths })
195 await this.assertReady()
196 await this.membership(principal.tenantId, route.name!, paths, route.action === 'streams')
197 return new Response(null, { status: 204 })
198 }
199 if (route.action === 'claim' && request.method === 'POST') {
200 await allowed('claim')
201 await this.assertReady()
202 const body = jsonBody(await readBody())
203 if (typeof body.worker !== 'string' || !body.worker || Buffer.byteLength(body.worker) > 512) throw new StreamError(400, 'INVALID_WORKER', 'Expected a worker name')
204 return this.claim(principal.tenantId, route.name!, body.worker)
205 }
206 throw new StreamError(405, 'METHOD_NOT_ALLOWED', 'Unsupported subscription method or route')
207 }
208 private async serialize(tenant: string, name: string, status = 200): Promise<Response> {
209 const value = await this.streams.transaction({ readOnly: true }, async (client) => {
210 const result = await client.query<Sub>(`SELECT * FROM ${this.schema}.subscriptions WHERE tenant_id = $1 AND name = $2 AND deleted_at IS NULL`, [tenant, name])
211 const sub = result.rows[0]
212 if (!sub) throw new StreamError(404, 'SUBSCRIPTION_NOT_FOUND', 'Subscription not found')
213 return { sub, members: await this.infos(client, sub) }
214 })
215 const sub = value.sub, config = sub.config
216 return Response.json({ id: name, subscription_id: name, type: config.type, pattern: config.pattern,
217 streams: value.members.map((member) => ({ path: member.path, link_type: member.explicit_link ? 'explicit' : 'glob', acked_offset: member.acked_offset })),
218 webhook: config.webhook ? { url: config.webhook.url, signing: { alg: 'ed25519', kid: await this.signer.active(), jwks_url: `${sub.public_base_url}/__ds/jwks.json` } } : null,
219 wake_stream: config.wake_stream, lease_ttl_ms: config.lease_ttl_ms, created_at: sub.created_at.toISOString(),
220 status: sub.retry_count || sub.blocked_members ? 'failed' : 'active', description: config.description }, { status })
221 }
222 private async membership(tenant: string, name: string, paths: readonly string[], add: boolean): Promise<void> {
223 await this.streams.transaction({}, async (client) => {
224 await this.registry(client, tenant, true)
225 const sub = await this.find(client, tenant, name)
226 let changed = false
227 for (const path of paths) {
228 const found = await client.query<Member>(`SELECT * FROM ${this.schema}.subscription_members WHERE subscription_id = $1 AND path = $2`, [sub.id, path])
229 const member = found.rows[0]
230 if (add) {
231 if (member?.explicit_link) continue
232 if (member) await client.query(`UPDATE ${this.schema}.subscription_members SET explicit_link = true WHERE subscription_id = $1 AND path = $2`, [sub.id, path])
233 else {
234 if (sub.member_count >= this.maxStreams) throw new StreamError(413, 'SUBSCRIPTION_CAPACITY', 'Subscription stream capacity reached')
235 const stream = await this.activePath(client, tenant, path)
236 await this.insertMember(client, sub, path, stream?.id ?? null, stream?.tail_offset ?? ZERO_OFFSET, true, sub.config.pattern !== null && globMatches(sub.config.pattern, path))
237 }
238 } else {
239 if (!member?.explicit_link) continue
240 if (member.glob_link) await client.query(`UPDATE ${this.schema}.subscription_members SET explicit_link = false WHERE subscription_id = $1 AND path = $2`, [sub.id, path])
241 else { await client.query(`DELETE FROM ${this.schema}.subscription_members WHERE subscription_id = $1 AND path = $2`, [sub.id, path]); await client.query(`UPDATE ${this.schema}.subscriptions SET member_count = member_count - 1 WHERE id = $1`, [sub.id]); sub.member_count-- }
242 }
243 changed = true
244 }
245 if (changed) { await this.invalidate(client, sub, 'fenced'); await this.queue(client, sub) }
246 })
247 }
248 private async wakeToken(sub: Sub, wakeId: string, generation: number): Promise<string> {
249 if (!this.signedTokens) return `dsw.${wakeId}.${randomBytes(32).toString('base64url')}`
250 const installation = await this.streams.guard.snapshot()
251 return this.tokens.sign({ installationId: installation.id, servingEpoch: installation.serving_epoch,
252 tenantId: sub.tenant_id, subscriptionId: sub.id, name: sub.name, wakeId, generation, kind: sub.config.type })
253 }
254 private async issue(client: PoolClient, sub: Sub, deliveryClaim?: string): Promise<{ wake: Wake; streams: readonly Snapshot[] }> {
255 const members = await this.infos(client, sub)
256 const generation = this.signedTokens
257 ? BigInt((await client.query<{ value: string }>(`SELECT nextval('${this.schema}.wake_generations') AS value`)).rows[0]!.value)
258 : BigInt(sub.generation) + 1n
259 if (generation > BigInt(Number.MAX_SAFE_INTEGER)) throw new StreamError(503, 'GENERATION_CAPACITY', 'Subscription generation capacity reached')
260 const id = randomUUID()
261 const token = sub.config.type === 'webhook' ? await this.wakeToken(sub, id, Number(generation)) : null
262 const result = await client.query<Wake>(`INSERT INTO ${this.schema}.subscription_wakes (id, subscription_id, tenant_id, generation, kind, token_hash, token_cipher, state, delivery_claim, delivery_until${this.signedTokens ? ',token_version' : ''})
263 VALUES ($1,$2,$3,$4,$5,$6,$7,'ready',$8,CASE WHEN $8::uuid IS NOT NULL THEN clock_timestamp() + $9 * interval '1 millisecond' ELSE NULL END${this.signedTokens ? ',2' : ''}) RETURNING *`, [id, sub.id, sub.tenant_id, String(generation), sub.config.type,
264 token ? hashToken(token) : null, token ? this.cipher.encrypt(Buffer.from(token), `${this.installationId}:wake:${id}`) : null,
265 sub.config.type === 'webhook' ? deliveryClaim ?? null : null, this.webhookTimeout + 10_000])
266 const snapshots = this.snapshot(members)
267 if (snapshots.length) await client.query(`INSERT INTO ${this.schema}.subscription_wake_streams (wake_id, tenant_id, path, stream_id, link_type, acked_offset, tail_offset)
268 SELECT $1,$2,x.path,x.stream_id,x.link_type,x.acked_offset,x.tail_offset FROM jsonb_to_recordset($3::jsonb) x(path text,stream_id uuid,link_type text,acked_offset text,tail_offset text)`, [id, sub.tenant_id, JSON.stringify(snapshots)])
269 if (sub.config.type === 'pull-wake') {
270 await this.streams.appendWake(client, sub.tenant_id, sub.config.wake_stream!, members.filter((member) => member.tail_offset > member.acked_offset).map((member) => ({
271 type: 'wake', subscription_id: sub.name, stream: member.path, generation: Number(generation), ts: result.rows[0]!.created_at.getTime(),
272 })))
273 await client.query(`UPDATE ${this.schema}.subscription_wakes SET pull_published = true WHERE id = $1`, [id])
274 }
275 const updated = await client.query<Sub>(`UPDATE ${this.schema}.subscriptions SET generation = $2, current_wake = $3,
276 holder = CASE WHEN $4 THEN 'webhook' ELSE NULL END,
277 lease_until = CASE WHEN $4 THEN clock_timestamp() + $5 * interval '1 millisecond' ELSE NULL END,
278 next_work_at = CASE WHEN $4 THEN clock_timestamp() + LEAST($5,$6) * interval '1 millisecond' ELSE NULL END WHERE id = $1 RETURNING *`, [sub.id, String(generation), id, sub.config.type === 'webhook', sub.config.lease_ttl_ms, this.webhookTimeout + 10_000])
279 Object.assign(sub, updated.rows[0])
280 return { wake: { ...result.rows[0]!, pull_published: sub.config.type === 'pull-wake' }, streams: snapshots }
281 }
282 private async claim(tenant: string, name: string, worker: string): Promise<Response> {
283 const outcome = await this.streams.transaction({}, async (client) => {
284 const sub = await this.find(client, tenant, name)
285 if (sub.config.type !== 'pull-wake') throw new StreamError(400, 'INVALID_REQUEST', 'Only pull-wake subscriptions can be claimed')
286 if (sub.holder && sub.lease_valid) return { busy: { code: 'ALREADY_CLAIMED', current_holder: sub.holder, generation: Number(sub.generation) } }
287 if (sub.holder) await this.invalidate(client, sub, 'expired')
288 if (!await this.pending(client, sub)) throw new StreamError(409, 'NO_PENDING_WORK', 'Subscription has no pending work')
289 if (!sub.current_wake) await this.issue(client, sub)
290 const id = sub.current_wake!
291 const token = await this.wakeToken(sub, id, Number(sub.generation))
292 const snapshots = this.snapshot(await this.infos(client, sub))
293 await client.query(`DELETE FROM ${this.schema}.subscription_wake_streams WHERE wake_id = $1`, [id])
294 if (snapshots.length) await client.query(`INSERT INTO ${this.schema}.subscription_wake_streams (wake_id, tenant_id, path, stream_id, link_type, acked_offset, tail_offset)
295 SELECT $1,$2,x.path,x.stream_id,x.link_type,x.acked_offset,x.tail_offset FROM jsonb_to_recordset($3::jsonb) x(path text,stream_id uuid,link_type text,acked_offset text,tail_offset text)`, [id, sub.tenant_id, JSON.stringify(snapshots)])
296 await client.query(`UPDATE ${this.schema}.subscription_wakes SET token_hash = $2, token_cipher = $3${this.signedTokens ? ',token_version=2' : ''} WHERE id = $1`, [id, hashToken(token), this.cipher.encrypt(Buffer.from(token), `${this.installationId}:wake:${id}`)])
297 await client.query(`UPDATE ${this.schema}.subscriptions SET holder = $2, lease_until = clock_timestamp() + $3 * interval '1 millisecond',
298 next_work_at = clock_timestamp() + $3 * interval '1 millisecond' WHERE id = $1`, [sub.id, worker, sub.config.lease_ttl_ms])
299 return { claimed: { wake_id: `w_${id}`, generation: Number(sub.generation), token,
300 streams: snapshots.map((row) => ({ path: row.path, link_type: row.link_type, acked_offset: row.acked_offset, tail_offset: row.tail_offset, has_pending: row.tail_offset > row.acked_offset })), lease_ttl_ms: sub.config.lease_ttl_ms } }
301 })
302 return 'busy' in outcome ? Response.json({ error: outcome.busy }, { status: 409 }) : Response.json(outcome.claimed)
303 }
304 async scoped(request: Request, route: ControlRoute, readBody: () => Promise<Buffer>): Promise<Response> {
305 if (request.method !== 'POST') throw new StreamError(405, 'METHOD_NOT_ALLOWED', 'Subscription tokens require POST')
306 const authorization = request.headers.get('authorization') ?? ''
307 const bearer = authorization.length <= 8199 ? /^Bearer (.+)$/i.exec(authorization) : null
308 if (!bearer) throw new StreamError(401, 'INVALID_TOKEN', 'A subscription-scoped token is required')
309 await this.assertReady()
310 const token = bearer[1]!
311 let wakeId: string, owner: { subscription_id: string; name: string }, claims: WakeTokenClaims | undefined
312 if (this.signedTokens && token.startsWith('dsw.2.')) {
313 claims = this.tokens.verify(token)
314 if (!claims || claims.name !== route.name) throw new StreamError(401, 'INVALID_TOKEN', 'Subscription token is invalid')
315 const installation = await this.streams.guard.snapshot()
316 if (claims.installationId !== installation.id || claims.servingEpoch !== installation.serving_epoch) throw fenced()
317 wakeId = claims.wakeId; owner = { subscription_id: claims.subscriptionId, name: claims.name }
318 } else {
319 const legacy = /^dsw\.([0-9a-f]{8}(?:-[0-9a-f]{4}){3}-[0-9a-f]{12})\.[A-Za-z0-9_-]{43}$/.exec(token)
320 if (!legacy) throw new StreamError(401, 'INVALID_TOKEN', 'Subscription token is invalid')
321 wakeId = legacy[1]!
322 const authenticated = await this.pool.query<{ token_hash: Buffer | null; subscription_id: string; name: string }>(`SELECT w.token_hash, w.subscription_id, s.name
323 FROM ${this.schema}.subscription_wakes w JOIN ${this.schema}.subscriptions s ON s.id = w.subscription_id WHERE w.id = $1
324 ${this.signedTokens ? `UNION ALL SELECT token_hash, subscription_id, subscription_name AS name FROM ${this.schema}.legacy_wake_tokens WHERE wake_id=$1` : ''}`, [wakeId])
325 const row = authenticated.rows[0]
326 if (!row?.token_hash || row.name !== route.name || !timingSafeEqual(row.token_hash, hashToken(token))) throw new StreamError(401, 'INVALID_TOKEN', 'Subscription token is invalid')
327 if (this.signedTokens) throw fenced()
328 owner = row
329 }
330 const body = jsonBody(await readBody())
331 const response = await this.streams.transaction({}, async (client) => {
332 const result = await client.query<Sub>(`WITH locked AS MATERIALIZED (SELECT * FROM ${this.schema}.subscriptions WHERE id = $1 FOR UPDATE)
333 SELECT *, lease_until > clock_timestamp() AS lease_valid FROM locked`, [owner.subscription_id])
334 const sub = result.rows[0]
335 const wake = (await client.query<Wake>(`SELECT * FROM ${this.schema}.subscription_wakes WHERE id = $1`, [wakeId])).rows[0]!
336 if (!sub || !wake || sub.deleted_at || sub.current_wake !== wakeId || !sub.lease_valid || !wake.token_hash || !timingSafeEqual(wake.token_hash, hashToken(token))
337 || (claims && (sub.tenant_id !== claims.tenantId || sub.name !== claims.name || Number(sub.generation) !== claims.generation || sub.config.type !== claims.kind))
338 || body.wake_id !== `w_${wakeId}` || body.generation !== Number(sub.generation)
339 || (route.action === 'callback' ? sub.config.type !== 'webhook' : sub.config.type !== 'pull-wake')) throw fenced()
340 if (route.action !== 'release') await this.applyAcks(client, sub, body.acks)
341 if (route.action === 'release' || body.done === true) {
342 await this.invalidate(client, sub, 'completed')
343 await client.query(`UPDATE ${this.schema}.subscriptions SET retry_count = 0, retry_at = NULL WHERE id = $1`, [sub.id])
344 sub.retry_at = null
345 return { next: await this.queue(client, sub) }
346 }
347 await client.query(`UPDATE ${this.schema}.subscriptions SET lease_until = clock_timestamp() + $2 * interval '1 millisecond',
348 next_work_at = clock_timestamp() + $2 * interval '1 millisecond' WHERE id = $1`, [sub.id, sub.config.lease_ttl_ms])
349 return { next: false }
350 })
351 return route.action === 'release' ? new Response(null, { status: 204 }) : Response.json({ ok: true, next_wake: response.next })
352 }
353 private async applyAcks(client: PoolClient, sub: Sub, input: unknown): Promise<void> {
354 if (input === undefined) return
355 if (!Array.isArray(input) || input.length > this.maxStreams) throw new StreamError(400, 'INVALID_ACKS', 'Invalid ack list')
356 const acks = input.map((item: unknown) => {
357 if (!item || typeof item !== 'object' || Array.isArray(item)) throw new StreamError(400, 'INVALID_ACKS', 'Invalid ack')
358 const raw = item as Record<string, unknown>
359 const path = relativeStreamPath(raw.stream ?? raw.path)
360 if (typeof raw.offset !== 'string') throw new StreamError(409, 'INVALID_OFFSET', 'Ack requires a returned offset')
361 try { parseOffset(raw.offset) } catch { throw new StreamError(409, 'INVALID_OFFSET', 'Ack requires a returned offset') }
362 return { path, offset: raw.offset }
363 })
364 if (new Set(acks.map((ack) => ack.path)).size !== acks.length) throw new StreamError(400, 'INVALID_ACKS', 'A stream may be acked only once per request')
365 const members = await client.query<Member>(`SELECT m.*, COALESCE(s.tail_offset,$3) AS tail_offset FROM ${this.schema}.subscription_members m
366 LEFT JOIN ${this.schema}.streams s ON s.id = m.stream_id WHERE m.subscription_id = $1 AND m.path = ANY($2::text[])`, [sub.id, acks.map((ack) => ack.path), ZERO_OFFSET])
367 const byPath = new Map(members.rows.map((member) => [member.path, member]))
368 const boundaries: { stream_id: string; offset: string }[] = []
369 for (const ack of acks) {
370 const member = byPath.get(ack.path)
371 if (!member || ack.offset < member.acked_offset || ack.offset > member.tail_offset) throw new StreamError(409, 'INVALID_OFFSET', 'Ack regresses the cursor, exceeds the tail, or names an unknown stream')
372 if (member.stream_id && ack.offset !== member.tail_offset && ack.offset !== ZERO_OFFSET) boundaries.push({ stream_id: member.stream_id, offset: ack.offset })
373 }
374 await this.streams.validateAckBoundaries(client, boundaries)
375 if (acks.length) await client.query(`UPDATE ${this.schema}.subscription_members m SET acked_offset = x.offset FROM jsonb_to_recordset($2::jsonb) x(path text,"offset" text)
376 WHERE m.subscription_id = $1 AND m.path = x.path`, [sub.id, JSON.stringify(acks)])
377 }
378 private async markPending(client: PoolClient, sub: Sub): Promise<void> {
379 if (!sub.current_wake) await client.query(`UPDATE ${this.schema}.subscriptions SET next_work_at = COALESCE(retry_at, clock_timestamp()) WHERE id = $1`, [sub.id])
380 }
381 private async applyChange(client: PoolClient, sub: Sub, change: Change, active: { id: string; tail_offset: string } | undefined): Promise<void> {
382 const found = await client.query<Member>(`SELECT * FROM ${this.schema}.subscription_members WHERE subscription_id = $1 AND path = $2`, [sub.id, change.path])
383 let member = found.rows[0]
384 if (active?.id !== change.stream_id) {
385 if (member?.stream_id === change.stream_id) {
386 await this.invalidate(client, sub, 'fenced')
387 if (member.explicit_link) await client.query(`UPDATE ${this.schema}.subscription_members SET stream_id = NULL, acked_offset = $3, glob_link = false WHERE subscription_id = $1 AND path = $2`, [sub.id, change.path, ZERO_OFFSET])
388 else { await client.query(`DELETE FROM ${this.schema}.subscription_members WHERE subscription_id = $1 AND path = $2`, [sub.id, change.path]); await client.query(`UPDATE ${this.schema}.subscriptions SET member_count = member_count - 1 WHERE id = $1`, [sub.id]); sub.member_count-- }
389 await this.queue(client, sub)
390 }
391 return
392 }
393 if (!member && sub.member_count >= this.maxStreams) {
394 const inserted = await client.query(`INSERT INTO ${this.schema}.subscription_pending_links (subscription_id, tenant_id, stream_id, before_offset)
395 VALUES ($1,$2,$3,$4) ON CONFLICT (subscription_id,stream_id) DO UPDATE SET before_offset = LEAST(${this.schema}.subscription_pending_links.before_offset, EXCLUDED.before_offset) RETURNING (xmax = 0) AS inserted`, [sub.id, sub.tenant_id, change.stream_id, change.before_offset])
396 if (inserted.rows[0]?.inserted) await client.query(`UPDATE ${this.schema}.subscriptions SET blocked_members = blocked_members + 1 WHERE id = $1`, [sub.id])
397 return
398 }
399 if (!member) {
400 await this.insertMember(client, sub, change.path, change.stream_id, change.before_offset, false, true)
401 // insertMember may adopt an earlier quota-blocked baseline. Querying the
402 // pending predicate avoids replacing that durable intent with this change.
403 if (await this.pending(client, sub)) await this.markPending(client, sub)
404 return
405 } else if (member.stream_id !== change.stream_id) {
406 if (member.stream_id !== null) await this.invalidate(client, sub, 'fenced')
407 await client.query(`UPDATE ${this.schema}.subscription_members SET stream_id = $3, acked_offset = $4 WHERE subscription_id = $1 AND path = $2`, [sub.id, change.path, change.stream_id, change.before_offset])
408 member.acked_offset = change.before_offset
409 }
410 if (active.tail_offset > member.acked_offset) await this.markPending(client, sub)
411 }
412 private async dispatch(): Promise<number> {
413 return this.streams.transaction({}, async (client) => {
414 const first = await client.query<Change>(`SELECT c.*, s.tenant_id, s.path FROM ${this.schema}.stream_changes c JOIN ${this.schema}.streams s ON s.id = c.stream_id
415 WHERE NOT c.processed AND NOT EXISTS (SELECT 1 FROM ${this.schema}.stream_changes prior WHERE prior.stream_id = c.stream_id AND prior.version < c.version AND NOT prior.processed)
416 ORDER BY c.created_at, c.stream_id, c.version LIMIT 1 FOR UPDATE OF c SKIP LOCKED`)
417 const change = first.rows[0]
418 if (!change) return 0
419 await this.registry(client, change.tenant_id, false)
420 const any = await client.query(`SELECT 1 FROM ${this.schema}.subscriptions WHERE tenant_id = $1 AND deleted_at IS NULL LIMIT 1`, [change.tenant_id])
421 if (!any.rowCount) {
422 // The shared registry lock makes this bulk fast path safe against a
423 // registration whose at-tail backfill has not committed yet.
424 const processed = await client.query(`WITH batch AS (SELECT c.stream_id, c.version FROM ${this.schema}.stream_changes c JOIN ${this.schema}.streams s ON s.id = c.stream_id
425 WHERE NOT c.processed AND s.tenant_id = $1 ORDER BY c.created_at, c.stream_id, c.version LIMIT 128 FOR UPDATE OF c SKIP LOCKED)
426 DELETE FROM ${this.schema}.stream_changes c USING batch b WHERE c.stream_id = b.stream_id AND c.version = b.version`, [change.tenant_id])
427 return processed.rowCount ?? 0
428 }
429 const subscribers = await client.query<Sub>(`SELECT s.* FROM ${this.schema}.subscriptions s WHERE s.tenant_id = $1 AND s.deleted_at IS NULL
430 AND ($2::uuid IS NULL OR s.id > $2) AND ((s.pattern_regex IS NOT NULL AND $3 ~ s.pattern_regex)
431 OR EXISTS (SELECT 1 FROM ${this.schema}.subscription_members m WHERE m.subscription_id = s.id AND m.path = $3))
432 ORDER BY s.id LIMIT 16 FOR UPDATE`, [change.tenant_id, change.fanout_after, change.path])
433 // A complete fan-out in this transaction can cover a bounded committed
434 // prefix of the same stream. The registry lock excludes registration,
435 // and pinning the cutoff before member updates preserves later append intent.
436 // Multi-transaction fan-out retains its original one-record checkpoint.
437 let through = change.version
438 if (change.fanout_after === null && subscribers.rows.length < 16) {
439 const prefix = await client.query<{ version: string }>(`SELECT version FROM ${this.schema}.stream_changes
440 WHERE stream_id = $1 AND version >= $2 AND NOT processed ORDER BY version LIMIT 128`, [change.stream_id, change.version])
441 through = prefix.rows.at(-1)?.version ?? through
442 }
443 const active = await this.activePath(client, change.tenant_id, change.path)
444 for (const sub of subscribers.rows) await this.applyChange(client, sub, change, active)
445 if (subscribers.rows.length < 16) {
446 // Member cursors/pending wake intent and job consumption commit
447 // together. Registration cannot depend on a completed job: it holds
448 // the exclusive registry barrier and establishes its own tail baseline.
449 // Stream versions live on the stream, independently of outbox retention.
450 const processed = await client.query(`DELETE FROM ${this.schema}.stream_changes
451 WHERE stream_id = $1 AND version >= $2 AND version <= $3 AND NOT processed`, [change.stream_id, change.version, through])
452 return processed.rowCount ?? 0
453 }
454 await client.query(`UPDATE ${this.schema}.stream_changes SET fanout_after = $3 WHERE stream_id = $1 AND version = $2`,
455 [change.stream_id, change.version, subscribers.rows.at(-1)!.id])
456 return 1
457 })
458 }
459 private async recoverLink(): Promise<boolean> {
460 return this.streams.transaction({}, async (client) => {
461 const next = await client.query<{ subscription_id: string; stream_id: string; tenant_id: string; path: string; before_offset: string }>(`SELECT q.*, s.path FROM ${this.schema}.subscription_pending_links q JOIN ${this.schema}.streams s ON s.id = q.stream_id
462 WHERE q.due_at <= clock_timestamp() ORDER BY q.due_at, q.subscription_id, q.stream_id LIMIT 1`)
463 const row = next.rows[0]
464 if (!row) return false
465 await this.registry(client, row.tenant_id, false)
466 const sub = (await client.query<Sub>(`SELECT * FROM ${this.schema}.subscriptions WHERE id = $1 FOR UPDATE`, [row.subscription_id])).rows[0]!
467 const still = await client.query(`SELECT 1 FROM ${this.schema}.subscription_pending_links WHERE subscription_id = $1 AND stream_id = $2`, [sub.id, row.stream_id])
468 if (!still.rowCount) return false
469 const active = sub.deleted_at ? undefined : await this.activePath(client, sub.tenant_id, row.path)
470 const member = await client.query(`SELECT 1 FROM ${this.schema}.subscription_members WHERE subscription_id = $1 AND path = $2`, [sub.id, row.path])
471 if (active?.id === row.stream_id && sub.member_count >= this.maxStreams && !member.rowCount) {
472 await client.query(`UPDATE ${this.schema}.subscription_pending_links SET due_at = clock_timestamp() + interval '60 seconds' WHERE subscription_id = $1 AND stream_id = $2`, [sub.id, row.stream_id])
473 return true
474 }
475 if (active?.id === row.stream_id) await this.applyChange(client, sub, { stream_id: row.stream_id, tenant_id: row.tenant_id, path: row.path, before_offset: row.before_offset, after_offset: active.tail_offset, version: '0', kind: 'appended', fanout_after: null, active_stream_id: active.id }, active)
476 const removed = await client.query(`DELETE FROM ${this.schema}.subscription_pending_links WHERE subscription_id = $1 AND stream_id = $2`, [sub.id, row.stream_id])
477 if (removed.rowCount) await client.query(`UPDATE ${this.schema}.subscriptions SET blocked_members = blocked_members - 1 WHERE id = $1`, [sub.id])
478 return true
479 })
480 }
481 private async prepareDelivery(): Promise<{ job?: WebhookJob; worked: boolean }> {
482 let attempted: string | undefined
483 try { return await this.streams.transaction({}, async (client) => {
484 const selected = await client.query<Sub>(`WITH locked AS MATERIALIZED (SELECT * FROM ${this.schema}.subscriptions WHERE deleted_at IS NULL AND next_work_at <= clock_timestamp()
485 ORDER BY next_work_at, id LIMIT 1 FOR UPDATE SKIP LOCKED) SELECT *, lease_until > clock_timestamp() AS lease_valid FROM locked`)
486 const sub = selected.rows[0]
487 if (!sub) return { worked: false }
488 attempted = sub.id
489 if (sub.holder && !sub.lease_valid) await this.invalidate(client, sub, 'expired')
490 if (sub.config.type === 'pull-wake' && sub.current_wake) {
491 // A published wake waits indefinitely for a claim; a held lease is due
492 // only on expiration. New appends do not flood the wake channel.
493 await client.query(`UPDATE ${this.schema}.subscriptions SET next_work_at = lease_until WHERE id = $1`, [sub.id])
494 return { worked: true }
495 }
496 if (!sub.current_wake && !await this.pending(client, sub)) {
497 await client.query(`UPDATE ${this.schema}.subscriptions SET next_work_at = NULL WHERE id = $1`, [sub.id])
498 return { worked: true }
499 }
500 const due = await client.query<{ due: boolean }>('SELECT $1::timestamptz IS NULL OR $1::timestamptz <= clock_timestamp() AS due', [sub.retry_at])
501 if (!due.rows[0]!.due) {
502 await client.query(`UPDATE ${this.schema}.subscriptions SET next_work_at = LEAST(retry_at,lease_until) WHERE id = $1`, [sub.id])
503 return { worked: true }
504 }
505 if (!sub.current_wake) {
506 const claim = randomUUID()
507 const issued = await this.issue(client, sub, claim)
508 if (sub.config.type === 'pull-wake') {
509 await client.query(`UPDATE ${this.schema}.subscriptions SET retry_count = 0, retry_at = NULL WHERE id = $1`, [sub.id])
510 return { worked: true }
511 }
512 return { worked: true, job: { sub, wake: issued.wake, streams: issued.streams, claim } }
513 }
514 const wake = (await client.query<Wake>(`SELECT * FROM ${this.schema}.subscription_wakes WHERE id = $1`, [sub.current_wake])).rows[0]!
515 const available = await client.query<{ available: boolean }>('SELECT $1::timestamptz IS NULL OR $1::timestamptz <= clock_timestamp() AS available', [wake.delivery_until])
516 if (wake.state === 'delivered' || !available.rows[0]!.available) {
517 await client.query(`UPDATE ${this.schema}.subscriptions SET next_work_at = LEAST(lease_until,$2::timestamptz) WHERE id = $1`, [sub.id, wake.delivery_until ?? sub.lease_until])
518 return { worked: true }
519 }
520 const claim = randomUUID()
521 await client.query(`UPDATE ${this.schema}.subscription_wakes SET delivery_claim = $2, delivery_until = clock_timestamp() + $3 * interval '1 millisecond' WHERE id = $1`, [wake.id, claim, this.webhookTimeout + 10_000])
522 await client.query(`UPDATE ${this.schema}.subscriptions SET next_work_at = LEAST(lease_until,clock_timestamp() + $2 * interval '1 millisecond') WHERE id = $1`, [sub.id, this.webhookTimeout + 10_000])
523 const snapshots = await client.query<Snapshot>(`SELECT * FROM ${this.schema}.subscription_wake_streams WHERE wake_id = $1 ORDER BY path`, [wake.id])
524 return { worked: true, job: { sub, wake, claim, streams: snapshots.rows } }
525 }) } catch (error) {
526 if (attempted) await this.streams.transaction({}, async (client) => {
527 const found = await client.query<Sub>(`WITH locked AS MATERIALIZED (SELECT * FROM ${this.schema}.subscriptions WHERE id = $1 AND deleted_at IS NULL FOR UPDATE)
528 SELECT *, lease_until > clock_timestamp() AS lease_valid FROM locked`, [attempted])
529 const sub = found.rows[0]
530 if (!sub) return
531 if (sub.holder && !sub.lease_valid) await this.invalidate(client, sub, 'expired')
532 const delay = this.retryDelay(sub.retry_count)
533 await client.query(`UPDATE ${this.schema}.subscriptions SET retry_count = retry_count + 1, retry_at = clock_timestamp() + $2 * interval '1 millisecond',
534 next_work_at = LEAST(lease_until,clock_timestamp() + $2 * interval '1 millisecond') WHERE id = $1`, [sub.id, delay])
535 }).catch(() => {})
536 throw error
537 }
538 }
539 private retryDelay(count: number): number {
540 const base = Math.min(60_000, 1000 * 2 ** Math.min(count, 16))
541 return Math.min(60_000, Math.round(base * randomInt(800, 1201) / 1000))
542 }
543 private async finishDelivery(job: WebhookJob, result: { ok: boolean; done: boolean }): Promise<void> {
544 await this.streams.transaction({}, async (client) => {
545 const found = await client.query<Sub>(`WITH locked AS MATERIALIZED (SELECT * FROM ${this.schema}.subscriptions WHERE id = $1 FOR UPDATE)
546 SELECT *, lease_until > clock_timestamp() AS lease_valid FROM locked`, [job.sub.id])
547 const sub = found.rows[0]!
548 const wake = (await client.query<Wake>(`SELECT * FROM ${this.schema}.subscription_wakes WHERE id = $1`, [job.wake.id])).rows[0]!
549 if (sub.deleted_at || sub.current_wake !== wake.id || !sub.lease_valid || wake.delivery_claim !== job.claim) return
550 if (!result.ok) {
551 const delay = this.retryDelay(sub.retry_count)
552 await client.query(`UPDATE ${this.schema}.subscription_wakes SET delivery_claim = NULL, delivery_until = NULL WHERE id = $1`, [wake.id])
553 await client.query(`UPDATE ${this.schema}.subscriptions SET retry_count = retry_count + 1, retry_at = clock_timestamp() + $2 * interval '1 millisecond',
554 next_work_at = LEAST(lease_until,clock_timestamp() + $2 * interval '1 millisecond') WHERE id = $1`, [sub.id, delay])
555 return
556 }
557 await client.query(`UPDATE ${this.schema}.subscriptions SET retry_count = 0, retry_at = NULL WHERE id = $1`, [sub.id])
558 sub.retry_at = null
559 if (result.done) {
560 // Ack only the immutable wake snapshot. Later appends stay pending.
561 await client.query(`UPDATE ${this.schema}.subscription_members m SET acked_offset = GREATEST(m.acked_offset,w.tail_offset)
562 FROM ${this.schema}.subscription_wake_streams w WHERE w.wake_id = $1 AND m.subscription_id = $2 AND m.path = w.path AND m.stream_id IS NOT DISTINCT FROM w.stream_id`, [wake.id, sub.id])
563 await this.invalidate(client, sub, 'completed')
564 await this.queue(client, sub)
565 } else {
566 await client.query(`UPDATE ${this.schema}.subscription_wakes SET state = 'delivered', delivery_claim = NULL, delivery_until = NULL WHERE id = $1`, [wake.id])
567 await client.query(`UPDATE ${this.schema}.subscriptions SET next_work_at = lease_until WHERE id = $1`, [sub.id])
568 }
569 })
570 }
571 async maintain(maximum = 8): Promise<{ changes: number; deliveries: number; links: number; worked: boolean }> {
572 await this.assertReady()
573 if (this.shutdown.signal.aborted) return { changes: 0, deliveries: 0, links: 0, worked: false }
574 let changes = 0, deliveries = 0, links = 0
575 let preparedAny = false
576 for (let i = 0; i < maximum; i++) { const n = await this.dispatch(); changes += n; if (!n) break }
577 for (let i = 0; i < maximum; i++) { if (!await this.recoverLink()) break; links++ }
578 for (let i = 0; i < maximum; i++) {
579 let prepared: { job?: WebhookJob; worked: boolean }
580 try { prepared = await this.prepareDelivery() } catch (error) { this.report(error); break }
581 if (!prepared.worked) break
582 preparedAny = true
583 const job = prepared.job
584 if (!job) continue
585 let result = { ok: false, done: false }
586 try {
587 const token = this.cipher.decrypt(job.wake.token_cipher!, `${this.installationId}:wake:${job.wake.id}`).toString('utf8')
588 const body = Buffer.from(JSON.stringify({ subscription_id: job.sub.name, tenant_id: job.sub.tenant_id, wake_id: `w_${job.wake.id}`, generation: Number(job.wake.generation),
589 streams: job.streams.map((row) => ({ path: row.path, link_type: row.link_type, acked_offset: row.acked_offset, tail_offset: row.tail_offset, has_pending: row.tail_offset > row.acked_offset })),
590 callback_url: `${job.sub.public_base_url}/__ds/subscriptions/${encodeURIComponent(job.sub.name)}/callback`, callback_token: token }))
591 result = await deliverWebhook(job.sub.config.webhook!.url, body, await this.signer.signature(body), { allowLocalhost: this.options.allowLocalhostWebhooks ?? false, timeoutMs: this.webhookTimeout, signal: this.shutdown.signal })
592 } catch (error) { if (!this.shutdown.signal.aborted) this.report(error) }
593 await this.finishDelivery(job, result)
594 deliveries++
595 }
596 return { changes, deliveries, links, worked: preparedAny || changes > 0 || links > 0 }
597 }
598 close(): void { this.shutdown.abort() }