or3-provider-sqlite 0.0.28 → 0.0.30
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 +11 -0
- package/dist/module.json +1 -1
- package/dist/runtime/server/db/migrate.js +3 -1
- package/dist/runtime/server/db/migrations/033_tool_result_operation_ids.d.ts +4 -0
- package/dist/runtime/server/db/migrations/033_tool_result_operation_ids.js +29 -0
- package/dist/runtime/server/sync/sqlite-sync-gateway-adapter.js +119 -172
- package/dist/runtime/server/utils/digest-uuid.d.ts +2 -0
- package/dist/runtime/server/utils/digest-uuid.js +7 -0
- package/package.json +1 -1
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.
|
|
@@ -434,6 +435,16 @@ Migration 030 adds generation records, current-hash heads, and canonical write b
|
|
|
434
435
|
|
|
435
436
|
Migrations 030–032 resume safely after interrupted startup and reject incompatible preexisting schema objects. Released migration 029 remains unchanged.
|
|
436
437
|
|
|
438
|
+
Tool-result retention writes deterministic UUID operation IDs so both incremental
|
|
439
|
+
pull and snapshot bootstrap remain valid. Migration 033 repairs legacy
|
|
440
|
+
`background-tool:<sha256>` IDs in the change log, canonical KV, tombstones and
|
|
441
|
+
captured snapshot pages, including embedded payload IDs. It preserves content,
|
|
442
|
+
clocks, server versions and cursors; replay allocates no duplicate versions.
|
|
443
|
+
With the updated host, every nonempty tool result uses immutable KV chunks and
|
|
444
|
+
bounded transcript references instead of consuming the assistant response budget.
|
|
445
|
+
Full results remain available after sync/reload and for model replay. The existing
|
|
446
|
+
256 KiB per-result limit remains in force. D1 background retention remains unsupported.
|
|
447
|
+
|
|
437
448
|
Migration 031 adds the upload ledger and restore tickets. Normal generation transfer routes remain unregistered. See [upload, restore, and recovery invariants](docs/storage-generation-uploads.md).
|
|
438
449
|
|
|
439
450
|
Background history admission and finalization failures expose structured codes for validation, authorization, conflicts, and supersession. Transient SQLite failures retain their original errors for retry.
|
package/dist/module.json
CHANGED
|
@@ -68,6 +68,7 @@ import * as m029 from "./migrations/029_delegation_wait.js";
|
|
|
68
68
|
import * as m030 from "./migrations/030_storage_generations.js";
|
|
69
69
|
import * as m031 from "./migrations/031_storage_generation_uploads.js";
|
|
70
70
|
import * as m032 from "./migrations/032_sync_observations.js";
|
|
71
|
+
import * as m033 from "./migrations/033_tool_result_operation_ids.js";
|
|
71
72
|
const migrations = {
|
|
72
73
|
"001_init": m001,
|
|
73
74
|
"002_sync_tables": m002,
|
|
@@ -100,7 +101,8 @@ const migrations = {
|
|
|
100
101
|
"029_delegation_wait": m029,
|
|
101
102
|
"030_storage_generations": m030,
|
|
102
103
|
"031_storage_generation_uploads": m031,
|
|
103
|
-
"032_sync_observations": m032
|
|
104
|
+
"032_sync_observations": m032,
|
|
105
|
+
"033_tool_result_operation_ids": m033
|
|
104
106
|
};
|
|
105
107
|
class StaticMigrationProvider {
|
|
106
108
|
async getMigrations() {
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
import { sql } from "kysely";
|
|
2
|
+
import { digestUuid } from "../../utils/digest-uuid.js";
|
|
3
|
+
export async function up(db) {
|
|
4
|
+
const tables = [
|
|
5
|
+
["change_log", "payload_json"],
|
|
6
|
+
["s_kv", "data_json"],
|
|
7
|
+
["sync_snapshot_items", "payload_json"],
|
|
8
|
+
["tombstones", null]
|
|
9
|
+
];
|
|
10
|
+
for (const [table, payload] of tables) {
|
|
11
|
+
let after = "";
|
|
12
|
+
for (; ; ) {
|
|
13
|
+
const { rows } = await sql`SELECT DISTINCT op_id FROM ${sql.table(table)}
|
|
14
|
+
WHERE op_id LIKE 'background-tool:%' AND op_id > ${after} ORDER BY op_id LIMIT 500`.execute(db);
|
|
15
|
+
if (!rows.length) break;
|
|
16
|
+
for (const { op_id: oldId } of rows) {
|
|
17
|
+
const match = /^background-tool:([a-f0-9]{64})$/.exec(oldId);
|
|
18
|
+
if (!match) continue;
|
|
19
|
+
const opId = digestUuid(match[1]);
|
|
20
|
+
const assignment = payload ? sql`, ${sql.ref(payload)} = CASE WHEN json_extract(${sql.ref(payload)}, '$.op_id') = ${oldId}
|
|
21
|
+
THEN json_set(${sql.ref(payload)}, '$.op_id', ${opId}) ELSE ${sql.ref(payload)} END` : sql``;
|
|
22
|
+
await sql`UPDATE ${sql.table(table)} SET op_id = ${opId}${assignment} WHERE op_id = ${oldId}`.execute(db);
|
|
23
|
+
}
|
|
24
|
+
after = rows.at(-1).op_id;
|
|
25
|
+
}
|
|
26
|
+
}
|
|
27
|
+
}
|
|
28
|
+
export async function down(_db) {
|
|
29
|
+
}
|
|
@@ -2,6 +2,8 @@ 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 { digestUuid } from "../utils/digest-uuid.js";
|
|
6
|
+
import { sql } from "kysely";
|
|
5
7
|
import { canRunSyncHistoryGc } from "./history-gc-policy.js";
|
|
6
8
|
import { createError } from "h3";
|
|
7
9
|
import {
|
|
@@ -43,6 +45,8 @@ const SESSION_CONTEXT_KEY_PREFIX = "__or3_session_context_";
|
|
|
43
45
|
const MIN_SYNC_RETENTION_SECONDS = 60 * 60;
|
|
44
46
|
const MAX_SYNC_RETENTION_SECONDS = 365 * 24 * 60 * 60;
|
|
45
47
|
const MAX_SYNC_PAYLOAD_BYTES = 256 * 1024;
|
|
48
|
+
const MAX_SYNC_PAGE_BYTES = 1024 * 1024;
|
|
49
|
+
const jsonBytes = (value) => new TextEncoder().encode(JSON.stringify(value)).byteLength;
|
|
46
50
|
const PENDING_UPLOAD_RESERVATIONS_SQL = `
|
|
47
51
|
SELECT MIN(intent.id) AS id, intent.hash,
|
|
48
52
|
MAX(intent.size_bytes) AS reserved_bytes, MAX(intent.expires_at) AS expires_at
|
|
@@ -64,6 +68,72 @@ const QUOTA_RESERVATIONS_SQL = `SELECT intent.hash, MAX(intent.size_bytes) AS re
|
|
|
64
68
|
ON retained.workspace_id = intent.workspace_id AND retained.hash = intent.hash
|
|
65
69
|
WHERE intent.workspace_id = ? AND intent.status = 'active' AND intent.expires_at > ?
|
|
66
70
|
GROUP BY intent.hash`;
|
|
71
|
+
function boundedPayloadRowCount(sizes, limit) {
|
|
72
|
+
let count = 0;
|
|
73
|
+
let bytes = 0;
|
|
74
|
+
for (const row of sizes.slice(0, limit)) {
|
|
75
|
+
const size = Math.max(0, Number(row.payload_bytes) || 0);
|
|
76
|
+
if (count && bytes + size > MAX_SYNC_PAGE_BYTES) break;
|
|
77
|
+
count++;
|
|
78
|
+
bytes += size;
|
|
79
|
+
}
|
|
80
|
+
return count;
|
|
81
|
+
}
|
|
82
|
+
function snapshotPageSelection(headerId, after) {
|
|
83
|
+
const clause = `FROM sync_snapshot_items WHERE snapshot_id = ?${after ? `
|
|
84
|
+
AND (table_name > ? OR (table_name = ? AND pk > ?)
|
|
85
|
+
OR (table_name = ? AND pk = ? AND kind > ?))` : ""}
|
|
86
|
+
ORDER BY table_name ASC, pk ASC, kind ASC LIMIT ?`;
|
|
87
|
+
const parameters = after ? [headerId, after.tableName, after.tableName, after.pk, after.tableName, after.pk, after.kind] : [headerId];
|
|
88
|
+
return { clause, parameters };
|
|
89
|
+
}
|
|
90
|
+
function buildSnapshotPage(header, rows, pageSize, availableRows) {
|
|
91
|
+
const items = [];
|
|
92
|
+
let itemBytes = 0;
|
|
93
|
+
let scanned = 0;
|
|
94
|
+
let token = null;
|
|
95
|
+
for (const row of rows.slice(0, pageSize)) {
|
|
96
|
+
const revision = { clock: row.clock, hlc: row.hlc, opId: row.op_id };
|
|
97
|
+
const item = row.kind === "row" ? {
|
|
98
|
+
kind: "row",
|
|
99
|
+
tableName: row.table_name,
|
|
100
|
+
pk: row.pk,
|
|
101
|
+
payload: JSON.parse(row.payload_json ?? "null"),
|
|
102
|
+
revision
|
|
103
|
+
} : {
|
|
104
|
+
kind: "tombstone",
|
|
105
|
+
tableName: row.table_name,
|
|
106
|
+
pk: row.pk,
|
|
107
|
+
revision,
|
|
108
|
+
serverDeletedAt: row.server_deleted_at ?? 0
|
|
109
|
+
};
|
|
110
|
+
const next = encodeSnapshotPageToken({
|
|
111
|
+
version: 1,
|
|
112
|
+
snapshotId: header.id,
|
|
113
|
+
after: { tableName: row.table_name, pk: row.pk, kind: row.kind }
|
|
114
|
+
});
|
|
115
|
+
const bytes = jsonBytes(item) + (items.length ? 1 : 0);
|
|
116
|
+
const envelope = jsonBytes({
|
|
117
|
+
workspaceId: header.workspace_id,
|
|
118
|
+
snapshotId: header.id,
|
|
119
|
+
highWatermark: header.high_watermark,
|
|
120
|
+
items: [],
|
|
121
|
+
nextPageToken: next
|
|
122
|
+
});
|
|
123
|
+
if (items.length && envelope + itemBytes + bytes > MAX_SYNC_PAGE_BYTES) break;
|
|
124
|
+
items.push(item);
|
|
125
|
+
itemBytes += bytes;
|
|
126
|
+
scanned++;
|
|
127
|
+
token = next;
|
|
128
|
+
}
|
|
129
|
+
return {
|
|
130
|
+
workspaceId: header.workspace_id,
|
|
131
|
+
snapshotId: header.id,
|
|
132
|
+
highWatermark: header.high_watermark,
|
|
133
|
+
items,
|
|
134
|
+
nextPageToken: availableRows > scanned ? token : null
|
|
135
|
+
};
|
|
136
|
+
}
|
|
67
137
|
function uid() {
|
|
68
138
|
return globalThis.crypto.randomUUID();
|
|
69
139
|
}
|
|
@@ -97,11 +167,7 @@ export async function pruneExpiredSyncSnapshots() {
|
|
|
97
167
|
}
|
|
98
168
|
}
|
|
99
169
|
function backgroundHistoryOpId(admission, stage) {
|
|
100
|
-
|
|
101
|
-
hex[12] = "4";
|
|
102
|
-
hex[16] = (Number.parseInt(hex[16], 16) & 3 | 8).toString(16);
|
|
103
|
-
const value = hex.join("");
|
|
104
|
-
return `${value.slice(0, 8)}-${value.slice(8, 12)}-${value.slice(12, 16)}-${value.slice(16, 20)}-${value.slice(20)}`;
|
|
170
|
+
return digestUuid(createHash("sha256").update(`${admission.workspaceId}\0${admission.generationId}\0${stage}`).digest("hex"));
|
|
105
171
|
}
|
|
106
172
|
function fingerprintPayload(tableName, operation, payload) {
|
|
107
173
|
if (tableName !== "notifications" || operation !== "delete") return payload;
|
|
@@ -1007,7 +1073,7 @@ export class SqliteSyncGatewayAdapter {
|
|
|
1007
1073
|
ON CONFLICT(workspace_id) DO UPDATE SET value = excluded.value`).run(admission.workspaceId, baseVersion + newRows.length);
|
|
1008
1074
|
const now = nowEpoch();
|
|
1009
1075
|
newRows.forEach((row, index) => {
|
|
1010
|
-
const opId =
|
|
1076
|
+
const opId = digestUuid(createHash("sha256").update(JSON.stringify([admission.workspaceId, admission.generationId, row.id])).digest("hex"));
|
|
1011
1077
|
const hlc = `${Date.now().toString(36).padStart(9, "0")}:000:background`;
|
|
1012
1078
|
const sanitized = sanitizePayloadForSync("kv", row, "put");
|
|
1013
1079
|
if (!sanitized) throw Object.assign(new Error("Invalid tool result payload"), { code: "VALIDATION_ERROR" });
|
|
@@ -1125,7 +1191,7 @@ export class SqliteSyncGatewayAdapter {
|
|
|
1125
1191
|
const now = nowEpoch();
|
|
1126
1192
|
const hash = normalizeStorageHash(input.hash);
|
|
1127
1193
|
const raw = isD1Driver() ? null : getRawDb();
|
|
1128
|
-
const
|
|
1194
|
+
const sql2 = `UPDATE upload_intents
|
|
1129
1195
|
SET status = 'consumed', storage_id = ?, consumed_at = ?
|
|
1130
1196
|
WHERE id = ? AND workspace_id = ? AND status = 'active' AND expires_at > ?
|
|
1131
1197
|
AND hash = ? AND mime_type = ? AND size_bytes = ?`;
|
|
@@ -1139,7 +1205,7 @@ export class SqliteSyncGatewayAdapter {
|
|
|
1139
1205
|
input.mimeType,
|
|
1140
1206
|
input.sizeBytes
|
|
1141
1207
|
];
|
|
1142
|
-
const changes = raw ? raw.prepare(
|
|
1208
|
+
const changes = raw ? raw.prepare(sql2).run(...parameters).changes : (await d1Run(sql2, ...parameters)).meta?.changes;
|
|
1143
1209
|
if (changes === 1) return;
|
|
1144
1210
|
const receiptSql = `SELECT 1 FROM upload_intents
|
|
1145
1211
|
WHERE id = ? AND workspace_id = ? AND status = 'consumed' AND expires_at > ?
|
|
@@ -1190,7 +1256,7 @@ export class SqliteSyncGatewayAdapter {
|
|
|
1190
1256
|
}
|
|
1191
1257
|
const after = decodeCanonicalStorageCursor(input.cursor, input.kind, hash);
|
|
1192
1258
|
const raw = isD1Driver() ? null : getRawDb();
|
|
1193
|
-
const all = async (
|
|
1259
|
+
const all = async (sql2, ...parameters) => raw ? raw.prepare(sql2).all(...parameters) : d1All(sql2, ...parameters);
|
|
1194
1260
|
if (input.kind === "active_reservations") {
|
|
1195
1261
|
if (after.length > 1) {
|
|
1196
1262
|
throw createError({ statusCode: 400, statusMessage: "Invalid canonical storage cursor" });
|
|
@@ -1769,30 +1835,13 @@ export class SqliteSyncGatewayAdapter {
|
|
|
1769
1835
|
const { scope, cursor, limit, tables } = input;
|
|
1770
1836
|
await assertWorkspaceScopeAuthorized(event, scope.workspaceId);
|
|
1771
1837
|
const fetchLimit = resolvePullLimit(limit);
|
|
1772
|
-
let query = db.selectFrom("change_log").
|
|
1838
|
+
let query = db.selectFrom("change_log").where("workspace_id", "=", scope.workspaceId).where("server_version", ">", cursor).orderBy("server_version", "asc");
|
|
1773
1839
|
if (tables?.length) {
|
|
1774
1840
|
query = query.where("table_name", "in", tables);
|
|
1775
1841
|
}
|
|
1776
|
-
const
|
|
1777
|
-
const
|
|
1778
|
-
const
|
|
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;
|
|
1842
|
+
const sizes = await query.select(sql`coalesce(length(cast(payload_json as blob)), 0)`.as("payload_bytes")).limit(fetchLimit + 1).execute();
|
|
1843
|
+
const selected = boundedPayloadRowCount(sizes, fetchLimit);
|
|
1844
|
+
const rows = selected ? await query.selectAll().limit(selected).execute() : [];
|
|
1796
1845
|
const minLog = await db.selectFrom("change_log").select("server_version").where("workspace_id", "=", scope.workspaceId).orderBy("server_version", "asc").limit(1).executeTakeFirst();
|
|
1797
1846
|
const counter = await db.selectFrom("server_version_counter").select("value").where("workspace_id", "=", scope.workspaceId).executeTakeFirst();
|
|
1798
1847
|
const retention = computePullRetention({
|
|
@@ -1800,12 +1849,30 @@ export class SqliteSyncGatewayAdapter {
|
|
|
1800
1849
|
oldestLogVersion: minLog?.server_version ?? null,
|
|
1801
1850
|
highWatermark: counter?.value ?? 0
|
|
1802
1851
|
});
|
|
1803
|
-
|
|
1804
|
-
|
|
1805
|
-
|
|
1806
|
-
|
|
1807
|
-
|
|
1808
|
-
|
|
1852
|
+
const changes = [];
|
|
1853
|
+
let itemBytes = 0;
|
|
1854
|
+
let scanned = 0;
|
|
1855
|
+
let nextCursor = cursor;
|
|
1856
|
+
for (const row of rows.slice(0, fetchLimit)) {
|
|
1857
|
+
const change = {
|
|
1858
|
+
serverVersion: row.server_version,
|
|
1859
|
+
tableName: row.table_name,
|
|
1860
|
+
pk: row.pk,
|
|
1861
|
+
op: row.op,
|
|
1862
|
+
payload: row.payload_json ? JSON.parse(row.payload_json) : void 0,
|
|
1863
|
+
stamp: { clock: row.clock, hlc: row.hlc, deviceId: row.device_id, opId: row.op_id }
|
|
1864
|
+
};
|
|
1865
|
+
if (isNotificationVisibleToUser(change, resolveSessionUserId(event))) {
|
|
1866
|
+
const bytes = jsonBytes(change) + (changes.length ? 1 : 0);
|
|
1867
|
+
const envelope = jsonBytes({ changes: [], nextCursor: row.server_version, hasMore: false, ...retention });
|
|
1868
|
+
if (changes.length && envelope + itemBytes + bytes > MAX_SYNC_PAGE_BYTES) break;
|
|
1869
|
+
changes.push(change);
|
|
1870
|
+
itemBytes += bytes;
|
|
1871
|
+
}
|
|
1872
|
+
scanned++;
|
|
1873
|
+
nextCursor = row.server_version;
|
|
1874
|
+
}
|
|
1875
|
+
return { changes, nextCursor, hasMore: sizes.length > scanned, ...retention };
|
|
1809
1876
|
}
|
|
1810
1877
|
async snapshot(event, input) {
|
|
1811
1878
|
return this.captureSnapshot(event, input, false);
|
|
@@ -1997,79 +2064,11 @@ export class SqliteSyncGatewayAdapter {
|
|
|
1997
2064
|
});
|
|
1998
2065
|
header = capture.immediate();
|
|
1999
2066
|
}
|
|
2000
|
-
const
|
|
2001
|
-
|
|
2002
|
-
|
|
2003
|
-
|
|
2004
|
-
|
|
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
|
-
};
|
|
2067
|
+
const selection = snapshotPageSelection(header.id, after);
|
|
2068
|
+
const sizes = raw.prepare(`SELECT coalesce(length(cast(payload_json as blob)), 0) AS payload_bytes ${selection.clause}`).all(...selection.parameters, pageSize + 1);
|
|
2069
|
+
const selected = boundedPayloadRowCount(sizes, pageSize);
|
|
2070
|
+
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) : [];
|
|
2071
|
+
return buildSnapshotPage(header, rows, pageSize, sizes.length);
|
|
2073
2072
|
}
|
|
2074
2073
|
async updateCursor(event, input) {
|
|
2075
2074
|
await assertWorkspaceScopeAuthorized(event, input.scope.workspaceId);
|
|
@@ -2467,34 +2466,18 @@ export class SqliteSyncGatewayAdapter {
|
|
|
2467
2466
|
if (!created) throw createError({ statusCode: 410, statusMessage: "Snapshot expired or unavailable" });
|
|
2468
2467
|
header = created;
|
|
2469
2468
|
}
|
|
2470
|
-
const
|
|
2471
|
-
|
|
2472
|
-
|
|
2473
|
-
|
|
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,
|
|
2469
|
+
const selection = snapshotPageSelection(header.id, after);
|
|
2470
|
+
const sizes = await d1All(
|
|
2471
|
+
`SELECT coalesce(length(cast(payload_json as blob)), 0) AS payload_bytes ${selection.clause}`,
|
|
2472
|
+
...selection.parameters,
|
|
2496
2473
|
pageSize + 1
|
|
2497
2474
|
);
|
|
2475
|
+
const selected = boundedPayloadRowCount(sizes, pageSize);
|
|
2476
|
+
const rows = selected ? await d1All(
|
|
2477
|
+
`SELECT table_name, pk, kind, payload_json, clock, hlc, op_id, server_deleted_at ${selection.clause}`,
|
|
2478
|
+
...selection.parameters,
|
|
2479
|
+
selected
|
|
2480
|
+
) : [];
|
|
2498
2481
|
const [retained] = await d1All(
|
|
2499
2482
|
"SELECT expires_at FROM sync_snapshots WHERE id = ?",
|
|
2500
2483
|
header.id
|
|
@@ -2502,43 +2485,7 @@ export class SqliteSyncGatewayAdapter {
|
|
|
2502
2485
|
if (!retained || retained.expires_at <= nowEpoch()) {
|
|
2503
2486
|
throw createError({ statusCode: 410, statusMessage: "Snapshot expired or unavailable" });
|
|
2504
2487
|
}
|
|
2505
|
-
|
|
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
|
-
};
|
|
2488
|
+
return buildSnapshotPage(header, rows, pageSize, sizes.length);
|
|
2542
2489
|
}
|
|
2543
2490
|
async updateCursorInD1(workspaceId, deviceId, version, ownerUserId, now) {
|
|
2544
2491
|
const [counter] = await d1All(
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
export function digestUuid(digest) {
|
|
2
|
+
const hex = digest.slice(0, 32).split("");
|
|
3
|
+
hex[12] = "4";
|
|
4
|
+
hex[16] = (Number.parseInt(hex[16], 16) & 3 | 8).toString(16);
|
|
5
|
+
const value = hex.join("");
|
|
6
|
+
return `${value.slice(0, 8)}-${value.slice(8, 12)}-${value.slice(12, 16)}-${value.slice(16, 20)}-${value.slice(20)}`;
|
|
7
|
+
}
|