cloudrop 0.0.0-stage → 0.1.0

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.
Files changed (48) hide show
  1. package/CHANGELOG.md +56 -0
  2. package/LICENSE +21 -0
  3. package/README.md +101 -2
  4. package/dist/adapters/drizzle.d.ts +204 -0
  5. package/dist/adapters/drizzle.js +216 -0
  6. package/dist/adapters/drizzle.js.map +1 -0
  7. package/dist/adapters/prisma.d.ts +81 -0
  8. package/dist/adapters/prisma.js +32 -0
  9. package/dist/adapters/prisma.js.map +1 -0
  10. package/dist/adapters/sql.d.ts +98 -0
  11. package/dist/adapters/sql.js +70 -0
  12. package/dist/adapters/sql.js.map +1 -0
  13. package/dist/client-Dj6ON4MN.d.ts +214 -0
  14. package/dist/client-Y1zUEbCj.js +1561 -0
  15. package/dist/client-Y1zUEbCj.js.map +1 -0
  16. package/dist/client.d.ts +3 -0
  17. package/dist/client.js +3 -0
  18. package/dist/d1-BY2c5bcL.js +16 -0
  19. package/dist/d1-BY2c5bcL.js.map +1 -0
  20. package/dist/errors-CUxMmFAe.js +40 -0
  21. package/dist/errors-CUxMmFAe.js.map +1 -0
  22. package/dist/executor-CEA7WV2W.d.ts +27 -0
  23. package/dist/index.d.ts +421 -0
  24. package/dist/index.js +3007 -0
  25. package/dist/index.js.map +1 -0
  26. package/dist/input-DTC476_I.js +13 -0
  27. package/dist/input-DTC476_I.js.map +1 -0
  28. package/dist/next.d.ts +9 -0
  29. package/dist/next.js +14 -0
  30. package/dist/next.js.map +1 -0
  31. package/dist/node.d.ts +32 -0
  32. package/dist/node.js +100 -0
  33. package/dist/node.js.map +1 -0
  34. package/dist/part-size-CvMoobfC.js +9 -0
  35. package/dist/part-size-CvMoobfC.js.map +1 -0
  36. package/dist/react.d.ts +123 -0
  37. package/dist/react.js +355 -0
  38. package/dist/react.js.map +1 -0
  39. package/dist/route-CspI1Ypt.js +72 -0
  40. package/dist/route-CspI1Ypt.js.map +1 -0
  41. package/dist/store-BfCJejGh.d.ts +382 -0
  42. package/dist/tables-DZnw2sPK.d.ts +11 -0
  43. package/dist/transactional-DnvnGsVH.js +672 -0
  44. package/dist/transactional-DnvnGsVH.js.map +1 -0
  45. package/dist/types-BZUOaz_B.js +5 -0
  46. package/dist/types-BZUOaz_B.js.map +1 -0
  47. package/dist/types-BrAx3dA4.d.ts +185 -0
  48. package/package.json +110 -4
