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

subscription-store.ts

597 lines48.1 KB

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