or3-provider-sqlite 0.0.19 → 0.0.21
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 +30 -12
- package/dist/module.json +1 -1
- package/dist/runtime/server/db/migrate.js +5 -1
- package/dist/runtime/server/db/migrations/027_verified_storage_usage.d.ts +6 -0
- package/dist/runtime/server/db/migrations/027_verified_storage_usage.js +12 -0
- package/dist/runtime/server/db/migrations/028_user_scoped_device_cursors.d.ts +6 -0
- package/dist/runtime/server/db/migrations/028_user_scoped_device_cursors.js +6 -0
- package/dist/runtime/server/plugins/register.js +16 -1
- package/dist/runtime/server/sync/sqlite-sync-gateway-adapter.d.ts +1 -0
- package/dist/runtime/server/sync/sqlite-sync-gateway-adapter.js +102 -55
- package/package.json +3 -3
package/README.md
CHANGED
|
@@ -2,6 +2,8 @@
|
|
|
2
2
|
|
|
3
3
|
SQLite sync and workspace store provider for OR3 Chat. Provides a lightweight, self-hosted alternative to Convex for SSR cloud mode.
|
|
4
4
|
|
|
5
|
+
Requires **Node.js 24.22.1 or newer on the 24.x line**, matching OR3 Chat. Development and CI pin **24.22.1** in `.node-version`.
|
|
6
|
+
|
|
5
7
|
## What it provides
|
|
6
8
|
|
|
7
9
|
- **AuthWorkspaceStore** (`sqlite`) — user identity mapping, workspace CRUD, role resolution
|
|
@@ -20,16 +22,22 @@ advertise `retainedStorageMetadata: 'v1'` on native SQLite and D1. Missing sizes
|
|
|
20
22
|
delete-before-put rows remain unknown; these reads never replay sync history.
|
|
21
23
|
|
|
22
24
|
Upload quota admission groups unexpired pending authorizations by hash and
|
|
23
|
-
reserves atomically on native SQLite and D1. Migration
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
25
|
+
reserves atomically on native SQLite and D1. Migration 027 replaces the
|
|
26
|
+
metadata-derived charges from migration 026 with persisted, verified consumed
|
|
27
|
+
upload receipts. Client-authored file sizes cannot create retained charges.
|
|
28
|
+
Trash, logical deletion and receipt replay expiry do not release verified
|
|
29
|
+
charges; restoring the same hash does not double-charge it. A larger upload
|
|
30
|
+
reserves the difference above its verified retained size.
|
|
31
|
+
|
|
32
|
+
Pre-receipt files and raw incomplete uploads are outside this verified ledger;
|
|
33
|
+
metadata alone cannot prove their physical size. Existing consumed receipts are
|
|
34
|
+
retained and reconciled during upgrade. Physical filesystem/S3 GC remains
|
|
35
|
+
disabled. The provider advertises `atomicUploadQuota: 'retained-v1'`; configure
|
|
36
|
+
`OR3_STORAGE_WORKSPACE_QUOTA_BYTES` to enforce a quota (the default is unlimited).
|
|
37
|
+
|
|
38
|
+
Migrations 027–028 are forward-only. Keep a pre-upgrade database backup;
|
|
39
|
+
rolling back the provider requires restoring that snapshot because the old
|
|
40
|
+
adapter expects the previous device-cursor unique key.
|
|
33
41
|
|
|
34
42
|
`watchVersion` shares one indexed workspace version-counter read every two
|
|
35
43
|
seconds per workspace per process across notification listeners. The host can
|
|
@@ -211,13 +219,23 @@ All tables use snake_case aligned with the sync wire format.
|
|
|
211
219
|
|
|
212
220
|
### Sync semantics
|
|
213
221
|
|
|
214
|
-
- **Push**: validates ops (including a 256 KB serialized payload ceiling per operation) → checks `op_id` idempotency → allocates contiguous `server_version`
|
|
222
|
+
- **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.
|
|
215
223
|
- **Pull**: returns ordered changes for `server_version > cursor` with limit/pagination, optional table filtering, `oldestRetainedVersion`, and `requiresSnapshot` when the cursor is behind retained history
|
|
216
224
|
- **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.
|
|
217
|
-
- **Cursor**: forward-only per
|
|
225
|
+
- **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.
|
|
218
226
|
- **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
|
|
219
227
|
- **Notifications**: push forces `payload.user_id` to the session user; foreign notification writes are rejected; pull/snapshot omit other users' rows
|
|
220
228
|
|
|
229
|
+
Snapshot continuations are bound to the capturing user and workspace, including
|
|
230
|
+
backup snapshots. Each user retains at most four copies per workspace across
|
|
231
|
+
both modes. A newer capture can supersede the oldest chain; expired,
|
|
232
|
+
superseded, and pre-upgrade tokens return HTTP 410 and require a fresh capture.
|
|
233
|
+
Copies expire after one hour. Native runtimes prune expired copies at startup
|
|
234
|
+
and every minute; D1 prunes on requests at most once per minute. Deleting a
|
|
235
|
+
snapshot also removes its copied items.
|
|
236
|
+
If a D1 snapshot is evicted while a page is being read, that request also returns
|
|
237
|
+
HTTP 410 instead of acknowledging a truncated final page.
|
|
238
|
+
|
|
221
239
|
LWW conflict resolution: incoming wins when `clock` is higher, then when clocks are equal and `hlc` is lexicographically greater, then when `op_id` is greater. Tombstones use the same `(clock, hlc, op_id)` tuple. LWW losers return `applied: false` with the current winner as either `{ kind: 'put', payload, revision }` or `{ kind: 'delete', revision, serverDeletedAt? }`. Idempotent `op_id` retries return `replayed: true` and, if superseded, the current winner. A replay does not allocate another server version.
|
|
222
240
|
|
|
223
241
|
Local, Bun, and Turso runtimes use `BEGIN IMMEDIATE` transactions. D1 uses its
|
package/dist/module.json
CHANGED
|
@@ -57,6 +57,8 @@ const REQUIRED_SCHEMA_TABLES = [
|
|
|
57
57
|
import * as m024 from "./migrations/024_signup_invites.js";
|
|
58
58
|
import * as m025 from "./migrations/025_background_shutdown_accounting.js";
|
|
59
59
|
import * as m026 from "./migrations/026_retained_storage_usage.js";
|
|
60
|
+
import * as m027 from "./migrations/027_verified_storage_usage.js";
|
|
61
|
+
import * as m028 from "./migrations/028_user_scoped_device_cursors.js";
|
|
60
62
|
const migrations = {
|
|
61
63
|
"001_init": m001,
|
|
62
64
|
"002_sync_tables": m002,
|
|
@@ -83,7 +85,9 @@ const migrations = {
|
|
|
83
85
|
"023_legacy_chat_seek_index": m023,
|
|
84
86
|
"024_signup_invites": m024,
|
|
85
87
|
"025_background_shutdown_accounting": m025,
|
|
86
|
-
"026_retained_storage_usage": m026
|
|
88
|
+
"026_retained_storage_usage": m026,
|
|
89
|
+
"027_verified_storage_usage": m027,
|
|
90
|
+
"028_user_scoped_device_cursors": m028
|
|
87
91
|
};
|
|
88
92
|
class StaticMigrationProvider {
|
|
89
93
|
async getMigrations() {
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
import { type Kysely } from 'kysely';
|
|
2
|
+
/** Client-synced metadata is descriptive, never evidence of retained bytes.
|
|
3
|
+
* Consumed upload receipts are persisted even after their replay TTL expires.
|
|
4
|
+
*/
|
|
5
|
+
export declare function up(db: Kysely<unknown>): Promise<void>;
|
|
6
|
+
export declare function down(_db: Kysely<unknown>): Promise<void>;
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
import { sql } from "kysely";
|
|
2
|
+
export async function up(db) {
|
|
3
|
+
await sql`DROP TRIGGER IF EXISTS file_meta_retained_insert`.execute(db);
|
|
4
|
+
await sql`DROP TRIGGER IF EXISTS file_meta_retained_update`.execute(db);
|
|
5
|
+
await sql`DELETE FROM retained_storage`.execute(db);
|
|
6
|
+
await sql`DELETE FROM storage_usage`.execute(db);
|
|
7
|
+
await sql`INSERT INTO retained_storage(workspace_id, hash, size_bytes)
|
|
8
|
+
SELECT workspace_id, hash, MAX(size_bytes) FROM upload_intents
|
|
9
|
+
WHERE status = 'consumed' GROUP BY workspace_id, hash`.execute(db);
|
|
10
|
+
}
|
|
11
|
+
export async function down(_db) {
|
|
12
|
+
}
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
import type { Kysely } from 'kysely';
|
|
2
|
+
/** The same browser device ID can be used by several accounts. Unowned legacy
|
|
3
|
+
* cursors remain untouched and expire under the existing retention policy.
|
|
4
|
+
*/
|
|
5
|
+
export declare function up(db: Kysely<unknown>): Promise<void>;
|
|
6
|
+
export declare function down(_db: Kysely<unknown>): Promise<void>;
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
export async function up(db) {
|
|
2
|
+
await db.schema.dropIndex("idx_device_cursors_ws_device").ifExists().execute();
|
|
3
|
+
await db.schema.createIndex("idx_device_cursors_ws_user_device").ifNotExists().on("device_cursors").columns(["workspace_id", "owner_user_id", "device_id"]).unique().execute();
|
|
4
|
+
}
|
|
5
|
+
export async function down(_db) {
|
|
6
|
+
}
|
|
@@ -9,7 +9,7 @@ import { registerPluginConnectionStore } from "~~/server/utils/plugins/connectio
|
|
|
9
9
|
import { registerRateLimitProvider } from "~~/server/utils/rate-limit/registry";
|
|
10
10
|
import { registerBackgroundJobProvider } from "~~/server/utils/background-jobs/registry";
|
|
11
11
|
import { createSqliteAuthWorkspaceStore } from "../auth/sqlite-auth-workspace-store.js";
|
|
12
|
-
import { createSqliteSyncGatewayAdapter } from "../sync/sqlite-sync-gateway-adapter.js";
|
|
12
|
+
import { createSqliteSyncGatewayAdapter, pruneExpiredSyncSnapshots } from "../sync/sqlite-sync-gateway-adapter.js";
|
|
13
13
|
import { createSqliteWebhookStore } from "../webhooks/sqlite-webhook-store.js";
|
|
14
14
|
import {
|
|
15
15
|
createSqliteAdminUserStore,
|
|
@@ -103,12 +103,27 @@ export default defineNitroPlugin(async (nitroApp) => {
|
|
|
103
103
|
});
|
|
104
104
|
registerProviderAdminAdapter(sqliteSyncAdminAdapter);
|
|
105
105
|
if (driver === "d1") {
|
|
106
|
+
let nextSnapshotCleanup = 0;
|
|
106
107
|
nitroApp.hooks.hook("request", async () => {
|
|
107
108
|
d1RuntimeInitialization ??= initializeSqliteDb().then(runMigrations);
|
|
108
109
|
await d1RuntimeInitialization;
|
|
110
|
+
if (Date.now() >= nextSnapshotCleanup) {
|
|
111
|
+
nextSnapshotCleanup = Date.now() + 6e4;
|
|
112
|
+
await pruneExpiredSyncSnapshots();
|
|
113
|
+
}
|
|
109
114
|
});
|
|
110
115
|
return;
|
|
111
116
|
}
|
|
112
117
|
const db = await initializeSqliteDb();
|
|
113
118
|
await runMigrations(db);
|
|
119
|
+
await pruneExpiredSyncSnapshots();
|
|
120
|
+
const snapshotCleanup = setInterval(() => {
|
|
121
|
+
void pruneExpiredSyncSnapshots().catch((error) => {
|
|
122
|
+
console.warn("[or3-sqlite] Snapshot cleanup failed", error);
|
|
123
|
+
});
|
|
124
|
+
}, 6e4);
|
|
125
|
+
snapshotCleanup.unref?.();
|
|
126
|
+
nitroApp.hooks.hook("close", () => {
|
|
127
|
+
clearInterval(snapshotCleanup);
|
|
128
|
+
});
|
|
114
129
|
});
|
|
@@ -10,6 +10,7 @@ import type { CanonicalStorageQueryRequest, CanonicalStorageQueryResponse, SyncG
|
|
|
10
10
|
import type { AdmitChatGenerationResult, CanonicalGenerationSnapshot, CanonicalHistoryActor, ChatGenerationAdmissionEnvelope, FinalizeChatGenerationResult } from '~~/shared/chat/background-history';
|
|
11
11
|
import type { PullRequest, PullResponse, PushBatch, PushResult, SnapshotRequest, SnapshotResponse } from '~~/shared/sync/types';
|
|
12
12
|
import { type CanonicalChatQuery, type CanonicalChatReadResult } from '~~/shared/chat/history-reader';
|
|
13
|
+
export declare function pruneExpiredSyncSnapshots(): Promise<void>;
|
|
13
14
|
export declare class SqliteSyncGatewayAdapter implements SyncGatewayAdapter {
|
|
14
15
|
id: string;
|
|
15
16
|
private versionWatchers;
|
|
@@ -29,6 +29,12 @@ const MAX_SNAPSHOT_PAGE_SIZE = 1e3;
|
|
|
29
29
|
const DEFAULT_CANONICAL_STORAGE_PAGE_SIZE = 100;
|
|
30
30
|
const MAX_CANONICAL_STORAGE_PAGE_SIZE = 500;
|
|
31
31
|
const SNAPSHOT_TTL_SECONDS = 60 * 60;
|
|
32
|
+
const MAX_RETAINED_SNAPSHOTS_PER_USER = 4;
|
|
33
|
+
const PRUNE_USER_SNAPSHOTS_SQL = `DELETE FROM sync_snapshots WHERE id IN (
|
|
34
|
+
SELECT id FROM sync_snapshots
|
|
35
|
+
WHERE workspace_id = ? AND (id LIKE ? OR id LIKE ?)
|
|
36
|
+
ORDER BY created_at DESC, rowid DESC LIMIT -1 OFFSET ?
|
|
37
|
+
)`;
|
|
32
38
|
const SESSION_CONTEXT_KEY_PREFIX = "__or3_session_context_";
|
|
33
39
|
const MIN_SYNC_RETENTION_SECONDS = 60 * 60;
|
|
34
40
|
const MAX_SYNC_RETENTION_SECONDS = 365 * 24 * 60 * 60;
|
|
@@ -60,6 +66,25 @@ function uid() {
|
|
|
60
66
|
function nowEpoch() {
|
|
61
67
|
return Math.floor(Date.now() / 1e3);
|
|
62
68
|
}
|
|
69
|
+
function snapshotOwnerPrefix(userId) {
|
|
70
|
+
return `user:${createHash("sha256").update(userId ?? "").digest("hex")}:`;
|
|
71
|
+
}
|
|
72
|
+
function assertSnapshotOwner(id, userId) {
|
|
73
|
+
const scopedId = id.replace(/^backup:/, "");
|
|
74
|
+
if (!scopedId.startsWith("user:")) {
|
|
75
|
+
throw createError({ statusCode: 410, statusMessage: "Snapshot expired or unavailable" });
|
|
76
|
+
}
|
|
77
|
+
if (!scopedId.startsWith(snapshotOwnerPrefix(userId))) {
|
|
78
|
+
throw createError({ statusCode: 403, statusMessage: "Forbidden" });
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
export async function pruneExpiredSyncSnapshots() {
|
|
82
|
+
if (isD1Driver()) {
|
|
83
|
+
await d1Run("DELETE FROM sync_snapshots WHERE expires_at <= ?", nowEpoch());
|
|
84
|
+
} else {
|
|
85
|
+
getRawDb().prepare("DELETE FROM sync_snapshots WHERE expires_at <= ?").run(nowEpoch());
|
|
86
|
+
}
|
|
87
|
+
}
|
|
63
88
|
function stableJson(value) {
|
|
64
89
|
if (value === void 0) return "undefined";
|
|
65
90
|
if (value === null || typeof value !== "object") return JSON.stringify(value);
|
|
@@ -425,7 +450,7 @@ function currentWinnerNative(raw, workspaceId, tableName, pk) {
|
|
|
425
450
|
).get(workspaceId, tableName, pk);
|
|
426
451
|
return materializedWinner(row, tombstone);
|
|
427
452
|
}
|
|
428
|
-
async function currentWinnerD1(workspaceId, tableName, pk) {
|
|
453
|
+
async function currentWinnerD1(workspaceId, tableName, pk, userId) {
|
|
429
454
|
const materializedTable = SYNCED_TABLE_MAP[tableName];
|
|
430
455
|
if (!materializedTable) return void 0;
|
|
431
456
|
const [row] = await d1All(
|
|
@@ -434,6 +459,9 @@ async function currentWinnerD1(workspaceId, tableName, pk) {
|
|
|
434
459
|
pk,
|
|
435
460
|
workspaceId
|
|
436
461
|
);
|
|
462
|
+
if (tableName === "notifications" && row && notificationPayloadUserId(JSON.parse(row.data_json)) !== userId) {
|
|
463
|
+
return void 0;
|
|
464
|
+
}
|
|
437
465
|
const [tombstone] = await d1All(
|
|
438
466
|
`SELECT clock, hlc, op_id, deleted_at FROM tombstones
|
|
439
467
|
WHERE workspace_id = ? AND table_name = ? AND pk = ?`,
|
|
@@ -1246,14 +1274,14 @@ export class SqliteSyncGatewayAdapter {
|
|
|
1246
1274
|
}
|
|
1247
1275
|
const failedBeforeAlloc = /* @__PURE__ */ new Set();
|
|
1248
1276
|
for (const op of uniqueOps) {
|
|
1249
|
-
if (op.tableName !== "notifications"
|
|
1277
|
+
if (op.tableName !== "notifications") continue;
|
|
1250
1278
|
const materializedTable = SYNCED_TABLE_MAP[op.tableName];
|
|
1251
1279
|
if (!materializedTable) continue;
|
|
1252
1280
|
const owned = raw.prepare(
|
|
1253
1281
|
`SELECT data_json FROM ${materializedTable} WHERE id = ? AND workspace_id = ?`
|
|
1254
1282
|
).get(op.pk, workspaceId);
|
|
1255
1283
|
const owner = owned ? notificationPayloadUserId(JSON.parse(owned.data_json)) : void 0;
|
|
1256
|
-
if (
|
|
1284
|
+
if (owned && owner !== userId || !owned && op.operation === "delete") {
|
|
1257
1285
|
failedBeforeAlloc.add(op.stamp.opId);
|
|
1258
1286
|
uniqueResults.push({
|
|
1259
1287
|
opId: op.stamp.opId,
|
|
@@ -1639,6 +1667,7 @@ export class SqliteSyncGatewayAdapter {
|
|
|
1639
1667
|
statusMessage: "Forbidden"
|
|
1640
1668
|
});
|
|
1641
1669
|
}
|
|
1670
|
+
assertSnapshotOwner(existing.id, snapshotUserId);
|
|
1642
1671
|
if (input.tables && existing.tables_json !== JSON.stringify(normalizeSnapshotTables(input.tables))) {
|
|
1643
1672
|
throw createError({
|
|
1644
1673
|
statusCode: 400,
|
|
@@ -1652,10 +1681,17 @@ export class SqliteSyncGatewayAdapter {
|
|
|
1652
1681
|
after = token.after;
|
|
1653
1682
|
} else {
|
|
1654
1683
|
const tables = normalizeSnapshotTables(input.tables);
|
|
1655
|
-
const
|
|
1684
|
+
const ownerPrefix = snapshotOwnerPrefix(snapshotUserId);
|
|
1685
|
+
const snapshotId = `${retainedFiles ? "backup:" : ""}${ownerPrefix}${uid()}`;
|
|
1656
1686
|
const expiresAt = now + SNAPSHOT_TTL_SECONDS;
|
|
1657
1687
|
const capture = raw.transaction(() => {
|
|
1658
1688
|
raw.prepare("DELETE FROM sync_snapshots WHERE expires_at <= ?").run(now);
|
|
1689
|
+
raw.prepare(PRUNE_USER_SNAPSHOTS_SQL).run(
|
|
1690
|
+
workspaceId,
|
|
1691
|
+
`${ownerPrefix}%`,
|
|
1692
|
+
`backup:${ownerPrefix}%`,
|
|
1693
|
+
MAX_RETAINED_SNAPSHOTS_PER_USER - 1
|
|
1694
|
+
);
|
|
1659
1695
|
const counter = raw.prepare(
|
|
1660
1696
|
"SELECT value FROM server_version_counter WHERE workspace_id = ?"
|
|
1661
1697
|
).get(workspaceId);
|
|
@@ -1876,11 +1912,8 @@ export class SqliteSyncGatewayAdapter {
|
|
|
1876
1912
|
}
|
|
1877
1913
|
const existing = raw.prepare(
|
|
1878
1914
|
`SELECT owner_user_id, last_seen_version
|
|
1879
|
-
FROM device_cursors WHERE workspace_id = ? AND device_id = ?`
|
|
1880
|
-
).get(input.scope.workspaceId, deviceId);
|
|
1881
|
-
if (existing?.owner_user_id && existing.owner_user_id !== ownerUserId) {
|
|
1882
|
-
throw createError({ statusCode: 403, statusMessage: "Device cursor belongs to another user" });
|
|
1883
|
-
}
|
|
1915
|
+
FROM device_cursors WHERE workspace_id = ? AND owner_user_id = ? AND device_id = ?`
|
|
1916
|
+
).get(input.scope.workspaceId, ownerUserId, deviceId);
|
|
1884
1917
|
if (existing && input.version < existing.last_seen_version) {
|
|
1885
1918
|
throw createError({ statusCode: 409, statusMessage: "Device cursor cannot regress" });
|
|
1886
1919
|
}
|
|
@@ -1888,8 +1921,7 @@ export class SqliteSyncGatewayAdapter {
|
|
|
1888
1921
|
`INSERT INTO device_cursors (
|
|
1889
1922
|
id, workspace_id, device_id, owner_user_id, last_seen_version, updated_at
|
|
1890
1923
|
) VALUES (?, ?, ?, ?, ?, ?)
|
|
1891
|
-
ON CONFLICT(workspace_id, device_id) DO UPDATE SET
|
|
1892
|
-
owner_user_id = COALESCE(device_cursors.owner_user_id, excluded.owner_user_id),
|
|
1924
|
+
ON CONFLICT(workspace_id, owner_user_id, device_id) DO UPDATE SET
|
|
1893
1925
|
last_seen_version = excluded.last_seen_version,
|
|
1894
1926
|
updated_at = excluded.updated_at`
|
|
1895
1927
|
).run(uid(), input.scope.workspaceId, deviceId, ownerUserId, input.version, now);
|
|
@@ -2090,6 +2122,7 @@ export class SqliteSyncGatewayAdapter {
|
|
|
2090
2122
|
if (existing.workspace_id !== workspaceId) {
|
|
2091
2123
|
throw createError({ statusCode: 403, statusMessage: "Forbidden" });
|
|
2092
2124
|
}
|
|
2125
|
+
assertSnapshotOwner(existing.id, snapshotUserId);
|
|
2093
2126
|
if (input.tables && existing.tables_json !== JSON.stringify(normalizeSnapshotTables(input.tables))) {
|
|
2094
2127
|
throw createError({
|
|
2095
2128
|
statusCode: 400,
|
|
@@ -2103,7 +2136,8 @@ export class SqliteSyncGatewayAdapter {
|
|
|
2103
2136
|
after = token.after;
|
|
2104
2137
|
} else {
|
|
2105
2138
|
const tables = normalizeSnapshotTables(input.tables);
|
|
2106
|
-
const
|
|
2139
|
+
const ownerPrefix = snapshotOwnerPrefix(snapshotUserId);
|
|
2140
|
+
const snapshotId = `${retainedFiles ? "backup:" : ""}${ownerPrefix}${uid()}`;
|
|
2107
2141
|
const expiresAt = now + SNAPSHOT_TTL_SECONDS;
|
|
2108
2142
|
const tablesJson = JSON.stringify(tables);
|
|
2109
2143
|
const statements = [
|
|
@@ -2111,6 +2145,10 @@ export class SqliteSyncGatewayAdapter {
|
|
|
2111
2145
|
sql: "DELETE FROM sync_snapshots WHERE expires_at <= ?",
|
|
2112
2146
|
parameters: [now]
|
|
2113
2147
|
},
|
|
2148
|
+
{
|
|
2149
|
+
sql: PRUNE_USER_SNAPSHOTS_SQL,
|
|
2150
|
+
parameters: [workspaceId, `${ownerPrefix}%`, `backup:${ownerPrefix}%`, MAX_RETAINED_SNAPSHOTS_PER_USER - 1]
|
|
2151
|
+
},
|
|
2114
2152
|
{
|
|
2115
2153
|
sql: `INSERT INTO sync_snapshots (
|
|
2116
2154
|
id, workspace_id, high_watermark, tables_json, created_at, expires_at
|
|
@@ -2239,7 +2277,7 @@ export class SqliteSyncGatewayAdapter {
|
|
|
2239
2277
|
FROM sync_snapshots WHERE id = ?`,
|
|
2240
2278
|
snapshotId
|
|
2241
2279
|
);
|
|
2242
|
-
if (!created) throw
|
|
2280
|
+
if (!created) throw createError({ statusCode: 410, statusMessage: "Snapshot expired or unavailable" });
|
|
2243
2281
|
header = created;
|
|
2244
2282
|
}
|
|
2245
2283
|
const rows = after ? await d1All(
|
|
@@ -2270,6 +2308,13 @@ export class SqliteSyncGatewayAdapter {
|
|
|
2270
2308
|
header.id,
|
|
2271
2309
|
pageSize + 1
|
|
2272
2310
|
);
|
|
2311
|
+
const [retained] = await d1All(
|
|
2312
|
+
"SELECT expires_at FROM sync_snapshots WHERE id = ?",
|
|
2313
|
+
header.id
|
|
2314
|
+
);
|
|
2315
|
+
if (!retained || retained.expires_at <= nowEpoch()) {
|
|
2316
|
+
throw createError({ statusCode: 410, statusMessage: "Snapshot expired or unavailable" });
|
|
2317
|
+
}
|
|
2273
2318
|
const hasMore = rows.length > pageSize;
|
|
2274
2319
|
const pageRows = hasMore ? rows.slice(0, pageSize) : rows;
|
|
2275
2320
|
const items = pageRows.map((row) => {
|
|
@@ -2318,13 +2363,11 @@ export class SqliteSyncGatewayAdapter {
|
|
|
2318
2363
|
}
|
|
2319
2364
|
const [existing] = await d1All(
|
|
2320
2365
|
`SELECT owner_user_id, last_seen_version
|
|
2321
|
-
FROM device_cursors WHERE workspace_id = ? AND device_id = ?`,
|
|
2366
|
+
FROM device_cursors WHERE workspace_id = ? AND owner_user_id = ? AND device_id = ?`,
|
|
2322
2367
|
workspaceId,
|
|
2368
|
+
ownerUserId,
|
|
2323
2369
|
deviceId
|
|
2324
2370
|
);
|
|
2325
|
-
if (existing?.owner_user_id && existing.owner_user_id !== ownerUserId) {
|
|
2326
|
-
throw createError({ statusCode: 403, statusMessage: "Device cursor belongs to another user" });
|
|
2327
|
-
}
|
|
2328
2371
|
if (existing && version < existing.last_seen_version) {
|
|
2329
2372
|
throw createError({ statusCode: 409, statusMessage: "Device cursor cannot regress" });
|
|
2330
2373
|
}
|
|
@@ -2332,19 +2375,16 @@ export class SqliteSyncGatewayAdapter {
|
|
|
2332
2375
|
`INSERT INTO device_cursors (
|
|
2333
2376
|
id, workspace_id, device_id, owner_user_id, last_seen_version, updated_at
|
|
2334
2377
|
) VALUES (?, ?, ?, ?, ?, ?)
|
|
2335
|
-
ON CONFLICT(workspace_id, device_id) DO UPDATE SET
|
|
2336
|
-
owner_user_id = COALESCE(device_cursors.owner_user_id, excluded.owner_user_id),
|
|
2378
|
+
ON CONFLICT(workspace_id, owner_user_id, device_id) DO UPDATE SET
|
|
2337
2379
|
last_seen_version = excluded.last_seen_version,
|
|
2338
2380
|
updated_at = excluded.updated_at
|
|
2339
|
-
WHERE
|
|
2340
|
-
AND excluded.last_seen_version >= device_cursors.last_seen_version`,
|
|
2381
|
+
WHERE excluded.last_seen_version >= device_cursors.last_seen_version`,
|
|
2341
2382
|
uid(),
|
|
2342
2383
|
workspaceId,
|
|
2343
2384
|
deviceId,
|
|
2344
2385
|
ownerUserId,
|
|
2345
2386
|
version,
|
|
2346
|
-
now
|
|
2347
|
-
ownerUserId
|
|
2387
|
+
now
|
|
2348
2388
|
);
|
|
2349
2389
|
if ((result.meta?.changes ?? 0) !== 1) {
|
|
2350
2390
|
throw createError({ statusCode: 409, statusMessage: "Device cursor changed concurrently" });
|
|
@@ -2389,8 +2429,8 @@ export class SqliteSyncGatewayAdapter {
|
|
|
2389
2429
|
}
|
|
2390
2430
|
}
|
|
2391
2431
|
for (const op of uniqueOps) {
|
|
2392
|
-
if (op.tableName !== "notifications"
|
|
2393
|
-
if (
|
|
2432
|
+
if (op.tableName !== "notifications") continue;
|
|
2433
|
+
if (rejected.has(op.stamp.opId)) continue;
|
|
2394
2434
|
const materializedTable = SYNCED_TABLE_MAP[op.tableName];
|
|
2395
2435
|
if (!materializedTable) continue;
|
|
2396
2436
|
const [owned] = await d1All(
|
|
@@ -2399,7 +2439,7 @@ export class SqliteSyncGatewayAdapter {
|
|
|
2399
2439
|
workspaceId
|
|
2400
2440
|
);
|
|
2401
2441
|
const owner = owned ? notificationPayloadUserId(JSON.parse(owned.data_json)) : void 0;
|
|
2402
|
-
if (
|
|
2442
|
+
if (owned && owner !== userId || !owned && op.operation === "delete") {
|
|
2403
2443
|
rejected.add(op.stamp.opId);
|
|
2404
2444
|
for (const index of indicesByOpId.get(op.stamp.opId) ?? []) {
|
|
2405
2445
|
resultSlots[index] = {
|
|
@@ -2414,10 +2454,6 @@ export class SqliteSyncGatewayAdapter {
|
|
|
2414
2454
|
const newOps = uniqueOps.filter(
|
|
2415
2455
|
(op) => !existingOps.has(op.stamp.opId) && !rejected.has(op.stamp.opId)
|
|
2416
2456
|
);
|
|
2417
|
-
const versionOffsets = /* @__PURE__ */ new Map();
|
|
2418
|
-
newOps.forEach((op, index) => {
|
|
2419
|
-
versionOffsets.set(op.stamp.opId, index + 1);
|
|
2420
|
-
});
|
|
2421
2457
|
const existingMaterializedKeys = /* @__PURE__ */ new Set();
|
|
2422
2458
|
const opsByTable = /* @__PURE__ */ new Map();
|
|
2423
2459
|
for (const op of newOps) {
|
|
@@ -2472,17 +2508,11 @@ export class SqliteSyncGatewayAdapter {
|
|
|
2472
2508
|
const now = nowEpoch();
|
|
2473
2509
|
const statements = [];
|
|
2474
2510
|
if (newOps.length > 0) {
|
|
2475
|
-
statements.push(
|
|
2476
|
-
|
|
2477
|
-
sql: `INSERT OR IGNORE INTO server_version_counter (workspace_id, value)
|
|
2511
|
+
statements.push({
|
|
2512
|
+
sql: `INSERT OR IGNORE INTO server_version_counter (workspace_id, value)
|
|
2478
2513
|
VALUES (?, 0)`,
|
|
2479
|
-
|
|
2480
|
-
|
|
2481
|
-
{
|
|
2482
|
-
sql: "UPDATE server_version_counter SET value = value + ? WHERE workspace_id = ?",
|
|
2483
|
-
parameters: [newOps.length, workspaceId]
|
|
2484
|
-
}
|
|
2485
|
-
);
|
|
2514
|
+
parameters: [workspaceId]
|
|
2515
|
+
});
|
|
2486
2516
|
}
|
|
2487
2517
|
const materializedStatementIndex = /* @__PURE__ */ new Map();
|
|
2488
2518
|
const materializedWasExisting = /* @__PURE__ */ new Map();
|
|
@@ -2490,8 +2520,6 @@ export class SqliteSyncGatewayAdapter {
|
|
|
2490
2520
|
for (const op of newOps) {
|
|
2491
2521
|
const materializedTable = SYNCED_TABLE_MAP[op.tableName];
|
|
2492
2522
|
if (!materializedTable) continue;
|
|
2493
|
-
const versionOffset = versionOffsets.get(op.stamp.opId);
|
|
2494
|
-
if (versionOffset === void 0) continue;
|
|
2495
2523
|
const payloadJson = op.payload == null ? null : JSON.stringify(op.payload);
|
|
2496
2524
|
const materializedKey = `${materializedTable}\0${op.pk}`;
|
|
2497
2525
|
materializedWasExisting.set(
|
|
@@ -2503,16 +2531,17 @@ export class SqliteSyncGatewayAdapter {
|
|
|
2503
2531
|
sql: `INSERT INTO change_log (
|
|
2504
2532
|
id, workspace_id, server_version, table_name, pk, op,
|
|
2505
2533
|
payload_json, clock, hlc, device_id, op_id, created_at
|
|
2506
|
-
)
|
|
2534
|
+
) SELECT
|
|
2507
2535
|
?, ?,
|
|
2508
|
-
(SELECT value
|
|
2536
|
+
(SELECT value + 1 FROM server_version_counter WHERE workspace_id = ?),
|
|
2509
2537
|
?, ?, ?, ?, ?, ?, ?, ?, ?
|
|
2510
|
-
|
|
2538
|
+
${op.tableName === "notifications" ? `WHERE NOT EXISTS (
|
|
2539
|
+
SELECT 1 FROM s_notifications WHERE id = ? AND workspace_id = ?
|
|
2540
|
+
AND json_extract(data_json, '$.user_id') IS NOT ?
|
|
2541
|
+
)` : ""}`,
|
|
2511
2542
|
parameters: [
|
|
2512
2543
|
uid(),
|
|
2513
2544
|
workspaceId,
|
|
2514
|
-
newOps.length,
|
|
2515
|
-
versionOffset,
|
|
2516
2545
|
workspaceId,
|
|
2517
2546
|
op.tableName,
|
|
2518
2547
|
op.pk,
|
|
@@ -2522,9 +2551,14 @@ export class SqliteSyncGatewayAdapter {
|
|
|
2522
2551
|
op.stamp.hlc,
|
|
2523
2552
|
op.stamp.deviceId,
|
|
2524
2553
|
op.stamp.opId,
|
|
2525
|
-
now
|
|
2554
|
+
now,
|
|
2555
|
+
...op.tableName === "notifications" ? [op.pk, workspaceId, userId] : []
|
|
2526
2556
|
]
|
|
2527
2557
|
});
|
|
2558
|
+
statements.push({
|
|
2559
|
+
sql: "UPDATE server_version_counter SET value = value + changes() WHERE workspace_id = ?",
|
|
2560
|
+
parameters: [workspaceId]
|
|
2561
|
+
});
|
|
2528
2562
|
if (skipMaterialize.has(op.stamp.opId)) continue;
|
|
2529
2563
|
materializedStatementIndex.set(op.stamp.opId, statements.length);
|
|
2530
2564
|
if (op.operation === "put") {
|
|
@@ -2541,7 +2575,8 @@ export class SqliteSyncGatewayAdapter {
|
|
|
2541
2575
|
op_id = excluded.op_id,
|
|
2542
2576
|
deleted = 0,
|
|
2543
2577
|
updated_at = excluded.updated_at
|
|
2544
|
-
WHERE ${lwwExcludedWins(`"${materializedTable}"`)}
|
|
2578
|
+
WHERE ${lwwExcludedWins(`"${materializedTable}"`)}
|
|
2579
|
+
${op.tableName === "notifications" ? `AND json_extract("${materializedTable}".data_json, '$.user_id') = json_extract(excluded.data_json, '$.user_id')` : ""}`,
|
|
2545
2580
|
parameters: [
|
|
2546
2581
|
op.pk,
|
|
2547
2582
|
workspaceId,
|
|
@@ -2585,7 +2620,7 @@ export class SqliteSyncGatewayAdapter {
|
|
|
2585
2620
|
hlc, op_id, server_version, created_at
|
|
2586
2621
|
) VALUES (
|
|
2587
2622
|
?, ?, ?, ?, ?, ?, ?, ?,
|
|
2588
|
-
(SELECT value
|
|
2623
|
+
(SELECT value FROM server_version_counter WHERE workspace_id = ?),
|
|
2589
2624
|
?
|
|
2590
2625
|
)
|
|
2591
2626
|
ON CONFLICT(workspace_id, table_name, pk) DO UPDATE SET
|
|
@@ -2604,8 +2639,6 @@ export class SqliteSyncGatewayAdapter {
|
|
|
2604
2639
|
op.stamp.clock,
|
|
2605
2640
|
op.stamp.hlc,
|
|
2606
2641
|
op.stamp.opId,
|
|
2607
|
-
newOps.length,
|
|
2608
|
-
versionOffset,
|
|
2609
2642
|
workspaceId,
|
|
2610
2643
|
now
|
|
2611
2644
|
]
|
|
@@ -2648,9 +2681,22 @@ export class SqliteSyncGatewayAdapter {
|
|
|
2648
2681
|
const emissions = [];
|
|
2649
2682
|
for (const op of uniqueOps) {
|
|
2650
2683
|
if (rejected.has(op.stamp.opId)) continue;
|
|
2684
|
+
if (op.tableName === "notifications") {
|
|
2685
|
+
const [owned] = await d1All(
|
|
2686
|
+
"SELECT data_json FROM s_notifications WHERE id = ? AND workspace_id = ?",
|
|
2687
|
+
op.pk,
|
|
2688
|
+
workspaceId
|
|
2689
|
+
);
|
|
2690
|
+
if (owned && notificationPayloadUserId(JSON.parse(owned.data_json)) !== userId) {
|
|
2691
|
+
for (const index of indicesByOpId.get(op.stamp.opId) ?? []) {
|
|
2692
|
+
resultSlots[index] = { opId: op.stamp.opId, success: false, error: "Forbidden: notification owner mismatch", errorCode: "UNAUTHORIZED" };
|
|
2693
|
+
}
|
|
2694
|
+
continue;
|
|
2695
|
+
}
|
|
2696
|
+
}
|
|
2651
2697
|
const existing = existingOps.get(op.stamp.opId);
|
|
2652
2698
|
if (existing) {
|
|
2653
|
-
const winner = await currentWinnerD1(workspaceId, op.tableName, op.pk);
|
|
2699
|
+
const winner = await currentWinnerD1(workspaceId, op.tableName, op.pk, userId);
|
|
2654
2700
|
const applied2 = winner?.revision.opId === op.stamp.opId;
|
|
2655
2701
|
const result2 = {
|
|
2656
2702
|
opId: op.stamp.opId,
|
|
@@ -2682,7 +2728,8 @@ export class SqliteSyncGatewayAdapter {
|
|
|
2682
2728
|
workspaceId
|
|
2683
2729
|
);
|
|
2684
2730
|
if (winner?.data_json) {
|
|
2685
|
-
|
|
2731
|
+
const payload = JSON.parse(winner.data_json);
|
|
2732
|
+
if (op.tableName !== "notifications" || notificationPayloadUserId(payload) === userId) winnerPayload = payload;
|
|
2686
2733
|
}
|
|
2687
2734
|
}
|
|
2688
2735
|
}
|
|
@@ -2693,7 +2740,7 @@ export class SqliteSyncGatewayAdapter {
|
|
|
2693
2740
|
applied,
|
|
2694
2741
|
...applied ? {} : { payload: winnerPayload },
|
|
2695
2742
|
...applied ? {} : {
|
|
2696
|
-
winner: await currentWinnerD1(workspaceId, op.tableName, op.pk)
|
|
2743
|
+
winner: await currentWinnerD1(workspaceId, op.tableName, op.pk, userId)
|
|
2697
2744
|
}
|
|
2698
2745
|
};
|
|
2699
2746
|
for (const index of indicesByOpId.get(op.stamp.opId) ?? []) {
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "or3-provider-sqlite",
|
|
3
|
-
"version": "0.0.
|
|
3
|
+
"version": "0.0.21",
|
|
4
4
|
"repository": {
|
|
5
5
|
"type": "git",
|
|
6
6
|
"url": "git+https://github.com/Saluana/or3-provider-sqlite.git"
|
|
@@ -9,7 +9,7 @@
|
|
|
9
9
|
"license": "MIT",
|
|
10
10
|
"type": "module",
|
|
11
11
|
"engines": {
|
|
12
|
-
"node": "
|
|
12
|
+
"node": "^24.22.1"
|
|
13
13
|
},
|
|
14
14
|
"packageManager": "bun@1.3.14",
|
|
15
15
|
"sideEffects": false,
|
|
@@ -67,6 +67,6 @@
|
|
|
67
67
|
"pathe": "^2.0.3",
|
|
68
68
|
"typescript": "^5.9.3",
|
|
69
69
|
"vitest": "^4.0.18",
|
|
70
|
-
"zod": "4.6.
|
|
70
|
+
"zod": "4.6.7"
|
|
71
71
|
}
|
|
72
72
|
}
|