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

reclamation.ts

271 lines21.8 KB

1import { randomUUID } from 'node:crypto'
2import type { PoolClient } from 'pg'
3import { ChunkIntegrityError, decodeChunk, MAX_CHUNK_BYTES } from './chunk-codec.js'
4import { StorageCompatibilityError } from './errors.js'
5import type { InstallationGuard } from './installation.js'
6import type { ChunkStorage } from './storage.js'
7import { ChunkNotFoundError } from './storage.js'
8​
9export interface ReclamationResult { reclaimedChunks: number; deletedObjects: number; prunedRows: number; inventoriedObjects: number }
10export const emptyReclamation = (): ReclamationResult => ({ reclaimedChunks: 0, deletedObjects: 0, prunedRows: 0, inventoriedObjects: 0 })
11interface ObjectRow {
12 object_key: string; stream_id: string; chunk_id: string; sha256: string; encoded_bytes: number
13 claim_token: string; claim_epoch: string
15const UUID = '[0-9a-f]{8}(?:-[0-9a-f]{4}){3}-[0-9a-f]{12}'
16const KEY = new RegExp(`^v1/(${UUID})/(${UUID})/(${UUID})/([0-9a-f]{64})\\.ndsc$`)
17const BATCH = 128
18const CLAIM_MS = 120_000
19// Stored cursor order is stable. These rotate work fairly; they are not object
20// lifecycle states, and an empty task must still advance to the next task.
21const COLLECTION_TASKS = ['retire', 'collect', 'pruneChunk', 'inventory', 'verifyOrphan', 'pruneMetadata'] as const
22const METADATA_TASKS = ['wakes', 'subscriptions', 'outbox', 'generation-data', 'generation-rows', 'paths', 'objects', 'pins'] as const
23​
24/** Durable phase rotation is shared across instances, including one-round hints.
25 * Every object operation runs outside SQL. Only explicit operator policy enables it. */
26export class ReclamationManager {
27 constructor(private readonly schema: string, private readonly guard: InstallationGuard, private readonly objects?: ChunkStorage) {}
28 private capabilities(enabled: boolean): void {
29 if (enabled && this.objects && (!this.objects.delete || !this.objects.list)) throw new StorageCompatibilityError('Enabled reclamation requires bounded object inventory and idempotent deletion')
30 }
31 async assertReady(): Promise<void> {
32 const enabled = await this.guard.run({ readOnly: true }, async (client) => (await client.query<{ enabled: boolean }>(`SELECT enabled FROM ${this.schema}.reclamation_policy`)).rows[0]!.enabled)
33 this.capabilities(enabled)
34 }
35 private unreferenced(alias = 's'): string {
36 return `${alias}.deleted_at IS NOT NULL AND ${alias}.ref_count=0 AND NOT ${alias}.edge_active AND NOT ${alias}.cleanup_pending
37 AND NOT EXISTS (SELECT 1 FROM ${this.schema}.paths p WHERE p.active_stream_id=${alias}.id)`
38 }
39 private noSubscriptionRefs(id: string): string {
40 return `NOT EXISTS (SELECT 1 FROM ${this.schema}.subscription_members m WHERE m.stream_id=${id})
41 AND NOT EXISTS (SELECT 1 FROM ${this.schema}.subscription_wake_streams w WHERE w.stream_id=${id})
42 AND NOT EXISTS (SELECT 1 FROM ${this.schema}.subscription_pending_links l WHERE l.stream_id=${id})`
43 }
44 async maintain(pruneUnusedChanges = false): Promise<ReclamationResult & { worked: boolean }> {
45 const result = emptyReclamation()
46 if (pruneUnusedChanges) result.prunedRows = await this.guard.run({}, (client) => this.pruneOutbox(client))
47 const phase = await this.guard.run({}, async (client) => {
48 const policy = (await client.query<{ enabled: boolean; work_phase: number }>(`SELECT enabled,work_phase FROM ${this.schema}.reclamation_policy FOR UPDATE`)).rows[0]!
49 if (!policy.enabled) return undefined
50 this.capabilities(policy.enabled)
51 await client.query(`UPDATE ${this.schema}.reclamation_policy SET work_phase=(work_phase+1)%${COLLECTION_TASKS.length}`)
52 return policy.work_phase
53 })
54 if (phase === undefined) return { ...result, worked: result.prunedRows > 0 }
55 switch (COLLECTION_TASKS[phase]) {
56 case 'retire': result.reclaimedChunks = await this.retire(); break
57 case 'collect': result.deletedObjects = await this.collect(); break
58 case 'pruneChunk': result.prunedRows += await this.pruneChunk(); break
59 case 'inventory': result.inventoriedObjects = await this.inventory(); break
60 case 'verifyOrphan': await this.verifyOrphan(); break
61 case 'pruneMetadata': result.prunedRows += await this.pruneMetadata(); break
62 }
63 // Even an empty phase must not end an unbudgeted round before other phases.
64 return { ...result, worked: true }
65 }
66 private async retire(): Promise<number> {
67 return this.guard.run({}, async (client) => {
68 const stream = (await client.query<{ id: string }>(`SELECT s.id FROM ${this.schema}.streams s WHERE ${this.unreferenced()}
69 AND EXISTS (SELECT 1 FROM ${this.schema}.chunks c WHERE c.stream_id=s.id AND c.retired_at IS NULL)
70 ORDER BY s.deleted_at,s.id LIMIT 1 FOR UPDATE OF s SKIP LOCKED`)).rows[0]
71 if (!stream) return 0
72 const chunks = await client.query<{ id: string; object_key: string | null; sha256: string | null; encoded_bytes: number | null }>(`SELECT id,object_key,sha256,encoded_bytes
73 FROM ${this.schema}.chunks WHERE stream_id=$1 AND retired_at IS NULL ORDER BY id LIMIT 16 FOR UPDATE`, [stream.id])
74 for (const chunk of chunks.rows) {
75 // Preserve deletion retry identity even if its upload intent was lost.
76 if (chunk.object_key) await client.query(`INSERT INTO ${this.schema}.chunk_objects (object_key,stream_id,chunk_id,sha256,encoded_bytes)
77 VALUES ($1,$2,$3,$4,$5) ON CONFLICT (object_key) DO NOTHING`, [chunk.object_key, stream.id, chunk.id, chunk.sha256, chunk.encoded_bytes])
78 await client.query(`UPDATE ${this.schema}.chunks SET retired_at=clock_timestamp(),
79 claim_token=NULL,claim_until=NULL,claim_epoch=claim_epoch+1 WHERE id=$1`, [chunk.id])
80 await client.query(`UPDATE ${this.schema}.chunk_objects SET retired_at=COALESCE(retired_at,clock_timestamp()),
81 orphan_candidate=false
82 WHERE chunk_id=$1`, [chunk.id])
83 }
84 return chunks.rows.length
85 })
86 }
87 private async claim(orphan: boolean): Promise<ObjectRow | undefined> {
88 return this.guard.run({}, async (client) => {
89 const candidate = (await client.query<{ object_key: string }>(`SELECT o.object_key FROM ${this.schema}.chunk_objects o
90 WHERE o.quarantine_reason IS NULL AND o.next_attempt_at<=clock_timestamp() AND (o.claim_until IS NULL OR o.claim_until<=clock_timestamp())
91 AND ${orphan ? `o.orphan_candidate AND o.retired_at IS NULL` : `NOT o.orphan_candidate AND o.retired_at IS NOT NULL AND o.collected_at IS NULL
92 AND NOT EXISTS (SELECT 1 FROM ${this.schema}.chunks c WHERE c.id=o.chunk_id AND c.retired_at IS NULL)
93 AND NOT EXISTS (SELECT 1 FROM ${this.schema}.replay_pins p WHERE p.chunk_id=o.chunk_id AND p.expires_at>clock_timestamp())`}
94 ORDER BY ${orphan ? 'o.next_attempt_at,o.created_at' : 'o.retired_at'},o.object_key LIMIT 1 FOR UPDATE OF o SKIP LOCKED`)).rows[0]
95 if (!candidate) return undefined
96 return (await client.query<ObjectRow>(`UPDATE ${this.schema}.chunk_objects SET claim_token=$2,claim_epoch=claim_epoch+1,
97 claim_until=clock_timestamp()+$3*interval '1 millisecond' WHERE object_key=$1 RETURNING *`, [candidate.object_key, randomUUID(), CLAIM_MS])).rows[0]!
98 })
99 }
100 private async release(claim: ObjectRow): Promise<void> {
101 await this.guard.run({}, async (client) => {
102 await client.query(`UPDATE ${this.schema}.chunk_objects SET claim_token=NULL,claim_until=NULL,next_attempt_at=clock_timestamp()+interval '5 seconds'
103 WHERE object_key=$1 AND claim_token=$2 AND claim_epoch=$3`, [claim.object_key, claim.claim_token, claim.claim_epoch])
104 }).catch(() => {})
105 }
106 private async collect(): Promise<number> {
107 if (!this.objects) return 0
108 const claim = await this.claim(false)
109 if (!claim) return 0
110 try {
111 await this.guard.check()
112 await this.objects.delete!(claim.object_key)
113 return await this.guard.run({}, async (client) => {
114 const removed = await client.query(`UPDATE ${this.schema}.chunk_objects SET collected_at=clock_timestamp(),claim_token=NULL,claim_until=NULL
115 WHERE object_key=$1 AND claim_token=$2 AND claim_epoch=$3 AND claim_until>clock_timestamp() AND retired_at IS NOT NULL
116 AND NOT EXISTS (SELECT 1 FROM ${this.schema}.replay_pins p WHERE p.chunk_id=chunk_objects.chunk_id AND p.expires_at>clock_timestamp())`,
117 [claim.object_key, claim.claim_token, claim.claim_epoch])
118 return removed.rowCount ?? 0
119 })
120 } catch (error) { await this.release(claim); throw error }
121 }
122 private async inventory(): Promise<number> {
123 if (!this.objects) return 0
124 const before = await this.guard.run({ readOnly: true }, async (client) => (await client.query<{ inventory_cursor: string | null }>(`SELECT inventory_cursor FROM ${this.schema}.reclamation_policy
125 WHERE inventory_cursor IS NOT NULL OR inventory_completed_at IS NULL OR inventory_completed_at<clock_timestamp()-interval '5 minutes'`)).rows[0])
126 if (!before) return 0
127 const identity = await this.guard.snapshot(), prefix = `v1/${identity.id}/`
128 const page = await this.objects.list!(prefix, before.inventory_cursor, BATCH)
129 if (page.objects.length > BATCH || (page.cursor !== null && (typeof page.cursor !== 'string' || !page.cursor || page.cursor.length > 8192 || page.cursor === before.inventory_cursor))) {
130 throw new StorageCompatibilityError('Object inventory exceeded its bounded page/cursor contract')
131 }
132 return this.guard.run({}, async (client) => {
133 const policy = (await client.query<{ inventory_cursor: string | null }>(`SELECT inventory_cursor FROM ${this.schema}.reclamation_policy FOR UPDATE`)).rows[0]!
134 if (policy.inventory_cursor !== before.inventory_cursor) return 0
135 for (const item of page.objects) {
136 const match = KEY.exec(item.key)
137 if (!match || match[1] !== identity.id || !Number.isSafeInteger(item.size) || item.size < 1 || item.size > MAX_CHUNK_BYTES) continue
138 await client.query(`INSERT INTO ${this.schema}.chunk_objects (object_key,stream_id,chunk_id,sha256,encoded_bytes,orphan_candidate)
139 VALUES ($1,$2,$3,$4,$5,true) ON CONFLICT (object_key) DO UPDATE SET orphan_candidate=true,retired_at=NULL,collected_at=NULL,
140 claim_token=NULL,claim_until=NULL,claim_epoch=chunk_objects.claim_epoch+1 WHERE chunk_objects.collected_at IS NOT NULL`, [item.key, match[2], match[3], match[4], item.size])
141 }
142 await client.query(`UPDATE ${this.schema}.reclamation_policy SET inventory_cursor=$1,
143 inventory_completed_at=CASE WHEN $1::text IS NULL THEN clock_timestamp() ELSE inventory_completed_at END`, [page.cursor])
144 return page.objects.length
145 })
146 }
147 private async verifyOrphan(): Promise<void> {
148 if (!this.objects) return
149 const claim = await this.claim(true)
150 if (!claim) return
151 try {
152 const identity = await this.guard.snapshot()
153 let valid = true, missing = false
154 try {
155 const match = KEY.exec(claim.object_key)
156 if (!match || match[1] !== identity.id || match[2] !== claim.stream_id || match[3] !== claim.chunk_id || match[4] !== claim.sha256) throw new ChunkIntegrityError('Invalid inventory identity')
157 const bytes = await this.objects.get(claim.object_key, claim.encoded_bytes)
158 if (bytes.length !== claim.encoded_bytes) throw new ChunkIntegrityError('Invalid inventory length')
159 decodeChunk(bytes, { installationId: identity.id, streamId: claim.stream_id, chunkId: claim.chunk_id }, claim.sha256)
160 } catch (error) {
161 if (error instanceof ChunkNotFoundError) missing = true
162 else if (error instanceof ChunkIntegrityError) valid = false
163 else throw error
164 }
165 await this.guard.run({}, async (client) => {
166 // Match retirement's stream -> chunk -> object order. An active chunk
167 // (including a FROZEN upload) retains every validated immutable intent.
168 await client.query(`SELECT id FROM ${this.schema}.streams WHERE id=$1 FOR UPDATE`, [claim.stream_id])
169 const chunk = (await client.query<{ retired_at: Date | null }>(`SELECT retired_at FROM ${this.schema}.chunks WHERE id=$1 FOR UPDATE`, [claim.chunk_id])).rows[0]
170 await client.query(`UPDATE ${this.schema}.chunk_objects SET orphan_candidate=false,quarantine_reason=$4,
171 retired_at=CASE WHEN $5 THEN clock_timestamp() ELSE NULL END,
172 collected_at=CASE WHEN $5 AND $6 THEN clock_timestamp() ELSE NULL END,claim_token=NULL,claim_until=NULL
173 WHERE object_key=$1 AND claim_token=$2 AND claim_epoch=$3 AND claim_until>clock_timestamp()`,
174 [claim.object_key, claim.claim_token, claim.claim_epoch, valid ? null : 'Invalid immutable chunk envelope', valid && (!chunk || chunk.retired_at !== null), missing])
175 })
176 } catch (error) { await this.release(claim); throw error }
177 }
178 private async pruneChunk(): Promise<number> {
179 return this.guard.run({}, async (client) => {
180 const chunk = (await client.query<{ id: string; stream_id: string; start_offset: string; end_offset: string; state: string }>(`SELECT c.id,c.stream_id,c.start_offset,c.end_offset,c.state FROM ${this.schema}.chunks c JOIN ${this.schema}.streams s ON s.id=c.stream_id
181 WHERE c.retired_at IS NOT NULL AND ${this.unreferenced()} AND ${this.noSubscriptionRefs('s.id')}
182 AND NOT EXISTS (SELECT 1 FROM ${this.schema}.streams child WHERE child.source_id=s.id)
183 AND NOT EXISTS (SELECT 1 FROM ${this.schema}.stream_changes j WHERE j.stream_id=s.id)
184 AND NOT EXISTS (SELECT 1 FROM ${this.schema}.replay_pins p WHERE p.chunk_id=c.id AND p.expires_at>clock_timestamp())
185 AND NOT EXISTS (SELECT 1 FROM ${this.schema}.chunk_objects o WHERE o.chunk_id=c.id AND o.collected_at IS NULL)
186 ORDER BY c.retired_at,c.id LIMIT 1 FOR UPDATE OF c SKIP LOCKED`)).rows[0]
187 if (!chunk) return 0
188 // Keep ON DELETE CASCADE from turning one chunk into an unbounded pin
189 // deletion after a period of failed reader cleanup. Valid pins already
190 // exclude the candidate; locked/remaining expired pins defer its removal.
191 const pins = await client.query(`WITH batch AS (SELECT id,chunk_id FROM ${this.schema}.replay_pins WHERE chunk_id=$1 AND expires_at<=clock_timestamp()
192 ORDER BY expires_at,id LIMIT ${BATCH} FOR UPDATE SKIP LOCKED) DELETE FROM ${this.schema}.replay_pins p USING batch b WHERE p.id=b.id AND p.chunk_id=b.chunk_id`, [chunk.id])
193 const frames = chunk.state==='frozen' ? await client.query(`WITH batch AS (SELECT end_offset FROM ${this.schema}.appends
194 WHERE stream_id=$1 AND end_offset>$2 AND end_offset<=$3 ORDER BY end_offset LIMIT ${BATCH})
195 DELETE FROM ${this.schema}.appends a USING batch b WHERE a.stream_id=$1 AND a.end_offset=b.end_offset`, [chunk.stream_id,chunk.start_offset,chunk.end_offset]) : undefined
196 const removed = await client.query(`DELETE FROM ${this.schema}.chunks c WHERE id=$1 AND NOT EXISTS (SELECT 1 FROM ${this.schema}.appends a
197 WHERE a.stream_id=c.stream_id AND a.end_offset>c.start_offset AND a.end_offset<=c.end_offset)
198 AND NOT EXISTS (SELECT 1 FROM ${this.schema}.replay_pins p WHERE p.chunk_id=c.id)`, [chunk.id])
199 return (pins.rowCount ?? 0) + (frames?.rowCount ?? 0) + (removed.rowCount ?? 0)
200 })
201 }
202 private async pruneMetadata(): Promise<number> {
203 return this.guard.run({}, async (client) => {
204 const phase = (await client.query<{ metadata_phase: number }>(`SELECT metadata_phase FROM ${this.schema}.reclamation_policy FOR UPDATE`)).rows[0]!.metadata_phase
205 await client.query(`UPDATE ${this.schema}.reclamation_policy SET metadata_phase=(metadata_phase+1)%${METADATA_TASKS.length}`)
206 const task = METADATA_TASKS[phase]
207 if (task === 'wakes') return this.pruneWake(client)
208 if (task === 'subscriptions') return (await client.query(`WITH batch AS (SELECT id FROM ${this.schema}.subscriptions s WHERE deleted_at IS NOT NULL
209 AND current_wake IS NULL AND NOT EXISTS (SELECT 1 FROM ${this.schema}.subscription_wakes w WHERE w.subscription_id=s.id)
210 AND NOT EXISTS (SELECT 1 FROM ${this.schema}.subscription_members m WHERE m.subscription_id=s.id)
211 AND NOT EXISTS (SELECT 1 FROM ${this.schema}.subscription_pending_links l WHERE l.subscription_id=s.id)
212 ORDER BY deleted_at,id LIMIT ${BATCH} FOR UPDATE SKIP LOCKED) DELETE FROM ${this.schema}.subscriptions s USING batch b WHERE s.id=b.id`)).rowCount ?? 0
213 if (task === 'outbox') return this.pruneOutbox(client)
214 if (task === 'generation-data' || task === 'generation-rows') return this.pruneGeneration(client, task === 'generation-rows')
215 if (task === 'paths') return (await client.query(`WITH batch AS (SELECT p.tenant_id,p.path FROM ${this.schema}.paths p WHERE active_stream_id IS NULL
216 AND NOT EXISTS (SELECT 1 FROM ${this.schema}.streams s WHERE s.tenant_id=p.tenant_id AND s.path=p.path)
217 ORDER BY p.tenant_id,p.path LIMIT ${BATCH} FOR UPDATE OF p SKIP LOCKED)
218 DELETE FROM ${this.schema}.paths p USING batch b WHERE p.tenant_id=b.tenant_id AND p.path=b.path`)).rowCount ?? 0
219 if (task === 'objects') return (await client.query(`WITH batch AS (SELECT object_key FROM ${this.schema}.chunk_objects WHERE collected_at IS NOT NULL
220 AND claim_token IS NULL ORDER BY collected_at,object_key LIMIT ${BATCH} FOR UPDATE SKIP LOCKED)
221 DELETE FROM ${this.schema}.chunk_objects o USING batch b WHERE o.object_key=b.object_key`)).rowCount ?? 0
222 return (await client.query(`WITH batch AS (SELECT id,chunk_id FROM ${this.schema}.replay_pins WHERE expires_at<=clock_timestamp() ORDER BY expires_at,id LIMIT ${BATCH} FOR UPDATE SKIP LOCKED)
223 DELETE FROM ${this.schema}.replay_pins p USING batch b WHERE p.id=b.id AND p.chunk_id=b.chunk_id`)).rowCount ?? 0
224 })
225 }
226 private async pruneWake(client: PoolClient): Promise<number> {
227 const candidate = (await client.query<{ id: string; subscription_id: string }>(`SELECT w.id,w.subscription_id FROM ${this.schema}.subscription_wakes w
228 JOIN ${this.schema}.subscriptions s ON s.id=w.subscription_id WHERE w.state IN ('completed','expired','fenced')
229 AND s.current_wake IS DISTINCT FROM w.id AND (w.delivery_until IS NULL OR w.delivery_until<=clock_timestamp())
230 ORDER BY w.created_at,w.id LIMIT 1`)).rows[0]
231 if (!candidate) return 0
232 const sub = await client.query(`SELECT id FROM ${this.schema}.subscriptions WHERE id=$1 AND current_wake IS DISTINCT FROM $2 FOR UPDATE SKIP LOCKED`, [candidate.subscription_id, candidate.id])
233 if (!sub.rowCount) return 0
234 const snapshots = await client.query(`WITH batch AS (SELECT wake_id,path FROM ${this.schema}.subscription_wake_streams WHERE wake_id=$1 ORDER BY path LIMIT ${BATCH})
235 DELETE FROM ${this.schema}.subscription_wake_streams w USING batch b WHERE w.wake_id=b.wake_id AND w.path=b.path`, [candidate.id])
236 const wakes = await client.query(`DELETE FROM ${this.schema}.subscription_wakes w WHERE id=$1 AND state IN ('completed','expired','fenced')
237 AND NOT EXISTS (SELECT 1 FROM ${this.schema}.subscription_wake_streams x WHERE x.wake_id=w.id)`, [candidate.id])
238 return (snapshots.rowCount ?? 0) + (wakes.rowCount ?? 0)
239 }
240 private async pruneOutbox(client: PoolClient): Promise<number> {
241 const candidate = (await client.query<{ tenant_id: string }>(`SELECT s.tenant_id FROM ${this.schema}.stream_changes c JOIN ${this.schema}.streams s ON s.id=c.stream_id
242 WHERE (NOT EXISTS (SELECT 1 FROM ${this.schema}.subscriptions x WHERE x.tenant_id=s.tenant_id AND x.deleted_at IS NULL))
243 ORDER BY c.created_at,c.stream_id,c.version LIMIT 1`)).rows[0]
244 if (!candidate) return 0
245 await client.query(`SELECT pg_advisory_xact_lock_shared(hashtextextended($1,0))`, [`durable-streams:subscription-registry:${this.schema}:${candidate.tenant_id}`])
246 return (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
247 WHERE s.tenant_id=$1 AND (NOT EXISTS (SELECT 1 FROM ${this.schema}.subscriptions x WHERE x.tenant_id=s.tenant_id AND x.deleted_at IS NULL))
248 ORDER BY c.created_at,c.stream_id,c.version LIMIT ${BATCH} FOR UPDATE OF c SKIP LOCKED)
249 DELETE FROM ${this.schema}.stream_changes c USING batch b WHERE c.stream_id=b.stream_id AND c.version=b.version`, [candidate.tenant_id])).rowCount ?? 0
250 }
251 private async pruneGeneration(client: PoolClient, final: boolean): Promise<number> {
252 const stream = (await client.query<{ id: string }>(`SELECT s.id FROM ${this.schema}.streams s WHERE ${this.unreferenced()} AND ${this.noSubscriptionRefs('s.id')}
253 AND NOT EXISTS (SELECT 1 FROM ${this.schema}.streams child WHERE child.source_id=s.id)
254 AND NOT EXISTS (SELECT 1 FROM ${this.schema}.chunks c WHERE c.stream_id=s.id)
255 AND NOT EXISTS (SELECT 1 FROM ${this.schema}.stream_changes j WHERE j.stream_id=s.id)
256 ${final ? `AND NOT EXISTS (SELECT 1 FROM ${this.schema}.appends a WHERE a.stream_id=s.id)
257 AND NOT EXISTS (SELECT 1 FROM ${this.schema}.producers p WHERE p.stream_id=s.id)` : `AND (EXISTS (SELECT 1 FROM ${this.schema}.appends a WHERE a.stream_id=s.id) OR EXISTS (SELECT 1 FROM ${this.schema}.producers p WHERE p.stream_id=s.id))`}
258 ORDER BY s.deleted_at,s.id LIMIT 1 FOR UPDATE OF s SKIP LOCKED`)).rows[0]
259 if (!stream) return 0
260 if (final) {
261 await client.query(`DELETE FROM ${this.schema}.stream_expirations WHERE stream_id=$1`, [stream.id])
262 await client.query(`DELETE FROM ${this.schema}.hot_chunks WHERE stream_id=$1`, [stream.id])
263 return (await client.query(`DELETE FROM ${this.schema}.streams WHERE id=$1`, [stream.id])).rowCount ?? 0
264 }
265 const frames = await client.query(`WITH batch AS (SELECT end_offset FROM ${this.schema}.appends WHERE stream_id=$1 ORDER BY end_offset LIMIT ${BATCH})
266 DELETE FROM ${this.schema}.appends a USING batch b WHERE a.stream_id=$1 AND a.end_offset=b.end_offset`, [stream.id])
267 const producers = await client.query(`WITH batch AS (SELECT producer_id FROM ${this.schema}.producers WHERE stream_id=$1 ORDER BY producer_id LIMIT ${BATCH})
268 DELETE FROM ${this.schema}.producers p USING batch b WHERE p.stream_id=$1 AND p.producer_id=b.producer_id`, [stream.id])
269 return (frames.rowCount ?? 0) + (producers.rowCount ?? 0)
270 }