Open History to see the last commit
1import { randomUUID } from 'node:crypto'
2import type { Pool } from 'pg'
3import { decodeChunk } from './chunk-codec.js'
4import { StorageCompatibilityError } from './errors.js'
5import type { InstallationIdentity } from './installation.js'
6import { validateSchema } from './path.js'
7import type { ChunkStorage } from './storage.js'
8import { transaction } from './transaction.js'
9import { SubscriptionSigner } from './subscription-crypto.js'
10import type { SubscriptionKeyring } from './subscription-crypto.js'
11
12export type { InstallationIdentity } from './installation.js'
13export interface OperationTarget { readonly schema?: string }
14export interface RecoveryOptions extends OperationTarget {
15 /** Persist this UUID before calling; reuse it after a lost response. */
16 readonly operationId: string
17 readonly expectedInstallationId: string
18 readonly expectedServingEpoch: string
19 /** A stable deployment identity, normally the consumer's Neon branch ID. */
20 readonly environmentId: string
21 /** The target branch/bucket. Every sealed object must already exist there. */
22 readonly storageIdentity: string | null
23 /** Set when adopting to a new server URL; omit to retain the original URL. */
24 readonly publicBaseUrl?: string
25}
26interface RecoveryFields {
27 recovery_token: string | null
28 recovery_source_epoch: string | null
29 completed_recovery_token: string | null
30 recovery_target_public_base_url: string | null
31 recovery_target_environment: string | null
32 recovery_target_storage: string | null
33 recovery_cursor: string | null
34 recovery_verified: string
35 recovery_complete: boolean
36}
37type RecoveringFields = RecoveryFields & { recovery_token: string; recovery_source_epoch: string; recovery_target_environment: string }
38type ActiveInstallation = InstallationIdentity & RecoveryFields & { serving_state: 'active'; recovery_token: null }
39type VerifyingRecovery = InstallationIdentity & RecoveringFields & { serving_state: 'recovering'; recovery_complete: false }
40type VerifiedRecovery = InstallationIdentity & RecoveringFields & { serving_state: 'recovering'; recovery_complete: true }
41type RecoveryRow = ActiveInstallation | VerifyingRecovery | VerifiedRecovery
42function target(options: OperationTarget): string { return validateSchema(options.schema ?? 'durable_streams') }
43function validRecovery(row: RecoveryRow | undefined, token: string): asserts row is VerifyingRecovery | VerifiedRecovery {
44 if (!row || row.serving_state !== 'recovering' || row.recovery_token !== token) throw new StorageCompatibilityError('Recovery token is stale or installation is active')
45}
46/** Administrative data-plane operation; never expose through the stream API. */
47export async function inspectInstallation(pool: Pool, options: OperationTarget = {}): Promise<InstallationIdentity> {
48 const result = await pool.query<InstallationIdentity>(`SELECT id, serving_epoch, serving_state, environment_id, storage_identity FROM ${target(options)}.installation`)
49 if (result.rows.length !== 1) throw new StorageCompatibilityError('Missing installation identity')
50 return result.rows[0]!
51}
52
53export interface ReclamationOptions extends OperationTarget {
54 /** An active, explicitly quiesced recovery operation from beginRecovery. */
55 readonly token: string
56 /** Deleted object history must be recoverable by the provider or a matching backup. */
57 readonly enabled: boolean
58}
59export type ReclamationStatus = { readonly supported: false } | {
60 readonly supported: true
61 readonly enabled: boolean
62 readonly inventoryCompletedAt: Date | null
63 readonly backlog?: { readonly pendingDeletes: number; readonly orphanCandidates: number; readonly quarantinedObjects: number; readonly oldestRetiredAt: Date | null }
64}
65/** Operator diagnostics. Backlog aggregates are opt-in; use a separate pool. */
66export async function inspectReclamation(pool: Pool, options: OperationTarget & { readonly includeBacklog?: boolean } = {}): Promise<ReclamationStatus> {
67 const schema = target(options)
68 if (options.includeBacklog !== undefined && typeof options.includeBacklog !== 'boolean') throw new TypeError('Invalid reclamation diagnostics selection')
69 return transaction(pool, { readOnly: true, repeatableRead: true }, async (client) => {
70 const policy = (await client.query<{ enabled: boolean; inventory_completed_at: Date | null }>(`SELECT enabled,inventory_completed_at FROM ${schema}.reclamation_policy`)).rows[0]!
71 const result = { supported: true as const, enabled: policy.enabled, inventoryCompletedAt: policy.inventory_completed_at }
72 if (!options.includeBacklog) return result
73 const counts = (await client.query<{ pending: string; orphans: string; quarantined: string; oldest: Date | null }>(`SELECT
74 count(*) FILTER (WHERE retired_at IS NOT NULL AND collected_at IS NULL) AS pending,
75 count(*) FILTER (WHERE orphan_candidate) AS orphans,
76 count(*) FILTER (WHERE quarantine_reason IS NOT NULL) AS quarantined,
77 min(retired_at) FILTER (WHERE retired_at IS NOT NULL AND collected_at IS NULL) AS oldest FROM ${schema}.chunk_objects`)).rows[0]!
78 return { ...result, backlog: { pendingDeletes: Number(counts.pending), orphanCandidates: Number(counts.orphans), quarantinedObjects: Number(counts.quarantined), oldestRetiredAt: counts.oldest } }
79 })
80}
81/** Once per stopped operation; retry with identical settings after lost replies.
82 * The library protects current references/readers. Historical recovery requires
83 * restoring the matching object history, including subsequently deleted keys. */
84export async function configureReclamation(pool: Pool, options: ReclamationOptions): Promise<void> {
85 const schema = target(options)
86 if (typeof options.enabled !== 'boolean') throw new TypeError('Invalid reclamation setting')
87 if ('recoveryWindowMs' in options || 'safetyMarginMs' in options) throw new TypeError('Recovery retention is provider-owned; remove the legacy reclamation policy options')
88 await transaction(pool, {}, async (client) => {
89 const row = (await client.query<RecoveryRow>(`SELECT * FROM ${schema}.installation FOR UPDATE`)).rows[0]
90 validRecovery(row, options.token)
91 const policy = (await client.query<{ configured_recovery_token: string | null; enabled: boolean }>(`SELECT configured_recovery_token,enabled FROM ${schema}.reclamation_policy FOR UPDATE`)).rows[0]!
92 if (policy.configured_recovery_token === options.token) {
93 if (policy.enabled !== options.enabled) throw new StorageCompatibilityError('This recovery operation already configured a different reclamation setting')
94 return
95 }
96 await client.query(`UPDATE ${schema}.reclamation_policy SET enabled=$1,configured_recovery_token=$2,inventory_cursor=NULL`, [options.enabled, options.token])
97 })
98}
99
100/** Waits for existing writer transactions, changes epoch, and stops admission. */
101export async function beginRecovery(pool: Pool, options: RecoveryOptions): Promise<{ token: string; servingEpoch: string }> {
102 const schema = target(options)
103 if (!/^[0-9a-f]{8}(?:-[0-9a-f]{4}){3}-[0-9a-f]{12}$/i.test(options.operationId)) throw new TypeError('Recovery operationId must be a UUID')
104 if (!options.environmentId || Buffer.byteLength(options.environmentId) > 2048
105 || (options.storageIdentity !== null && (!options.storageIdentity || options.storageIdentity.length > 2048))) throw new TypeError('Invalid recovery destination')
106 let publicBase: string | null = null
107 if (options.publicBaseUrl !== undefined) {
108 const url = new URL(options.publicBaseUrl)
109 if (!['https:', 'http:'].includes(url.protocol) || url.username || url.password || url.search || url.hash || url.pathname.endsWith('/')) throw new TypeError('Invalid recovery public base URL')
110 publicBase = url.href
111 }
112 return transaction(pool, {}, async (client) => {
113 // FOR UPDATE conflicts with all writer KEY SHARE guards. Do not replace
114 // this with an ordinary UPDATE (which would take NO KEY UPDATE).
115 const current = (await client.query<RecoveryRow>(`SELECT * FROM ${schema}.installation FOR UPDATE`)).rows[0]
116 if (current?.serving_state === 'recovering' && current.id === options.expectedInstallationId && current.recovery_token === options.operationId
117 && current.recovery_source_epoch === options.expectedServingEpoch && current.recovery_target_environment === options.environmentId
118 && current.recovery_target_storage === options.storageIdentity && current.recovery_target_public_base_url === publicBase) {
119 return { token: options.operationId, servingEpoch: current.serving_epoch }
120 }
121 if (!current || current.id !== options.expectedInstallationId || current.serving_epoch !== options.expectedServingEpoch || current.serving_state !== 'active') {
122 throw new StorageCompatibilityError('Installation changed; inspect its current identity before starting recovery')
123 }
124 if (current.storage_identity !== null && options.storageIdentity === null) throw new StorageCompatibilityError('A tiered installation requires object storage during recovery')
125 const token = options.operationId, servingEpoch = randomUUID()
126 await client.query(`UPDATE ${schema}.installation SET serving_state = 'recovering', serving_epoch = $1, recovery_token = $2, recovery_source_epoch = $6,
127 recovery_target_environment = $3, recovery_target_storage = $4, recovery_target_public_base_url = $5, recovery_cursor = NULL, recovery_verified = 0,
128 recovery_complete = false, recovery_started_at = clock_timestamp()`, [servingEpoch, token, options.environmentId, options.storageIdentity, publicBase, options.expectedServingEpoch])
129 return { token, servingEpoch }
130 })
131}
132
133export interface VerifyRecoveryOptions extends OperationTarget {
134 readonly token: string
135 readonly objects?: ChunkStorage
136 readonly keyring?: SubscriptionKeyring
137 readonly maxChunks?: number
138}
139/** Resumable, checksum-validated reconciliation. Object I/O holds no SQL lock. */
140export async function verifyRecovery(pool: Pool, options: VerifyRecoveryOptions): Promise<{ complete: boolean; verified: number }> {
141 const schema = target(options), maximum = options.maxChunks ?? 16
142 if (!Number.isSafeInteger(maximum) || maximum < 1 || maximum > 128) throw new RangeError('Invalid recovery batch size')
143 const before = (await pool.query<RecoveryRow>(`SELECT * FROM ${schema}.installation`)).rows[0]
144 validRecovery(before, options.token)
145 if ((options.objects?.identity ?? null) !== before.recovery_target_storage) throw new StorageCompatibilityError('Recovery object storage differs from the recorded target')
146 const signing = await pool.query(`SELECT 1 FROM ${schema}.webhook_signing_keys WHERE active`)
147 if (signing.rowCount) {
148 if (!options.keyring) throw new StorageCompatibilityError('Recovery requires the subscription wrapping keyring')
149 await new SubscriptionSigner(pool, options.schema ?? 'durable_streams', options.keyring).signature(Buffer.alloc(0))
150 }
151 if (before.recovery_complete) return { complete: true, verified: Number(before.recovery_verified) }
152 const manifests = await pool.query<{ id: string; stream_id: string; object_key: string; sha256: string; encoded_bytes: number; frame_count: number; payload_bytes: string; start_offset: string; end_offset: string; block_directory: Buffer }>(
153 `SELECT * FROM ${schema}.chunks WHERE state = 'sealed' AND retired_at IS NULL
154 AND ($1::uuid IS NULL OR id > $1) ORDER BY id LIMIT $2`, [before.recovery_cursor, maximum])
155 for (const chunk of manifests.rows) {
156 if (!options.objects) throw new StorageCompatibilityError('Sealed manifests require target object storage')
157 const bytes = await options.objects.get(chunk.object_key, chunk.encoded_bytes)
158 if (bytes.length !== chunk.encoded_bytes) throw new StorageCompatibilityError('Recovery object length differs from manifest')
159 const frames = decodeChunk(bytes, { installationId: before.id, streamId: chunk.stream_id, chunkId: chunk.id }, chunk.sha256).frames
160 if (!bytes.subarray(68, 68 + bytes.readUInt32BE(64)).equals(chunk.block_directory)) throw new StorageCompatibilityError('Recovery object differs from block directory')
161 if (frames.length !== chunk.frame_count || frames[0]?.start !== chunk.start_offset || frames.at(-1)?.end !== chunk.end_offset
162 || BigInt(frames.reduce((n, frame) => n + frame.payload.length, 0)) !== BigInt(chunk.payload_bytes)) throw new StorageCompatibilityError('Recovery object frames differ from manifest')
163 }
164 return transaction(pool, {}, async (client) => {
165 const current = (await client.query<RecoveryRow>(`SELECT * FROM ${schema}.installation FOR UPDATE`)).rows[0]
166 validRecovery(current, options.token)
167 if (current.recovery_cursor !== before.recovery_cursor || current.recovery_verified !== before.recovery_verified) throw new StorageCompatibilityError('Recovery batch advanced concurrently; retry from its persisted cursor')
168 const complete = manifests.rows.length < maximum
169 const verified = Number(before.recovery_verified) + manifests.rows.length
170 await client.query(`UPDATE ${schema}.installation SET recovery_cursor = $1, recovery_verified = $2, recovery_complete = $3`,
171 [manifests.rows.at(-1)?.id ?? before.recovery_cursor, verified, complete])
172 return { complete, verified }
173 })
174}
175
176/** Activates only a completed reconciliation and fences all restored wakes. */
177export async function finishRecovery(pool: Pool, options: OperationTarget & { readonly token: string }): Promise<InstallationIdentity> {
178 const schema = target(options)
179 return transaction(pool, { timeoutMs: 60_000 }, async (client) => {
180 const row = (await client.query<RecoveryRow>(`SELECT * FROM ${schema}.installation FOR UPDATE`)).rows[0]
181 if (row?.serving_state === 'active' && row.completed_recovery_token === options.token) {
182 return { id: row.id, serving_epoch: row.serving_epoch, serving_state: row.serving_state, environment_id: row.environment_id, storage_identity: row.storage_identity }
183 }
184 validRecovery(row, options.token)
185 if (!row.recovery_complete) throw new StorageCompatibilityError('Verify every sealed manifest before activating this installation')
186 const readers = await client.query(`SELECT 1 FROM ${schema}.live_leases WHERE expires_at > clock_timestamp() AND serving_epoch <> $1 LIMIT 1`, [row.serving_epoch])
187 if (readers.rowCount) throw new StorageCompatibilityError('Drain active live readers or wait for their bounded leases before activating recovery')
188 const replays = await client.query(`SELECT 1 FROM ${schema}.replay_pins WHERE expires_at>clock_timestamp() AND serving_epoch<>$1 LIMIT 1`, [row.serving_epoch])
189 if (replays.rowCount) throw new StorageCompatibilityError('Drain active replay readers or wait for their bounded pins before activating recovery')
190 await client.query(`DELETE FROM ${schema}.replay_pins`)
191 await client.query(`UPDATE ${schema}.chunk_objects SET claim_token=NULL, claim_until=NULL, claim_epoch=claim_epoch+1 WHERE retired_at IS NOT NULL`)
192 await client.query(`UPDATE ${schema}.reclamation_policy SET inventory_cursor=NULL`)
193 // Process eviction can leave durable claims and leases behind. UUID tokens
194 // invalidate callbacks issued on either side of a point-in-time rollback.
195 await client.query(`UPDATE ${schema}.chunks SET claim_token = NULL, claim_until = NULL, claim_epoch = claim_epoch + 1 WHERE state = 'frozen'`)
196 await client.query(`UPDATE ${schema}.subscription_wakes SET state = 'fenced', delivery_claim = NULL, delivery_until = NULL WHERE state IN ('ready', 'delivered')`)
197 await client.query(`UPDATE ${schema}.subscriptions SET current_wake = NULL, holder = NULL, lease_until = NULL,
198 retry_count = 0, retry_at = NULL, next_work_at = clock_timestamp(),
199 public_base_url = COALESCE((SELECT recovery_target_public_base_url FROM ${schema}.installation), public_base_url) WHERE deleted_at IS NULL`)
200 await client.query(`DELETE FROM ${schema}.live_leases`)
201 const activated = await client.query<InstallationIdentity>(`UPDATE ${schema}.installation SET serving_state = 'active',
202 environment_id = recovery_target_environment, storage_identity = recovery_target_storage, completed_recovery_token = recovery_token, recovery_token = NULL
203 RETURNING id, serving_epoch, serving_state, environment_id, storage_identity`)
204 return activated.rows[0]!
205 })
206}