or3-provider-sqlite 0.0.17 → 0.0.18
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 +23 -1
- package/dist/module.json +1 -1
- package/dist/runtime/server/plugins/register.js +2 -1
- package/dist/runtime/server/sync/sqlite-sync-gateway-adapter.d.ts +2 -0
- package/dist/runtime/server/sync/sqlite-sync-gateway-adapter.js +137 -74
- package/dist/runtime/server/webhooks/sqlite-webhook-store.js +11 -4
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -11,6 +11,26 @@ SQLite sync and workspace store provider for OR3 Chat. Provides a lightweight, s
|
|
|
11
11
|
- **Admin stores** (`sqlite`) — workspace access/lifecycle, workspace settings, user search, and deployment-admin grants (local, Bun, and Turso runtimes)
|
|
12
12
|
- **RateLimitProvider** (`sqlite`) — durable rate-limit counters
|
|
13
13
|
|
|
14
|
+
SSR-authenticated deployments also activate SQLite when it is selected only by
|
|
15
|
+
`OR3_LIMITS_ENABLED=true` and `OR3_LIMITS_STORAGE_PROVIDER=sqlite`, independently
|
|
16
|
+
of the account workspace backend.
|
|
17
|
+
|
|
18
|
+
Canonical storage queries include bounded retained deleted metadata pages and
|
|
19
|
+
advertise `retainedStorageMetadata: 'v1'` on native SQLite and D1. Missing sizes in
|
|
20
|
+
delete-before-put rows remain unknown; these reads never replay sync history.
|
|
21
|
+
|
|
22
|
+
Upload quota admission groups pending authorizations by hash, keeps consumed
|
|
23
|
+
uploads charged until their original expiry or canonical metadata admission,
|
|
24
|
+
and runs atomically on native SQLite and D1. Exact consumed receipts can retry
|
|
25
|
+
within that lifetime without consuming twice. After expiry, obtain a fresh
|
|
26
|
+
reservation; mismatched hash, MIME, size, workspace, or storage ID is rejected.
|
|
27
|
+
Quota measures logical live metadata plus pending authorizations, not retained
|
|
28
|
+
physical disk usage.
|
|
29
|
+
|
|
30
|
+
## Atomic webhook registration quotas
|
|
31
|
+
|
|
32
|
+
The webhook store advertises `registrationLimit: 'atomic-v1'`. `createWebhook(input, limit)` checks the user/workspace quota (or instance-wide admin quota) in the same immediate transaction as insertion. Independent connections share the limit; exhaustion throws `WEBHOOK_LIMIT_EXCEEDED`. The optional argument leaves non-quota internal calls unchanged. OR3 Chat requires this capability for registration; ship this provider change before integrating the coordinated host change.
|
|
33
|
+
|
|
14
34
|
## Install
|
|
15
35
|
|
|
16
36
|
```bash
|
|
@@ -291,7 +311,9 @@ The canonical-history qualification lane defaults to a sibling `../or3-chat` che
|
|
|
291
311
|
|
|
292
312
|
## Workspace Files and Trash admission
|
|
293
313
|
|
|
294
|
-
Persistent Projects uses this same capability for opaque `or3:project-settings`, `or3:project-memory`, and `or3:project-source` posts. Preserve their JSON, metadata, and every original/extraction `file_hashes` reference. The project-aware canonical reader resolves `threads.project_id` or a single legacy membership in its authorized SQLite snapshot, returning `project_ownership: resolved | conflict`. String entries and JSON-encoded membership arrays remain supported;
|
|
314
|
+
Persistent Projects uses this same capability for opaque `or3:project-settings`, `or3:project-memory`, and `or3:project-source` posts. Preserve their JSON, metadata, and every original/extraction `file_hashes` reference. The project-aware canonical reader resolves `threads.project_id` or a single legacy membership in its authorized SQLite snapshot, returning `project_ownership: resolved | conflict`. String entries and JSON-encoded membership arrays remain supported; chat IDs are trimmed and entry kinds ignore case and surrounding whitespace, matching the host's legacy normalization. Malformed or ambiguous memberships do not grant server execution. Hosts without this result must refuse project-sensitive server admission rather than infer ownership from the visible UI.
|
|
315
|
+
|
|
316
|
+
Explicit ownership requires a live project in the same workspace. A missing or deleted project releases the chat even if a concurrent thread write retained its former pointer; legacy folders do not override that explicit release. Canonical reads leave the persisted pointer untouched.
|
|
295
317
|
|
|
296
318
|
Version 0.0.15 declares `projectOwnership: 'v1'` on the native canonical-history adapter. D1 does not advertise this contract. Projects qualification: `OR3_PROJECT_HOST_ROOT=/absolute/path/to/or3-chat bun x vitest run src/runtime/__tests__/sqlite-sync-gateway-adapter.test.ts`. This explicit lane uses the host's canonical-reader query contract while retaining the pinned standalone fixture for existing contracts. Qualify the published exact version with the disposable host cloud journey.
|
|
297
319
|
|
package/dist/module.json
CHANGED
|
@@ -33,7 +33,8 @@ export default defineNitroPlugin(async (nitroApp) => {
|
|
|
33
33
|
const syncSelected = config.sync?.enabled === true && config.sync?.provider === SQLITE_PROVIDER_ID;
|
|
34
34
|
const connectSelected = config.connect?.enabled === true && config.connect?.provider === SQLITE_PROVIDER_ID;
|
|
35
35
|
const backgroundJobsSelected = config.backgroundJobs?.enabled === true && config.backgroundJobs?.storageProvider === SQLITE_PROVIDER_ID;
|
|
36
|
-
|
|
36
|
+
const limitsSelected = config.limits?.enabled === true && config.limits?.storageProvider === SQLITE_PROVIDER_ID;
|
|
37
|
+
if (!workspaceSelected && !connectSelected && !backgroundJobsSelected && !limitsSelected)
|
|
37
38
|
return;
|
|
38
39
|
const driver = getSqliteDriver();
|
|
39
40
|
if (driver === "d1" && connectSelected) {
|
|
@@ -15,6 +15,7 @@ export declare class SqliteSyncGatewayAdapter implements SyncGatewayAdapter {
|
|
|
15
15
|
get capabilities(): {
|
|
16
16
|
readonly snapshotBootstrap: "snapshot-v1";
|
|
17
17
|
readonly historyRetention: "snapshot-v1";
|
|
18
|
+
readonly retainedStorageMetadata: "v1";
|
|
18
19
|
readonly backgroundGenerationHistory?: undefined;
|
|
19
20
|
readonly canonicalChatHistory?: undefined;
|
|
20
21
|
readonly projectOwnership?: undefined;
|
|
@@ -26,6 +27,7 @@ export declare class SqliteSyncGatewayAdapter implements SyncGatewayAdapter {
|
|
|
26
27
|
readonly canonicalChatHistory: "v1";
|
|
27
28
|
readonly projectOwnership: "v1";
|
|
28
29
|
readonly workspaceItems: "v1";
|
|
30
|
+
readonly retainedStorageMetadata: "v1";
|
|
29
31
|
};
|
|
30
32
|
private get db();
|
|
31
33
|
readChatHistory(actor: CanonicalHistoryActor, query: CanonicalChatQuery, signal?: AbortSignal): Promise<CanonicalChatReadResult>;
|
|
@@ -33,6 +33,21 @@ const SESSION_CONTEXT_KEY_PREFIX = "__or3_session_context_";
|
|
|
33
33
|
const MIN_SYNC_RETENTION_SECONDS = 60 * 60;
|
|
34
34
|
const MAX_SYNC_RETENTION_SECONDS = 365 * 24 * 60 * 60;
|
|
35
35
|
const MAX_SYNC_PAYLOAD_BYTES = 256 * 1024;
|
|
36
|
+
const PENDING_UPLOAD_RESERVATIONS_SQL = `
|
|
37
|
+
SELECT MIN(intent.id) AS id, intent.hash,
|
|
38
|
+
MAX(intent.size_bytes) AS reserved_bytes, MAX(intent.expires_at) AS expires_at
|
|
39
|
+
FROM upload_intents AS intent
|
|
40
|
+
WHERE intent.workspace_id = ? AND intent.status IN ('active', 'consumed')
|
|
41
|
+
AND intent.expires_at > ? AND intent.size_bytes > 0
|
|
42
|
+
AND NOT EXISTS (
|
|
43
|
+
SELECT 1 FROM s_file_meta AS metadata
|
|
44
|
+
WHERE metadata.workspace_id = intent.workspace_id AND metadata.deleted = 0
|
|
45
|
+
AND lower(CASE WHEN instr(trim(metadata.id), ':') > 0
|
|
46
|
+
THEN substr(trim(metadata.id), instr(trim(metadata.id), ':') + 1)
|
|
47
|
+
ELSE trim(metadata.id) END) = intent.hash
|
|
48
|
+
)
|
|
49
|
+
GROUP BY intent.hash
|
|
50
|
+
`;
|
|
36
51
|
function uid() {
|
|
37
52
|
return globalThis.crypto.randomUUID();
|
|
38
53
|
}
|
|
@@ -427,14 +442,16 @@ export class SqliteSyncGatewayAdapter {
|
|
|
427
442
|
get capabilities() {
|
|
428
443
|
return isD1Driver() ? {
|
|
429
444
|
snapshotBootstrap: "snapshot-v1",
|
|
430
|
-
historyRetention: "snapshot-v1"
|
|
445
|
+
historyRetention: "snapshot-v1",
|
|
446
|
+
retainedStorageMetadata: "v1"
|
|
431
447
|
} : {
|
|
432
448
|
snapshotBootstrap: "snapshot-v1",
|
|
433
449
|
historyRetention: "snapshot-v1",
|
|
434
450
|
backgroundGenerationHistory: "v1",
|
|
435
451
|
canonicalChatHistory: "v1",
|
|
436
452
|
projectOwnership: "v1",
|
|
437
|
-
workspaceItems: "v1"
|
|
453
|
+
workspaceItems: "v1",
|
|
454
|
+
retainedStorageMetadata: "v1"
|
|
438
455
|
};
|
|
439
456
|
}
|
|
440
457
|
get db() {
|
|
@@ -460,18 +477,32 @@ export class SqliteSyncGatewayAdapter {
|
|
|
460
477
|
const threadRevision = raw.prepare("SELECT value FROM chat_history_revisions WHERE workspace_id = ? AND thread_id = ?").get(actor.workspaceId, query.thread_id);
|
|
461
478
|
const row = raw.prepare("SELECT id, data_json, clock, deleted FROM s_threads WHERE workspace_id = ? AND id = ?").get(actor.workspaceId, query.thread_id);
|
|
462
479
|
const thread = row ? parse(row) : void 0;
|
|
463
|
-
if (!thread
|
|
480
|
+
if (!thread) return {
|
|
464
481
|
status: "ok",
|
|
465
482
|
project_ownership: "resolved",
|
|
466
483
|
revision: String(threadRevision?.value ?? 0),
|
|
467
484
|
thread
|
|
468
485
|
};
|
|
486
|
+
if (thread.project_id) {
|
|
487
|
+
const owner = raw.prepare("SELECT id FROM s_projects WHERE workspace_id = ? AND id = ? AND COALESCE(deleted, 0) = 0").get(actor.workspaceId, thread.project_id);
|
|
488
|
+
return {
|
|
489
|
+
status: "ok",
|
|
490
|
+
project_ownership: "resolved",
|
|
491
|
+
revision: String(threadRevision?.value ?? 0),
|
|
492
|
+
thread: { ...thread, project_id: owner ? thread.project_id : null }
|
|
493
|
+
};
|
|
494
|
+
}
|
|
469
495
|
const projects = raw.prepare("SELECT id, data_json FROM s_projects WHERE workspace_id = ? AND COALESCE(deleted, 0) = 0").all(actor.workspaceId);
|
|
470
496
|
const owners = projects.filter((project) => {
|
|
471
497
|
const payload = JSON.parse(project.data_json);
|
|
472
498
|
const entries = typeof payload.data === "string" ? JSON.parse(payload.data) : payload.data ?? [];
|
|
473
499
|
if (!Array.isArray(entries)) throw new Error("Canonical project membership is unresolved.");
|
|
474
|
-
return entries.some((entry) =>
|
|
500
|
+
return entries.some((entry) => {
|
|
501
|
+
if (typeof entry === "string") return entry.trim() === query.thread_id;
|
|
502
|
+
if (!entry || typeof entry !== "object" || Array.isArray(entry) || typeof entry.id !== "string") return false;
|
|
503
|
+
const kind = typeof entry.kind === "string" ? entry.kind.trim().toLowerCase() : entry.kind;
|
|
504
|
+
return (kind === void 0 || kind === "chat") && entry.id.trim() === query.thread_id;
|
|
505
|
+
});
|
|
475
506
|
});
|
|
476
507
|
return {
|
|
477
508
|
status: "ok",
|
|
@@ -801,21 +832,28 @@ export class SqliteSyncGatewayAdapter {
|
|
|
801
832
|
WHERE workspace_id = ? AND deleted = 0`).all(input.workspaceId);
|
|
802
833
|
let usedBytes = 0;
|
|
803
834
|
let alreadyStored = false;
|
|
835
|
+
const liveSizes = /* @__PURE__ */ new Map();
|
|
804
836
|
for (const row of liveRows) {
|
|
805
837
|
const payload = JSON.parse(row.data_json);
|
|
806
838
|
const size = payload.size_bytes ?? payload.sizeBytes;
|
|
807
839
|
if (typeof size !== "number" || !Number.isSafeInteger(size) || size < 0) {
|
|
808
840
|
throw createError({ statusCode: 500, statusMessage: "Invalid canonical file size" });
|
|
809
841
|
}
|
|
810
|
-
|
|
811
|
-
|
|
842
|
+
const liveHash = normalizeStorageHash(row.id);
|
|
843
|
+
const previousSize = liveSizes.get(liveHash);
|
|
844
|
+
if (previousSize !== void 0 && previousSize !== size) {
|
|
845
|
+
throw createError({ statusCode: 500, statusMessage: "Conflicting canonical file size" });
|
|
846
|
+
}
|
|
847
|
+
if (previousSize === void 0) usedBytes += size;
|
|
848
|
+
liveSizes.set(liveHash, size);
|
|
849
|
+
if (liveHash === hash) alreadyStored = true;
|
|
812
850
|
}
|
|
813
|
-
const totals = raw.prepare(`SELECT
|
|
851
|
+
const totals = raw.prepare(`WITH pending AS (${PENDING_UPLOAD_RESERVATIONS_SQL}) SELECT
|
|
814
852
|
COALESCE(SUM(reserved_bytes), 0) AS reserved_bytes,
|
|
815
|
-
MAX(CASE WHEN hash = ?
|
|
816
|
-
FROM
|
|
817
|
-
const
|
|
818
|
-
if (input.workspaceQuotaBytes !== void 0 && usedBytes + totals.reserved_bytes +
|
|
853
|
+
COALESCE(MAX(CASE WHEN hash = ? THEN reserved_bytes END), 0) AS same_hash
|
|
854
|
+
FROM pending`).get(input.workspaceId, now, hash);
|
|
855
|
+
const addedBytes = alreadyStored ? 0 : Math.max(0, input.sizeBytes - totals.same_hash);
|
|
856
|
+
if (input.workspaceQuotaBytes !== void 0 && usedBytes + totals.reserved_bytes + addedBytes > input.workspaceQuotaBytes) {
|
|
819
857
|
throw createError({ statusCode: 413, statusMessage: "Workspace storage quota exceeded" });
|
|
820
858
|
}
|
|
821
859
|
raw.prepare(`INSERT INTO upload_intents (
|
|
@@ -827,7 +865,7 @@ export class SqliteSyncGatewayAdapter {
|
|
|
827
865
|
hash,
|
|
828
866
|
input.mimeType,
|
|
829
867
|
input.sizeBytes,
|
|
830
|
-
|
|
868
|
+
input.sizeBytes,
|
|
831
869
|
input.expiresAt,
|
|
832
870
|
now
|
|
833
871
|
);
|
|
@@ -835,42 +873,39 @@ export class SqliteSyncGatewayAdapter {
|
|
|
835
873
|
}
|
|
836
874
|
async consumeUploadIntent(event, input) {
|
|
837
875
|
await assertWorkspaceScopeAuthorized(event, input.workspaceId);
|
|
838
|
-
|
|
839
|
-
|
|
840
|
-
|
|
841
|
-
|
|
842
|
-
SET status = 'consumed', storage_id = ?, consumed_at = ?
|
|
843
|
-
WHERE id = ? AND workspace_id = ? AND status = 'active' AND expires_at > ?
|
|
844
|
-
AND hash = ? AND mime_type = ? AND size_bytes = ?`,
|
|
845
|
-
input.storageId,
|
|
846
|
-
now,
|
|
847
|
-
input.intentId,
|
|
848
|
-
input.workspaceId,
|
|
849
|
-
now,
|
|
850
|
-
normalizeStorageHash(input.hash),
|
|
851
|
-
input.mimeType,
|
|
852
|
-
input.sizeBytes
|
|
853
|
-
);
|
|
854
|
-
if ((result2.meta?.changes ?? 0) !== 1) {
|
|
855
|
-
throw createError({ statusCode: 409, statusMessage: "Upload intent expired, mismatched, or already consumed" });
|
|
856
|
-
}
|
|
857
|
-
return;
|
|
858
|
-
}
|
|
859
|
-
const raw = getRawDb();
|
|
860
|
-
const result = raw.prepare(`UPDATE upload_intents
|
|
876
|
+
const now = nowEpoch();
|
|
877
|
+
const hash = normalizeStorageHash(input.hash);
|
|
878
|
+
const raw = isD1Driver() ? null : getRawDb();
|
|
879
|
+
const sql = `UPDATE upload_intents
|
|
861
880
|
SET status = 'consumed', storage_id = ?, consumed_at = ?
|
|
862
881
|
WHERE id = ? AND workspace_id = ? AND status = 'active' AND expires_at > ?
|
|
863
|
-
AND hash = ? AND mime_type = ? AND size_bytes =
|
|
882
|
+
AND hash = ? AND mime_type = ? AND size_bytes = ?`;
|
|
883
|
+
const parameters = [
|
|
864
884
|
input.storageId,
|
|
865
|
-
|
|
885
|
+
now,
|
|
866
886
|
input.intentId,
|
|
867
887
|
input.workspaceId,
|
|
868
|
-
|
|
869
|
-
|
|
888
|
+
now,
|
|
889
|
+
hash,
|
|
870
890
|
input.mimeType,
|
|
871
891
|
input.sizeBytes
|
|
872
|
-
|
|
873
|
-
|
|
892
|
+
];
|
|
893
|
+
const changes = raw ? raw.prepare(sql).run(...parameters).changes : (await d1Run(sql, ...parameters)).meta?.changes;
|
|
894
|
+
if (changes === 1) return;
|
|
895
|
+
const receiptSql = `SELECT 1 FROM upload_intents
|
|
896
|
+
WHERE id = ? AND workspace_id = ? AND status = 'consumed' AND expires_at > ?
|
|
897
|
+
AND hash = ? AND mime_type = ? AND size_bytes = ? AND storage_id = ?`;
|
|
898
|
+
const receiptParameters = [
|
|
899
|
+
input.intentId,
|
|
900
|
+
input.workspaceId,
|
|
901
|
+
now,
|
|
902
|
+
hash,
|
|
903
|
+
input.mimeType,
|
|
904
|
+
input.sizeBytes,
|
|
905
|
+
input.storageId
|
|
906
|
+
];
|
|
907
|
+
const receipt = raw ? raw.prepare(receiptSql).get(...receiptParameters) : (await d1All(receiptSql, ...receiptParameters))[0];
|
|
908
|
+
if (!receipt) {
|
|
874
909
|
throw createError({ statusCode: 409, statusMessage: "Upload intent expired, mismatched, or already consumed" });
|
|
875
910
|
}
|
|
876
911
|
}
|
|
@@ -912,10 +947,9 @@ export class SqliteSyncGatewayAdapter {
|
|
|
912
947
|
throw createError({ statusCode: 400, statusMessage: "Invalid canonical storage cursor" });
|
|
913
948
|
}
|
|
914
949
|
const now = input.now ?? nowEpoch();
|
|
915
|
-
const rows2 = await all(`
|
|
916
|
-
FROM
|
|
917
|
-
WHERE
|
|
918
|
-
AND id > ? AND reserved_bytes > 0 AND (? IS NULL OR hash = ?)
|
|
950
|
+
const rows2 = await all(`WITH pending AS (${PENDING_UPLOAD_RESERVATIONS_SQL})
|
|
951
|
+
SELECT id, hash, reserved_bytes, expires_at FROM pending
|
|
952
|
+
WHERE id > ? AND (? IS NULL OR hash = ?)
|
|
919
953
|
ORDER BY id ASC LIMIT ?`, workspaceId, now, after[0] ?? "", hash ?? null, hash ?? null, limit + 1);
|
|
920
954
|
const hasMore2 = rows2.length > limit;
|
|
921
955
|
const page2 = hasMore2 ? rows2.slice(0, limit) : rows2;
|
|
@@ -937,7 +971,8 @@ export class SqliteSyncGatewayAdapter {
|
|
|
937
971
|
}) } : {}
|
|
938
972
|
};
|
|
939
973
|
}
|
|
940
|
-
if (input.kind === "live_metadata") {
|
|
974
|
+
if (input.kind === "live_metadata" || input.kind === "retained_metadata") {
|
|
975
|
+
const retained = input.kind === "retained_metadata";
|
|
941
976
|
if (after.length > 1) {
|
|
942
977
|
throw createError({ statusCode: 400, statusMessage: "Invalid canonical storage cursor" });
|
|
943
978
|
}
|
|
@@ -945,7 +980,7 @@ export class SqliteSyncGatewayAdapter {
|
|
|
945
980
|
SELECT id, data_json, updated_at
|
|
946
981
|
FROM s_file_meta
|
|
947
982
|
WHERE workspace_id = ?
|
|
948
|
-
AND deleted =
|
|
983
|
+
AND deleted = ?
|
|
949
984
|
AND id > ?
|
|
950
985
|
AND (? IS NULL OR lower(
|
|
951
986
|
CASE
|
|
@@ -956,7 +991,7 @@ export class SqliteSyncGatewayAdapter {
|
|
|
956
991
|
) = ?)
|
|
957
992
|
ORDER BY id ASC
|
|
958
993
|
LIMIT ?
|
|
959
|
-
`, workspaceId, after[0] ?? "", hash ?? null, hash ?? null, limit + 1);
|
|
994
|
+
`, workspaceId, retained ? 1 : 0, after[0] ?? "", hash ?? null, hash ?? null, limit + 1);
|
|
960
995
|
const hasMore2 = rows2.length > limit;
|
|
961
996
|
const page2 = hasMore2 ? rows2.slice(0, limit) : rows2;
|
|
962
997
|
const items = page2.map((row) => {
|
|
@@ -967,21 +1002,25 @@ export class SqliteSyncGatewayAdapter {
|
|
|
967
1002
|
throw createError({ statusCode: 500, statusMessage: "Invalid canonical file metadata" });
|
|
968
1003
|
}
|
|
969
1004
|
const size = payload.size_bytes ?? payload.sizeBytes;
|
|
970
|
-
|
|
1005
|
+
const missingSize = !("size_bytes" in payload) && !("sizeBytes" in payload);
|
|
1006
|
+
if (!(retained && missingSize) && (typeof size !== "number" || !Number.isSafeInteger(size) || size < 0)) {
|
|
971
1007
|
throw createError({ statusCode: 500, statusMessage: "Invalid canonical file size" });
|
|
972
1008
|
}
|
|
973
1009
|
const storageId = payload.storage_id ?? payload.storageId;
|
|
974
1010
|
const fileKind = payload.kind === "image" ? "image" : payload.kind === "pdf" ? "pdf" : payload.kind === "file" ? "file" : void 0;
|
|
975
|
-
|
|
976
|
-
kind: "metadata",
|
|
1011
|
+
const metadata = {
|
|
977
1012
|
hash: normalizeStorageHash(row.id),
|
|
978
|
-
sizeBytes: size,
|
|
979
1013
|
...typeof storageId === "string" && storageId ? { storageId } : {},
|
|
980
1014
|
...typeof (payload.mime_type ?? payload.mimeType) === "string" ? { mimeType: String(payload.mime_type ?? payload.mimeType) } : {},
|
|
981
1015
|
...typeof payload.name === "string" ? { name: payload.name } : {},
|
|
982
1016
|
...fileKind ? { fileKind } : {},
|
|
983
1017
|
updatedAt: row.updated_at
|
|
984
1018
|
};
|
|
1019
|
+
return retained ? {
|
|
1020
|
+
...metadata,
|
|
1021
|
+
kind: "retained_metadata",
|
|
1022
|
+
...typeof size === "number" ? { sizeBytes: size } : {}
|
|
1023
|
+
} : { ...metadata, kind: "metadata", sizeBytes: size };
|
|
985
1024
|
});
|
|
986
1025
|
const last2 = page2[page2.length - 1];
|
|
987
1026
|
return {
|
|
@@ -1946,53 +1985,77 @@ export class SqliteSyncGatewayAdapter {
|
|
|
1946
1985
|
WHERE workspace_id = ? AND deleted = 0`,
|
|
1947
1986
|
input.workspaceId
|
|
1948
1987
|
);
|
|
1949
|
-
|
|
1950
|
-
let alreadyStored = false;
|
|
1988
|
+
const liveSizes = /* @__PURE__ */ new Map();
|
|
1951
1989
|
for (const row of liveRows) {
|
|
1952
1990
|
const payload = JSON.parse(row.data_json);
|
|
1953
1991
|
const size = payload.size_bytes ?? payload.sizeBytes;
|
|
1954
1992
|
if (typeof size !== "number" || !Number.isSafeInteger(size) || size < 0) {
|
|
1955
1993
|
throw createError({ statusCode: 500, statusMessage: "Invalid canonical file size" });
|
|
1956
1994
|
}
|
|
1957
|
-
|
|
1958
|
-
|
|
1959
|
-
|
|
1960
|
-
|
|
1961
|
-
|
|
1962
|
-
|
|
1963
|
-
FROM upload_intents
|
|
1964
|
-
WHERE workspace_id = ? AND status = 'active' AND expires_at > ?`,
|
|
1965
|
-
hash,
|
|
1966
|
-
input.workspaceId,
|
|
1967
|
-
now
|
|
1968
|
-
);
|
|
1969
|
-
const reservedBytes = alreadyStored || totals?.same_hash === 1 ? 0 : input.sizeBytes;
|
|
1970
|
-
if (input.workspaceQuotaBytes !== void 0 && usedBytes + (totals?.reserved_bytes ?? 0) + reservedBytes > input.workspaceQuotaBytes) {
|
|
1971
|
-
throw createError({ statusCode: 413, statusMessage: "Workspace storage quota exceeded" });
|
|
1995
|
+
const liveHash = normalizeStorageHash(row.id);
|
|
1996
|
+
const previousSize = liveSizes.get(liveHash);
|
|
1997
|
+
if (previousSize !== void 0 && previousSize !== size) {
|
|
1998
|
+
throw createError({ statusCode: 500, statusMessage: "Conflicting canonical file size" });
|
|
1999
|
+
}
|
|
2000
|
+
liveSizes.set(liveHash, size);
|
|
1972
2001
|
}
|
|
1973
|
-
await d1Batch([
|
|
2002
|
+
const results = await d1Batch([
|
|
1974
2003
|
{
|
|
1975
2004
|
sql: `UPDATE upload_intents SET status = 'expired'
|
|
1976
2005
|
WHERE workspace_id = ? AND status = 'active' AND expires_at <= ?`,
|
|
1977
2006
|
parameters: [input.workspaceId, now]
|
|
1978
2007
|
},
|
|
1979
2008
|
{
|
|
1980
|
-
|
|
2009
|
+
// Keep the quota decision in the write statement: D1's async
|
|
2010
|
+
// preflight reads cannot serialize concurrent reservations.
|
|
2011
|
+
sql: `WITH pending AS (${PENDING_UPLOAD_RESERVATIONS_SQL}), live AS (
|
|
2012
|
+
SELECT lower(CASE WHEN instr(trim(id), ':') > 0
|
|
2013
|
+
THEN substr(trim(id), instr(trim(id), ':') + 1)
|
|
2014
|
+
ELSE trim(id) END) AS hash,
|
|
2015
|
+
COALESCE(json_extract(data_json, '$.size_bytes'),
|
|
2016
|
+
json_extract(data_json, '$.sizeBytes')) AS size_bytes
|
|
2017
|
+
FROM s_file_meta WHERE workspace_id = ? AND deleted = 0
|
|
2018
|
+
), quota AS (
|
|
2019
|
+
SELECT
|
|
2020
|
+
(SELECT COALESCE(SUM(size_bytes), 0) FROM (
|
|
2021
|
+
SELECT MAX(size_bytes) AS size_bytes FROM live GROUP BY hash
|
|
2022
|
+
)) AS used_bytes,
|
|
2023
|
+
(SELECT COALESCE(SUM(reserved_bytes), 0) FROM pending) AS pending_bytes,
|
|
2024
|
+
CASE WHEN EXISTS (SELECT 1 FROM live WHERE hash = ?) THEN 0
|
|
2025
|
+
ELSE MAX(0, ? - (SELECT COALESCE(MAX(reserved_bytes), 0)
|
|
2026
|
+
FROM pending WHERE hash = ?)) END AS added_bytes
|
|
2027
|
+
) INSERT INTO upload_intents (
|
|
1981
2028
|
id, workspace_id, hash, mime_type, size_bytes, reserved_bytes,
|
|
1982
2029
|
expires_at, status, created_at
|
|
1983
|
-
)
|
|
2030
|
+
) SELECT ?, ?, ?, ?, ?, ?, ?, 'active', ? FROM quota
|
|
2031
|
+
WHERE (? IS NULL OR used_bytes + pending_bytes + added_bytes <= ?)
|
|
2032
|
+
AND NOT EXISTS (SELECT 1 FROM live WHERE size_bytes IS NULL
|
|
2033
|
+
OR typeof(size_bytes) NOT IN ('integer', 'real')
|
|
2034
|
+
OR size_bytes < 0 OR size_bytes > 9007199254740991
|
|
2035
|
+
OR size_bytes != CAST(size_bytes AS INTEGER))`,
|
|
1984
2036
|
parameters: [
|
|
2037
|
+
input.workspaceId,
|
|
2038
|
+
now,
|
|
2039
|
+
input.workspaceId,
|
|
2040
|
+
hash,
|
|
2041
|
+
input.sizeBytes,
|
|
2042
|
+
hash,
|
|
1985
2043
|
input.intentId,
|
|
1986
2044
|
input.workspaceId,
|
|
1987
2045
|
hash,
|
|
1988
2046
|
input.mimeType,
|
|
1989
2047
|
input.sizeBytes,
|
|
1990
|
-
|
|
2048
|
+
input.sizeBytes,
|
|
1991
2049
|
input.expiresAt,
|
|
1992
|
-
now
|
|
2050
|
+
now,
|
|
2051
|
+
input.workspaceQuotaBytes ?? null,
|
|
2052
|
+
input.workspaceQuotaBytes ?? null
|
|
1993
2053
|
]
|
|
1994
2054
|
}
|
|
1995
2055
|
]);
|
|
2056
|
+
if (results[1]?.meta?.changes !== 1) {
|
|
2057
|
+
throw createError({ statusCode: 413, statusMessage: "Workspace storage quota exceeded" });
|
|
2058
|
+
}
|
|
1996
2059
|
}
|
|
1997
2060
|
async snapshotInD1(workspaceId, input, pageSize, snapshotUserId) {
|
|
1998
2061
|
const now = nowEpoch();
|
|
@@ -53,6 +53,7 @@ class SqliteWebhookStore {
|
|
|
53
53
|
this.db = db;
|
|
54
54
|
this.initialize();
|
|
55
55
|
}
|
|
56
|
+
registrationLimit = "atomic-v1";
|
|
56
57
|
initialize() {
|
|
57
58
|
if (getSqliteDriver() !== "turso") {
|
|
58
59
|
this.db.pragma?.("journal_mode = WAL");
|
|
@@ -126,7 +127,7 @@ class SqliteWebhookStore {
|
|
|
126
127
|
WHERE typeof(json_each.value) = 'text'
|
|
127
128
|
`);
|
|
128
129
|
}
|
|
129
|
-
async createWebhook(webhook) {
|
|
130
|
+
async createWebhook(webhook, registrationLimit) {
|
|
130
131
|
const now = Date.now();
|
|
131
132
|
const row = {
|
|
132
133
|
...webhook,
|
|
@@ -136,6 +137,11 @@ class SqliteWebhookStore {
|
|
|
136
137
|
updated_at: now
|
|
137
138
|
};
|
|
138
139
|
const create = this.db.transaction(() => {
|
|
140
|
+
if (registrationLimit !== void 0) {
|
|
141
|
+
if (!Number.isSafeInteger(registrationLimit) || registrationLimit < 1) throw new Error("Invalid webhook registration limit");
|
|
142
|
+
const count = this.db.prepare(webhook.scope === "admin" ? "SELECT COUNT(*) AS count FROM webhook_registrations WHERE scope = 'admin'" : "SELECT COUNT(*) AS count FROM webhook_registrations WHERE scope = 'user' AND user_id = ? AND workspace_id = ?").get(...webhook.scope === "admin" ? [] : [webhook.user_id, webhook.workspace_id]);
|
|
143
|
+
if (count.count >= registrationLimit) throw Object.assign(new Error("Webhook limit exceeded"), { code: "WEBHOOK_LIMIT_EXCEEDED" });
|
|
144
|
+
}
|
|
139
145
|
this.db.prepare(
|
|
140
146
|
`
|
|
141
147
|
INSERT INTO webhook_registrations (
|
|
@@ -168,7 +174,7 @@ class SqliteWebhookStore {
|
|
|
168
174
|
insertCustomHook.run(row.id, hookName);
|
|
169
175
|
}
|
|
170
176
|
});
|
|
171
|
-
create();
|
|
177
|
+
create.immediate();
|
|
172
178
|
return row;
|
|
173
179
|
}
|
|
174
180
|
async updateWebhook(webhookId, patch) {
|
|
@@ -496,8 +502,9 @@ class LazySqliteWebhookStore {
|
|
|
496
502
|
constructor(store) {
|
|
497
503
|
this.store = store;
|
|
498
504
|
}
|
|
499
|
-
|
|
500
|
-
|
|
505
|
+
registrationLimit = "atomic-v1";
|
|
506
|
+
createWebhook(webhook, registrationLimit) {
|
|
507
|
+
return this.store.then((store) => store.createWebhook(webhook, registrationLimit));
|
|
501
508
|
}
|
|
502
509
|
updateWebhook(webhookId, patch) {
|
|
503
510
|
return this.store.then((store) => store.updateWebhook(webhookId, patch));
|