or3-provider-sqlite 0.0.18 → 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
@@ -19,13 +19,23 @@ Canonical storage queries include bounded retained deleted metadata pages and
19
19
  advertise `retainedStorageMetadata: 'v1'` on native SQLite and D1. Missing sizes in
20
20
  delete-before-put rows remain unknown; these reads never replay sync history.
21
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.
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.
29
39
 
30
40
  ## Atomic webhook registration quotas
31
41
 
@@ -228,6 +238,11 @@ model execution there; ordinary sync and other D1 features are unchanged.
228
238
 
229
239
  ## Backup
230
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
+
231
246
  For local-file and Bun runtimes, everything lives in a single SQLite file:
232
247
 
233
248
  ```bash
@@ -264,9 +279,17 @@ mismatched source rather than falling back to fixtures. See the
264
279
  ### Known differences vs Convex
265
280
 
266
281
  - Single-process SQLite vs distributed Convex backend
267
- - No real-time subscriptions (gateway polling only)
282
+ - Gateway version notifications use a shared counter poll; no native reactive SQLite subscription
268
283
  - Migrations run on boot, or on the first Worker request for D1; schema changes require restart
269
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
+
270
293
  ## Troubleshooting
271
294
 
272
295
  - **`OR3_SQLITE_DB_PATH is required in non-test environments`** — set a file
@@ -315,6 +338,10 @@ Persistent Projects uses this same capability for opaque `or3:project-settings`,
315
338
 
316
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.
317
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.
344
+
318
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.
319
346
 
320
347
  Native synchronous adapters advertise workspace-item capability v1. Canonical
@@ -336,3 +363,19 @@ the supported profile is qualified.
336
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.
337
364
 
338
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.18",
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
+ }
@@ -12,10 +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";
18
22
  readonly retainedStorageMetadata: "v1";
23
+ readonly atomicUploadQuota: "retained-v1";
19
24
  readonly backgroundGenerationHistory?: undefined;
20
25
  readonly canonicalChatHistory?: undefined;
21
26
  readonly projectOwnership?: undefined;
@@ -28,6 +33,7 @@ export declare class SqliteSyncGatewayAdapter implements SyncGatewayAdapter {
28
33
  readonly projectOwnership: "v1";
29
34
  readonly workspaceItems: "v1";
30
35
  readonly retainedStorageMetadata: "v1";
36
+ readonly atomicUploadQuota: "retained-v1";
31
37
  };
32
38
  private get db();
33
39
  readChatHistory(actor: CanonicalHistoryActor, query: CanonicalChatQuery, signal?: AbortSignal): Promise<CanonicalChatReadResult>;
@@ -47,6 +53,9 @@ export declare class SqliteSyncGatewayAdapter implements SyncGatewayAdapter {
47
53
  push(event: H3Event, input: PushBatch): Promise<PushResult>;
48
54
  pull(event: H3Event, input: PullRequest): Promise<PullResponse>;
49
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;
50
59
  updateCursor(event: H3Event, input: {
51
60
  scope: {
52
61
  workspaceId: string;
@@ -48,6 +48,12 @@ const PENDING_UPLOAD_RESERVATIONS_SQL = `
48
48
  )
49
49
  GROUP BY intent.hash
50
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`;
51
57
  function uid() {
52
58
  return globalThis.crypto.randomUUID();
53
59
  }
@@ -439,11 +445,53 @@ async function currentWinnerD1(workspaceId, tableName, pk) {
439
445
  }
440
446
  export class SqliteSyncGatewayAdapter {
441
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
+ }
442
489
  get capabilities() {
443
490
  return isD1Driver() ? {
444
491
  snapshotBootstrap: "snapshot-v1",
445
492
  historyRetention: "snapshot-v1",
446
- retainedStorageMetadata: "v1"
493
+ retainedStorageMetadata: "v1",
494
+ atomicUploadQuota: "retained-v1"
447
495
  } : {
448
496
  snapshotBootstrap: "snapshot-v1",
449
497
  historyRetention: "snapshot-v1",
@@ -451,7 +499,8 @@ export class SqliteSyncGatewayAdapter {
451
499
  canonicalChatHistory: "v1",
452
500
  projectOwnership: "v1",
453
501
  workspaceItems: "v1",
454
- retainedStorageMetadata: "v1"
502
+ retainedStorageMetadata: "v1",
503
+ atomicUploadQuota: "retained-v1"
455
504
  };
456
505
  }
457
506
  get db() {
@@ -828,31 +877,13 @@ export class SqliteSyncGatewayAdapter {
828
877
  const now = nowEpoch();
829
878
  raw.prepare(`UPDATE upload_intents SET status = 'expired'
