@g9tm/syncdata 1.3.0 → 1.4.0

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.
@@ -1 +1 @@
1
- {"version":3,"file":"store.js","sourceRoot":"","sources":["../../src/sqlite/store.ts"],"names":[],"mappings":"AAAA,yHAAyH;AACzH,0HAA0H;AAC1H,sDAAsD;AACtD,OAAO,EAAE,gBAAgB,EAAE,gBAAgB,EAAE,MAAM,0BAA0B,CAAC;AAC9E,OAAO,EAAE,gBAAgB,EAAE,eAAe,EAAE,MAAM,2BAA2B,CAAC;AAC9E,OAAO,EAAE,OAAO,EAAE,OAAO,EAAE,MAAM,yBAAyB,CAAC;AAC3D,OAAO,EAAE,MAAM,EAAE,MAAM,yBAAyB,CAAC;AACjD,OAAO,EAAE,gBAAgB,EAAE,MAAM,+BAA+B,CAAC;AAGjE,OAAO,EACL,aAAa,EACb,mBAAmB,EACnB,oBAAoB,GAoBrB,MAAM,yBAAyB,CAAC;AAEjC,OAAO,KAAK,KAAK,MAAM,YAAY,CAAC;AACpC,OAAO,KAAK,QAAQ,MAAM,eAAe,CAAC;AAC1C,OAAO,EAAE,QAAQ,EAAE,gBAAgB,EAAE,QAAQ,EAAE,WAAW,EAAE,kBAAkB,EAAE,gBAAgB,EAAE,YAAY,EAAE,MAAM,iBAAiB,CAAC;AAExI,OAAO,EACL,KAAK,EACL,UAAU,EACV,KAAK,EACL,IAAI,EACJ,KAAK,EACL,aAAa,EACb,eAAe,EACf,wBAAwB,EACxB,uBAAuB,EACvB,iBAAiB,EACjB,eAAe,EACf,OAAO,GAER,MAAM,gBAAgB,CAAC;AACxB,OAAO,EAAE,mBAAmB,EAAoE,MAAM,cAAc,CAAC;AACrH,OAAO,KAAK,IAAI,MAAM,WAAW,CAAC;AAClC,OAAO,KAAK,KAAK,MAAM,YAAY,CAAC;AACpC,OAAO,KAAK,UAAU,MAAM,iBAAiB,CAAC;AAC9C,OAAO,EAAE,qBAAqB,EA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ACX,MAAM,MAAM,CAAC,QAAQ,EAAE,CAAC;YACxB,MAAM,IAAI,CAAC,OAAO,CAAC,MAAM,CAAC,KAAK,CAAC,MAAM,CAAC,OAAO,CAAC,CAAC;QAClD,CAAC;QACD,IAAI,MAAM;YAAE,MAAM,IAAI,CAAC,OAAO,CAAC,MAAM,CAAC,KAAK,CAAC,MAAM,CAAC,OAAO,CAAC,CAAC;IAC9D,CAAC;CACF;AAED,yDAAyD;AACzD,OAAO,EAAE,MAAM,EAAE,CAAC","sourcesContent":["// Twin of G9SyncData.Client.Sqlite/G9CSqliteSyncStore.cs (+ .Incarnation.cs, .Recovery.cs): the SQLite implementation of\n// the client store. Every object it creates is the one the .NET store creates (AiGuides/08-Client-Sqlite.md), so the same\n// database file serves the MAUI app and the Lynx app.\nimport { G9EMoveOutPolicy, G9ESyncDirection } from '../abstractions/enums.js';\nimport { G9SyncErrorCodes, G9SyncException } from '../abstractions/errors.js';\nimport { guidToN, newGuid } from '../abstractions/guid.js';\nimport { G9Long } from '../abstractions/long.js';\nimport { G9SyncParameters } from '../abstractions/parameters.js';\nimport type { G9SyncClientModel, G9SyncClientTable } from '../client/model.js';\nimport type { G9SyncLogLevel } from '../client/runs.js';\nimport {\n G9ApplyReport,\n G9ERevocationReason,\n G9ESubscriptionState,\n type G9ApplySlice,\n type G9ChangeFeedEntry,\n type G9ClientServerState,\n type G9CommandRequest,\n type G9ELocalCommandState,\n type G9LocalCommand,\n type G9LocalCommandWriter,\n type G9LocalRowEntry,\n type G9PendingSummary,\n type G9PushBatch,\n type G9QuarantinedRow,\n type G9ResumePoint,\n type G9RetainedRow,\n type G9StagedPull,\n type G9SubscriptionUpdate,\n type G9SyncClientStore,\n type G9SyncRejection,\n type G9SyncRunReport,\n type G9SyncSubscriptionRecord,\n} from '../client/storeTypes.js';\nimport type { G9DtBackfillRequest, G9DtHelloResult, G9DtNegotiatedTable, G9DtPushResult, G9DtSnapshotFileRequest, G9DtSyncChunk, G9DtTableDigest } from '../protocol/dtos.js';\nimport * as apply from './apply.js';\nimport * as commands from './commands.js';\nimport { asNumber, asOptionalString, asString, G9AsyncLock, G9SqliteConnection, G9StatementBatch, statementsOf } from './connection.js';\nimport type { G9SessionToken } from './driver.js';\nimport {\n byTid,\n LocalTable,\n logTo,\n meta,\n nowMs,\n persistedJson,\n readLocalValues,\n readPersistedDefinitions,\n readPersistedNegotiated,\n readSubscriptions,\n serializeValues,\n setMeta,\n type StoreInternals,\n} from './internals.js';\nimport { resolveStoreOptions, type G9ResolvedSqliteStoreOptions, type G9SqliteSyncStoreOptions } from './options.js';\nimport * as push from './push.js';\nimport * as query from './query.js';\nimport * as revocation from './revocation.js';\nimport { describeSnapshotFiles, sweepOrphanSnapshotFiles } from './snapshotFiles.js';\nimport { allColumnsMask, bit, columnDefinition, createCommandTriggers, createTable, createTriggers, dropTriggers, EPHEMERAL_SLOT, keyExpression, METADATA, modelHash, quote } from './sql.js';\n\n/** What exportPendingChanges managed to save (`G9CPendingExport`). */\nexport interface G9PendingExport {\n rows: number;\n unreadable: number;\n}\n\n/**\n * The SQLite client store over a G9SqliteDriver. Library writes are serialised in-process; app writes on other\n * connections are captured by triggers and wait on SQLite's busy timeout.\n */\nexport class G9SqliteSyncStore implements G9SyncClientStore, StoreInternals {\n readonly options: G9ResolvedSqliteStoreOptions;\n readonly writeLock = new G9AsyncLock();\n byLocal = new Map<string, LocalTable>();\n byServerId = new Map<number, LocalTable>();\n /** True when this initialisation found a database of another installation and gave it a new identity (ADR-0067). */\n replicaIdentityWasReplaced = false;\n\n private _model: G9SyncClientModel | null = null;\n private _writer: G9SqliteConnection | null = null;\n private _reader: G9SqliteConnection | null = null;\n private _opening: Promise<void> | null = null;\n\n constructor(options: G9SqliteSyncStoreOptions) {\n this.options = resolveStoreOptions(options);\n }\n\n // ================================================================ internals\n\n writer(): G9SqliteConnection {\n if (!this._writer) throw new Error('The SQLite sync store is not open; call initialize first.');\n return this._writer;\n }\n\n reader(): G9SqliteConnection {\n if (!this._reader) throw new Error('The SQLite sync store is not open; call initialize first.');\n return this._reader;\n }\n\n ensureInitialized(): G9SyncClientModel {\n if (!this._model) throw new Error('The SQLite sync store is not initialised; call initialize first.');\n return this._model;\n }\n\n log(level: G9SyncLogLevel, eventId: number, message: string, error?: unknown): void {\n logTo(this.options.logger, level, eventId, message, error);\n }\n\n private async _open(): Promise<void> {\n if (this._writer && this._reader) return;\n if (!this._opening) {\n this._opening = (async () => {\n const driver = this.options.driver;\n const pragmas = { busyTimeoutMs: this.options.busyTimeoutMs, foreignKeys: false };\n const writerSession: G9SessionToken = await driver.open({ path: this.options.databasePath, create: true, pragmas });\n const writer = new G9SqliteConnection(driver, writerSession);\n await this._configure(writer);\n if (this.options.useWriteAheadLog) await writer.query('PRAGMA journal_mode = WAL');\n const readerSession: G9SessionToken = await driver.open({ path: this.options.databasePath, create: true, pragmas });\n const reader = new G9SqliteConnection(driver, readerSession);\n await this._configure(reader);\n this._writer = writer;\n this._reader = reader;\n })();\n this._opening.catch(() => (this._opening = null));\n }\n await this._opening;\n }\n\n /** The PRAGMAs the .NET store sets on every connection it opens. */\n private async _configure(connection: G9SqliteConnection): Promise<void> {\n await connection.exec(\n 'PRAGMA busy_timeout = ' + this.options.busyTimeoutMs + '; PRAGMA foreign_keys = OFF; PRAGMA journal_size_limit = ' + this.options.walSizeLimitBytes + ';',\n );\n }\n\n // ================================================================ initialise\n\n async initialize(model: G9SyncClientModel): Promise<void> {\n if (!model) throw new TypeError('A model is required.');\n await this._open();\n await this.writeLock.run(async () => {\n const connection = this.writer();\n const tables: LocalTable[] = [];\n await connection.transaction('immediate', async () => {\n await connection.exec(METADATA);\n if (asNumber(await connection.scalar(\"SELECT count(*) FROM pragma_table_info('g9_ctx') WHERE name = 'command_id'\")) === 0) {\n // Stores created before commands existed (ADR-0025).\n await connection.exec('ALTER TABLE g9_ctx ADD COLUMN command_id TEXT NULL');\n }\n if (asNumber(await connection.scalar(\"SELECT count(*) FROM pragma_table_info('g9_stage_runs') WHERE name = 'generation'\")) === 0) {\n // Stores created before stages were validated on resume (ADR-0046): a stage in flight is dropped and replanned.\n await connection.exec('ALTER TABLE g9_stage_runs ADD COLUMN generation TEXT NULL');\n await connection.exec('ALTER TABLE g9_stage_runs ADD COLUMN stage_seq INTEGER NOT NULL DEFAULT 0');\n await connection.exec('DELETE FROM g9_stage; DELETE FROM g9_stage_runs;');\n }\n if (asNumber(await connection.scalar(\"SELECT count(*) FROM pragma_table_info('g9_stage_runs') WHERE name = 'from_cursors_json'\")) === 0) {\n await connection.exec('ALTER TABLE g9_stage_runs ADD COLUMN from_cursors_json TEXT NULL');\n }\n if (asNumber(await connection.scalar(\"SELECT count(*) FROM pragma_table_info('g9_subscriptions') WHERE name = 'move_out_policy'\")) === 0) {\n await connection.exec('ALTER TABLE g9_subscriptions ADD COLUMN move_out_policy INTEGER NULL');\n }\n if ((await meta(connection, 'client_id')) === null) await setMeta(connection, 'client_id', newGuid());\n if ((await meta(connection, 'next_batch_id')) === null) await setMeta(connection, 'next_batch_id', '1');\n await this._verifyIncarnation(connection);\n for (const table of await this._provisionTables(connection, model.tables)) tables.push(table);\n });\n this._model = model;\n this.byLocal = new Map(tables.map((t) => [t.model.localName.toLowerCase(), t] as [string, LocalTable]));\n this.byServerId = new Map(tables.filter((t) => t.negotiated !== null).map((t) => [(t.negotiated as G9DtNegotiatedTable).tableId, t] as [number, LocalTable]));\n await sweepOrphanSnapshotFiles(this, connection);\n this.log('information', 20101, `G9SyncData SQLite store initialised with ${tables.length} tables`);\n });\n }\n\n /** The store's offer to receive snapshot files (ADR-0072); null without a `snapshotFiles` sink. */\n describeSnapshotFiles(negotiated: readonly G9DtNegotiatedTable[]): G9DtSnapshotFileRequest | null {\n if (!this._model) return null;\n return describeSnapshotFiles(this, negotiated);\n }\n\n /**\n * Provisions every model table (`ProvisionTable` of the .NET store, for all tables at once).\n *\n * The .NET store asks SQLite per table (~6 statements each) because a statement costs nothing in process. Through a\n * bridged driver every call is a round trip (~5.7 ms on the Android emulator: 296 calls = 1.7 s on EVERY app start, 534\n * on the first), so this reads everything the decisions need in ONE call — g9_tables, the tables, their columns, the\n * triggers and the AUTOINCREMENT counter — and runs the resulting statements in ONE batch, in exactly the order the\n * per-table path runs them. New tables get their tid explicitly (the value AUTOINCREMENT would hand out, in model\n * order), so the triggers can be written in the same batch. Same objects, same rows, same order (PARITY.md).\n */\n private async _provisionTables(connection: G9SqliteConnection, models: readonly G9SyncClientTable[]): Promise<LocalTable[]> {\n const [registered, tableNames, columns, triggers, sequence] = await connection.runStatements([\n ...statementsOf('SELECT tid, local_name, model_hash, negotiated_json, synced_columns, server_name FROM g9_tables'),\n ...statementsOf(\"SELECT name FROM sqlite_master WHERE type = 'table'\"),\n ...statementsOf(\"SELECT m.name, p.name FROM sqlite_master AS m JOIN pragma_table_info(m.name) AS p WHERE m.type = 'table'\"),\n ...statementsOf(\"SELECT name FROM sqlite_master WHERE type = 'trigger'\"),\n ...statementsOf(\"SELECT (SELECT seq FROM sqlite_sequence WHERE name = 'g9_tables'), (SELECT max(tid) FROM g9_tables)\"),\n ]);\n const known = new Map<string, readonly (string | number | null)[]>();\n for (const row of registered?.rows ?? []) known.set(asString(row[1]), row as readonly (string | number | null)[]);\n const existingTables = new Set((tableNames?.rows ?? []).map((r) => asString(r[0]).toLowerCase()));\n const columnsByTable = new Map<string, Set<string>>();\n for (const row of columns?.rows ?? []) {\n const table = asString(row[0]).toLowerCase();\n let set = columnsByTable.get(table);\n if (!set) columnsByTable.set(table, (set = new Set<string>()));\n set.add(asString(row[1]).toLowerCase());\n }\n const triggerNames = new Set((triggers?.rows ?? []).map((r) => asString(r[0])));\n const counters = sequence?.rows[0] ?? [];\n let nextTid = Math.max(asNumber(counters[0]), asNumber(counters[1])) + 1;\n\n const batch = new G9StatementBatch(connection, Number.MAX_SAFE_INTEGER);\n const result: LocalTable[] = [];\n for (const table of models) {\n const hash = modelHash(table);\n const found = known.get(table.localName);\n let tid: number;\n let existingHash: string | null = null;\n let negotiatedJson: string | null = null;\n let syncedJson: string | null = null;\n const isNew = !found;\n if (found) {\n tid = asNumber(found[0]);\n existingHash = asString(found[2]);\n negotiatedJson = asOptionalString(found[3]);\n syncedJson = asOptionalString(found[4]);\n if (asString(found[5]) !== table.serverName) batch.add('UPDATE g9_tables SET server_name = $s WHERE tid = $t', { $s: table.serverName, $t: tid });\n } else {\n tid = nextTid++;\n batch.add(\"INSERT INTO g9_tables (tid, local_name, server_name, model_hash) VALUES ($t, $n, $s, '')\", { $t: tid, $n: table.localName, $s: table.serverName });\n }\n\n const exists = existingTables.has(table.localName.toLowerCase());\n if (!exists) {\n batch.add(createTable(table, this.options));\n } else {\n const existing = columnsByTable.get(table.localName.toLowerCase()) ?? new Set<string>();\n for (const column of table.columns) {\n if (existing.has(column.name.toLowerCase())) continue;\n batch.add('ALTER TABLE ' + quote(table.localName) + ' ADD COLUMN ' + columnDefinition(column, this.options));\n this.log('information', 20102, `Added column ${table.localName}.${column.name} from the client model`);\n }\n }\n for (const index of table.indexes) {\n batch.add(`CREATE ${index.unique ? 'UNIQUE ' : ''}INDEX IF NOT EXISTS ${quote(index.name)} ON ${quote(table.localName)} (${index.columns.map(quote).join(', ')})`);\n }\n\n const negotiated = readPersistedNegotiated(negotiatedJson);\n const captureWanted = !negotiated || negotiated.direction !== G9ESyncDirection.DownloadOnly;\n const has = (suffix: string): number => (triggerNames.has('g9_' + table.localName + '_' + suffix) ? 1 : 0);\n const triggerCount = has('ai') + has('au') + has('ad');\n const commandTriggerCount = has('ci') + has('cu') + has('cd');\n if (existingHash !== hash || (captureWanted && triggerCount !== 3) || commandTriggerCount !== 3) {\n batch.add(dropTriggers(table));\n if (captureWanted) batch.add(createTriggers(table, tid));\n batch.add(createCommandTriggers(table, tid));\n if (existingHash !== null && existingHash.length > 0 && existingHash !== hash) {\n // Column order may have changed: pending rows upload every column rather than trusting old mask bits.\n batch.add('UPDATE g9_rows SET dirty_mask = $m WHERE tid = $t AND dirty = 1', { $m: allColumnsMask(table.columns.length), $t: tid });\n }\n batch.add('UPDATE g9_tables SET model_hash = $h WHERE tid = $t', { $h: hash, $t: tid });\n }\n if (isNew && exists) {\n const localName = table.localName;\n batch.add(`INSERT OR IGNORE INTO g9_rows (tid, pk) SELECT $t, ${keyExpression(table, 'b')} FROM ${quote(localName)} AS b`, { $t: tid }, (results) => {\n const adopted = results[0]?.changes ?? 0;\n if (adopted > 0) this.log('information', 20103, `Adopted ${adopted} existing rows of ${localName} into change capture`);\n });\n }\n const synced = syncedJson === null ? [] : (JSON.parse(syncedJson) as string[]);\n result.push(new LocalTable(table, tid, negotiated, Array.isArray(synced) ? synced.map(String) : []));\n }\n await batch.flush();\n return result;\n }\n\n /** ADR-0067: a database restored from a backup or copied from another device gets a new identity. */\n private async _verifyIncarnation(connection: G9SqliteConnection): Promise<void> {\n const marker = this.options.incarnationMarker;\n if (!marker) return;\n const inDatabase = await meta(connection, 'incarnation');\n const inMarker = await marker.read();\n if (inDatabase !== null && inDatabase === inMarker) return;\n // The marker is written BEFORE the transaction commits; if that fails nothing is recorded and nothing is reset.\n const incarnation = guidToN(newGuid());\n if (!(await marker.write(incarnation))) {\n this.log('warning', 20106, 'The incarnation marker could not be read or written; restore detection is off for this run');\n return;\n }\n if (inDatabase === null) {\n // A database from before this check existed, or a brand-new one: adopt it.\n await setMeta(connection, 'incarnation', incarnation);\n return;\n }\n const pending = asNumber(await connection.scalar('SELECT count(*) FROM g9_rows WHERE dirty <> 0'));\n await setMeta(connection, 'incarnation', incarnation);\n await setMeta(connection, 'client_id', newGuid());\n await setMeta(connection, 'next_batch_id', '1');\n await connection.exec(\n \"DELETE FROM g9_meta WHERE key IN ('inflight_batch_id', 'inflight_max_seq'); UPDATE g9_commands SET batch_id = NULL WHERE state = 0; DELETE FROM g9_stage; DELETE FROM g9_stage_runs;\",\n );\n this.replicaIdentityWasReplaced = true;\n this.log(\n 'warning',\n 20105,\n `This database was restored or copied from another installation: it has a new client id and its push batch counter starts again. ${pending} pending row(s) were kept and upload as usual`,\n );\n }\n\n async getClientId(): Promise<string> {\n await this._open();\n const id = await meta(this.reader(), 'client_id');\n if (id === null) throw new Error('The store is not initialised.');\n return id;\n }\n\n // ================================================================ server state\n\n async getServerState(): Promise<G9ClientServerState> {\n await this._open();\n const connection = this.reader();\n const epoch = await meta(connection, 'epoch');\n const lastHello = await meta(connection, 'last_hello_utc');\n const offset = await meta(connection, 'server_offset_ms');\n const definitions = await meta(connection, 'definitions_json');\n const tables = await meta(connection, 'tables_json');\n const parsedTables = tables === null ? [] : (JSON.parse(tables) as unknown[]);\n return {\n epoch,\n lastHelloUtcMs: lastHello === null ? null : Number(lastHello),\n serverClockOffsetMs: offset === null ? 0 : Number(offset),\n definitions: readPersistedDefinitions(definitions),\n tables: Array.isArray(parsedTables) ? parsedTables.map((t) => readPersistedNegotiated(JSON.stringify(t)) as G9DtNegotiatedTable) : [],\n };\n }\n\n /**\n * Records a Hello (`SaveHello`): epoch, clock offset, definitions, every negotiated table and the capture each needs.\n * The .NET store writes table by table; through a bridged driver that was ~90 calls on EVERY run for AgriPad's 47\n * tables (LES-0055), so the writes go in ONE batch, in the same order, after one read for the only per-table\n * question (does a table with newly negotiated columns hold rows?). Same database.\n */\n async saveHello(hello: G9DtHelloResult): Promise<void> {\n const model = this.ensureInitialized();\n await this.writeLock.run(async () => {\n const connection = this.writer();\n const updates: { local: LocalTable; negotiated: G9DtNegotiatedTable; synced: string[] }[] = [];\n await connection.transaction('immediate', async () => {\n const batch = new G9StatementBatch(connection, this.options.statementsPerBatch);\n const metaUpsert = 'INSERT INTO g9_meta (key, value) VALUES ($k, $v) ON CONFLICT(key) DO UPDATE SET value = excluded.value';\n batch.add(metaUpsert, { $k: 'epoch', $v: hello.epoch });\n batch.add(metaUpsert, { $k: 'last_hello_utc', $v: String(nowMs()) });\n batch.add(metaUpsert, { $k: 'server_offset_ms', $v: String(Math.trunc(hello.serverTimeUtcMs - Date.now())) });\n batch.add(metaUpsert, { $k: 'definitions_json', $v: persistedJson(hello.definitions) });\n batch.add(metaUpsert, { $k: 'tables_json', $v: persistedJson(hello.tables) });\n // Kept per subscription: a caller who loses access stops being told the definition (ADR-0048).\n for (const definition of hello.definitions) {\n batch.add('UPDATE g9_subscriptions SET move_out_policy = $p WHERE name = $n', { $p: definition.moveOutPolicy, $n: definition.name });\n }\n\n // Which tables get new columns, and which of those already hold rows: one read for all of them.\n const resolved: { local: LocalTable; negotiated: G9DtNegotiatedTable; names: string[]; added: string[] }[] = [];\n for (const negotiated of hello.tables) {\n const clientTable = model.findByServerName(negotiated.name);\n const local = clientTable ? this.byLocal.get(clientTable.localName.toLowerCase()) : undefined;\n if (!local) continue;\n const names = negotiated.columns.map((c) => c.name);\n const added = local.negotiated === null ? [] : names.filter((n) => !local.syncedColumns.some((s) => s.toLowerCase() === n.toLowerCase()));\n resolved.push({ local, negotiated, names, added });\n }\n const askHolding = resolved.filter((r) => r.added.length > 0).map((r) => r.local.tid);\n const holding = new Set<number>();\n if (askHolding.length > 0) {\n const rows = await connection.query(\n 'SELECT DISTINCT tid FROM g9_rows WHERE deleted = 0 AND tid IN (SELECT value FROM json_each($tids))',\n { $tids: JSON.stringify(askHolding) },\n );\n for (const r of rows) holding.add(asNumber(r[0]));\n }\n\n for (const { local, negotiated, names, added } of resolved) {\n let synced: string[];\n if (local.negotiated === null) {\n synced = names;\n } else {\n synced = local.syncedColumns.slice();\n if (added.length > 0 && !holding.has(local.tid)) {\n for (const a of added) synced.push(a);\n }\n }\n batch.add('UPDATE g9_tables SET server_table_id = $s, negotiated_json = $j, synced_columns = $c WHERE tid = $t', {\n $s: negotiated.tableId,\n $j: persistedJson(negotiated),\n $c: persistedJson(synced),\n $t: local.tid,\n });\n if (negotiated.direction === G9ESyncDirection.DownloadOnly) {\n batch.add(dropTriggers(local.model));\n // A row marked as a local change in a download-only table can never be sent: it would stay pending for ever and hold\n // the server's updates off. The engine's capture cannot make one there (no triggers); rows imported from outside it\n // can. The server's copy wins. In the batch, not behind a read: the partial dirty index makes it free when there is\n // nothing to clear. (The C# twin, SaveHelloAsync, also logs the count as 20109.)\n batch.add('UPDATE g9_rows SET dirty = 0, dirty_mask = 0, rejected = 0 WHERE tid = $t AND dirty <> 0', { $t: local.tid });\n batch.add('DELETE FROM g9_rejections WHERE tid = $t', { $t: local.tid });\n } else if (local.negotiated && local.negotiated.direction === G9ESyncDirection.DownloadOnly) {\n batch.add(dropTriggers(local.model) + createTriggers(local.model, local.tid));\n }\n updates.push({ local, negotiated, synced });\n }\n await batch.flush();\n });\n for (const { local, negotiated, synced } of updates) {\n local.negotiated = negotiated;\n local.syncedColumns = synced;\n }\n const byServerId = new Map<number, LocalTable>();\n this.byLocal.forEach((t) => {\n if (t.negotiated) byServerId.set(t.negotiated.tableId, t);\n });\n this.byServerId = byServerId;\n });\n }\n\n async getPendingBackfills(): Promise<G9DtBackfillRequest[]> {\n this.ensureInitialized();\n const backfills: G9DtBackfillRequest[] = [];\n this.byLocal.forEach((table) => {\n if (!table.negotiated) return;\n const missing = table.negotiated.columns.map((c) => c.name).filter((n) => !table.syncedColumns.some((s) => s.toLowerCase() === n.toLowerCase()));\n if (missing.length > 0) backfills.push({ tableId: table.negotiated.tableId, columns: missing });\n });\n return backfills;\n }\n\n // ================================================================ subscriptions\n\n async getSubscriptions(): Promise<G9SyncSubscriptionRecord[]> {\n await this._open();\n return readSubscriptions(this.reader(), null);\n }\n\n async ensureSubscription(name: string, parameters: G9SyncParameters, ephemeral: boolean, ttlMs: number | null, adoptExistingRows: boolean): Promise<G9SyncSubscriptionRecord> {\n if (typeof name !== 'string' || name.trim() === '') throw new TypeError('A subscription name is required.');\n const key = G9SyncParameters.buildSubscriptionKey(name, parameters);\n await this._open();\n return this.writeLock.run(() =>\n this.writer().transaction('immediate', async () => {\n const connection = this.writer();\n const existing = await readSubscriptions(connection, key);\n if (existing.length > 0) return existing[0] as G9SyncSubscriptionRecord;\n let slot = EPHEMERAL_SLOT;\n if (!ephemeral) {\n const used = new Set((await connection.query('SELECT slot FROM g9_subscriptions WHERE ephemeral = 0')).map((r) => asNumber(r[0])));\n slot = -1;\n for (let s = 0; s < EPHEMERAL_SLOT; s++) {\n if (!used.has(s)) {\n slot = s;\n break;\n }\n }\n if (slot < 0) {\n throw new G9SyncException(G9SyncErrorCodes.LocalStoreError, 'At most 63 persistent subscriptions per database; declare per-item subscriptions Ephemeral(ttl) on the server.');\n }\n }\n const now = nowMs();\n await connection.exec(\n 'INSERT INTO g9_subscriptions (key, name, params, slot, ephemeral, ttl_seconds, state, created_utc, last_access_utc) VALUES ($k, $n, $p, $s, $e, $t, $st, $c, $c)',\n {\n $k: key,\n $n: name,\n $p: JSON.stringify(parameters.values),\n $s: slot,\n $e: ephemeral ? 1 : 0,\n $t: ttlMs === null ? null : Math.trunc(ttlMs / 1000),\n $st: adoptExistingRows ? G9ESubscriptionState.NeedsReconcile : G9ESubscriptionState.Active,\n $c: now,\n },\n );\n return (await readSubscriptions(connection, key))[0] as G9SyncSubscriptionRecord;\n }),\n );\n }\n\n removeSubscription(key: string, policy: G9EMoveOutPolicy): Promise<void> {\n return this._removeSubscription(key, policy, G9ERevocationReason.Unsubscribed, false, null);\n }\n\n async releaseSubscriptionRows(key: string): Promise<G9ApplyReport> {\n // The policy comes from the last definition the server announced for this subscription (ADR-0048).\n const report = new G9ApplyReport();\n await this._removeSubscription(key, null, G9ERevocationReason.AccessRevoked, true, report);\n return report;\n }\n\n private async _removeSubscription(key: string, policy: G9EMoveOutPolicy | null, reason: G9ERevocationReason, keepSubscription: boolean, report: G9ApplyReport | null): Promise<void> {\n this.ensureInitialized();\n await this.writeLock.run(() =>\n this.writer().transaction('immediate', async () => {\n const connection = this.writer();\n const record = (await readSubscriptions(connection, key))[0];\n if (!record) return;\n const effective = policy ?? record.moveOutPolicy ?? G9EMoveOutPolicy.Delete;\n await connection.exec('UPDATE g9_ctx SET applying = 1 WHERE id = 1');\n await connection.exec('DROP TABLE IF EXISTS temp.g9_affected; CREATE TEMP TABLE g9_affected (tid INTEGER NOT NULL, pk TEXT NOT NULL, PRIMARY KEY (tid, pk)) WITHOUT ROWID');\n if (record.ephemeral) {\n await connection.exec('INSERT INTO temp.g9_affected (tid, pk) SELECT tid, pk FROM g9_ephemeral_rows WHERE sub_key = $k', { $k: key });\n await connection.exec('DELETE FROM g9_ephemeral_rows WHERE sub_key = $k', { $k: key });\n await connection.exec(\n 'UPDATE g9_rows SET subs = subs & $n WHERE (tid, pk) IN (SELECT tid, pk FROM temp.g9_affected) AND NOT EXISTS (SELECT 1 FROM g9_ephemeral_rows e WHERE e.tid = g9_rows.tid AND e.pk = g9_rows.pk)',\n { $n: bit(EPHEMERAL_SLOT).not() },\n );\n } else {\n const b = bit(record.slot);\n await connection.exec('INSERT INTO temp.g9_affected (tid, pk) SELECT tid, pk FROM g9_rows WHERE (subs & $b) <> 0', { $b: b });\n await connection.exec('UPDATE g9_rows SET subs = subs & $n WHERE (subs & $b) <> 0', { $n: b.not(), $b: b });\n }\n if (effective === G9EMoveOutPolicy.Delete) {\n // Rows no other subscription holds go through the revocation policy (ADR-0026), pending changes included.\n const releasedSql = 'SELECT r.tid, r.pk FROM g9_rows r JOIN temp.g9_affected a ON a.tid = r.tid AND a.pk = r.pk WHERE r.subs = 0 AND r.deleted = 0';\n let removed = 0;\n if ((await apply.foreignTriggerNames(this, connection)).length === 0) {\n removed = await revocation.disposeReleasedRows(this, connection, releasedSql, {}, reason, key, report);\n } else {\n // A foreign trigger may write what the next row's decision reads: row by row, each decision after the last.\n const released = (await connection.query(releasedSql)).map((r) => ({ tid: asNumber(r[0]), key: asString(r[1]) }));\n for (const row of released) {\n const table = byTid(this, row.tid);\n // The .NET store advances its sequence for every released row of a known table, whether or not it moved.\n if (!table) continue;\n if (await revocation.disposeReleasedRow(this, connection, table, row.key, reason, key, report)) removed++;\n await connection.exec('UPDATE g9_clock SET seq = seq + 1 WHERE id = 1');\n }\n }\n this.log('information', 20104, `Removed subscription ${key}; deleted ${removed} rows no other subscription held`);\n }\n await connection.exec(\n keepSubscription\n ? 'UPDATE g9_subscriptions SET cursor = NULL, last_success_utc = NULL, last_reconcile_utc = NULL WHERE key = $k'\n : 'DELETE FROM g9_subscriptions WHERE key = $k',\n { $k: key },\n );\n await connection.exec('DROP TABLE temp.g9_affected; UPDATE g9_ctx SET applying = 0 WHERE id = 1');\n }),\n );\n }\n\n async updateSubscription(key: string, update: G9SubscriptionUpdate): Promise<void> {\n const sets: string[] = [];\n const params: { [name: string]: string | number | null } = { $k: key };\n if (update.cursor !== undefined && update.cursor !== null) {\n sets.push('cursor = $cursor');\n params.$cursor = update.cursor;\n }\n if (update.clearCursor) sets.push('cursor = NULL');\n if (update.definitionHash !== undefined && update.definitionHash !== null) {\n sets.push('definition_hash = $def');\n params.$def = update.definitionHash;\n }\n if (update.authHash !== undefined && update.authHash !== null) {\n sets.push('auth_hash = $auth');\n params.$auth = update.authHash;\n }\n if (update.state !== undefined && update.state !== null) {\n sets.push('state = $state');\n params.$state = update.state;\n }\n if (update.errorCode !== undefined && update.errorCode !== null) {\n sets.push('error_code = $error');\n params.$error = update.errorCode;\n }\n if (update.clearError) sets.push('error_code = NULL');\n const now = nowMs();\n if (update.succeeded) sets.push('last_success_utc = ' + now);\n if (update.reconciled) sets.push('last_reconcile_utc = ' + now);\n if (update.accessed) sets.push('last_access_utc = ' + now);\n if (sets.length === 0) return;\n await this._open();\n await this.writeLock.run(() => this.writer().exec('UPDATE g9_subscriptions SET ' + sets.join(', ') + ' WHERE key = $k', params));\n }\n\n async collectExpiredEphemeral(utcNowMs: number): Promise<number> {\n await this._open();\n const expired = (\n await this.reader().query(\n 'SELECT key FROM g9_subscriptions WHERE ephemeral = 1 AND ttl_seconds IS NOT NULL AND coalesce(last_access_utc, created_utc) + ttl_seconds * 1000 < $now',\n { $now: utcNowMs },\n )\n ).map((r) => asString(r[0]));\n for (const key of expired) await this._removeSubscription(key, G9EMoveOutPolicy.Delete, G9ERevocationReason.Expired, false, null);\n return expired.length;\n }\n\n // ================================================================ push\n\n buildPushBatch(tables: readonly G9DtNegotiatedTable[], maxRows: number, maxBytes: number): Promise<G9PushBatch | null> {\n return push.buildPushBatch(this, tables, maxRows, maxBytes);\n }\n\n forgetUploadedRows(localTable: string, keys: readonly string[] | null): Promise<number> {\n return push.forgetUploadedRows(this, localTable, keys);\n }\n\n applyPushResult(batch: G9PushBatch, result: G9DtPushResult, signal?: AbortSignal): Promise<G9ApplyReport> {\n return push.applyPushResult(this, batch, result, signal);\n }\n\n // ================================================================ pull\n\n async getStagedPull(): Promise<G9StagedPull | null> {\n await this._open();\n return query.getStagedPull(this, null);\n }\n\n async getStagedPullForGeneration(generation: string): Promise<G9StagedPull | null> {\n await this._open();\n return query.getStagedPull(this, generation);\n }\n\n beginStagedPull(pull: G9StagedPull): Promise<void> {\n return query.beginStagedPull(this, pull);\n }\n\n pruneStagedPulls(olderThanUtcMs: number, maxBytes: number, keepGeneration: string | null): Promise<number> {\n return query.pruneStagedPulls(this, olderThanUtcMs, maxBytes, keepGeneration);\n }\n\n discardAllStagedPulls(): Promise<number> {\n return query.discardAllStagedPulls(this);\n }\n\n stageChunk(runId: string, chunk: G9DtSyncChunk): Promise<void> {\n return query.stageChunk(this, runId, chunk, (connection) => apply.downloadDurability(this, connection));\n }\n\n getResumePoint(runId: string): Promise<G9ResumePoint> {\n return query.getResumePoint(this, runId);\n }\n\n applyStagedPull(runId: string, rowsApplied: ((rows: number) => void) | null, slices: ((slice: G9ApplySlice) => void) | null, signal?: AbortSignal): Promise<G9ApplyReport> {\n return apply.applyStagedPull(this, runId, rowsApplied, slices, query.readStagedRun, signal);\n }\n\n discardStagedPull(runId: string): Promise<void> {\n return query.discardStagedPull(this, runId);\n }\n\n // ================================================================ reconcile\n\n computeDigest(subscriptionKey: string, table: G9DtNegotiatedTable): Promise<G9DtTableDigest> {\n return query.computeDigest(this, subscriptionKey, table);\n }\n\n readLocalEntries(subscriptionKey: string, table: G9DtNegotiatedTable, buckets: ReadonlySet<number>, serverKeys: ReadonlySet<string>): Promise<G9LocalRowEntry[]> {\n return query.readLocalEntries(this, subscriptionKey, table, buckets, serverKeys);\n }\n\n applyReconcile(\n subscriptionKey: string,\n table: G9DtNegotiatedTable,\n fetchedFrames: readonly Uint8Array[],\n addMembership: readonly string[],\n moveOut: readonly string[],\n policy: G9EMoveOutPolicy,\n signal?: AbortSignal,\n ): Promise<G9ApplyReport> {\n return apply.applyReconcile(this, subscriptionKey, table, fetchedFrames, addMembership, moveOut, policy, signal);\n }\n\n // ================================================================ queries and maintenance\n\n getPendingSummary(): Promise<G9PendingSummary> {\n return query.getPendingSummary(this);\n }\n\n enqueueCommand(request: G9CommandRequest, applyLocally: ((writer: G9LocalCommandWriter, signal?: AbortSignal) => Promise<void>) | null, signal?: AbortSignal): Promise<G9LocalCommand> {\n return commands.enqueueCommand(this, request, applyLocally, signal);\n }\n\n /**\n * Records a command on a connection the APP owns (its own driver session, inside its own transaction or not), so the\n * command and the effects the app writes in `applyLocally` commit or roll back together (the .NET overload that takes the\n * app's `sqlite3` handle). The session must be open on this store's database file.\n */\n enqueueCommandOnSession(\n session: { driver: G9SqliteSyncStoreOptions['driver']; session: G9SessionToken; tx?: import('./driver.js').G9TxToken | null },\n request: G9CommandRequest,\n applyLocally: (() => Promise<void>) | null,\n ): Promise<G9LocalCommand> {\n this.ensureInitialized();\n const connection = new G9SqliteConnection(session.driver, session.session);\n connection.tx = session.tx ?? null;\n return commands.enqueueCommandOnConnection(connection, request, applyLocally);\n }\n\n getQuarantined(): Promise<G9QuarantinedRow[]> {\n return revocation.getQuarantined(this);\n }\n\n restoreQuarantined(localTable: string, key: string): Promise<number> {\n return revocation.restoreQuarantined(this, localTable, key);\n }\n\n discardQuarantined(localTable: string | null, key: string | null): Promise<number> {\n return revocation.discardQuarantined(this, localTable, key);\n }\n\n getRetained(): Promise<G9RetainedRow[]> {\n return revocation.getRetained(this);\n }\n\n reevaluateRetained(): Promise<number> {\n return revocation.reevaluateRetained(this);\n }\n\n getCommands(state: G9ELocalCommandState | null, limit: number): Promise<G9LocalCommand[]> {\n return commands.getCommands(this, state, limit);\n }\n\n readChangeFeed(localTable: string, afterSequence: number, limit: number): Promise<G9ChangeFeedEntry[]> {\n return query.readChangeFeed(this, localTable, afterSequence, limit);\n }\n\n getChangeSequence(): Promise<number> {\n return query.getChangeSequence(this);\n }\n\n getChangeFeedFloor(): Promise<number> {\n return query.getChangeFeedFloor(this);\n }\n\n getRejections(): Promise<G9SyncRejection[]> {\n return query.getRejections(this);\n }\n\n retryRejected(localTable: string | null, key: string | null): Promise<number> {\n return query.retryRejected(this, localTable, key);\n }\n\n markDirty(localTable: string, keys: readonly string[]): Promise<number> {\n return query.markDirty(this, localTable, keys);\n }\n\n adoptExistingRows(): Promise<number> {\n return query.adoptExistingRows(this);\n }\n\n saveRunReport(report: G9SyncRunReport, keep: number): Promise<void> {\n return query.saveRunReport(this, report, keep);\n }\n\n getRecentRunReports(count: number): Promise<G9SyncRunReport[]> {\n return query.getRecentRunReports(this, count);\n }\n\n getPhaseStatistics(): Promise<{ [key: string]: number }> {\n return query.getPhaseStatistics(this);\n }\n\n recordPhaseStatistics(samples: { [key: string]: number }): Promise<void> {\n return query.recordPhaseStatistics(this, samples);\n }\n\n purgeDeletedFeed(keep: number): Promise<number> {\n return query.purgeDeletedFeed(this, keep);\n }\n\n /** The triggers in the database that the library did not create (they keep trigger execution on during applies). */\n async getForeignTriggers(): Promise<string[]> {\n this.ensureInitialized();\n return apply.foreignTriggerNames(this, this.reader());\n }\n\n // ================================================================ recovery (ADR-0068)\n\n /** Runs SQLite's quick_check; an empty list means the file is sound. A file too damaged to check is one problem. */\n async checkIntegrity(): Promise<string[]> {\n const problems: string[] = [];\n try {\n await this._open();\n for (const r of await this.reader().query('PRAGMA quick_check(50)')) {\n const line = asString(r[0]);\n if (line.toLowerCase() !== 'ok') problems.push(line);\n }\n } catch (error) {\n problems.push(error instanceof Error ? error.message : String(error));\n }\n if (problems.length > 0) this.log('error', 20107, `The device database failed its integrity check with ${problems.length} problem(s); first: ${problems[0]}`);\n return problems;\n }\n\n /**\n * Hands every pending local change to `write`, one JSON line per row — `{\"table\":…,\"key\":…,\"deleted\":…,\"values\":{…}}` —\n * best effort: a row that cannot be read is listed with its key and no values. Nothing in the database changes.\n */\n async exportPendingChanges(write: (line: string) => void | Promise<void>): Promise<G9PendingExport> {\n this.ensureInitialized();\n const connection = this.reader();\n const pending = (await connection.query('SELECT tid, pk, dirty FROM g9_rows WHERE dirty <> 0 ORDER BY local_seq')).map((r) => ({\n tid: asNumber(r[0]),\n key: asString(r[1]),\n deleted: asNumber(r[2]) === 2,\n }));\n let rows = 0;\n let unreadable = 0;\n for (const row of pending) {\n const table = byTid(this, row.tid);\n if (!table) continue;\n let values: string | null = null;\n if (!row.deleted) {\n try {\n const read = await readLocalValues(connection, table, row.key);\n if (Object.keys(read).length > 0) values = serializeValues(read);\n } catch {\n // The page this row lives on is one of the damaged ones. Its key is still worth keeping.\n }\n if (values === null) unreadable++;\n }\n const line =\n '{\"table\":' + JSON.stringify(table.model.localName) + ',\"key\":' + JSON.stringify(row.key) + ',\"deleted\":' + (row.deleted ? 'true' : 'false') + (values === null ? '' : ',\"values\":' + values) + '}';\n await write(line);\n rows++;\n }\n if (rows > 0) this.log('warning', 20108, `Exported ${rows} pending row(s) (${unreadable} without readable values)`);\n return { rows, unreadable };\n }\n\n async dispose(): Promise<void> {\n const writer = this._writer;\n const reader = this._reader;\n this._writer = null;\n this._reader = null;\n this._opening = null;\n if (writer) {\n await writer.rollback();\n await this.options.driver.close(writer.session);\n }\n if (reader) await this.options.driver.close(reader.session);\n }\n}\n\n/** Long values the store exposes for tests and tools. */\nexport { G9Long };\n"]}
1
+ {"version":3,"file":"store.js","sourceRoot":"","sources":["../../src/sqlite/store.ts"],"names":[],"mappings":"AAAA,yHAAyH;AACzH,0HAA0H;AAC1H,sDAAsD;AACtD,OAAO,EAAE,gBAAgB,EAAE,gBAAgB,EAAE,MAAM,0BAA0B,CAAC;AAC9E,OAAO,EAAE,gBAAg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AAI,MAAM;YAAE,MAAM,IAAI,CAAC,OAAO,CAAC,MAAM,CAAC,KAAK,CAAC,MAAM,CAAC,OAAO,CAAC,CAAC;IAC9D,CAAC;CACF;AAED,yDAAyD;AACzD,OAAO,EAAE,MAAM,EAAE,CAAC","sourcesContent":["// Twin of G9SyncData.Client.Sqlite/G9CSqliteSyncStore.cs (+ .Incarnation.cs, .Recovery.cs): the SQLite implementation of\n// the client store. Every object it creates is the one the .NET store creates (AiGuides/08-Client-Sqlite.md), so the same\n// database file serves the MAUI app and the Lynx app.\nimport { G9EMoveOutPolicy, G9ESyncDirection } from '../abstractions/enums.js';\nimport { G9SyncErrorCodes, G9SyncException } from '../abstractions/errors.js';\nimport { guidToN, newGuid } from '../abstractions/guid.js';\nimport { G9Long } from '../abstractions/long.js';\nimport { G9SyncParameters } from '../abstractions/parameters.js';\nimport type { G9SyncClientModel, G9SyncClientTable } from '../client/model.js';\nimport type { G9SyncLogLevel } from '../client/runs.js';\nimport {\n G9ApplyReport,\n G9ERevocationReason,\n G9ESubscriptionState,\n type G9ApplySlice,\n type G9ChangeFeedEntry,\n type G9ChangeFeedKeyFilter,\n type G9ClientServerState,\n type G9CommandRequest,\n type G9ELocalCommandState,\n type G9LocalCommand,\n type G9LocalCommandWriter,\n type G9LocalRowEntry,\n type G9PendingSummary,\n type G9PushBatch,\n type G9QuarantinedRow,\n type G9ResumePoint,\n type G9RetainedRow,\n type G9StagedPull,\n type G9SubscriptionUpdate,\n type G9SyncClientStore,\n type G9SyncRejection,\n type G9SyncRunReport,\n type G9SyncSubscriptionRecord,\n} from '../client/storeTypes.js';\nimport type { G9DtBackfillRequest, G9DtHelloResult, G9DtNegotiatedTable, G9DtPushResult, G9DtSnapshotFileRequest, G9DtSyncChunk, G9DtTableDigest } from '../protocol/dtos.js';\nimport * as apply from './apply.js';\nimport * as commands from './commands.js';\nimport { asNumber, asOptionalString, asString, G9AsyncLock, G9SqliteConnection, G9StatementBatch, statementsOf } from './connection.js';\nimport type { G9SessionToken } from './driver.js';\nimport {\n byTid,\n LocalTable,\n logTo,\n meta,\n nowMs,\n persistedJson,\n readLocalValues,\n readPersistedDefinitions,\n readPersistedNegotiated,\n readSubscriptions,\n serializeValues,\n setMeta,\n type StoreInternals,\n} from './internals.js';\nimport { resolveStoreOptions, type G9ResolvedSqliteStoreOptions, type G9SqliteSyncStoreOptions } from './options.js';\nimport * as push from './push.js';\nimport * as query from './query.js';\nimport * as revocation from './revocation.js';\nimport { describeSnapshotFiles, sweepOrphanSnapshotFiles } from './snapshotFiles.js';\nimport { allColumnsMask, bit, columnDefinition, createCommandTriggers, createTable, createTriggers, dropTriggers, EPHEMERAL_SLOT, keyExpression, METADATA, modelHash, quote } from './sql.js';\n\n/** What exportPendingChanges managed to save (`G9CPendingExport`). */\nexport interface G9PendingExport {\n rows: number;\n unreadable: number;\n}\n\n/**\n * The SQLite client store over a G9SqliteDriver. Library writes are serialised in-process; app writes on other\n * connections are captured by triggers and wait on SQLite's busy timeout.\n */\nexport class G9SqliteSyncStore implements G9SyncClientStore, StoreInternals {\n readonly options: G9ResolvedSqliteStoreOptions;\n readonly writeLock = new G9AsyncLock();\n byLocal = new Map<string, LocalTable>();\n byServerId = new Map<number, LocalTable>();\n /** True when this initialisation found a database of another installation and gave it a new identity (ADR-0067). */\n replicaIdentityWasReplaced = false;\n\n private _model: G9SyncClientModel | null = null;\n private _writer: G9SqliteConnection | null = null;\n private _reader: G9SqliteConnection | null = null;\n private _opening: Promise<void> | null = null;\n\n constructor(options: G9SqliteSyncStoreOptions) {\n this.options = resolveStoreOptions(options);\n }\n\n // ================================================================ internals\n\n writer(): G9SqliteConnection {\n if (!this._writer) throw new Error('The SQLite sync store is not open; call initialize first.');\n return this._writer;\n }\n\n reader(): G9SqliteConnection {\n if (!this._reader) throw new Error('The SQLite sync store is not open; call initialize first.');\n return this._reader;\n }\n\n ensureInitialized(): G9SyncClientModel {\n if (!this._model) throw new Error('The SQLite sync store is not initialised; call initialize first.');\n return this._model;\n }\n\n log(level: G9SyncLogLevel, eventId: number, message: string, error?: unknown): void {\n logTo(this.options.logger, level, eventId, message, error);\n }\n\n private async _open(): Promise<void> {\n if (this._writer && this._reader) return;\n if (!this._opening) {\n this._opening = (async () => {\n const driver = this.options.driver;\n const pragmas = { busyTimeoutMs: this.options.busyTimeoutMs, foreignKeys: false };\n const writerSession: G9SessionToken = await driver.open({ path: this.options.databasePath, create: true, pragmas });\n const writer = new G9SqliteConnection(driver, writerSession);\n await this._configure(writer);\n if (this.options.useWriteAheadLog) await writer.query('PRAGMA journal_mode = WAL');\n const readerSession: G9SessionToken = await driver.open({ path: this.options.databasePath, create: true, pragmas });\n const reader = new G9SqliteConnection(driver, readerSession);\n await this._configure(reader);\n this._writer = writer;\n this._reader = reader;\n })();\n this._opening.catch(() => (this._opening = null));\n }\n await this._opening;\n }\n\n /** The PRAGMAs the .NET store sets on every connection it opens. */\n private async _configure(connection: G9SqliteConnection): Promise<void> {\n await connection.exec(\n 'PRAGMA busy_timeout = ' + this.options.busyTimeoutMs + '; PRAGMA foreign_keys = OFF; PRAGMA journal_size_limit = ' + this.options.walSizeLimitBytes + ';',\n );\n }\n\n // ================================================================ initialise\n\n async initialize(model: G9SyncClientModel): Promise<void> {\n if (!model) throw new TypeError('A model is required.');\n await this._open();\n await this.writeLock.run(async () => {\n const connection = this.writer();\n const tables: LocalTable[] = [];\n await connection.transaction('immediate', async () => {\n await connection.exec(METADATA);\n if (asNumber(await connection.scalar(\"SELECT count(*) FROM pragma_table_info('g9_ctx') WHERE name = 'command_id'\")) === 0) {\n // Stores created before commands existed (ADR-0025).\n await connection.exec('ALTER TABLE g9_ctx ADD COLUMN command_id TEXT NULL');\n }\n if (asNumber(await connection.scalar(\"SELECT count(*) FROM pragma_table_info('g9_stage_runs') WHERE name = 'generation'\")) === 0) {\n // Stores created before stages were validated on resume (ADR-0046): a stage in flight is dropped and replanned.\n await connection.exec('ALTER TABLE g9_stage_runs ADD COLUMN generation TEXT NULL');\n await connection.exec('ALTER TABLE g9_stage_runs ADD COLUMN stage_seq INTEGER NOT NULL DEFAULT 0');\n await connection.exec('DELETE FROM g9_stage; DELETE FROM g9_stage_runs;');\n }\n if (asNumber(await connection.scalar(\"SELECT count(*) FROM pragma_table_info('g9_stage_runs') WHERE name = 'from_cursors_json'\")) === 0) {\n await connection.exec('ALTER TABLE g9_stage_runs ADD COLUMN from_cursors_json TEXT NULL');\n }\n if (asNumber(await connection.scalar(\"SELECT count(*) FROM pragma_table_info('g9_subscriptions') WHERE name = 'move_out_policy'\")) === 0) {\n await connection.exec('ALTER TABLE g9_subscriptions ADD COLUMN move_out_policy INTEGER NULL');\n }\n if ((await meta(connection, 'client_id')) === null) await setMeta(connection, 'client_id', newGuid());\n if ((await meta(connection, 'next_batch_id')) === null) await setMeta(connection, 'next_batch_id', '1');\n await this._verifyIncarnation(connection);\n for (const table of await this._provisionTables(connection, model.tables)) tables.push(table);\n });\n this._model = model;\n this.byLocal = new Map(tables.map((t) => [t.model.localName.toLowerCase(), t] as [string, LocalTable]));\n this.byServerId = new Map(tables.filter((t) => t.negotiated !== null).map((t) => [(t.negotiated as G9DtNegotiatedTable).tableId, t] as [number, LocalTable]));\n await sweepOrphanSnapshotFiles(this, connection);\n this.log('information', 20101, `G9SyncData SQLite store initialised with ${tables.length} tables`);\n });\n }\n\n /** The store's offer to receive snapshot files (ADR-0072); null without a `snapshotFiles` sink. */\n describeSnapshotFiles(negotiated: readonly G9DtNegotiatedTable[]): G9DtSnapshotFileRequest | null {\n if (!this._model) return null;\n return describeSnapshotFiles(this, negotiated);\n }\n\n /**\n * Provisions every model table (`ProvisionTable` of the .NET store, for all tables at once).\n *\n * The .NET store asks SQLite per table (~6 statements each) because a statement costs nothing in process. Through a\n * bridged driver every call is a round trip (~5.7 ms on the Android emulator: 296 calls = 1.7 s on EVERY app start, 534\n * on the first), so this reads everything the decisions need in ONE call — g9_tables, the tables, their columns, the\n * triggers and the AUTOINCREMENT counter — and runs the resulting statements in ONE batch, in exactly the order the\n * per-table path runs them. New tables get their tid explicitly (the value AUTOINCREMENT would hand out, in model\n * order), so the triggers can be written in the same batch. Same objects, same rows, same order (PARITY.md).\n */\n private async _provisionTables(connection: G9SqliteConnection, models: readonly G9SyncClientTable[]): Promise<LocalTable[]> {\n const [registered, tableNames, columns, triggers, sequence] = await connection.runStatements([\n ...statementsOf('SELECT tid, local_name, model_hash, negotiated_json, synced_columns, server_name FROM g9_tables'),\n ...statementsOf(\"SELECT name FROM sqlite_master WHERE type = 'table'\"),\n ...statementsOf(\"SELECT m.name, p.name FROM sqlite_master AS m JOIN pragma_table_info(m.name) AS p WHERE m.type = 'table'\"),\n ...statementsOf(\"SELECT name FROM sqlite_master WHERE type = 'trigger'\"),\n ...statementsOf(\"SELECT (SELECT seq FROM sqlite_sequence WHERE name = 'g9_tables'), (SELECT max(tid) FROM g9_tables)\"),\n ]);\n const known = new Map<string, readonly (string | number | null)[]>();\n for (const row of registered?.rows ?? []) known.set(asString(row[1]), row as readonly (string | number | null)[]);\n const existingTables = new Set((tableNames?.rows ?? []).map((r) => asString(r[0]).toLowerCase()));\n const columnsByTable = new Map<string, Set<string>>();\n for (const row of columns?.rows ?? []) {\n const table = asString(row[0]).toLowerCase();\n let set = columnsByTable.get(table);\n if (!set) columnsByTable.set(table, (set = new Set<string>()));\n set.add(asString(row[1]).toLowerCase());\n }\n const triggerNames = new Set((triggers?.rows ?? []).map((r) => asString(r[0])));\n const counters = sequence?.rows[0] ?? [];\n let nextTid = Math.max(asNumber(counters[0]), asNumber(counters[1])) + 1;\n\n const batch = new G9StatementBatch(connection, Number.MAX_SAFE_INTEGER);\n const result: LocalTable[] = [];\n for (const table of models) {\n const hash = modelHash(table);\n const found = known.get(table.localName);\n let tid: number;\n let existingHash: string | null = null;\n let negotiatedJson: string | null = null;\n let syncedJson: string | null = null;\n const isNew = !found;\n if (found) {\n tid = asNumber(found[0]);\n existingHash = asString(found[2]);\n negotiatedJson = asOptionalString(found[3]);\n syncedJson = asOptionalString(found[4]);\n if (asString(found[5]) !== table.serverName) batch.add('UPDATE g9_tables SET server_name = $s WHERE tid = $t', { $s: table.serverName, $t: tid });\n } else {\n tid = nextTid++;\n batch.add(\"INSERT INTO g9_tables (tid, local_name, server_name, model_hash) VALUES ($t, $n, $s, '')\", { $t: tid, $n: table.localName, $s: table.serverName });\n }\n\n const exists = existingTables.has(table.localName.toLowerCase());\n if (!exists) {\n batch.add(createTable(table, this.options));\n } else {\n const existing = columnsByTable.get(table.localName.toLowerCase()) ?? new Set<string>();\n for (const column of table.columns) {\n if (existing.has(column.name.toLowerCase())) continue;\n batch.add('ALTER TABLE ' + quote(table.localName) + ' ADD COLUMN ' + columnDefinition(column, this.options));\n this.log('information', 20102, `Added column ${table.localName}.${column.name} from the client model`);\n }\n }\n for (const index of table.indexes) {\n batch.add(`CREATE ${index.unique ? 'UNIQUE ' : ''}INDEX IF NOT EXISTS ${quote(index.name)} ON ${quote(table.localName)} (${index.columns.map(quote).join(', ')})`);\n }\n\n const negotiated = readPersistedNegotiated(negotiatedJson);\n const captureWanted = !negotiated || negotiated.direction !== G9ESyncDirection.DownloadOnly;\n const has = (suffix: string): number => (triggerNames.has('g9_' + table.localName + '_' + suffix) ? 1 : 0);\n const triggerCount = has('ai') + has('au') + has('ad');\n const commandTriggerCount = has('ci') + has('cu') + has('cd');\n if (existingHash !== hash || (captureWanted && triggerCount !== 3) || commandTriggerCount !== 3) {\n batch.add(dropTriggers(table));\n if (captureWanted) batch.add(createTriggers(table, tid));\n batch.add(createCommandTriggers(table, tid));\n if (existingHash !== null && existingHash.length > 0 && existingHash !== hash) {\n // Column order may have changed: pending rows upload every column rather than trusting old mask bits.\n batch.add('UPDATE g9_rows SET dirty_mask = $m WHERE tid = $t AND dirty = 1', { $m: allColumnsMask(table.columns.length), $t: tid });\n }\n batch.add('UPDATE g9_tables SET model_hash = $h WHERE tid = $t', { $h: hash, $t: tid });\n }\n if (isNew && exists) {\n const localName = table.localName;\n batch.add(`INSERT OR IGNORE INTO g9_rows (tid, pk) SELECT $t, ${keyExpression(table, 'b')} FROM ${quote(localName)} AS b`, { $t: tid }, (results) => {\n const adopted = results[0]?.changes ?? 0;\n if (adopted > 0) this.log('information', 20103, `Adopted ${adopted} existing rows of ${localName} into change capture`);\n });\n }\n const synced = syncedJson === null ? [] : (JSON.parse(syncedJson) as string[]);\n result.push(new LocalTable(table, tid, negotiated, Array.isArray(synced) ? synced.map(String) : []));\n }\n await batch.flush();\n return result;\n }\n\n /** ADR-0067: a database restored from a backup or copied from another device gets a new identity. */\n private async _verifyIncarnation(connection: G9SqliteConnection): Promise<void> {\n const marker = this.options.incarnationMarker;\n if (!marker) return;\n const inDatabase = await meta(connection, 'incarnation');\n const inMarker = await marker.read();\n if (inDatabase !== null && inDatabase === inMarker) return;\n // The marker is written BEFORE the transaction commits; if that fails nothing is recorded and nothing is reset.\n const incarnation = guidToN(newGuid());\n if (!(await marker.write(incarnation))) {\n this.log('warning', 20106, 'The incarnation marker could not be read or written; restore detection is off for this run');\n return;\n }\n if (inDatabase === null) {\n // A database from before this check existed, or a brand-new one: adopt it.\n await setMeta(connection, 'incarnation', incarnation);\n return;\n }\n const pending = asNumber(await connection.scalar('SELECT count(*) FROM g9_rows WHERE dirty <> 0'));\n await setMeta(connection, 'incarnation', incarnation);\n await setMeta(connection, 'client_id', newGuid());\n await setMeta(connection, 'next_batch_id', '1');\n await connection.exec(\n \"DELETE FROM g9_meta WHERE key IN ('inflight_batch_id', 'inflight_max_seq'); UPDATE g9_commands SET batch_id = NULL WHERE state = 0; DELETE FROM g9_stage; DELETE FROM g9_stage_runs;\",\n );\n this.replicaIdentityWasReplaced = true;\n this.log(\n 'warning',\n 20105,\n `This database was restored or copied from another installation: it has a new client id and its push batch counter starts again. ${pending} pending row(s) were kept and upload as usual`,\n );\n }\n\n async getClientId(): Promise<string> {\n await this._open();\n const id = await meta(this.reader(), 'client_id');\n if (id === null) throw new Error('The store is not initialised.');\n return id;\n }\n\n // ================================================================ server state\n\n async getServerState(): Promise<G9ClientServerState> {\n await this._open();\n const connection = this.reader();\n const epoch = await meta(connection, 'epoch');\n const lastHello = await meta(connection, 'last_hello_utc');\n const offset = await meta(connection, 'server_offset_ms');\n const definitions = await meta(connection, 'definitions_json');\n const tables = await meta(connection, 'tables_json');\n const parsedTables = tables === null ? [] : (JSON.parse(tables) as unknown[]);\n return {\n epoch,\n lastHelloUtcMs: lastHello === null ? null : Number(lastHello),\n serverClockOffsetMs: offset === null ? 0 : Number(offset),\n definitions: readPersistedDefinitions(definitions),\n tables: Array.isArray(parsedTables) ? parsedTables.map((t) => readPersistedNegotiated(JSON.stringify(t)) as G9DtNegotiatedTable) : [],\n };\n }\n\n /**\n * Records a Hello (`SaveHello`): epoch, clock offset, definitions, every negotiated table and the capture each needs.\n * The .NET store writes table by table; through a bridged driver that was ~90 calls on EVERY run for AgriPad's 47\n * tables (LES-0055), so the writes go in ONE batch, in the same order, after one read for the only per-table\n * question (does a table with newly negotiated columns hold rows?). Same database.\n */\n async saveHello(hello: G9DtHelloResult): Promise<void> {\n const model = this.ensureInitialized();\n await this.writeLock.run(async () => {\n const connection = this.writer();\n const updates: { local: LocalTable; negotiated: G9DtNegotiatedTable; synced: string[] }[] = [];\n await connection.transaction('immediate', async () => {\n const batch = new G9StatementBatch(connection, this.options.statementsPerBatch);\n const metaUpsert = 'INSERT INTO g9_meta (key, value) VALUES ($k, $v) ON CONFLICT(key) DO UPDATE SET value = excluded.value';\n batch.add(metaUpsert, { $k: 'epoch', $v: hello.epoch });\n batch.add(metaUpsert, { $k: 'last_hello_utc', $v: String(nowMs()) });\n batch.add(metaUpsert, { $k: 'server_offset_ms', $v: String(Math.trunc(hello.serverTimeUtcMs - Date.now())) });\n batch.add(metaUpsert, { $k: 'definitions_json', $v: persistedJson(hello.definitions) });\n batch.add(metaUpsert, { $k: 'tables_json', $v: persistedJson(hello.tables) });\n // Kept per subscription: a caller who loses access stops being told the definition (ADR-0048).\n for (const definition of hello.definitions) {\n batch.add('UPDATE g9_subscriptions SET move_out_policy = $p WHERE name = $n', { $p: definition.moveOutPolicy, $n: definition.name });\n }\n\n // Which tables get new columns, and which of those already hold rows: one read for all of them.\n const resolved: { local: LocalTable; negotiated: G9DtNegotiatedTable; names: string[]; added: string[] }[] = [];\n for (const negotiated of hello.tables) {\n const clientTable = model.findByServerName(negotiated.name);\n const local = clientTable ? this.byLocal.get(clientTable.localName.toLowerCase()) : undefined;\n if (!local) continue;\n const names = negotiated.columns.map((c) => c.name);\n const added = local.negotiated === null ? [] : names.filter((n) => !local.syncedColumns.some((s) => s.toLowerCase() === n.toLowerCase()));\n resolved.push({ local, negotiated, names, added });\n }\n const askHolding = resolved.filter((r) => r.added.length > 0).map((r) => r.local.tid);\n const holding = new Set<number>();\n if (askHolding.length > 0) {\n const rows = await connection.query(\n 'SELECT DISTINCT tid FROM g9_rows WHERE deleted = 0 AND tid IN (SELECT value FROM json_each($tids))',\n { $tids: JSON.stringify(askHolding) },\n );\n for (const r of rows) holding.add(asNumber(r[0]));\n }\n\n for (const { local, negotiated, names, added } of resolved) {\n let synced: string[];\n if (local.negotiated === null) {\n synced = names;\n } else {\n synced = local.syncedColumns.slice();\n if (added.length > 0 && !holding.has(local.tid)) {\n for (const a of added) synced.push(a);\n }\n }\n batch.add('UPDATE g9_tables SET server_table_id = $s, negotiated_json = $j, synced_columns = $c WHERE tid = $t', {\n $s: negotiated.tableId,\n $j: persistedJson(negotiated),\n $c: persistedJson(synced),\n $t: local.tid,\n });\n if (negotiated.direction === G9ESyncDirection.DownloadOnly) {\n batch.add(dropTriggers(local.model));\n // A row marked as a local change in a download-only table can never be sent: it would stay pending for ever and hold\n // the server's updates off. The engine's capture cannot make one there (no triggers); rows imported from outside it\n // can. The server's copy wins. In the batch, not behind a read: the partial dirty index makes it free when there is\n // nothing to clear. (The C# twin, SaveHelloAsync, also logs the count as 20109.)\n batch.add('UPDATE g9_rows SET dirty = 0, dirty_mask = 0, rejected = 0 WHERE tid = $t AND dirty <> 0', { $t: local.tid });\n batch.add('DELETE FROM g9_rejections WHERE tid = $t', { $t: local.tid });\n } else if (local.negotiated && local.negotiated.direction === G9ESyncDirection.DownloadOnly) {\n batch.add(dropTriggers(local.model) + createTriggers(local.model, local.tid));\n }\n updates.push({ local, negotiated, synced });\n }\n await batch.flush();\n });\n for (const { local, negotiated, synced } of updates) {\n local.negotiated = negotiated;\n local.syncedColumns = synced;\n }\n const byServerId = new Map<number, LocalTable>();\n this.byLocal.forEach((t) => {\n if (t.negotiated) byServerId.set(t.negotiated.tableId, t);\n });\n this.byServerId = byServerId;\n });\n }\n\n async getPendingBackfills(): Promise<G9DtBackfillRequest[]> {\n this.ensureInitialized();\n const backfills: G9DtBackfillRequest[] = [];\n this.byLocal.forEach((table) => {\n if (!table.negotiated) return;\n const missing = table.negotiated.columns.map((c) => c.name).filter((n) => !table.syncedColumns.some((s) => s.toLowerCase() === n.toLowerCase()));\n if (missing.length > 0) backfills.push({ tableId: table.negotiated.tableId, columns: missing });\n });\n return backfills;\n }\n\n // ================================================================ subscriptions\n\n async getSubscriptions(): Promise<G9SyncSubscriptionRecord[]> {\n await this._open();\n return readSubscriptions(this.reader(), null);\n }\n\n async ensureSubscription(name: string, parameters: G9SyncParameters, ephemeral: boolean, ttlMs: number | null, adoptExistingRows: boolean): Promise<G9SyncSubscriptionRecord> {\n if (typeof name !== 'string' || name.trim() === '') throw new TypeError('A subscription name is required.');\n const key = G9SyncParameters.buildSubscriptionKey(name, parameters);\n await this._open();\n return this.writeLock.run(() =>\n this.writer().transaction('immediate', async () => {\n const connection = this.writer();\n const existing = await readSubscriptions(connection, key);\n if (existing.length > 0) return existing[0] as G9SyncSubscriptionRecord;\n let slot = EPHEMERAL_SLOT;\n if (!ephemeral) {\n const used = new Set((await connection.query('SELECT slot FROM g9_subscriptions WHERE ephemeral = 0')).map((r) => asNumber(r[0])));\n slot = -1;\n for (let s = 0; s < EPHEMERAL_SLOT; s++) {\n if (!used.has(s)) {\n slot = s;\n break;\n }\n }\n if (slot < 0) {\n throw new G9SyncException(G9SyncErrorCodes.LocalStoreError, 'At most 63 persistent subscriptions per database; declare per-item subscriptions Ephemeral(ttl) on the server.');\n }\n }\n const now = nowMs();\n await connection.exec(\n 'INSERT INTO g9_subscriptions (key, name, params, slot, ephemeral, ttl_seconds, state, created_utc, last_access_utc) VALUES ($k, $n, $p, $s, $e, $t, $st, $c, $c)',\n {\n $k: key,\n $n: name,\n $p: JSON.stringify(parameters.values),\n $s: slot,\n $e: ephemeral ? 1 : 0,\n $t: ttlMs === null ? null : Math.trunc(ttlMs / 1000),\n $st: adoptExistingRows ? G9ESubscriptionState.NeedsReconcile : G9ESubscriptionState.Active,\n $c: now,\n },\n );\n return (await readSubscriptions(connection, key))[0] as G9SyncSubscriptionRecord;\n }),\n );\n }\n\n removeSubscription(key: string, policy: G9EMoveOutPolicy): Promise<void> {\n return this._removeSubscription(key, policy, G9ERevocationReason.Unsubscribed, false, null);\n }\n\n async releaseSubscriptionRows(key: string): Promise<G9ApplyReport> {\n // The policy comes from the last definition the server announced for this subscription (ADR-0048).\n const report = new G9ApplyReport();\n await this._removeSubscription(key, null, G9ERevocationReason.AccessRevoked, true, report);\n return report;\n }\n\n private async _removeSubscription(key: string, policy: G9EMoveOutPolicy | null, reason: G9ERevocationReason, keepSubscription: boolean, report: G9ApplyReport | null): Promise<void> {\n this.ensureInitialized();\n await this.writeLock.run(() =>\n this.writer().transaction('immediate', async () => {\n const connection = this.writer();\n const record = (await readSubscriptions(connection, key))[0];\n if (!record) return;\n const effective = policy ?? record.moveOutPolicy ?? G9EMoveOutPolicy.Delete;\n await connection.exec('UPDATE g9_ctx SET applying = 1 WHERE id = 1');\n await connection.exec('DROP TABLE IF EXISTS temp.g9_affected; CREATE TEMP TABLE g9_affected (tid INTEGER NOT NULL, pk TEXT NOT NULL, PRIMARY KEY (tid, pk)) WITHOUT ROWID');\n if (record.ephemeral) {\n await connection.exec('INSERT INTO temp.g9_affected (tid, pk) SELECT tid, pk FROM g9_ephemeral_rows WHERE sub_key = $k', { $k: key });\n await connection.exec('DELETE FROM g9_ephemeral_rows WHERE sub_key = $k', { $k: key });\n await connection.exec(\n 'UPDATE g9_rows SET subs = subs & $n WHERE (tid, pk) IN (SELECT tid, pk FROM temp.g9_affected) AND NOT EXISTS (SELECT 1 FROM g9_ephemeral_rows e WHERE e.tid = g9_rows.tid AND e.pk = g9_rows.pk)',\n { $n: bit(EPHEMERAL_SLOT).not() },\n );\n } else {\n const b = bit(record.slot);\n await connection.exec('INSERT INTO temp.g9_affected (tid, pk) SELECT tid, pk FROM g9_rows WHERE (subs & $b) <> 0', { $b: b });\n await connection.exec('UPDATE g9_rows SET subs = subs & $n WHERE (subs & $b) <> 0', { $n: b.not(), $b: b });\n }\n if (effective === G9EMoveOutPolicy.Delete) {\n // Rows no other subscription holds go through the revocation policy (ADR-0026), pending changes included.\n const releasedSql = 'SELECT r.tid, r.pk FROM g9_rows r JOIN temp.g9_affected a ON a.tid = r.tid AND a.pk = r.pk WHERE r.subs = 0 AND r.deleted = 0';\n let removed = 0;\n if ((await apply.foreignTriggerNames(this, connection)).length === 0) {\n removed = await revocation.disposeReleasedRows(this, connection, releasedSql, {}, reason, key, report);\n } else {\n // A foreign trigger may write what the next row's decision reads: row by row, each decision after the last.\n const released = (await connection.query(releasedSql)).map((r) => ({ tid: asNumber(r[0]), key: asString(r[1]) }));\n for (const row of released) {\n const table = byTid(this, row.tid);\n // The .NET store advances its sequence for every released row of a known table, whether or not it moved.\n if (!table) continue;\n if (await revocation.disposeReleasedRow(this, connection, table, row.key, reason, key, report)) removed++;\n await connection.exec('UPDATE g9_clock SET seq = seq + 1 WHERE id = 1');\n }\n }\n this.log('information', 20104, `Removed subscription ${key}; deleted ${removed} rows no other subscription held`);\n }\n await connection.exec(\n keepSubscription\n ? 'UPDATE g9_subscriptions SET cursor = NULL, last_success_utc = NULL, last_reconcile_utc = NULL WHERE key = $k'\n : 'DELETE FROM g9_subscriptions WHERE key = $k',\n { $k: key },\n );\n await connection.exec('DROP TABLE temp.g9_affected; UPDATE g9_ctx SET applying = 0 WHERE id = 1');\n }),\n );\n }\n\n async updateSubscription(key: string, update: G9SubscriptionUpdate): Promise<void> {\n const sets: string[] = [];\n const params: { [name: string]: string | number | null } = { $k: key };\n if (update.cursor !== undefined && update.cursor !== null) {\n sets.push('cursor = $cursor');\n params.$cursor = update.cursor;\n }\n if (update.clearCursor) sets.push('cursor = NULL');\n if (update.definitionHash !== undefined && update.definitionHash !== null) {\n sets.push('definition_hash = $def');\n params.$def = update.definitionHash;\n }\n if (update.authHash !== undefined && update.authHash !== null) {\n sets.push('auth_hash = $auth');\n params.$auth = update.authHash;\n }\n if (update.state !== undefined && update.state !== null) {\n sets.push('state = $state');\n params.$state = update.state;\n }\n if (update.errorCode !== undefined && update.errorCode !== null) {\n sets.push('error_code = $error');\n params.$error = update.errorCode;\n }\n if (update.clearError) sets.push('error_code = NULL');\n const now = nowMs();\n if (update.succeeded) sets.push('last_success_utc = ' + now);\n if (update.reconciled) sets.push('last_reconcile_utc = ' + now);\n if (update.accessed) sets.push('last_access_utc = ' + now);\n if (sets.length === 0) return;\n await this._open();\n await this.writeLock.run(() => this.writer().exec('UPDATE g9_subscriptions SET ' + sets.join(', ') + ' WHERE key = $k', params));\n }\n\n async collectExpiredEphemeral(utcNowMs: number): Promise<number> {\n await this._open();\n const expired = (\n await this.reader().query(\n 'SELECT key FROM g9_subscriptions WHERE ephemeral = 1 AND ttl_seconds IS NOT NULL AND coalesce(last_access_utc, created_utc) + ttl_seconds * 1000 < $now',\n { $now: utcNowMs },\n )\n ).map((r) => asString(r[0]));\n for (const key of expired) await this._removeSubscription(key, G9EMoveOutPolicy.Delete, G9ERevocationReason.Expired, false, null);\n return expired.length;\n }\n\n // ================================================================ push\n\n buildPushBatch(tables: readonly G9DtNegotiatedTable[], maxRows: number, maxBytes: number): Promise<G9PushBatch | null> {\n return push.buildPushBatch(this, tables, maxRows, maxBytes);\n }\n\n forgetUploadedRows(localTable: string, keys: readonly string[] | null): Promise<number> {\n return push.forgetUploadedRows(this, localTable, keys);\n }\n\n applyPushResult(batch: G9PushBatch, result: G9DtPushResult, signal?: AbortSignal): Promise<G9ApplyReport> {\n return push.applyPushResult(this, batch, result, signal);\n }\n\n // ================================================================ pull\n\n async getStagedPull(): Promise<G9StagedPull | null> {\n await this._open();\n return query.getStagedPull(this, null);\n }\n\n async getStagedPullForGeneration(generation: string): Promise<G9StagedPull | null> {\n await this._open();\n return query.getStagedPull(this, generation);\n }\n\n beginStagedPull(pull: G9StagedPull): Promise<void> {\n return query.beginStagedPull(this, pull);\n }\n\n pruneStagedPulls(olderThanUtcMs: number, maxBytes: number, keepGeneration: string | null): Promise<number> {\n return query.pruneStagedPulls(this, olderThanUtcMs, maxBytes, keepGeneration);\n }\n\n discardAllStagedPulls(): Promise<number> {\n return query.discardAllStagedPulls(this);\n }\n\n stageChunk(runId: string, chunk: G9DtSyncChunk): Promise<void> {\n return query.stageChunk(this, runId, chunk, (connection) => apply.downloadDurability(this, connection));\n }\n\n getResumePoint(runId: string): Promise<G9ResumePoint> {\n return query.getResumePoint(this, runId);\n }\n\n applyStagedPull(runId: string, rowsApplied: ((rows: number) => void) | null, slices: ((slice: G9ApplySlice) => void) | null, signal?: AbortSignal): Promise<G9ApplyReport> {\n return apply.applyStagedPull(this, runId, rowsApplied, slices, query.readStagedRun, signal);\n }\n\n discardStagedPull(runId: string): Promise<void> {\n return query.discardStagedPull(this, runId);\n }\n\n // ================================================================ reconcile\n\n computeDigest(subscriptionKey: string, table: G9DtNegotiatedTable): Promise<G9DtTableDigest> {\n return query.computeDigest(this, subscriptionKey, table);\n }\n\n readLocalEntries(subscriptionKey: string, table: G9DtNegotiatedTable, buckets: ReadonlySet<number>, serverKeys: ReadonlySet<string>): Promise<G9LocalRowEntry[]> {\n return query.readLocalEntries(this, subscriptionKey, table, buckets, serverKeys);\n }\n\n applyReconcile(\n subscriptionKey: string,\n table: G9DtNegotiatedTable,\n fetchedFrames: readonly Uint8Array[],\n addMembership: readonly string[],\n moveOut: readonly string[],\n policy: G9EMoveOutPolicy,\n signal?: AbortSignal,\n ): Promise<G9ApplyReport> {\n return apply.applyReconcile(this, subscriptionKey, table, fetchedFrames, addMembership, moveOut, policy, signal);\n }\n\n // ================================================================ queries and maintenance\n\n getPendingSummary(): Promise<G9PendingSummary> {\n return query.getPendingSummary(this);\n }\n\n enqueueCommand(request: G9CommandRequest, applyLocally: ((writer: G9LocalCommandWriter, signal?: AbortSignal) => Promise<void>) | null, signal?: AbortSignal): Promise<G9LocalCommand> {\n return commands.enqueueCommand(this, request, applyLocally, signal);\n }\n\n /**\n * Records a command on a connection the APP owns (its own driver session, inside its own transaction or not), so the\n * command and the effects the app writes in `applyLocally` commit or roll back together (the .NET overload that takes the\n * app's `sqlite3` handle). The session must be open on this store's database file.\n */\n enqueueCommandOnSession(\n session: { driver: G9SqliteSyncStoreOptions['driver']; session: G9SessionToken; tx?: import('./driver.js').G9TxToken | null },\n request: G9CommandRequest,\n applyLocally: (() => Promise<void>) | null,\n ): Promise<G9LocalCommand> {\n this.ensureInitialized();\n const connection = new G9SqliteConnection(session.driver, session.session);\n connection.tx = session.tx ?? null;\n return commands.enqueueCommandOnConnection(connection, request, applyLocally);\n }\n\n getQuarantined(): Promise<G9QuarantinedRow[]> {\n return revocation.getQuarantined(this);\n }\n\n restoreQuarantined(localTable: string, key: string): Promise<number> {\n return revocation.restoreQuarantined(this, localTable, key);\n }\n\n discardQuarantined(localTable: string | null, key: string | null): Promise<number> {\n return revocation.discardQuarantined(this, localTable, key);\n }\n\n getRetained(): Promise<G9RetainedRow[]> {\n return revocation.getRetained(this);\n }\n\n reevaluateRetained(): Promise<number> {\n return revocation.reevaluateRetained(this);\n }\n\n getCommands(state: G9ELocalCommandState | null, limit: number): Promise<G9LocalCommand[]> {\n return commands.getCommands(this, state, limit);\n }\n\n readChangeFeed(localTable: string, afterSequence: number, limit: number): Promise<G9ChangeFeedEntry[]> {\n return query.readChangeFeed(this, localTable, afterSequence, limit);\n }\n\n readChangeFeedFiltered(localTable: string, afterSequence: number, limit: number, keyFilter: G9ChangeFeedKeyFilter): Promise<G9ChangeFeedEntry[]> {\n return query.readChangeFeedFiltered(this, localTable, afterSequence, limit, keyFilter);\n }\n\n getChangeSequence(): Promise<number> {\n return query.getChangeSequence(this);\n }\n\n getChangeFeedFloor(): Promise<number> {\n return query.getChangeFeedFloor(this);\n }\n\n getRejections(): Promise<G9SyncRejection[]> {\n return query.getRejections(this);\n }\n\n retryRejected(localTable: string | null, key: string | null): Promise<number> {\n return query.retryRejected(this, localTable, key);\n }\n\n markDirty(localTable: string, keys: readonly string[]): Promise<number> {\n return query.markDirty(this, localTable, keys);\n }\n\n adoptExistingRows(): Promise<number> {\n return query.adoptExistingRows(this);\n }\n\n saveRunReport(report: G9SyncRunReport, keep: number): Promise<void> {\n return query.saveRunReport(this, report, keep);\n }\n\n getRecentRunReports(count: number): Promise<G9SyncRunReport[]> {\n return query.getRecentRunReports(this, count);\n }\n\n getPhaseStatistics(): Promise<{ [key: string]: number }> {\n return query.getPhaseStatistics(this);\n }\n\n recordPhaseStatistics(samples: { [key: string]: number }): Promise<void> {\n return query.recordPhaseStatistics(this, samples);\n }\n\n purgeDeletedFeed(keep: number): Promise<number> {\n return query.purgeDeletedFeed(this, keep);\n }\n\n /** The triggers in the database that the library did not create (they keep trigger execution on during applies). */\n async getForeignTriggers(): Promise<string[]> {\n this.ensureInitialized();\n return apply.foreignTriggerNames(this, this.reader());\n }\n\n // ================================================================ recovery (ADR-0068)\n\n /** Runs SQLite's quick_check; an empty list means the file is sound. A file too damaged to check is one problem. */\n async checkIntegrity(): Promise<string[]> {\n const problems: string[] = [];\n try {\n await this._open();\n for (const r of await this.reader().query('PRAGMA quick_check(50)')) {\n const line = asString(r[0]);\n if (line.toLowerCase() !== 'ok') problems.push(line);\n }\n } catch (error) {\n problems.push(error instanceof Error ? error.message : String(error));\n }\n if (problems.length > 0) this.log('error', 20107, `The device database failed its integrity check with ${problems.length} problem(s); first: ${problems[0]}`);\n return problems;\n }\n\n /**\n * Hands every pending local change to `write`, one JSON line per row — `{\"table\":…,\"key\":…,\"deleted\":…,\"values\":{…}}` —\n * best effort: a row that cannot be read is listed with its key and no values. Nothing in the database changes.\n */\n async exportPendingChanges(write: (line: string) => void | Promise<void>): Promise<G9PendingExport> {\n this.ensureInitialized();\n const connection = this.reader();\n const pending = (await connection.query('SELECT tid, pk, dirty FROM g9_rows WHERE dirty <> 0 ORDER BY local_seq')).map((r) => ({\n tid: asNumber(r[0]),\n key: asString(r[1]),\n deleted: asNumber(r[2]) === 2,\n }));\n let rows = 0;\n let unreadable = 0;\n for (const row of pending) {\n const table = byTid(this, row.tid);\n if (!table) continue;\n let values: string | null = null;\n if (!row.deleted) {\n try {\n const read = await readLocalValues(connection, table, row.key);\n if (Object.keys(read).length > 0) values = serializeValues(read);\n } catch {\n // The page this row lives on is one of the damaged ones. Its key is still worth keeping.\n }\n if (values === null) unreadable++;\n }\n const line =\n '{\"table\":' + JSON.stringify(table.model.localName) + ',\"key\":' + JSON.stringify(row.key) + ',\"deleted\":' + (row.deleted ? 'true' : 'false') + (values === null ? '' : ',\"values\":' + values) + '}';\n await write(line);\n rows++;\n }\n if (rows > 0) this.log('warning', 20108, `Exported ${rows} pending row(s) (${unreadable} without readable values)`);\n return { rows, unreadable };\n }\n\n async dispose(): Promise<void> {\n const writer = this._writer;\n const reader = this._reader;\n this._writer = null;\n this._reader = null;\n this._opening = null;\n if (writer) {\n await writer.rollback();\n await this.options.driver.close(writer.session);\n }\n if (reader) await this.options.driver.close(reader.session);\n }\n}\n\n/** Long values the store exposes for tests and tools. */\nexport { G9Long };\n"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@g9tm/syncdata",
3
- "version": "1.3.0",
3
+ "version": "1.4.0",
4
4
  "description": "TypeScript twin of the G9SyncData .NET client for Lynx, Node and browsers: the sync engine, the G9RowBatch protocol, the SQLite client store (same schema as the .NET store) and the SignalR transport.",
5
5
  "license": "MIT",
6
6
  "author": "Iman Kari (G9TM)",
@@ -73,7 +73,7 @@
73
73
  "prepack": "npm run build"
74
74
  },
75
75
  "peerDependencies": {
76
- "@g9tm/signalr-supernetcore-client": "^2.10.1",
76
+ "@g9tm/signalr-supernetcore-client": "^2.11.0",
77
77
  "@microsoft/signalr": "^10.0.0",
78
78
  "@microsoft/signalr-protocol-msgpack": "^10.0.0",
79
79
  "@msgpack/msgpack": "^2.8.0"
@@ -93,7 +93,7 @@
93
93
  }
94
94
  },
95
95
  "devDependencies": {
96
- "@g9tm/signalr-supernetcore-client": "2.10.1",
96
+ "@g9tm/signalr-supernetcore-client": "2.11.0",
97
97
  "@microsoft/signalr": "^10.0.11",
98
98
  "@microsoft/signalr-protocol-msgpack": "^10.0.11",
99
99
  "@msgpack/msgpack": "2.8.0",