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