830
879
  WHERE workspace_id = ? AND status = 'active' AND expires_at <= ?`).run(input.workspaceId, now);
831
- const liveRows = raw.prepare(`SELECT id, data_json FROM s_file_meta
832
- WHERE workspace_id = ? AND deleted = 0`).all(input.workspaceId);
833
- let usedBytes = 0;
834
- let alreadyStored = false;
835
- const liveSizes = /* @__PURE__ */ new Map();
836
- for (const row of liveRows) {
837
- const payload = JSON.parse(row.data_json);
838
- const size = payload.size_bytes ?? payload.sizeBytes;
839
- if (typeof size !== "number" || !Number.isSafeInteger(size) || size < 0) {
840
- throw createError({ statusCode: 500, statusMessage: "Invalid canonical file size" });
841
- }
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;
850
- }
851
- const totals = raw.prepare(`WITH pending AS (${PENDING_UPLOAD_RESERVATIONS_SQL}) SELECT
852
- COALESCE(SUM(reserved_bytes), 0) AS reserved_bytes,
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,
853
884
  COALESCE(MAX(CASE WHEN hash = ? THEN reserved_bytes END), 0) AS same_hash
854
885
  FROM pending`).get(input.workspaceId, now, hash);
855
- const addedBytes = alreadyStored ? 0 : Math.max(0, input.sizeBytes - totals.same_hash);
886
+ const addedBytes = Math.max(0, input.sizeBytes - Math.max(retainedBytes, totals.same_hash));
856
887
  if (input.workspaceQuotaBytes !== void 0 && usedBytes + totals.reserved_bytes + addedBytes > input.workspaceQuotaBytes) {
857
888
  throw createError({ statusCode: 413, statusMessage: "Workspace storage quota exceeded" });
858
889
  }
@@ -1562,12 +1593,19 @@ export class SqliteSyncGatewayAdapter {
1562
1593
  };
1563
1594
  }
1564
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) {
1565
1603
  const workspaceId = input.scope.workspaceId;
1566
1604
  await assertWorkspaceScopeAuthorized(event, workspaceId);
1567
1605
  const pageSize = resolveSnapshotPageSize(input.pageSize);
1568
1606
  const snapshotUserId = resolveSessionUserId(event);
1569
1607
  if (isD1Driver()) {
1570
- return this.snapshotInD1(workspaceId, input, pageSize, snapshotUserId);
1608
+ return this.snapshotInD1(workspaceId, input, pageSize, snapshotUserId, retainedFiles);
1571
1609
  }
1572
1610
  const raw = getRawDb();
1573
1611
  const now = nowEpoch();
@@ -1607,11 +1645,14 @@ export class SqliteSyncGatewayAdapter {
1607
1645
  statusMessage: "Snapshot table filter cannot change between pages"
1608
1646
  });
1609
1647
  }
1648
+ if (existing.id.startsWith("backup:") !== retainedFiles) {
1649
+ throw createError({ statusCode: 400, statusMessage: "Snapshot mode cannot change between pages" });
1650
+ }
1610
1651
  header = existing;
1611
1652
  after = token.after;
1612
1653
  } else {
1613
1654
  const tables = normalizeSnapshotTables(input.tables);
1614
- const snapshotId = uid();
1655
+ const snapshotId = `${retainedFiles ? "backup:" : ""}${uid()}`;
1615
1656
  const expiresAt = now + SNAPSHOT_TTL_SECONDS;
1616
1657
  const capture = raw.transaction(() => {
1617
1658
  raw.prepare("DELETE FROM sync_snapshots WHERE expires_at <= ?").run(now);
@@ -1670,7 +1711,8 @@ export class SqliteSyncGatewayAdapter {
1670
1711
  clock, hlc, op_id, server_deleted_at
1671
1712
  )
1672
1713
  SELECT
1673
- ?, ?, 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"},
1674
1716
  materialized.clock,
1675
1717
  CASE
1676
1718
  WHEN materialized.hlc <> '' THEN materialized.hlc
@@ -1980,25 +2022,6 @@ export class SqliteSyncGatewayAdapter {
1980
2022
  }
1981
2023
  async reserveUploadIntentInD1(input, hash) {
1982
2024
  const now = nowEpoch();
1983
- const liveRows = await d1All(
1984
- `SELECT id, data_json FROM s_file_meta
1985
- WHERE workspace_id = ? AND deleted = 0`,
1986
- input.workspaceId
1987
- );
1988
- const liveSizes = /* @__PURE__ */ new Map();
1989
- for (const row of liveRows) {
1990
- const payload = JSON.parse(row.data_json);
1991
- const size = payload.size_bytes ?? payload.sizeBytes;
1992
- if (typeof size !== "number" || !Number.isSafeInteger(size) || size < 0) {
1993
- throw createError({ statusCode: 500, statusMessage: "Invalid canonical file size" });
1994
- }
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);
2001
- }
2002
2025
  const results = await d1Batch([
2003
2026
  {
2004
2027
  sql: `UPDATE upload_intents SET status = 'expired'
