or3-provider-sqlite 0.0.17 → 0.0.19

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 CHANGED
@@ -11,6 +11,36 @@ 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 unexpired pending authorizations by hash and
23
+ reserves atomically on native SQLite and D1. Migration 026 backfills retained
24
+ hashes from metadata (including Trash) and consumed receipts into an indexed
25
+ usage total. Trash, logical deletion and receipt expiry do not release retained
26
+ charges; a restore of the same hash does not double-charge. A larger upload
27
+ reserves the difference above the retained size, even when historical metadata
28
+ understated it. This provider
29
+ advertises `atomicUploadQuota: 'retained-v1'`, allowing the host to omit its full
30
+ catalog preflight. Physical filesystem/S3 GC remains disabled, so retained
31
+ charges intentionally remain conservative. Configure
32
+ `OR3_STORAGE_WORKSPACE_QUOTA_BYTES`; its host default remains unlimited.
33
+
34
+ `watchVersion` shares one indexed workspace version-counter read every two
35
+ seconds per workspace per process across notification listeners. The host can
36
+ wake its ordinary sync pull immediately when the counter changes and use a
37
+ one-minute safety pull while connected. Last-listener teardown stops the timer;
38
+ unsupported notification routes retain normal gateway polling.
39
+
40
+ ## Atomic webhook registration quotas
41
+
42
+ 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.
43
+
14
44
  ## Install
15
45
 
16
46
  ```bash
@@ -208,6 +238,11 @@ model execution there; ordinary sync and other D1 features are unchanged.
208
238
 
209
239
  ## Backup
210
240
 
241
+ Workspace archives use `backupSnapshot` to include retained Trash file metadata
242
+ and originals. Normal sync snapshots continue to emit tombstones. Archive pages
243
+ share a frozen SQLite/D1 transaction snapshot and reject tokens from another
244
+ snapshot mode. Backup reads do not remove originals or unfinished uploads.
245
+
211
246
  For local-file and Bun runtimes, everything lives in a single SQLite file:
212
247
 
213
248
  ```bash
@@ -244,9 +279,17 @@ mismatched source rather than falling back to fixtures. See the
244
279
  ### Known differences vs Convex
245
280
 
246
281
  - Single-process SQLite vs distributed Convex backend
247
- - No real-time subscriptions (gateway polling only)
282
+ - Gateway version notifications use a shared counter poll; no native reactive SQLite subscription
248
283
  - Migrations run on boot, or on the first Worker request for D1; schema changes require restart
249
284
 
285
+ ## Admin maintenance
286
+
287
+ **Operations → Maintenance** labels the history tools **Clear old sync history**
288
+ (`sync.gc-change-log`) and **Clear old deletion history** (`sync.gc-tombstones`).
289
+ Descriptions explain the retention period and active-device requirements without
290
+ internal terminology. They wrap fully on narrow screens. These tools preserve
291
+ current chats and files; they do not empty Trash or remove stored files.
292
+
250
293
  ## Troubleshooting
251
294
 
252
295
  - **`OR3_SQLITE_DB_PATH is required in non-test environments`** — set a file
@@ -291,7 +334,13 @@ The canonical-history qualification lane defaults to a sibling `../or3-chat` che
291
334
 
292
335
  ## Workspace Files and Trash admission
293
336
 
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; 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.
337
+ 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.
338
+
339
+ 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.
340
+
341
+ Current hosts refuse server tools and workflows when the reader cannot return
342
+ resolved canonical ownership. Older providers require an upgrade even for chats
343
+ with no explicit project pointer, because legacy folder membership may own them.
295
344
 
296
345
  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
346
 
@@ -314,3 +363,19 @@ the supported profile is qualified.
314
363
  The updated host distinguishes signup invites from existing team invites. Signup invites create a private workspace with only the recipient as owner; team invites retain their selected workspace and role. This requires the updated host and rebuilt provider artifacts, rather than the existing published release alone.
315
364
 
316
365
  Native SQLite implements five optional AuthWorkspaceStore methods with one additive signup_invites migration and one immediate acceptance transaction. User, identity mapping, recipient-only workspace membership, active pointer, and acceptance receipt commit together. Replay performs no provisioning writes. D1 deliberately does not advertise these methods. Dates are milliseconds; history pages contain at most 100 rows without hashes, with 90-day terminal retention and cleanup capped at 100 records per create/list call.
366
+
367
+ ### Short signup codes
368
+
369
+ New signup invitations use eight random characters (shown as `K7MP-4X9Q`) and retain clickable invite links. Lowercase, spaces, and an optional dash are accepted. The host hashes codes with HMAC using `OR3_AUTH_INVITE_TOKEN_SECRET`, shares a 20/minute/IP lookup limit across invitation entry points, and preserves email binding, expiry, revocation, and atomic single use. Previously issued signed links remain supported. Codes and hashes are omitted from invitation history.
370
+
371
+ `findSignupInviteByTokenHash` resolves pending proofs through the existing unique `token_hash` index and returns only ID, email, and expiry to the host. No new migration is required. D1 continues to omit signup invitation capabilities.
372
+
373
+ ## Dashboard restart drain accounting
374
+
375
+ The background provider implements `getShutdownBlockerCount`: streaming jobs
376
+ (including browser-tool handoffs and workflows), pending admission and terminal
377
+ history delivery prevent replacement. Database failures propagate so the host
378
+ cancels preparation and restores admission rather than treating failure as idle.
379
+ An additive covering index migration keeps counts off stored response bodies.
380
+
381
+ Admin workspace summaries, workspace details, and deployment-admin lists expose `createdAt` in Unix milliseconds for the host UI. SQLite continues to store the underlying creation timestamps in Unix seconds; no data migration is needed.
package/dist/module.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "or3-provider-sqlite",
3
3
  "configKey": "or3-provider-sqlite",
