or3-provider-sqlite 0.0.27 → 0.0.28
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 +34 -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 +12 -0
- 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.
|
|
@@ -423,11 +430,11 @@ Admin workspace summaries, workspace details, and deployment-admin lists expose
|
|
|
423
430
|
|
|
424
431
|
## Dormant immutable-generation foundation (unreleased)
|
|
425
432
|
|
|
426
|
-
Migration 030 adds
|
|
433
|
+
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
434
|
|
|
428
|
-
Migrations 030–
|
|
435
|
+
Migrations 030–032 resume safely after interrupted startup and reject incompatible preexisting schema objects. Released migration 029 remains unchanged.
|
|
429
436
|
|
|
430
|
-
Migration 031 adds the
|
|
437
|
+
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
438
|
|
|
432
439
|
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
440
|
|
|
@@ -437,3 +444,27 @@ releases enrolled-object charges after confirmed removal acknowledgement. Restor
|
|
|
437
444
|
reuse their retained charge; replacement waits for confirmed deletion. Legacy
|
|
438
445
|
retained objects cannot be implicitly adopted. This adds no schema migration,
|
|
439
446
|
registration or production cleanup activation.
|
|
447
|
+
|
|
448
|
+
### Admin diagnostics and managed-generation inspection
|
|
449
|
+
|
|
450
|
+
The optional customer-read store includes bounded completed-sync observations
|
|
451
|
+
(migration `032_sync_observations`): last successful gateway operation and latest
|
|
452
|
+
classified failure per user/workspace. These observations contain no sync payload,
|
|
453
|
+
are independent of cursor contact, and cannot invalidate an accepted sync write.
|
|
454
|
+
The SQLite admin adapter's explicit health probe verifies a canonical database
|
|
455
|
+
read; configuration/enablement alone is not a health result.
|
|
456
|
+
|
|
457
|
+
The dormant generation coordinator also exposes `inspectCandidates` to trusted
|
|
458
|
+
server callers. It pages at most 100 exact enrolled generations per workspace,
|
|
459
|
+
uses the same bounded eligibility proof as claims, and changes no generation or
|
|
460
|
+
accounting state. Estimates describe logical managed bytes, not reclaimed disk
|
|
461
|
+
blocks. Mutable legacy storage is excluded. This read does not register deletion,
|
|
462
|
+
HTTP upload, restore, cleanup automation or a production capability. Installed
|
|
463
|
+
Linux filesystem and independent S3 backup/crash lifecycle gates remain required
|
|
464
|
+
before activation.
|
|
465
|
+
|
|
466
|
+
### Opt-in enrolled-generation cleanup
|
|
467
|
+
|
|
468
|
+
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.
|
|
469
|
+
|
|
470
|
+
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,3 +1,4 @@
|
|
|
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";
|
|
@@ -560,6 +561,16 @@ export class SqliteSyncGatewayAdapter {
|
|
|
560
561
|
if (this.versionWatchers.get(scope.workspaceId) === current) this.versionWatchers.delete(scope.workspaceId);
|
|
561
562
|
};
|
|
562
563
|
}
|
|
564
|
+
/** Construct only on use, after the provider initializes its database. */
|
|
565
|
+
get storageGenerationCoordinator() {
|
|
566
|
+
const namespace = process.env.OR3_STORAGE_FS_CLEANUP_NAMESPACE_ID;
|
|
567
|
+
if (process.platform !== "linux" || !namespace || isD1Driver()) return void 0;
|
|
568
|
+
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");
|
|
569
|
+
const raw = getRawDb();
|
|
570
|
+
const durability = raw.prepare("PRAGMA synchronous").get();
|
|
571
|
+
if (durability.synchronous !== 2 && durability.synchronous !== 3) return void 0;
|
|
572
|
+
return new SqliteExternalStorageGenerationUploadCoordinator({ storageProviderId: "fs", database: raw });
|
|
573
|
+
}
|
|
563
574
|
get capabilities() {
|
|
564
575
|
return isD1Driver() ? {
|
|
565
576
|
snapshotBootstrap: "snapshot-v1",
|
|
@@ -569,6 +580,7 @@ export class SqliteSyncGatewayAdapter {
|
|
|
569
580
|
} : {
|
|
570
581
|
snapshotBootstrap: "snapshot-v1",
|
|
571
582
|
historyRetention: "snapshot-v1",
|
|
583
|
+
...this.storageGenerationCoordinator ? { externalStorageGenerations: "v1" } : {},
|
|
572
584
|
backgroundGenerationHistory: "v1",
|
|
573
585
|
delegationTerminalHistory: "v1",
|
|
574
586
|
canonicalChatHistory: "v1",
|