@@ -2008,37 +2031,24 @@ export class SqliteSyncGatewayAdapter {
2008
2031
  {
2009
2032
  // Keep the quota decision in the write statement: D1's async
2010
2033
  // 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 (
2034
+ sql: `WITH pending AS (${QUOTA_RESERVATIONS_SQL}), quota AS (
2019
2035
  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
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
2027
2040
  ) INSERT INTO upload_intents (
2028
2041
  id, workspace_id, hash, mime_type, size_bytes, reserved_bytes,
2029
2042
  expires_at, status, created_at
2030
2043
  ) 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))`,
2044
+ WHERE (? IS NULL OR used_bytes + pending_bytes + added_bytes <= ?)`,
2036
2045
  parameters: [
2037
2046
  input.workspaceId,
2038
2047
  now,
2039
2048
  input.workspaceId,
2040
- hash,
2041
2049
  input.sizeBytes,
2050
+ input.workspaceId,
2051
+ hash,
2042
2052
  hash,
2043
2053
  input.intentId,
2044
2054
  input.workspaceId,
@@ -2057,7 +2067,7 @@ export class SqliteSyncGatewayAdapter {
2057
2067
  throw createError({ statusCode: 413, statusMessage: "Workspace storage quota exceeded" });
2058
2068
  }
2059
2069
  }
2060
- async snapshotInD1(workspaceId, input, pageSize, snapshotUserId) {
2070
+ async snapshotInD1(workspaceId, input, pageSize, snapshotUserId, retainedFiles) {
2061
2071
  const now = nowEpoch();
2062
2072
  let header;
2063
2073
  let after;
@@ -2086,11 +2096,14 @@ export class SqliteSyncGatewayAdapter {
2086
2096
  statusMessage: "Snapshot table filter cannot change between pages"
2087
2097
  });
2088
2098
  }
2099
+ if (existing.id.startsWith("backup:") !== retainedFiles) {
2100
+ throw createError({ statusCode: 400, statusMessage: "Snapshot mode cannot change between pages" });
2101
+ }
2089
2102
  header = existing;
2090
2103
  after = token.after;
2091
2104
  } else {
2092
2105
  const tables = normalizeSnapshotTables(input.tables);
2093
- const snapshotId = uid();
2106
+ const snapshotId = `${retainedFiles ? "backup:" : ""}${uid()}`;
2094
2107
  const expiresAt = now + SNAPSHOT_TTL_SECONDS;
2095
2108
  const tablesJson = JSON.stringify(tables);
2096
2109
  const statements = [
@@ -2159,7 +2172,8 @@ export class SqliteSyncGatewayAdapter {
2159
2172
  clock, hlc, op_id, server_deleted_at
2160
2173
  )
2161
2174
  SELECT
2162
- ?, ?, 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"},
2163
2177
  materialized.clock,
2164
2178
  CASE
2165
2179
  WHEN materialized.hlc <> '' THEN materialized.hlc
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "or3-provider-sqlite",
3
- "version": "0.0.18",
3
+ "version": "0.0.19",
4
4
  "repository": {
5
5
  "type": "git",
6
6
  "url": "git+https://github.com/Saluana/or3-provider-sqlite.git"