or3-provider-sqlite 0.0.27 → 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 +35 -3
- package/dist/module.json +1 -1
- package/dist/runtime/server/admin/adapters/sync-sqlite.js +6 -0
- package/dist/runtime/server/admin/stores/sqlite-store.js +106 -0
- package/dist/runtime/server/db/migrate.js +5 -2
- package/dist/runtime/server/db/migrations/032_sync_observations.d.ts +3 -0
- package/dist/runtime/server/db/migrations/032_sync_observations.js +16 -0
- package/dist/runtime/server/storage/sqlite-generation-coordinator.d.ts +23 -0
- package/dist/runtime/server/storage/sqlite-generation-coordinator.js +60 -17
- package/dist/runtime/server/sync/sqlite-sync-gateway-adapter.d.ts +6 -7
- package/dist/runtime/server/sync/sqlite-sync-gateway-adapter.js +128 -166
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -18,6 +18,13 @@ cached sessions. A granted account can manage settings only for a workspace it
|
|
|
18
18
|
owns; instance administration still requires the super-admin login. D1 does
|
|
19
19
|
not provide the deployment-admin grant store.
|
|
20
20
|
|
|
21
|
+
The access store also implements OR3's optional, read-only customer support reads:
|
|
22
|
+
`listCustomers` (keyset-paged by creation time, at most 50 rows, literal
|
|
23
|
+
substring search), `getCustomersByIds` and `getCustomerWorkspaces` (owned
|
|
24
|
+
workspaces including deleted ones, plus memberships). They never provision rows.
|
|
25
|
+
"Last contact" is the latest `device_cursors.updated_at` for the user. Hosts that
|
|
26
|
+
predate these reads ignore them.
|
|
27
|
+
|
|
21
28
|
SSR-authenticated deployments also activate SQLite when it is selected only by
|
|
22
29
|
`OR3_LIMITS_ENABLED=true` and `OR3_LIMITS_STORAGE_PROVIDER=sqlite`, independently
|
|
23
30
|
of the account workspace backend.
|
|
@@ -229,6 +236,7 @@ All tables use snake_case aligned with the sync wire format.
|
|
|
229
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.
|
|
230
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
|
|
231
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.
|
|
232
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.
|
|
233
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
|
|
234
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.
|
|
@@ -423,11 +431,11 @@ Admin workspace summaries, workspace details, and deployment-admin lists expose
|
|
|
423
431
|
|
|
424
432
|
## Dormant immutable-generation foundation (unreleased)
|
|
425
433
|
|
|
426
|
-
Migration 030 adds
|
|
434
|
+
Migration 030 adds generation records, current-hash heads, and canonical write barriers after the released migrations. Normal transfer routes do not create these records. Cleanup is disabled by default; the Linux adapter can expose the coordinator through the explicit opt-in described below. See [protocol invariants and activation blockers](docs/storage-generations.md).
|
|
427
435
|
|
|
428
|
-
Migrations 030–
|
|
436
|
+
Migrations 030–032 resume safely after interrupted startup and reject incompatible preexisting schema objects. Released migration 029 remains unchanged.
|
|
429
437
|
|
|
430
|
-
Migration 031 adds the
|
|
438
|
+
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).
|
|
431
439
|
|
|
432
440
|
Background history admission and finalization failures expose structured codes for validation, authorization, conflicts, and supersession. Transient SQLite failures retain their original errors for retry.
|
|
433
441
|
|
|
@@ -437,3 +445,27 @@ releases enrolled-object charges after confirmed removal acknowledgement. Restor
|
|
|
437
445
|
reuse their retained charge; replacement waits for confirmed deletion. Legacy
|
|
438
446
|
retained objects cannot be implicitly adopted. This adds no schema migration,
|
|
439
447
|
registration or production cleanup activation.
|
|
448
|
+
|
|
449
|
+
### Admin diagnostics and managed-generation inspection
|
|
450
|
+
|
|
451
|
+
The optional customer-read store includes bounded completed-sync observations
|
|
452
|
+
(migration `032_sync_observations`): last successful gateway operation and latest
|
|
453
|
+
classified failure per user/workspace. These observations contain no sync payload,
|
|
454
|
+
are independent of cursor contact, and cannot invalidate an accepted sync write.
|
|
455
|
+
The SQLite admin adapter's explicit health probe verifies a canonical database
|
|
456
|
+
read; configuration/enablement alone is not a health result.
|
|
457
|
+
|
|
458
|
+
The dormant generation coordinator also exposes `inspectCandidates` to trusted
|
|
459
|
+
server callers. It pages at most 100 exact enrolled generations per workspace,
|
|
460
|
+
uses the same bounded eligibility proof as claims, and changes no generation or
|
|
461
|
+
accounting state. Estimates describe logical managed bytes, not reclaimed disk
|
|
462
|
+
blocks. Mutable legacy storage is excluded. This read does not register deletion,
|
|
463
|
+
HTTP upload, restore, cleanup automation or a production capability. Installed
|
|
464
|
+
Linux filesystem and independent S3 backup/crash lifecycle gates remain required
|
|
465
|
+
before activation.
|
|
466
|
+
|
|
467
|
+
### Opt-in enrolled-generation cleanup
|
|
468
|
+
|
|
469
|
+
On Linux, the SQLite/filesystem pairing exposes managed-generation cleanup only when `OR3_STORAGE_FS_CLEANUP_NAMESPACE_ID` names the existing filesystem namespace UUID and SQLite runs with `OR3_SQLITE_PRAGMA_SYNCHRONOUS=FULL` (or `EXTRA`). The namespace must already have been provisioned by the generation protocol; this setting neither provisions it nor enrolls legacy files. It does not change normal upload/download routing. Leave the namespace setting unset to keep cleanup unavailable. D1 and other unsupported drivers remain unavailable.
|
|
470
|
+
|
|
471
|
+
Manual admin cleanup rechecks canonical eligibility and uses the installed filesystem remover. Optional `OR3_STORAGE_RETENTION_WORKSPACES` selects explicit workspace IDs for the same audited primitive, with seven-day retention and at most 25 examined generations per hourly turn. Changing these environment settings requires a managed restart. Defaults remain disabled. Use the repaired managed backup/restore path for enrolled data; raw file copying is not a supported restore.
|
package/dist/module.json
CHANGED
|
@@ -9,6 +9,8 @@ import {
|
|
|
9
9
|
SYNC_MAINTENANCE_RETENTION_SECONDS
|
|
10
10
|
} from "../../sync/maintenance-state.js";
|
|
11
11
|
import { createSqliteSyncGatewayAdapter } from "../../sync/sqlite-sync-gateway-adapter.js";
|
|
12
|
+
import { sql } from "kysely";
|
|
13
|
+
import { getSqliteDb } from "../../db/kysely.js";
|
|
12
14
|
import { getSqliteDriver } from "../../db/kysely.js";
|
|
13
15
|
const SQLITE_PROVIDER_ID = "sqlite";
|
|
14
16
|
let gatewayInstance;
|
|
@@ -19,6 +21,10 @@ function getGateway() {
|
|
|
19
21
|
export const sqliteSyncAdminAdapter = {
|
|
20
22
|
id: SQLITE_PROVIDER_ID,
|
|
21
23
|
kind: "sync",
|
|
24
|
+
async check() {
|
|
25
|
+
await sql`SELECT 1 FROM users LIMIT 1`.execute(getSqliteDb());
|
|
26
|
+
return { result: "passed", kind: "database_read", scope: "canonical SQLite database", code: "read_ok" };
|
|
27
|
+
},
|
|
22
28
|
async getStatus(_event, _ctx) {
|
|
23
29
|
const driver = getSqliteDriver();
|
|
24
30
|
const isLocalDriver = driver === "better-sqlite3" || driver === "bun";
|
|
@@ -1,4 +1,6 @@
|
|
|
1
|
+
import { sql } from "kysely";
|
|
1
2
|
import { getSqliteDb } from "../../db/kysely.js";
|
|
3
|
+
import { SqliteExternalStorageGenerationCoordinator } from "../../storage/sqlite-generation-coordinator.js";
|
|
2
4
|
function nowEpoch() {
|
|
3
5
|
return Math.floor(Date.now() / 1e3);
|
|
4
6
|
}
|
|
@@ -8,10 +10,46 @@ function normalizeEmail(value) {
|
|
|
8
10
|
function isEmail(value) {
|
|
9
11
|
return value.includes("@");
|
|
10
12
|
}
|
|
13
|
+
const CUSTOMER_PAGE_MAX = 50;
|
|
14
|
+
function escapeLike(value) {
|
|
15
|
+
return value.replace(/[\\%_]/g, (character) => `\\${character}`);
|
|
16
|
+
}
|
|
17
|
+
function encodeCursor(createdAt, id) {
|
|
18
|
+
return Buffer.from(JSON.stringify([createdAt, id])).toString("base64url");
|
|
19
|
+
}
|
|
20
|
+
function decodeCursor(cursor) {
|
|
21
|
+
try {
|
|
22
|
+
const value = JSON.parse(Buffer.from(cursor, "base64url").toString("utf8"));
|
|
23
|
+
return Array.isArray(value) && value.length === 2 && Number.isSafeInteger(value[0]) && typeof value[1] === "string" ? [value[0], value[1]] : null;
|
|
24
|
+
} catch {
|
|
25
|
+
return null;
|
|
26
|
+
}
|
|
27
|
+
}
|
|
11
28
|
class SqliteWorkspaceAccessStore {
|
|
29
|
+
async getStorageGenerationCandidates(input) {
|
|
30
|
+
return new SqliteExternalStorageGenerationCoordinator({ storageProviderId: input.storageProviderId }).inspectCandidates(input);
|
|
31
|
+
}
|
|
12
32
|
get db() {
|
|
13
33
|
return getSqliteDb();
|
|
14
34
|
}
|
|
35
|
+
async recordSyncObservation(input) {
|
|
36
|
+
if (!Number.isSafeInteger(input.observedAt) || input.observedAt < 0) throw new Error("Invalid observation time");
|
|
37
|
+
const success = input.outcome === "success";
|
|
38
|
+
const code = ["provider_failed", "request_rejected", "operation_rejected", "rate_limited", "access_denied"].includes(input.code ?? "") ? input.code : "provider_failed";
|
|
39
|
+
await sql`INSERT INTO sync_observations (user_id, workspace_id, last_success_at, last_success_operation, last_failure_at, last_failure_code)
|
|
40
|
+
VALUES (${input.userId}, ${input.workspaceId}, ${success ? input.observedAt : null}, ${success ? input.operation : null}, ${success ? null : input.observedAt}, ${success ? null : code})
|
|
41
|
+
ON CONFLICT (user_id, workspace_id) DO UPDATE SET
|
|
42
|
+
last_success_at = CASE WHEN excluded.last_success_at >= COALESCE(last_success_at, 0) THEN excluded.last_success_at ELSE last_success_at END,
|
|
43
|
+
last_success_operation = CASE WHEN excluded.last_success_at >= COALESCE(last_success_at, 0) THEN excluded.last_success_operation ELSE last_success_operation END,
|
|
44
|
+
last_failure_at = CASE WHEN excluded.last_failure_at >= COALESCE(last_failure_at, 0) THEN excluded.last_failure_at ELSE last_failure_at END,
|
|
45
|
+
last_failure_code = CASE WHEN excluded.last_failure_at >= COALESCE(last_failure_at, 0) THEN excluded.last_failure_code ELSE last_failure_code END`.execute(this.db);
|
|
46
|
+
}
|
|
47
|
+
async getCustomerSyncObservations(input) {
|
|
48
|
+
const result = await sql`
|
|
49
|
+
SELECT workspace_id, last_success_at, last_success_operation, last_failure_at, last_failure_code
|
|
50
|
+
FROM sync_observations WHERE user_id = ${input.userId} ORDER BY workspace_id LIMIT 500`.execute(this.db);
|
|
51
|
+
return result.rows.map((row) => ({ workspaceId: row.workspace_id, lastSuccessAt: row.last_success_at, lastSuccessOperation: row.last_success_operation, lastFailureAt: row.last_failure_at, lastFailureCode: row.last_failure_code }));
|
|
52
|
+
}
|
|
15
53
|
async listMembers(input) {
|
|
16
54
|
const rows = await this.db.selectFrom("workspace_members").innerJoin("users", "users.id", "workspace_members.user_id").select([
|
|
17
55
|
"workspace_members.user_id as user_id",
|
|
@@ -282,6 +320,74 @@ class SqliteWorkspaceAccessStore {
|
|
|
282
320
|
deleted_at: null
|
|
283
321
|
}).where("id", "=", input.workspaceId).execute();
|
|
284
322
|
}
|
|
323
|
+
/** Bounded, read-only canonical directory. Keyset-paginated by creation time; never provisions. */
|
|
324
|
+
async listCustomers(input) {
|
|
325
|
+
const limit = Math.max(1, Math.min(input.limit, CUSTOMER_PAGE_MAX));
|
|
326
|
+
const query = input.query?.trim();
|
|
327
|
+
const cursor = input.cursor ? decodeCursor(input.cursor) : null;
|
|
328
|
+
if (input.cursor && !cursor) throw new Error("Invalid customer cursor");
|
|
329
|
+
let rows = this.db.selectFrom("users").select(["id", "email", "display_name", "created_at"]);
|
|
330
|
+
if (query) {
|
|
331
|
+
const pattern = `%${escapeLike(query)}%`;
|
|
332
|
+
rows = rows.where(sql`(email LIKE ${pattern} ESCAPE '\\' OR display_name LIKE ${pattern} ESCAPE '\\' OR id LIKE ${pattern} ESCAPE '\\')`);
|
|
333
|
+
}
|
|
334
|
+
if (cursor) rows = rows.where(sql`(created_at < ${cursor[0]} OR (created_at = ${cursor[0]} AND id < ${cursor[1]}))`);
|
|
335
|
+
const page = await rows.orderBy("created_at", "desc").orderBy("id", "desc").limit(limit + 1).execute();
|
|
336
|
+
const items = page.slice(0, limit);
|
|
337
|
+
const last = items.at(-1);
|
|
338
|
+
return {
|
|
339
|
+
items: await this.withLastContact(items),
|
|
340
|
+
nextCursor: page.length > limit && last ? encodeCursor(last.created_at, last.id) : null
|
|
341
|
+
};
|
|
342
|
+
}
|
|
343
|
+
/** Batch lookup by internal IDs. Unknown IDs are omitted, never invented. */
|
|
344
|
+
async getCustomersByIds(input) {
|
|
345
|
+
const ids = [...new Set(input.userIds)].slice(0, CUSTOMER_PAGE_MAX);
|
|
346
|
+
if (!ids.length) return [];
|
|
347
|
+
const rows = await this.db.selectFrom("users").select(["id", "email", "display_name", "created_at"]).where("id", "in", ids).execute();
|
|
348
|
+
return this.withLastContact(rows);
|
|
349
|
+
}
|
|
350
|
+
/** Owned workspaces (including retained deleted ones) and memberships for one canonical user. */
|
|
351
|
+
async getCustomerWorkspaces(input) {
|
|
352
|
+
const rows = await this.db.selectFrom("workspaces").leftJoin("workspace_members as membership", (join) => join.onRef("membership.workspace_id", "=", "workspaces.id").on("membership.user_id", "=", input.userId)).select([
|
|
353
|
+
"workspaces.id as id",
|
|
354
|
+
"workspaces.name as name",
|
|
355
|
+
"workspaces.owner_user_id as owner_user_id",
|
|
356
|
+
"workspaces.created_at as created_at",
|
|
357
|
+
"workspaces.deleted as deleted",
|
|
358
|
+
"workspaces.deleted_at as deleted_at",
|
|
359
|
+
"membership.role as role",
|
|
360
|
+
(eb) => eb.selectFrom("workspace_members").select((inner) => inner.fn.countAll().as("n")).whereRef("workspace_members.workspace_id", "=", "workspaces.id").as("member_count"),
|
|
361
|
+
(eb) => eb.selectFrom("device_cursors").select((inner) => inner.fn.max("device_cursors.updated_at").as("t")).whereRef("device_cursors.workspace_id", "=", "workspaces.id").where("device_cursors.owner_user_id", "=", input.userId).as("last_contact")
|
|
362
|
+
]).where((eb) => eb.or([
|
|
363
|
+
eb("workspaces.owner_user_id", "=", input.userId),
|
|
364
|
+
eb("membership.user_id", "=", input.userId)
|
|
365
|
+
])).orderBy("workspaces.created_at", "asc").limit(500).execute();
|
|
366
|
+
return rows.map((row) => ({
|
|
367
|
+
id: row.id,
|
|
368
|
+
name: row.name,
|
|
369
|
+
role: row.owner_user_id === input.userId ? "owner" : row.role ?? "viewer",
|
|
370
|
+
ownerUserId: row.owner_user_id,
|
|
371
|
+
createdAt: row.created_at * 1e3,
|
|
372
|
+
deleted: row.deleted === 1,
|
|
373
|
+
deletedAt: row.deleted_at ?? void 0,
|
|
374
|
+
memberCount: Number(row.member_count ?? 0),
|
|
375
|
+
lastContactAt: row.last_contact == null ? null : Number(row.last_contact) * 1e3
|
|
376
|
+
}));
|
|
377
|
+
}
|
|
378
|
+
/** Last sync cursor write by this user (server contact, not proof of a completed sync). */
|
|
379
|
+
async withLastContact(rows) {
|
|
380
|
+
if (!rows.length) return [];
|
|
381
|
+
const contacts = await this.db.selectFrom("device_cursors").select(["owner_user_id", (eb) => eb.fn.max("updated_at").as("t")]).where("owner_user_id", "in", rows.map((row) => row.id)).groupBy("owner_user_id").execute();
|
|
382
|
+
const byUser = new Map(contacts.map((row) => [row.owner_user_id, Number(row.t) * 1e3]));
|
|
383
|
+
return rows.map((row) => ({
|
|
384
|
+
userId: row.id,
|
|
385
|
+
email: row.email ?? void 0,
|
|
386
|
+
displayName: row.display_name ?? void 0,
|
|
387
|
+
createdAt: row.created_at * 1e3,
|
|
388
|
+
lastContactAt: byUser.get(row.id) ?? null
|
|
389
|
+
}));
|
|
390
|
+
}
|
|
285
391
|
async searchUsers(input) {
|
|
286
392
|
const query = input.query.trim();
|
|
287
393
|
const limit = Math.max(1, Math.min(input.limit ?? 20, 100));
|
|
@@ -56,7 +56,8 @@ const REQUIRED_SCHEMA_TABLES = [
|
|
|
56
56
|
"background_generation_receipts",
|
|
57
57
|
"storage_object_generations",
|
|
58
58
|
"storage_object_heads",
|
|
59
|
-
"storage_generation_uploads"
|
|
59
|
+
"storage_generation_uploads",
|
|
60
|
+
"sync_observations"
|
|
60
61
|
];
|
|
61
62
|
import * as m024 from "./migrations/024_signup_invites.js";
|
|
62
63
|
import * as m025 from "./migrations/025_background_shutdown_accounting.js";
|
|
@@ -66,6 +67,7 @@ import * as m028 from "./migrations/028_user_scoped_device_cursors.js";
|
|
|
66
67
|
import * as m029 from "./migrations/029_delegation_wait.js";
|
|
67
68
|
import * as m030 from "./migrations/030_storage_generations.js";
|
|
68
69
|
import * as m031 from "./migrations/031_storage_generation_uploads.js";
|
|
70
|
+
import * as m032 from "./migrations/032_sync_observations.js";
|
|
69
71
|
const migrations = {
|
|
70
72
|
"001_init": m001,
|
|
71
73
|
"002_sync_tables": m002,
|
|
@@ -97,7 +99,8 @@ const migrations = {
|
|
|
97
99
|
"028_user_scoped_device_cursors": m028,
|
|
98
100
|
"029_delegation_wait": m029,
|
|
99
101
|
"030_storage_generations": m030,
|
|
100
|
-
"031_storage_generation_uploads": m031
|
|
102
|
+
"031_storage_generation_uploads": m031,
|
|
103
|
+
"032_sync_observations": m032
|
|
101
104
|
};
|
|
102
105
|
class StaticMigrationProvider {
|
|
103
106
|
async getMigrations() {
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
import { sql } from "kysely";
|
|
2
|
+
import { ensureMigrationSchema } from "../migration-schema.js";
|
|
3
|
+
export async function up(db) {
|
|
4
|
+
await ensureMigrationSchema(db, `CREATE TABLE sync_observations (
|
|
5
|
+
user_id TEXT NOT NULL REFERENCES users(id) ON DELETE CASCADE,
|
|
6
|
+
workspace_id TEXT NOT NULL REFERENCES workspaces(id) ON DELETE CASCADE,
|
|
7
|
+
last_success_at INTEGER, last_success_operation TEXT,
|
|
8
|
+
last_failure_at INTEGER, last_failure_code TEXT,
|
|
9
|
+
PRIMARY KEY (user_id, workspace_id)
|
|
10
|
+
)`);
|
|
11
|
+
await ensureMigrationSchema(db, "CREATE INDEX idx_users_admin_created_id ON users (created_at DESC, id DESC)");
|
|
12
|
+
}
|
|
13
|
+
export async function down(db) {
|
|
14
|
+
await sql`DROP INDEX idx_users_admin_created_id`.execute(db);
|
|
15
|
+
await sql`DROP TABLE sync_observations`.execute(db);
|
|
16
|
+
}
|
|
@@ -48,6 +48,29 @@ export declare class SqliteExternalStorageGenerationCoordinator implements Exter
|
|
|
48
48
|
generation: ExternalStorageGenerationRecord;
|
|
49
49
|
}>;
|
|
50
50
|
getGeneration(input: ExternalStorageGenerationKey): Promise<ExternalStorageGenerationRecord | null>;
|
|
51
|
+
private eligibility;
|
|
52
|
+
/** Read-only bounded advisory proof. A result is never deletion authority;
|
|
53
|
+
* claimGeneration repeats every proof in its own durable transaction. */
|
|
54
|
+
inspectCandidates(input: {
|
|
55
|
+
workspaceId: string;
|
|
56
|
+
retentionSeconds: number;
|
|
57
|
+
limit?: number;
|
|
58
|
+
cursor?: string;
|
|
59
|
+
}): Promise<{
|
|
60
|
+
items: {
|
|
61
|
+
generation: ExternalStorageGenerationRecord;
|
|
62
|
+
status: "deleted" | "blocked" | "claimed" | "eligible";
|
|
63
|
+
reason: "missing" | "not_current" | "in_use" | "unknown_references" | "active_upload" | "claim_conflict" | "retention" | "proof_incomplete" | null;
|
|
64
|
+
}[];
|
|
65
|
+
complete: boolean;
|
|
66
|
+
nextCursor: string | null;
|
|
67
|
+
observedAt: number;
|
|
68
|
+
workspaceId: string;
|
|
69
|
+
retentionSeconds: number;
|
|
70
|
+
estimatedLogicalBytes: number | null;
|
|
71
|
+
scope: "managed_generations_only";
|
|
72
|
+
legacyIncluded: false;
|
|
73
|
+
}>;
|
|
51
74
|
claimGeneration(input: ExternalStorageGenerationKey & {
|
|
52
75
|
claimId: string;
|
|
53
76
|
retentionSeconds: number;
|
|
@@ -173,6 +173,64 @@ export class SqliteExternalStorageGenerationCoordinator {
|
|
|
173
173
|
return row ? generationRecord(row) : null;
|
|
174
174
|
});
|
|
175
175
|
}
|
|
176
|
+
eligibility(row, retentionSeconds) {
|
|
177
|
+
const key = generationRecord(row);
|
|
178
|
+
if (this.head(key)?.generation_id !== key.generationId) return { reason: "not_current", lastActivity: row.last_activity_at };
|
|
179
|
+
const proof = this.metadataProof(key, false, row.storage_id) ?? this.referenceProof(key, false);
|
|
180
|
+
if (proof) return { reason: proof, lastActivity: row.last_activity_at };
|
|
181
|
+
const now = this.now();
|
|
182
|
+
const intents = this.raw.prepare(`SELECT ${validGenerationHashSql("hash")} AS valid_hash,
|
|
183
|
+
${generationHashSql("hash")} AS hash, expires_at FROM upload_intents
|
|
184
|
+
WHERE workspace_id = ? AND status = 'active' LIMIT ?`).all(key.workspaceId, GENERATION_PROOF_ROWS + 1);
|
|
185
|
+
if (intents.length > GENERATION_PROOF_ROWS) return { reason: "proof_incomplete", lastActivity: row.last_activity_at };
|
|
186
|
+
let lastActivity = row.last_activity_at;
|
|
187
|
+
for (const intent of intents) {
|
|
188
|
+
if (intent.valid_hash !== 1 || !Number.isSafeInteger(intent.expires_at) || intent.expires_at < 0) {
|
|
189
|
+
return { reason: "unknown_references", lastActivity: row.last_activity_at };
|
|
190
|
+
}
|
|
191
|
+
if (intent.hash !== key.hash) continue;
|
|
192
|
+
if (intent.expires_at > now) return { reason: "active_upload", lastActivity: row.last_activity_at };
|
|
193
|
+
lastActivity = Math.max(lastActivity, intent.expires_at);
|
|
194
|
+
}
|
|
195
|
+
if (now < lastActivity || now - lastActivity < retentionSeconds) return { reason: "retention", lastActivity: row.last_activity_at };
|
|
196
|
+
return { reason: null, lastActivity };
|
|
197
|
+
}
|
|
198
|
+
/** Read-only bounded advisory proof. A result is never deletion authority;
|
|
199
|
+
* claimGeneration repeats every proof in its own durable transaction. */
|
|
200
|
+
async inspectCandidates(input) {
|
|
201
|
+
assertGenerationIdentifier(input.workspaceId, "workspace");
|
|
202
|
+
const limit = input.limit ?? 25;
|
|
203
|
+
if (!Number.isSafeInteger(limit) || limit < 1 || limit > 100) throw new Error("Invalid storage candidate limit");
|
|
204
|
+
if (!Number.isSafeInteger(input.retentionSeconds) || input.retentionSeconds < 0) throw new Error("Invalid storage retention interval");
|
|
205
|
+
if (input.cursor !== void 0) assertGenerationIdentifier(input.cursor, "cursor");
|
|
206
|
+
if (this.raw.inTransaction !== false) throw new Error("Storage inspection requires its own read snapshot");
|
|
207
|
+
return this.raw.transaction(() => {
|
|
208
|
+
this.assertIntegrity();
|
|
209
|
+
const rows = this.raw.prepare(`SELECT * FROM ${GENERATION_TABLE} WHERE workspace_id = ? AND storage_provider_id = ?
|
|
210
|
+
AND generation_id > ? ORDER BY generation_id LIMIT ?`).all(input.workspaceId, this.storageProviderId, input.cursor ?? "", limit + 1);
|
|
211
|
+
const complete = rows.length <= limit;
|
|
212
|
+
const items = rows.slice(0, limit).map((row) => {
|
|
213
|
+
const proof = row.state === "verified" ? this.eligibility(row, input.retentionSeconds) : null;
|
|
214
|
+
return {
|
|
215
|
+
generation: generationRecord(row),
|
|
216
|
+
status: row.state !== "verified" ? row.state : proof?.reason ? "blocked" : "eligible",
|
|
217
|
+
reason: proof?.reason ?? null
|
|
218
|
+
};
|
|
219
|
+
});
|
|
220
|
+
const estimated = items.filter((item) => item.status === "eligible").reduce((sum, item) => sum + item.generation.sizeBytes, 0);
|
|
221
|
+
return {
|
|
222
|
+
items,
|
|
223
|
+
complete,
|
|
224
|
+
nextCursor: complete ? null : items.at(-1).generation.generationId,
|
|
225
|
+
observedAt: this.now(),
|
|
226
|
+
workspaceId: input.workspaceId,
|
|
227
|
+
retentionSeconds: input.retentionSeconds,
|
|
228
|
+
estimatedLogicalBytes: Number.isSafeInteger(estimated) ? estimated : null,
|
|
229
|
+
scope: "managed_generations_only",
|
|
230
|
+
legacyIncluded: false
|
|
231
|
+
};
|
|
232
|
+
})();
|
|
233
|
+
}
|
|
176
234
|
async claimGeneration(input) {
|
|
177
235
|
const key = this.key(input);
|
|
178
236
|
assertGenerationIdentifier(input.claimId, "claim");
|
|
@@ -181,24 +239,9 @@ export class SqliteExternalStorageGenerationCoordinator {
|
|
|
181
239
|
const row = this.find(key);
|
|
182
240
|
if (!row) return { status: "blocked", reason: "missing" };
|
|
183
241
|
if (row.state !== "verified") return row.claim_id === input.claimId ? { status: "replayed", generation: generationRecord(row) } : { status: "blocked", reason: "claim_conflict" };
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
if (proof) return { status: "blocked", reason: proof };
|
|
242
|
+
const { reason, lastActivity } = this.eligibility(row, input.retentionSeconds);
|
|
243
|
+
if (reason) return { status: "blocked", reason };
|
|
187
244
|
const now = this.now();
|
|
188
|
-
const intents = this.raw.prepare(`SELECT ${validGenerationHashSql("hash")} AS valid_hash,
|
|
189
|
-
${generationHashSql("hash")} AS hash, expires_at FROM upload_intents
|
|
190
|
-
WHERE workspace_id = ? AND status = 'active' LIMIT ?`).all(key.workspaceId, GENERATION_PROOF_ROWS + 1);
|
|
191
|
-
if (intents.length > GENERATION_PROOF_ROWS) return { status: "blocked", reason: "proof_incomplete" };
|
|
192
|
-
let lastActivity = row.last_activity_at;
|
|
193
|
-
for (const intent of intents) {
|
|
194
|
-
if (intent.valid_hash !== 1 || !Number.isSafeInteger(intent.expires_at) || intent.expires_at < 0) {
|
|
195
|
-
return { status: "blocked", reason: "unknown_references" };
|
|
196
|
-
}
|
|
197
|
-
if (intent.hash !== key.hash) continue;
|
|
198
|
-
if (intent.expires_at > now) return { status: "blocked", reason: "active_upload" };
|
|
199
|
-
lastActivity = Math.max(lastActivity, intent.expires_at);
|
|
200
|
-
}
|
|
201
|
-
if (now < lastActivity || now - lastActivity < input.retentionSeconds) return { status: "blocked", reason: "retention" };
|
|
202
245
|
if (this.raw.prepare(`SELECT 1 FROM ${GENERATION_TABLE} WHERE claim_id = ?`).get(input.claimId)) {
|
|
203
246
|
return { status: "blocked", reason: "claim_conflict" };
|
|
204
247
|
}
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { SqliteExternalStorageGenerationUploadCoordinator } from '../storage/sqlite-generation-upload-coordinator.js';
|
|
1
2
|
/**
|
|
2
3
|
* SQLite implementation of SyncGatewayAdapter.
|
|
3
4
|
*
|
|
@@ -18,19 +19,14 @@ export declare class SqliteSyncGatewayAdapter implements SyncGatewayAdapter {
|
|
|
18
19
|
watchVersion(event: H3Event, scope: {
|
|
19
20
|
workspaceId: string;
|
|
20
21
|
}, onVersion: (version: number) => void, onError: (error: unknown) => void): Promise<() => void>;
|
|
22
|
+
/** Construct only on use, after the provider initializes its database. */
|
|
23
|
+
get storageGenerationCoordinator(): SqliteExternalStorageGenerationUploadCoordinator | undefined;
|
|
21
24
|
get capabilities(): {
|
|
22
25
|
readonly snapshotBootstrap: "snapshot-v1";
|
|
23
26
|
readonly historyRetention: "snapshot-v1";
|
|
24
27
|
readonly retainedStorageMetadata: "v1";
|
|
25
28
|
readonly atomicUploadQuota: "retained-v1";
|
|
26
|
-
readonly backgroundGenerationHistory?: undefined;
|
|
27
|
-
readonly delegationTerminalHistory?: undefined;
|
|
28
|
-
readonly canonicalChatHistory?: undefined;
|
|
29
|
-
readonly projectOwnership?: undefined;
|
|
30
|
-
readonly workspaceItems?: undefined;
|
|
31
29
|
} | {
|
|
32
|
-
readonly snapshotBootstrap: "snapshot-v1";
|
|
33
|
-
readonly historyRetention: "snapshot-v1";
|
|
34
30
|
readonly backgroundGenerationHistory: "v1";
|
|
35
31
|
readonly delegationTerminalHistory: "v1";
|
|
36
32
|
readonly canonicalChatHistory: "v1";
|
|
@@ -38,6 +34,9 @@ export declare class SqliteSyncGatewayAdapter implements SyncGatewayAdapter {
|
|
|
38
34
|
readonly workspaceItems: "v1";
|
|
39
35
|
readonly retainedStorageMetadata: "v1";
|
|
40
36
|
readonly atomicUploadQuota: "retained-v1";
|
|
37
|
+
readonly externalStorageGenerations?: "v1" | undefined;
|
|
38
|
+
readonly snapshotBootstrap: "snapshot-v1";
|
|
39
|
+
readonly historyRetention: "snapshot-v1";
|
|
41
40
|
};
|
|
42
41
|
private get db();
|
|
43
42
|
readChatHistory(actor: CanonicalHistoryActor, query: CanonicalChatQuery, signal?: AbortSignal): Promise<CanonicalChatReadResult>;
|
|
@@ -1,6 +1,8 @@
|
|
|
1
|
+
import { SqliteExternalStorageGenerationUploadCoordinator } from "../storage/sqlite-generation-upload-coordinator.js";
|
|
1
2
|
import { backgroundFinalizationFingerprint, stableJson } from "./background-history-fingerprint.js";
|
|
2
3
|
import { hasWorkspaceItemSemantics, WORKSPACE_ITEM_CAPABILITY } from "./workspace-item-capability.js";
|
|
3
4
|
import { createHash } from "node:crypto";
|
|
5
|
+
import { sql } from "kysely";
|
|
4
6
|
import { canRunSyncHistoryGc } from "./history-gc-policy.js";
|
|
5
7
|
import { createError } from "h3";
|
|
6
8
|
import {
|
|
@@ -42,6 +44,8 @@ const SESSION_CONTEXT_KEY_PREFIX = "__or3_session_context_";
|
|
|
42
44
|
const MIN_SYNC_RETENTION_SECONDS = 60 * 60;
|
|
43
45
|
const MAX_SYNC_RETENTION_SECONDS = 365 * 24 * 60 * 60;
|
|
44
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;
|
|
45
49
|
const PENDING_UPLOAD_RESERVATIONS_SQL = `
|
|
46
50
|
SELECT MIN(intent.id) AS id, intent.hash,
|
|
47
51
|
MAX(intent.size_bytes) AS reserved_bytes, MAX(intent.expires_at) AS expires_at
|
|
@@ -63,6 +67,72 @@ const QUOTA_RESERVATIONS_SQL = `SELECT intent.hash, MAX(intent.size_bytes) AS re
|
|
|
63
67
|
ON retained.workspace_id = intent.workspace_id AND retained.hash = intent.hash
|
|
64
68
|
WHERE intent.workspace_id = ? AND intent.status = 'active' AND intent.expires_at > ?
|
|
65
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
|
+
}
|
|
66
136
|
function uid() {
|
|
67
137
|
return globalThis.crypto.randomUUID();
|
|
68
138
|
}
|
|
@@ -560,6 +630,16 @@ export class SqliteSyncGatewayAdapter {
|
|
|
560
630
|
if (this.versionWatchers.get(scope.workspaceId) === current) this.versionWatchers.delete(scope.workspaceId);
|
|
561
631
|
};
|
|
562
632
|
}
|
|
633
|
+
/** Construct only on use, after the provider initializes its database. */
|
|
634
|
+
get storageGenerationCoordinator() {
|
|
635
|
+
const namespace = process.env.OR3_STORAGE_FS_CLEANUP_NAMESPACE_ID;
|
|
636
|
+
if (process.platform !== "linux" || !namespace || isD1Driver()) return void 0;
|
|
637
|
+
if (!/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/.test(namespace)) throw new Error("Invalid filesystem cleanup namespace");
|
|
638
|
+
const raw = getRawDb();
|
|
639
|
+
const durability = raw.prepare("PRAGMA synchronous").get();
|
|
640
|
+
if (durability.synchronous !== 2 && durability.synchronous !== 3) return void 0;
|
|
641
|
+
return new SqliteExternalStorageGenerationUploadCoordinator({ storageProviderId: "fs", database: raw });
|
|
642
|
+
}
|
|
563
643
|
get capabilities() {
|
|
564
644
|
return isD1Driver() ? {
|
|
565
645
|
snapshotBootstrap: "snapshot-v1",
|
|
@@ -569,6 +649,7 @@ export class SqliteSyncGatewayAdapter {
|
|
|
569
649
|
} : {
|
|
570
650
|
snapshotBootstrap: "snapshot-v1",
|
|
571
651
|
historyRetention: "snapshot-v1",
|
|
652
|
+
...this.storageGenerationCoordinator ? { externalStorageGenerations: "v1" } : {},
|
|
572
653
|
backgroundGenerationHistory: "v1",
|
|
573
654
|
delegationTerminalHistory: "v1",
|
|
574
655
|
canonicalChatHistory: "v1",
|
|
@@ -1113,7 +1194,7 @@ export class SqliteSyncGatewayAdapter {
|
|
|
1113
1194
|
const now = nowEpoch();
|
|
1114
1195
|
const hash = normalizeStorageHash(input.hash);
|
|
1115
1196
|
const raw = isD1Driver() ? null : getRawDb();
|
|
1116
|
-
const
|
|
1197
|
+
const sql2 = `UPDATE upload_intents
|
|
1117
1198
|
SET status = 'consumed', storage_id = ?, consumed_at = ?
|
|
1118
1199
|
WHERE id = ? AND workspace_id = ? AND status = 'active' AND expires_at > ?
|
|
1119
1200
|
AND hash = ? AND mime_type = ? AND size_bytes = ?`;
|
|
@@ -1127,7 +1208,7 @@ export class SqliteSyncGatewayAdapter {
|
|
|
1127
1208
|
input.mimeType,
|
|
1128
1209
|
input.sizeBytes
|
|
1129
1210
|
];
|
|
1130
|
-
const changes = raw ? raw.prepare(
|
|
1211
|
+
const changes = raw ? raw.prepare(sql2).run(...parameters).changes : (await d1Run(sql2, ...parameters)).meta?.changes;
|
|
1131
1212
|
if (changes === 1) return;
|
|
1132
1213
|
const receiptSql = `SELECT 1 FROM upload_intents
|
|
1133
1214
|
WHERE id = ? AND workspace_id = ? AND status = 'consumed' AND expires_at > ?
|
|
@@ -1178,7 +1259,7 @@ export class SqliteSyncGatewayAdapter {
|
|
|
1178
1259
|
}
|
|
1179
1260
|
const after = decodeCanonicalStorageCursor(input.cursor, input.kind, hash);
|
|
1180
1261
|
const raw = isD1Driver() ? null : getRawDb();
|
|
1181
|
-
const all = async (
|
|
1262
|
+
const all = async (sql2, ...parameters) => raw ? raw.prepare(sql2).all(...parameters) : d1All(sql2, ...parameters);
|
|
1182
1263
|
if (input.kind === "active_reservations") {
|
|
1183
1264
|
if (after.length > 1) {
|
|
1184
1265
|
throw createError({ statusCode: 400, statusMessage: "Invalid canonical storage cursor" });
|
|
@@ -1757,30 +1838,13 @@ export class SqliteSyncGatewayAdapter {
|
|
|
1757
1838
|
const { scope, cursor, limit, tables } = input;
|
|
1758
1839
|
await assertWorkspaceScopeAuthorized(event, scope.workspaceId);
|
|
1759
1840
|
const fetchLimit = resolvePullLimit(limit);
|
|
1760
|
-
let query = db.selectFrom("change_log").
|
|
1841
|
+
let query = db.selectFrom("change_log").where("workspace_id", "=", scope.workspaceId).where("server_version", ">", cursor).orderBy("server_version", "asc");
|
|
1761
1842
|
if (tables?.length) {
|
|
1762
1843
|
query = query.where("table_name", "in", tables);
|
|
1763
1844
|
}
|
|
1764
|
-
const
|
|
1765
|
-
const
|
|
1766
|
-
const
|
|
1767
|
-
const changes = resultRows.map((row) => ({
|
|
1768
|
-
serverVersion: row.server_version,
|
|
1769
|
-
tableName: row.table_name,
|
|
1770
|
-
pk: row.pk,
|
|
1771
|
-
op: row.op,
|
|
1772
|
-
payload: row.payload_json ? JSON.parse(row.payload_json) : void 0,
|
|
1773
|
-
stamp: {
|
|
1774
|
-
clock: row.clock,
|
|
1775
|
-
hlc: row.hlc,
|
|
1776
|
-
deviceId: row.device_id,
|
|
1777
|
-
opId: row.op_id
|
|
1778
|
-
}
|
|
1779
|
-
})).filter(
|
|
1780
|
-
(change) => isNotificationVisibleToUser(change, resolveSessionUserId(event))
|
|
1781
|
-
);
|
|
1782
|
-
const lastRow = resultRows[resultRows.length - 1];
|
|
1783
|
-
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() : [];
|
|
1784
1848
|
const minLog = await db.selectFrom("change_log").select("server_version").where("workspace_id", "=", scope.workspaceId).orderBy("server_version", "asc").limit(1).executeTakeFirst();
|
|
1785
1849
|
const counter = await db.selectFrom("server_version_counter").select("value").where("workspace_id", "=", scope.workspaceId).executeTakeFirst();
|
|
1786
1850
|
const retention = computePullRetention({
|
|
@@ -1788,12 +1852,30 @@ export class SqliteSyncGatewayAdapter {
|
|
|
1788
1852
|
oldestLogVersion: minLog?.server_version ?? null,
|
|
1789
1853
|
highWatermark: counter?.value ?? 0
|
|
1790
1854
|
});
|
|
1791
|
-
|
|
1792
|
-
|
|
1793
|
-
|
|
1794
|
-
|
|
1795
|
-
|
|
1796
|
-
|
|
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 };
|
|
1797
1879
|
}
|
|
1798
1880
|
async snapshot(event, input) {
|
|
1799
1881
|
return this.captureSnapshot(event, input, false);
|
|
@@ -1985,79 +2067,11 @@ export class SqliteSyncGatewayAdapter {
|
|
|
1985
2067
|
});
|
|
1986
2068
|
header = capture.immediate();
|
|
1987
2069
|
}
|
|
1988
|
-
const
|
|
1989
|
-
|
|
1990
|
-
|
|
1991
|
-
|
|
1992
|
-
|
|
1993
|
-
WHERE snapshot_id = ?
|
|
1994
|
-
AND (
|
|
1995
|
-
table_name > ?
|
|
1996
|
-
OR (table_name = ? AND pk > ?)
|
|
1997
|
-
OR (table_name = ? AND pk = ? AND kind > ?)
|
|
1998
|
-
)
|
|
1999
|
-
ORDER BY table_name ASC, pk ASC, kind ASC
|
|
2000
|
-
LIMIT ?
|
|
2001
|
-
`).all(
|
|
2002
|
-
header.id,
|
|
2003
|
-
after.tableName,
|
|
2004
|
-
after.tableName,
|
|
2005
|
-
after.pk,
|
|
2006
|
-
after.tableName,
|
|
2007
|
-
after.pk,
|
|
2008
|
-
after.kind,
|
|
2009
|
-
pageSize + 1
|
|
2010
|
-
) : raw.prepare(`
|
|
2011
|
-
SELECT
|
|
2012
|
-
table_name, pk, kind, payload_json, clock, hlc, op_id,
|
|
2013
|
-
server_deleted_at
|
|
2014
|
-
FROM sync_snapshot_items
|
|
2015
|
-
WHERE snapshot_id = ?
|
|
2016
|
-
ORDER BY table_name ASC, pk ASC, kind ASC
|
|
2017
|
-
LIMIT ?
|
|
2018
|
-
`).all(header.id, pageSize + 1);
|
|
2019
|
-
const hasMore = rows.length > pageSize;
|
|
2020
|
-
const pageRows = hasMore ? rows.slice(0, pageSize) : rows;
|
|
2021
|
-
const items = pageRows.map((row) => {
|
|
2022
|
-
const revision = {
|
|
2023
|
-
clock: row.clock,
|
|
2024
|
-
hlc: row.hlc,
|
|
2025
|
-
opId: row.op_id
|
|
2026
|
-
};
|
|
2027
|
-
if (row.kind === "row") {
|
|
2028
|
-
return {
|
|
2029
|
-
kind: "row",
|
|
2030
|
-
tableName: row.table_name,
|
|
2031
|
-
pk: row.pk,
|
|
2032
|
-
payload: JSON.parse(row.payload_json ?? "null"),
|
|
2033
|
-
revision
|
|
2034
|
-
};
|
|
2035
|
-
}
|
|
2036
|
-
return {
|
|
2037
|
-
kind: "tombstone",
|
|
2038
|
-
tableName: row.table_name,
|
|
2039
|
-
pk: row.pk,
|
|
2040
|
-
revision,
|
|
2041
|
-
serverDeletedAt: row.server_deleted_at ?? 0
|
|
2042
|
-
};
|
|
2043
|
-
});
|
|
2044
|
-
const lastRow = pageRows.at(-1);
|
|
2045
|
-
const nextPageToken = hasMore && lastRow ? encodeSnapshotPageToken({
|
|
2046
|
-
version: 1,
|
|
2047
|
-
snapshotId: header.id,
|
|
2048
|
-
after: {
|
|
2049
|
-
tableName: lastRow.table_name,
|
|
2050
|
-
pk: lastRow.pk,
|
|
2051
|
-
kind: lastRow.kind
|
|
2052
|
-
}
|
|
2053
|
-
}) : null;
|
|
2054
|
-
return {
|
|
2055
|
-
workspaceId: header.workspace_id,
|
|
2056
|
-
snapshotId: header.id,
|
|
2057
|
-
highWatermark: header.high_watermark,
|
|
2058
|
-
items,
|
|
2059
|
-
nextPageToken
|
|
2060
|
-
};
|
|
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);
|
|
2061
2075
|
}
|
|
2062
2076
|
async updateCursor(event, input) {
|
|
2063
2077
|
await assertWorkspaceScopeAuthorized(event, input.scope.workspaceId);
|
|
@@ -2455,34 +2469,18 @@ export class SqliteSyncGatewayAdapter {
|
|
|
2455
2469
|
if (!created) throw createError({ statusCode: 410, statusMessage: "Snapshot expired or unavailable" });
|
|
2456
2470
|
header = created;
|
|
2457
2471
|
}
|
|
2458
|
-
const
|
|
2459
|
-
|
|
2460
|
-
|
|
2461
|
-
|
|
2462
|
-
AND (
|
|
2463
|
-
table_name > ?
|
|
2464
|
-
OR (table_name = ? AND pk > ?)
|
|
2465
|
-
OR (table_name = ? AND pk = ? AND kind > ?)
|
|
2466
|
-
)
|
|
2467
|
-
ORDER BY table_name ASC, pk ASC, kind ASC
|
|
2468
|
-
LIMIT ?`,
|
|
2469
|
-
header.id,
|
|
2470
|
-
after.tableName,
|
|
2471
|
-
after.tableName,
|
|
2472
|
-
after.pk,
|
|
2473
|
-
after.tableName,
|
|
2474
|
-
after.pk,
|
|
2475
|
-
after.kind,
|
|
2476
|
-
pageSize + 1
|
|
2477
|
-
) : await d1All(
|
|
2478
|
-
`SELECT table_name, pk, kind, payload_json, clock, hlc, op_id, server_deleted_at
|
|
2479
|
-
FROM sync_snapshot_items
|
|
2480
|
-
WHERE snapshot_id = ?
|
|
2481
|
-
ORDER BY table_name ASC, pk ASC, kind ASC
|
|
2482
|
-
LIMIT ?`,
|
|
2483
|
-
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,
|
|
2484
2476
|
pageSize + 1
|
|
2485
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
|
+
) : [];
|
|
2486
2484
|
const [retained] = await d1All(
|
|
2487
2485
|
"SELECT expires_at FROM sync_snapshots WHERE id = ?",
|
|
2488
2486
|
header.id
|
|
@@ -2490,43 +2488,7 @@ export class SqliteSyncGatewayAdapter {
|
|
|
2490
2488
|
if (!retained || retained.expires_at <= nowEpoch()) {
|
|
2491
2489
|
throw createError({ statusCode: 410, statusMessage: "Snapshot expired or unavailable" });
|
|
2492
2490
|
}
|
|
2493
|
-
|
|
2494
|
-
const pageRows = hasMore ? rows.slice(0, pageSize) : rows;
|
|
2495
|
-
const items = pageRows.map((row) => {
|
|
2496
|
-
const revision = { clock: row.clock, hlc: row.hlc, opId: row.op_id };
|
|
2497
|
-
if (row.kind === "row") {
|
|
2498
|
-
return {
|
|
2499
|
-
kind: "row",
|
|
2500
|
-
tableName: row.table_name,
|
|
2501
|
-
pk: row.pk,
|
|
2502
|
-
payload: JSON.parse(row.payload_json ?? "null"),
|
|
2503
|
-
revision
|
|
2504
|
-
};
|
|
2505
|
-
}
|
|
2506
|
-
return {
|
|
2507
|
-
kind: "tombstone",
|
|
2508
|
-
tableName: row.table_name,
|
|
2509
|
-
pk: row.pk,
|
|
2510
|
-
revision,
|
|
2511
|
-
serverDeletedAt: row.server_deleted_at ?? 0
|
|
2512
|
-
};
|
|
2513
|
-
});
|
|
2514
|
-
const lastRow = pageRows.at(-1);
|
|
2515
|
-
return {
|
|
2516
|
-
workspaceId: header.workspace_id,
|
|
2517
|
-
snapshotId: header.id,
|
|
2518
|
-
highWatermark: header.high_watermark,
|
|
2519
|
-
items,
|
|
2520
|
-
nextPageToken: hasMore && lastRow ? encodeSnapshotPageToken({
|
|
2521
|
-
version: 1,
|
|
2522
|
-
snapshotId: header.id,
|
|
2523
|
-
after: {
|
|
2524
|
-
tableName: lastRow.table_name,
|
|
2525
|
-
pk: lastRow.pk,
|
|
2526
|
-
kind: lastRow.kind
|
|
2527
|
-
}
|
|
2528
|
-
}) : null
|
|
2529
|
-
};
|
|
2491
|
+
return buildSnapshotPage(header, rows, pageSize, sizes.length);
|
|
2530
2492
|
}
|
|
2531
2493
|
async updateCursorInD1(workspaceId, deviceId, version, ownerUserId, now) {
|
|
2532
2494
|
const [counter] = await d1All(
|