or3-provider-sqlite 0.0.28 → 0.0.29

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
@@ -236,6 +236,7 @@ All tables use snake_case aligned with the sync wire format.
236
236
  - **Push**: validates ops (including a 256 KB serialized payload ceiling per operation) → checks `op_id` idempotency → allocates contiguous `server_version` values for admitted change-log entries → applies LWW to materialized tables → upserts tombstones for deletes. D1 admission and version allocation share one atomic batch; rejected notification races consume no versions.
237
237
  - **Pull**: returns ordered changes for `server_version > cursor` with limit/pagination, optional table filtering, `oldestRetainedVersion`, and `requiresSnapshot` when the cursor is behind retained history
238
238
  - **Snapshot**: captures canonical live rows and current tombstones at one `highWatermark`, then serves immutable, keyset-paginated pages ordered by `(tableName, pk, kind)`. Notification live rows are filtered to the session user.
239
+ - **Page size**: pull and snapshot responses target at most 1 MiB of serialized JSON, including the envelope, as well as their row limit. A preliminary size scan limits payloads transferred from the database; the database may still read rows to determine their sizes. A single oversized record is returned whole so pagination always progresses. Filtered notifications still advance the pull cursor.
239
240
  - **Cursor**: forward-only tracking per authenticated user and device within a workspace. Migration 028 changes the unique key so accounts sharing a browser device ID cannot claim each other’s acknowledgements. Legacy unowned rows are never adopted and expire through normal cursor GC.
240
241
  - **Retention safety**: tombstone and `change_log` GC is enabled only under the explicit `snapshot-v1` capability and deletes old revisions acknowledged by every registered device