4
- "version": "0.0.17",
4
+ "version": "0.0.19",
5
5
  "builder": {
6
6
  "@nuxt/module-builder": "1.0.2",
7
7
  "unbuild": "3.6.1"
@@ -66,14 +66,14 @@ export const sqliteSyncAdminAdapter = {
66
66
  actions: [
67
67
  {
68
68
  id: "sync.gc-change-log",
69
- label: "GC change log",
70
- description: `Prune change-log entries older than ${SYNC_MAINTENANCE_RETENTION_SECONDS / 86400} days and behind every device cursor.`,
69
+ label: "Clear old sync history",
70
+ description: `Remove update history older than ${SYNC_MAINTENANCE_RETENTION_SECONDS / 86400} days after all active devices are up to date. Current chats and files are kept.`,
71
71
  danger: true
72
72
  },
73
73
  {
74
74
  id: "sync.gc-tombstones",
75
- label: "GC tombstones",
76
- description: `Prune tombstones older than ${SYNC_MAINTENANCE_RETENTION_SECONDS / 86400} days and behind every device cursor.`,
75
+ label: "Clear old deletion history",
76
+ description: `Remove records of items deleted more than ${SYNC_MAINTENANCE_RETENTION_SECONDS / 86400} days ago, after all active devices are up to date. This does not empty Trash or remove stored files.`,
77
77
  danger: true
78
78
  }
79
79
  ]
@@ -209,7 +209,7 @@ class SqliteWorkspaceAccessStore {
209
209
  id: row.id,
210
210
  name: row.name,
211
211
  description: row.description ?? void 0,
212
- createdAt: row.created_at,
212
+ createdAt: row.created_at * 1e3,
213
213
  deleted: row.deleted === 1,
214
214
  deletedAt: row.deleted_at ?? void 0,
215
215
  ownerUserId: row.owner_user_id ?? void 0,
@@ -235,7 +235,7 @@ class SqliteWorkspaceAccessStore {
235
235
  id: row.id,
236
236
  name: row.name,
237
237
  description: row.description ?? void 0,
238
- createdAt: row.created_at,
238
+ createdAt: row.created_at * 1e3,
239
239
  deleted: row.deleted === 1,
240
240
  deletedAt: row.deleted_at ?? void 0,
241
241
  ownerUserId: row.owner_user_id ?? void 0,
@@ -355,7 +355,7 @@ class SqliteAdminUserStore {
355
355
  userId: row.user_id,
356
356
  email: row.email ?? void 0,
357
357
  displayName: row.display_name ?? void 0,
358
- createdAt: row.created_at
358
+ createdAt: row.created_at * 1e3
359
359
  }));
360
360
  }
361
361
  async grantAdmin(input) {
@@ -18,6 +18,9 @@ export declare class SqliteAuthWorkspaceStore implements AuthWorkspaceStore {
18
18
  }): Promise<{
19
19
  id: string;
20
20
  }>;
21
+ findSignupInviteByTokenHash(input: {
22
+ token_hash: string;
23
+ }): Promise<Pick<SignupInviteSummary, 'id' | 'email' | 'expires_at'> | null>;
21
24
  listSignupInvites(input: {
22
25
  limit: number;
23
26
  cursor?: string;
@@ -17,6 +17,7 @@ export class SqliteAuthWorkspaceStore {
17
17
  listSignupInvites: void 0,
18
18
  revokeSignupInvite: void 0,
19
19
  validateSignupInvite: void 0,
20
+ findSignupInviteByTokenHash: void 0,
20
21
  acceptSignupInviteAndProvisionUser: void 0
21
22
  });
22
23
  }
@@ -30,6 +31,10 @@ export class SqliteAuthWorkspaceStore {
30
31
  getRawDb().prepare("INSERT INTO signup_invites (id, email, token_hash, expires_at, created_at, created_by_admin, retain_until) VALUES (?, ?, ?, ?, ?, ?, ?)").run(input.id, normalizeEmail(input.email), input.token_hash, input.expires_at, Date.now(), input.created_by_admin, input.expires_at + 90 * 864e5);
31
32
  return { id: input.id };
32
33
  }
34
+ async findSignupInviteByTokenHash(input) {
35
+ this.db;
36
+ return getRawDb().prepare("SELECT id, email, expires_at FROM signup_invites WHERE token_hash = ? AND status = 'pending'").get(input.token_hash) ?? null;
37
+ }
33
38
  async listSignupInvites(input) {
34
39
  this.db;
35
40
  this.cleanupSignupInvites();
@@ -25,5 +25,6 @@ export declare class SqliteBackgroundJobProvider implements BackgroundJobProvide
25
25
  getPendingHistoryJobs(limit: number): Promise<BackgroundJob[]>;
26
26
  cleanupExpired(): Promise<number>;
27
27
  getActiveJobCount(): Promise<number>;
28
+ getShutdownBlockerCount(): Promise<number>;
28
29
  }
29
30
  export declare const sqliteBackgroundJobProvider: SqliteBackgroundJobProvider;
@@ -626,5 +626,16 @@ export class SqliteBackgroundJobProvider {
626
626
  );
627
627
  return row?.total ?? 0;
628
628
  }
629
+ async getShutdownBlockerCount() {
630
+ const row = await one(
631
+ `SELECT
632
+ (SELECT COUNT(*) FROM background_jobs WHERE status = 'streaming') +
633
+ (SELECT COUNT(*) FROM background_jobs
634
+ WHERE history_phase IN ('admission_pending', 'finalization_pending')
635
+ AND status != 'streaming') AS total`
636
+ );
637
+ if (!row) throw new Error("SQLite shutdown accounting unavailable");
638
+ return row.total;
639
+ }
629
640
  }
630
641
  export const sqliteBackgroundJobProvider = new SqliteBackgroundJobProvider();