@@ -0,0 +1,672 @@
1
+ import { n as configError, t as CloudropError } from "./errors-CUxMmFAe.js";
2
+ import { o as routeFor } from "./route-CspI1Ypt.js";
3
+ // src/store/sql/executor.ts
4
+ function sequential(dialect, query) {
5
+ return {
6
+ dialect,
7
+ query,
8
+ async batch(statements) {
9
+ const results = [];
10
+ for (const { sql, params } of statements) results.push(await query(sql, params));
11
+ return results;
12
+ }
13
+ };
14
+ }
15
+ function runStatement(executor, statement) {
16
+ return executor.query(statement.sql, statement.params);
17
+ }
18
+ function hasCode(error, sqlState) {
19
+ let current = error;
20
+ for (let depth = 0; depth < 5 && typeof current === "object" && current !== null; depth++) {
21
+ const { code, originalCode, cause, meta } = current;
22
+ if (code === sqlState || originalCode === sqlState) return true;
23
+ current = cause ?? meta?.driverAdapterError;
24
+ }
25
+ return false;
26
+ }
27
+ const isLockTimeout = (error) => hasCode(error, "55P03");
28
+ const isUniqueViolation = (error) => hasCode(error, "23505");
29
+ // src/store/sql/bind.ts
30
+ function binder(dialect) {
31
+ const params = [];
32
+ const bind = (value, type) => {
33
+ params.push(value);
34
+ return dialect === "postgres" ? `$${params.length}::${type}` : "?";
35
+ };
36
+ return {
37
+ text: (value) => bind(value, "text"),
38
+ bigint: (value) => bind(value, "bigint"),
39
+ integer: (value) => bind(value, "integer"),
40
+ time: (value) => dialect === "postgres" ? bind(value?.toISOString() ?? null, "timestamptz") : bind(value?.getTime() ?? null, "bigint"),
41
+ json: (value) => `${bind(value, "text")}::json`,
42
+ statement: (sql) => ({
43
+ sql,
44
+ params
45
+ })
46
+ };
47
+ }
48
+ // src/store/sql/records.ts
49
+ const FILE_COLUMNS = [
50
+ "id",
51
+ "route",
52
+ "key",
53
+ "owner",
54
+ "status",
55
+ "name",
56
+ "type",
57
+ "size",
58
+ "upload_id",
59
+ "metadata",
60
+ "result",
61
+ "claim",
62
+ "claimed_at",
63
+ "expires_at",
64
+ "created_at",
65
+ "updated_at",
66
+ "completed_at",
67
+ "ended_at",
68
+ "cleaned_at",
69
+ "request_key"
70
+ ];
71
+ const RECORD_COLUMNS = FILE_COLUMNS.filter((column) => column !== "claim" && column !== "updated_at" && column !== "request_key").join(", ");
72
+ function describe(value) {
73
+ return typeof value === "string" ? JSON.stringify(value) : `${typeof value} ${String(value)}`;
74
+ }
75
+ function toSafeInteger(value, column) {
76
+ const digits = typeof value === "bigint" || typeof value === "object" && value !== null ? String(value) : value;
77
+ const number = typeof digits === "string" && /^-?\d+$/.test(digits) ? Number(digits) : digits;
78
+ if (typeof number === "number" && Number.isSafeInteger(number)) return number;
79
+ throw new Error(`The database returned ${describe(value)} for ${column}; expected a whole number up to 2^53.`);
80
+ }
81
+ function toDate(value, column) {
82
+ const ms = value instanceof Date ? value.getTime() : typeof value === "string" && !/^-?\d+$/.test(value) ? Date.parse(value) : toSafeInteger(value, column);
83
+ if (Number.isNaN(ms)) throw new Error(`The database returned ${describe(value)} for ${column}; expected a time.`);
84
+ return new Date(ms);
85
+ }
86
+ const text = (row, column) => {
87
+ const value = row[column];
88
+ if (typeof value === "string") return value;
89
+ throw new Error(`The database returned ${describe(value)} for ${column}; expected text.`);
90
+ };
91
+ const optionalText = (row, column) => row[column] == null ? null : text(row, column);
92
+ const optionalDate = (row, column) => row[column] == null ? null : toDate(row[column], column);
93
+ function toRecord(row) {
94
+ return {
95
+ id: text(row, "id"),
96
+ route: text(row, "route"),
97
+ key: text(row, "key"),
98
+ name: text(row, "name"),
99
+ type: text(row, "type"),
100
+ size: toSafeInteger(row.size, "size"),
101
+ metadata: optionalText(row, "metadata"),
102
+ owner: optionalText(row, "owner"),
103
+ status: text(row, "status"),
104
+ uploadId: optionalText(row, "upload_id"),
105
+ result: optionalText(row, "result"),
106
+ expiresAt: toDate(row.expires_at, "expires_at"),
107
+ createdAt: toDate(row.created_at, "created_at"),
108
+ claimedAt: optionalDate(row, "claimed_at"),
109
+ completedAt: optionalDate(row, "completed_at"),
110
+ endedAt: optionalDate(row, "ended_at"),
111
+ cleanedAt: optionalDate(row, "cleaned_at")
112
+ };
113
+ }
114
+ function toUsage(row) {
115
+ if (!row) return {
116
+ reservedBytes: 0,
117
+ activeBytes: 0,
118
+ files: 0
119
+ };
120
+ return {
121
+ reservedBytes: toSafeInteger(row.reserved_bytes, "reserved_bytes"),
122
+ activeBytes: toSafeInteger(row.active_bytes, "active_bytes"),
123
+ files: toSafeInteger(row.files, "files")
124
+ };
125
+ }
126
+ function encodeCursor(time, id) {
127
+ return `${time.getTime()}:${id}`;
128
+ }
129
+ function decodeCursor(cursor) {
130
+ const match = /^(\d+):(.*)$/s.exec(cursor);
131
+ if (!match?.[1] || match[2] === void 0) throw new Error("This sweep cursor was not made by the store. Start the sweep again with cursor null.");
132
+ return {
133
+ time: new Date(Number(match[1])),
134
+ id: match[2]
135
+ };
136
+ }
137
+ // src/store/sql/outcomes.ts
138
+ function claimOutcome(claimed, row) {
139
+ if (claimed) return { kind: "claimed" };
140
+ if (!row) return { kind: "missing" };
141
+ const record = toRecord(row);
142
+ if (record.status === "completed") return {
143
+ kind: "completed",
144
+ record
145
+ };
146
+ if (record.status === "pending" || record.status === "completing") return { kind: "busy" };
147
+ return {
148
+ kind: "ended",
149
+ record
150
+ };
151
+ }
152
+ function transition(changed, row) {
153
+ if (changed && row) return {
154
+ changed: true,
155
+ record: toRecord(row)
156
+ };
157
+ return {
158
+ changed: false,
159
+ record: row ? toRecord(row) : null
160
+ };
161
+ }
162
+ function releaseFrom(from, size) {
163
+ if (from === "pending" || from === "completing") return `reserved_bytes = reserved_bytes - ${size}`;
164
+ if (from === "completed") return `active_bytes = active_bytes - ${size}, files = files - 1`;
165
+ return null;
166
+ }
167
+ const RECOUNT = {
168
+ reserved: "coalesce(sum(CASE WHEN status IN ('pending', 'completing') THEN size END), 0)",
169
+ active: "coalesce(sum(CASE WHEN status = 'completed' THEN size END), 0)",
170
+ files: "count(CASE WHEN status = 'completed' THEN 1 END)"
171
+ };
172
+ // src/store/sql/postgres.ts
173
+ const INPUT_COLUMNS = "ord integer, id text, route text, key text, name text, type text, size bigint, metadata text";
174
+ const INSERT_COLUMNS$1 = "id, route, key, owner, status, name, type, size, metadata, expires_at, created_at, updated_at, request_key";
175
+ const inputJson = (files) => JSON.stringify(files.map(({ id, route, key, name, type, size, metadata }, index) => ({
176
+ ord: index + 1,
177
+ id,
178
+ route,
179
+ key,
180
+ name,
181
+ type,
182
+ size,
183
+ metadata
184
+ })));
185
+ function superseding(files, key, who, at) {
186
+ if (key === null) return {
187
+ cte: "",
188
+ freed: "0"
189
+ };
190
+ return {
191
+ cte: `, superseded AS (
192
+ UPDATE ${files} SET status = 'aborted', ended_at = ${at}, updated_at = ${at}
193
+ WHERE request_key = ${key} AND owner IS NOT DISTINCT FROM ${who}
194
+ AND route IN (SELECT route FROM input) AND status = 'pending'
195
+ RETURNING size
196
+ )`,
197
+ freed: "(SELECT coalesce(sum(size), 0) FROM superseded)"
198
+ };
199
+ }
200
+ function postgresWrites({ executor, tables }) {
201
+ const { files, usage } = tables;
202
+ async function transitionRow(update, set, id, from, b) {
203
+ const counted = set ? `, counted AS (UPDATE ${usage} SET ${set} FROM changed WHERE ${usage}.owner = changed.owner)` : "";
204
+ const sql = `WITH changed AS (${update} RETURNING ${RECORD_COLUMNS})${counted}
205
+ SELECT true AS changed, ${RECORD_COLUMNS} FROM changed
206
+ UNION ALL
207
+ SELECT false, ${RECORD_COLUMNS} FROM ${files} WHERE id = ${b.text(id)} AND NOT EXISTS (SELECT 1 FROM changed)`;
208
+ const [row] = await runStatement(executor, b.statement(sql));
209
+ const found = transition(row?.changed === true, row);
210
+ if (found.changed || found.record?.status !== from) return found;
211
+ const again = binder("postgres");
212
+ const [current] = await runStatement(executor, again.statement(`SELECT ${RECORD_COLUMNS} FROM ${files} WHERE id = ${again.text(id)}`));
213
+ return transition(false, current);
214
+ }
215
+ return {
216
+ async reserve({ owner, limit, expiresAt, requestKey, files: accepted }, now) {
217
+ if (accepted.length === 0) return [];
218
+ const b = binder("postgres");
219
+ const [input, expires, at, key] = [
220
+ b.json(inputJson(accepted)),
221
+ b.time(expiresAt),
222
+ b.time(now),
223
+ b.text(requestKey)
224
+ ];
225
+ const who = owner === null ? "NULL" : b.text(owner);
226
+ const { cte, freed } = superseding(files, requestKey === null ? null : key, who, at);
227
+ const head = `input AS (SELECT * FROM json_to_recordset(${input}) AS input(${INPUT_COLUMNS}))${cte}`;
228
+ const values = `input.id, input.route, input.key, ${who}, 'pending', input.name, input.type, input.size,
229
+ input.metadata, ${expires}, ${at}, ${at}, ${key}`;
230
+ if (owner === null) {
231
+ await runStatement(executor, b.statement(`WITH ${head} INSERT INTO ${files} (${INSERT_COLUMNS$1}) SELECT ${values} FROM input`));
232
+ return accepted.map(() => "reserved");
233
+ }
234
+ const fits = limit === null ? "true" : `decided.used + input.size <= ${b.bigint(limit)}`;
235
+ const onConflict = limit === null ? `ON CONFLICT (owner) DO UPDATE SET reserved_bytes = ${usage}.reserved_bytes + EXCLUDED.reserved_bytes,
236
+ updated_at = EXCLUDED.updated_at` : "";
237
+ const sql = `WITH RECURSIVE ${head},
238
+ locked AS (
239
+ SELECT reserved_bytes + active_bytes - ${freed} AS used FROM ${usage} WHERE owner = ${who} FOR UPDATE
240
+ ),
241
+ decided (ord, used, reserved) AS (
242
+ SELECT 0, coalesce((SELECT used FROM locked), 0), false
243
+ UNION ALL
244
+ SELECT input.ord, decided.used + CASE WHEN ${fits} THEN input.size ELSE 0 END, ${fits}
245
+ FROM decided JOIN input ON input.ord = decided.ord + 1
246
+ ),
247
+ inserted AS (
248
+ INSERT INTO ${files} (${INSERT_COLUMNS$1})
249
+ SELECT ${values} FROM input JOIN decided ON decided.ord = input.ord WHERE decided.reserved
250
+ RETURNING size
251
+ ),
252
+ total AS (SELECT coalesce(sum(size), 0) AS bytes, count(*) AS reserved, ${freed} AS freed FROM inserted),
253
+ counted AS (
254
+ UPDATE ${usage} SET reserved_bytes = reserved_bytes + total.bytes - total.freed, updated_at = ${at}
255
+ FROM total WHERE owner = ${who} AND (total.reserved > 0 OR total.freed > 0)
256
+ ),
257
+ created AS (
258
+ INSERT INTO ${usage} (owner, reserved_bytes, active_bytes, files, updated_at)
259
+ SELECT ${who}, total.bytes, 0, 0, ${at} FROM total
260
+ WHERE total.reserved > 0 AND NOT EXISTS (SELECT 1 FROM locked)
261
+ ${onConflict}
262
+ )
263
+ SELECT reserved FROM decided WHERE ord > 0 ORDER BY ord`;
264
+ const statement = b.statement(sql);
265
+ return (await runStatement(executor, statement).catch((error) => {
266
+ if (limit === null || !isUniqueViolation(error)) throw error;
267
+ return runStatement(executor, statement);
268
+ })).map((row) => row.reserved === true ? "reserved" : "over-quota");
269
+ },
270
+ async claim(id, claim, now, leaseMs) {
271
+ const b = binder("postgres");
272
+ const [key, at] = [b.text(id), b.time(now)];
273
+ const sql = `WITH claimed AS (
274
+ UPDATE ${files} SET status = 'completing', claim = ${b.text(claim)}, claimed_at = ${at}, updated_at = ${at}
275
+ WHERE id = ${key} AND (status = 'pending'
276
+ OR (status = 'completing' AND claimed_at < ${b.time(new Date(now.getTime() - leaseMs))}))
277
+ RETURNING id
278
+ )
279
+ SELECT EXISTS (SELECT 1 FROM claimed) AS claimed, ${RECORD_COLUMNS} FROM ${files} WHERE id = ${key}`;
280
+ const [row] = await runStatement(executor, b.statement(sql));
281
+ return claimOutcome(row?.claimed === true, row);
282
+ },
283
+ async complete(id, claim, result, now) {
284
+ const b = binder("postgres");
285
+ const at = b.time(now);
286
+ return transitionRow(`UPDATE ${files} SET status = 'completed', result = ${b.text(result)}, completed_at = ${at},
287
+ updated_at = ${at} WHERE id = ${b.text(id)} AND status = 'completing' AND claim = ${b.text(claim)}`, `reserved_bytes = reserved_bytes - changed.size, active_bytes = active_bytes + changed.size,
288
+ files = files + 1, updated_at = ${at}`, id, "completing", b);
289
+ },
290
+ async end(id, from, to, now, options) {
291
+ const b = binder("postgres");
292
+ const at = b.time(now);
293
+ const cleaned = options?.cleaned ? `, cleaned_at = ${at}` : "";
294
+ const update = `UPDATE ${files} SET status = ${b.text(to)}, ended_at = ${at}, updated_at = ${at}${cleaned}
295
+ WHERE id = ${b.text(id)} AND status = ${b.text(from)}`;
296
+ const released = releaseFrom(from, "changed.size");
297
+ return transitionRow(update, released && `${released}, updated_at = ${at}`, id, from, b);
298
+ },
299
+ async revoke(owner, now) {
300
+ const b = binder("postgres");
301
+ const [who, at] = [b.text(owner), b.time(now)];
302
+ const sql = `WITH revoked AS (
303
+ UPDATE ${files} SET status = 'aborted', ended_at = ${at}, updated_at = ${at}
304
+ WHERE owner = ${who} AND status = 'pending' RETURNING size
305
+ ),
306
+ counted AS (
307
+ UPDATE ${usage} SET reserved_bytes = reserved_bytes - (SELECT sum(size) FROM revoked), updated_at = ${at}
308
+ WHERE owner = ${who} AND EXISTS (SELECT 1 FROM revoked)
309
+ )
310
+ SELECT count(*) AS revoked FROM revoked`;
311
+ const [row] = await runStatement(executor, b.statement(sql));
312
+ return toSafeInteger(row?.revoked, "revoked");
313
+ },
314
+ async reconcile(owner) {
315
+ const forOwner = (sql) => {
316
+ const b = binder("postgres");
317
+ return b.statement(sql(b.text(owner)));
318
+ };
319
+ const [, , changed] = await executor.batch([
320
+ forOwner((who) => `INSERT INTO ${usage} (owner, reserved_bytes, active_bytes, files, updated_at)
321
+ VALUES (${who}, 0, 0, 0, '-infinity') ON CONFLICT (owner) DO NOTHING`),
322
+ forOwner((who) => `SELECT 1 FROM ${usage} WHERE owner = ${who} FOR UPDATE`),
323
+ forOwner((who) => `UPDATE ${usage} SET reserved_bytes = counted.reserved, active_bytes = counted.active,
324
+ files = counted.files, updated_at = now()
325
+ FROM (SELECT ${RECOUNT.reserved} AS reserved, ${RECOUNT.active} AS active, ${RECOUNT.files} AS files
326
+ FROM ${files} WHERE owner = ${who}) AS counted
327
+ WHERE ${usage}.owner = ${who} AND (${usage}.reserved_bytes, ${usage}.active_bytes, ${usage}.files)
328
+ IS DISTINCT FROM (counted.reserved, counted.active, counted.files)
329
+ RETURNING ${usage}.owner`),
330
+ forOwner((who) => `DELETE FROM ${usage} WHERE owner = ${who} AND updated_at = '-infinity'`)
331
+ ]);
332
+ return (changed?.length ?? 0) > 0;
333
+ }
334
+ };
335
+ }
336
+ // src/store/sql/reads.ts
337
+ const CLEANUP_STATUSES = "'aborted', 'rejected', 'failed', 'expired', 'deleted'";
338
+ function page(rows, limit, cursorOf) {
339
+ const kept = rows.slice(0, limit);
340
+ const last = kept.at(-1);
341
+ return {
342
+ kept,
343
+ cursor: rows.length > limit && last !== void 0 ? cursorOf(last) : null
344
+ };
345
+ }
346
+ function singleStatementMethods({ executor, dialect, tables }) {
347
+ const { files, usage } = tables;
348
+ const byteOrder = (expression) => dialect === "postgres" ? `${expression} COLLATE "C"` : expression;
349
+ const run = (statement) => runStatement(executor, statement);
350
+ return {
351
+ async attach(id, uploadId, now) {
352
+ const b = binder(dialect);
353
+ const sql = `UPDATE ${files} SET upload_id = ${b.text(uploadId)}, updated_at = ${b.time(now)}
354
+ WHERE id = ${b.text(id)} AND status = 'pending' AND (upload_id IS NULL OR upload_id = ${b.text(uploadId)})
355
+ RETURNING id`;
356
+ return (await run(b.statement(sql))).length > 0;
357
+ },
358
+ async get(id) {
359
+ const b = binder(dialect);
360
+ const [row] = await run(b.statement(`SELECT ${RECORD_COLUMNS} FROM ${files} WHERE id = ${b.text(id)}`));
361
+ return row ? toRecord(row) : null;
362
+ },
363
+ async release(id, claim, now) {
364
+ const b = binder(dialect);
365
+ const sql = `UPDATE ${files} SET status = 'pending', claim = NULL, claimed_at = NULL, updated_at = ${b.time(now)}
366
+ WHERE id = ${b.text(id)} AND status = 'completing' AND claim = ${b.text(claim)} RETURNING id`;
367
+ return (await run(b.statement(sql))).length > 0;
368
+ },
369
+ async cleaned(id, now) {
370
+ const b = binder(dialect);
371
+ const sql = `UPDATE ${files} SET cleaned_at = ${b.time(now)}, updated_at = ${b.time(now)}
372
+ WHERE id = ${b.text(id)} AND cleaned_at IS NULL`;
373
+ await run(b.statement(sql));
374
+ },
375
+ async usage(owner) {
376
+ const b = binder(dialect);
377
+ const sql = `SELECT reserved_bytes, active_bytes, files FROM ${usage} WHERE owner = ${b.text(owner)}`;
378
+ return toUsage((await run(b.statement(sql)))[0]);
379
+ },
380
+ async stale({ kind, before, claimedBefore, limit, cursor }) {
381
+ const b = binder(dialect);
382
+ const time = kind === "expire" ? "expires_at" : "ended_at";
383
+ const work = kind === "expire" ? `expires_at < ${b.time(before)}
384
+ AND (status = 'pending' OR (status = 'completing' AND claimed_at < ${b.time(claimedBefore)}))` : `status IN (${CLEANUP_STATUSES}) AND cleaned_at IS NULL AND ended_at < ${b.time(before)}`;
385
+ const start = cursor === null ? null : decodeCursor(cursor);
386
+ const after = start ? `AND (${time}, ${byteOrder("id")}) > (${b.time(start.time)}, ${b.text(start.id)})` : "";
387
+ const sql = `SELECT ${RECORD_COLUMNS} FROM ${files} WHERE ${work} ${after}
388
+ ORDER BY ${time}, ${byteOrder("id")} LIMIT ${b.integer(limit + 1)}`;
389
+ const records = (await run(b.statement(sql))).map(toRecord);
390
+ const timeOf = (record) => kind === "expire" ? record.expiresAt : record.endedAt ?? /* @__PURE__ */ new Date(0);
391
+ const { kept, cursor: next } = page(records, limit, (last) => encodeCursor(timeOf(last), last.id));
392
+ return {
393
+ records: kept,
394
+ cursor: next
395
+ };
396
+ },
397
+ async owners(cursor, limit) {
398
+ const b = binder(dialect);
399
+ const after = cursor === null ? "" : `WHERE ${byteOrder("owner")} > ${b.text(cursor)}`;
400
+ const sql = `SELECT owner FROM ${usage} ${after} ORDER BY ${byteOrder("owner")} LIMIT ${b.integer(limit + 1)}`;
401
+ const { kept, cursor: next } = page((await run(b.statement(sql))).map((row) => String(row.owner)), limit, (last) => last);
402
+ return {
403
+ owners: kept,
404
+ cursor: next
405
+ };
406
+ }
407
+ };
408
+ }
409
+ // src/store/sql/sqlite.ts
410
+ const INSERT_COLUMNS = "id, route, key, owner, status, name, type, size, metadata, expires_at, created_at, updated_at, request_key";
411
+ const NOW_MS = "CAST((julianday('now') - 2440587.5) * 86400000 AS INTEGER)";
412
+ function sqliteWrites({ executor, tables }) {
413
+ const { files, usage } = tables;
414
+ const select = (id) => {
415
+ const b = binder("sqlite");
416
+ return b.statement(`SELECT ${RECORD_COLUMNS} FROM ${files} WHERE id = ${b.text(id)}`);
417
+ };
418
+ async function transitionBatch(counted, update, id) {
419
+ const statements = [{
420
+ sql: `${update.sql} RETURNING id`,
421
+ params: update.params
422
+ }, select(id)];
423
+ const [updated, found] = (await executor.batch(counted ? [counted, ...statements] : statements)).slice(-2);
424
+ return transition((updated?.length ?? 0) > 0, found?.[0]);
425
+ }
426
+ function usageFor(set, id, from, now, guard) {
427
+ if (set === null) return null;
428
+ const b = binder("sqlite");
429
+ return b.statement(`UPDATE ${usage} SET ${set}, updated_at = ${b.time(now)} FROM ${files} AS f
430
+ WHERE f.id = ${b.text(id)} AND f.status = ${b.text(from)} ${guard?.(b) ?? ""} AND ${usage}.owner = f.owner`);
431
+ }
432
+ function supersede(key, owner, accepted, now) {
433
+ const routes = [...new Set(accepted.map((file) => file.route))];
434
+ const superseded = (b) => `request_key = ${b.text(key)} AND owner IS ${b.text(owner)}
435
+ AND route IN (${routes.map((route) => b.text(route)).join(", ")}) AND status = 'pending'`;
436
+ const b = binder("sqlite");
437
+ const end = b.statement(`UPDATE ${files} SET status = 'aborted', ended_at = ${b.time(now)},
438
+ updated_at = ${b.time(now)} WHERE ${superseded(b)}`);
439
+ if (owner === null) return [end];
440
+ const counter = binder("sqlite");
441
+ const rows = (c) => `FROM ${files} WHERE ${superseded(c)}`;
442
+ return [counter.statement(`UPDATE ${usage}
443
+ SET reserved_bytes = reserved_bytes - (SELECT sum(size) ${rows(counter)}), updated_at = ${counter.time(now)}
444
+ WHERE owner = ${counter.text(owner)} AND EXISTS (SELECT 1 ${rows(counter)})`), end];
445
+ }
446
+ return {
447
+ async reserve({ owner, limit, expiresAt, requestKey, files: accepted }, now) {
448
+ const fits = (b, file) => owner === null || limit === null ? "1" : `coalesce((SELECT reserved_bytes + active_bytes FROM ${usage} WHERE owner = ${b.text(owner)}), 0)
449
+ + ${b.bigint(file.size)} <= ${b.bigint(limit)}`;
450
+ const statements = accepted.flatMap((file) => {
451
+ const row = binder("sqlite");
452
+ const insert = row.statement(`INSERT INTO ${files} (${INSERT_COLUMNS})
453
+ SELECT ${row.text(file.id)}, ${row.text(file.route)}, ${row.text(file.key)}, ${row.text(owner)}, 'pending',
454
+ ${row.text(file.name)}, ${row.text(file.type)}, ${row.bigint(file.size)}, ${row.text(file.metadata)},
455
+ ${row.time(expiresAt)}, ${row.time(now)}, ${row.time(now)}, ${row.text(requestKey)}
456
+ WHERE ${fits(row, file)} RETURNING id`);
457
+ if (owner === null) return [insert];
458
+ const counter = binder("sqlite");
459
+ return [insert, counter.statement(`INSERT INTO ${usage} (owner, reserved_bytes, active_bytes, files, updated_at)
460
+ SELECT ${counter.text(owner)}, ${counter.bigint(file.size)}, 0, 0, ${counter.time(now)}
461
+ WHERE ${fits(counter, file)}
462
+ ON CONFLICT (owner) DO UPDATE SET reserved_bytes = reserved_bytes + excluded.reserved_bytes,
463
+ updated_at = excluded.updated_at`)];
464
+ });
465
+ if (statements.length === 0) return [];
466
+ const superseded = requestKey === null ? [] : supersede(requestKey, owner, accepted, now);
467
+ const results = (await executor.batch([...superseded, ...statements])).slice(superseded.length);
468
+ const step = owner === null ? 1 : 2;
469
+ return accepted.map((_, index) => (results[index * step]?.length ?? 0) > 0 ? "reserved" : "over-quota");
470
+ },
471
+ async claim(id, claim, now, leaseMs) {
472
+ const b = binder("sqlite");
473
+ const update = b.statement(`UPDATE ${files}
474
+ SET status = 'completing', claim = ${b.text(claim)}, claimed_at = ${b.time(now)}, updated_at = ${b.time(now)}
475
+ WHERE id = ${b.text(id)} AND (status = 'pending'
476
+ OR (status = 'completing' AND claimed_at < ${b.time(new Date(now.getTime() - leaseMs))}))
477
+ RETURNING id`);
478
+ const [claimed, found] = await executor.batch([update, select(id)]);
479
+ return claimOutcome((claimed?.length ?? 0) > 0, found?.[0]);
480
+ },
481
+ async complete(id, claim, result, now) {
482
+ const counted = usageFor("reserved_bytes = reserved_bytes - f.size, active_bytes = active_bytes + f.size, files = files + 1", id, "completing", now, (b) => `AND f.claim = ${b.text(claim)}`);
483
+ const b = binder("sqlite");
484
+ return transitionBatch(counted, b.statement(`UPDATE ${files} SET status = 'completed', result = ${b.text(result)},
485
+ completed_at = ${b.time(now)}, updated_at = ${b.time(now)}
486
+ WHERE id = ${b.text(id)} AND status = 'completing' AND claim = ${b.text(claim)}`), id);
487
+ },
488
+ async end(id, from, to, now, options) {
489
+ const counted = usageFor(releaseFrom(from, "f.size"), id, from, now);
490
+ const b = binder("sqlite");
491
+ return transitionBatch(counted, b.statement(`UPDATE ${files}
492
+ SET status = ${b.text(to)}${options?.cleaned ? `, cleaned_at = ${b.time(now)}` : ""}, ended_at = ${b.time(now)},
493
+ updated_at = ${b.time(now)} WHERE id = ${b.text(id)} AND status = ${b.text(from)}`), id);
494
+ },
495
+ async revoke(owner, now) {
496
+ const counter = binder("sqlite");
497
+ const pending = (b) => `FROM ${files} WHERE owner = ${b.text(owner)} AND status = 'pending'`;
498
+ const count = counter.statement(`UPDATE ${usage}
499
+ SET reserved_bytes = reserved_bytes - (SELECT sum(size) ${pending(counter)}), updated_at = ${counter.time(now)}
500
+ WHERE owner = ${counter.text(owner)} AND EXISTS (SELECT 1 ${pending(counter)})`);
501
+ const b = binder("sqlite");
502
+ const revoke = b.statement(`UPDATE ${files} SET status = 'aborted', ended_at = ${b.time(now)},
503
+ updated_at = ${b.time(now)} WHERE owner = ${b.text(owner)} AND status = 'pending' RETURNING id`);
504
+ const [, revoked] = await executor.batch([count, revoke]);
505
+ return revoked?.length ?? 0;
506
+ },
507
+ async reconcile(owner) {
508
+ const b = binder("sqlite");
509
+ const sql = `INSERT INTO ${usage} (owner, reserved_bytes, active_bytes, files, updated_at)
510
+ SELECT ${b.text(owner)}, ${RECOUNT.reserved}, ${RECOUNT.active}, ${RECOUNT.files}, ${NOW_MS}
511
+ FROM ${files} WHERE owner = ${b.text(owner)}
512
+ HAVING ${RECOUNT.reserved} + ${RECOUNT.active} + ${RECOUNT.files} > 0
513
+ OR EXISTS (SELECT 1 FROM ${usage} WHERE owner = ${b.text(owner)})
514
+ ON CONFLICT (owner) DO UPDATE SET reserved_bytes = excluded.reserved_bytes,
515
+ active_bytes = excluded.active_bytes, files = excluded.files, updated_at = excluded.updated_at
516
+ WHERE reserved_bytes <> excluded.reserved_bytes OR active_bytes <> excluded.active_bytes
517
+ OR files <> excluded.files
518
+ RETURNING owner`;
519
+ return (await runStatement(executor, b.statement(sql))).length > 0;
520
+ }
521
+ };
522
+ }
523
+ // src/store/sql/tables.ts
524
+ const NAME = /^[A-Za-z_][A-Za-z0-9_]*$/;
525
+ const NO_SQLITE_SCHEMA = "SQLite has no schemas: remove schema from { tables }.";
526
+ const USAGE_COLUMNS = [
527
+ "owner",
528
+ "reserved_bytes",
529
+ "active_bytes",
530
+ "files",
531
+ "updated_at"
532
+ ];
533
+ function tableNames(tables = {}, dialect) {
534
+ const { schema } = tables;
535
+ if (schema !== void 0 && dialect === "sqlite") throw configError(NO_SQLITE_SCHEMA);
536
+ const names = {
537
+ files: tables.files ?? "cloudrop_files",
538
+ usage: tables.usage ?? "cloudrop_usage"
539
+ };
540
+ const checked = schema === void 0 ? names : {
541
+ ...names,
542
+ schema
543
+ };
544
+ for (const [option, name] of Object.entries(checked)) if (typeof name !== "string" || !NAME.test(name)) {
545
+ const what = option === "schema" ? "schema" : `${option} table`;
546
+ throw configError(`The ${what} name ${JSON.stringify(name)} is not allowed. Use letters, digits and "_", not starting with a digit: { tables: { ${option}: "..." } }.`);
547
+ }
548
+ return checked;
549
+ }
550
+ function quoteTables({ files, usage, schema }) {
551
+ const prefix = schema === void 0 ? "" : `"${schema}".`;
552
+ return {
553
+ files: `${prefix}"${files}"`,
554
+ usage: `${prefix}"${usage}"`
555
+ };
556
+ }
557
+ async function runs(executor, sql) {
558
+ try {
559
+ await executor.query(sql, []);
560
+ return true;
561
+ } catch {
562
+ return false;
563
+ }
564
+ }
565
+ async function findMissing(executor, table, columns) {
566
+ if (!await runs(executor, `SELECT 1 FROM ${table} WHERE 1 = 0`)) return `The table ${table} does not exist.`;
567
+ for (const column of columns) if (!await runs(executor, `SELECT ${column} FROM ${table} WHERE 1 = 0`)) return `The table ${table} has no column "${column}".`;
568
+ return null;
569
+ }
570
+ async function checkSchema(executor, quoted) {
571
+ const tables = [[quoted.files, FILE_COLUMNS], [quoted.usage, USAGE_COLUMNS]];
572
+ for (const [table, columns] of tables) try {
573
+ await executor.query(`SELECT ${columns.join(", ")} FROM ${table} WHERE 1 = 0`, []);
574
+ } catch (error) {
575
+ const missing = await runs(executor, "SELECT 1") ? await findMissing(executor, table, columns) : null;
576
+ if (missing === null) throw error;
577
+ throw new CloudropError("INVALID_CONFIG", `${missing} Create the store's tables as the cloudrop docs show, or pass their names in { tables }.`, { cause: error });
578
+ }
579
+ }
580
+ // src/store/sql/store.ts
581
+ const NEEDS_POSTGRES = "transaction: true needs Postgres. SQLite has one writer at a time, so a transaction held open while onComplete runs would stall every other upload; leave the option out and completions use a lease.";
582
+ const NEEDS_TRANSACTION = "transaction: true needs an executor with transaction(), such as pgExecutor or postgresJsExecutor. Add one to your executor, or leave the option out and completions use a lease.";
583
+ const LOCK_TIMEOUT = "2s";
584
+ function methodsOver(context) {
585
+ const writes = context.dialect === "postgres" ? postgresWrites(context) : sqliteWrites(context);
586
+ return {
587
+ ...singleStatementMethods(context),
588
+ ...writes
589
+ };
590
+ }
591
+ function afterCheck(methods, ready) {
592
+ const checked = {};
593
+ for (const [name, method] of Object.entries(methods)) checked[name] = async (...args) => {
594
+ await ready();
595
+ return method(...args);
596
+ };
597
+ return checked;
598
+ }
599
+ function sqlStore(executor, options = {}) {
600
+ const { dialect } = executor;
601
+ if (dialect !== "postgres" && dialect !== "sqlite") throw configError(`The executor's dialect ${JSON.stringify(dialect)} is not supported. Use "postgres" or "sqlite".`);
602
+ const tables = quoteTables(tableNames(options.tables, dialect));
603
+ let schema;
604
+ const ready = () => {
605
+ schema ??= checkSchema(executor, tables).catch((error) => {
606
+ schema = void 0;
607
+ throw error;
608
+ });
609
+ return schema;
610
+ };
611
+ const store = afterCheck(methodsOver({
612
+ executor,
613
+ dialect,
614
+ tables
615
+ }), ready);
616
+ if (!options.transaction) return store;
617
+ if (dialect !== "postgres") throw configError(NEEDS_POSTGRES);
618
+ if (!executor.transaction) throw configError(NEEDS_TRANSACTION);
619
+ const transaction = executor.transaction.bind(executor);
620
+ return {
621
+ ...store,
622
+ async transaction(run) {
623
+ await ready();
624
+ let timedOut = false;
625
+ let answer;
626
+ try {
627
+ return await transaction(async (inner, tx) => {
628
+ const methods = methodsOver({
629
+ executor: inner,
630
+ dialect,
631
+ tables
632
+ });
633
+ const capLockWait = async () => {
634
+ if (dialect !== "postgres") return void 0;
635
+ const [row] = await inner.query(`WITH before AS MATERIALIZED (SELECT current_setting('lock_timeout') AS saved)
636
+ SELECT saved, set_config('lock_timeout', '${LOCK_TIMEOUT}', true) FROM before`, []);
637
+ return String(row?.saved);
638
+ };
639
+ const claim = async (...args) => {
640
+ const saved = await capLockWait();
641
+ let outcome;
642
+ try {
643
+ outcome = await methods.claim(...args);
644
+ } catch (error) {
645
+ if (!isLockTimeout(error)) throw error;
646
+ timedOut = true;
647
+ return { kind: "busy" };
648
+ }
649
+ if (saved !== void 0) await inner.query("SELECT set_config('lock_timeout', $1::text, true)", [saved]);
650
+ return outcome;
651
+ };
652
+ const value = await run(tx, {
653
+ ...methods,
654
+ claim
655
+ });
656
+ answer = { value };
657
+ return value;
658
+ });
659
+ } catch (error) {
660
+ if (timedOut && answer && isLockTimeout(error)) return answer.value;
661
+ throw error;
662
+ }
663
+ }
664
+ };
665
+ }
666
+ // src/adapters/transactional.ts
667
+ function withRoute(store) {
668
+ return Object.assign(store, { route: routeFor(store) });
669
+ }
670
+ export { sequential as i, sqlStore as n, tableNames as r, withRoute as t };
671
+
672
+ //# sourceMappingURL=transactional-DnvnGsVH.js.map