241
242
  - **Notifications**: push forces `payload.user_id` to the session user on puts and deletes; foreign notification writes are rejected. Successful deletes remain visible to the owner's other devices while pull/snapshot omit other users' rows.
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.28",
4
+ "version": "0.0.29",
5
5
  "builder": {
6
6
  "@nuxt/module-builder": "1.0.3",
7
7
  "unbuild": "3.6.1"
@@ -2,6 +2,7 @@ import { SqliteExternalStorageGenerationUploadCoordinator } from "../storage/sql
2
2
  import { backgroundFinalizationFingerprint, stableJson } from "./background-history-fingerprint.js";
3
3
  import { hasWorkspaceItemSemantics, WORKSPACE_ITEM_CAPABILITY } from "./workspace-item-capability.js";
4
4
  import { createHash } from "node:crypto";
5
+ import { sql } from "kysely";
5
6
  import { canRunSyncHistoryGc } from "./history-gc-policy.js";
6
7
  import { createError } from "h3";
7
8
  import {
@@ -43,6 +44,8 @@ const SESSION_CONTEXT_KEY_PREFIX = "__or3_session_context_";
43
44
  const MIN_SYNC_RETENTION_SECONDS = 60 * 60;
44
45
  const MAX_SYNC_RETENTION_SECONDS = 365 * 24 * 60 * 60;
45
46
  const MAX_SYNC_PAYLOAD_BYTES = 256 * 1024;
47
+ const MAX_SYNC_PAGE_BYTES = 1024 * 1024;
48
+ const jsonBytes = (value) => new TextEncoder().encode(JSON.stringify(value)).byteLength;
46
49
  const PENDING_UPLOAD_RESERVATIONS_SQL = `
47
50
  SELECT MIN(intent.id) AS id, intent.hash,
48
51
  MAX(intent.size_bytes) AS reserved_bytes, MAX(intent.expires_at) AS expires_at
@@ -64,6 +67,72 @@ const QUOTA_RESERVATIONS_SQL = `SELECT intent.hash, MAX(intent.size_bytes) AS re
64
67
  ON retained.workspace_id = intent.workspace_id AND retained.hash = intent.hash
65
68
  WHERE intent.workspace_id = ? AND intent.status = 'active' AND intent.expires_at > ?
66
69
  GROUP BY intent.hash`;
70
+ function boundedPayloadRowCount(sizes, limit) {
71
+ let count = 0;
72
+ let bytes = 0;
73
+ for (const row of sizes.slice(0, limit)) {
74
+ const size = Math.max(0, Number(row.payload_bytes) || 0);
75
+ if (count && bytes + size > MAX_SYNC_PAGE_BYTES) break;
76
+ count++;
77
+ bytes += size;
78
+ }
79
+ return count;
80
+ }
81
+ function snapshotPageSelection(headerId, after) {
82
+ const clause = `FROM sync_snapshot_items WHERE snapshot_id = ?${after ? `
83
+ AND (table_name > ? OR (table_name = ? AND pk > ?)
84
+ OR (table_name = ? AND pk = ? AND kind > ?))` : ""}
85
+ ORDER BY table_name ASC, pk ASC, kind ASC LIMIT ?`;
86
+ const parameters = after ? [headerId, after.tableName, after.tableName, after.pk, after.tableName, after.pk, after.kind] : [headerId];
87
+ return { clause, parameters };
88
+ }
89
+ function buildSnapshotPage(header, rows, pageSize, availableRows) {
90
+ const items = [];
91
+ let itemBytes = 0;
92
+ let scanned = 0;
93
+ let token = null;
94
+ for (const row of rows.slice(0, pageSize)) {
95
+ const revision = { clock: row.clock, hlc: row.hlc, opId: row.op_id };
96
+ const item = row.kind === "row" ? {
97
+ kind: "row",
98
+ tableName: row.table_name,
99
+ pk: row.pk,
100
+ payload: JSON.parse(row.payload_json ?? "null"),
101
+ revision
102
+ } : {
103
+ kind: "tombstone",
104
+ tableName: row.table_name,
105
+ pk: row.pk,
106
+ revision,
107
+ serverDeletedAt: row.server_deleted_at ?? 0
108
+ };
109
+ const next = encodeSnapshotPageToken({
110
+ version: 1,
111
+ snapshotId: header.id,
112
+ after: { tableName: row.table_name, pk: row.pk, kind: row.kind }
113
+ });
114
+ const bytes = jsonBytes(item) + (items.length ? 1 : 0);
115
+ const envelope = jsonBytes({
116
+ workspaceId: header.workspace_id,
117
+ snapshotId: header.id,
118
+ highWatermark: header.high_watermark,
119
+ items: [],
120
+ nextPageToken: next
121
+ });
122
+ if (items.length && envelope + itemBytes + bytes > MAX_SYNC_PAGE_BYTES) break;
123
+ items.push(item);
124
+ itemBytes += bytes;
125
+ scanned++;
126
+ token = next;
127
+ }
128
+ return {
129
+ workspaceId: header.workspace_id,
130
+ snapshotId: header.id,
131
+ highWatermark: header.high_watermark,
132
+ items,
133
+ nextPageToken: availableRows > scanned ? token : null
134
+ };
135
+ }
67
136
  function uid() {
68
137
  return globalThis.crypto.randomUUID();
69
138
  }
@@ -1125,7 +1194,7 @@ export class SqliteSyncGatewayAdapter {
1125
1194
  const now = nowEpoch();
1126
1195
  const hash = normalizeStorageHash(input.hash);
1127
1196
  const raw = isD1Driver() ? null : getRawDb();
1128
- const sql = `UPDATE upload_intents
1197
+ const sql2 = `UPDATE upload_intents
1129
1198
  SET status = 'consumed', storage_id = ?, consumed_at = ?
1130
1199
  WHERE id = ? AND workspace_id = ? AND status = 'active' AND expires_at > ?
1131
1200
  AND hash = ? AND mime_type = ? AND size_bytes = ?`;
@@ -1139,7 +1208,7 @@ export class SqliteSyncGatewayAdapter {
1139
1208
  input.mimeType,
1140
1209
  input.sizeBytes
1141
1210
  ];
1142
- const changes = raw ? raw.prepare(sql).run(...parameters).changes : (await d1Run(sql, ...parameters)).meta?.changes;
1211
+ const changes = raw ? raw.prepare(sql2).run(...parameters).changes : (await d1Run(sql2, ...parameters)).meta?.changes;
1143
1212
  if (changes === 1) return;
1144
1213
  const receiptSql = `SELECT 1 FROM upload_intents
1145
1214
  WHERE id = ? AND workspace_id = ? AND status = 'consumed' AND expires_at > ?
@@ -1190,7 +1259,7 @@ export class SqliteSyncGatewayAdapter {
1190
1259
  }
1191
1260
  const after = decodeCanonicalStorageCursor(input.cursor, input.kind, hash);
1192
1261
  const raw = isD1Driver() ? null : getRawDb();
1193
- const all = async (sql, ...parameters) => raw ? raw.prepare(sql).all(...parameters) : d1All(sql, ...parameters);
1262
+ const all = async (sql2, ...parameters) => raw ? raw.prepare(sql2).all(...parameters) : d1All(sql2, ...parameters);
1194
1263
  if (input.kind === "active_reservations") {
1195
1264
  if (after.length > 1) {
1196
1265
  throw createError({ statusCode: 400, statusMessage: "Invalid canonical storage cursor" });
@@ -1769,30 +1838,13 @@ export class SqliteSyncGatewayAdapter {
1769
1838
  const { scope, cursor, limit, tables } = input;
1770
1839
  await assertWorkspaceScopeAuthorized(event, scope.workspaceId);
1771
1840
  const fetchLimit = resolvePullLimit(limit);
1772
- let query = db.selectFrom("change_log").selectAll().where("workspace_id", "=", scope.workspaceId).where("server_version", ">", cursor).orderBy("server_version", "asc").limit(fetchLimit + 1);
1841
+ let query = db.selectFrom("change_log").where("workspace_id", "=", scope.workspaceId).where("server_version", ">", cursor).orderBy("server_version", "asc");
1773
1842
  if (tables?.length) {
1774
1843
  query = query.where("table_name", "in", tables);
1775
1844
  }
1776
- const rows = await query.execute();
1777
- const hasMore = rows.length > fetchLimit;
1778
- const resultRows = hasMore ? rows.slice(0, fetchLimit) : rows;
1779
- const changes = resultRows.map((row) => ({
1780
- serverVersion: row.server_version,
1781
- tableName: row.table_name,
1782
- pk: row.pk,
1783
- op: row.op,
1784
- payload: row.payload_json ? JSON.parse(row.payload_json) : void 0,
1785
- stamp: {
1786
- clock: row.clock,
1787
- hlc: row.hlc,
1788
- deviceId: row.device_id,
1789
- opId: row.op_id
1790
- }
1791
- })).filter(
1792
- (change) => isNotificationVisibleToUser(change, resolveSessionUserId(event))
1793
- );
1794
- const lastRow = resultRows[resultRows.length - 1];
1795
- const nextCursor = lastRow ? lastRow.server_version : cursor;
1845
+ const sizes = await query.select(sql`coalesce(length(cast(payload_json as blob)), 0)`.as("payload_bytes")).limit(fetchLimit + 1).execute();
1846
+ const selected = boundedPayloadRowCount(sizes, fetchLimit);
1847
+ const rows = selected ? await query.selectAll().limit(selected).execute() : [];
1796
1848
  const minLog = await db.selectFrom("change_log").select("server_version").where("workspace_id", "=", scope.workspaceId).orderBy("server_version", "asc").limit(1).executeTakeFirst();
1797
1849
  const counter = await db.selectFrom("server_version_counter").select("value").where("workspace_id", "=", scope.workspaceId).executeTakeFirst();
1798
1850
  const retention = computePullRetention({
@@ -1800,12 +1852,30 @@ export class SqliteSyncGatewayAdapter {
1800
1852
  oldestLogVersion: minLog?.server_version ?? null,
1801
1853
  highWatermark: counter?.value ?? 0
1802
1854
  });
1803
- return {
1804
- changes,
1805
- nextCursor,
1806
- hasMore,
1807
- ...retention
1808
- };
1855
+ const changes = [];
1856
+ let itemBytes = 0;
1857
+ let scanned = 0;
1858
+ let nextCursor = cursor;
1859
+ for (const row of rows.slice(0, fetchLimit)) {
1860
+ const change = {
1861
+ serverVersion: row.server_version,
1862
+ tableName: row.table_name,
1863
+ pk: row.pk,
1864
+ op: row.op,
1865
+ payload: row.payload_json ? JSON.parse(row.payload_json) : void 0,
1866
+ stamp: { clock: row.clock, hlc: row.hlc, deviceId: row.device_id, opId: row.op_id }
1867
+ };
1868
+ if (isNotificationVisibleToUser(change, resolveSessionUserId(event))) {
1869
+ const bytes = jsonBytes(change) + (changes.length ? 1 : 0);
1870
+ const envelope = jsonBytes({ changes: [], nextCursor: row.server_version, hasMore: false, ...retention });
1871
+ if (changes.length && envelope + itemBytes + bytes > MAX_SYNC_PAGE_BYTES) break;
1872
+ changes.push(change);
1873
+ itemBytes += bytes;
1874
+ }
1875
+ scanned++;
1876
+ nextCursor = row.server_version;
1877
+ }
1878
+ return { changes, nextCursor, hasMore: sizes.length > scanned, ...retention };
1809
1879
  }
1810
1880
  async snapshot(event, input) {
1811
1881
  return this.captureSnapshot(event, input, false);
@@ -1997,79 +2067,11 @@ export class SqliteSyncGatewayAdapter {
1997
2067
  });
1998
2068
  header = capture.immediate();
1999
2069
  }
2000
- const rows = after ? raw.prepare(`
2001
- SELECT
2002
- table_name, pk, kind, payload_json, clock, hlc, op_id,
2003
- server_deleted_at
2004
- FROM sync_snapshot_items
2005
- WHERE snapshot_id = ?
2006
- AND (
2007
- table_name > ?
2008
- OR (table_name = ? AND pk > ?)
2009
- OR (table_name = ? AND pk = ? AND kind > ?)
2010
- )
2011
- ORDER BY table_name ASC, pk ASC, kind ASC
2012
- LIMIT ?
2013
- `).all(
2014
- header.id,
2015
- after.tableName,
2016
- after.tableName,
2017
- after.pk,
2018
- after.tableName,
2019
- after.pk,
2020
- after.kind,
2021
- pageSize + 1
2022
- ) : raw.prepare(`
2023
- SELECT
2024
- table_name, pk, kind, payload_json, clock, hlc, op_id,
2025
- server_deleted_at
2026
- FROM sync_snapshot_items
2027
- WHERE snapshot_id = ?
2028
- ORDER BY table_name ASC, pk ASC, kind ASC
2029
- LIMIT ?
2030
- `).all(header.id, pageSize + 1);
2031
- const hasMore = rows.length > pageSize;
2032
- const pageRows = hasMore ? rows.slice(0, pageSize) : rows;
2033
- const items = pageRows.map((row) => {
2034
- const revision = {
2035
- clock: row.clock,
2036
- hlc: row.hlc,
2037
- opId: row.op_id
2038
- };
2039
- if (row.kind === "row") {
2040
- return {
2041
- kind: "row",
2042
- tableName: row.table_name,
2043
- pk: row.pk,
2044
- payload: JSON.parse(row.payload_json ?? "null"),
2045
- revision
2046
- };
2047
- }
2048
- return {
2049
- kind: "tombstone",
2050
- tableName: row.table_name,
2051
- pk: row.pk,
2052
- revision,
2053
- serverDeletedAt: row.server_deleted_at ?? 0
2054
- };
2055
- });
2056
- const lastRow = pageRows.at(-1);
2057
- const nextPageToken = hasMore && lastRow ? encodeSnapshotPageToken({
2058
- version: 1,
2059
- snapshotId: header.id,
2060
- after: {
2061
- tableName: lastRow.table_name,
2062
- pk: lastRow.pk,
2063
- kind: lastRow.kind
2064
- }
2065
- }) : null;
2066
- return {
2067
- workspaceId: header.workspace_id,
2068
- snapshotId: header.id,
2069
- highWatermark: header.high_watermark,
2070
- items,
2071
- nextPageToken
2072
- };
2070
+ const selection = snapshotPageSelection(header.id, after);
2071
+ const sizes = raw.prepare(`SELECT coalesce(length(cast(payload_json as blob)), 0) AS payload_bytes ${selection.clause}`).all(...selection.parameters, pageSize + 1);
2072
+ const selected = boundedPayloadRowCount(sizes, pageSize);
2073
+ const rows = selected ? raw.prepare(`SELECT table_name, pk, kind, payload_json, clock, hlc, op_id, server_deleted_at ${selection.clause}`).all(...selection.parameters, selected) : [];
2074
+ return buildSnapshotPage(header, rows, pageSize, sizes.length);
2073
2075
  }
2074
2076
  async updateCursor(event, input) {
2075
2077
  await assertWorkspaceScopeAuthorized(event, input.scope.workspaceId);
@@ -2467,34 +2469,18 @@ export class SqliteSyncGatewayAdapter {
2467
2469
  if (!created) throw createError({ statusCode: 410, statusMessage: "Snapshot expired or unavailable" });
2468
2470
  header = created;
2469
2471
  }
2470
- const rows = after ? await d1All(
2471
- `SELECT table_name, pk, kind, payload_json, clock, hlc, op_id, server_deleted_at
2472
- FROM sync_snapshot_items
2473
- WHERE snapshot_id = ?
2474
- AND (
2475
- table_name > ?
2476
- OR (table_name = ? AND pk > ?)
2477
- OR (table_name = ? AND pk = ? AND kind > ?)
2478
- )
2479
- ORDER BY table_name ASC, pk ASC, kind ASC
2480
- LIMIT ?`,
2481
- header.id,
2482
- after.tableName,
2483
- after.tableName,
2484
- after.pk,
2485
- after.tableName,
2486
- after.pk,
2487
- after.kind,
2488
- pageSize + 1
2489
- ) : await d1All(
2490
- `SELECT table_name, pk, kind, payload_json, clock, hlc, op_id, server_deleted_at
2491
- FROM sync_snapshot_items
2492
- WHERE snapshot_id = ?
2493
- ORDER BY table_name ASC, pk ASC, kind ASC
2494
- LIMIT ?`,
2495
- header.id,
2472
+ const selection = snapshotPageSelection(header.id, after);
2473
+ const sizes = await d1All(
2474
+ `SELECT coalesce(length(cast(payload_json as blob)), 0) AS payload_bytes ${selection.clause}`,
2475
+ ...selection.parameters,
2496
2476
  pageSize + 1
2497
2477
  );
2478
+ const selected = boundedPayloadRowCount(sizes, pageSize);
2479
+ const rows = selected ? await d1All(
2480
+ `SELECT table_name, pk, kind, payload_json, clock, hlc, op_id, server_deleted_at ${selection.clause}`,
2481
+ ...selection.parameters,
2482
+ selected
2483
+ ) : [];
2498
2484
  const [retained] = await d1All(
2499
2485
  "SELECT expires_at FROM sync_snapshots WHERE id = ?",
2500
2486
  header.id
@@ -2502,43 +2488,7 @@ export class SqliteSyncGatewayAdapter {
2502
2488
  if (!retained || retained.expires_at <= nowEpoch()) {
2503
2489
  throw createError({ statusCode: 410, statusMessage: "Snapshot expired or unavailable" });
2504
2490
  }
2505
- const hasMore = rows.length > pageSize;
2506
- const pageRows = hasMore ? rows.slice(0, pageSize) : rows;
2507
- const items = pageRows.map((row) => {
2508
- const revision = { clock: row.clock, hlc: row.hlc, opId: row.op_id };
2509
- if (row.kind === "row") {
2510
- return {
2511
- kind: "row",
2512
- tableName: row.table_name,
2513
- pk: row.pk,
2514
- payload: JSON.parse(row.payload_json ?? "null"),
2515
- revision
2516
- };
2517
- }
2518
- return {
2519
- kind: "tombstone",
2520
- tableName: row.table_name,
2521
- pk: row.pk,
2522
- revision,
2523
- serverDeletedAt: row.server_deleted_at ?? 0
2524
- };
2525
- });
2526
- const lastRow = pageRows.at(-1);
2527
- return {
2528
- workspaceId: header.workspace_id,
2529
- snapshotId: header.id,
2530
- highWatermark: header.high_watermark,
2531
- items,
2532
- nextPageToken: hasMore && lastRow ? encodeSnapshotPageToken({
2533
- version: 1,
2534
- snapshotId: header.id,
2535
- after: {
2536
- tableName: lastRow.table_name,
2537
- pk: lastRow.pk,
2538
- kind: lastRow.kind
2539
- }
2540
- }) : null
2541
- };
2491
+ return buildSnapshotPage(header, rows, pageSize, sizes.length);
2542
2492
  }
2543
2493
  async updateCursorInD1(workspaceId, deviceId, version, ownerUserId, now) {
2544
2494
  const [counter] = await d1All(
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "or3-provider-sqlite",
3
- "version": "0.0.28",
3
+ "version": "0.0.29",
4
4
  "repository": {
5
5
  "type": "git",
6
6
  "url": "git+https://github.com/Saluana/or3-provider-sqlite.git"