@@ -45,6 +45,8 @@ const REQUIRED_SCHEMA_TABLES = [
45
45
  "sync_snapshots",
46
46
  "sync_snapshot_items",
47
47
  "upload_intents",
48
+ "retained_storage",
49
+ "storage_usage",
48
50
  "connect_device_authorizations",
49
51
  "connect_environments",
50
52
  "rate_limits",
@@ -53,6 +55,8 @@ const REQUIRED_SCHEMA_TABLES = [
53
55
  "background_generation_receipts"
54
56
  ];
55
57
  import * as m024 from "./migrations/024_signup_invites.js";
58
+ import * as m025 from "./migrations/025_background_shutdown_accounting.js";
59
+ import * as m026 from "./migrations/026_retained_storage_usage.js";
56
60
  const migrations = {
57
61
  "001_init": m001,
58
62
  "002_sync_tables": m002,
@@ -77,7 +81,9 @@ const migrations = {
77
81
  "021_background_request_usage": m021,
78
82
  "022_canonical_chat_reader": m022,
79
83
  "023_legacy_chat_seek_index": m023,
80
- "024_signup_invites": m024
84
+ "024_signup_invites": m024,
85
+ "025_background_shutdown_accounting": m025,
86
+ "026_retained_storage_usage": m026
81
87
  };
82
88
  class StaticMigrationProvider {
83
89
  async getMigrations() {
@@ -0,0 +1,4 @@
1
+ import { type Kysely } from 'kysely';
2
+ /** Cover pending-history shutdown counts without reading stored response blobs. */
3
+ export declare function up(db: Kysely<unknown>): Promise<void>;
4
+ export declare function down(db: Kysely<unknown>): Promise<void>;
@@ -0,0 +1,8 @@
1
+ import { sql } from "kysely";
2
+ export async function up(db) {
3
+ await sql`CREATE INDEX background_jobs_history_status
4
+ ON background_jobs(history_phase, status)`.execute(db);
5
+ }
6
+ export async function down(db) {
7
+ await sql`DROP INDEX IF EXISTS background_jobs_history_status`.execute(db);
8
+ }
@@ -0,0 +1,7 @@
1
+ import { type Kysely } from 'kysely';
2
+ /** Keep quota proportional to retained immutable content, not visible metadata.
3
+ * Logical deletes/receipt expiry cannot release physical storage charges. External
4
+ * storage deletion remains fail-closed; this ledger deliberately never decrements.
5
+ */
6
+ export declare function up(db: Kysely<unknown>): Promise<void>;
7
+ export declare function down(db: Kysely<unknown>): Promise<void>;
@@ -0,0 +1,61 @@
1
+ import { sql } from "kysely";
2
+ export async function up(db) {
3
+ await sql`CREATE TABLE retained_storage (
4
+ workspace_id TEXT NOT NULL, hash TEXT NOT NULL,
5
+ size_bytes INTEGER NOT NULL CHECK(size_bytes >= 0),
6
+ PRIMARY KEY(workspace_id, hash)
7
+ )`.execute(db);
8
+ await sql`CREATE TABLE storage_usage (
9
+ workspace_id TEXT PRIMARY KEY, used_bytes INTEGER NOT NULL
10
+ )`.execute(db);
11
+ await sql`CREATE TRIGGER retained_storage_insert AFTER INSERT ON retained_storage BEGIN
12
+ INSERT INTO storage_usage(workspace_id, used_bytes) VALUES(NEW.workspace_id, NEW.size_bytes)
13
+ ON CONFLICT(workspace_id) DO UPDATE SET used_bytes = used_bytes + NEW.size_bytes;
14
+ END`.execute(db);
15
+ await sql`CREATE TRIGGER retained_storage_update AFTER UPDATE OF size_bytes ON retained_storage BEGIN
16
+ UPDATE storage_usage SET used_bytes = used_bytes + NEW.size_bytes - OLD.size_bytes
17
+ WHERE workspace_id = NEW.workspace_id;
18
+ END`.execute(db);
19
+ const hash = (id) => `lower(CASE WHEN instr(trim(${id}), ':') > 0
20
+ THEN substr(trim(${id}), instr(trim(${id}), ':') + 1) ELSE trim(${id}) END)`;
21
+ const size = (data) => `CASE WHEN typeof(COALESCE(json_extract(${data}, '$.size_bytes'), json_extract(${data}, '$.sizeBytes'))) IN ('integer','real')
22
+ AND COALESCE(json_extract(${data}, '$.size_bytes'), json_extract(${data}, '$.sizeBytes')) BETWEEN 0 AND 9007199254740991
23
+ AND COALESCE(json_extract(${data}, '$.size_bytes'), json_extract(${data}, '$.sizeBytes')) = CAST(COALESCE(json_extract(${data}, '$.size_bytes'), json_extract(${data}, '$.sizeBytes')) AS INTEGER)
24
+ THEN CAST(COALESCE(json_extract(${data}, '$.size_bytes'), json_extract(${data}, '$.sizeBytes')) AS INTEGER)
25
+ ELSE 9007199254740991 END`;
26
+ const known = (data) => `(json_type(${data}, '$.size_bytes') IS NOT NULL OR json_type(${data}, '$.sizeBytes') IS NOT NULL)`;
27
+ for (const operation of ["INSERT", "UPDATE"]) {
28
+ await sql.raw(`CREATE TRIGGER file_meta_retained_${operation.toLowerCase()} AFTER ${operation} ON s_file_meta
29
+ WHEN ${known("NEW.data_json")} BEGIN
30
+ INSERT INTO retained_storage(workspace_id, hash, size_bytes)
31
+ VALUES(NEW.workspace_id, ${hash("NEW.id")}, ${size("NEW.data_json")})
32
+ ON CONFLICT(workspace_id, hash) DO UPDATE SET size_bytes = MAX(size_bytes, excluded.size_bytes);
33
+ END`).execute(db);
34
+ await sql.raw(`CREATE TRIGGER upload_retained_${operation.toLowerCase()} AFTER ${operation} ON upload_intents
35
+ WHEN NEW.status = 'consumed' BEGIN
36
+ INSERT INTO retained_storage(workspace_id, hash, size_bytes)
37
+ VALUES(NEW.workspace_id, NEW.hash, NEW.size_bytes)
38
+ ON CONFLICT(workspace_id, hash) DO UPDATE SET size_bytes = MAX(size_bytes, excluded.size_bytes);
39
+ END`).execute(db);
40
+ }
41
+ await sql.raw(`INSERT INTO retained_storage(workspace_id, hash, size_bytes)
42
+ SELECT workspace_id, ${hash("id")}, ${size("data_json")} FROM s_file_meta WHERE ${known("data_json")}
43
+ ON CONFLICT(workspace_id, hash) DO UPDATE SET size_bytes = MAX(size_bytes, excluded.size_bytes)`).execute(db);
44
+ await sql`INSERT INTO retained_storage(workspace_id, hash, size_bytes)
45
+ SELECT workspace_id, hash, size_bytes FROM upload_intents WHERE status = 'consumed'
46
+ ON CONFLICT(workspace_id, hash) DO UPDATE SET size_bytes = MAX(size_bytes, excluded.size_bytes)`.execute(db);
47
+ }
48
+ export async function down(db) {
49
+ for (const name of [
50
+ "file_meta_retained_insert",
51
+ "file_meta_retained_update",
52
+ "upload_retained_insert",
53
+ "upload_retained_update",
54
+ "retained_storage_insert",
55
+ "retained_storage_update"
56
+ ]) {
57
+ await sql.raw(`DROP TRIGGER IF EXISTS ${name}`).execute(db);
58
+ }
59
+ await sql`DROP TABLE IF EXISTS retained_storage`.execute(db);
60
+ await sql`DROP TABLE IF EXISTS storage_usage`.execute(db);
61
+ }
@@ -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
- if (!workspaceSelected && !connectSelected && !backgroundJobsSelected)
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) {
@@ -12,9 +12,15 @@ import type { PullRequest, PullResponse, PushBatch, PushResult, SnapshotRequest,
12
12
  import { type CanonicalChatQuery, type CanonicalChatReadResult } from '~~/shared/chat/history-reader';
13
13
  export declare class SqliteSyncGatewayAdapter implements SyncGatewayAdapter {
14
14
  id: string;
15
+ private versionWatchers;
16
+ watchVersion(event: H3Event, scope: {
17
+ workspaceId: string;
18
+ }, onVersion: (version: number) => void, onError: (error: unknown) => void): Promise<() => void>;
15
19
  get capabilities(): {
16
20
  readonly snapshotBootstrap: "snapshot-v1";
17
21
  readonly historyRetention: "snapshot-v1";
22
+ readonly retainedStorageMetadata: "v1";
23
+ readonly atomicUploadQuota: "retained-v1";
18
24
  readonly backgroundGenerationHistory?: undefined;
19
25
  readonly canonicalChatHistory?: undefined;
20
26
  readonly projectOwnership?: undefined;
@@ -26,6 +32,8 @@ export declare class SqliteSyncGatewayAdapter implements SyncGatewayAdapter {
26
32
  readonly canonicalChatHistory: "v1";
27
33
  readonly projectOwnership: "v1";
28
34
  readonly workspaceItems: "v1";
35
+ readonly retainedStorageMetadata: "v1";
36
+ readonly atomicUploadQuota: "retained-v1";
29
37
  };
30
38
  private get db();
31
39
  readChatHistory(actor: CanonicalHistoryActor, query: CanonicalChatQuery, signal?: AbortSignal): Promise<CanonicalChatReadResult>;
@@ -45,6 +53,9 @@ export declare class SqliteSyncGatewayAdapter implements SyncGatewayAdapter {
45
53
  push(event: H3Event, input: PushBatch): Promise<PushResult>;
46
54
  pull(event: H3Event, input: PullRequest): Promise<PullResponse>;
47
55
  snapshot(event: H3Event, input: SnapshotRequest): Promise<SnapshotResponse>;
56
+ /** Archives retain full Trash metadata; normal sync still emits tombstones. */
57
+ backupSnapshot(event: H3Event, input: SnapshotRequest): Promise<SnapshotResponse>;
58
+ private captureSnapshot;
48
59
  updateCursor(event: H3Event, input: {
49
60
  scope: {
50
61
  workspaceId: string;
@@ -33,6 +33,27 @@ 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
+ `;
51
+ const QUOTA_RESERVATIONS_SQL = `SELECT intent.hash, MAX(intent.size_bytes) AS reserved_bytes,
52
+ MAX(0, MAX(intent.size_bytes) - COALESCE(retained.size_bytes, 0)) AS held_bytes
53
+ FROM upload_intents AS intent LEFT JOIN retained_storage AS retained
54
+ ON retained.workspace_id = intent.workspace_id AND retained.hash = intent.hash
55
+ WHERE intent.workspace_id = ? AND intent.status = 'active' AND intent.expires_at > ?
56
+ GROUP BY intent.hash`;
36
57
  function uid() {
37
58
  return globalThis.crypto.randomUUID();
38
59
  }
@@ -424,17 +445,62 @@ async function currentWinnerD1(workspaceId, tableName, pk) {
424
445
  }
425
446
  export class SqliteSyncGatewayAdapter {
426
447
  id = "sqlite";
448
+ versionWatchers = /* @__PURE__ */ new Map();
449
+ async watchVersion(event, scope, onVersion, onError) {
450
+ await assertWorkspaceScopeAuthorized(event, scope.workspaceId);
451
+ let watcher = this.versionWatchers.get(scope.workspaceId);
452
+ if (!watcher) {
453
+ watcher = { listeners: /* @__PURE__ */ new Map(), running: false };
454
+ this.versionWatchers.set(scope.workspaceId, watcher);
455
+ }
456
+ const current = watcher;
457
+ current.listeners.set(onVersion, onError);
458
+ if (current.version !== void 0) onVersion(current.version);
459
+ const poll = async () => {
460
+ if (current.running || this.versionWatchers.get(scope.workspaceId) !== current) return;
461
+ current.running = true;
462
+ try {
463
+ const row = await getSqliteDb().selectFrom("server_version_counter").select("value").where("workspace_id", "=", scope.workspaceId).executeTakeFirst();
464
+ const version = row?.value ?? 0;
465
+ if (current.version !== version) {
466
+ current.version = version;
467
+ for (const notify of [...current.listeners.keys()]) notify(version);
468
+ }
469
+ } catch (error) {
470
+ for (const fail of [...current.listeners.values()]) fail(error);
471
+ } finally {
472
+ current.running = false;
473
+ }
474
+ if (this.versionWatchers.get(scope.workspaceId) === current && current.listeners.size) {
475
+ current.timer = setTimeout(() => {
476
+ void poll();
477
+ }, 2e3);
478
+ current.timer.unref?.();
479
+ }
480
+ };
481
+ if (!current.running && !current.timer) void poll();
482
+ return () => {
483
+ current.listeners.delete(onVersion);
484
+ if (current.listeners.size) return;
485
+ if (current.timer) clearTimeout(current.timer);
486
+ if (this.versionWatchers.get(scope.workspaceId) === current) this.versionWatchers.delete(scope.workspaceId);
487
+ };
488
+ }
427
489
  get capabilities() {
428
490
  return isD1Driver() ? {
429
491
  snapshotBootstrap: "snapshot-v1",
430
- historyRetention: "snapshot-v1"
492
+ historyRetention: "snapshot-v1",
493
+ retainedStorageMetadata: "v1",
494
+ atomicUploadQuota: "retained-v1"
431
495
  } : {
432
496
  snapshotBootstrap: "snapshot-v1",
433
497
  historyRetention: "snapshot-v1",
434
498
  backgroundGenerationHistory: "v1",
435
499
  canonicalChatHistory: "v1",
436
500
  projectOwnership: "v1",
437
- workspaceItems: "v1"
501
+ workspaceItems: "v1",
502
+ retainedStorageMetadata: "v1",
503
+ atomicUploadQuota: "retained-v1"
438
504
  };
439
505
  }
440
506
  get db() {
@@ -460,18 +526,32 @@ export class SqliteSyncGatewayAdapter {
460
526
  const threadRevision = raw.prepare("SELECT value FROM chat_history_revisions WHERE workspace_id = ? AND thread_id = ?").get(actor.workspaceId, query.thread_id);
461
527
  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
528
  const thread = row ? parse(row) : void 0;
463
- if (!thread || thread.project_id) return {
529
+ if (!thread) return {
464
530
  status: "ok",
465
531
  project_ownership: "resolved",
466
532
  revision: String(threadRevision?.value ?? 0),
467
533
  thread
468
534
  };
535
+ if (thread.project_id) {
536
+ 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);
537
+ return {
538
+ status: "ok",
539
+ project_ownership: "resolved",
540
+ revision: String(threadRevision?.value ?? 0),
541
+ thread: { ...thread, project_id: owner ? thread.project_id : null }
542
+ };
543
+ }
469
544
  const projects = raw.prepare("SELECT id, data_json FROM s_projects WHERE workspace_id = ? AND COALESCE(deleted, 0) = 0").all(actor.workspaceId);
470
545
  const owners = projects.filter((project) => {
471
546
  const payload = JSON.parse(project.data_json);
472
547
  const entries = typeof payload.data === "string" ? JSON.parse(payload.data) : payload.data ?? [];
473
548
  if (!Array.isArray(entries)) throw new Error("Canonical project membership is unresolved.");
474
- return entries.some((entry) => typeof entry === "string" ? entry === query.thread_id : entry && typeof entry === "object" && !Array.isArray(entry) && (entry.kind === void 0 || entry.kind === "chat") && entry.id === query.thread_id);
549
+ return entries.some((entry) => {
550
+ if (typeof entry === "string") return entry.trim() === query.thread_id;
551
+ if (!entry || typeof entry !== "object" || Array.isArray(entry) || typeof entry.id !== "string") return false;
552
+ const kind = typeof entry.kind === "string" ? entry.kind.trim().toLowerCase() : entry.kind;
553
+ return (kind === void 0 || kind === "chat") && entry.id.trim() === query.thread_id;
554
+ });
475
555
  });
476
556
  return {
477
557
  status: "ok",
@@ -797,25 +877,14 @@ export class SqliteSyncGatewayAdapter {
797
877
  const now = nowEpoch();
798
878
  raw.prepare(`UPDATE upload_intents SET status = 'expired'
799
879
  WHERE workspace_id = ? AND status = 'active' AND expires_at <= ?`).run(input.workspaceId, now);
800
- const liveRows = raw.prepare(`SELECT id, data_json FROM s_file_meta
801
- WHERE workspace_id = ? AND deleted = 0`).all(input.workspaceId);
802
- let usedBytes = 0;
803
- let alreadyStored = false;
804
- for (const row of liveRows) {
805
- const payload = JSON.parse(row.data_json);
806
- const size = payload.size_bytes ?? payload.sizeBytes;
807
- if (typeof size !== "number" || !Number.isSafeInteger(size) || size < 0) {
808
- throw createError({ statusCode: 500, statusMessage: "Invalid canonical file size" });
809
- }
810
- usedBytes += size;
811
- if (normalizeStorageHash(row.id) === hash) alreadyStored = true;
812
- }
813
- const totals = raw.prepare(`SELECT
814
- COALESCE(SUM(reserved_bytes), 0) AS reserved_bytes,
815
- MAX(CASE WHEN hash = ? AND reserved_bytes > 0 THEN 1 ELSE 0 END) AS same_hash
816
- FROM upload_intents WHERE workspace_id = ? AND status = 'active' AND expires_at > ?`).get(hash, input.workspaceId, now);
817
- const reservedBytes = alreadyStored || totals.same_hash === 1 ? 0 : input.sizeBytes;
818
- if (input.workspaceQuotaBytes !== void 0 && usedBytes + totals.reserved_bytes + reservedBytes > input.workspaceQuotaBytes) {
880
+ const usedBytes = raw.prepare("SELECT used_bytes FROM storage_usage WHERE workspace_id = ?").get(input.workspaceId)?.used_bytes ?? 0;
881
+ const retainedBytes = raw.prepare("SELECT size_bytes FROM retained_storage WHERE workspace_id = ? AND hash = ?").get(input.workspaceId, hash)?.size_bytes ?? 0;
882
+ const totals = raw.prepare(`WITH pending AS (${QUOTA_RESERVATIONS_SQL}) SELECT
883
+ COALESCE(SUM(held_bytes), 0) AS reserved_bytes,
884
+ COALESCE(MAX(CASE WHEN hash = ? THEN reserved_bytes END), 0) AS same_hash
885
+ FROM pending`).get(input.workspaceId, now, hash);
886
+ const addedBytes = Math.max(0, input.sizeBytes - Math.max(retainedBytes, totals.same_hash));
887
+ if (input.workspaceQuotaBytes !== void 0 && usedBytes + totals.reserved_bytes + addedBytes > input.workspaceQuotaBytes) {
819
888
  throw createError({ statusCode: 413, statusMessage: "Workspace storage quota exceeded" });
820
889
  }
821
890
  raw.prepare(`INSERT INTO upload_intents (
@@ -827,7 +896,7 @@ export class SqliteSyncGatewayAdapter {
827
896
  hash,
828
897
  input.mimeType,
829
898
  input.sizeBytes,
830
- reservedBytes,
899
+ input.sizeBytes,
831
900
  input.expiresAt,
832
901
  now
833
902
  );
@@ -835,42 +904,39 @@ export class SqliteSyncGatewayAdapter {
835
904
  }
836
905
  async consumeUploadIntent(event, input) {
837
906
  await assertWorkspaceScopeAuthorized(event, input.workspaceId);
838
- if (isD1Driver()) {
839
- const now = nowEpoch();
840
- const result2 = await d1Run(
841
- `UPDATE upload_intents
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
907
+ const now = nowEpoch();
908
+ const hash = normalizeStorageHash(input.hash);
909
+ const raw = isD1Driver() ? null : getRawDb();
910
+ const sql = `UPDATE upload_intents
861
911
  SET status = 'consumed', storage_id = ?, consumed_at = ?
862
912
  WHERE id = ? AND workspace_id = ? AND status = 'active' AND expires_at > ?
863
- AND hash = ? AND mime_type = ? AND size_bytes = ?`).run(
913
+ AND hash = ? AND mime_type = ? AND size_bytes = ?`;
914
+ const parameters = [
864
915
  input.storageId,
865
- nowEpoch(),
916
+ now,
866
917
  input.intentId,
867
918
  input.workspaceId,
868
- nowEpoch(),
869
- normalizeStorageHash(input.hash),
919
+ now,
920
+ hash,
870
921
  input.mimeType,
871
922
  input.sizeBytes
872
- );
873
- if (result.changes !== 1) {
923
+ ];
924
+ const changes = raw ? raw.prepare(sql).run(...parameters).changes : (await d1Run(sql, ...parameters)).meta?.changes;
925
+ if (changes === 1) return;
926
+ const receiptSql = `SELECT 1 FROM upload_intents
927
+ WHERE id = ? AND workspace_id = ? AND status = 'consumed' AND expires_at > ?
928
+ AND hash = ? AND mime_type = ? AND size_bytes = ? AND storage_id = ?`;
929
+ const receiptParameters = [
930
+ input.intentId,
931
+ input.workspaceId,
932
+ now,
933
+ hash,
934
+ input.mimeType,
935
+ input.sizeBytes,
936
+ input.storageId
937
+ ];
938
+ const receipt = raw ? raw.prepare(receiptSql).get(...receiptParameters) : (await d1All(receiptSql, ...receiptParameters))[0];
939
+ if (!receipt) {
874
940
  throw createError({ statusCode: 409, statusMessage: "Upload intent expired, mismatched, or already consumed" });
875
941
  }
876
942
  }
@@ -912,10 +978,9 @@ export class SqliteSyncGatewayAdapter {
912
978
  throw createError({ statusCode: 400, statusMessage: "Invalid canonical storage cursor" });
913
979
  }
914
980
  const now = input.now ?? nowEpoch();
915
- const rows2 = await all(`SELECT id, hash, reserved_bytes, expires_at
916
- FROM upload_intents
917
- WHERE workspace_id = ? AND status = 'active' AND expires_at > ?
918
- AND id > ? AND reserved_bytes > 0 AND (? IS NULL OR hash = ?)
981
+ const rows2 = await all(`WITH pending AS (${PENDING_UPLOAD_RESERVATIONS_SQL})
982
+ SELECT id, hash, reserved_bytes, expires_at FROM pending
983
+ WHERE id > ? AND (? IS NULL OR hash = ?)
919
984
  ORDER BY id ASC LIMIT ?`, workspaceId, now, after[0] ?? "", hash ?? null, hash ?? null, limit + 1);
920
985
  const hasMore2 = rows2.length > limit;
921
986
  const page2 = hasMore2 ? rows2.slice(0, limit) : rows2;
@@ -937,7 +1002,8 @@ export class SqliteSyncGatewayAdapter {
937
1002
  }) } : {}
938
1003
  };
939
1004
  }
940
- if (input.kind === "live_metadata") {
1005
+ if (input.kind === "live_metadata" || input.kind === "retained_metadata") {
1006
+ const retained = input.kind === "retained_metadata";
941
1007
  if (after.length > 1) {
942
1008
  throw createError({ statusCode: 400, statusMessage: "Invalid canonical storage cursor" });
943
1009
  }
@@ -945,7 +1011,7 @@ export class SqliteSyncGatewayAdapter {
945
1011
  SELECT id, data_json, updated_at
946
1012
  FROM s_file_meta
947
1013
  WHERE workspace_id = ?
948
- AND deleted = 0
1014
+ AND deleted = ?
949
1015
  AND id > ?
950
1016
  AND (? IS NULL OR lower(
951
1017
  CASE
@@ -956,7 +1022,7 @@ export class SqliteSyncGatewayAdapter {
956
1022
  ) = ?)
957
1023
  ORDER BY id ASC
958
1024
  LIMIT ?
959
- `, workspaceId, after[0] ?? "", hash ?? null, hash ?? null, limit + 1);
1025
+ `, workspaceId, retained ? 1 : 0, after[0] ?? "", hash ?? null, hash ?? null, limit + 1);
960
1026
  const hasMore2 = rows2.length > limit;
961
1027
  const page2 = hasMore2 ? rows2.slice(0, limit) : rows2;
962
1028
  const items = page2.map((row) => {
@@ -967,21 +1033,25 @@ export class SqliteSyncGatewayAdapter {
967
1033
  throw createError({ statusCode: 500, statusMessage: "Invalid canonical file metadata" });
968
1034
  }
969
1035
  const size = payload.size_bytes ?? payload.sizeBytes;
970
- if (typeof size !== "number" || !Number.isSafeInteger(size) || size < 0) {
1036
+ const missingSize = !("size_bytes" in payload) && !("sizeBytes" in payload);
1037
+ if (!(retained && missingSize) && (typeof size !== "number" || !Number.isSafeInteger(size) || size < 0)) {
971
1038
  throw createError({ statusCode: 500, statusMessage: "Invalid canonical file size" });
972
1039
  }
973
1040
  const storageId = payload.storage_id ?? payload.storageId;
974
1041
  const fileKind = payload.kind === "image" ? "image" : payload.kind === "pdf" ? "pdf" : payload.kind === "file" ? "file" : void 0;
975
- return {
976
- kind: "metadata",
1042
+ const metadata = {
977
1043
  hash: normalizeStorageHash(row.id),
978
- sizeBytes: size,
979
1044
  ...typeof storageId === "string" && storageId ? { storageId } : {},
980
1045
  ...typeof (payload.mime_type ?? payload.mimeType) === "string" ? { mimeType: String(payload.mime_type ?? payload.mimeType) } : {},
981
1046
  ...typeof payload.name === "string" ? { name: payload.name } : {},
982
1047
  ...fileKind ? { fileKind } : {},
983
1048
  updatedAt: row.updated_at
984
1049
  };
1050
+ return retained ? {
1051
+ ...metadata,
1052
+ kind: "retained_metadata",
1053
+ ...typeof size === "number" ? { sizeBytes: size } : {}
1054
+ } : { ...metadata, kind: "metadata", sizeBytes: size };
985
1055
  });
986
1056
  const last2 = page2[page2.length - 1];
987
1057
  return {
@@ -1523,12 +1593,19 @@ export class SqliteSyncGatewayAdapter {
1523
1593
  };
1524
1594
  }
1525
1595
  async snapshot(event, input) {
1596
+ return this.captureSnapshot(event, input, false);
1597
+ }
1598
+ /** Archives retain full Trash metadata; normal sync still emits tombstones. */
1599
+ async backupSnapshot(event, input) {
1600
+ return this.captureSnapshot(event, input, true);
1601
+ }
1602
+ async captureSnapshot(event, input, retainedFiles) {
1526
1603
  const workspaceId = input.scope.workspaceId;
1527
1604
  await assertWorkspaceScopeAuthorized(event, workspaceId);
1528
1605
  const pageSize = resolveSnapshotPageSize(input.pageSize);
1529
1606
  const snapshotUserId = resolveSessionUserId(event);
1530
1607
  if (isD1Driver()) {
1531
- return this.snapshotInD1(workspaceId, input, pageSize, snapshotUserId);
1608
+ return this.snapshotInD1(workspaceId, input, pageSize, snapshotUserId, retainedFiles);
1532
1609
  }
1533
1610
  const raw = getRawDb();
1534
1611
  const now = nowEpoch();
@@ -1568,11 +1645,14 @@ export class SqliteSyncGatewayAdapter {
1568
1645
  statusMessage: "Snapshot table filter cannot change between pages"
1569
1646
  });
1570
1647
  }
1648
+ if (existing.id.startsWith("backup:") !== retainedFiles) {
1649
+ throw createError({ statusCode: 400, statusMessage: "Snapshot mode cannot change between pages" });
1650
+ }
1571
1651
  header = existing;
1572
1652
  after = token.after;
1573
1653
  } else {
1574
1654
  const tables = normalizeSnapshotTables(input.tables);
1575
- const snapshotId = uid();
1655
+ const snapshotId = `${retainedFiles ? "backup:" : ""}${uid()}`;
1576
1656
  const expiresAt = now + SNAPSHOT_TTL_SECONDS;
1577
1657
  const capture = raw.transaction(() => {
1578
1658
  raw.prepare("DELETE FROM sync_snapshots WHERE expires_at <= ?").run(now);
@@ -1631,7 +1711,8 @@ export class SqliteSyncGatewayAdapter {
1631
1711
  clock, hlc, op_id, server_deleted_at
1632
1712
  )
1633
1713
  SELECT
1634
- ?, ?, materialized.id, 'tombstone', NULL,
1714
+ ?, ?, materialized.id, '${retainedFiles && tableName === "file_meta" ? "row" : "tombstone"}',
1715
+ ${retainedFiles && tableName === "file_meta" ? "json_set(materialized.data_json, '$.deleted', json('true'), '$.clock', materialized.clock, '$.hlc', materialized.hlc, '$.updated_at', materialized.updated_at)" : "NULL"},
1635
1716
  materialized.clock,
1636
1717
  CASE
1637
1718
  WHEN materialized.hlc <> '' THEN materialized.hlc
@@ -1941,60 +2022,52 @@ export class SqliteSyncGatewayAdapter {
1941
2022
  }
1942
2023
  async reserveUploadIntentInD1(input, hash) {
1943
2024
  const now = nowEpoch();
1944
- const liveRows = await d1All(
1945
- `SELECT id, data_json FROM s_file_meta
1946
- WHERE workspace_id = ? AND deleted = 0`,
1947
- input.workspaceId
1948
- );
1949
- let usedBytes = 0;
1950
- let alreadyStored = false;
1951
- for (const row of liveRows) {
1952
- const payload = JSON.parse(row.data_json);
1953
- const size = payload.size_bytes ?? payload.sizeBytes;
1954
- if (typeof size !== "number" || !Number.isSafeInteger(size) || size < 0) {
1955
- throw createError({ statusCode: 500, statusMessage: "Invalid canonical file size" });
1956
- }
1957
- usedBytes += size;
1958
- if (normalizeStorageHash(row.id) === hash) alreadyStored = true;
1959
- }
1960
- const [totals] = await d1All(
1961
- `SELECT COALESCE(SUM(reserved_bytes), 0) AS reserved_bytes,
1962
- MAX(CASE WHEN hash = ? AND reserved_bytes > 0 THEN 1 ELSE 0 END) AS same_hash
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" });
1972
- }
1973
- await d1Batch([
2025
+ const results = await d1Batch([
1974
2026
  {
1975
2027
  sql: `UPDATE upload_intents SET status = 'expired'
1976
2028
  WHERE workspace_id = ? AND status = 'active' AND expires_at <= ?`,
1977
2029
  parameters: [input.workspaceId, now]
1978
2030
  },
1979
2031
  {
1980
- sql: `INSERT INTO upload_intents (
2032
+ // Keep the quota decision in the write statement: D1's async
2033
+ // preflight reads cannot serialize concurrent reservations.
2034
+ sql: `WITH pending AS (${QUOTA_RESERVATIONS_SQL}), quota AS (
2035
+ SELECT
2036
+ COALESCE((SELECT used_bytes FROM storage_usage WHERE workspace_id = ?), 0) AS used_bytes,
2037
+ (SELECT COALESCE(SUM(held_bytes), 0) FROM pending) AS pending_bytes,
2038
+ MAX(0, ? - MAX(COALESCE((SELECT size_bytes FROM retained_storage WHERE workspace_id = ? AND hash = ?), 0),
2039
+ (SELECT COALESCE(MAX(reserved_bytes), 0) FROM pending WHERE hash = ?))) AS added_bytes
2040
+ ) INSERT INTO upload_intents (
1981
2041
  id, workspace_id, hash, mime_type, size_bytes, reserved_bytes,
1982
2042
  expires_at, status, created_at
1983
- ) VALUES (?, ?, ?, ?, ?, ?, ?, 'active', ?)`,
2043
+ ) SELECT ?, ?, ?, ?, ?, ?, ?, 'active', ? FROM quota
2044
+ WHERE (? IS NULL OR used_bytes + pending_bytes + added_bytes <= ?)`,
1984
2045
  parameters: [
2046
+ input.workspaceId,
2047
+ now,
2048
+ input.workspaceId,
2049
+ input.sizeBytes,
2050
+ input.workspaceId,
2051
+ hash,
2052
+ hash,
1985
2053
  input.intentId,
1986
2054
  input.workspaceId,
1987
2055
  hash,
1988
2056
  input.mimeType,
1989
2057
  input.sizeBytes,
1990
- reservedBytes,
2058
+ input.sizeBytes,
1991
2059
  input.expiresAt,
1992
- now
2060
+ now,
2061
+ input.workspaceQuotaBytes ?? null,
2062
+ input.workspaceQuotaBytes ?? null
1993
2063
  ]
1994
2064
  }
1995
2065
  ]);
2066
+ if (results[1]?.meta?.changes !== 1) {
2067
+ throw createError({ statusCode: 413, statusMessage: "Workspace storage quota exceeded" });
2068
+ }
1996
2069
  }
1997
- async snapshotInD1(workspaceId, input, pageSize, snapshotUserId) {
2070
+ async snapshotInD1(workspaceId, input, pageSize, snapshotUserId, retainedFiles) {
1998
2071
  const now = nowEpoch();
1999
2072
  let header;
2000
2073
  let after;
@@ -2023,11 +2096,14 @@ export class SqliteSyncGatewayAdapter {
2023
2096
  statusMessage: "Snapshot table filter cannot change between pages"
2024
2097
  });
2025
2098
  }
2099
+ if (existing.id.startsWith("backup:") !== retainedFiles) {
2100
+ throw createError({ statusCode: 400, statusMessage: "Snapshot mode cannot change between pages" });
2101
+ }
2026
2102
  header = existing;
2027
2103
  after = token.after;
2028
2104
  } else {
2029
2105
  const tables = normalizeSnapshotTables(input.tables);
2030
- const snapshotId = uid();
2106
+ const snapshotId = `${retainedFiles ? "backup:" : ""}${uid()}`;
2031
2107
  const expiresAt = now + SNAPSHOT_TTL_SECONDS;
2032
2108
  const tablesJson = JSON.stringify(tables);
2033
2109
  const statements = [
@@ -2096,7 +2172,8 @@ export class SqliteSyncGatewayAdapter {
2096
2172
  clock, hlc, op_id, server_deleted_at
2097
2173
  )
2098
2174
  SELECT
2099
- ?, ?, materialized.id, 'tombstone', NULL,
2175
+ ?, ?, materialized.id, '${retainedFiles && tableName === "file_meta" ? "row" : "tombstone"}',
2176
+ ${retainedFiles && tableName === "file_meta" ? "json_set(materialized.data_json, '$.deleted', json('true'), '$.clock', materialized.clock, '$.hlc', materialized.hlc, '$.updated_at', materialized.updated_at)" : "NULL"},
2100
2177
  materialized.clock,
2101
2178
  CASE
2102
2179
  WHEN materialized.hlc <> '' THEN materialized.hlc
@@ -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
- createWebhook(webhook) {
500
- return this.store.then((store) => store.createWebhook(webhook));
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));
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "or3-provider-sqlite",
3
- "version": "0.0.17",
3
+ "version": "0.0.19",
4
4
  "repository": {
5
5
  "type": "git",
6
6
  "url": "git+https://github.com/Saluana/or3-provider-sqlite.git"