or3-provider-sqlite 0.0.25 → 0.0.27

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,444 @@
1
+ import {
2
+ SqliteExternalStorageGenerationCoordinator,
3
+ assertGenerationIdentifier,
4
+ generationRecord
5
+ } from "./sqlite-generation-coordinator.js";
6
+ import { GENERATION_TABLE, HEAD_TABLE, GENERATION_PROOF_ROWS, generationHashSql, validGenerationHashSql } from "../db/storage-generation-guards.js";
7
+ import {
8
+ GENERATION_UPLOAD_TABLE as UPLOADS,
9
+ GENERATION_UPLOAD_HOLD_EXPIRY,
10
+ GENERATION_UPLOAD_MAX_TTL_SECONDS,
11
+ GENERATION_UPLOAD_MAX_PENDING
12
+ } from "../db/storage-generation-upload-guards.js";
13
+ function intent(row) {
14
+ return {
15
+ intentId: row.intent_id,
16
+ workspaceId: row.workspace_id,
17
+ hash: row.hash,
18
+ purpose: row.purpose,
19
+ generationId: row.generation_id,
20
+ userId: row.user_id,
21
+ storageProviderId: row.storage_provider_id,
22
+ namespaceId: row.namespace_id,
23
+ storageId: row.storage_id,
24
+ mimeType: row.mime_type,
25
+ sizeBytes: row.size_bytes,
26
+ reservedBytes: row.reserved_bytes,
27
+ createdAt: row.created_at,
28
+ expiresAt: row.expires_at,
29
+ state: row.state,
30
+ ...row.ready_receipt_id === null ? {} : { readyReceiptId: row.ready_receipt_id },
31
+ ...row.ready_at === null ? {} : { readyAt: row.ready_at },
32
+ ...row.published_at === null ? {} : { publishedAt: row.published_at },
33
+ ...row.materialized_at === null ? {} : { materializedAt: row.materialized_at },
34
+ ...row.claim_id === null ? {} : { claimId: row.claim_id },
35
+ ...row.claimed_at === null ? {} : { claimedAt: row.claimed_at },
36
+ ...row.deleted_at === null ? {} : { deletedAt: row.deleted_at }
37
+ };
38
+ }
39
+ export class SqliteExternalStorageGenerationUploadCoordinator extends SqliteExternalStorageGenerationCoordinator {
40
+ uploadVersion = 1;
41
+ /** Allocation/Trash/claimed bytes remain in the canonical retained ledger
42
+ * until independently verified removal is acknowledged. */
43
+ retainedGenerationQuotaVersion = 1;
44
+ uploadKey(input) {
45
+ assertGenerationIdentifier(input.intentId, "upload intent");
46
+ assertGenerationIdentifier(input.userId, "upload owner");
47
+ return { ...this.key(input), intentId: input.intentId, userId: input.userId };
48
+ }
49
+ claimKey(input) {
50
+ assertGenerationIdentifier(input.intentId, "upload intent");
51
+ assertGenerationIdentifier(input.claimId, "upload claim");
52
+ return { ...this.key(input), intentId: input.intentId, claimId: input.claimId };
53
+ }
54
+ upload(input) {
55
+ const row = this.raw.prepare(`SELECT * FROM ${UPLOADS} WHERE intent_id = ? AND workspace_id = ? AND hash = ?
56
+ AND generation_id = ? AND storage_provider_id = ? ${input.userId === void 0 ? "" : "AND user_id = ?"}`).get(
57
+ input.intentId,
58
+ input.workspaceId,
59
+ input.hash,
60
+ input.generationId,
61
+ this.storageProviderId,
62
+ ...input.userId === void 0 ? [] : [input.userId]
63
+ );
64
+ if (row) this.assertProjection(row);
65
+ return row;
66
+ }
67
+ assertProjection(row) {
68
+ const ledger = this.raw.prepare("SELECT * FROM upload_intents WHERE id = ?").get(row.intent_id);
69
+ const holding = ["reserved", "ready", "published_pending_metadata"].includes(row.state);
70
+ const materialized = row.state === "materialized";
71
+ const expected = {
72
+ workspace_id: row.workspace_id,
73
+ hash: row.hash,
74
+ mime_type: row.mime_type,
75
+ size_bytes: row.size_bytes,
76
+ storage_id: row.storage_id,
77
+ created_at: row.created_at,
78
+ expires_at: GENERATION_UPLOAD_HOLD_EXPIRY,
79
+ status: holding ? "active" : materialized ? "consumed" : "cancelled",
80
+ reserved_bytes: holding ? row.size_bytes : 0,
81
+ consumed_at: materialized ? row.materialized_at : null,
82
+ cancelled_at: holding || materialized ? null : row.claimed_at
83
+ };
84
+ if (!ledger || Object.entries(expected).some(([key, value]) => ledger[key] !== value)) {
85
+ throw new Error("Storage upload ledger projection integrity failure");
86
+ }
87
+ }
88
+ mustUpload(key) {
89
+ const row = this.upload(key);
90
+ if (!row) throw new Error("Storage generation upload is missing or owner/binding mismatched");
91
+ return row;
92
+ }
93
+ activeIntents(workspaceId) {
94
+ const rows = this.raw.prepare(`SELECT id, ${generationHashSql("hash")} AS hash,
95
+ ${validGenerationHashSql("hash")} AS valid_hash, reserved_bytes, expires_at
96
+ FROM upload_intents WHERE workspace_id = ? AND status = 'active' LIMIT ?`).all(workspaceId, GENERATION_PROOF_ROWS + 1);
97
+ if (rows.length > GENERATION_PROOF_ROWS) throw new Error("Storage upload proof_incomplete: intent budget");
98
+ for (const row of rows) {
99
+ if (row.valid_hash !== 1 || !Number.isSafeInteger(row.reserved_bytes) || row.reserved_bytes < 0 || !Number.isSafeInteger(row.expires_at) || row.expires_at < 0) throw new Error("Storage upload unknown_references: invalid reservation");
100
+ }
101
+ return rows;
102
+ }
103
+ quotaUsed(workspaceId) {
104
+ const rows = this.raw.prepare("SELECT size_bytes FROM retained_storage WHERE workspace_id = ? LIMIT ?").all(workspaceId, GENERATION_PROOF_ROWS + 1);
105
+ if (rows.length > GENERATION_PROOF_ROWS) throw new Error("Storage upload proof_incomplete: retained budget");
106
+ let used = 0;
107
+ for (const row of rows) {
108
+ used = this.sum(used, row.size_bytes);
109
+ }
110
+ return used;
111
+ }
112
+ retainedBytes(workspaceId, hash) {
113
+ const row = this.raw.prepare("SELECT size_bytes FROM retained_storage WHERE workspace_id = ? AND hash = ?").get(workspaceId, hash);
114
+ return this.sum(0, row?.size_bytes ?? 0);
115
+ }
116
+ chargedBytes(workspaceId, hash, now) {
117
+ let charged = this.quotaUsed(workspaceId);
118
+ const pending = /* @__PURE__ */ new Map();
119
+ for (const row of this.activeIntents(workspaceId)) {
120
+ if (row.expires_at <= now) continue;
121
+ if (row.hash === hash) throw new Error("Storage upload already has an active reservation");
122
+ pending.set(row.hash, Math.max(pending.get(row.hash) ?? 0, row.reserved_bytes));
123
+ }
124
+ for (const [digest, size] of pending) charged = this.sum(charged, Math.max(0, size - this.retainedBytes(workspaceId, digest)));
125
+ return charged;
126
+ }
127
+ sum(left, right) {
128
+ const value = left + right;
129
+ if (!Number.isSafeInteger(value) || value < 0) throw new Error("Storage upload quota accounting overflow");
130
+ return value;
131
+ }
132
+ async reserveGenerationUpload(input) {
133
+ const key = this.uploadKey(input);
134
+ for (const [name, value] of Object.entries({ namespace: input.namespaceId, target: input.storageId, mime: input.mimeType })) {
135
+ assertGenerationIdentifier(value, name, name === "target" ? 2048 : 256);
136
+ }
137
+ if (!Number.isSafeInteger(input.sizeBytes) || input.sizeBytes < 0) throw new Error("Invalid storage generation size");
138
+ if (!Number.isSafeInteger(input.expiresInSeconds) || input.expiresInSeconds < 1 || input.expiresInSeconds > GENERATION_UPLOAD_MAX_TTL_SECONDS) {
139
+ throw new Error("Invalid storage generation upload lifetime");
140
+ }
141
+ if (input.workspaceQuotaBytes !== void 0 && (!Number.isSafeInteger(input.workspaceQuotaBytes) || input.workspaceQuotaBytes < 1)) {
142
+ throw new Error("Invalid workspace storage quota");
143
+ }
144
+ return this.mutate(() => {
145
+ const existing = this.raw.prepare(`SELECT * FROM ${UPLOADS} WHERE intent_id = ?`).all(key.intentId);
146
+ if (existing.length) {
147
+ const row = existing[0];
148
+ if (existing.length !== 1 || row.purpose !== "upload" || row.intent_id !== key.intentId || row.generation_id !== key.generationId || row.workspace_id !== key.workspaceId || row.hash !== key.hash || row.user_id !== key.userId || row.storage_provider_id !== this.storageProviderId || row.namespace_id !== input.namespaceId || row.storage_id !== input.storageId || row.mime_type !== input.mimeType || row.size_bytes !== input.sizeBytes || row.request_ttl !== input.expiresInSeconds || row.quota_bytes !== (input.workspaceQuotaBytes ?? null)) {
149
+ throw new Error("Storage upload replay identity or immutable target mismatch");
150
+ }
151
+ this.assertProjection(row);
152
+ return { status: "replayed", intent: intent(row) };
153
+ }
154
+ if (this.raw.prepare(`SELECT 1 FROM ${UPLOADS} WHERE generation_id = ? OR storage_id = ?`).get(key.generationId, input.storageId)) {
155
+ throw new Error("Storage generation identity or target cannot be reused");
156
+ }
157
+ if (this.raw.prepare(`SELECT 1 FROM ${GENERATION_TABLE} WHERE generation_id = ? OR storage_id = ?`).get(key.generationId, input.storageId)) {
158
+ throw new Error("Storage generation identity or target cannot be reused");
159
+ }
160
+ const head = this.head(key);
161
+ if (head && (head.storage_provider_id !== this.storageProviderId || head.state !== "deleted")) {
162
+ throw new Error("Current storage generation must have confirmed removal before replacement");
163
+ }
164
+ const enrolled = Boolean(this.raw.prepare(`SELECT 1 FROM ${UPLOADS} WHERE workspace_id = ? AND hash = ? LIMIT 1`).get(key.workspaceId, key.hash));
165
+ if (!enrolled && this.raw.prepare("SELECT 1 FROM retained_storage WHERE workspace_id = ? AND hash = ?").get(key.workspaceId, key.hash)) {
166
+ throw new Error("Storage generation cannot adopt legacy retained bytes");
167
+ }
168
+ const proof = this.metadataProof(key, !head && !enrolled, input.storageId) ?? this.referenceProof(key, !head && !enrolled);
169
+ if (proof) throw new Error(`Legacy storage adoption or upload proof failed: ${proof}`);
170
+ const pending = this.raw.prepare(`SELECT count(*) AS count FROM ${UPLOADS} WHERE workspace_id = ?
171
+ AND state IN ('reserved','ready','published_pending_metadata')`).get(key.workspaceId);
172
+ if (pending.count >= GENERATION_UPLOAD_MAX_PENDING) throw new Error("Storage upload pending allocation limit");
173
+ const now = this.now();
174
+ const expires = this.sum(now, input.expiresInSeconds);
175
+ const charged = this.chargedBytes(key.workspaceId, key.hash, now);
176
+ const projectedBytes = this.sum(charged, input.sizeBytes);
177
+ if (input.workspaceQuotaBytes !== void 0 && projectedBytes > input.workspaceQuotaBytes) {
178
+ throw new Error("Workspace storage quota exceeded");
179
+ }
180
+ this.raw.prepare(`INSERT INTO ${UPLOADS}
181
+ (intent_id,workspace_id,hash,generation_id,user_id,storage_provider_id,namespace_id,storage_id,mime_type,
182
+ size_bytes,reserved_bytes,created_at,expires_at,request_ttl,quota_bytes,state)
183
+ VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,'reserved')`).run(
184
+ key.intentId,
185
+ key.workspaceId,
186
+ key.hash,
187
+ key.generationId,
188
+ key.userId,
189
+ this.storageProviderId,
190
+ input.namespaceId,
191
+ input.storageId,
192
+ input.mimeType,
193
+ input.sizeBytes,
194
+ input.sizeBytes,
195
+ now,
196
+ expires,
197
+ input.expiresInSeconds,
198
+ input.workspaceQuotaBytes ?? null
199
+ );
200
+ this.raw.prepare(`INSERT INTO upload_intents
201
+ (id,workspace_id,hash,mime_type,size_bytes,reserved_bytes,expires_at,status,storage_id,created_at)
202
+ VALUES (?,?,?,?,?,?,?,'active',?,?)`).run(
203
+ key.intentId,
204
+ key.workspaceId,
205
+ key.hash,
206
+ input.mimeType,
207
+ input.sizeBytes,
208
+ input.sizeBytes,
209
+ GENERATION_UPLOAD_HOLD_EXPIRY,
210
+ input.storageId,
211
+ now
212
+ );
213
+ this.raw.prepare(`INSERT INTO retained_storage(workspace_id,hash,size_bytes) VALUES (?,?,?)
214
+ ON CONFLICT(workspace_id,hash) DO UPDATE SET size_bytes=MAX(size_bytes,excluded.size_bytes)`).run(key.workspaceId, key.hash, input.sizeBytes);
215
+ return { status: "reserved", intent: intent(this.mustUpload(key)) };
216
+ });
217
+ }
218
+ async getGenerationUpload(input) {
219
+ const key = this.uploadKey(input);
220
+ return this.mutate(() => {
221
+ const row = this.upload(key);
222
+ return row ? intent(row) : null;
223
+ });
224
+ }
225
+ async reserveGenerationRestore(input) {
226
+ const key = this.uploadKey(input);
227
+ if (!Number.isSafeInteger(input.expiresInSeconds) || input.expiresInSeconds < 1 || input.expiresInSeconds > GENERATION_UPLOAD_MAX_TTL_SECONDS) {
228
+ throw new Error("Invalid storage generation restore lifetime");
229
+ }
230
+ if (input.workspaceQuotaBytes !== void 0 && (!Number.isSafeInteger(input.workspaceQuotaBytes) || input.workspaceQuotaBytes < 1)) {
231
+ throw new Error("Invalid workspace storage quota");
232
+ }
233
+ return this.mutate(() => {
234
+ const previous = this.raw.prepare(`SELECT * FROM ${UPLOADS} WHERE intent_id = ?`).get(key.intentId);
235
+ if (previous) {
236
+ if (previous.purpose !== "restore" || previous.workspace_id !== key.workspaceId || previous.hash !== key.hash || previous.generation_id !== key.generationId || previous.user_id !== key.userId || previous.storage_provider_id !== this.storageProviderId || previous.request_ttl !== input.expiresInSeconds || previous.quota_bytes !== (input.workspaceQuotaBytes ?? null)) {
237
+ throw new Error("Storage restore replay identity mismatch");
238
+ }
239
+ this.assertProjection(previous);
240
+ return { status: "replayed", intent: intent(previous) };
241
+ }
242
+ const generation = this.find(key);
243
+ const origin = this.raw.prepare(`SELECT * FROM ${UPLOADS} WHERE generation_id = ? AND purpose = 'upload'`).get(key.generationId);
244
+ if (!generation || generation.state !== "verified" || this.head(key)?.generation_id !== key.generationId || !origin || origin.state !== "materialized" || origin.storage_id !== generation.storage_id || origin.workspace_id !== key.workspaceId || origin.hash !== key.hash || origin.storage_provider_id !== this.storageProviderId) {
245
+ throw new Error("Storage restore requires an exact verified materialized origin");
246
+ }
247
+ this.assertProjection(origin);
248
+ if (this.raw.prepare(`SELECT 1 FROM s_file_meta WHERE workspace_id = ? AND deleted = 0 AND ${generationHashSql("id")} = ? LIMIT 1`).get(key.workspaceId, key.hash)) throw new Error("Storage restore metadata is already live");
249
+ const pending = this.raw.prepare(`SELECT count(*) AS count FROM ${UPLOADS} WHERE workspace_id = ?
250
+ AND state IN ('reserved','ready','published_pending_metadata')`).get(key.workspaceId);
251
+ if (pending.count >= GENERATION_UPLOAD_MAX_PENDING) throw new Error("Storage restore pending allocation limit");
252
+ const now = this.now();
253
+ if (now < generation.last_activity_at) throw new Error("Storage restore server clock regressed");
254
+ const charged = this.chargedBytes(key.workspaceId, key.hash, now);
255
+ const projected = this.sum(charged, Math.max(0, origin.size_bytes - this.retainedBytes(key.workspaceId, key.hash)));
256
+ if (input.workspaceQuotaBytes !== void 0 && projected > input.workspaceQuotaBytes) throw new Error("Workspace storage quota exceeded");
257
+ this.raw.prepare(`INSERT INTO ${UPLOADS}
258
+ (intent_id,workspace_id,hash,generation_id,user_id,storage_provider_id,namespace_id,storage_id,mime_type,
259
+ size_bytes,reserved_bytes,created_at,expires_at,request_ttl,quota_bytes,state,purpose,
260
+ ready_receipt_id,ready_at,published_generation_id,published_at)
261
+ VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,'published_pending_metadata','restore',?,?,?,?)`).run(
262
+ key.intentId,
263
+ key.workspaceId,
264
+ key.hash,
265
+ key.generationId,
266
+ key.userId,
267
+ this.storageProviderId,
268
+ origin.namespace_id,
269
+ origin.storage_id,
270
+ origin.mime_type,
271
+ origin.size_bytes,
272
+ origin.size_bytes,
273
+ now,
274
+ this.sum(now, input.expiresInSeconds),
275
+ input.expiresInSeconds,
276
+ input.workspaceQuotaBytes ?? null,
277
+ origin.ready_receipt_id,
278
+ now,
279
+ key.generationId,
280
+ now
281
+ );
282
+ this.raw.prepare(`INSERT INTO upload_intents
283
+ (id,workspace_id,hash,mime_type,size_bytes,reserved_bytes,expires_at,status,storage_id,created_at)
284
+ VALUES (?,?,?,?,?,?,?,'active',?,?)`).run(
285
+ key.intentId,
286
+ key.workspaceId,
287
+ key.hash,
288
+ origin.mime_type,
289
+ origin.size_bytes,
290
+ origin.size_bytes,
291
+ GENERATION_UPLOAD_HOLD_EXPIRY,
292
+ origin.storage_id,
293
+ now
294
+ );
295
+ return { status: "reserved", intent: intent(this.mustUpload(key)) };
296
+ });
297
+ }
298
+ async markGenerationUploadReady(input) {
299
+ const key = this.uploadKey(input);
300
+ assertGenerationIdentifier(input.readyReceiptId, "ready receipt", 2048);
301
+ return this.mutate(() => {
302
+ const row = this.mustUpload(key);
303
+ if (row.purpose !== "upload") throw new Error("Restore intents do not authorize upload readiness");
304
+ if (row.storage_id !== input.storageId || row.ready_receipt_id !== null && row.ready_receipt_id !== input.readyReceiptId) {
305
+ throw new Error("Storage upload readiness receipt mismatch");
306
+ }
307
+ if (row.ready_receipt_id !== null) return { status: "replayed", intent: intent(row) };
308
+ const now = this.now();
309
+ if (row.state !== "reserved" || now < row.created_at) throw new Error("Storage upload readiness state or clock mismatch");
310
+ this.raw.prepare(`UPDATE ${UPLOADS} SET state = 'ready', ready_receipt_id = ?, ready_at = ? WHERE intent_id = ?`).run(input.readyReceiptId, now, key.intentId);
311
+ return { status: "ready", intent: intent(this.mustUpload(key)) };
312
+ });
313
+ }
314
+ async publishGenerationUpload(input) {
315
+ const key = this.uploadKey(input);
316
+ return this.mutate(() => {
317
+ const row = this.mustUpload(key);
318
+ if (row.purpose !== "upload") throw new Error("Restore intents do not authorize byte publication");
319
+ if (row.storage_id !== input.storageId || row.size_bytes !== input.sizeBytes || row.ready_receipt_id !== input.readyReceiptId) {
320
+ throw new Error("Storage upload publication receipt mismatch");
321
+ }
322
+ if (row.state === "published_pending_metadata" || row.state === "materialized") {
323
+ const generation = this.find(key);
324
+ if (!generation || generation.state !== "verified") throw new Error("Storage upload publication is no longer live");
325
+ return { status: "replayed", intent: intent(row), generation: generationRecord(generation) };
326
+ }
327
+ const now = this.now();
328
+ if (row.state !== "ready" || row.expires_at <= now || row.ready_at === null || now < row.ready_at) {
329
+ throw new Error("Storage upload expired, not ready, or terminal");
330
+ }
331
+ const proof = this.metadataProof(key, false, row.storage_id) ?? this.referenceProof(key, false);
332
+ if (proof) throw new Error(`Storage upload publication proof failed: ${proof}`);
333
+ const head = this.head(key);
334
+ if (head && (head.state === "verified" || head.storage_provider_id !== this.storageProviderId)) throw new Error("Storage upload head conflict");
335
+ this.raw.prepare(`UPDATE ${UPLOADS} SET state = 'published_pending_metadata', published_generation_id = ?, published_at = ? WHERE intent_id = ?`).run(key.generationId, now, key.intentId);
336
+ this.raw.prepare(`INSERT INTO ${GENERATION_TABLE}
337
+ (generation_id,workspace_id,hash,storage_provider_id,storage_id,size_bytes,state,created_at,last_activity_at)
338
+ VALUES (?,?,?,?,?,?,'verified',?,?)`).run(key.generationId, key.workspaceId, key.hash, this.storageProviderId, row.storage_id, row.size_bytes, now, now);
339
+ if (head) this.raw.prepare(`UPDATE ${HEAD_TABLE} SET generation_id = ? WHERE workspace_id = ? AND hash = ?`).run(key.generationId, key.workspaceId, key.hash);
340
+ else this.raw.prepare(`INSERT INTO ${HEAD_TABLE}(workspace_id,hash,generation_id) VALUES (?,?,?)`).run(key.workspaceId, key.hash, key.generationId);
341
+ return { status: "published", intent: intent(this.mustUpload(key)), generation: generationRecord(this.find(key)) };
342
+ });
343
+ }
344
+ async claimAbandonedGenerationUpload(input) {
345
+ const key = this.claimKey(input);
346
+ if (!Number.isSafeInteger(input.retentionSeconds) || input.retentionSeconds < 0) throw new Error("Invalid storage retention interval");
347
+ return this.mutate(() => {
348
+ const row = this.upload(key);
349
+ if (!row) return { status: "blocked", reason: "missing" };
350
+ if (row.state === "abandon_claimed" || row.state === "abandoned") return row.claim_id === key.claimId ? { status: "replayed", intent: intent(row) } : { status: "blocked", reason: "claim_conflict" };
351
+ if (row.state === "materialized") return { status: "blocked", reason: "materialized" };
352
+ if (row.state === "reserved" || row.ready_at === null) return { status: "blocked", reason: "not_ready" };
353
+ const now = this.now();
354
+ if (now < row.expires_at) return { status: "blocked", reason: "not_expired" };
355
+ const proof = this.metadataProof(key, false, row.storage_id) ?? this.referenceProof(key, false);
356
+ if (proof) return { status: "blocked", reason: proof };
357
+ const generation = row.published_generation_id === null ? void 0 : this.find(key);
358
+ if (row.published_generation_id !== null && (!generation || generation.state !== "verified" || this.head(key)?.generation_id !== key.generationId)) return { status: "blocked", reason: "not_current" };
359
+ let activity = Math.max(row.expires_at, row.ready_at, row.published_at ?? 0, generation?.last_activity_at ?? 0);
360
+ let reservations;
361
+ try {
362
+ reservations = this.activeIntents(key.workspaceId);
363
+ } catch (error) {
364
+ return { status: "blocked", reason: String(error).includes("proof_incomplete") ? "proof_incomplete" : "unknown_references" };
365
+ }
366
+ for (const reservation of reservations) {
367
+ if (reservation.id === key.intentId || reservation.hash !== key.hash) continue;
368
+ if (reservation.expires_at > now) return { status: "blocked", reason: "active_upload" };
369
+ activity = Math.max(activity, reservation.expires_at);
370
+ }
371
+ if (now < activity || now - activity < input.retentionSeconds) return { status: "blocked", reason: "retention" };
372
+ if (this.raw.prepare(`SELECT 1 FROM ${UPLOADS} WHERE claim_id = ? UNION ALL SELECT 1 FROM ${GENERATION_TABLE} WHERE claim_id = ?`).get(key.claimId, key.claimId)) {
373
+ return { status: "blocked", reason: "claim_conflict" };
374
+ }
375
+ if (generation) this.raw.prepare(`UPDATE ${GENERATION_TABLE} SET state = 'claimed', claim_id = ?, claimed_at = ?, last_activity_at = ? WHERE generation_id = ?`).run(key.claimId, now, activity, key.generationId);
376
+ this.raw.prepare(`UPDATE ${UPLOADS} SET state = 'abandon_claimed', reserved_bytes = 0, claim_id = ?, claimed_at = ? WHERE intent_id = ?`).run(key.claimId, now, key.intentId);
377
+ this.raw.prepare(`UPDATE upload_intents SET status = 'cancelled', reserved_bytes = 0, cancelled_at = ? WHERE id = ?`).run(now, key.intentId);
378
+ return { status: "claimed", intent: intent(this.upload(key)) };
379
+ });
380
+ }
381
+ claimedUpload(key) {
382
+ const row = this.upload(key);
383
+ if (!row || row.claim_id !== key.claimId || !["abandon_claimed", "abandoned"].includes(row.state)) return void 0;
384
+ if (row.published_generation_id !== null) {
385
+ const generation = this.find(key);
386
+ if (!generation || generation.claim_id !== key.claimId || !["claimed", "deleted"].includes(generation.state)) {
387
+ throw new Error("Storage upload durable generation claim mismatch");
388
+ }
389
+ }
390
+ return row;
391
+ }
392
+ async getGenerationUploadClaim(input) {
393
+ const key = this.claimKey(input);
394
+ return this.mutate(() => {
395
+ const row = this.claimedUpload(key);
396
+ return row ? intent(row) : null;
397
+ });
398
+ }
399
+ async completeGenerationUploadAbandonment(input) {
400
+ const key = this.claimKey(input);
401
+ return this.mutate(() => {
402
+ const row = this.claimedUpload(key);
403
+ if (!row) throw new Error("Storage upload abandonment claim mismatch");
404
+ if (row.state === "abandoned") {
405
+ this.releaseManagedRetainedCharge(key);
406
+ return { status: "replayed", intent: intent(row) };
407
+ }
408
+ const now = this.now();
409
+ if (row.claimed_at === null || now < row.claimed_at) throw new Error("Storage upload server clock regressed");
410
+ if (row.published_generation_id !== null) this.raw.prepare(`UPDATE ${GENERATION_TABLE} SET state = 'deleted', deleted_at = ? WHERE generation_id = ? AND state = 'claimed'`).run(now, key.generationId);
411
+ this.raw.prepare(`UPDATE ${UPLOADS} SET state = 'abandoned', deleted_at = ? WHERE intent_id = ?`).run(now, key.intentId);
412
+ this.releaseManagedRetainedCharge(key);
413
+ return { status: "abandoned", intent: intent(this.upload(key)) };
414
+ });
415
+ }
416
+ async listGenerationUploadRecovery(input) {
417
+ assertGenerationIdentifier(input.workspaceId, "workspace");
418
+ const limit = input.limit ?? 100;
419
+ if (!Number.isSafeInteger(limit) || limit < 1 || limit > 100) throw new Error("Invalid upload recovery page limit");
420
+ let after = "";
421
+ if (input.cursor !== void 0) {
422
+ try {
423
+ if (input.cursor.length > 4096) throw new Error("size");
424
+ const cursor = JSON.parse(Buffer.from(input.cursor, "base64url").toString("utf8"));
425
+ if (cursor.version !== 1 || cursor.workspaceId !== input.workspaceId || cursor.providerId !== this.storageProviderId) throw new Error("scope");
426
+ assertGenerationIdentifier(cursor.after, "cursor");
427
+ after = cursor.after;
428
+ } catch {
429
+ throw new Error("Invalid upload recovery cursor");
430
+ }
431
+ }
432
+ return this.mutate(() => {
433
+ const rows = this.raw.prepare(`SELECT * FROM ${UPLOADS} WHERE workspace_id = ? AND intent_id > ? AND storage_provider_id = ? ORDER BY intent_id LIMIT ?`).all(input.workspaceId, after, this.storageProviderId, limit + 1);
434
+ const hasMore = rows.length > limit;
435
+ const page = rows.slice(0, limit);
436
+ const now = this.now();
437
+ return {
438
+ items: page.filter((row) => row.state === "abandon_claimed" || ["reserved", "ready", "published_pending_metadata"].includes(row.state) && row.expires_at <= now).map(intent),
439
+ hasMore,
440
+ ...hasMore ? { nextCursor: Buffer.from(JSON.stringify({ version: 1, workspaceId: input.workspaceId, providerId: this.storageProviderId, after: page.at(-1).intent_id })).toString("base64url") } : {}
441
+ };
442
+ });
443
+ }
444
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "or3-provider-sqlite",
3
- "version": "0.0.25",
3
+ "version": "0.0.27",
4
4
  "repository": {
5
5
  "type": "git",
6
6
  "url": "git+https://github.com/Saluana/or3-provider-sqlite.git"