@g9tm/syncdata 1.5.3 → 1.5.5

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.
@@ -438,6 +438,7 @@ export class G9SyncEngine {
438
438
  let modelProblems = [];
439
439
  const synced = [];
440
440
  let pushed = 0;
441
+ let accepted = 0;
441
442
  let rejected = 0;
442
443
  let conflicts = 0;
443
444
  let downloaded = 0;
@@ -513,6 +514,7 @@ export class G9SyncEngine {
513
514
  try {
514
515
  const totals = await this._pushAll(negotiated, subscriptions, hello.maxPushRows, hello.maxPushBytes, tracker, changes, ct);
515
516
  pushed = totals.pushed;
517
+ accepted = totals.accepted;
516
518
  rejected = totals.rejected;
517
519
  conflicts = totals.conflicts;
518
520
  }
@@ -715,6 +717,7 @@ export class G9SyncEngine {
715
717
  outcome,
716
718
  error,
717
719
  pushed,
720
+ accepted,
718
721
  rejected,
719
722
  conflicts,
720
723
  downloaded,
@@ -817,6 +820,7 @@ export class G9SyncEngine {
817
820
  }
818
821
  async _pushAll(negotiated, subscriptions, serverMaxRows, serverMaxBytes, tracker, changes, ct) {
819
822
  let pushed = 0;
823
+ let accepted = 0;
820
824
  let rejected = 0;
821
825
  let conflicts = 0;
822
826
  const references = subscriptions.map(toSubscriptionRef);
@@ -864,6 +868,9 @@ export class G9SyncEngine {
864
868
  if (report.upserts + report.deletes > 0)
865
869
  this._raiseRowsApplied(report, G9ESyncPhase.Pushing);
866
870
  pushed += batch.rowCount + batch.commands.length;
871
+ // What the server TOOK (its acknowledgement), not "sent minus refused": a row refused on the device (too large) is in
872
+ // `rejected` but was never sent (LES-0071).
873
+ accepted += report.accepted + report.commandsCompleted;
867
874
  rejected += result.rejections.length;
868
875
  conflicts += result.conflicts.length;
869
876
  tracker.report(pushed);
@@ -878,7 +885,7 @@ export class G9SyncEngine {
878
885
  if (batchRows < targetRows)
879
886
  batchRows = Math.min(targetRows, batchRows * 2);
880
887
  }
881
- return { pushed, rejected, conflicts };
888
+ return { pushed, accepted, rejected, conflicts };
882
889
  }
883
890
  async _download(runId, plan, tracker, ct) {
884
891
  var _a;
@@ -1 +1 @@
1
- {"version":3,"file":"engine.js","sourceRoot":"","sources":["../../src/client/engine.ts"],"names":[],"mappings":"AAAA,qHAAqH;AACrH,oHAAoH;AACpH,OAAO,EAAE,gBAAgB,EAAE,gBAAgB,EAAE,MAAM,0BAA0B,CAAC;AAC9E,OAAO,EAAE,gBAAgB,EAAE,eAAe,EAAE,eAAe,EAAE,MAAM,2BAA2B,CAAC;AAC/F,OAAO,EAAE,OAAO,EAAE,OAAO,EAAE,MAAM,yBAAyB,CAAC;AAC3D,OAAO,EAAE,gBAAgB,EAAE,cAAc,EAAE,MAAM,+BAA+B,CAAC;AAEjF,OAAO,EAAE,KAAK,EAAE,WAAW,EAAE,OAAO,EAAE,MAAM,sBAAsB,CAAC;AACnE,OAAO,EAAE,MAAM,EAAE,KAAK,EAAE,MAAM,uBAAuB,CAAC;AACtD,OAAO,EAAE,UAAU,EAAE,MAAM,qBAAqB,CAAC;AACjD,OAAO,EACL,eAAe,EACf,qBAAqB,EAYrB,oBAAoB,GACrB,MAAM,qBAAqB,CAAC;AAC7B,OAAO,EAAE,YAAY,EAAE,MAAM,gCAAgC,CAAC;AAE9D,OAAO,EAAE,YAAY,EAAE,qBAAqB,EAAE,SAAS,EAAE,MAAM,eAAe,CAAC;AAC/E,OAAO,EACL,cAAc,EACd,eAAe,EACf,SAAS,EACT,WAAW,EACX,oBAAoB,EACpB,gBAAgB,EAChB,aAAa,EACb,cAAc,EACd,WAAW,EACX,YAAY,EACZ,gBAAgB,EAChB,oBAAoB,EACpB,cAAc,GAWf,MAAM,WAAW,CAAC;AACnB,OAAO,EACL,aAAa,EACb,oBAAoB,EACpB,iBAAiB,EAIjB,2BAA2B,GAa5B,MAAM,iBAAiB,CAAC;AAGzB,MAAM,eAAe,GAAG,YAAY,CAAC;AACrC,MAAM,aAAa,GAAG,UAAU,CAAC;AACjC,MAAM,mBAAmB,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CAAC,GAAG,QAAQ,GAAG,CAAC,CAAC,OAAO,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,IAAI,CAAC,GAAG,CAAC,GAAG,IAAI,CAAC;IACjH,OAAO,KAAK,CAAC,MAAM,CAAC,UAAU,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;AACzC,CAAC;AAED,SAAS,UAAU,CAAC,MAAc;IAChC,QAAQ,MAAM,EAAE,CAAC;QACf,KAAK,qBAAqB,CAAC,OAAO;YAChC,OAAO,gBAAgB,CAAC,mBAAmB,CAAC;QAC9C,KAAK,qBAAqB,CAAC,SAAS;YAClC,OAAO,gBAAgB,CAAC,qBAAqB,CAAC;QAChD;YACE,OAAO,gBAAgB,CAAC,iBAAiB,CAAC;IAC9C,CAAC;AACH,CAAC;AAED,SAAS,OAAO,CAAI,KAAmB,EAAE,IAAY;IACnD,MAAM,GAAG,GAAU,EAAE,CAAC;IACtB,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,KAAK,CAAC,MAAM,EAAE,CAAC,IAAI,IAAI;QAAE,GAAG,CAAC,IAAI,CAAC,KAAK,CAAC,KAAK,CAAC,CAAC,EAAE,CAAC,GAAG,IAAI,CAAC,CAAC,CAAC;IAChF,OAAO,GAAG,CAAC;AACb,CAAC;AAED,KAAK,SAAS,CAAC,CAAC,QAAQ,CAAC,KAAkB;IACzC,IAAI,QAAQ,GAAG,CAAC,CAAC;IACjB,KAAK,MAAM,KAAK,IAAI,KAAK,CAAC,MAAM;QAAE,MAAM,EAAE,QAAQ,EAAE,QAAQ,EAAE,EAAE,OAAO,EAAE,KAAK,EAAE,QAAQ,EAAE,CAAC,EAAE,OAAO,EAAE,KAAK,EAAE,CAAC;AAChH,CAAC","sourcesContent":["// Twin of G9SyncData.Client/G9CSyncEngine.cs, .Execution.cs and .Reconcile.cs: one engine per local database, with a\r\n// prioritised run queue (status queries never wait for a running sync) and background runs that yield to user runs.\r\nimport { G9EMoveOutPolicy, G9ESyncDirection } from '../abstractions/enums.js';\r\nimport { G9SyncErrorCodes, G9SyncException, isSyncException } from '../abstractions/errors.js';\r\nimport { guidToN, newGuid } from '../abstractions/guid.js';\r\nimport { G9SyncParameters, compareOrdinal } from '../abstractions/parameters.js';\r\nimport type { G9Long } from '../abstractions/long.js';\r\nimport { delay, linkSignals, onAbort } from '../internal/abort.js';\r\nimport { sha256, toHex } from '../internal/sha256.js';\r\nimport { utf8Encode } from '../internal/utf8.js';\r\nimport {\r\n G9EPullPartKind,\r\n G9ESubscriptionAction,\r\n type G9DtChangesAvailable,\r\n type G9DtHelloResult,\r\n type G9DtNegotiatedTable,\r\n type G9DtPullPlan,\r\n type G9DtPushRequest,\r\n type G9DtPushResult,\r\n type G9DtReconcileRequest,\r\n type G9DtReconcileSummary,\r\n type G9DtSubscriptionDefinition,\r\n type G9DtSubscriptionState,\r\n type G9DtSyncChunk,\r\n syncErrorToException,\r\n} from '../protocol/dtos.js';\r\nimport { openRowBatch } from '../protocol/rowBatch/reader.js';\r\nimport type { G9SyncClientModel } from './model.js';\r\nimport { G9ESyncPhase, G9SyncProgressTracker, phaseName } from './progress.js';\r\nimport {\r\n G9ESyncOutcome,\r\n G9ESyncPriority,\r\n G9SyncRun,\r\n canCoalesce,\r\n describeModelProblem,\r\n isTransientError,\r\n makeRunResult,\r\n normalizeError,\r\n outcomeName,\r\n priorityName,\r\n requestSignature,\r\n resolveEngineOptions,\r\n resolveRequest,\r\n type G9ResolvedEngineOptions,\r\n type G9ResolvedSyncRequest,\r\n type G9RowsAppliedEvent,\r\n type G9SubscriptionOptions,\r\n type G9SyncEngineOptions,\r\n type G9SyncHealth,\r\n type G9SyncLogLevel,\r\n type G9SyncModelProblem,\r\n type G9SyncRequest,\r\n type G9SyncRunResult,\r\n} from './runs.js';\r\nimport {\r\n G9ApplyReport,\r\n G9ESubscriptionState,\r\n toSubscriptionRef,\r\n type G9ApplySlice,\r\n type G9ChangeFeedEntry,\r\n type G9ChangeFeedKeyFilter,\r\n validateChangeFeedKeyFilter,\r\n type G9LocalCommand,\r\n type G9LocalCommandWriter,\r\n type G9ELocalCommandState,\r\n type G9LocalRowEntry,\r\n type G9PendingSummary,\r\n type G9PushBatch,\r\n type G9QuarantinedRow,\r\n type G9RetainedRow,\r\n type G9SyncClientStore,\r\n type G9SyncRejection,\r\n type G9SyncRunReport,\r\n type G9SyncSubscriptionRecord,\r\n} from './storeTypes.js';\r\nimport type { G9SyncTransport } from './transport.js';\r\n\r\nconst STAT_CONNECTING = 'Connecting';\r\nconst STAT_PLANNING = 'Planning';\r\nconst STAT_PUSH_PER_K_ROW = 'PushPerKRow';\r\nconst STAT_DOWNLOAD_PER_K_ROW = 'DownloadPerKRow';\r\nconst STAT_APPLY_PER_K_ROW = 'ApplyPerKRow';\r\nconst STAT_RECONCILE_PER_SUBSCRIPTION = 'ReconcilePerSubscription';\r\n\r\ninterface QueuedRun {\r\n run: G9SyncRun;\r\n priority: number;\r\n order: number;\r\n}\r\n\r\n/**\r\n * The client sync engine (`G9CSyncEngine`): one per local database. Owns a prioritised run queue, so status queries\r\n * never wait for a running sync and background runs yield to user runs.\r\n */\r\nexport class G9SyncEngine {\r\n readonly model: G9SyncClientModel;\r\n private readonly _store: G9SyncClientStore;\r\n private readonly _transport: G9SyncTransport;\r\n private readonly _options: G9ResolvedEngineOptions;\r\n private readonly _lifetime = linkSignals();\r\n private readonly _queue: QueuedRun[] = [];\r\n private readonly _pokedTables: { [lower: string]: string } = {};\r\n private readonly _rowsAppliedListeners: ((event: G9RowsAppliedEvent) => void)[] = [];\r\n private readonly _runCompletedListeners: ((result: G9SyncRunResult) => void)[] = [];\r\n private readonly _unsubscribePokes: () => void;\r\n\r\n private _initialized = false;\r\n private _initializing: Promise<void> | null = null;\r\n private _clientId = '';\r\n private _order = 0;\r\n private _current: G9SyncRun | null = null;\r\n private _suppressions = 0;\r\n private _autoTimer: ReturnType<typeof setInterval> | null = null;\r\n private _pokeTimer: ReturnType<typeof setTimeout> | null = null;\r\n private _wake: (() => void) | null = null;\r\n private _worker: Promise<void> | null = null;\r\n private _disposed = false;\r\n /** The model problems last logged, so the warning is said once per distinct set (ADR-0061). */\r\n private _reportedModelProblems: string | null = null;\r\n\r\n constructor(store: G9SyncClientStore, transport: G9SyncTransport, model: G9SyncClientModel, options?: G9SyncEngineOptions) {\r\n if (!store) throw new TypeError('A store is required.');\r\n if (!transport) throw new TypeError('A transport is required.');\r\n if (!model) throw new TypeError('A model is required.');\r\n this._store = store;\r\n this._transport = transport;\r\n this.model = model;\r\n this._options = resolveEngineOptions(options);\r\n this._unsubscribePokes = transport.onChangesAvailable((changes) => this._onChangesAvailable(changes));\r\n }\r\n\r\n get clientId(): string {\r\n if (!this._initialized) throw new Error('Call initialize first.');\r\n return this._clientId;\r\n }\r\n\r\n get isRunning(): boolean {\r\n return this._current !== null;\r\n }\r\n\r\n get queuedRuns(): number {\r\n return this._queue.length;\r\n }\r\n\r\n get isBackgroundSuppressed(): boolean {\r\n return this._suppressions > 0;\r\n }\r\n\r\n /** Raised after rows were written locally (download, reconciliation or canonical push results). Returns the unsubscribe function. */\r\n onRowsApplied(listener: (event: G9RowsAppliedEvent) => void): () => void {\r\n this._rowsAppliedListeners.push(listener);\r\n return () => remove(this._rowsAppliedListeners, listener);\r\n }\r\n\r\n onRunCompleted(listener: (result: G9SyncRunResult) => void): () => void {\r\n this._runCompletedListeners.push(listener);\r\n return () => remove(this._runCompletedListeners, listener);\r\n }\r\n\r\n /** Provisions local tables and capture, and starts the run worker. Idempotent. */\r\n initialize(signal?: AbortSignal): Promise<void> {\r\n if (this._initialized) return Promise.resolve();\r\n if (!this._initializing) {\r\n this._initializing = (async () => {\r\n try {\r\n await this._store.initialize(this.model, signal);\r\n this._clientId = await this._store.getClientId(signal);\r\n this._initialized = true;\r\n this._worker = this._workerLoop();\r\n } finally {\r\n if (!this._initialized) this._initializing = null;\r\n }\r\n })();\r\n }\r\n return this._initializing;\r\n }\r\n\r\n // ================================================================ subscriptions\r\n\r\n /** Adds (or returns) a subscription. Its rows arrive on the next run that includes it. */\r\n async subscribe(name: string, parameters?: G9SyncParameters | null, options?: G9SubscriptionOptions | null, signal?: AbortSignal): Promise<G9SyncSubscriptionRecord> {\r\n if (typeof name !== 'string' || name.trim() === '') throw new TypeError('A subscription name is required.');\r\n await this.initialize(signal);\r\n const state = await this._store.getServerState(signal);\r\n const definition = state.definitions.find((d) => d.name === name) ?? null;\r\n const ephemeral = options?.ephemeral ?? definition?.ephemeral ?? false;\r\n const ttlMs = options?.ttlMs ?? (definition && definition.ephemeral && definition.ttlSeconds > 0 ? definition.ttlSeconds * 1000 : null);\r\n const record = await this._store.ensureSubscription(name, parameters ?? new G9SyncParameters(), ephemeral, ttlMs, options?.adoptExistingRows ?? false, signal);\r\n await this._store.updateSubscription(record.key, { accessed: true }, signal);\r\n return record;\r\n }\r\n\r\n /** Removes a subscription; rows no other subscription holds follow the server's move-out policy. */\r\n async unsubscribe(name: string, parameters?: G9SyncParameters | null, signal?: AbortSignal): Promise<void> {\r\n await this.initialize(signal);\r\n const state = await this._store.getServerState(signal);\r\n const policy = state.definitions.find((d) => d.name === name)?.moveOutPolicy ?? G9EMoveOutPolicy.Delete;\r\n await this._store.removeSubscription(G9SyncParameters.buildSubscriptionKey(name, parameters ?? null), policy, signal);\r\n }\r\n\r\n async getSubscriptions(signal?: AbortSignal): Promise<G9SyncSubscriptionRecord[]> {\r\n await this.initialize(signal);\r\n return this._store.getSubscriptions(signal);\r\n }\r\n\r\n // ================================================================ runs\r\n\r\n /** Queues a run. Identical plain requests already waiting are coalesced into one run. */\r\n run(request?: G9SyncRequest | null): G9SyncRun {\r\n if (!this._initialized) throw new Error('Call initialize first.');\r\n const resolved = resolveRequest(request);\r\n if (canCoalesce(resolved)) {\r\n const signature = requestSignature(resolved);\r\n for (const queued of this._queue) {\r\n const r = queued.run;\r\n if (!r.isStarted && canCoalesce(r.request) && r.request.priority === resolved.priority && requestSignature(r.request) === signature) return r;\r\n }\r\n }\r\n const run = new G9SyncRun(resolved);\r\n this._queue.push({ run, priority: resolved.priority, order: this._order++ });\r\n const current = this._current;\r\n let preempted: G9SyncRun | null = null;\r\n if (current !== null && current.request.priority === G9ESyncPriority.Background && resolved.priority > G9ESyncPriority.Background) {\r\n current.preempted = true;\r\n preempted = current;\r\n }\r\n this._signal();\r\n if (preempted) {\r\n preempted.cancel();\r\n this._log('information', 20001, `Background run ${preempted.runId} pre-empted by run ${run.runId}`);\r\n }\r\n return run;\r\n }\r\n\r\n /** Queues a run and awaits its result. */\r\n sync(request?: G9SyncRequest | null): Promise<G9SyncRunResult> {\r\n return this.run(request).completion;\r\n }\r\n\r\n /** While the returned scope is alive, background runs are skipped. Call the returned function to end it. */\r\n suppressBackground(): () => void {\r\n this._suppressions++;\r\n let done = false;\r\n return () => {\r\n if (done) return;\r\n done = true;\r\n this._suppressions--;\r\n };\r\n }\r\n\r\n /** Queues a background push+pull of every non-heavy subscription on a fixed interval. */\r\n startAutomaticSync(intervalMs: number): void {\r\n if (!(intervalMs > 0)) throw new RangeError('The interval must be positive.');\r\n this.stopAutomaticSync();\r\n this._autoTimer = setInterval(() => this._tryQueueBackground(null), intervalMs);\r\n }\r\n\r\n stopAutomaticSync(): void {\r\n if (this._autoTimer !== null) {\r\n clearInterval(this._autoTimer);\r\n this._autoTimer = null;\r\n }\r\n }\r\n\r\n // ================================================================ queries\r\n\r\n /**\r\n * Records a command (ADR-0025): the server executes the handler registered for `name` on the next push, once, in\r\n * device order. `applyLocally` writes its local effects immediately, in the same transaction.\r\n */\r\n async executeCommand(\r\n name: string,\r\n payloadJson: string,\r\n applyLocally?: ((writer: G9LocalCommandWriter, signal?: AbortSignal) => Promise<void>) | null,\r\n version = 1,\r\n signal?: AbortSignal,\r\n ): Promise<G9LocalCommand> {\r\n if (typeof name !== 'string' || name.trim() === '') throw new TypeError('A command name is required.');\r\n if (typeof payloadJson !== 'string') throw new TypeError('The payload JSON is required.');\r\n await this.initialize(signal);\r\n return this._store.enqueueCommand({ name, version, payload: payloadJson }, applyLocally ?? null, signal);\r\n }\r\n\r\n /** Frees space taken by an UPLOAD-ONLY table: removes uploaded rows without uploading a delete. */\r\n async forgetUploadedRows(localTable: string, keys?: readonly string[] | null, signal?: AbortSignal): Promise<number> {\r\n await this.initialize(signal);\r\n return this._store.forgetUploadedRows(localTable, keys ?? null, signal);\r\n }\r\n\r\n async getCommands(state?: G9ELocalCommandState | null, limit = 200, signal?: AbortSignal): Promise<G9LocalCommand[]> {\r\n await this.initialize(signal);\r\n return this._store.getCommands(state ?? null, limit, signal);\r\n }\r\n\r\n async getPendingSummary(signal?: AbortSignal): Promise<G9PendingSummary> {\r\n await this.initialize(signal);\r\n return this._store.getPendingSummary(signal);\r\n }\r\n\r\n async getRejections(signal?: AbortSignal): Promise<G9SyncRejection[]> {\r\n await this.initialize(signal);\r\n return this._store.getRejections(signal);\r\n }\r\n\r\n async getQuarantined(signal?: AbortSignal): Promise<G9QuarantinedRow[]> {\r\n await this.initialize(signal);\r\n return this._store.getQuarantined(signal);\r\n }\r\n\r\n async restoreQuarantined(localTable: string, key: string, signal?: AbortSignal): Promise<number> {\r\n await this.initialize(signal);\r\n return this._store.restoreQuarantined(localTable, key, signal);\r\n }\r\n\r\n /** Throws away every staged pull, so the next run plans afresh. Returns whether there was one. */\r\n async discardStagedPull(signal?: AbortSignal): Promise<boolean> {\r\n await this.initialize(signal);\r\n return (await this._store.discardAllStagedPulls(signal)) > 0;\r\n }\r\n\r\n async discardQuarantined(localTable?: string | null, key?: string | null, signal?: AbortSignal): Promise<number> {\r\n await this.initialize(signal);\r\n return this._store.discardQuarantined(localTable ?? null, key ?? null, signal);\r\n }\r\n\r\n async getRetained(signal?: AbortSignal): Promise<G9RetainedRow[]> {\r\n await this.initialize(signal);\r\n return this._store.getRetained(signal);\r\n }\r\n\r\n async retryRejected(localTable?: string | null, key?: string | null, signal?: AbortSignal): Promise<number> {\r\n await this.initialize(signal);\r\n return this._store.retryRejected(localTable ?? null, key ?? null, signal);\r\n }\r\n\r\n /**\r\n * Gives up the local change of rejected rows and takes the server's copy (LES-0070, .NET `RevertRejectedAsync`): a row the server\r\n * never had is removed locally, any other is fetched again by the next run with `forceReconcile` - run one after this. Nothing is\r\n * uploaded. Omitted arguments widen the scope.\r\n */\r\n async revertRejected(localTable?: string | null, key?: string | null, signal?: AbortSignal): Promise<number> {\r\n await this.initialize(signal);\r\n return this._store.revertRejected(localTable ?? null, key ?? null, signal);\r\n }\r\n\r\n async readChangeFeed(localTable: string, afterSequence: number, limit = 1000, signal?: AbortSignal): Promise<G9ChangeFeedEntry[]> {\r\n await this.initialize(signal);\r\n return this._store.readChangeFeed(localTable, afterSequence, limit, signal);\r\n }\r\n\r\n /**\r\n * The change feed for one table narrowed to the keys `keyFilter` selects (plus every deletion), so a projection of one site does\r\n * not walk the entries of every other one (`ReadChangeFeedAsync(..., G9CChangeFeedKeyFilter, ...)`).\r\n */\r\n async readChangeFeedFiltered(localTable: string, afterSequence: number, limit: number, keyFilter: G9ChangeFeedKeyFilter, signal?: AbortSignal): Promise<G9ChangeFeedEntry[]> {\r\n validateChangeFeedKeyFilter(keyFilter);\r\n await this.initialize(signal);\r\n return this._store.readChangeFeedFiltered(localTable, afterSequence, limit, keyFilter, signal);\r\n }\r\n\r\n /** The highest sequence readChangeFeed can return today (a watermark above it belongs to a store that no longer exists). */\r\n async getChangeSequence(signal?: AbortSignal): Promise<number> {\r\n await this.initialize(signal);\r\n return this._store.getChangeSequence(signal);\r\n }\r\n\r\n /** The highest sequence ever purged from the change feed; 0 when nothing was (ADR-0059). */\r\n async getChangeFeedFloor(signal?: AbortSignal): Promise<number> {\r\n await this.initialize(signal);\r\n return this._store.getChangeFeedFloor(signal);\r\n }\r\n\r\n async adoptExistingRows(signal?: AbortSignal): Promise<number> {\r\n await this.initialize(signal);\r\n return this._store.adoptExistingRows(signal);\r\n }\r\n\r\n async markDirty(localTable: string, keys: readonly string[], signal?: AbortSignal): Promise<number> {\r\n await this.initialize(signal);\r\n return this._store.markDirty(localTable, keys, signal);\r\n }\r\n\r\n async getHealth(signal?: AbortSignal): Promise<G9SyncHealth> {\r\n await this.initialize(signal);\r\n const state = await this._store.getServerState(signal);\r\n return {\r\n clientId: this._clientId,\r\n isConnected: this._transport.isConnected,\r\n isRunning: this.isRunning,\r\n queuedRuns: this.queuedRuns,\r\n serverEpoch: state.epoch,\r\n lastHelloUtcMs: state.lastHelloUtcMs,\r\n pending: await this._store.getPendingSummary(signal),\r\n subscriptions: await this._store.getSubscriptions(signal),\r\n recentRuns: await this._store.getRecentRunReports(10, signal),\r\n };\r\n }\r\n\r\n async dispose(): Promise<void> {\r\n if (this._disposed) return;\r\n this._disposed = true;\r\n this.stopAutomaticSync();\r\n this._unsubscribePokes();\r\n this._lifetime.abort();\r\n const abandoned = this._queue.splice(0, this._queue.length);\r\n for (const { run } of abandoned) {\r\n run.complete(makeRunResult({ runId: run.runId, outcome: G9ESyncOutcome.Canceled, error: new G9SyncException(G9SyncErrorCodes.Canceled, 'The sync engine was disposed.') }));\r\n }\r\n this._current?.cancel();\r\n this._signal();\r\n if (this._worker) {\r\n try {\r\n await this._worker;\r\n } catch {\r\n // shutting down\r\n }\r\n }\r\n if (this._pokeTimer !== null) {\r\n clearTimeout(this._pokeTimer);\r\n this._pokeTimer = null;\r\n }\r\n }\r\n\r\n // ================================================================ worker\r\n\r\n private _signal(): void {\r\n const wake = this._wake;\r\n this._wake = null;\r\n if (wake) wake();\r\n }\r\n\r\n private _dequeue(): G9SyncRun | null {\r\n if (this._queue.length === 0) return null;\r\n let best = 0;\r\n for (let i = 1; i < this._queue.length; i++) {\r\n const a = this._queue[i] as QueuedRun;\r\n const b = this._queue[best] as QueuedRun;\r\n if (a.priority > b.priority || (a.priority === b.priority && a.order < b.order)) best = i;\r\n }\r\n return (this._queue.splice(best, 1)[0] as QueuedRun).run;\r\n }\r\n\r\n private async _workerLoop(): Promise<void> {\r\n while (!this._lifetime.signal.aborted) {\r\n const run = this._dequeue();\r\n if (!run) {\r\n await new Promise<void>((resolve) => {\r\n this._wake = resolve;\r\n });\r\n continue;\r\n }\r\n run.isStarted = true;\r\n this._current = run;\r\n try {\r\n await this._executeRun(run);\r\n } catch (exception) {\r\n this._log('error', 20002, `Unexpected failure executing run ${run.runId}`, exception);\r\n run.complete(makeRunResult({ runId: run.runId, outcome: G9ESyncOutcome.Failed, error: normalizeError(exception) }));\r\n } finally {\r\n this._current = null;\r\n }\r\n // A pre-empted background run still owes its work: queue it again behind the run that pre-empted it.\r\n if (run.preempted && run.request.priority === G9ESyncPriority.Background) this._tryQueueBackground(run.request.subscriptions);\r\n }\r\n }\r\n\r\n private _tryQueueBackground(subscriptions: readonly string[] | null): void {\r\n if (!this._initialized || this.isBackgroundSuppressed || (this._options.hooks && !this._options.hooks.isNetworkAvailable) || this._lifetime.signal.aborted) {\r\n return;\r\n }\r\n this.run({ priority: G9ESyncPriority.Background, subscriptions });\r\n }\r\n\r\n private _onChangesAvailable(payload: G9DtChangesAvailable): void {\r\n if (!this._options.pullOnChangesAvailable || payload.tables.length === 0) return;\r\n for (const table of payload.tables) this._pokedTables[table.toLowerCase()] = table;\r\n if (this._pokeTimer === null) this._pokeTimer = setTimeout(() => this._flushPokes(), this._options.changesDebounceMs);\r\n }\r\n\r\n private _flushPokes(): void {\r\n const tables = Object.keys(this._pokedTables);\r\n for (const key of tables) delete this._pokedTables[key];\r\n this._pokeTimer = null;\r\n if (tables.length === 0 || !this._initialized) return;\r\n const signal = this._lifetime.signal;\r\n void (async () => {\r\n try {\r\n const state = await this._store.getServerState(signal);\r\n const names: { [name: string]: true } = {};\r\n let any = false;\r\n for (const d of state.definitions) {\r\n if (!d.heavy && d.tables.some((t) => tables.indexOf(t.toLowerCase()) >= 0)) {\r\n names[d.name] = true;\r\n any = true;\r\n }\r\n }\r\n if (!any) return;\r\n const keys = (await this._store.getSubscriptions(signal)).filter((s) => names[s.name] === true).map((s) => s.key);\r\n if (keys.length > 0) this._tryQueueBackground(keys);\r\n } catch (exception) {\r\n if (!signal.aborted) this._log('warning', 20003, 'Handling a server change notification failed', exception);\r\n }\r\n })();\r\n }\r\n\r\n private _raiseRowsApplied(report: G9ApplyReport, source: G9ESyncPhase, slice: G9ApplySlice | null = null): void {\r\n for (const listener of this._rowsAppliedListeners.slice()) {\r\n try {\r\n listener({ report, source, slice });\r\n } catch (exception) {\r\n this._log('warning', 20004, 'A RowsApplied handler threw', exception);\r\n }\r\n }\r\n }\r\n\r\n private _log(level: G9SyncLogLevel, eventId: number, message: string, error?: unknown): void {\r\n const logger = this._options.logger;\r\n if (!logger) return;\r\n try {\r\n logger.log(level, eventId, message, error);\r\n } catch {\r\n // A logger must never break the sync.\r\n }\r\n }\r\n\r\n // ================================================================ execution\r\n\r\n private async _executeRun(run: G9SyncRun): Promise<void> {\r\n const request = run.request;\r\n const startedUtcMs = Date.now();\r\n const changes = new G9ApplyReport();\r\n const problems: G9DtSubscriptionState[] = [];\r\n let modelProblems: G9SyncModelProblem[] = [];\r\n const synced: string[] = [];\r\n let pushed = 0;\r\n let rejected = 0;\r\n let conflicts = 0;\r\n let downloaded = 0;\r\n let downloadedBytes = 0;\r\n let reconciled = 0;\r\n let error: G9SyncException | null = null;\r\n let outcome: G9ESyncOutcome = G9ESyncOutcome.Succeeded;\r\n\r\n const tracker = new G9SyncProgressTracker(run.runId, (p) => run.publish(p), () => this.queuedRuns, this._options.progressMaxHz);\r\n try {\r\n if (request.priority === G9ESyncPriority.Background && this.isBackgroundSuppressed) {\r\n tracker.complete(G9ESyncPhase.Canceled);\r\n run.complete(makeRunResult({ runId: run.runId, outcome: G9ESyncOutcome.Canceled, error: new G9SyncException(G9SyncErrorCodes.Canceled, 'Background sync is suppressed.') }));\r\n return;\r\n }\r\n\r\n const linked = linkSignals(run.cancellation.signal, this._lifetime.signal);\r\n const ct = linked.signal;\r\n const cancelRegistration = onAbort(ct, () => tracker.setCancelPending());\r\n let hostScope: { dispose(): void | Promise<void> } | null = null;\r\n\r\n try {\r\n const history = await this._store.getPhaseStatistics(ct);\r\n const pending = request.push ? await this._store.getPendingSummary(ct) : null;\r\n this._planPhases(tracker, history, request, pending ? pending.totalRows : 0);\r\n if (this._options.hooks) hostScope = await this._options.hooks.beginRun(run, ct);\r\n\r\n // ---------------------------------------------------------------- 1. connect + hello\r\n tracker.enter(G9ESyncPhase.Connecting);\r\n await this._ensureConnected(ct);\r\n await this._store.collectExpiredEphemeral(Date.now(), ct);\r\n const subscriptions = await this._store.getSubscriptions(ct);\r\n const hello = await this._withRetry(\r\n (token) =>\r\n this._transport.hello(\r\n {\r\n clientId: this._clientId,\r\n appVersion: this._options.appVersion,\r\n protocolVersion: 1,\r\n tables: this.model.tables.map((t) => t.toWire()),\r\n subscriptions: subscriptions.map(toSubscriptionRef),\r\n },\r\n token,\r\n ),\r\n ct,\r\n );\r\n if (hello.error) throw syncErrorToException(hello.error);\r\n await this._store.saveHello(hello, ct);\r\n if (hello.unknownTables.length > 0) {\r\n this._log('warning', 20016, 'The server does not know these client tables (they will not sync): ' + hello.unknownTables.join(', '));\r\n }\r\n\r\n // A column declared with the wrong type syncs in NEITHER direction (ADR-0061): say it on every run's result, and once\r\n // per distinct set in the log.\r\n modelProblems = [];\r\n for (const table of hello.tables) {\r\n for (const column of table.typeMismatchColumns) {\r\n modelProblems.push({ code: G9SyncErrorCodes.ModelTypeMismatch, table: table.name, column: column.name, clientType: column.clientType, serverType: column.serverType });\r\n }\r\n }\r\n if (modelProblems.length > 0) {\r\n const described = modelProblems.map(describeModelProblem).join('; ');\r\n if (this._reportedModelProblems !== described) {\r\n this._reportedModelProblems = described;\r\n this._log(\r\n 'warning',\r\n 20022,\r\n `The client model declares ${modelProblems.length} column(s) with a type the server does not have; they sync in NEITHER direction until the model is fixed: ${described}`,\r\n );\r\n }\r\n if (this._options.failOnTypeMismatch) {\r\n throw new G9SyncException(G9SyncErrorCodes.ModelTypeMismatch, 'The client model declares column types the server does not have; those columns would not sync: ' + described);\r\n }\r\n }\r\n\r\n const negotiated = hello.tables;\r\n const definitions: { [name: string]: G9DtSubscriptionDefinition } = {};\r\n for (const d of hello.definitions) definitions[d.name] = d;\r\n const states: { [key: string]: G9DtSubscriptionState } = {};\r\n for (const state of hello.subscriptions) states[state.key] = state;\r\n\r\n // ---------------------------------------------------------------- 2. push\r\n // A FAILED PUSH MUST NOT COST THE PULL: the failure is rethrown after the pull, never swallowed.\r\n let pushFailure: { error: unknown } | null = null;\r\n if (request.push && pending && (pending.totalRows > 0 || pending.pendingCommands > 0)) {\r\n tracker.enter(G9ESyncPhase.Pushing, pending.totalRows + pending.pendingCommands);\r\n try {\r\n const totals = await this._pushAll(negotiated, subscriptions, hello.maxPushRows, hello.maxPushBytes, tracker, changes, ct);\r\n pushed = totals.pushed;\r\n rejected = totals.rejected;\r\n conflicts = totals.conflicts;\r\n } catch (exception) {\r\n if (ct.aborted) throw exception;\r\n this._log('warning', 20019, `Run ${run.runId}: the push failed; continuing to the pull so the device keeps receiving, then reporting the failure`, exception);\r\n pushFailure = { error: exception };\r\n }\r\n }\r\n\r\n if (request.pull) {\r\n // ------------------------------------------------------------ 3. select subscriptions (+ dependencies)\r\n const selected = await this._selectSubscriptions(request, subscriptions, definitions, problems, ct);\r\n const usable: G9SyncSubscriptionRecord[] = [];\r\n for (const subscription of selected) {\r\n const state = states[subscription.key];\r\n if (\r\n state &&\r\n (state.action === G9ESubscriptionAction.Unknown || state.action === G9ESubscriptionAction.InvalidParameters || state.action === G9ESubscriptionAction.Forbidden)\r\n ) {\r\n problems.push(state);\r\n await this._store.updateSubscription(subscription.key, { state: G9ESubscriptionState.Failed, errorCode: actionCode(state.action) }, ct);\r\n // Forbidden: these rows are no longer this caller's to hold (ADR-0048).\r\n if (state.action === G9ESubscriptionAction.Forbidden) {\r\n const released = await this._store.releaseSubscriptionRows(subscription.key, ct);\r\n changes.merge(released);\r\n if (released.total > 0) {\r\n this._log(\r\n 'warning',\r\n 20018,\r\n `Subscription ${subscription.key} is forbidden; released its rows (${released.revokedDeleted} deleted, ${released.revokedQuarantined} quarantined, ${released.revokedRetained} retained)`,\r\n );\r\n this._raiseRowsApplied(released, G9ESyncPhase.Reconciling);\r\n }\r\n }\r\n continue;\r\n }\r\n usable.push(subscription);\r\n }\r\n\r\n // ------------------------------------------------------------ 4. reconcile\r\n const now = Date.now();\r\n const toReconcile = usable.filter((s) => needsReconcile(s, request, states, definitions, now));\r\n tracker.expect(G9ESyncPhase.Reconciling, toReconcile.length * historyOf(history, STAT_RECONCILE_PER_SUBSCRIPTION, 2500));\r\n if (toReconcile.length > 0) {\r\n tracker.enter(G9ESyncPhase.Reconciling, toReconcile.length);\r\n let done = 0;\r\n for (const subscription of toReconcile) {\r\n try {\r\n const report = await this._reconcileSubscription(subscription, definitions[subscription.name] as G9DtSubscriptionDefinition, negotiated, ct);\r\n changes.merge(report);\r\n reconciled += report.total;\r\n if (report.total > 0) this._raiseRowsApplied(report, G9ESyncPhase.Reconciling);\r\n } catch (exception) {\r\n if (isSyncException(exception) && !exception.retryable && exception.code !== G9SyncErrorCodes.Canceled) {\r\n problems.push({ key: subscription.key, action: G9ESubscriptionAction.Reconcile, message: exception.message });\r\n await this._store.updateSubscription(subscription.key, { state: G9ESubscriptionState.Failed, errorCode: exception.code }, ct);\r\n } else {\r\n throw exception;\r\n }\r\n }\r\n tracker.report(++done, -1, null, subscription.key);\r\n }\r\n }\r\n\r\n // ------------------------------------------------------------ 5. plan (or resume a staged pull)\r\n tracker.enter(G9ESyncPhase.Planning);\r\n const failedKeys: { [key: string]: true } = {};\r\n for (const p of problems) failedKeys[p.key] = true;\r\n const current: { [key: string]: G9SyncSubscriptionRecord } = {};\r\n for (const s of await this._store.getSubscriptions(ct)) current[s.key] = s;\r\n const plannable = usable.filter((s) => !failedKeys[s.key] && current[s.key] !== undefined).map((s) => current[s.key] as G9SyncSubscriptionRecord);\r\n\r\n // A stage is kept PER GENERATION (ADR-0060); what makes one resumable is that the epoch, permissions, columns and\r\n // the cursors it was planned from are all still exactly what they were.\r\n const generation = stageGeneration(hello, plannable, states, negotiated);\r\n const pruned = await this._store.pruneStagedPulls(Date.now() - this._options.stagedPullMaxAgeMs, this._options.stagedPullsMaxBytes, generation, ct);\r\n if (pruned > 0) this._log('information', 20021, `Removed ${pruned} staged pull(s) past their age or the byte cap`);\r\n\r\n // Snapshot files are offered unless one already failed in this run (ADR-0072): a file is a faster way to the same rows,\r\n // never the only one, so a file the server cannot build or the device rejects costs one replan as rows - not the run.\r\n let allowFiles = this._options.acceptSnapshotFiles;\r\n for (let attempt = 0; ; attempt++) {\r\n const problemsBefore = problems.length;\r\n const syncedBefore = synced.length;\r\n let runId: string | null = null;\r\n try {\r\n const staged = await this._store.getStagedPullForGeneration(generation, ct);\r\n let plan: G9DtPullPlan;\r\n if (staged && staged.createdUtcMs > Date.now() - this._options.stagedPullMaxAgeMs) {\r\n plan = staged.plan;\r\n runId = staged.runId;\r\n this._log('information', 20012, `Resuming staged pull ${runId} (${plan.totalRows} rows planned)`);\r\n } else {\r\n const backfills = await this._store.getPendingBackfills(ct);\r\n const files = allowFiles && this._store.describeSnapshotFiles ? this._store.describeSnapshotFiles(negotiated) : null;\r\n plan = await this._withRetry(\r\n (token) =>\r\n this._transport.planPull(\r\n {\r\n clientId: this._clientId,\r\n subscriptions: plannable.map(toSubscriptionRef),\r\n tables: negotiated.map((t) => ({ tableId: t.tableId, columns: t.columns.map((c) => c.name) })),\r\n backfills: backfills.slice(),\r\n frameVersion: this._options.maxFrameVersion,\r\n ...(files ? { snapshotFiles: files } : {}),\r\n },\r\n token,\r\n ),\r\n ct,\r\n );\r\n if (plan.error) throw syncErrorToException(plan.error);\r\n runId = guidToN(newGuid());\r\n const plannedFromCursors: { [key: string]: string | null } = {};\r\n for (const s of plannable) plannedFromCursors[s.key] = s.cursor;\r\n await this._store.beginStagedPull(\r\n { runId, plan, createdUtcMs: Date.now(), backfills, generation, plannedFromCursors, stageSequence: 0 },\r\n ct,\r\n );\r\n }\r\n\r\n for (const skipped of plan.skipped) {\r\n problems.push(skipped);\r\n if (skipped.action === G9ESubscriptionAction.Reconcile || skipped.action === G9ESubscriptionAction.ResyncRequired) {\r\n await this._store.updateSubscription(skipped.key, { state: G9ESubscriptionState.NeedsReconcile }, ct);\r\n }\r\n }\r\n\r\n for (const c of plan.cursors) synced.push(c.key);\r\n const fileParts = plan.parts.filter((p) => p.kind === G9EPullPartKind.SnapshotFile);\r\n if (fileParts.length > 0) {\r\n this._log('information', 20025, `The pull carries ${fileParts.length} snapshot file(s) for ${fileParts.reduce((sum, p) => sum + p.rows, 0)} row(s)`);\r\n }\r\n tracker.expect(G9ESyncPhase.Downloading, Math.max(200, (plan.totalRows / 1000) * historyOf(history, STAT_DOWNLOAD_PER_K_ROW, 350)));\r\n tracker.expect(G9ESyncPhase.Applying, Math.max(100, (plan.totalRows / 1000) * historyOf(history, STAT_APPLY_PER_K_ROW, 250)));\r\n\r\n // ------------------------------------------------------------ 6. download (resumable)\r\n tracker.enter(G9ESyncPhase.Downloading, plan.totalRows, plan.estimatedBytes);\r\n const totals = await this._download(runId, plan, tracker, ct);\r\n downloaded = totals.rows;\r\n downloadedBytes = totals.bytes;\r\n\r\n // ------------------------------------------------------------ 7. apply (atomic, or in committed slices)\r\n tracker.enter(G9ESyncPhase.Applying, downloaded);\r\n const applied = await this._store.applyStagedPull(\r\n runId,\r\n (rows) => tracker.report(rows),\r\n (slice) => {\r\n if (slice.report.total > 0) this._raiseRowsApplied(slice.report, G9ESyncPhase.Applying, slice);\r\n },\r\n ct,\r\n );\r\n changes.merge(applied);\r\n break;\r\n } catch (exception) {\r\n if (\r\n attempt === 0 &&\r\n !ct.aborted &&\r\n isSyncException(exception) &&\r\n (exception.code === G9SyncErrorCodes.SnapshotFileUnavailable || exception.code === G9SyncErrorCodes.SnapshotFileCorrupt)\r\n ) {\r\n this._log('warning', 20026, `A snapshot file failed (${exception.code}); the staged download was discarded and the pull is planned again as rows`, exception);\r\n if (runId !== null) await this._store.discardStagedPull(runId);\r\n problems.length = problemsBefore;\r\n synced.length = syncedBefore;\r\n allowFiles = false;\r\n tracker.enter(G9ESyncPhase.Planning);\r\n continue;\r\n }\r\n throw exception;\r\n }\r\n }\r\n }\r\n\r\n // ---------------------------------------------------------------- 8. post steps\r\n for (const step of request.postSteps) {\r\n tracker.enter(G9ESyncPhase.PostStep, 0, 0, step.name);\r\n await step.action({ run, changes, progress: (fraction) => tracker.reportFraction(fraction) }, ct);\r\n }\r\n\r\n // Rows retained after revocation by a RetainWhile rule are re-checked once per run (ADR-0026).\r\n changes.revokedDeleted += await this._store.reevaluateRetained(ct);\r\n\r\n // The pull has been applied and its cursors committed; now the push failure decides the run's fate.\r\n if (pushFailure) throw pushFailure.error;\r\n\r\n outcome = rejected > 0 || problems.length > 0 ? G9ESyncOutcome.CompletedWithRejections : G9ESyncOutcome.Succeeded;\r\n tracker.complete(G9ESyncPhase.Completed);\r\n } catch (exception) {\r\n if (ct.aborted) {\r\n outcome = G9ESyncOutcome.Canceled;\r\n error = new G9SyncException(G9SyncErrorCodes.Canceled, run.preempted ? 'Pre-empted by a higher-priority sync.' : 'The sync was canceled.', { cause: exception });\r\n tracker.complete(G9ESyncPhase.Canceled);\r\n } else {\r\n error = normalizeError(exception);\r\n outcome = G9ESyncOutcome.Failed;\r\n tracker.complete(G9ESyncPhase.Failed);\r\n this._log('warning', 20011, `Run ${run.runId} failed with ${error.code}`, error);\r\n }\r\n } finally {\r\n cancelRegistration();\r\n linked.dispose();\r\n if (hostScope) {\r\n try {\r\n await hostScope.dispose();\r\n } catch (exception) {\r\n this._log('warning', 20004, 'A host scope handler threw', exception);\r\n }\r\n }\r\n }\r\n\r\n const durations = tracker.durations;\r\n const phaseMs: { [phase: string]: number } = {};\r\n for (const key of Object.keys(durations)) phaseMs[key] = Math.floor(durations[key] as number);\r\n const result = makeRunResult({\r\n runId: run.runId,\r\n outcome,\r\n error,\r\n pushed,\r\n rejected,\r\n conflicts,\r\n downloaded,\r\n applied: changes.total,\r\n durationMs: Date.now() - startedUtcMs,\r\n subscriptions: synced,\r\n problems,\r\n modelProblems,\r\n changes,\r\n phaseMs,\r\n });\r\n\r\n try {\r\n await this._persistRun(run, result, durations, startedUtcMs, downloadedBytes, reconciled);\r\n } catch (exception) {\r\n this._log('warning', 20004, 'A run report handler threw', exception);\r\n }\r\n\r\n this._log(\r\n 'information',\r\n 20010,\r\n `Run ${run.runId} finished ${outcomeName(outcome)}: pushed ${pushed}, downloaded ${downloaded}, applied ${changes.total} in ${result.durationMs} ms`,\r\n );\r\n run.complete(result);\r\n for (const listener of this._runCompletedListeners.slice()) {\r\n try {\r\n listener(result);\r\n } catch (exception) {\r\n this._log('warning', 20004, 'A RunCompleted handler threw', exception);\r\n }\r\n }\r\n } finally {\r\n tracker.dispose();\r\n }\r\n }\r\n\r\n private _planPhases(tracker: G9SyncProgressTracker, history: { [key: string]: number }, request: G9ResolvedSyncRequest, pendingRows: number): void {\r\n const connecting = historyOf(history, STAT_CONNECTING, 800);\r\n const pushing = request.push && pendingRows > 0 ? Math.max(300, (pendingRows / 1000) * historyOf(history, STAT_PUSH_PER_K_ROW, 1200)) : 0;\r\n const planning = request.pull ? historyOf(history, STAT_PLANNING, 700) : 0;\r\n const downloading = request.pull ? 2000 : 0;\r\n const applying = request.pull ? 1500 : 0;\r\n tracker.plan(G9ESyncPhase.Connecting, connecting);\r\n if (pushing > 0) tracker.plan(G9ESyncPhase.Pushing, pushing);\r\n if (request.pull) {\r\n tracker.plan(G9ESyncPhase.Reconciling, 0);\r\n tracker.plan(G9ESyncPhase.Planning, planning);\r\n tracker.plan(G9ESyncPhase.Downloading, downloading);\r\n tracker.plan(G9ESyncPhase.Applying, applying);\r\n }\r\n const core = connecting + pushing + planning + downloading + applying;\r\n for (const step of request.postSteps) {\r\n const hint = step.weightHint;\r\n tracker.plan(G9ESyncPhase.PostStep, historyOf(history, 'PostStep:' + step.name, hint >= 0.9 ? core * 9 : (core * hint) / (1 - hint)), step.name);\r\n }\r\n }\r\n\r\n private async _selectSubscriptions(\r\n request: G9ResolvedSyncRequest,\r\n all: G9SyncSubscriptionRecord[],\r\n definitions: { [name: string]: G9DtSubscriptionDefinition },\r\n problems: G9DtSubscriptionState[],\r\n ct: AbortSignal,\r\n ): Promise<G9SyncSubscriptionRecord[]> {\r\n const byKey: { [key: string]: G9SyncSubscriptionRecord } = {};\r\n for (const s of all) byKey[s.key] = s;\r\n const wanted = request.subscriptions;\r\n let roots = wanted === null ? all.slice() : all.filter((s) => wanted.indexOf(s.key) >= 0 || wanted.indexOf(s.name) >= 0);\r\n if (request.priority === G9ESyncPriority.Background && wanted === null) {\r\n roots = roots.filter((s) => !(definitions[s.name] && (definitions[s.name] as G9DtSubscriptionDefinition).heavy));\r\n }\r\n const ordered: G9SyncSubscriptionRecord[] = [];\r\n const visiting: { [key: string]: true } = {};\r\n const done: { [key: string]: true } = {};\r\n\r\n const visit = async (record: G9SyncSubscriptionRecord): Promise<void> => {\r\n if (done[record.key] || visiting[record.key]) return;\r\n visiting[record.key] = true;\r\n const definition = definitions[record.name];\r\n if (definition) {\r\n for (const dependency of definition.dependsOn) {\r\n const parentDefinition = definitions[dependency.name];\r\n if (!parentDefinition) {\r\n if (dependency.required) {\r\n problems.push({ key: record.key, action: G9ESubscriptionAction.Unknown, message: `Required dependency '${dependency.name}' is not available.` });\r\n }\r\n continue;\r\n }\r\n let parent = byKey[dependency.name];\r\n if (!parent) {\r\n parent = await this._store.ensureSubscription(\r\n dependency.name,\r\n new G9SyncParameters(),\r\n parentDefinition.ephemeral,\r\n parentDefinition.ephemeral ? parentDefinition.ttlSeconds * 1000 : null,\r\n false,\r\n ct,\r\n );\r\n byKey[parent.key] = parent;\r\n }\r\n await visit(parent);\r\n }\r\n }\r\n done[record.key] = true;\r\n ordered.push(record);\r\n };\r\n\r\n // Creation order. Two subscriptions created in the same millisecond keep it through their slots (handed out lowest\r\n // free first), then the key, ordinal (JS `<` compares UTF-16 units, like StringComparer.Ordinal) — never the order\r\n // the store happened to list them in (by key: a random GUID decided which site's rows came first, LES-0052).\r\n const sorted = roots\r\n .map((r, i) => ({ r, i }))\r\n .sort((a, b) => a.r.createdUtcMs - b.r.createdUtcMs || a.r.slot - b.r.slot || (a.r.key < b.r.key ? -1 : a.r.key > b.r.key ? 1 : 0) || a.i - b.i);\r\n for (const { r } of sorted) await visit(r);\r\n return ordered;\r\n }\r\n\r\n private async _pushAll(\r\n negotiated: G9DtNegotiatedTable[],\r\n subscriptions: G9SyncSubscriptionRecord[],\r\n serverMaxRows: number,\r\n serverMaxBytes: number,\r\n tracker: G9SyncProgressTracker,\r\n changes: G9ApplyReport,\r\n ct: AbortSignal,\r\n ): Promise<{ pushed: number; rejected: number; conflicts: number }> {\r\n let pushed = 0;\r\n let rejected = 0;\r\n let conflicts = 0;\r\n const references = subscriptions.map(toSubscriptionRef);\r\n // The server's limits win over the device's preference; bytes keep a margin for the header and compression variance.\r\n const targetRows = Math.max(1, serverMaxRows > 0 ? Math.min(this._options.pushBatchRows, serverMaxRows) : this._options.pushBatchRows);\r\n let batchRows = targetRows;\r\n const batchBytes = serverMaxBytes > 0 ? Math.floor(serverMaxBytes * 0.9) : Number.MAX_SAFE_INTEGER;\r\n for (;;) {\r\n const batch = await this._store.buildPushBatch(negotiated, batchRows, batchBytes, ct);\r\n if (!batch) break;\r\n rejected += batch.rejectedLocally;\r\n if (batch.rowCount === 0 && batch.commands.length === 0) break; // only rows that can never be uploaded were left\r\n\r\n const request: G9DtPushRequest = {\r\n clientId: this._clientId,\r\n batchId: batch.batchId,\r\n subscriptions: references,\r\n tables: batch.tables.slice(),\r\n commands: batch.commands.slice(),\r\n // Canonical rows come back in the columns the DEVICE holds (LES-0035).\r\n heldTables: negotiated\r\n .filter((t) => batch.commands.length > 0 || batch.tables.some((p) => p.tableId === t.tableId))\r\n .map((t) => ({ tableId: t.tableId, columns: t.columns.map((c) => c.name) })),\r\n frameVersion: this._options.maxFrameVersion,\r\n };\r\n let result: G9DtPushResult;\r\n try {\r\n result = await this._withRetry((token) => this._transport.push(request, toChunks(batch), token), ct);\r\n if (result.error) throw syncErrorToException(result.error);\r\n } catch (exception) {\r\n if (isSyncException(exception) && exception.code === G9SyncErrorCodes.RejectTooMany && batchRows > 1 && batch.rowCount > 1) {\r\n // The server rolled the WHOLE push back for too many rejections (ADR-0063): halve and resend the smaller prefix\r\n // under the same batch id, so the valid rows get through and the bad ones are parked one by one.\r\n batchRows = Math.max(1, Math.floor(Math.min(batchRows, batch.rowCount) / 2));\r\n this._log(\r\n 'warning',\r\n 20023,\r\n `Push batch ${batch.batchId} of ${batch.rowCount} rows was rolled back for too many rejections; sending it again as ${batchRows} rows so the valid rows get through`,\r\n );\r\n continue;\r\n }\r\n throw exception;\r\n }\r\n\r\n const report = await this._store.applyPushResult(batch, result, ct);\r\n changes.merge(report);\r\n if (report.upserts + report.deletes > 0) this._raiseRowsApplied(report, G9ESyncPhase.Pushing);\r\n pushed += batch.rowCount + batch.commands.length;\r\n rejected += result.rejections.length;\r\n conflicts += result.conflicts.length;\r\n tracker.report(pushed);\r\n this._log(\r\n 'debug',\r\n 20014,\r\n `Pushed batch ${batch.batchId}: ${batch.rowCount} rows, ${result.rejections.length} rejected, ${result.conflicts.length} conflicts, replayed ${result.alreadyApplied}`,\r\n );\r\n\r\n if (report.accepted + report.rejected + report.conflicts + report.commandsCompleted === 0 && !result.alreadyApplied) {\r\n this._log('warning', 20015, `Push batch ${batch.batchId} changed no row state; stopping the push loop for this run`);\r\n break;\r\n }\r\n if (batch.rowCount < batchRows && batch.commands.length < batchRows && !batch.truncated && !result.alreadyApplied) break;\r\n // After a split: grow back towards the normal size.\r\n if (batchRows < targetRows) batchRows = Math.min(targetRows, batchRows * 2);\r\n }\r\n return { pushed, rejected, conflicts };\r\n }\r\n\r\n private async _download(runId: string, plan: G9DtPullPlan, tracker: G9SyncProgressTracker, ct: AbortSignal): Promise<{ rows: number; bytes: number }> {\r\n // maxRetries counts failures in a row WITHOUT progress (the .NET twin, DownloadAsync): progress is the DURABLE resume point\r\n // moving, not a chunk arriving - segments after the last checkpoint are written again on resume.\r\n let failures = 0;\r\n let lastFailedAt: { stagedRows: number; stagedBytes: number } | null = null;\r\n for (;;) {\r\n const resume = await this._store.getResumePoint(runId, ct);\r\n let rows = resume.stagedRows;\r\n let bytes = resume.stagedBytes;\r\n if (resume.complete) return { rows, bytes };\r\n if (lastFailedAt !== null && (resume.stagedRows > lastFailedAt.stagedRows || resume.stagedBytes > lastFailedAt.stagedBytes)) failures = 0;\r\n tracker.report(rows, bytes);\r\n try {\r\n // Inside the try (the .NET twin, DownloadAsync): a reconnect that fails while the network is still down is one more\r\n // transient failure, not the end of the run.\r\n await this._ensureConnected(ct);\r\n for await (const chunk of this._transport.pull(plan.token, resume.continuation, ct)) {\r\n await this._store.stageChunk(runId, chunk, ct);\r\n if (chunk.isFinal) return { rows, bytes };\r\n rows += chunk.rowCount;\r\n bytes += chunk.payload ? chunk.payload.length : 0;\r\n tracker.report(rows, bytes, null, chunk.subscriptionKey ?? null);\r\n }\r\n throw new G9SyncException(G9SyncErrorCodes.NetworkFailure, 'The pull stream ended before its final chunk.');\r\n } catch (exception) {\r\n if (\r\n isSyncException(exception) &&\r\n (exception.code === G9SyncErrorCodes.TokenExpired ||\r\n exception.code === G9SyncErrorCodes.TokenInvalid ||\r\n exception.code === G9SyncErrorCodes.ResyncEpoch ||\r\n exception.code === G9SyncErrorCodes.ResyncAuthChanged)\r\n ) {\r\n await this._store.discardStagedPull(runId);\r\n throw exception;\r\n }\r\n if (!ct.aborted && isTransientError(exception) && failures < this._options.maxRetries) {\r\n this._log('warning', 20013, `Transient pull failure, retry ${failures + 1}: ${messageOf(exception)}`);\r\n await delay(this._backoff(failures), ct);\r\n failures++;\r\n lastFailedAt = resume;\r\n continue;\r\n }\r\n throw exception;\r\n }\r\n }\r\n }\r\n\r\n private async _withRetry<T>(operation: (signal: AbortSignal) => Promise<T>, ct: AbortSignal): Promise<T> {\r\n for (let attempt = 0; ; attempt++) {\r\n try {\r\n await this._ensureConnected(ct);\r\n return await operation(ct);\r\n } catch (exception) {\r\n if (!ct.aborted && isTransientError(exception) && attempt < this._options.maxRetries) {\r\n this._log('warning', 20013, `Transient call failure, retry ${attempt + 1}: ${messageOf(exception)}`);\r\n await delay(this._backoff(attempt), ct);\r\n continue;\r\n }\r\n throw exception;\r\n }\r\n }\r\n }\r\n\r\n private _backoff(attempt: number): number {\r\n return Math.min(30000, this._options.retryBaseDelayMs * Math.pow(2, attempt)) * (0.85 + Math.random() * 0.3);\r\n }\r\n\r\n private async _ensureConnected(ct: AbortSignal): Promise<void> {\r\n if (!this._transport.isConnected) await this._transport.connect(ct);\r\n }\r\n\r\n private async _persistRun(\r\n run: G9SyncRun,\r\n result: G9SyncRunResult,\r\n durations: { [key: string]: number },\r\n startedUtcMs: number,\r\n downloadedBytes: number,\r\n reconciledRows: number,\r\n ): Promise<void> {\r\n const diagnostics = result.changes.diagnostics;\r\n const phaseMs: { [phase: string]: number } = {};\r\n for (const key of Object.keys(durations)) phaseMs[key] = Math.floor(durations[key] as number);\r\n const report: G9SyncRunReport = {\r\n runId: run.runId,\r\n startedUtcMs,\r\n durationMs: result.durationMs,\r\n outcome: outcomeName(result.outcome),\r\n priority: priorityName(run.request.priority),\r\n errorCode: result.error ? result.error.code : null,\r\n errorMessage: result.error ? result.error.message : null,\r\n pushed: result.pushed,\r\n rejected: result.rejected,\r\n conflicts: result.conflicts,\r\n downloaded: result.downloaded,\r\n applied: result.applied,\r\n downloadedBytes,\r\n subscriptions: result.subscriptions.slice(),\r\n phaseMs,\r\n triggersSkipped: diagnostics.triggersSkipped,\r\n foreignTriggers: diagnostics.foreignTriggers.slice(),\r\n applyTransactions: diagnostics.transactions,\r\n indexesDeferred: diagnostics.deferredIndexCount,\r\n indexRebuildMs: diagnostics.indexRebuildMs,\r\n liveIndexReasons: { ...diagnostics.liveIndexReasons },\r\n unchangedRows: result.changes.unchangedRows,\r\n };\r\n await this._store.saveRunReport(report, this._options.keepRunReports);\r\n\r\n if (!result.isSuccess) return;\r\n const samples: { [key: string]: number } = {};\r\n const connecting = durations[phaseName(G9ESyncPhase.Connecting)];\r\n if (connecting !== undefined) samples[STAT_CONNECTING] = connecting;\r\n const planning = durations[phaseName(G9ESyncPhase.Planning)];\r\n if (planning !== undefined) samples[STAT_PLANNING] = planning;\r\n const pushingMs = durations[phaseName(G9ESyncPhase.Pushing)];\r\n if (result.pushed >= 100 && pushingMs !== undefined) samples[STAT_PUSH_PER_K_ROW] = pushingMs / (result.pushed / 1000);\r\n const downloadingMs = durations[phaseName(G9ESyncPhase.Downloading)];\r\n if (result.downloaded >= 500 && downloadingMs !== undefined) samples[STAT_DOWNLOAD_PER_K_ROW] = downloadingMs / (result.downloaded / 1000);\r\n const applyingMs = durations[phaseName(G9ESyncPhase.Applying)];\r\n if (result.downloaded >= 500 && applyingMs !== undefined) samples[STAT_APPLY_PER_K_ROW] = applyingMs / (result.downloaded / 1000);\r\n const reconcilingMs = durations[phaseName(G9ESyncPhase.Reconciling)];\r\n if (reconcilingMs !== undefined && reconciledRows >= 0 && run.request.pull) {\r\n samples[STAT_RECONCILE_PER_SUBSCRIPTION] = reconcilingMs / Math.max(1, result.subscriptions.length);\r\n }\r\n for (const step of run.request.postSteps) {\r\n const stepMs = durations['PostStep:' + step.name];\r\n if (stepMs !== undefined) samples['PostStep:' + step.name] = stepMs;\r\n }\r\n if (Object.keys(samples).length > 0) await this._store.recordPhaseStatistics(samples);\r\n if (result.applied > 0) await this._store.purgeDeletedFeed(this._options.keepDeletedFeedEntries);\r\n }\r\n\r\n // ================================================================ reconciliation (D-07)\r\n\r\n private async _reconcileSubscription(\r\n subscription: G9SyncSubscriptionRecord,\r\n definition: G9DtSubscriptionDefinition,\r\n negotiated: G9DtNegotiatedTable[],\r\n ct: AbortSignal,\r\n ): Promise<G9ApplyReport> {\r\n const tables: G9DtNegotiatedTable[] = [];\r\n for (const name of definition.tables) {\r\n const table = negotiated.find((t) => t.name.toLowerCase() === name.toLowerCase());\r\n // UploadOnly: the device's own rows, nothing on the server to compare them with.\r\n if (table && table.direction !== G9ESyncDirection.UploadOnly) tables.push(table);\r\n }\r\n\r\n const request: G9DtReconcileRequest = { clientId: this._clientId, subscription: toSubscriptionRef(subscription), tables: [], frameVersion: this._options.maxFrameVersion };\r\n for (const table of tables) request.tables.push(await this._store.computeDigest(subscription.key, table, ct));\r\n\r\n const serverRows: { [tableId: number]: Map<string, { version: number; hash: G9Long }> } = {};\r\n let summary: G9DtReconcileSummary | null = null;\r\n for await (const chunk of this._transport.reconcile(request, ct)) {\r\n if (chunk.isFinal) {\r\n summary = chunk.reconcileSummary ?? null;\r\n break;\r\n }\r\n if (!chunk.payload) continue;\r\n const reader = await openRowBatch(chunk.payload, { maxBodyBytes: this._options.maxDecodedFrameBytes });\r\n while (reader.nextSection()) {\r\n let rows = serverRows[reader.tableId];\r\n if (!rows) serverRows[reader.tableId] = rows = new Map();\r\n while (reader.readRow()) rows.set(reader.key, { version: reader.version, hash: reader.rowHash });\r\n }\r\n }\r\n if (!summary) throw new G9SyncException(G9SyncErrorCodes.NetworkFailure, 'The reconcile stream ended before its summary.');\r\n\r\n const report = new G9ApplyReport();\r\n let handedToSnapshot = false;\r\n for (const mismatch of summary.mismatched) {\r\n const table = tables.find((t) => t.tableId === mismatch.tableId);\r\n if (!table) continue;\r\n const server = serverRows[table.tableId] ?? new Map<string, { version: number; hash: G9Long }>();\r\n const buckets = new Set<number>(mismatch.buckets);\r\n const serverKeys = new Set<string>();\r\n server.forEach((_value, key) => serverKeys.add(key));\r\n const local = await this._store.readLocalEntries(subscription.key, table, buckets, serverKeys, ct);\r\n const localByKey = new Map<string, G9LocalRowEntry>();\r\n for (const entry of local) localByKey.set(entry.key, entry);\r\n\r\n const fetch: string[] = [];\r\n const addMembership: string[] = [];\r\n const moveOut: string[] = [];\r\n server.forEach(({ hash }, key) => {\r\n const entry = localByKey.get(key);\r\n if (!entry) fetch.push(key);\r\n else if (entry.dirty) {\r\n // A pending local change is never overwritten here; a row visible again still gets its membership back.\r\n if (!entry.member) addMembership.push(key);\r\n } else if (!entry.hash.equals(hash)) fetch.push(key);\r\n else if (!entry.member) addMembership.push(key);\r\n });\r\n for (const entry of local) {\r\n // Rows with pending changes are released too; the store's revocation policy decides (ADR-0026).\r\n if (entry.member && buckets.has(entry.bucket) && !server.has(entry.key)) moveOut.push(entry.key);\r\n }\r\n\r\n // A difference this large is a download, not a repair (ADR-0066).\r\n if (this._options.reconcileSnapshotThreshold > 0 && fetch.length >= this._options.reconcileSnapshotThreshold) {\r\n const released = await this._store.applyReconcile(subscription.key, table, [], addMembership, moveOut, definition.moveOutPolicy, ct);\r\n report.merge(released);\r\n handedToSnapshot = true;\r\n this._log(\r\n 'information',\r\n 20024,\r\n `Reconciling ${subscription.key} / ${table.name} would fetch ${fetch.length} rows (threshold ${this._options.reconcileSnapshotThreshold}): released what left, and leaving the rows to a staged snapshot pull`,\r\n );\r\n continue;\r\n }\r\n\r\n // Fetched and applied in groups (ADR-0066).\r\n const groupKeys = Math.max(Math.max(1, this._options.fetchKeysPerRequest), this._options.reconcileApplyRows);\r\n let pendingMembership = addMembership;\r\n let pendingMoveOut = moveOut;\r\n let fetched = 0;\r\n for (const group of chunked(fetch, groupKeys)) {\r\n const frames: Uint8Array[] = [];\r\n const returned = new Set<string>();\r\n for (const keys of chunked(group, Math.max(1, this._options.fetchKeysPerRequest))) {\r\n const fetchRequest = {\r\n clientId: this._clientId,\r\n subscription: toSubscriptionRef(subscription),\r\n tableId: table.tableId,\r\n keys,\r\n columns: table.columns.map((c) => c.name),\r\n frameVersion: this._options.maxFrameVersion,\r\n };\r\n for await (const chunk of this._transport.fetchRows(fetchRequest, ct)) {\r\n if (chunk.isFinal || !chunk.payload) continue;\r\n frames.push(chunk.payload);\r\n const reader = await openRowBatch(chunk.payload, { maxBodyBytes: this._options.maxDecodedFrameBytes });\r\n while (reader.nextSection()) {\r\n while (reader.readRow()) returned.add(reader.key);\r\n }\r\n }\r\n }\r\n // A key listed but not returned left the subscription between listing and fetch.\r\n const groupMoveOut = group.filter((k) => !returned.has(k) && (localByKey.get(k)?.member ?? false));\r\n for (const key of pendingMoveOut) groupMoveOut.push(key);\r\n const applied = await this._store.applyReconcile(subscription.key, table, frames, pendingMembership, groupMoveOut, definition.moveOutPolicy, ct);\r\n report.merge(applied);\r\n pendingMembership = [];\r\n pendingMoveOut = [];\r\n fetched += group.length;\r\n }\r\n if (fetched === 0 && (pendingMembership.length > 0 || pendingMoveOut.length > 0)) {\r\n report.merge(await this._store.applyReconcile(subscription.key, table, [], pendingMembership, pendingMoveOut, definition.moveOutPolicy, ct));\r\n }\r\n this._log(\r\n 'information',\r\n 20020,\r\n `Reconciled ${subscription.key} / ${table.name}: ${mismatch.buckets.length} buckets differed, fetched ${fetch.length}, adopted ${addMembership.length}, moved out ${moveOut.length}`,\r\n );\r\n }\r\n\r\n await this._store.updateSubscription(\r\n subscription.key,\r\n handedToSnapshot\r\n ? // No cursor: the plan step of this run sees an initial pull and stages a snapshot.\r\n { clearCursor: true, state: G9ESubscriptionState.Active, clearError: true, reconciled: true }\r\n : {\r\n cursor: summary.cursor,\r\n definitionHash: summary.definitionHash,\r\n authHash: summary.authHash,\r\n state: G9ESubscriptionState.Active,\r\n clearError: true,\r\n reconciled: true,\r\n },\r\n ct,\r\n );\r\n return report;\r\n }\r\n}\r\n\r\n// ---------------------------------------------------------------- helpers\r\n\r\nfunction remove<T>(list: T[], item: T): void {\r\n const index = list.indexOf(item);\r\n if (index >= 0) list.splice(index, 1);\r\n}\r\n\r\nfunction messageOf(error: unknown): string {\r\n return error instanceof Error ? error.message : String(error);\r\n}\r\n\r\nfunction historyOf(history: { [key: string]: number }, key: string, fallback: number): number {\r\n const value = history[key];\r\n return value !== undefined && value > 0 ? value : fallback;\r\n}\r\n\r\nfunction needsReconcile(\r\n subscription: G9SyncSubscriptionRecord,\r\n request: G9ResolvedSyncRequest,\r\n states: { [key: string]: G9DtSubscriptionState },\r\n definitions: { [name: string]: G9DtSubscriptionDefinition },\r\n nowMs: number,\r\n): boolean {\r\n if (subscription.state === G9ESubscriptionState.NeedsReconcile) return true;\r\n const state = states[subscription.key];\r\n if (state && (state.action === G9ESubscriptionAction.Reconcile || state.action === G9ESubscriptionAction.ResyncRequired)) return true;\r\n if (subscription.cursor === null) return false;\r\n if (request.forceReconcile) return true;\r\n const definition = definitions[subscription.name];\r\n return (\r\n definition !== undefined &&\r\n definition.reconcileIntervalMinutes > 0 &&\r\n (subscription.lastReconcileUtcMs ?? subscription.lastSuccessUtcMs ?? subscription.createdUtcMs) < nowMs - definition.reconcileIntervalMinutes * 60000\r\n );\r\n}\r\n\r\n/**\r\n * Everything a staged pull's rows depend on (ADR-0046): the server's epoch, the exact set of subscriptions with their\r\n * definition and authorisation hashes, and the negotiated columns. The cursor is deliberately NOT part of it (ADR-0060).\r\n */\r\nexport function stageGeneration(\r\n hello: G9DtHelloResult,\r\n plannable: readonly G9SyncSubscriptionRecord[],\r\n states: { [key: string]: G9DtSubscriptionState },\r\n negotiated: readonly G9DtNegotiatedTable[],\r\n): string {\r\n let text = guidToN(hello.epoch) + '\\n';\r\n for (const subscription of plannable.slice().sort((a, b) => compareOrdinal(a.key, b.key))) {\r\n const state = states[subscription.key];\r\n text += subscription.key + '\\u001F' + ((state ? state.definitionHash : null) ?? subscription.definitionHash ?? '') + '\\u001F' + ((state ? state.authHash : null) ?? subscription.authHash ?? '') + '\\n';\r\n }\r\n text += '\\n';\r\n const tables = negotiated.map((t, i) => ({ t, i })).sort((a, b) => a.t.tableId - b.t.tableId || a.i - b.i);\r\n for (const { t } of tables) text += String(t.tableId) + '\\u001F' + t.columns.map((c) => c.name).join(',') + '\\n';\r\n return toHex(sha256(utf8Encode(text)));\r\n}\r\n\r\nfunction actionCode(action: number): string {\r\n switch (action) {\r\n case G9ESubscriptionAction.Unknown:\r\n return G9SyncErrorCodes.UnknownSubscription;\r\n case G9ESubscriptionAction.Forbidden:\r\n return G9SyncErrorCodes.SubscriptionForbidden;\r\n default:\r\n return G9SyncErrorCodes.InvalidParameters;\r\n }\r\n}\r\n\r\nfunction chunked<T>(items: readonly T[], size: number): T[][] {\r\n const out: T[][] = [];\r\n for (let i = 0; i < items.length; i += size) out.push(items.slice(i, i + size));\r\n return out;\r\n}\r\n\r\nasync function* toChunks(batch: G9PushBatch): AsyncGenerator<G9DtSyncChunk> {\r\n let sequence = 0;\r\n for (const frame of batch.frames) yield { sequence: sequence++, payload: frame, rowCount: 0, isFinal: false };\r\n}\r\n"]}
1
+ {"version":3,"file":"engine.js","sourceRoot":"","sources":["../../src/client/engine.ts"],"names":[],"mappings":"AAAA,qHAAqH;AACrH,oHAAoH;AACpH,OAAO,EAAE,gBAAgB,EAAE,gBAAgB,EAAE,MAAM,0BAA0B,CAAC;AAC9E,OAAO,EAAE,gBAAgB,EAAE,eAAe,EAAE,eAAe,EAAE,MAAM,2BAA2B,CAAC;AAC/F,OAAO,EAAE,OAAO,EAAE,OAAO,EAAE,MAAM,yBAAyB,CAAC;AAC3D,OAAO,EAAE,gBAAgB,EAAE,cAAc,EAAE,MAAM,+BAA+B,CAAC;AAEjF,OAAO,EAAE,KAAK,EAAE,WAAW,EAAE,OAAO,EAAE,MAAM,sBAAsB,CAAC;AACnE,OAAO,EAAE,MAAM,EAAE,KAAK,EAAE,MAAM,uBAAuB,CAAC;AACtD,OAAO,EAAE,UAAU,EAAE,MAAM,qBAAqB,CAAC;AACjD,OAAO,EACL,eAAe,EACf,qBAAqB,EAYrB,oBAAoB,GACrB,MAAM,qBAAqB,CAAC;AAC7B,OAAO,EAAE,YAAY,EAAE,MAAM,gCAAgC,CAAC;AAE9D,OAAO,EAAE,YAAY,EAAE,qBAAqB,EAAE,SAAS,EAAE,MAAM,eAAe,CAAC;AAC/E,OAAO,EACL,cAAc,EACd,eAAe,EACf,SAAS,EACT,WAAW,EACX,oBAAoB,EACpB,gBAAgB,EAChB,aAAa,EACb,cAAc,EACd,WAAW,EACX,YAAY,EACZ,gBAAg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AAC,KAAK,CAAC,CAAC,EAAE,CAAC,GAAG,IAAI,CAAC,CAAC,CAAC;IAChF,OAAO,GAAG,CAAC;AACb,CAAC;AAED,KAAK,SAAS,CAAC,CAAC,QAAQ,CAAC,KAAkB;IACzC,IAAI,QAAQ,GAAG,CAAC,CAAC;IACjB,KAAK,MAAM,KAAK,IAAI,KAAK,CAAC,MAAM;QAAE,MAAM,EAAE,QAAQ,EAAE,QAAQ,EAAE,EAAE,OAAO,EAAE,KAAK,EAAE,QAAQ,EAAE,CAAC,EAAE,OAAO,EAAE,KAAK,EAAE,CAAC;AAChH,CAAC","sourcesContent":["// Twin of G9SyncData.Client/G9CSyncEngine.cs, .Execution.cs and .Reconcile.cs: one engine per local database, with a\r\n// prioritised run queue (status queries never wait for a running sync) and background runs that yield to user runs.\r\nimport { G9EMoveOutPolicy, G9ESyncDirection } from '../abstractions/enums.js';\r\nimport { G9SyncErrorCodes, G9SyncException, isSyncException } from '../abstractions/errors.js';\r\nimport { guidToN, newGuid } from '../abstractions/guid.js';\r\nimport { G9SyncParameters, compareOrdinal } from '../abstractions/parameters.js';\r\nimport type { G9Long } from '../abstractions/long.js';\r\nimport { delay, linkSignals, onAbort } from '../internal/abort.js';\r\nimport { sha256, toHex } from '../internal/sha256.js';\r\nimport { utf8Encode } from '../internal/utf8.js';\r\nimport {\r\n G9EPullPartKind,\r\n G9ESubscriptionAction,\r\n type G9DtChangesAvailable,\r\n type G9DtHelloResult,\r\n type G9DtNegotiatedTable,\r\n type G9DtPullPlan,\r\n type G9DtPushRequest,\r\n type G9DtPushResult,\r\n type G9DtReconcileRequest,\r\n type G9DtReconcileSummary,\r\n type G9DtSubscriptionDefinition,\r\n type G9DtSubscriptionState,\r\n type G9DtSyncChunk,\r\n syncErrorToException,\r\n} from '../protocol/dtos.js';\r\nimport { openRowBatch } from '../protocol/rowBatch/reader.js';\r\nimport type { G9SyncClientModel } from './model.js';\r\nimport { G9ESyncPhase, G9SyncProgressTracker, phaseName } from './progress.js';\r\nimport {\r\n G9ESyncOutcome,\r\n G9ESyncPriority,\r\n G9SyncRun,\r\n canCoalesce,\r\n describeModelProblem,\r\n isTransientError,\r\n makeRunResult,\r\n normalizeError,\r\n outcomeName,\r\n priorityName,\r\n requestSignature,\r\n resolveEngineOptions,\r\n resolveRequest,\r\n type G9ResolvedEngineOptions,\r\n type G9ResolvedSyncRequest,\r\n type G9RowsAppliedEvent,\r\n type G9SubscriptionOptions,\r\n type G9SyncEngineOptions,\r\n type G9SyncHealth,\r\n type G9SyncLogLevel,\r\n type G9SyncModelProblem,\r\n type G9SyncRequest,\r\n type G9SyncRunResult,\r\n} from './runs.js';\r\nimport {\r\n G9ApplyReport,\r\n G9ESubscriptionState,\r\n toSubscriptionRef,\r\n type G9ApplySlice,\r\n type G9ChangeFeedEntry,\r\n type G9ChangeFeedKeyFilter,\r\n validateChangeFeedKeyFilter,\r\n type G9LocalCommand,\r\n type G9LocalCommandWriter,\r\n type G9ELocalCommandState,\r\n type G9LocalRowEntry,\r\n type G9PendingSummary,\r\n type G9PushBatch,\r\n type G9QuarantinedRow,\r\n type G9RetainedRow,\r\n type G9SyncClientStore,\r\n type G9SyncRejection,\r\n type G9SyncRunReport,\r\n type G9SyncSubscriptionRecord,\r\n} from './storeTypes.js';\r\nimport type { G9SyncTransport } from './transport.js';\r\n\r\nconst STAT_CONNECTING = 'Connecting';\r\nconst STAT_PLANNING = 'Planning';\r\nconst STAT_PUSH_PER_K_ROW = 'PushPerKRow';\r\nconst STAT_DOWNLOAD_PER_K_ROW = 'DownloadPerKRow';\r\nconst STAT_APPLY_PER_K_ROW = 'ApplyPerKRow';\r\nconst STAT_RECONCILE_PER_SUBSCRIPTION = 'ReconcilePerSubscription';\r\n\r\ninterface QueuedRun {\r\n run: G9SyncRun;\r\n priority: number;\r\n order: number;\r\n}\r\n\r\n/**\r\n * The client sync engine (`G9CSyncEngine`): one per local database. Owns a prioritised run queue, so status queries\r\n * never wait for a running sync and background runs yield to user runs.\r\n */\r\nexport class G9SyncEngine {\r\n readonly model: G9SyncClientModel;\r\n private readonly _store: G9SyncClientStore;\r\n private readonly _transport: G9SyncTransport;\r\n private readonly _options: G9ResolvedEngineOptions;\r\n private readonly _lifetime = linkSignals();\r\n private readonly _queue: QueuedRun[] = [];\r\n private readonly _pokedTables: { [lower: string]: string } = {};\r\n private readonly _rowsAppliedListeners: ((event: G9RowsAppliedEvent) => void)[] = [];\r\n private readonly _runCompletedListeners: ((result: G9SyncRunResult) => void)[] = [];\r\n private readonly _unsubscribePokes: () => void;\r\n\r\n private _initialized = false;\r\n private _initializing: Promise<void> | null = null;\r\n private _clientId = '';\r\n private _order = 0;\r\n private _current: G9SyncRun | null = null;\r\n private _suppressions = 0;\r\n private _autoTimer: ReturnType<typeof setInterval> | null = null;\r\n private _pokeTimer: ReturnType<typeof setTimeout> | null = null;\r\n private _wake: (() => void) | null = null;\r\n private _worker: Promise<void> | null = null;\r\n private _disposed = false;\r\n /** The model problems last logged, so the warning is said once per distinct set (ADR-0061). */\r\n private _reportedModelProblems: string | null = null;\r\n\r\n constructor(store: G9SyncClientStore, transport: G9SyncTransport, model: G9SyncClientModel, options?: G9SyncEngineOptions) {\r\n if (!store) throw new TypeError('A store is required.');\r\n if (!transport) throw new TypeError('A transport is required.');\r\n if (!model) throw new TypeError('A model is required.');\r\n this._store = store;\r\n this._transport = transport;\r\n this.model = model;\r\n this._options = resolveEngineOptions(options);\r\n this._unsubscribePokes = transport.onChangesAvailable((changes) => this._onChangesAvailable(changes));\r\n }\r\n\r\n get clientId(): string {\r\n if (!this._initialized) throw new Error('Call initialize first.');\r\n return this._clientId;\r\n }\r\n\r\n get isRunning(): boolean {\r\n return this._current !== null;\r\n }\r\n\r\n get queuedRuns(): number {\r\n return this._queue.length;\r\n }\r\n\r\n get isBackgroundSuppressed(): boolean {\r\n return this._suppressions > 0;\r\n }\r\n\r\n /** Raised after rows were written locally (download, reconciliation or canonical push results). Returns the unsubscribe function. */\r\n onRowsApplied(listener: (event: G9RowsAppliedEvent) => void): () => void {\r\n this._rowsAppliedListeners.push(listener);\r\n return () => remove(this._rowsAppliedListeners, listener);\r\n }\r\n\r\n onRunCompleted(listener: (result: G9SyncRunResult) => void): () => void {\r\n this._runCompletedListeners.push(listener);\r\n return () => remove(this._runCompletedListeners, listener);\r\n }\r\n\r\n /** Provisions local tables and capture, and starts the run worker. Idempotent. */\r\n initialize(signal?: AbortSignal): Promise<void> {\r\n if (this._initialized) return Promise.resolve();\r\n if (!this._initializing) {\r\n this._initializing = (async () => {\r\n try {\r\n await this._store.initialize(this.model, signal);\r\n this._clientId = await this._store.getClientId(signal);\r\n this._initialized = true;\r\n this._worker = this._workerLoop();\r\n } finally {\r\n if (!this._initialized) this._initializing = null;\r\n }\r\n })();\r\n }\r\n return this._initializing;\r\n }\r\n\r\n // ================================================================ subscriptions\r\n\r\n /** Adds (or returns) a subscription. Its rows arrive on the next run that includes it. */\r\n async subscribe(name: string, parameters?: G9SyncParameters | null, options?: G9SubscriptionOptions | null, signal?: AbortSignal): Promise<G9SyncSubscriptionRecord> {\r\n if (typeof name !== 'string' || name.trim() === '') throw new TypeError('A subscription name is required.');\r\n await this.initialize(signal);\r\n const state = await this._store.getServerState(signal);\r\n const definition = state.definitions.find((d) => d.name === name) ?? null;\r\n const ephemeral = options?.ephemeral ?? definition?.ephemeral ?? false;\r\n const ttlMs = options?.ttlMs ?? (definition && definition.ephemeral && definition.ttlSeconds > 0 ? definition.ttlSeconds * 1000 : null);\r\n const record = await this._store.ensureSubscription(name, parameters ?? new G9SyncParameters(), ephemeral, ttlMs, options?.adoptExistingRows ?? false, signal);\r\n await this._store.updateSubscription(record.key, { accessed: true }, signal);\r\n return record;\r\n }\r\n\r\n /** Removes a subscription; rows no other subscription holds follow the server's move-out policy. */\r\n async unsubscribe(name: string, parameters?: G9SyncParameters | null, signal?: AbortSignal): Promise<void> {\r\n await this.initialize(signal);\r\n const state = await this._store.getServerState(signal);\r\n const policy = state.definitions.find((d) => d.name === name)?.moveOutPolicy ?? G9EMoveOutPolicy.Delete;\r\n await this._store.removeSubscription(G9SyncParameters.buildSubscriptionKey(name, parameters ?? null), policy, signal);\r\n }\r\n\r\n async getSubscriptions(signal?: AbortSignal): Promise<G9SyncSubscriptionRecord[]> {\r\n await this.initialize(signal);\r\n return this._store.getSubscriptions(signal);\r\n }\r\n\r\n // ================================================================ runs\r\n\r\n /** Queues a run. Identical plain requests already waiting are coalesced into one run. */\r\n run(request?: G9SyncRequest | null): G9SyncRun {\r\n if (!this._initialized) throw new Error('Call initialize first.');\r\n const resolved = resolveRequest(request);\r\n if (canCoalesce(resolved)) {\r\n const signature = requestSignature(resolved);\r\n for (const queued of this._queue) {\r\n const r = queued.run;\r\n if (!r.isStarted && canCoalesce(r.request) && r.request.priority === resolved.priority && requestSignature(r.request) === signature) return r;\r\n }\r\n }\r\n const run = new G9SyncRun(resolved);\r\n this._queue.push({ run, priority: resolved.priority, order: this._order++ });\r\n const current = this._current;\r\n let preempted: G9SyncRun | null = null;\r\n if (current !== null && current.request.priority === G9ESyncPriority.Background && resolved.priority > G9ESyncPriority.Background) {\r\n current.preempted = true;\r\n preempted = current;\r\n }\r\n this._signal();\r\n if (preempted) {\r\n preempted.cancel();\r\n this._log('information', 20001, `Background run ${preempted.runId} pre-empted by run ${run.runId}`);\r\n }\r\n return run;\r\n }\r\n\r\n /** Queues a run and awaits its result. */\r\n sync(request?: G9SyncRequest | null): Promise<G9SyncRunResult> {\r\n return this.run(request).completion;\r\n }\r\n\r\n /** While the returned scope is alive, background runs are skipped. Call the returned function to end it. */\r\n suppressBackground(): () => void {\r\n this._suppressions++;\r\n let done = false;\r\n return () => {\r\n if (done) return;\r\n done = true;\r\n this._suppressions--;\r\n };\r\n }\r\n\r\n /** Queues a background push+pull of every non-heavy subscription on a fixed interval. */\r\n startAutomaticSync(intervalMs: number): void {\r\n if (!(intervalMs > 0)) throw new RangeError('The interval must be positive.');\r\n this.stopAutomaticSync();\r\n this._autoTimer = setInterval(() => this._tryQueueBackground(null), intervalMs);\r\n }\r\n\r\n stopAutomaticSync(): void {\r\n if (this._autoTimer !== null) {\r\n clearInterval(this._autoTimer);\r\n this._autoTimer = null;\r\n }\r\n }\r\n\r\n // ================================================================ queries\r\n\r\n /**\r\n * Records a command (ADR-0025): the server executes the handler registered for `name` on the next push, once, in\r\n * device order. `applyLocally` writes its local effects immediately, in the same transaction.\r\n */\r\n async executeCommand(\r\n name: string,\r\n payloadJson: string,\r\n applyLocally?: ((writer: G9LocalCommandWriter, signal?: AbortSignal) => Promise<void>) | null,\r\n version = 1,\r\n signal?: AbortSignal,\r\n ): Promise<G9LocalCommand> {\r\n if (typeof name !== 'string' || name.trim() === '') throw new TypeError('A command name is required.');\r\n if (typeof payloadJson !== 'string') throw new TypeError('The payload JSON is required.');\r\n await this.initialize(signal);\r\n return this._store.enqueueCommand({ name, version, payload: payloadJson }, applyLocally ?? null, signal);\r\n }\r\n\r\n /** Frees space taken by an UPLOAD-ONLY table: removes uploaded rows without uploading a delete. */\r\n async forgetUploadedRows(localTable: string, keys?: readonly string[] | null, signal?: AbortSignal): Promise<number> {\r\n await this.initialize(signal);\r\n return this._store.forgetUploadedRows(localTable, keys ?? null, signal);\r\n }\r\n\r\n async getCommands(state?: G9ELocalCommandState | null, limit = 200, signal?: AbortSignal): Promise<G9LocalCommand[]> {\r\n await this.initialize(signal);\r\n return this._store.getCommands(state ?? null, limit, signal);\r\n }\r\n\r\n async getPendingSummary(signal?: AbortSignal): Promise<G9PendingSummary> {\r\n await this.initialize(signal);\r\n return this._store.getPendingSummary(signal);\r\n }\r\n\r\n async getRejections(signal?: AbortSignal): Promise<G9SyncRejection[]> {\r\n await this.initialize(signal);\r\n return this._store.getRejections(signal);\r\n }\r\n\r\n async getQuarantined(signal?: AbortSignal): Promise<G9QuarantinedRow[]> {\r\n await this.initialize(signal);\r\n return this._store.getQuarantined(signal);\r\n }\r\n\r\n async restoreQuarantined(localTable: string, key: string, signal?: AbortSignal): Promise<number> {\r\n await this.initialize(signal);\r\n return this._store.restoreQuarantined(localTable, key, signal);\r\n }\r\n\r\n /** Throws away every staged pull, so the next run plans afresh. Returns whether there was one. */\r\n async discardStagedPull(signal?: AbortSignal): Promise<boolean> {\r\n await this.initialize(signal);\r\n return (await this._store.discardAllStagedPulls(signal)) > 0;\r\n }\r\n\r\n async discardQuarantined(localTable?: string | null, key?: string | null, signal?: AbortSignal): Promise<number> {\r\n await this.initialize(signal);\r\n return this._store.discardQuarantined(localTable ?? null, key ?? null, signal);\r\n }\r\n\r\n async getRetained(signal?: AbortSignal): Promise<G9RetainedRow[]> {\r\n await this.initialize(signal);\r\n return this._store.getRetained(signal);\r\n }\r\n\r\n async retryRejected(localTable?: string | null, key?: string | null, signal?: AbortSignal): Promise<number> {\r\n await this.initialize(signal);\r\n return this._store.retryRejected(localTable ?? null, key ?? null, signal);\r\n }\r\n\r\n /**\r\n * Gives up the local change of rejected rows and takes the server's copy (LES-0070, .NET `RevertRejectedAsync`): a row the server\r\n * never had is removed locally, any other is fetched again by the next run with `forceReconcile` - run one after this. Nothing is\r\n * uploaded. Omitted arguments widen the scope.\r\n */\r\n async revertRejected(localTable?: string | null, key?: string | null, signal?: AbortSignal): Promise<number> {\r\n await this.initialize(signal);\r\n return this._store.revertRejected(localTable ?? null, key ?? null, signal);\r\n }\r\n\r\n async readChangeFeed(localTable: string, afterSequence: number, limit = 1000, signal?: AbortSignal): Promise<G9ChangeFeedEntry[]> {\r\n await this.initialize(signal);\r\n return this._store.readChangeFeed(localTable, afterSequence, limit, signal);\r\n }\r\n\r\n /**\r\n * The change feed for one table narrowed to the keys `keyFilter` selects (plus every deletion), so a projection of one site does\r\n * not walk the entries of every other one (`ReadChangeFeedAsync(..., G9CChangeFeedKeyFilter, ...)`).\r\n */\r\n async readChangeFeedFiltered(localTable: string, afterSequence: number, limit: number, keyFilter: G9ChangeFeedKeyFilter, signal?: AbortSignal): Promise<G9ChangeFeedEntry[]> {\r\n validateChangeFeedKeyFilter(keyFilter);\r\n await this.initialize(signal);\r\n return this._store.readChangeFeedFiltered(localTable, afterSequence, limit, keyFilter, signal);\r\n }\r\n\r\n /** The highest sequence readChangeFeed can return today (a watermark above it belongs to a store that no longer exists). */\r\n async getChangeSequence(signal?: AbortSignal): Promise<number> {\r\n await this.initialize(signal);\r\n return this._store.getChangeSequence(signal);\r\n }\r\n\r\n /** The highest sequence ever purged from the change feed; 0 when nothing was (ADR-0059). */\r\n async getChangeFeedFloor(signal?: AbortSignal): Promise<number> {\r\n await this.initialize(signal);\r\n return this._store.getChangeFeedFloor(signal);\r\n }\r\n\r\n async adoptExistingRows(signal?: AbortSignal): Promise<number> {\r\n await this.initialize(signal);\r\n return this._store.adoptExistingRows(signal);\r\n }\r\n\r\n async markDirty(localTable: string, keys: readonly string[], signal?: AbortSignal): Promise<number> {\r\n await this.initialize(signal);\r\n return this._store.markDirty(localTable, keys, signal);\r\n }\r\n\r\n async getHealth(signal?: AbortSignal): Promise<G9SyncHealth> {\r\n await this.initialize(signal);\r\n const state = await this._store.getServerState(signal);\r\n return {\r\n clientId: this._clientId,\r\n isConnected: this._transport.isConnected,\r\n isRunning: this.isRunning,\r\n queuedRuns: this.queuedRuns,\r\n serverEpoch: state.epoch,\r\n lastHelloUtcMs: state.lastHelloUtcMs,\r\n pending: await this._store.getPendingSummary(signal),\r\n subscriptions: await this._store.getSubscriptions(signal),\r\n recentRuns: await this._store.getRecentRunReports(10, signal),\r\n };\r\n }\r\n\r\n async dispose(): Promise<void> {\r\n if (this._disposed) return;\r\n this._disposed = true;\r\n this.stopAutomaticSync();\r\n this._unsubscribePokes();\r\n this._lifetime.abort();\r\n const abandoned = this._queue.splice(0, this._queue.length);\r\n for (const { run } of abandoned) {\r\n run.complete(makeRunResult({ runId: run.runId, outcome: G9ESyncOutcome.Canceled, error: new G9SyncException(G9SyncErrorCodes.Canceled, 'The sync engine was disposed.') }));\r\n }\r\n this._current?.cancel();\r\n this._signal();\r\n if (this._worker) {\r\n try {\r\n await this._worker;\r\n } catch {\r\n // shutting down\r\n }\r\n }\r\n if (this._pokeTimer !== null) {\r\n clearTimeout(this._pokeTimer);\r\n this._pokeTimer = null;\r\n }\r\n }\r\n\r\n // ================================================================ worker\r\n\r\n private _signal(): void {\r\n const wake = this._wake;\r\n this._wake = null;\r\n if (wake) wake();\r\n }\r\n\r\n private _dequeue(): G9SyncRun | null {\r\n if (this._queue.length === 0) return null;\r\n let best = 0;\r\n for (let i = 1; i < this._queue.length; i++) {\r\n const a = this._queue[i] as QueuedRun;\r\n const b = this._queue[best] as QueuedRun;\r\n if (a.priority > b.priority || (a.priority === b.priority && a.order < b.order)) best = i;\r\n }\r\n return (this._queue.splice(best, 1)[0] as QueuedRun).run;\r\n }\r\n\r\n private async _workerLoop(): Promise<void> {\r\n while (!this._lifetime.signal.aborted) {\r\n const run = this._dequeue();\r\n if (!run) {\r\n await new Promise<void>((resolve) => {\r\n this._wake = resolve;\r\n });\r\n continue;\r\n }\r\n run.isStarted = true;\r\n this._current = run;\r\n try {\r\n await this._executeRun(run);\r\n } catch (exception) {\r\n this._log('error', 20002, `Unexpected failure executing run ${run.runId}`, exception);\r\n run.complete(makeRunResult({ runId: run.runId, outcome: G9ESyncOutcome.Failed, error: normalizeError(exception) }));\r\n } finally {\r\n this._current = null;\r\n }\r\n // A pre-empted background run still owes its work: queue it again behind the run that pre-empted it.\r\n if (run.preempted && run.request.priority === G9ESyncPriority.Background) this._tryQueueBackground(run.request.subscriptions);\r\n }\r\n }\r\n\r\n private _tryQueueBackground(subscriptions: readonly string[] | null): void {\r\n if (!this._initialized || this.isBackgroundSuppressed || (this._options.hooks && !this._options.hooks.isNetworkAvailable) || this._lifetime.signal.aborted) {\r\n return;\r\n }\r\n this.run({ priority: G9ESyncPriority.Background, subscriptions });\r\n }\r\n\r\n private _onChangesAvailable(payload: G9DtChangesAvailable): void {\r\n if (!this._options.pullOnChangesAvailable || payload.tables.length === 0) return;\r\n for (const table of payload.tables) this._pokedTables[table.toLowerCase()] = table;\r\n if (this._pokeTimer === null) this._pokeTimer = setTimeout(() => this._flushPokes(), this._options.changesDebounceMs);\r\n }\r\n\r\n private _flushPokes(): void {\r\n const tables = Object.keys(this._pokedTables);\r\n for (const key of tables) delete this._pokedTables[key];\r\n this._pokeTimer = null;\r\n if (tables.length === 0 || !this._initialized) return;\r\n const signal = this._lifetime.signal;\r\n void (async () => {\r\n try {\r\n const state = await this._store.getServerState(signal);\r\n const names: { [name: string]: true } = {};\r\n let any = false;\r\n for (const d of state.definitions) {\r\n if (!d.heavy && d.tables.some((t) => tables.indexOf(t.toLowerCase()) >= 0)) {\r\n names[d.name] = true;\r\n any = true;\r\n }\r\n }\r\n if (!any) return;\r\n const keys = (await this._store.getSubscriptions(signal)).filter((s) => names[s.name] === true).map((s) => s.key);\r\n if (keys.length > 0) this._tryQueueBackground(keys);\r\n } catch (exception) {\r\n if (!signal.aborted) this._log('warning', 20003, 'Handling a server change notification failed', exception);\r\n }\r\n })();\r\n }\r\n\r\n private _raiseRowsApplied(report: G9ApplyReport, source: G9ESyncPhase, slice: G9ApplySlice | null = null): void {\r\n for (const listener of this._rowsAppliedListeners.slice()) {\r\n try {\r\n listener({ report, source, slice });\r\n } catch (exception) {\r\n this._log('warning', 20004, 'A RowsApplied handler threw', exception);\r\n }\r\n }\r\n }\r\n\r\n private _log(level: G9SyncLogLevel, eventId: number, message: string, error?: unknown): void {\r\n const logger = this._options.logger;\r\n if (!logger) return;\r\n try {\r\n logger.log(level, eventId, message, error);\r\n } catch {\r\n // A logger must never break the sync.\r\n }\r\n }\r\n\r\n // ================================================================ execution\r\n\r\n private async _executeRun(run: G9SyncRun): Promise<void> {\r\n const request = run.request;\r\n const startedUtcMs = Date.now();\r\n const changes = new G9ApplyReport();\r\n const problems: G9DtSubscriptionState[] = [];\r\n let modelProblems: G9SyncModelProblem[] = [];\r\n const synced: string[] = [];\r\n let pushed = 0;\r\n let accepted = 0;\r\n let rejected = 0;\r\n let conflicts = 0;\r\n let downloaded = 0;\r\n let downloadedBytes = 0;\r\n let reconciled = 0;\r\n let error: G9SyncException | null = null;\r\n let outcome: G9ESyncOutcome = G9ESyncOutcome.Succeeded;\r\n\r\n const tracker = new G9SyncProgressTracker(run.runId, (p) => run.publish(p), () => this.queuedRuns, this._options.progressMaxHz);\r\n try {\r\n if (request.priority === G9ESyncPriority.Background && this.isBackgroundSuppressed) {\r\n tracker.complete(G9ESyncPhase.Canceled);\r\n run.complete(makeRunResult({ runId: run.runId, outcome: G9ESyncOutcome.Canceled, error: new G9SyncException(G9SyncErrorCodes.Canceled, 'Background sync is suppressed.') }));\r\n return;\r\n }\r\n\r\n const linked = linkSignals(run.cancellation.signal, this._lifetime.signal);\r\n const ct = linked.signal;\r\n const cancelRegistration = onAbort(ct, () => tracker.setCancelPending());\r\n let hostScope: { dispose(): void | Promise<void> } | null = null;\r\n\r\n try {\r\n const history = await this._store.getPhaseStatistics(ct);\r\n const pending = request.push ? await this._store.getPendingSummary(ct) : null;\r\n this._planPhases(tracker, history, request, pending ? pending.totalRows : 0);\r\n if (this._options.hooks) hostScope = await this._options.hooks.beginRun(run, ct);\r\n\r\n // ---------------------------------------------------------------- 1. connect + hello\r\n tracker.enter(G9ESyncPhase.Connecting);\r\n await this._ensureConnected(ct);\r\n await this._store.collectExpiredEphemeral(Date.now(), ct);\r\n const subscriptions = await this._store.getSubscriptions(ct);\r\n const hello = await this._withRetry(\r\n (token) =>\r\n this._transport.hello(\r\n {\r\n clientId: this._clientId,\r\n appVersion: this._options.appVersion,\r\n protocolVersion: 1,\r\n tables: this.model.tables.map((t) => t.toWire()),\r\n subscriptions: subscriptions.map(toSubscriptionRef),\r\n },\r\n token,\r\n ),\r\n ct,\r\n );\r\n if (hello.error) throw syncErrorToException(hello.error);\r\n await this._store.saveHello(hello, ct);\r\n if (hello.unknownTables.length > 0) {\r\n this._log('warning', 20016, 'The server does not know these client tables (they will not sync): ' + hello.unknownTables.join(', '));\r\n }\r\n\r\n // A column declared with the wrong type syncs in NEITHER direction (ADR-0061): say it on every run's result, and once\r\n // per distinct set in the log.\r\n modelProblems = [];\r\n for (const table of hello.tables) {\r\n for (const column of table.typeMismatchColumns) {\r\n modelProblems.push({ code: G9SyncErrorCodes.ModelTypeMismatch, table: table.name, column: column.name, clientType: column.clientType, serverType: column.serverType });\r\n }\r\n }\r\n if (modelProblems.length > 0) {\r\n const described = modelProblems.map(describeModelProblem).join('; ');\r\n if (this._reportedModelProblems !== described) {\r\n this._reportedModelProblems = described;\r\n this._log(\r\n 'warning',\r\n 20022,\r\n `The client model declares ${modelProblems.length} column(s) with a type the server does not have; they sync in NEITHER direction until the model is fixed: ${described}`,\r\n );\r\n }\r\n if (this._options.failOnTypeMismatch) {\r\n throw new G9SyncException(G9SyncErrorCodes.ModelTypeMismatch, 'The client model declares column types the server does not have; those columns would not sync: ' + described);\r\n }\r\n }\r\n\r\n const negotiated = hello.tables;\r\n const definitions: { [name: string]: G9DtSubscriptionDefinition } = {};\r\n for (const d of hello.definitions) definitions[d.name] = d;\r\n const states: { [key: string]: G9DtSubscriptionState } = {};\r\n for (const state of hello.subscriptions) states[state.key] = state;\r\n\r\n // ---------------------------------------------------------------- 2. push\r\n // A FAILED PUSH MUST NOT COST THE PULL: the failure is rethrown after the pull, never swallowed.\r\n let pushFailure: { error: unknown } | null = null;\r\n if (request.push && pending && (pending.totalRows > 0 || pending.pendingCommands > 0)) {\r\n tracker.enter(G9ESyncPhase.Pushing, pending.totalRows + pending.pendingCommands);\r\n try {\r\n const totals = await this._pushAll(negotiated, subscriptions, hello.maxPushRows, hello.maxPushBytes, tracker, changes, ct);\r\n pushed = totals.pushed;\r\n accepted = totals.accepted;\r\n rejected = totals.rejected;\r\n conflicts = totals.conflicts;\r\n } catch (exception) {\r\n if (ct.aborted) throw exception;\r\n this._log('warning', 20019, `Run ${run.runId}: the push failed; continuing to the pull so the device keeps receiving, then reporting the failure`, exception);\r\n pushFailure = { error: exception };\r\n }\r\n }\r\n\r\n if (request.pull) {\r\n // ------------------------------------------------------------ 3. select subscriptions (+ dependencies)\r\n const selected = await this._selectSubscriptions(request, subscriptions, definitions, problems, ct);\r\n const usable: G9SyncSubscriptionRecord[] = [];\r\n for (const subscription of selected) {\r\n const state = states[subscription.key];\r\n if (\r\n state &&\r\n (state.action === G9ESubscriptionAction.Unknown || state.action === G9ESubscriptionAction.InvalidParameters || state.action === G9ESubscriptionAction.Forbidden)\r\n ) {\r\n problems.push(state);\r\n await this._store.updateSubscription(subscription.key, { state: G9ESubscriptionState.Failed, errorCode: actionCode(state.action) }, ct);\r\n // Forbidden: these rows are no longer this caller's to hold (ADR-0048).\r\n if (state.action === G9ESubscriptionAction.Forbidden) {\r\n const released = await this._store.releaseSubscriptionRows(subscription.key, ct);\r\n changes.merge(released);\r\n if (released.total > 0) {\r\n this._log(\r\n 'warning',\r\n 20018,\r\n `Subscription ${subscription.key} is forbidden; released its rows (${released.revokedDeleted} deleted, ${released.revokedQuarantined} quarantined, ${released.revokedRetained} retained)`,\r\n );\r\n this._raiseRowsApplied(released, G9ESyncPhase.Reconciling);\r\n }\r\n }\r\n continue;\r\n }\r\n usable.push(subscription);\r\n }\r\n\r\n // ------------------------------------------------------------ 4. reconcile\r\n const now = Date.now();\r\n const toReconcile = usable.filter((s) => needsReconcile(s, request, states, definitions, now));\r\n tracker.expect(G9ESyncPhase.Reconciling, toReconcile.length * historyOf(history, STAT_RECONCILE_PER_SUBSCRIPTION, 2500));\r\n if (toReconcile.length > 0) {\r\n tracker.enter(G9ESyncPhase.Reconciling, toReconcile.length);\r\n let done = 0;\r\n for (const subscription of toReconcile) {\r\n try {\r\n const report = await this._reconcileSubscription(subscription, definitions[subscription.name] as G9DtSubscriptionDefinition, negotiated, ct);\r\n changes.merge(report);\r\n reconciled += report.total;\r\n if (report.total > 0) this._raiseRowsApplied(report, G9ESyncPhase.Reconciling);\r\n } catch (exception) {\r\n if (isSyncException(exception) && !exception.retryable && exception.code !== G9SyncErrorCodes.Canceled) {\r\n problems.push({ key: subscription.key, action: G9ESubscriptionAction.Reconcile, message: exception.message });\r\n await this._store.updateSubscription(subscription.key, { state: G9ESubscriptionState.Failed, errorCode: exception.code }, ct);\r\n } else {\r\n throw exception;\r\n }\r\n }\r\n tracker.report(++done, -1, null, subscription.key);\r\n }\r\n }\r\n\r\n // ------------------------------------------------------------ 5. plan (or resume a staged pull)\r\n tracker.enter(G9ESyncPhase.Planning);\r\n const failedKeys: { [key: string]: true } = {};\r\n for (const p of problems) failedKeys[p.key] = true;\r\n const current: { [key: string]: G9SyncSubscriptionRecord } = {};\r\n for (const s of await this._store.getSubscriptions(ct)) current[s.key] = s;\r\n const plannable = usable.filter((s) => !failedKeys[s.key] && current[s.key] !== undefined).map((s) => current[s.key] as G9SyncSubscriptionRecord);\r\n\r\n // A stage is kept PER GENERATION (ADR-0060); what makes one resumable is that the epoch, permissions, columns and\r\n // the cursors it was planned from are all still exactly what they were.\r\n const generation = stageGeneration(hello, plannable, states, negotiated);\r\n const pruned = await this._store.pruneStagedPulls(Date.now() - this._options.stagedPullMaxAgeMs, this._options.stagedPullsMaxBytes, generation, ct);\r\n if (pruned > 0) this._log('information', 20021, `Removed ${pruned} staged pull(s) past their age or the byte cap`);\r\n\r\n // Snapshot files are offered unless one already failed in this run (ADR-0072): a file is a faster way to the same rows,\r\n // never the only one, so a file the server cannot build or the device rejects costs one replan as rows - not the run.\r\n let allowFiles = this._options.acceptSnapshotFiles;\r\n for (let attempt = 0; ; attempt++) {\r\n const problemsBefore = problems.length;\r\n const syncedBefore = synced.length;\r\n let runId: string | null = null;\r\n try {\r\n const staged = await this._store.getStagedPullForGeneration(generation, ct);\r\n let plan: G9DtPullPlan;\r\n if (staged && staged.createdUtcMs > Date.now() - this._options.stagedPullMaxAgeMs) {\r\n plan = staged.plan;\r\n runId = staged.runId;\r\n this._log('information', 20012, `Resuming staged pull ${runId} (${plan.totalRows} rows planned)`);\r\n } else {\r\n const backfills = await this._store.getPendingBackfills(ct);\r\n const files = allowFiles && this._store.describeSnapshotFiles ? this._store.describeSnapshotFiles(negotiated) : null;\r\n plan = await this._withRetry(\r\n (token) =>\r\n this._transport.planPull(\r\n {\r\n clientId: this._clientId,\r\n subscriptions: plannable.map(toSubscriptionRef),\r\n tables: negotiated.map((t) => ({ tableId: t.tableId, columns: t.columns.map((c) => c.name) })),\r\n backfills: backfills.slice(),\r\n frameVersion: this._options.maxFrameVersion,\r\n ...(files ? { snapshotFiles: files } : {}),\r\n },\r\n token,\r\n ),\r\n ct,\r\n );\r\n if (plan.error) throw syncErrorToException(plan.error);\r\n runId = guidToN(newGuid());\r\n const plannedFromCursors: { [key: string]: string | null } = {};\r\n for (const s of plannable) plannedFromCursors[s.key] = s.cursor;\r\n await this._store.beginStagedPull(\r\n { runId, plan, createdUtcMs: Date.now(), backfills, generation, plannedFromCursors, stageSequence: 0 },\r\n ct,\r\n );\r\n }\r\n\r\n for (const skipped of plan.skipped) {\r\n problems.push(skipped);\r\n if (skipped.action === G9ESubscriptionAction.Reconcile || skipped.action === G9ESubscriptionAction.ResyncRequired) {\r\n await this._store.updateSubscription(skipped.key, { state: G9ESubscriptionState.NeedsReconcile }, ct);\r\n }\r\n }\r\n\r\n for (const c of plan.cursors) synced.push(c.key);\r\n const fileParts = plan.parts.filter((p) => p.kind === G9EPullPartKind.SnapshotFile);\r\n if (fileParts.length > 0) {\r\n this._log('information', 20025, `The pull carries ${fileParts.length} snapshot file(s) for ${fileParts.reduce((sum, p) => sum + p.rows, 0)} row(s)`);\r\n }\r\n tracker.expect(G9ESyncPhase.Downloading, Math.max(200, (plan.totalRows / 1000) * historyOf(history, STAT_DOWNLOAD_PER_K_ROW, 350)));\r\n tracker.expect(G9ESyncPhase.Applying, Math.max(100, (plan.totalRows / 1000) * historyOf(history, STAT_APPLY_PER_K_ROW, 250)));\r\n\r\n // ------------------------------------------------------------ 6. download (resumable)\r\n tracker.enter(G9ESyncPhase.Downloading, plan.totalRows, plan.estimatedBytes);\r\n const totals = await this._download(runId, plan, tracker, ct);\r\n downloaded = totals.rows;\r\n downloadedBytes = totals.bytes;\r\n\r\n // ------------------------------------------------------------ 7. apply (atomic, or in committed slices)\r\n tracker.enter(G9ESyncPhase.Applying, downloaded);\r\n const applied = await this._store.applyStagedPull(\r\n runId,\r\n (rows) => tracker.report(rows),\r\n (slice) => {\r\n if (slice.report.total > 0) this._raiseRowsApplied(slice.report, G9ESyncPhase.Applying, slice);\r\n },\r\n ct,\r\n );\r\n changes.merge(applied);\r\n break;\r\n } catch (exception) {\r\n if (\r\n attempt === 0 &&\r\n !ct.aborted &&\r\n isSyncException(exception) &&\r\n (exception.code === G9SyncErrorCodes.SnapshotFileUnavailable || exception.code === G9SyncErrorCodes.SnapshotFileCorrupt)\r\n ) {\r\n this._log('warning', 20026, `A snapshot file failed (${exception.code}); the staged download was discarded and the pull is planned again as rows`, exception);\r\n if (runId !== null) await this._store.discardStagedPull(runId);\r\n problems.length = problemsBefore;\r\n synced.length = syncedBefore;\r\n allowFiles = false;\r\n tracker.enter(G9ESyncPhase.Planning);\r\n continue;\r\n }\r\n throw exception;\r\n }\r\n }\r\n }\r\n\r\n // ---------------------------------------------------------------- 8. post steps\r\n for (const step of request.postSteps) {\r\n tracker.enter(G9ESyncPhase.PostStep, 0, 0, step.name);\r\n await step.action({ run, changes, progress: (fraction) => tracker.reportFraction(fraction) }, ct);\r\n }\r\n\r\n // Rows retained after revocation by a RetainWhile rule are re-checked once per run (ADR-0026).\r\n changes.revokedDeleted += await this._store.reevaluateRetained(ct);\r\n\r\n // The pull has been applied and its cursors committed; now the push failure decides the run's fate.\r\n if (pushFailure) throw pushFailure.error;\r\n\r\n outcome = rejected > 0 || problems.length > 0 ? G9ESyncOutcome.CompletedWithRejections : G9ESyncOutcome.Succeeded;\r\n tracker.complete(G9ESyncPhase.Completed);\r\n } catch (exception) {\r\n if (ct.aborted) {\r\n outcome = G9ESyncOutcome.Canceled;\r\n error = new G9SyncException(G9SyncErrorCodes.Canceled, run.preempted ? 'Pre-empted by a higher-priority sync.' : 'The sync was canceled.', { cause: exception });\r\n tracker.complete(G9ESyncPhase.Canceled);\r\n } else {\r\n error = normalizeError(exception);\r\n outcome = G9ESyncOutcome.Failed;\r\n tracker.complete(G9ESyncPhase.Failed);\r\n this._log('warning', 20011, `Run ${run.runId} failed with ${error.code}`, error);\r\n }\r\n } finally {\r\n cancelRegistration();\r\n linked.dispose();\r\n if (hostScope) {\r\n try {\r\n await hostScope.dispose();\r\n } catch (exception) {\r\n this._log('warning', 20004, 'A host scope handler threw', exception);\r\n }\r\n }\r\n }\r\n\r\n const durations = tracker.durations;\r\n const phaseMs: { [phase: string]: number } = {};\r\n for (const key of Object.keys(durations)) phaseMs[key] = Math.floor(durations[key] as number);\r\n const result = makeRunResult({\r\n runId: run.runId,\r\n outcome,\r\n error,\r\n pushed,\r\n accepted,\r\n rejected,\r\n conflicts,\r\n downloaded,\r\n applied: changes.total,\r\n durationMs: Date.now() - startedUtcMs,\r\n subscriptions: synced,\r\n problems,\r\n modelProblems,\r\n changes,\r\n phaseMs,\r\n });\r\n\r\n try {\r\n await this._persistRun(run, result, durations, startedUtcMs, downloadedBytes, reconciled);\r\n } catch (exception) {\r\n this._log('warning', 20004, 'A run report handler threw', exception);\r\n }\r\n\r\n this._log(\r\n 'information',\r\n 20010,\r\n `Run ${run.runId} finished ${outcomeName(outcome)}: pushed ${pushed}, downloaded ${downloaded}, applied ${changes.total} in ${result.durationMs} ms`,\r\n );\r\n run.complete(result);\r\n for (const listener of this._runCompletedListeners.slice()) {\r\n try {\r\n listener(result);\r\n } catch (exception) {\r\n this._log('warning', 20004, 'A RunCompleted handler threw', exception);\r\n }\r\n }\r\n } finally {\r\n tracker.dispose();\r\n }\r\n }\r\n\r\n private _planPhases(tracker: G9SyncProgressTracker, history: { [key: string]: number }, request: G9ResolvedSyncRequest, pendingRows: number): void {\r\n const connecting = historyOf(history, STAT_CONNECTING, 800);\r\n const pushing = request.push && pendingRows > 0 ? Math.max(300, (pendingRows / 1000) * historyOf(history, STAT_PUSH_PER_K_ROW, 1200)) : 0;\r\n const planning = request.pull ? historyOf(history, STAT_PLANNING, 700) : 0;\r\n const downloading = request.pull ? 2000 : 0;\r\n const applying = request.pull ? 1500 : 0;\r\n tracker.plan(G9ESyncPhase.Connecting, connecting);\r\n if (pushing > 0) tracker.plan(G9ESyncPhase.Pushing, pushing);\r\n if (request.pull) {\r\n tracker.plan(G9ESyncPhase.Reconciling, 0);\r\n tracker.plan(G9ESyncPhase.Planning, planning);\r\n tracker.plan(G9ESyncPhase.Downloading, downloading);\r\n tracker.plan(G9ESyncPhase.Applying, applying);\r\n }\r\n const core = connecting + pushing + planning + downloading + applying;\r\n for (const step of request.postSteps) {\r\n const hint = step.weightHint;\r\n tracker.plan(G9ESyncPhase.PostStep, historyOf(history, 'PostStep:' + step.name, hint >= 0.9 ? core * 9 : (core * hint) / (1 - hint)), step.name);\r\n }\r\n }\r\n\r\n private async _selectSubscriptions(\r\n request: G9ResolvedSyncRequest,\r\n all: G9SyncSubscriptionRecord[],\r\n definitions: { [name: string]: G9DtSubscriptionDefinition },\r\n problems: G9DtSubscriptionState[],\r\n ct: AbortSignal,\r\n ): Promise<G9SyncSubscriptionRecord[]> {\r\n const byKey: { [key: string]: G9SyncSubscriptionRecord } = {};\r\n for (const s of all) byKey[s.key] = s;\r\n const wanted = request.subscriptions;\r\n let roots = wanted === null ? all.slice() : all.filter((s) => wanted.indexOf(s.key) >= 0 || wanted.indexOf(s.name) >= 0);\r\n if (request.priority === G9ESyncPriority.Background && wanted === null) {\r\n roots = roots.filter((s) => !(definitions[s.name] && (definitions[s.name] as G9DtSubscriptionDefinition).heavy));\r\n }\r\n const ordered: G9SyncSubscriptionRecord[] = [];\r\n const visiting: { [key: string]: true } = {};\r\n const done: { [key: string]: true } = {};\r\n\r\n const visit = async (record: G9SyncSubscriptionRecord): Promise<void> => {\r\n if (done[record.key] || visiting[record.key]) return;\r\n visiting[record.key] = true;\r\n const definition = definitions[record.name];\r\n if (definition) {\r\n for (const dependency of definition.dependsOn) {\r\n const parentDefinition = definitions[dependency.name];\r\n if (!parentDefinition) {\r\n if (dependency.required) {\r\n problems.push({ key: record.key, action: G9ESubscriptionAction.Unknown, message: `Required dependency '${dependency.name}' is not available.` });\r\n }\r\n continue;\r\n }\r\n let parent = byKey[dependency.name];\r\n if (!parent) {\r\n parent = await this._store.ensureSubscription(\r\n dependency.name,\r\n new G9SyncParameters(),\r\n parentDefinition.ephemeral,\r\n parentDefinition.ephemeral ? parentDefinition.ttlSeconds * 1000 : null,\r\n false,\r\n ct,\r\n );\r\n byKey[parent.key] = parent;\r\n }\r\n await visit(parent);\r\n }\r\n }\r\n done[record.key] = true;\r\n ordered.push(record);\r\n };\r\n\r\n // Creation order. Two subscriptions created in the same millisecond keep it through their slots (handed out lowest\r\n // free first), then the key, ordinal (JS `<` compares UTF-16 units, like StringComparer.Ordinal) — never the order\r\n // the store happened to list them in (by key: a random GUID decided which site's rows came first, LES-0052).\r\n const sorted = roots\r\n .map((r, i) => ({ r, i }))\r\n .sort((a, b) => a.r.createdUtcMs - b.r.createdUtcMs || a.r.slot - b.r.slot || (a.r.key < b.r.key ? -1 : a.r.key > b.r.key ? 1 : 0) || a.i - b.i);\r\n for (const { r } of sorted) await visit(r);\r\n return ordered;\r\n }\r\n\r\n private async _pushAll(\r\n negotiated: G9DtNegotiatedTable[],\r\n subscriptions: G9SyncSubscriptionRecord[],\r\n serverMaxRows: number,\r\n serverMaxBytes: number,\r\n tracker: G9SyncProgressTracker,\r\n changes: G9ApplyReport,\r\n ct: AbortSignal,\r\n ): Promise<{ pushed: number; accepted: number; rejected: number; conflicts: number }> {\r\n let pushed = 0;\r\n let accepted = 0;\r\n let rejected = 0;\r\n let conflicts = 0;\r\n const references = subscriptions.map(toSubscriptionRef);\r\n // The server's limits win over the device's preference; bytes keep a margin for the header and compression variance.\r\n const targetRows = Math.max(1, serverMaxRows > 0 ? Math.min(this._options.pushBatchRows, serverMaxRows) : this._options.pushBatchRows);\r\n let batchRows = targetRows;\r\n const batchBytes = serverMaxBytes > 0 ? Math.floor(serverMaxBytes * 0.9) : Number.MAX_SAFE_INTEGER;\r\n for (;;) {\r\n const batch = await this._store.buildPushBatch(negotiated, batchRows, batchBytes, ct);\r\n if (!batch) break;\r\n rejected += batch.rejectedLocally;\r\n if (batch.rowCount === 0 && batch.commands.length === 0) break; // only rows that can never be uploaded were left\r\n\r\n const request: G9DtPushRequest = {\r\n clientId: this._clientId,\r\n batchId: batch.batchId,\r\n subscriptions: references,\r\n tables: batch.tables.slice(),\r\n commands: batch.commands.slice(),\r\n // Canonical rows come back in the columns the DEVICE holds (LES-0035).\r\n heldTables: negotiated\r\n .filter((t) => batch.commands.length > 0 || batch.tables.some((p) => p.tableId === t.tableId))\r\n .map((t) => ({ tableId: t.tableId, columns: t.columns.map((c) => c.name) })),\r\n frameVersion: this._options.maxFrameVersion,\r\n };\r\n let result: G9DtPushResult;\r\n try {\r\n result = await this._withRetry((token) => this._transport.push(request, toChunks(batch), token), ct);\r\n if (result.error) throw syncErrorToException(result.error);\r\n } catch (exception) {\r\n if (isSyncException(exception) && exception.code === G9SyncErrorCodes.RejectTooMany && batchRows > 1 && batch.rowCount > 1) {\r\n // The server rolled the WHOLE push back for too many rejections (ADR-0063): halve and resend the smaller prefix\r\n // under the same batch id, so the valid rows get through and the bad ones are parked one by one.\r\n batchRows = Math.max(1, Math.floor(Math.min(batchRows, batch.rowCount) / 2));\r\n this._log(\r\n 'warning',\r\n 20023,\r\n `Push batch ${batch.batchId} of ${batch.rowCount} rows was rolled back for too many rejections; sending it again as ${batchRows} rows so the valid rows get through`,\r\n );\r\n continue;\r\n }\r\n throw exception;\r\n }\r\n\r\n const report = await this._store.applyPushResult(batch, result, ct);\r\n changes.merge(report);\r\n if (report.upserts + report.deletes > 0) this._raiseRowsApplied(report, G9ESyncPhase.Pushing);\r\n pushed += batch.rowCount + batch.commands.length;\r\n // What the server TOOK (its acknowledgement), not \"sent minus refused\": a row refused on the device (too large) is in\r\n // `rejected` but was never sent (LES-0071).\r\n accepted += report.accepted + report.commandsCompleted;\r\n rejected += result.rejections.length;\r\n conflicts += result.conflicts.length;\r\n tracker.report(pushed);\r\n this._log(\r\n 'debug',\r\n 20014,\r\n `Pushed batch ${batch.batchId}: ${batch.rowCount} rows, ${result.rejections.length} rejected, ${result.conflicts.length} conflicts, replayed ${result.alreadyApplied}`,\r\n );\r\n\r\n if (report.accepted + report.rejected + report.conflicts + report.commandsCompleted === 0 && !result.alreadyApplied) {\r\n this._log('warning', 20015, `Push batch ${batch.batchId} changed no row state; stopping the push loop for this run`);\r\n break;\r\n }\r\n if (batch.rowCount < batchRows && batch.commands.length < batchRows && !batch.truncated && !result.alreadyApplied) break;\r\n // After a split: grow back towards the normal size.\r\n if (batchRows < targetRows) batchRows = Math.min(targetRows, batchRows * 2);\r\n }\r\n return { pushed, accepted, rejected, conflicts };\r\n }\r\n\r\n private async _download(runId: string, plan: G9DtPullPlan, tracker: G9SyncProgressTracker, ct: AbortSignal): Promise<{ rows: number; bytes: number }> {\r\n // maxRetries counts failures in a row WITHOUT progress (the .NET twin, DownloadAsync): progress is the DURABLE resume point\r\n // moving, not a chunk arriving - segments after the last checkpoint are written again on resume.\r\n let failures = 0;\r\n let lastFailedAt: { stagedRows: number; stagedBytes: number } | null = null;\r\n for (;;) {\r\n const resume = await this._store.getResumePoint(runId, ct);\r\n let rows = resume.stagedRows;\r\n let bytes = resume.stagedBytes;\r\n if (resume.complete) return { rows, bytes };\r\n if (lastFailedAt !== null && (resume.stagedRows > lastFailedAt.stagedRows || resume.stagedBytes > lastFailedAt.stagedBytes)) failures = 0;\r\n tracker.report(rows, bytes);\r\n try {\r\n // Inside the try (the .NET twin, DownloadAsync): a reconnect that fails while the network is still down is one more\r\n // transient failure, not the end of the run.\r\n await this._ensureConnected(ct);\r\n for await (const chunk of this._transport.pull(plan.token, resume.continuation, ct)) {\r\n await this._store.stageChunk(runId, chunk, ct);\r\n if (chunk.isFinal) return { rows, bytes };\r\n rows += chunk.rowCount;\r\n bytes += chunk.payload ? chunk.payload.length : 0;\r\n tracker.report(rows, bytes, null, chunk.subscriptionKey ?? null);\r\n }\r\n throw new G9SyncException(G9SyncErrorCodes.NetworkFailure, 'The pull stream ended before its final chunk.');\r\n } catch (exception) {\r\n if (\r\n isSyncException(exception) &&\r\n (exception.code === G9SyncErrorCodes.TokenExpired ||\r\n exception.code === G9SyncErrorCodes.TokenInvalid ||\r\n exception.code === G9SyncErrorCodes.ResyncEpoch ||\r\n exception.code === G9SyncErrorCodes.ResyncAuthChanged)\r\n ) {\r\n await this._store.discardStagedPull(runId);\r\n throw exception;\r\n }\r\n if (!ct.aborted && isTransientError(exception) && failures < this._options.maxRetries) {\r\n this._log('warning', 20013, `Transient pull failure, retry ${failures + 1}: ${messageOf(exception)}`);\r\n await delay(this._backoff(failures), ct);\r\n failures++;\r\n lastFailedAt = resume;\r\n continue;\r\n }\r\n throw exception;\r\n }\r\n }\r\n }\r\n\r\n private async _withRetry<T>(operation: (signal: AbortSignal) => Promise<T>, ct: AbortSignal): Promise<T> {\r\n for (let attempt = 0; ; attempt++) {\r\n try {\r\n await this._ensureConnected(ct);\r\n return await operation(ct);\r\n } catch (exception) {\r\n if (!ct.aborted && isTransientError(exception) && attempt < this._options.maxRetries) {\r\n this._log('warning', 20013, `Transient call failure, retry ${attempt + 1}: ${messageOf(exception)}`);\r\n await delay(this._backoff(attempt), ct);\r\n continue;\r\n }\r\n throw exception;\r\n }\r\n }\r\n }\r\n\r\n private _backoff(attempt: number): number {\r\n return Math.min(30000, this._options.retryBaseDelayMs * Math.pow(2, attempt)) * (0.85 + Math.random() * 0.3);\r\n }\r\n\r\n private async _ensureConnected(ct: AbortSignal): Promise<void> {\r\n if (!this._transport.isConnected) await this._transport.connect(ct);\r\n }\r\n\r\n private async _persistRun(\r\n run: G9SyncRun,\r\n result: G9SyncRunResult,\r\n durations: { [key: string]: number },\r\n startedUtcMs: number,\r\n downloadedBytes: number,\r\n reconciledRows: number,\r\n ): Promise<void> {\r\n const diagnostics = result.changes.diagnostics;\r\n const phaseMs: { [phase: string]: number } = {};\r\n for (const key of Object.keys(durations)) phaseMs[key] = Math.floor(durations[key] as number);\r\n const report: G9SyncRunReport = {\r\n runId: run.runId,\r\n startedUtcMs,\r\n durationMs: result.durationMs,\r\n outcome: outcomeName(result.outcome),\r\n priority: priorityName(run.request.priority),\r\n errorCode: result.error ? result.error.code : null,\r\n errorMessage: result.error ? result.error.message : null,\r\n pushed: result.pushed,\r\n rejected: result.rejected,\r\n conflicts: result.conflicts,\r\n downloaded: result.downloaded,\r\n applied: result.applied,\r\n downloadedBytes,\r\n subscriptions: result.subscriptions.slice(),\r\n phaseMs,\r\n triggersSkipped: diagnostics.triggersSkipped,\r\n foreignTriggers: diagnostics.foreignTriggers.slice(),\r\n applyTransactions: diagnostics.transactions,\r\n indexesDeferred: diagnostics.deferredIndexCount,\r\n indexRebuildMs: diagnostics.indexRebuildMs,\r\n liveIndexReasons: { ...diagnostics.liveIndexReasons },\r\n unchangedRows: result.changes.unchangedRows,\r\n };\r\n await this._store.saveRunReport(report, this._options.keepRunReports);\r\n\r\n if (!result.isSuccess) return;\r\n const samples: { [key: string]: number } = {};\r\n const connecting = durations[phaseName(G9ESyncPhase.Connecting)];\r\n if (connecting !== undefined) samples[STAT_CONNECTING] = connecting;\r\n const planning = durations[phaseName(G9ESyncPhase.Planning)];\r\n if (planning !== undefined) samples[STAT_PLANNING] = planning;\r\n const pushingMs = durations[phaseName(G9ESyncPhase.Pushing)];\r\n if (result.pushed >= 100 && pushingMs !== undefined) samples[STAT_PUSH_PER_K_ROW] = pushingMs / (result.pushed / 1000);\r\n const downloadingMs = durations[phaseName(G9ESyncPhase.Downloading)];\r\n if (result.downloaded >= 500 && downloadingMs !== undefined) samples[STAT_DOWNLOAD_PER_K_ROW] = downloadingMs / (result.downloaded / 1000);\r\n const applyingMs = durations[phaseName(G9ESyncPhase.Applying)];\r\n if (result.downloaded >= 500 && applyingMs !== undefined) samples[STAT_APPLY_PER_K_ROW] = applyingMs / (result.downloaded / 1000);\r\n const reconcilingMs = durations[phaseName(G9ESyncPhase.Reconciling)];\r\n if (reconcilingMs !== undefined && reconciledRows >= 0 && run.request.pull) {\r\n samples[STAT_RECONCILE_PER_SUBSCRIPTION] = reconcilingMs / Math.max(1, result.subscriptions.length);\r\n }\r\n for (const step of run.request.postSteps) {\r\n const stepMs = durations['PostStep:' + step.name];\r\n if (stepMs !== undefined) samples['PostStep:' + step.name] = stepMs;\r\n }\r\n if (Object.keys(samples).length > 0) await this._store.recordPhaseStatistics(samples);\r\n if (result.applied > 0) await this._store.purgeDeletedFeed(this._options.keepDeletedFeedEntries);\r\n }\r\n\r\n // ================================================================ reconciliation (D-07)\r\n\r\n private async _reconcileSubscription(\r\n subscription: G9SyncSubscriptionRecord,\r\n definition: G9DtSubscriptionDefinition,\r\n negotiated: G9DtNegotiatedTable[],\r\n ct: AbortSignal,\r\n ): Promise<G9ApplyReport> {\r\n const tables: G9DtNegotiatedTable[] = [];\r\n for (const name of definition.tables) {\r\n const table = negotiated.find((t) => t.name.toLowerCase() === name.toLowerCase());\r\n // UploadOnly: the device's own rows, nothing on the server to compare them with.\r\n if (table && table.direction !== G9ESyncDirection.UploadOnly) tables.push(table);\r\n }\r\n\r\n const request: G9DtReconcileRequest = { clientId: this._clientId, subscription: toSubscriptionRef(subscription), tables: [], frameVersion: this._options.maxFrameVersion };\r\n for (const table of tables) request.tables.push(await this._store.computeDigest(subscription.key, table, ct));\r\n\r\n const serverRows: { [tableId: number]: Map<string, { version: number; hash: G9Long }> } = {};\r\n let summary: G9DtReconcileSummary | null = null;\r\n for await (const chunk of this._transport.reconcile(request, ct)) {\r\n if (chunk.isFinal) {\r\n summary = chunk.reconcileSummary ?? null;\r\n break;\r\n }\r\n if (!chunk.payload) continue;\r\n const reader = await openRowBatch(chunk.payload, { maxBodyBytes: this._options.maxDecodedFrameBytes });\r\n while (reader.nextSection()) {\r\n let rows = serverRows[reader.tableId];\r\n if (!rows) serverRows[reader.tableId] = rows = new Map();\r\n while (reader.readRow()) rows.set(reader.key, { version: reader.version, hash: reader.rowHash });\r\n }\r\n }\r\n if (!summary) throw new G9SyncException(G9SyncErrorCodes.NetworkFailure, 'The reconcile stream ended before its summary.');\r\n\r\n const report = new G9ApplyReport();\r\n let handedToSnapshot = false;\r\n for (const mismatch of summary.mismatched) {\r\n const table = tables.find((t) => t.tableId === mismatch.tableId);\r\n if (!table) continue;\r\n const server = serverRows[table.tableId] ?? new Map<string, { version: number; hash: G9Long }>();\r\n const buckets = new Set<number>(mismatch.buckets);\r\n const serverKeys = new Set<string>();\r\n server.forEach((_value, key) => serverKeys.add(key));\r\n const local = await this._store.readLocalEntries(subscription.key, table, buckets, serverKeys, ct);\r\n const localByKey = new Map<string, G9LocalRowEntry>();\r\n for (const entry of local) localByKey.set(entry.key, entry);\r\n\r\n const fetch: string[] = [];\r\n const addMembership: string[] = [];\r\n const moveOut: string[] = [];\r\n server.forEach(({ hash }, key) => {\r\n const entry = localByKey.get(key);\r\n if (!entry) fetch.push(key);\r\n else if (entry.dirty) {\r\n // A pending local change is never overwritten here; a row visible again still gets its membership back.\r\n if (!entry.member) addMembership.push(key);\r\n } else if (!entry.hash.equals(hash)) fetch.push(key);\r\n else if (!entry.member) addMembership.push(key);\r\n });\r\n for (const entry of local) {\r\n // Rows with pending changes are released too; the store's revocation policy decides (ADR-0026).\r\n if (entry.member && buckets.has(entry.bucket) && !server.has(entry.key)) moveOut.push(entry.key);\r\n }\r\n\r\n // A difference this large is a download, not a repair (ADR-0066).\r\n if (this._options.reconcileSnapshotThreshold > 0 && fetch.length >= this._options.reconcileSnapshotThreshold) {\r\n const released = await this._store.applyReconcile(subscription.key, table, [], addMembership, moveOut, definition.moveOutPolicy, ct);\r\n report.merge(released);\r\n handedToSnapshot = true;\r\n this._log(\r\n 'information',\r\n 20024,\r\n `Reconciling ${subscription.key} / ${table.name} would fetch ${fetch.length} rows (threshold ${this._options.reconcileSnapshotThreshold}): released what left, and leaving the rows to a staged snapshot pull`,\r\n );\r\n continue;\r\n }\r\n\r\n // Fetched and applied in groups (ADR-0066).\r\n const groupKeys = Math.max(Math.max(1, this._options.fetchKeysPerRequest), this._options.reconcileApplyRows);\r\n let pendingMembership = addMembership;\r\n let pendingMoveOut = moveOut;\r\n let fetched = 0;\r\n for (const group of chunked(fetch, groupKeys)) {\r\n const frames: Uint8Array[] = [];\r\n const returned = new Set<string>();\r\n for (const keys of chunked(group, Math.max(1, this._options.fetchKeysPerRequest))) {\r\n const fetchRequest = {\r\n clientId: this._clientId,\r\n subscription: toSubscriptionRef(subscription),\r\n tableId: table.tableId,\r\n keys,\r\n columns: table.columns.map((c) => c.name),\r\n frameVersion: this._options.maxFrameVersion,\r\n };\r\n for await (const chunk of this._transport.fetchRows(fetchRequest, ct)) {\r\n if (chunk.isFinal || !chunk.payload) continue;\r\n frames.push(chunk.payload);\r\n const reader = await openRowBatch(chunk.payload, { maxBodyBytes: this._options.maxDecodedFrameBytes });\r\n while (reader.nextSection()) {\r\n while (reader.readRow()) returned.add(reader.key);\r\n }\r\n }\r\n }\r\n // A key listed but not returned left the subscription between listing and fetch.\r\n const groupMoveOut = group.filter((k) => !returned.has(k) && (localByKey.get(k)?.member ?? false));\r\n for (const key of pendingMoveOut) groupMoveOut.push(key);\r\n const applied = await this._store.applyReconcile(subscription.key, table, frames, pendingMembership, groupMoveOut, definition.moveOutPolicy, ct);\r\n report.merge(applied);\r\n pendingMembership = [];\r\n pendingMoveOut = [];\r\n fetched += group.length;\r\n }\r\n if (fetched === 0 && (pendingMembership.length > 0 || pendingMoveOut.length > 0)) {\r\n report.merge(await this._store.applyReconcile(subscription.key, table, [], pendingMembership, pendingMoveOut, definition.moveOutPolicy, ct));\r\n }\r\n this._log(\r\n 'information',\r\n 20020,\r\n `Reconciled ${subscription.key} / ${table.name}: ${mismatch.buckets.length} buckets differed, fetched ${fetch.length}, adopted ${addMembership.length}, moved out ${moveOut.length}`,\r\n );\r\n }\r\n\r\n await this._store.updateSubscription(\r\n subscription.key,\r\n handedToSnapshot\r\n ? // No cursor: the plan step of this run sees an initial pull and stages a snapshot.\r\n { clearCursor: true, state: G9ESubscriptionState.Active, clearError: true, reconciled: true }\r\n : {\r\n cursor: summary.cursor,\r\n definitionHash: summary.definitionHash,\r\n authHash: summary.authHash,\r\n state: G9ESubscriptionState.Active,\r\n clearError: true,\r\n reconciled: true,\r\n },\r\n ct,\r\n );\r\n return report;\r\n }\r\n}\r\n\r\n// ---------------------------------------------------------------- helpers\r\n\r\nfunction remove<T>(list: T[], item: T): void {\r\n const index = list.indexOf(item);\r\n if (index >= 0) list.splice(index, 1);\r\n}\r\n\r\nfunction messageOf(error: unknown): string {\r\n return error instanceof Error ? error.message : String(error);\r\n}\r\n\r\nfunction historyOf(history: { [key: string]: number }, key: string, fallback: number): number {\r\n const value = history[key];\r\n return value !== undefined && value > 0 ? value : fallback;\r\n}\r\n\r\nfunction needsReconcile(\r\n subscription: G9SyncSubscriptionRecord,\r\n request: G9ResolvedSyncRequest,\r\n states: { [key: string]: G9DtSubscriptionState },\r\n definitions: { [name: string]: G9DtSubscriptionDefinition },\r\n nowMs: number,\r\n): boolean {\r\n if (subscription.state === G9ESubscriptionState.NeedsReconcile) return true;\r\n const state = states[subscription.key];\r\n if (state && (state.action === G9ESubscriptionAction.Reconcile || state.action === G9ESubscriptionAction.ResyncRequired)) return true;\r\n if (subscription.cursor === null) return false;\r\n if (request.forceReconcile) return true;\r\n const definition = definitions[subscription.name];\r\n return (\r\n definition !== undefined &&\r\n definition.reconcileIntervalMinutes > 0 &&\r\n (subscription.lastReconcileUtcMs ?? subscription.lastSuccessUtcMs ?? subscription.createdUtcMs) < nowMs - definition.reconcileIntervalMinutes * 60000\r\n );\r\n}\r\n\r\n/**\r\n * Everything a staged pull's rows depend on (ADR-0046): the server's epoch, the exact set of subscriptions with their\r\n * definition and authorisation hashes, and the negotiated columns. The cursor is deliberately NOT part of it (ADR-0060).\r\n */\r\nexport function stageGeneration(\r\n hello: G9DtHelloResult,\r\n plannable: readonly G9SyncSubscriptionRecord[],\r\n states: { [key: string]: G9DtSubscriptionState },\r\n negotiated: readonly G9DtNegotiatedTable[],\r\n): string {\r\n let text = guidToN(hello.epoch) + '\\n';\r\n for (const subscription of plannable.slice().sort((a, b) => compareOrdinal(a.key, b.key))) {\r\n const state = states[subscription.key];\r\n text += subscription.key + '\\u001F' + ((state ? state.definitionHash : null) ?? subscription.definitionHash ?? '') + '\\u001F' + ((state ? state.authHash : null) ?? subscription.authHash ?? '') + '\\n';\r\n }\r\n text += '\\n';\r\n const tables = negotiated.map((t, i) => ({ t, i })).sort((a, b) => a.t.tableId - b.t.tableId || a.i - b.i);\r\n for (const { t } of tables) text += String(t.tableId) + '\\u001F' + t.columns.map((c) => c.name).join(',') + '\\n';\r\n return toHex(sha256(utf8Encode(text)));\r\n}\r\n\r\nfunction actionCode(action: number): string {\r\n switch (action) {\r\n case G9ESubscriptionAction.Unknown:\r\n return G9SyncErrorCodes.UnknownSubscription;\r\n case G9ESubscriptionAction.Forbidden:\r\n return G9SyncErrorCodes.SubscriptionForbidden;\r\n default:\r\n return G9SyncErrorCodes.InvalidParameters;\r\n }\r\n}\r\n\r\nfunction chunked<T>(items: readonly T[], size: number): T[][] {\r\n const out: T[][] = [];\r\n for (let i = 0; i < items.length; i += size) out.push(items.slice(i, i + size));\r\n return out;\r\n}\r\n\r\nasync function* toChunks(batch: G9PushBatch): AsyncGenerator<G9DtSyncChunk> {\r\n let sequence = 0;\r\n for (const frame of batch.frames) yield { sequence: sequence++, payload: frame, rowCount: 0, isFinal: false };\r\n}\r\n"]}
@@ -80,7 +80,11 @@ export interface G9SyncRunResult {
80
80
  runId: string;
81
81
  outcome: G9ESyncOutcome;
82
82
  error: G9SyncException | null;
83
+ /** Rows and commands SENT, refused ones included (a row refused on the device before sending is not). */
83
84
  pushed: number;
85
+ /** Rows and commands the server TOOK - what an app may call "sent"; never `pushed - rejected` (LES-0071). */
86
+ accepted: number;
87
+ /** Rows refused by the server, or on the device before sending (too large). */
84
88
  rejected: number;
85
89
  conflicts: number;
86
90
  downloaded: number;
@@ -70,6 +70,7 @@ export function makeRunResult(fields) {
70
70
  return {
71
71
  error: null,
72
72
  pushed: 0,
73
+ accepted: 0,
73
74
  rejected: 0,
74
75
  conflicts: 0,
75
76
  downloaded: 0,
@@ -1 +1 @@
1
- {"version":3,"file":"runs.js","sourceRoot":"","sources":["../../src/client/runs.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,gBAAgB,EAAE,eAAe,EAAE,eAAe,EAAE,MAAM,2BAA2B,CAAC;AAC/F,OAAO,EAAE,OAAO,EAAE,MAAM,yBAAyB,CAAC;AAClD,OAAO,EAAE,cAAc,EAAE,MAAM,yBAAyB,CAAC;AAEzD,OAAO,EAAE,qBAAqB,EAAE,MAAM,gCAAgC,CAAC;AACvE,OAAO,EAAE,cAAc,EAAE,MAAM,0BAA0B,CAAC;AAC1D,OAAO,EAAE,qBAAqB,EAA0B,MAAM,sBAAsB,CAAC;AAErF,OAAO,EACL,aAAa,EACb,oBAAoB,EACpB,mBAAmB,GAKpB,MAAM,iBAAiB,CAAC;AAEzB,qGAAqG;AACrG,MAAM,CAAC,MAAM,eAAe,GAAG;IAC7B,UAAU,EAAE,CAAC;IACb,UAAU,EAAE,CAAC;IACb,eAAe,EAAE,CAAC;CACV,CAAC;AAGX,MAAM,cAAc,GAAG,CAAC,YAAY,EAAE,YAAY,EAAE,iBAAiB,CAAC,CAAC;AACvE,MAAM,UAAU,YAAY,CAAC,QAAgB;;IAC3C,OAAO,MAAA,cAAc,CAAC,QAAQ,CAAC,mCAAI,MAAM,CAAC,QAAQ,CAAC,CAAC;AACtD,CAAC;AAED,wBAAwB;AACxB,MAAM,CAAC,MAAM,cAAc,GAAG;IAC5B,SAAS,EAAE,CAAC;IACZ,uFAAuF;IACvF,uBAAuB,EAAE,CAAC;IAC1B,MAAM,EAAE,CAAC;IACT,QAAQ,EAAE,CAAC;CACH,CAAC;AAGX,MAAM,aA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AAM,IAAI,GAAG,cAAc,CAAC,KAAK,CAAC,CAAC,IAAI,CAAC;IACxC,OAAO,IAAI,KAAK,gBAAgB,CAAC,cAAc,IAAI,IAAI,KAAK,gBAAgB,CAAC,WAAW,IAAI,IAAI,KAAK,gBAAgB,CAAC,UAAU,CAAC;AACnI,CAAC","sourcesContent":["// Twins of G9SyncData.Client/Runs/G9SyncRunTypes.cs and the option/health/error types of G9CSyncEngineOptions.cs.\r\nimport type { G9ESyncColumnType } from '../abstractions/enums.js';\r\nimport { G9SyncErrorCodes, G9SyncException, isSyncException } from '../abstractions/errors.js';\r\nimport { newGuid } from '../abstractions/guid.js';\r\nimport { G9SyncProtocol } from '../protocol/protocol.js';\r\nimport type { G9DtSubscriptionState } from '../protocol/dtos.js';\r\nimport { G9RowBatchFormatError } from '../protocol/rowBatch/format.js';\r\nimport { columnTypeName } from '../abstractions/enums.js';\r\nimport { createAbortController, type G9AbortController } from '../internal/abort.js';\r\nimport type { G9DtSyncProgress, G9ESyncPhase } from './progress.js';\r\nimport {\r\n G9ApplyReport,\r\n G9ELocalStoreFailure,\r\n isLocalStoreFailure,\r\n type G9ApplySlice,\r\n type G9PendingSummary,\r\n type G9SyncRunReport,\r\n type G9SyncSubscriptionRecord,\r\n} from './storeTypes.js';\r\n\r\n/** Scheduling priority (`G9ESyncPriority`). A higher priority pre-empts a running background run. */\r\nexport const G9ESyncPriority = {\r\n Background: 0,\r\n Foreground: 1,\r\n UserInteractive: 2,\r\n} as const;\r\nexport type G9ESyncPriority = (typeof G9ESyncPriority)[keyof typeof G9ESyncPriority];\r\n\r\nconst PRIORITY_NAMES = ['Background', 'Foreground', 'UserInteractive'];\r\nexport function priorityName(priority: number): string {\r\n return PRIORITY_NAMES[priority] ?? String(priority);\r\n}\r\n\r\n/** `G9ESyncOutcome`. */\r\nexport const G9ESyncOutcome = {\r\n Succeeded: 0,\r\n /** Data moved, but some rows were rejected or some subscriptions reported problems. */\r\n CompletedWithRejections: 1,\r\n Failed: 2,\r\n Canceled: 3,\r\n} as const;\r\nexport type G9ESyncOutcome = (typeof G9ESyncOutcome)[keyof typeof G9ESyncOutcome];\r\n\r\nconst OUTCOME_NAMES = ['Succeeded', 'CompletedWithRejections', 'Failed', 'Canceled'];\r\nexport function outcomeName(outcome: number): string {\r\n return OUTCOME_NAMES[outcome] ?? String(outcome);\r\n}\r\n\r\n/** Context handed to an app-owned post step (`G9CSyncPostStepContext`). */\r\nexport interface G9SyncPostStepContext {\r\n run: G9SyncRun;\r\n /** Everything this run changed so far. */\r\n changes: G9ApplyReport;\r\n /** Report 0..1 of the step; mapped into the step's slice of the bar. */\r\n progress: (fraction: number) => void;\r\n}\r\n\r\n/** An app-owned step that runs after the data applied and owns a slice of the progress bar (`G9CSyncPostStep`). */\r\nexport class G9SyncPostStep {\r\n readonly name: string;\r\n readonly weightHint: number;\r\n readonly action: (context: G9SyncPostStepContext, signal: AbortSignal) => Promise<void>;\r\n\r\n constructor(name: string, weightHint: number, action: (context: G9SyncPostStepContext, signal: AbortSignal) => Promise<void>) {\r\n if (typeof name !== 'string' || name.trim() === '') throw new TypeError('A post step needs a name.');\r\n if (typeof action !== 'function') throw new TypeError('A post step needs an action.');\r\n this.name = name;\r\n this.weightHint = Math.min(Math.max(weightHint, 0), 0.9);\r\n this.action = action;\r\n }\r\n}\r\n\r\n/** A sync request (`G9CSyncRequest`). */\r\nexport interface G9SyncRequest {\r\n /** Subscription keys or names to pull; omitted = every local subscription (background runs skip heavy ones). */\r\n subscriptions?: readonly string[] | null;\r\n push?: boolean;\r\n pull?: boolean;\r\n /** Reconcile the selected subscriptions even when nothing asks for it. */\r\n forceReconcile?: boolean;\r\n priority?: G9ESyncPriority;\r\n postSteps?: readonly G9SyncPostStep[];\r\n progress?: ((progress: G9DtSyncProgress) => void) | null;\r\n signal?: AbortSignal | null;\r\n}\r\n\r\n/** The request with its defaults filled in. */\r\nexport interface G9ResolvedSyncRequest {\r\n subscriptions: readonly string[] | null;\r\n push: boolean;\r\n pull: boolean;\r\n forceReconcile: boolean;\r\n priority: G9ESyncPriority;\r\n postSteps: readonly G9SyncPostStep[];\r\n progress: ((progress: G9DtSyncProgress) => void) | null;\r\n signal: AbortSignal | null;\r\n}\r\n\r\nexport function resolveRequest(request: G9SyncRequest | null | undefined): G9ResolvedSyncRequest {\r\n return {\r\n subscriptions: request?.subscriptions ?? null,\r\n push: request?.push ?? true,\r\n pull: request?.pull ?? true,\r\n forceReconcile: request?.forceReconcile ?? false,\r\n priority: request?.priority ?? 1,\r\n postSteps: request?.postSteps ?? [],\r\n progress: request?.progress ?? null,\r\n signal: request?.signal ?? null,\r\n };\r\n}\r\n\r\n/** `G9CSyncRequest.CanCoalesce`. */\r\nexport function canCoalesce(request: G9ResolvedSyncRequest): boolean {\r\n return request.postSteps.length === 0 && request.progress === null && request.signal === null;\r\n}\r\n\r\n/** `G9CSyncRequest.Signature`. */\r\nexport function requestSignature(request: G9ResolvedSyncRequest): string {\r\n const subscriptions = request.subscriptions === null ? '*' : request.subscriptions.slice().sort((a, b) => (a < b ? -1 : a > b ? 1 : 0)).join(',');\r\n return `${request.push ? 'True' : 'False'}|${request.pull ? 'True' : 'False'}|${request.forceReconcile ? 'True' : 'False'}|${subscriptions}`;\r\n}\r\n\r\n/** One defect of the client model, as the server sees it (`G9CSyncModelProblem`). */\r\nexport interface G9SyncModelProblem {\r\n code: string;\r\n table: string;\r\n column: string;\r\n clientType: G9ESyncColumnType;\r\n serverType: G9ESyncColumnType;\r\n}\r\n\r\nexport function describeModelProblem(problem: G9SyncModelProblem): string {\r\n return `${problem.table}.${problem.column} is ${columnTypeName(problem.clientType)} on the client and ${columnTypeName(problem.serverType)} on the server`;\r\n}\r\n\r\n/** The result of a run (`G9CSyncRunResult`). */\r\nexport interface G9SyncRunResult {\r\n runId: string;\r\n outcome: G9ESyncOutcome;\r\n error: G9SyncException | null;\r\n pushed: number;\r\n rejected: number;\r\n conflicts: number;\r\n downloaded: number;\r\n applied: number;\r\n durationMs: number;\r\n /** Milliseconds spent in each phase of this run, keyed by phase name. */\r\n phaseMs: { [phase: string]: number };\r\n subscriptions: string[];\r\n /** Subscriptions that could not sync, with the server's reason. */\r\n problems: G9DtSubscriptionState[];\r\n /** Defects of the client model the server reported in this run's hello (ADR-0061). */\r\n modelProblems: G9SyncModelProblem[];\r\n changes: G9ApplyReport;\r\n isSuccess: boolean;\r\n}\r\n\r\nexport function makeRunResult(fields: Partial<G9SyncRunResult> & { runId: string; outcome: G9ESyncOutcome }): G9SyncRunResult {\r\n return {\r\n error: null,\r\n pushed: 0,\r\n rejected: 0,\r\n conflicts: 0,\r\n downloaded: 0,\r\n applied: 0,\r\n durationMs: 0,\r\n phaseMs: {},\r\n subscriptions: [],\r\n problems: [],\r\n modelProblems: [],\r\n changes: new G9ApplyReport(),\r\n ...fields,\r\n isSuccess: fields.outcome === G9ESyncOutcome.Succeeded || fields.outcome === G9ESyncOutcome.CompletedWithRejections,\r\n };\r\n}\r\n\r\n/** A queued or running sync (`G9CSyncRun`). Await {@link completion}; read progress with {@link onProgress} or {@link progress}. */\r\nexport class G9SyncRun {\r\n readonly runId: string = newGuid();\r\n readonly request: G9ResolvedSyncRequest;\r\n readonly completion: Promise<G9SyncRunResult>;\r\n latestProgress: G9DtSyncProgress | null = null;\r\n isStarted = false;\r\n\r\n /** @internal */\r\n readonly cancellation: G9AbortController;\r\n /** @internal */\r\n preempted = false;\r\n\r\n private _resolve!: (result: G9SyncRunResult) => void;\r\n private readonly _listeners: ((progress: G9DtSyncProgress) => void)[] = [];\r\n private readonly _buffer: G9DtSyncProgress[] = [];\r\n private readonly _waiters: ((value: IteratorResult<G9DtSyncProgress>) => void)[] = [];\r\n private _done = false;\r\n private _unlink: () => void = () => undefined;\r\n\r\n constructor(request: G9ResolvedSyncRequest) {\r\n this.request = request;\r\n this.completion = new Promise<G9SyncRunResult>((resolve) => {\r\n this._resolve = resolve;\r\n });\r\n this.cancellation = createAbortController();\r\n const external = request.signal;\r\n if (external) {\r\n if (external.aborted) this.cancellation.abort();\r\n else {\r\n const listener = (): void => this.cancellation.abort();\r\n external.addEventListener('abort', listener);\r\n this._unlink = () => external.removeEventListener('abort', listener);\r\n }\r\n }\r\n }\r\n\r\n /** Requests cancellation. Network phases stop at once; an apply in progress finishes atomically first. */\r\n cancel(): void {\r\n this.cancellation.abort();\r\n }\r\n\r\n /** Subscribes to progress samples; returns the unsubscribe function. */\r\n onProgress(listener: (progress: G9DtSyncProgress) => void): () => void {\r\n this._listeners.push(listener);\r\n return () => {\r\n const index = this._listeners.indexOf(listener);\r\n if (index >= 0) this._listeners.splice(index, 1);\r\n };\r\n }\r\n\r\n /** The progress stream (bounded: the oldest samples are dropped when a reader falls 64 behind), ending with the run. */\r\n progress(): AsyncIterable<G9DtSyncProgress> {\r\n // eslint-disable-next-line @typescript-eslint/no-this-alias\r\n const run = this;\r\n return {\r\n [Symbol.asyncIterator](): AsyncIterator<G9DtSyncProgress> {\r\n return {\r\n next(): Promise<IteratorResult<G9DtSyncProgress>> {\r\n const value = run._buffer.shift();\r\n if (value) return Promise.resolve({ value, done: false });\r\n if (run._done) return Promise.resolve({ value: undefined as unknown as G9DtSyncProgress, done: true });\r\n return new Promise((resolve) => run._waiters.push(resolve));\r\n },\r\n };\r\n },\r\n };\r\n }\r\n\r\n /** @internal */\r\n publish(progress: G9DtSyncProgress): void {\r\n this.latestProgress = progress;\r\n const waiter = this._waiters.shift();\r\n if (waiter) waiter({ value: progress, done: false });\r\n else {\r\n this._buffer.push(progress);\r\n if (this._buffer.length > 64) this._buffer.shift();\r\n }\r\n for (const listener of this._listeners.slice()) {\r\n try {\r\n listener(progress);\r\n } catch {\r\n // A progress consumer must never break the sync.\r\n }\r\n }\r\n try {\r\n this.request.progress?.(progress);\r\n } catch {\r\n // A progress consumer must never break the sync.\r\n }\r\n }\r\n\r\n /** @internal */\r\n complete(result: G9SyncRunResult): void {\r\n if (this._done) return;\r\n this._done = true;\r\n for (const waiter of this._waiters.splice(0, this._waiters.length)) waiter({ value: undefined as unknown as G9DtSyncProgress, done: true });\r\n this._unlink();\r\n this._resolve(result);\r\n }\r\n}\r\n\r\n/** `G9CSubscriptionOptions`. */\r\nexport interface G9SubscriptionOptions {\r\n /** Overrides the server definition's ephemeral flag. */\r\n ephemeral?: boolean;\r\n ttlMs?: number;\r\n /** The rows already exist locally: reconcile instead of downloading a snapshot. Call adoptExistingRows first. */\r\n adoptExistingRows?: boolean;\r\n}\r\n\r\n/** Engine options (`G9CSyncEngineOptions`). Durations are milliseconds. */\r\nexport interface G9SyncEngineOptions {\r\n /** Sent at Hello; the server's connect gates may refuse old versions. */\r\n appVersion?: string | null;\r\n pushBatchRows?: number;\r\n /** Transient failures retried inside one run. */\r\n maxRetries?: number;\r\n retryBaseDelayMs?: number;\r\n /** Queue a background pull when the server pokes about changed tables. */\r\n pullOnChangesAvailable?: boolean;\r\n changesDebounceMs?: number;\r\n progressMaxHz?: number;\r\n fetchKeysPerRequest?: number;\r\n /** Rows a reconciliation fetches before it applies them (ADR-0066). */\r\n reconcileApplyRows?: number;\r\n /** A reconciliation that would fetch at least this many rows of one table hands them to a staged snapshot (ADR-0066). 0 = never. */\r\n reconcileSnapshotThreshold?: number;\r\n /** The largest decoded body accepted from one server frame (ADR-0051). */\r\n maxDecodedFrameBytes?: number;\r\n /** The newest G9RowBatch body layout to ask the server for (ADR-0040). */\r\n maxFrameVersion?: number;\r\n /** Fail a run when the server reports a client column whose type differs (ADR-0061). */\r\n failOnTypeMismatch?: boolean;\r\n /**\r\n * Offer the server to send large first downloads as SQLite snapshot files (ADR-0072), when the store can take them (a store\r\n * with a `snapshotFiles` sink). Default true. A file that fails is replaced by the same pull as rows, in the same run.\r\n */\r\n acceptSnapshotFiles?: boolean;\r\n /** A staged pull older than this is discarded instead of resumed. */\r\n stagedPullMaxAgeMs?: number;\r\n /** Most payload bytes kept in stages other than the one a run resumes (ADR-0060). */\r\n stagedPullsMaxBytes?: number;\r\n keepDeletedFeedEntries?: number;\r\n keepRunReports?: number;\r\n /** Where the engine logs (the ILogger twin); silent when omitted. */\r\n logger?: G9SyncLogger | null;\r\n /** Platform integration (foreground service, keep-awake, connectivity). */\r\n hooks?: G9SyncHostHooks | null;\r\n}\r\n\r\nexport type G9ResolvedEngineOptions = Required<Omit<G9SyncEngineOptions, 'appVersion' | 'logger' | 'hooks'>> & {\r\n appVersion: string | null;\r\n logger: G9SyncLogger | null;\r\n hooks: G9SyncHostHooks | null;\r\n};\r\n\r\nexport function resolveEngineOptions(options: G9SyncEngineOptions | null | undefined): G9ResolvedEngineOptions {\r\n return {\r\n appVersion: options?.appVersion ?? null,\r\n pushBatchRows: options?.pushBatchRows ?? 2000,\r\n maxRetries: options?.maxRetries ?? 5,\r\n retryBaseDelayMs: options?.retryBaseDelayMs ?? 1000,\r\n pullOnChangesAvailable: options?.pullOnChangesAvailable ?? true,\r\n changesDebounceMs: options?.changesDebounceMs ?? 2000,\r\n progressMaxHz: options?.progressMaxHz ?? 10,\r\n fetchKeysPerRequest: options?.fetchKeysPerRequest ?? 2000,\r\n reconcileApplyRows: options?.reconcileApplyRows ?? 20000,\r\n reconcileSnapshotThreshold: options?.reconcileSnapshotThreshold ?? 100000,\r\n maxDecodedFrameBytes: options?.maxDecodedFrameBytes ?? 64 * 1024 * 1024,\r\n maxFrameVersion: options?.maxFrameVersion ?? G9SyncProtocol.MaxFrameVersion,\r\n failOnTypeMismatch: options?.failOnTypeMismatch ?? false,\r\n acceptSnapshotFiles: options?.acceptSnapshotFiles ?? true,\r\n stagedPullMaxAgeMs: options?.stagedPullMaxAgeMs ?? 90 * 60 * 1000,\r\n stagedPullsMaxBytes: options?.stagedPullsMaxBytes ?? 64 * 1024 * 1024,\r\n keepDeletedFeedEntries: options?.keepDeletedFeedEntries ?? 50000,\r\n keepRunReports: options?.keepRunReports ?? 50,\r\n logger: options?.logger ?? null,\r\n hooks: options?.hooks ?? null,\r\n };\r\n}\r\n\r\n/** Log levels of {@link G9SyncLogger} (Microsoft.Extensions.Logging's). */\r\nexport type G9SyncLogLevel = 'debug' | 'information' | 'warning' | 'error';\r\n\r\n/** Where the library logs. `eventId` is the .NET LoggerMessage event id of the same message. */\r\nexport interface G9SyncLogger {\r\n log(level: G9SyncLogLevel, eventId: number, message: string, error?: unknown): void;\r\n}\r\n\r\n/** Platform integration points (`IG9SyncHostHooks`). */\r\nexport interface G9SyncHostHooks {\r\n /** Called when a run starts executing; the returned scope's `dispose` runs when it ends. */\r\n beginRun(run: G9SyncRun, signal: AbortSignal): Promise<{ dispose(): void | Promise<void> } | null>;\r\n /** False skips automatic background runs. */\r\n readonly isNetworkAvailable: boolean;\r\n}\r\n\r\n/** `G9CSyncHealth`. */\r\nexport interface G9SyncHealth {\r\n clientId: string;\r\n isConnected: boolean;\r\n isRunning: boolean;\r\n queuedRuns: number;\r\n serverEpoch: string | null;\r\n lastHelloUtcMs: number | null;\r\n pending: G9PendingSummary;\r\n subscriptions: G9SyncSubscriptionRecord[];\r\n recentRuns: G9SyncRunReport[];\r\n}\r\n\r\n/** `G9CRowsAppliedEventArgs`. */\r\nexport interface G9RowsAppliedEvent {\r\n report: G9ApplyReport;\r\n source: G9ESyncPhase;\r\n /** Set for a staged pull applied in slices (ADR-0053). */\r\n slice: G9ApplySlice | null;\r\n}\r\n\r\n/** `G9CSyncErrors.Normalize`: every failure becomes a G9SyncException with a stable code. */\r\nexport function normalizeError(error: unknown): G9SyncException {\r\n if (isSyncException(error)) return error as G9SyncException;\r\n const message = error instanceof Error ? error.message : String(error);\r\n if (error instanceof Error && error.name === 'AbortError') return new G9SyncException(G9SyncErrorCodes.Canceled, 'The sync was canceled.', { cause: error });\r\n if (isLocalStoreFailure(error)) {\r\n const code =\r\n error.localStoreFailure === G9ELocalStoreFailure.Corrupt\r\n ? G9SyncErrorCodes.LocalStoreCorrupt\r\n : error.localStoreFailure === G9ELocalStoreFailure.DiskFull\r\n ? G9SyncErrorCodes.LocalStoreDiskFull\r\n : error.localStoreFailure === G9ELocalStoreFailure.Busy\r\n ? G9SyncErrorCodes.LocalStoreBusy\r\n : G9SyncErrorCodes.LocalStoreError;\r\n return new G9SyncException(code, message, { cause: error });\r\n }\r\n if (error instanceof G9RowBatchFormatError) return new G9SyncException(G9SyncErrorCodes.Unknown, message, { cause: error });\r\n if (error instanceof Error && (error.name === 'TimeoutError' || /network|socket|websocket|connection/i.test(error.name))) {\r\n return new G9SyncException(G9SyncErrorCodes.NetworkFailure, message, { cause: error });\r\n }\r\n return new G9SyncException(G9SyncErrorCodes.Unknown, message, { cause: error });\r\n}\r\n\r\n/** `G9CSyncErrors.IsTransient`. */\r\nexport function isTransientError(error: unknown): boolean {\r\n const code = normalizeError(error).code;\r\n return code === G9SyncErrorCodes.NetworkFailure || code === G9SyncErrorCodes.ServerError || code === G9SyncErrorCodes.ServerBusy;\r\n}\r\n"]}
1
+ {"version":3,"file":"runs.js","sourceRoot":"","sources":["../../src/client/runs.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,gBAAgB,EAAE,eAAe,EAAE,eAAe,EAAE,MAAM,2BAA2B,CAAC;AAC/F,OAAO,EAAE,OAAO,EAAE,MAAM,yBAAyB,CAAC;AAClD,OAAO,EAAE,cAAc,EAAE,MAAM,yBAAyB,CAAC;AAEzD,OAAO,EAAE,qBAAqB,EAAE,MAAM,gCAAgC,CAAC;AACvE,OAAO,EAAE,cAAc,EAAE,MAAM,0BAA0B,CAAC;AAC1D,OAAO,EAAE,qBAAqB,EAA0B,MAAM,sBAAsB,CAAC;AAErF,OAAO,EACL,aAAa,EACb,oBAAoB,EACpB,mBAAmB,GAKpB,MAAM,iBAAiB,CAAC;AAEzB,qGAAqG;AACrG,MAAM,CAAC,MAAM,eAAe,GAAG;IAC7B,UAAU,EAAE,CAAC;IACb,UAAU,EAAE,CAAC;IACb,eAAe,EAAE,CAAC;CACV,CAAC;AAGX,MAAM,cAAc,GAAG,CAAC,YAAY,EAAE,YAAY,EAAE,iBAAiB,CAAC,CAAC;AACvE,MAAM,UAAU,YAAY,CAAC,QAAgB;;IA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C;QACzH,OAAO,IAAI,eAAe,CAAC,gBAAgB,CAAC,cAAc,EAAE,OAAO,EAAE,EAAE,KAAK,EAAE,KAAK,EAAE,CAAC,CAAC;IACzF,CAAC;IACD,OAAO,IAAI,eAAe,CAAC,gBAAgB,CAAC,OAAO,EAAE,OAAO,EAAE,EAAE,KAAK,EAAE,KAAK,EAAE,CAAC,CAAC;AAClF,CAAC;AAED,mCAAmC;AACnC,MAAM,UAAU,gBAAgB,CAAC,KAAc;IAC7C,MAAM,IAAI,GAAG,cAAc,CAAC,KAAK,CAAC,CAAC,IAAI,CAAC;IACxC,OAAO,IAAI,KAAK,gBAAgB,CAAC,cAAc,IAAI,IAAI,KAAK,gBAAgB,CAAC,WAAW,IAAI,IAAI,KAAK,gBAAgB,CAAC,UAAU,CAAC;AACnI,CAAC","sourcesContent":["// Twins of G9SyncData.Client/Runs/G9SyncRunTypes.cs and the option/health/error types of G9CSyncEngineOptions.cs.\r\nimport type { G9ESyncColumnType } from '../abstractions/enums.js';\r\nimport { G9SyncErrorCodes, G9SyncException, isSyncException } from '../abstractions/errors.js';\r\nimport { newGuid } from '../abstractions/guid.js';\r\nimport { G9SyncProtocol } from '../protocol/protocol.js';\r\nimport type { G9DtSubscriptionState } from '../protocol/dtos.js';\r\nimport { G9RowBatchFormatError } from '../protocol/rowBatch/format.js';\r\nimport { columnTypeName } from '../abstractions/enums.js';\r\nimport { createAbortController, type G9AbortController } from '../internal/abort.js';\r\nimport type { G9DtSyncProgress, G9ESyncPhase } from './progress.js';\r\nimport {\r\n G9ApplyReport,\r\n G9ELocalStoreFailure,\r\n isLocalStoreFailure,\r\n type G9ApplySlice,\r\n type G9PendingSummary,\r\n type G9SyncRunReport,\r\n type G9SyncSubscriptionRecord,\r\n} from './storeTypes.js';\r\n\r\n/** Scheduling priority (`G9ESyncPriority`). A higher priority pre-empts a running background run. */\r\nexport const G9ESyncPriority = {\r\n Background: 0,\r\n Foreground: 1,\r\n UserInteractive: 2,\r\n} as const;\r\nexport type G9ESyncPriority = (typeof G9ESyncPriority)[keyof typeof G9ESyncPriority];\r\n\r\nconst PRIORITY_NAMES = ['Background', 'Foreground', 'UserInteractive'];\r\nexport function priorityName(priority: number): string {\r\n return PRIORITY_NAMES[priority] ?? String(priority);\r\n}\r\n\r\n/** `G9ESyncOutcome`. */\r\nexport const G9ESyncOutcome = {\r\n Succeeded: 0,\r\n /** Data moved, but some rows were rejected or some subscriptions reported problems. */\r\n CompletedWithRejections: 1,\r\n Failed: 2,\r\n Canceled: 3,\r\n} as const;\r\nexport type G9ESyncOutcome = (typeof G9ESyncOutcome)[keyof typeof G9ESyncOutcome];\r\n\r\nconst OUTCOME_NAMES = ['Succeeded', 'CompletedWithRejections', 'Failed', 'Canceled'];\r\nexport function outcomeName(outcome: number): string {\r\n return OUTCOME_NAMES[outcome] ?? String(outcome);\r\n}\r\n\r\n/** Context handed to an app-owned post step (`G9CSyncPostStepContext`). */\r\nexport interface G9SyncPostStepContext {\r\n run: G9SyncRun;\r\n /** Everything this run changed so far. */\r\n changes: G9ApplyReport;\r\n /** Report 0..1 of the step; mapped into the step's slice of the bar. */\r\n progress: (fraction: number) => void;\r\n}\r\n\r\n/** An app-owned step that runs after the data applied and owns a slice of the progress bar (`G9CSyncPostStep`). */\r\nexport class G9SyncPostStep {\r\n readonly name: string;\r\n readonly weightHint: number;\r\n readonly action: (context: G9SyncPostStepContext, signal: AbortSignal) => Promise<void>;\r\n\r\n constructor(name: string, weightHint: number, action: (context: G9SyncPostStepContext, signal: AbortSignal) => Promise<void>) {\r\n if (typeof name !== 'string' || name.trim() === '') throw new TypeError('A post step needs a name.');\r\n if (typeof action !== 'function') throw new TypeError('A post step needs an action.');\r\n this.name = name;\r\n this.weightHint = Math.min(Math.max(weightHint, 0), 0.9);\r\n this.action = action;\r\n }\r\n}\r\n\r\n/** A sync request (`G9CSyncRequest`). */\r\nexport interface G9SyncRequest {\r\n /** Subscription keys or names to pull; omitted = every local subscription (background runs skip heavy ones). */\r\n subscriptions?: readonly string[] | null;\r\n push?: boolean;\r\n pull?: boolean;\r\n /** Reconcile the selected subscriptions even when nothing asks for it. */\r\n forceReconcile?: boolean;\r\n priority?: G9ESyncPriority;\r\n postSteps?: readonly G9SyncPostStep[];\r\n progress?: ((progress: G9DtSyncProgress) => void) | null;\r\n signal?: AbortSignal | null;\r\n}\r\n\r\n/** The request with its defaults filled in. */\r\nexport interface G9ResolvedSyncRequest {\r\n subscriptions: readonly string[] | null;\r\n push: boolean;\r\n pull: boolean;\r\n forceReconcile: boolean;\r\n priority: G9ESyncPriority;\r\n postSteps: readonly G9SyncPostStep[];\r\n progress: ((progress: G9DtSyncProgress) => void) | null;\r\n signal: AbortSignal | null;\r\n}\r\n\r\nexport function resolveRequest(request: G9SyncRequest | null | undefined): G9ResolvedSyncRequest {\r\n return {\r\n subscriptions: request?.subscriptions ?? null,\r\n push: request?.push ?? true,\r\n pull: request?.pull ?? true,\r\n forceReconcile: request?.forceReconcile ?? false,\r\n priority: request?.priority ?? 1,\r\n postSteps: request?.postSteps ?? [],\r\n progress: request?.progress ?? null,\r\n signal: request?.signal ?? null,\r\n };\r\n}\r\n\r\n/** `G9CSyncRequest.CanCoalesce`. */\r\nexport function canCoalesce(request: G9ResolvedSyncRequest): boolean {\r\n return request.postSteps.length === 0 && request.progress === null && request.signal === null;\r\n}\r\n\r\n/** `G9CSyncRequest.Signature`. */\r\nexport function requestSignature(request: G9ResolvedSyncRequest): string {\r\n const subscriptions = request.subscriptions === null ? '*' : request.subscriptions.slice().sort((a, b) => (a < b ? -1 : a > b ? 1 : 0)).join(',');\r\n return `${request.push ? 'True' : 'False'}|${request.pull ? 'True' : 'False'}|${request.forceReconcile ? 'True' : 'False'}|${subscriptions}`;\r\n}\r\n\r\n/** One defect of the client model, as the server sees it (`G9CSyncModelProblem`). */\r\nexport interface G9SyncModelProblem {\r\n code: string;\r\n table: string;\r\n column: string;\r\n clientType: G9ESyncColumnType;\r\n serverType: G9ESyncColumnType;\r\n}\r\n\r\nexport function describeModelProblem(problem: G9SyncModelProblem): string {\r\n return `${problem.table}.${problem.column} is ${columnTypeName(problem.clientType)} on the client and ${columnTypeName(problem.serverType)} on the server`;\r\n}\r\n\r\n/** The result of a run (`G9CSyncRunResult`). */\r\nexport interface G9SyncRunResult {\r\n runId: string;\r\n outcome: G9ESyncOutcome;\r\n error: G9SyncException | null;\r\n /** Rows and commands SENT, refused ones included (a row refused on the device before sending is not). */\r\n pushed: number;\r\n /** Rows and commands the server TOOK - what an app may call \"sent\"; never `pushed - rejected` (LES-0071). */\r\n accepted: number;\r\n /** Rows refused by the server, or on the device before sending (too large). */\r\n rejected: number;\r\n conflicts: number;\r\n downloaded: number;\r\n applied: number;\r\n durationMs: number;\r\n /** Milliseconds spent in each phase of this run, keyed by phase name. */\r\n phaseMs: { [phase: string]: number };\r\n subscriptions: string[];\r\n /** Subscriptions that could not sync, with the server's reason. */\r\n problems: G9DtSubscriptionState[];\r\n /** Defects of the client model the server reported in this run's hello (ADR-0061). */\r\n modelProblems: G9SyncModelProblem[];\r\n changes: G9ApplyReport;\r\n isSuccess: boolean;\r\n}\r\n\r\nexport function makeRunResult(fields: Partial<G9SyncRunResult> & { runId: string; outcome: G9ESyncOutcome }): G9SyncRunResult {\r\n return {\r\n error: null,\r\n pushed: 0,\r\n accepted: 0,\r\n rejected: 0,\r\n conflicts: 0,\r\n downloaded: 0,\r\n applied: 0,\r\n durationMs: 0,\r\n phaseMs: {},\r\n subscriptions: [],\r\n problems: [],\r\n modelProblems: [],\r\n changes: new G9ApplyReport(),\r\n ...fields,\r\n isSuccess: fields.outcome === G9ESyncOutcome.Succeeded || fields.outcome === G9ESyncOutcome.CompletedWithRejections,\r\n };\r\n}\r\n\r\n/** A queued or running sync (`G9CSyncRun`). Await {@link completion}; read progress with {@link onProgress} or {@link progress}. */\r\nexport class G9SyncRun {\r\n readonly runId: string = newGuid();\r\n readonly request: G9ResolvedSyncRequest;\r\n readonly completion: Promise<G9SyncRunResult>;\r\n latestProgress: G9DtSyncProgress | null = null;\r\n isStarted = false;\r\n\r\n /** @internal */\r\n readonly cancellation: G9AbortController;\r\n /** @internal */\r\n preempted = false;\r\n\r\n private _resolve!: (result: G9SyncRunResult) => void;\r\n private readonly _listeners: ((progress: G9DtSyncProgress) => void)[] = [];\r\n private readonly _buffer: G9DtSyncProgress[] = [];\r\n private readonly _waiters: ((value: IteratorResult<G9DtSyncProgress>) => void)[] = [];\r\n private _done = false;\r\n private _unlink: () => void = () => undefined;\r\n\r\n constructor(request: G9ResolvedSyncRequest) {\r\n this.request = request;\r\n this.completion = new Promise<G9SyncRunResult>((resolve) => {\r\n this._resolve = resolve;\r\n });\r\n this.cancellation = createAbortController();\r\n const external = request.signal;\r\n if (external) {\r\n if (external.aborted) this.cancellation.abort();\r\n else {\r\n const listener = (): void => this.cancellation.abort();\r\n external.addEventListener('abort', listener);\r\n this._unlink = () => external.removeEventListener('abort', listener);\r\n }\r\n }\r\n }\r\n\r\n /** Requests cancellation. Network phases stop at once; an apply in progress finishes atomically first. */\r\n cancel(): void {\r\n this.cancellation.abort();\r\n }\r\n\r\n /** Subscribes to progress samples; returns the unsubscribe function. */\r\n onProgress(listener: (progress: G9DtSyncProgress) => void): () => void {\r\n this._listeners.push(listener);\r\n return () => {\r\n const index = this._listeners.indexOf(listener);\r\n if (index >= 0) this._listeners.splice(index, 1);\r\n };\r\n }\r\n\r\n /** The progress stream (bounded: the oldest samples are dropped when a reader falls 64 behind), ending with the run. */\r\n progress(): AsyncIterable<G9DtSyncProgress> {\r\n // eslint-disable-next-line @typescript-eslint/no-this-alias\r\n const run = this;\r\n return {\r\n [Symbol.asyncIterator](): AsyncIterator<G9DtSyncProgress> {\r\n return {\r\n next(): Promise<IteratorResult<G9DtSyncProgress>> {\r\n const value = run._buffer.shift();\r\n if (value) return Promise.resolve({ value, done: false });\r\n if (run._done) return Promise.resolve({ value: undefined as unknown as G9DtSyncProgress, done: true });\r\n return new Promise((resolve) => run._waiters.push(resolve));\r\n },\r\n };\r\n },\r\n };\r\n }\r\n\r\n /** @internal */\r\n publish(progress: G9DtSyncProgress): void {\r\n this.latestProgress = progress;\r\n const waiter = this._waiters.shift();\r\n if (waiter) waiter({ value: progress, done: false });\r\n else {\r\n this._buffer.push(progress);\r\n if (this._buffer.length > 64) this._buffer.shift();\r\n }\r\n for (const listener of this._listeners.slice()) {\r\n try {\r\n listener(progress);\r\n } catch {\r\n // A progress consumer must never break the sync.\r\n }\r\n }\r\n try {\r\n this.request.progress?.(progress);\r\n } catch {\r\n // A progress consumer must never break the sync.\r\n }\r\n }\r\n\r\n /** @internal */\r\n complete(result: G9SyncRunResult): void {\r\n if (this._done) return;\r\n this._done = true;\r\n for (const waiter of this._waiters.splice(0, this._waiters.length)) waiter({ value: undefined as unknown as G9DtSyncProgress, done: true });\r\n this._unlink();\r\n this._resolve(result);\r\n }\r\n}\r\n\r\n/** `G9CSubscriptionOptions`. */\r\nexport interface G9SubscriptionOptions {\r\n /** Overrides the server definition's ephemeral flag. */\r\n ephemeral?: boolean;\r\n ttlMs?: number;\r\n /** The rows already exist locally: reconcile instead of downloading a snapshot. Call adoptExistingRows first. */\r\n adoptExistingRows?: boolean;\r\n}\r\n\r\n/** Engine options (`G9CSyncEngineOptions`). Durations are milliseconds. */\r\nexport interface G9SyncEngineOptions {\r\n /** Sent at Hello; the server's connect gates may refuse old versions. */\r\n appVersion?: string | null;\r\n pushBatchRows?: number;\r\n /** Transient failures retried inside one run. */\r\n maxRetries?: number;\r\n retryBaseDelayMs?: number;\r\n /** Queue a background pull when the server pokes about changed tables. */\r\n pullOnChangesAvailable?: boolean;\r\n changesDebounceMs?: number;\r\n progressMaxHz?: number;\r\n fetchKeysPerRequest?: number;\r\n /** Rows a reconciliation fetches before it applies them (ADR-0066). */\r\n reconcileApplyRows?: number;\r\n /** A reconciliation that would fetch at least this many rows of one table hands them to a staged snapshot (ADR-0066). 0 = never. */\r\n reconcileSnapshotThreshold?: number;\r\n /** The largest decoded body accepted from one server frame (ADR-0051). */\r\n maxDecodedFrameBytes?: number;\r\n /** The newest G9RowBatch body layout to ask the server for (ADR-0040). */\r\n maxFrameVersion?: number;\r\n /** Fail a run when the server reports a client column whose type differs (ADR-0061). */\r\n failOnTypeMismatch?: boolean;\r\n /**\r\n * Offer the server to send large first downloads as SQLite snapshot files (ADR-0072), when the store can take them (a store\r\n * with a `snapshotFiles` sink). Default true. A file that fails is replaced by the same pull as rows, in the same run.\r\n */\r\n acceptSnapshotFiles?: boolean;\r\n /** A staged pull older than this is discarded instead of resumed. */\r\n stagedPullMaxAgeMs?: number;\r\n /** Most payload bytes kept in stages other than the one a run resumes (ADR-0060). */\r\n stagedPullsMaxBytes?: number;\r\n keepDeletedFeedEntries?: number;\r\n keepRunReports?: number;\r\n /** Where the engine logs (the ILogger twin); silent when omitted. */\r\n logger?: G9SyncLogger | null;\r\n /** Platform integration (foreground service, keep-awake, connectivity). */\r\n hooks?: G9SyncHostHooks | null;\r\n}\r\n\r\nexport type G9ResolvedEngineOptions = Required<Omit<G9SyncEngineOptions, 'appVersion' | 'logger' | 'hooks'>> & {\r\n appVersion: string | null;\r\n logger: G9SyncLogger | null;\r\n hooks: G9SyncHostHooks | null;\r\n};\r\n\r\nexport function resolveEngineOptions(options: G9SyncEngineOptions | null | undefined): G9ResolvedEngineOptions {\r\n return {\r\n appVersion: options?.appVersion ?? null,\r\n pushBatchRows: options?.pushBatchRows ?? 2000,\r\n maxRetries: options?.maxRetries ?? 5,\r\n retryBaseDelayMs: options?.retryBaseDelayMs ?? 1000,\r\n pullOnChangesAvailable: options?.pullOnChangesAvailable ?? true,\r\n changesDebounceMs: options?.changesDebounceMs ?? 2000,\r\n progressMaxHz: options?.progressMaxHz ?? 10,\r\n fetchKeysPerRequest: options?.fetchKeysPerRequest ?? 2000,\r\n reconcileApplyRows: options?.reconcileApplyRows ?? 20000,\r\n reconcileSnapshotThreshold: options?.reconcileSnapshotThreshold ?? 100000,\r\n maxDecodedFrameBytes: options?.maxDecodedFrameBytes ?? 64 * 1024 * 1024,\r\n maxFrameVersion: options?.maxFrameVersion ?? G9SyncProtocol.MaxFrameVersion,\r\n failOnTypeMismatch: options?.failOnTypeMismatch ?? false,\r\n acceptSnapshotFiles: options?.acceptSnapshotFiles ?? true,\r\n stagedPullMaxAgeMs: options?.stagedPullMaxAgeMs ?? 90 * 60 * 1000,\r\n stagedPullsMaxBytes: options?.stagedPullsMaxBytes ?? 64 * 1024 * 1024,\r\n keepDeletedFeedEntries: options?.keepDeletedFeedEntries ?? 50000,\r\n keepRunReports: options?.keepRunReports ?? 50,\r\n logger: options?.logger ?? null,\r\n hooks: options?.hooks ?? null,\r\n };\r\n}\r\n\r\n/** Log levels of {@link G9SyncLogger} (Microsoft.Extensions.Logging's). */\r\nexport type G9SyncLogLevel = 'debug' | 'information' | 'warning' | 'error';\r\n\r\n/** Where the library logs. `eventId` is the .NET LoggerMessage event id of the same message. */\r\nexport interface G9SyncLogger {\r\n log(level: G9SyncLogLevel, eventId: number, message: string, error?: unknown): void;\r\n}\r\n\r\n/** Platform integration points (`IG9SyncHostHooks`). */\r\nexport interface G9SyncHostHooks {\r\n /** Called when a run starts executing; the returned scope's `dispose` runs when it ends. */\r\n beginRun(run: G9SyncRun, signal: AbortSignal): Promise<{ dispose(): void | Promise<void> } | null>;\r\n /** False skips automatic background runs. */\r\n readonly isNetworkAvailable: boolean;\r\n}\r\n\r\n/** `G9CSyncHealth`. */\r\nexport interface G9SyncHealth {\r\n clientId: string;\r\n isConnected: boolean;\r\n isRunning: boolean;\r\n queuedRuns: number;\r\n serverEpoch: string | null;\r\n lastHelloUtcMs: number | null;\r\n pending: G9PendingSummary;\r\n subscriptions: G9SyncSubscriptionRecord[];\r\n recentRuns: G9SyncRunReport[];\r\n}\r\n\r\n/** `G9CRowsAppliedEventArgs`. */\r\nexport interface G9RowsAppliedEvent {\r\n report: G9ApplyReport;\r\n source: G9ESyncPhase;\r\n /** Set for a staged pull applied in slices (ADR-0053). */\r\n slice: G9ApplySlice | null;\r\n}\r\n\r\n/** `G9CSyncErrors.Normalize`: every failure becomes a G9SyncException with a stable code. */\r\nexport function normalizeError(error: unknown): G9SyncException {\r\n if (isSyncException(error)) return error as G9SyncException;\r\n const message = error instanceof Error ? error.message : String(error);\r\n if (error instanceof Error && error.name === 'AbortError') return new G9SyncException(G9SyncErrorCodes.Canceled, 'The sync was canceled.', { cause: error });\r\n if (isLocalStoreFailure(error)) {\r\n const code =\r\n error.localStoreFailure === G9ELocalStoreFailure.Corrupt\r\n ? G9SyncErrorCodes.LocalStoreCorrupt\r\n : error.localStoreFailure === G9ELocalStoreFailure.DiskFull\r\n ? G9SyncErrorCodes.LocalStoreDiskFull\r\n : error.localStoreFailure === G9ELocalStoreFailure.Busy\r\n ? G9SyncErrorCodes.LocalStoreBusy\r\n : G9SyncErrorCodes.LocalStoreError;\r\n return new G9SyncException(code, message, { cause: error });\r\n }\r\n if (error instanceof G9RowBatchFormatError) return new G9SyncException(G9SyncErrorCodes.Unknown, message, { cause: error });\r\n if (error instanceof Error && (error.name === 'TimeoutError' || /network|socket|websocket|connection/i.test(error.name))) {\r\n return new G9SyncException(G9SyncErrorCodes.NetworkFailure, message, { cause: error });\r\n }\r\n return new G9SyncException(G9SyncErrorCodes.Unknown, message, { cause: error });\r\n}\r\n\r\n/** `G9CSyncErrors.IsTransient`. */\r\nexport function isTransientError(error: unknown): boolean {\r\n const code = normalizeError(error).code;\r\n return code === G9SyncErrorCodes.NetworkFailure || code === G9SyncErrorCodes.ServerError || code === G9SyncErrorCodes.ServerBusy;\r\n}\r\n"]}
package/dist/index.d.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  /** The package version; equal to the .NET packages' (G9SyncDataVersion) — one release, both sides. */
2
- export declare const VERSION = "1.5.3";
2
+ export declare const VERSION = "1.5.5";
3
3
  export { G9EConflictPolicy, G9EMoveOutPolicy, G9ESyncColumnType, G9ESyncDirection, columnTypeName, isColumnType } from './abstractions/enums.js';
4
4
  export { G9SyncErrorCodes, G9SyncException, isRetryableCode, isSyncException, type G9SyncExceptionOptions } from './abstractions/errors.js';
5
5
  export { G9Long, parseJson, stringifyJson } from './abstractions/long.js';
package/dist/index.js CHANGED
@@ -3,7 +3,7 @@
3
3
  // doubles `@g9tm/syncdata/testing`, the pure-JavaScript Brotli decoder `@g9tm/syncdata/brotli-js`; Lynx wiring is the
4
4
  // separate package `@g9tm/syncdata-lynx`. Every public type keeps its .NET name without the G9C prefix (PARITY.md).
5
5
  /** The package version; equal to the .NET packages' (G9SyncDataVersion) — one release, both sides. */
6
- export const VERSION = '1.5.3';
6
+ export const VERSION = '1.5.5';
7
7
  // abstractions
8
8
  export { G9EConflictPolicy, G9EMoveOutPolicy, G9ESyncColumnType, G9ESyncDirection, columnTypeName, isColumnType } from './abstractions/enums.js';
9
9
  export { G9SyncErrorCodes, G9SyncException, isRetryableCode, isSyncException } from './abstractions/errors.js';
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,wHAAwH;AACxH,uHAAuH;AACvH,sHAAsH;AACtH,oHAAoH;AAEpH,sGAAsG;AACtG,MAAM,CAAC,MAAM,OAAO,GAAG,OAAO,CAAC;AAE/B,eAAe;AACf,OAAO,EAAE,iBAAiB,EAAE,gBAAgB,EAAE,iBAAiB,EAAE,gBAAgB,EAAE,cAAc,EAAE,YAAY,EAAE,MAAM,yBAAyB,CAAC;AACjJ,OAAO,EAAE,gBAAgB,EAAE,eAAe,EAAE,eAAe,EAAE,eAAe,EAA+B,MAAM,0BAA0B,CAAC;AAC5I,OAAO,EAAE,MAAM,EAAE,SAAS,EAAE,aAAa,EAAE,MAAM,wBAAwB,CAAC;AAC1E,OAAO,EAAE,UAAU,EAAE,OAAO,EAAE,OAAO,EAAE,aAAa,EAAE,gBAAgB,EAAE,MAAM,wBAAwB,CAAC;AACvG,OAAO,EAAE,SAAS,EAAE,MAAM,uBAAuB,CAAC;AAClD,OAAO,EAAE,Y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AAC;AAEnE,2CAA2C;AAC3C,OAAO,EAAE,aAAa,EAAE,aAAa,EAAE,MAAM,sBAAsB,CAAC;AACpE,OAAO,EAAE,UAAU,EAAE,UAAU,EAAE,MAAM,oBAAoB,CAAC;AAC5D,OAAO,EAAE,GAAG,EAAE,MAAM,mBAAmB,CAAC;AACxC,OAAO,EAAE,MAAM,EAAE,KAAK,EAAE,MAAM,sBAAsB,CAAC;AACrD,OAAO,EAAE,iBAAiB,EAAE,qBAAqB,EAAE,KAAK,EAAE,WAAW,EAAE,OAAO,EAAE,gBAAgB,EAAE,MAAM,qBAAqB,CAAC","sourcesContent":["// @g9tm/syncdata — the TypeScript twin of the G9SyncData .NET client (abstractions, protocol, engine). The SQLite store\n// is `@g9tm/syncdata/sqlite`, the SignalR transport `@g9tm/syncdata/signalr`, Node helpers `@g9tm/syncdata/node`, test\n// doubles `@g9tm/syncdata/testing`, the pure-JavaScript Brotli decoder `@g9tm/syncdata/brotli-js`; Lynx wiring is the\n// separate package `@g9tm/syncdata-lynx`. Every public type keeps its .NET name without the G9C prefix (PARITY.md).\n\n/** The package version; equal to the .NET packages' (G9SyncDataVersion) — one release, both sides. */\nexport const VERSION = '1.5.3';\n\n// abstractions\nexport { G9EConflictPolicy, G9EMoveOutPolicy, G9ESyncColumnType, G9ESyncDirection, columnTypeName, isColumnType } from './abstractions/enums.js';\nexport { G9SyncErrorCodes, G9SyncException, isRetryableCode, isSyncException, type G9SyncExceptionOptions } from './abstractions/errors.js';\nexport { G9Long, parseJson, stringifyJson } from './abstractions/long.js';\nexport { EMPTY_GUID, guidToN, newGuid, normalizeGuid, tryNormalizeGuid } from './abstractions/guid.js';\nexport { G9SyncKey } from './abstractions/key.js';\nexport { G9SyncDigest } from './abstractions/digest.js';\nexport { G9SyncParameters, escapeDataString } from './abstractions/parameters.js';\n\n// protocol\nexport * from './protocol/dtos.js';\nexport { G9SyncHubErrors, G9SyncProtocol, negotiateFrameVersion, tableGroup } from './protocol/protocol.js';\nexport {\n bytesField,\n dateTimeMs,\n fromMessagePackNames,\n G9WireGuid,\n GUID_EXTENSION_TYPE,\n readChangesAvailable,\n readContinuation,\n readHelloResult,\n readPullPlan,\n readPushResult,\n readReconcileSummary,\n readSyncChunk,\n toMessagePackNames,\n type G9WireFormat,\n} from './protocol/wire.js';\nexport { G9ECompression, G9EPushRowOp, G9ERowBatchOp, G9RowBatchFormat, G9RowBatchFormatError } from './protocol/rowBatch/format.js';\nexport { G9RowBatchWriter, type G9DateTimeOffsetValue, type G9DateTimeValue, type G9FrameCompressor } from './protocol/rowBatch/writer.js';\nexport {\n G9RowBatchReader,\n getDefaultFrameDecompressor,\n openRowBatch,\n openRowBatchSync,\n readFrameHeader,\n setDefaultFrameDecompressor,\n type G9FrameDecompressor,\n type G9FrameHeader,\n type G9OpenRowBatchOptions,\n} from './protocol/rowBatch/reader.js';\nexport { decimalToDouble, formatDecimal, formatDouble, parseDecimal, type DecimalParts } from './internal/dotnetFormat.js';\n\n// client\nexport { G9SyncClientModel, G9SyncClientModelBuilder, G9SyncClientTable, G9SyncClientTableBuilder, type G9SyncClientColumn, type G9SyncClientIndex } from './client/model.js';\nexport * from './client/storeTypes.js';\nexport type { G9SyncTransport } from './client/transport.js';\nexport { G9ESyncPhase, G9SyncProgressTracker, phaseName, type G9DtSyncProgress } from './client/progress.js';\nexport {\n G9ESyncOutcome,\n G9ESyncPriority,\n G9SyncPostStep,\n G9SyncRun,\n describeModelProblem,\n isTransientError,\n normalizeError,\n outcomeName,\n priorityName,\n resolveEngineOptions,\n type G9RowsAppliedEvent,\n type G9SubscriptionOptions,\n type G9SyncEngineOptions,\n type G9SyncHealth,\n type G9SyncHostHooks,\n type G9SyncLogger,\n type G9SyncLogLevel,\n type G9SyncModelProblem,\n type G9SyncPostStepContext,\n type G9SyncRequest,\n type G9SyncRunResult,\n} from './client/runs.js';\nexport { G9SyncEngine, stageGeneration } from './client/engine.js';\n\n// helpers the Lynx package and tests share\nexport { base64ToBytes, bytesToBase64 } from './internal/base64.js';\nexport { utf8Decode, utf8Encode } from './internal/utf8.js';\nexport { md5 } from './internal/md5.js';\nexport { sha256, toHex } from './internal/sha256.js';\nexport { cancellationError, createAbortController, delay, linkSignals, onAbort, yieldToEventLoop } from './internal/abort.js';\n"]}
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,wHAAwH;AACxH,uHAAuH;AACvH,sHAAsH;AACtH,oHAAoH;AAEpH,sGAAsG;AACtG,MAAM,CAAC,MAAM,OAAO,GAAG,OAAO,CAAC;AAE/B,eAAe;AACf,OAAO,EAAE,iBAAiB,EAAE,gBAAgB,EAAE,iBAAiB,EAAE,gBAAgB,EAAE,cAAc,EAAE,YAAY,EAAE,MAAM,yBAAyB,CAAC;AACjJ,OAAO,EAAE,gBAAgB,EAAE,eAAe,EAAE,eAAe,EAAE,eAAe,EAA+B,MAAM,0BAA0B,CAAC;AAC5I,OAAO,EAAE,MAAM,EAAE,SAAS,EAAE,aAAa,EAAE,MAAM,wBAAwB,CAAC;AAC1E,OAAO,EAAE,UAAU,EAAE,OAAO,EAAE,OAAO,EAAE,aAAa,EAAE,gBAAgB,EAAE,MAAM,wBAAwB,CAAC;AACvG,OAAO,EAAE,SAAS,EAAE,MAAM,uBAAuB,CAAC;AAClD,OAAO,EAAE,YAAY,EAAE,MAAM,0BAA0B,CAAC;AACxD,OAAO,EAAE,gBAAgB,EAAE,gBAAgB,EAAE,MAAM,8BAA8B,CAAC;AAElF,WAAW;AACX,cAAc,oBAAoB,CAAC;AACnC,OAAO,EAAE,eAAe,EAAE,cAAc,EAAE,qBAAqB,EAAE,UAAU,EAAE,MAAM,wBAAwB,CAAC;AAC5G,OAAO,EACL,UAAU,EACV,UAAU,EACV,oBAAoB,EACpB,UAAU,EACV,mBAAmB,EACnB,oBAAoB,EACpB,gBAAgB,EAChB,eAAe,EACf,YAAY,EACZ,cAAc,EACd,oBAAoB,EACpB,aAAa,EACb,kBAAkB,GAEnB,MAAM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of the G9SyncData .NET client (abstractions, protocol, engine). The SQLite store\n// is `@g9tm/syncdata/sqlite`, the SignalR transport `@g9tm/syncdata/signalr`, Node helpers `@g9tm/syncdata/node`, test\n// doubles `@g9tm/syncdata/testing`, the pure-JavaScript Brotli decoder `@g9tm/syncdata/brotli-js`; Lynx wiring is the\n// separate package `@g9tm/syncdata-lynx`. Every public type keeps its .NET name without the G9C prefix (PARITY.md).\n\n/** The package version; equal to the .NET packages' (G9SyncDataVersion) — one release, both sides. */\nexport const VERSION = '1.5.5';\n\n// abstractions\nexport { G9EConflictPolicy, G9EMoveOutPolicy, G9ESyncColumnType, G9ESyncDirection, columnTypeName, isColumnType } from './abstractions/enums.js';\nexport { G9SyncErrorCodes, G9SyncException, isRetryableCode, isSyncException, type G9SyncExceptionOptions } from './abstractions/errors.js';\nexport { G9Long, parseJson, stringifyJson } from './abstractions/long.js';\nexport { EMPTY_GUID, guidToN, newGuid, normalizeGuid, tryNormalizeGuid } from './abstractions/guid.js';\nexport { G9SyncKey } from './abstractions/key.js';\nexport { G9SyncDigest } from './abstractions/digest.js';\nexport { G9SyncParameters, escapeDataString } from './abstractions/parameters.js';\n\n// protocol\nexport * from './protocol/dtos.js';\nexport { G9SyncHubErrors, G9SyncProtocol, negotiateFrameVersion, tableGroup } from './protocol/protocol.js';\nexport {\n bytesField,\n dateTimeMs,\n fromMessagePackNames,\n G9WireGuid,\n GUID_EXTENSION_TYPE,\n readChangesAvailable,\n readContinuation,\n readHelloResult,\n readPullPlan,\n readPushResult,\n readReconcileSummary,\n readSyncChunk,\n toMessagePackNames,\n type G9WireFormat,\n} from './protocol/wire.js';\nexport { G9ECompression, G9EPushRowOp, G9ERowBatchOp, G9RowBatchFormat, G9RowBatchFormatError } from './protocol/rowBatch/format.js';\nexport { G9RowBatchWriter, type G9DateTimeOffsetValue, type G9DateTimeValue, type G9FrameCompressor } from './protocol/rowBatch/writer.js';\nexport {\n G9RowBatchReader,\n getDefaultFrameDecompressor,\n openRowBatch,\n openRowBatchSync,\n readFrameHeader,\n setDefaultFrameDecompressor,\n type G9FrameDecompressor,\n type G9FrameHeader,\n type G9OpenRowBatchOptions,\n} from './protocol/rowBatch/reader.js';\nexport { decimalToDouble, formatDecimal, formatDouble, parseDecimal, type DecimalParts } from './internal/dotnetFormat.js';\n\n// client\nexport { G9SyncClientModel, G9SyncClientModelBuilder, G9SyncClientTable, G9SyncClientTableBuilder, type G9SyncClientColumn, type G9SyncClientIndex } from './client/model.js';\nexport * from './client/storeTypes.js';\nexport type { G9SyncTransport } from './client/transport.js';\nexport { G9ESyncPhase, G9SyncProgressTracker, phaseName, type G9DtSyncProgress } from './client/progress.js';\nexport {\n G9ESyncOutcome,\n G9ESyncPriority,\n G9SyncPostStep,\n G9SyncRun,\n describeModelProblem,\n isTransientError,\n normalizeError,\n outcomeName,\n priorityName,\n resolveEngineOptions,\n type G9RowsAppliedEvent,\n type G9SubscriptionOptions,\n type G9SyncEngineOptions,\n type G9SyncHealth,\n type G9SyncHostHooks,\n type G9SyncLogger,\n type G9SyncLogLevel,\n type G9SyncModelProblem,\n type G9SyncPostStepContext,\n type G9SyncRequest,\n type G9SyncRunResult,\n} from './client/runs.js';\nexport { G9SyncEngine, stageGeneration } from './client/engine.js';\n\n// helpers the Lynx package and tests share\nexport { base64ToBytes, bytesToBase64 } from './internal/base64.js';\nexport { utf8Decode, utf8Encode } from './internal/utf8.js';\nexport { md5 } from './internal/md5.js';\nexport { sha256, toHex } from './internal/sha256.js';\nexport { cancellationError, createAbortController, delay, linkSignals, onAbort, yieldToEventLoop } from './internal/abort.js';\n"]}
@@ -19,8 +19,11 @@ export declare function disposeReleasedRow(store: StoreInternals, connection: G9
19
19
  export declare function disposeReleasedRows(store: StoreInternals, connection: G9SqliteConnection, releasedSql: string, releasedParams: G9Params, reason: G9ERevocationReason, subscriptionKey: string | null, report: G9ApplyReport | null, onRemoved?: (tid: number, key: string) => void): Promise<number>;
20
20
  /**
21
21
  * `RevertRejectedAsync` (LES-0070): gives up the local change of rejected rows and takes the server's copy. A row the server never had
22
- * (`server_ver = 0`) is removed locally; any other drops its pending change and its version, so the next forced reconciliation
23
- * fetches the server's copy (the digest hashes key + server_ver, not the values). A library write: capture is silent, nothing uploads.
22
+ * (`server_ver = 0` and held by no subscription) is removed locally. Any other drops its pending change and gets `server_ver = -1`: the
23
+ * digest hashes key + server_ver, not the values, and a server reports version 0 for every row unchanged since its tracking began, so
24
+ * "forget the version" (0) would leave the hash equal and the local values in place for good. -1 is a version no server issues: the
25
+ * reconcile fetches the row and the apply writes the server's values and real version. The subscriptions holding the row become
26
+ * NeedsReconcile, so their next sync of any kind does it (offline now is fine). A library write: capture is silent, nothing uploads.
24
27
  */
25
28
  export declare function revertRejected(store: StoreInternals, localTable: string | null, key: string | null): Promise<number>;
26
29
  /** `RemoveLocalRow`: the row leaves the app's table; its metadata becomes a tombstone at the clock's next value. */
@@ -6,7 +6,7 @@
6
6
  // clock afterwards (unconditionally, like the .NET store's `++sequence`).
7
7
  import { G9ESyncColumnType } from '../abstractions/enums.js';
8
8
  import { G9Long } from '../abstractions/long.js';
9
- import { G9ApplyReport, G9ERevocationDisposition, G9ERevocationReason, } from '../client/storeTypes.js';
9
+ import { G9ApplyReport, G9ERevocationDisposition, G9ERevocationReason, G9ESubscriptionState, } from '../client/storeTypes.js';
10
10
  import { asLong, asNumber, asOptionalString, asString, G9StatementBatch, statementsOf } from './connection.js';
11
11
  import { byTid, deserializeValues, getLocal, keyValue, nowMs, readLocalValues, serializeValues } from './internals.js';
12
12
  import { quote } from './sql.js';
@@ -212,8 +212,11 @@ function removeLocalRowStatements(table, key, seq, seqParams) {
212
212
  }
213
213
  /**
214
214
  * `RevertRejectedAsync` (LES-0070): gives up the local change of rejected rows and takes the server's copy. A row the server never had
215
- * (`server_ver = 0`) is removed locally; any other drops its pending change and its version, so the next forced reconciliation
216
- * fetches the server's copy (the digest hashes key + server_ver, not the values). A library write: capture is silent, nothing uploads.
215
+ * (`server_ver = 0` and held by no subscription) is removed locally. Any other drops its pending change and gets `server_ver = -1`: the
216
+ * digest hashes key + server_ver, not the values, and a server reports version 0 for every row unchanged since its tracking began, so
217
+ * "forget the version" (0) would leave the hash equal and the local values in place for good. -1 is a version no server issues: the
218
+ * reconcile fetches the row and the apply writes the server's values and real version. The subscriptions holding the row become
219
+ * NeedsReconcile, so their next sync of any kind does it (offline now is fine). A library write: capture is silent, nothing uploads.
217
220
  */
218
221
  export async function revertRejected(store, localTable, key) {
219
222
  store.ensureInitialized();
@@ -229,7 +232,7 @@ export async function revertRejected(store, localTable, key) {
229
232
  }
230
233
  return store.writeLock.run(() => store.writer().transaction('immediate', async () => {
231
234
  const connection = store.writer();
232
- const rows = await connection.query('SELECT tid, pk, server_ver FROM g9_rows WHERE ' + where, params);
235
+ const rows = await connection.query('SELECT tid, pk, (server_ver = 0 AND subs = 0) FROM g9_rows WHERE ' + where, params);
233
236
  if (rows.length === 0)
234
237
  return 0;
235
238
  await connection.exec('UPDATE g9_ctx SET applying = 1 WHERE id = 1');
@@ -239,13 +242,15 @@ export async function revertRejected(store, localTable, key) {
239
242
  const table = byTid(store, tid);
240
243
  if (!table)
241
244
  continue;
242
- if (asNumber(r[2]) === 0) {
245
+ if (asNumber(r[2]) === 1) {
243
246
  for (const statement of removeLocalRowStatements(table, pk, NEXT_SEQ, {}))
244
247
  await connection.exec(statement.script, statement.params);
245
248
  await connection.exec('UPDATE g9_clock SET seq = seq + 1 WHERE id = 1');
246
249
  continue;
247
250
  }
248
- await connection.exec('DELETE FROM g9_rejections WHERE tid = $t AND pk = $pk; UPDATE g9_rows SET dirty = 0, dirty_mask = 0, rejected = 0, server_ver = 0 WHERE tid = $t AND pk = $pk', { $t: tid, $pk: pk });
251
+ await connection.exec('DELETE FROM g9_rejections WHERE tid = $t AND pk = $pk; ' +
252
+ 'UPDATE g9_subscriptions SET state = $needs WHERE (((SELECT subs FROM g9_rows WHERE tid = $t AND pk = $pk) >> slot) & 1) = 1; ' +
253
+ 'UPDATE g9_rows SET dirty = 0, dirty_mask = 0, rejected = 0, server_ver = -1 WHERE tid = $t AND pk = $pk', { $t: tid, $pk: pk, $needs: G9ESubscriptionState.NeedsReconcile });
249
254
  }
250
255
  await connection.exec('UPDATE g9_ctx SET applying = 0 WHERE id = 1');
251
256
  return rows.length;
@@ -1 +1 @@
1
- {"version":3,"file":"revocation.js","sourceRoot":"","sources":["../../src/sqlite/revocation.ts"],"names":[],"mappings":"AAAA,yHAAyH;AACzH,yHAAyH;AACzH,6GAA6G;AAC7G,EAAE;AACF,qHAAqH;AACrH,0EAA0E;AAC1E,OAAO,EAAE,iBAAiB,EAAE,MAAM,0BAA0B,CAAC;AAC7D,OAAO,EAAE,MAAM,EAAE,MAAM,yBAAyB,CAAC;AACjD,OAAO,EACL,aAAa,EACb,wBAAwB,EACxB,mBAAmB,GAKpB,MAAM,yBAAyB,CAAC;AACjC,OAAO,EAAE,MAAM,EAAE,QAAQ,EAAE,gBAAgB,EAAE,QAAQ,EAAE,gBAAgB,EAAE,YAAY,EAA0C,MAAM,iBAAiB,CAAC;AAEvJ,OAAO,EAAE,KAAK,EAAE,iBAAiB,EAAE,QAAQ,EAAE,QAAQ,EAAE,KAAK,EAAE,eAAe,EAAE,eAAe,EAAwC,MAAM,gBAAgB,CAAC;AAC7J,OAAO,EAAE,KAAK,EAAE,MAAM,UAAU,CAAC;AAEjC,MAAM,CAAC,MAAM,sBAAsB,GAAG,iBAAiB,CAAC;AACxD,MAAM,QAAQ,GAAG,6CAA6C,CAAC;AAE/D,MAAM,SAAS;IAIb,YAAY,MAAwC;QAH3C,YAAO,GAAG,IAAI,GAAG,EAAkB,CAAC;QAI3C,IAAI,CAAC,OAAO,GAAG,MAAM,CAAC;IACxB,CAAC;IAED,GAAG,CAAC,MAAc,EAAE,KAAc;QAChC,IAAI,OAAO,MAAM,KAAK,QAAQ,IAAI,MAAM,CAAC,IAAI,EAAE,KAAK,EAAE;YAAE,MAAM,IAAI,SAAS,CAAC,uBAAuB,CAAC,CAAC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IAAI,CAAC,CAAC;YACpF,MAAM,GAAG,GAAiB;gBACxB,UAAU,EAAE,KAAK,CAAC,KAAK,CAAC,SAAS;gBACjC,GAAG,EAAE,KAAK,CAAC,GAAG;gBACd,MAAM,EAAE,KAAK,CAAC,MAA6B;gBAC3C,eAAe,EAAE,IAAI;gBACrB,iBAAiB,EAAE,KAAK;gBACxB,UAAU,EAAE,KAAK;gBACjB,MAAM;aACP,CAAC;YACF,IAAI,IAAI,IAAI,IAAI,CAAC,WAAW,IAAI,MAAM,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC,MAAM,GAAG,CAAC,IAAI,IAAI,CAAC,WAAW,CAAC,GAAG,CAAC;gBAAE,SAAS;YAClG,MAAM,cAAc,CAAC,UAAU,EAAE,KAAK,EAAE,KAAK,CAAC,GAAG,CAAC,CAAC;YACnD,MAAM,UAAU,CAAC,IAAI,CAAC,gDAAgD,CAAC,CAAC;YACxE,OAAO,EAAE,CAAC;QACZ,CAAC;QACD,MAAM,UAAU,CAAC,IAAI,CAAC,6CAA6C,CAAC,CAAC;QACrE,OAAO,OAAO,CAAC;IACjB,CAAC,CAAC,CACH,CAAC;AACJ,CAAC","sourcesContent":["// Twin of G9SyncData.Client.Sqlite/G9CSqliteSyncStore.Revocation.cs: revocation dispositions (ADR-0026). Every path that\r\n// releases a row — a move-out in a pull or a reconciliation, an unsubscribe, an expired ephemeral subscription — ends in\r\n// disposeReleasedRow, which asks the revocation policy what to do with a row NO subscription holds any more.\r\n//\r\n// The local sequence such a row gets is the clock's next value, (SELECT seq FROM g9_clock) + 1; the CALLER moves the\r\n// clock afterwards (unconditionally, like the .NET store's `++sequence`).\r\nimport { G9ESyncColumnType } from '../abstractions/enums.js';\r\nimport { G9Long } from '../abstractions/long.js';\r\nimport {\r\n G9ApplyReport,\r\n G9ERevocationDisposition,\r\n G9ERevocationReason,\r\n type G9QuarantinedRow,\r\n type G9RetainedRow,\r\n type G9RevokedRow,\r\n type G9RevokedRowEditor,\r\n} from '../client/storeTypes.js';\r\nimport { asLong, asNumber, asOptionalString, asString, G9StatementBatch, statementsOf, type G9Params, type G9SqliteConnection } from './connection.js';\r\nimport type { G9SqlValue } from './driver.js';\r\nimport { byTid, deserializeValues, getLocal, keyValue, nowMs, readLocalValues, serializeValues, type LocalTable, type StoreInternals } from './internals.js';\r\nimport { quote } from './sql.js';\r\n\r\nexport const REVOKED_REJECTION_CODE = 'G9S-REJ-REVOKED';\r\nconst NEXT_SEQ = '(SELECT seq FROM g9_clock WHERE id = 1) + 1';\r\n\r\nclass RowEditor implements G9RevokedRowEditor {\r\n readonly changed = new Map<string, string>();\r\n private readonly _values: { [column: string]: G9SqlValue };\r\n\r\n constructor(values: { [column: string]: G9SqlValue }) {\r\n this._values = values;\r\n }\r\n\r\n set(column: string, value: unknown): void {\r\n if (typeof column !== 'string' || column.trim() === '') throw new TypeError('A column is required.');\r\n const actual = Object.keys(this._values).find((c) => c.toLowerCase() === column.toLowerCase());\r\n if (actual === undefined) throw new RangeError(`'${column}' is not a column of the row.`);\r\n this._values[actual] = value as G9SqlValue;\r\n this.changed.set(actual.toLowerCase(), actual);\r\n }\r\n}\r\n\r\n/** What disposing a released row reads about it before anything is written. */\r\ninterface ReleasedRowState {\r\n /** Another subscription still holds the row. */\r\n held: boolean;\r\n dirty: number;\r\n dirtyMask: G9SqlValue;\r\n rejected: number;\r\n /** A pending command touches the row (only looked at when the row has no pending change). */\r\n pendingCommand: boolean;\r\n /** The app row; empty when it is gone. */\r\n values: { [column: string]: G9SqlValue };\r\n}\r\n\r\n/** A row with no metadata row: what the per-row path assumes when its first read finds nothing. */\r\nfunction emptyState(): ReleasedRowState {\r\n return { held: false, dirty: 0, dirtyMask: 0, rejected: 0, pendingCommand: false, values: {} };\r\n}\r\n\r\ninterface Statement {\r\n script: string;\r\n params: G9Params;\r\n}\r\n\r\n/**\r\n * The revocation decision for one released row, as the statements that carry it out, in the order the .NET store runs\r\n * them. `seq` is the SQL of the local sequence the row gets when it moves: NEXT_SEQ, or `$seq` with its value in `seqParams`.\r\n */\r\nfunction planDisposal(\r\n store: StoreInternals,\r\n table: LocalTable,\r\n key: string,\r\n state: ReleasedRowState,\r\n reason: G9ERevocationReason,\r\n subscriptionKey: string | null,\r\n report: G9ApplyReport | null,\r\n seq: string,\r\n seqParams: G9Params,\r\n): { removed: boolean; statements: Statement[] } {\r\n if (state.held) return { removed: false, statements: [] };\r\n // A row touched by a pending command is settled by that command's result, never disposed underneath it.\r\n if (state.dirty === 0 && state.pendingCommand) return { removed: false, statements: [] };\r\n\r\n const values = state.values;\r\n if (Object.keys(values).length === 0) {\r\n const script = 'UPDATE g9_rows SET deleted = 1, dirty = 0, dirty_mask = 0, rejected = 0, local_seq = ' + seq + ' WHERE tid = $t AND pk = $pk';\r\n return { removed: false, statements: [{ script, params: { ...seqParams, $t: table.tid, $pk: key } }] };\r\n }\r\n\r\n const editor = new RowEditor(values);\r\n const row: G9RevokedRow = {\r\n localTable: table.model.localName,\r\n key,\r\n reason,\r\n subscriptionKey,\r\n hasPendingChanges: state.dirty !== 0,\r\n isRejected: state.rejected !== 0,\r\n values,\r\n };\r\n const { rule, disposition } = store.options.revocation.decide(row, editor);\r\n const now = nowMs();\r\n const statements: Statement[] = [];\r\n\r\n switch (disposition) {\r\n case G9ERevocationDisposition.MarkRevoked:\r\n case G9ERevocationDisposition.Retain: {\r\n if (editor.changed.size > 0) {\r\n const columns = Array.from(editor.changed.values());\r\n const params: G9Params = { $k: keyValue(table, key) };\r\n columns.forEach((c, i) => (params['$v' + i] = values[c] as G9SqlValue));\r\n statements.push({ script: `UPDATE ${table.quoted} SET ${columns.map((c, i) => quote(c) + ' = $v' + i).join(', ')} WHERE ${table.keyQuoted} = $k`, params });\r\n }\r\n statements.push({\r\n script: 'INSERT OR REPLACE INTO g9_revoked (tid, pk, disposition, reason, rule, at_utc) VALUES ($t, $pk, $d, $r, $rule, $now)',\r\n params: { $t: table.tid, $pk: key, $d: disposition, $r: reason, $rule: rule ? rule.name : null, $now: now },\r\n });\r\n if (state.dirty !== 0) {\r\n // Its pending change can no longer be accepted: park it as rejected instead of uploading it on every push.\r\n statements.push({\r\n script:\r\n 'UPDATE g9_rows SET rejected = 1 WHERE tid = $t AND pk = $pk; ' +\r\n 'INSERT OR REPLACE INTO g9_rejections (tid, pk, code, message, at_utc) VALUES ($t, $pk, $code, $message, $now)',\r\n params: { $t: table.tid, $pk: key, $code: REVOKED_REJECTION_CODE, $message: 'The row is no longer visible to this device; its pending change was not uploaded.', $now: now },\r\n });\r\n }\r\n if (report) report.revokedRetained++;\r\n return { removed: false, statements };\r\n }\r\n case G9ERevocationDisposition.Quarantine:\r\n statements.push({\r\n script: 'INSERT OR REPLACE INTO g9_quarantine (tid, pk, reason, rule, row_json, had_pending, dirty_mask, at_utc) VALUES ($t, $pk, $r, $rule, $json, $p, $m, $now)',\r\n params: { $t: table.tid, $pk: key, $r: reason, $rule: rule ? rule.name : null, $json: serializeValues(values), $p: state.dirty !== 0 ? 1 : 0, $m: state.dirtyMask, $now: now },\r\n });\r\n statements.push(...removeLocalRowStatements(table, key, seq, seqParams));\r\n if (report) report.revokedQuarantined++;\r\n return { removed: true, statements };\r\n default:\r\n statements.push(...removeLocalRowStatements(table, key, seq, seqParams));\r\n if (report) report.revokedDeleted++;\r\n return { removed: true, statements };\r\n }\r\n}\r\n\r\n/**\r\n * Applies the revocation policy to a released row (`DisposeReleasedRow`). Rows still held by another subscription are\r\n * untouched. Returns true when the row left the app's table (deleted or quarantined). Reads the row first, so it sees\r\n * whatever the caller ran before it; a release of many rows goes through disposeReleasedRows.\r\n */\r\nexport async function disposeReleasedRow(\r\n store: StoreInternals,\r\n connection: G9SqliteConnection,\r\n table: LocalTable,\r\n key: string,\r\n reason: G9ERevocationReason,\r\n subscriptionKey: string | null,\r\n report: G9ApplyReport | null,\r\n): Promise<boolean> {\r\n const state = emptyState();\r\n const first = (await connection.query('SELECT subs, dirty, dirty_mask, rejected FROM g9_rows WHERE tid = $t AND pk = $pk AND deleted = 0', { $t: table.tid, $pk: key }))[0];\r\n if (first) {\r\n state.held = !asLong(first[0]).isZero();\r\n state.dirty = asNumber(first[1]);\r\n state.dirtyMask = first[2] as G9SqlValue;\r\n state.rejected = asNumber(first[3]);\r\n }\r\n if (state.held) return false;\r\n if (state.dirty === 0) {\r\n const commands = await connection.scalar(\r\n 'SELECT count(*) FROM g9_command_rows r JOIN g9_commands c ON c.command_id = r.command_id WHERE c.state = 0 AND r.tid = $t AND r.pk = $pk',\r\n { $t: table.tid, $pk: key },\r\n );\r\n state.pendingCommand = asNumber(commands) > 0;\r\n if (state.pendingCommand) return false;\r\n }\r\n state.values = await readLocalValues(connection, table, key);\r\n const plan = planDisposal(store, table, key, state, reason, subscriptionKey, report, NEXT_SEQ, {});\r\n for (const statement of plan.statements) await connection.exec(statement.script, statement.params);\r\n return plan.removed;\r\n}\r\n\r\n/**\r\n * `DisposeReleasedRow` for every row `releasedSql` selects (`SELECT tid, pk …`, in the order the .NET store walks them),\r\n * then the clock moves once per row of a known table — the database state the row-by-row path leaves, in a handful of\r\n * driver calls instead of ~6 per row (on Lynx every call crosses the bridge: 25,000 rows took 850 s row by row,\r\n * LES-0051). Everything is read before anything is written, which is exact because disposing a row writes nothing\r\n * another released row's decision reads: the store's connections run with foreign keys OFF, and the CALLER must take the\r\n * row-by-row path when the database holds a foreign trigger. Returns how many rows left the app's tables.\r\n */\r\nexport async function disposeReleasedRows(\r\n store: StoreInternals,\r\n connection: G9SqliteConnection,\r\n releasedSql: string,\r\n releasedParams: G9Params,\r\n reason: G9ERevocationReason,\r\n subscriptionKey: string | null,\r\n report: G9ApplyReport | null,\r\n onRemoved?: (tid: number, key: string) => void,\r\n): Promise<number> {\r\n const released = (await connection.query(releasedSql, releasedParams)).map((r) => ({ tid: asNumber(r[0]), key: asString(r[1]) }));\r\n if (released.length === 0) return 0;\r\n const id = (tid: number, key: string): string => tid + '\\u001f' + key;\r\n\r\n const states = new Map<string, ReleasedRowState>();\r\n const stateRows = await connection.query(\r\n 'SELECT r.tid, r.pk, r.subs, r.dirty, r.dirty_mask, r.rejected, ' +\r\n 'EXISTS (SELECT 1 FROM g9_command_rows cr JOIN g9_commands c ON c.command_id = cr.command_id WHERE c.state = 0 AND cr.tid = r.tid AND cr.pk = r.pk) ' +\r\n `FROM (${releasedSql}) g JOIN g9_rows r ON r.tid = g.tid AND r.pk = g.pk WHERE r.deleted = 0`,\r\n releasedParams,\r\n );\r\n for (const r of stateRows) {\r\n states.set(id(asNumber(r[0]), asString(r[1])), {\r\n held: !asLong(r[2]).isZero(),\r\n dirty: asNumber(r[3]),\r\n dirtyMask: r[4] as G9SqlValue,\r\n rejected: asNumber(r[5]),\r\n pendingCommand: asNumber(r[6]) !== 0,\r\n values: {},\r\n });\r\n }\r\n\r\n // The app rows, one query per table: `SELECT *` of exactly the rows the per-row path reads by key.\r\n for (const tid of new Set(released.map((r) => r.tid))) {\r\n const table = byTid(store, tid);\r\n if (!table) continue;\r\n const integerKey = table.model.keyType === G9ESyncColumnType.Int32 || table.model.keyType === G9ESyncColumnType.Int64;\r\n const sql = `SELECT g.pk, t.* FROM (${releasedSql}) g JOIN ${table.quoted} t ON t.${table.keyQuoted} = ${integerKey ? 'CAST(g.pk AS INTEGER)' : 'g.pk'} WHERE g.tid = ${tid}`;\r\n const result = (await connection.runStatements(statementsOf(sql, releasedParams)))[0];\r\n if (!result) continue;\r\n const columns = result.columns.slice(1);\r\n for (const row of result.rows) {\r\n const rowId = id(tid, asString(row[0] as G9SqlValue));\r\n const state = states.get(rowId) ?? emptyState();\r\n states.set(rowId, state);\r\n columns.forEach((name, i) => (state.values[name] = row[i + 1] as G9SqlValue));\r\n }\r\n }\r\n\r\n const batch = new G9StatementBatch(connection, store.options.statementsPerBatch);\r\n const base = asLong(await connection.scalar('SELECT seq FROM g9_clock WHERE id = 1'));\r\n let advanced = 0;\r\n let removed = 0;\r\n for (const row of released) {\r\n const table = byTid(store, row.tid);\r\n // The .NET store advances its sequence for every released row of a known table, whether or not it moved.\r\n if (!table) continue;\r\n const state = states.get(id(row.tid, row.key)) ?? emptyState();\r\n const plan = planDisposal(store, table, row.key, state, reason, subscriptionKey, report, '$seq', { $seq: base.add(G9Long.fromNumber(++advanced)) });\r\n if (plan.removed) {\r\n removed++;\r\n onRemoved?.(row.tid, row.key);\r\n }\r\n for (const statement of plan.statements) if (batch.add(statement.script, statement.params)) await batch.flush();\r\n }\r\n await batch.flush();\r\n if (advanced > 0) await connection.exec('UPDATE g9_clock SET seq = seq + $n WHERE id = 1', { $n: advanced });\r\n return removed;\r\n}\r\n\r\nfunction removeLocalRowStatements(table: LocalTable, key: string, seq: string, seqParams: G9Params): Statement[] {\r\n return [\r\n { script: `DELETE FROM ${table.quoted} WHERE ${table.keyQuoted} = $k`, params: { $k: keyValue(table, key) } },\r\n {\r\n script:\r\n 'UPDATE g9_rows SET deleted = 1, dirty = 0, dirty_mask = 0, rejected = 0, local_seq = ' +\r\n seq +\r\n ' WHERE tid = $t AND pk = $pk; ' +\r\n 'DELETE FROM g9_rejections WHERE tid = $t AND pk = $pk; DELETE FROM g9_revoked WHERE tid = $t AND pk = $pk',\r\n params: { ...seqParams, $t: table.tid, $pk: key },\r\n },\r\n ];\r\n}\r\n\r\n/**\r\n * `RevertRejectedAsync` (LES-0070): gives up the local change of rejected rows and takes the server's copy. A row the server never had\r\n * (`server_ver = 0`) is removed locally; any other drops its pending change and its version, so the next forced reconciliation\r\n * fetches the server's copy (the digest hashes key + server_ver, not the values). A library write: capture is silent, nothing uploads.\r\n */\r\nexport async function revertRejected(store: StoreInternals, localTable: string | null, key: string | null): Promise<number> {\r\n store.ensureInitialized();\r\n let where = 'rejected = 1';\r\n const params: G9Params = {};\r\n if (localTable !== null) {\r\n where += ' AND tid = $t';\r\n params.$t = getLocal(store, localTable).tid;\r\n }\r\n if (key !== null) {\r\n where += ' AND pk = $pk';\r\n params.$pk = key;\r\n }\r\n return store.writeLock.run(() =>\r\n store.writer().transaction('immediate', async () => {\r\n const connection = store.writer();\r\n const rows = await connection.query('SELECT tid, pk, server_ver FROM g9_rows WHERE ' + where, params);\r\n if (rows.length === 0) return 0;\r\n await connection.exec('UPDATE g9_ctx SET applying = 1 WHERE id = 1');\r\n for (const r of rows) {\r\n const tid = asNumber(r[0]);\r\n const pk = asString(r[1]);\r\n const table = byTid(store, tid);\r\n if (!table) continue;\r\n if (asNumber(r[2]) === 0) {\r\n for (const statement of removeLocalRowStatements(table, pk, NEXT_SEQ, {})) await connection.exec(statement.script, statement.params);\r\n await connection.exec('UPDATE g9_clock SET seq = seq + 1 WHERE id = 1');\r\n continue;\r\n }\r\n await connection.exec(\r\n 'DELETE FROM g9_rejections WHERE tid = $t AND pk = $pk; UPDATE g9_rows SET dirty = 0, dirty_mask = 0, rejected = 0, server_ver = 0 WHERE tid = $t AND pk = $pk',\r\n { $t: tid, $pk: pk },\r\n );\r\n }\r\n await connection.exec('UPDATE g9_ctx SET applying = 0 WHERE id = 1');\r\n return rows.length;\r\n }),\r\n );\r\n}\r\n\r\n/** `RemoveLocalRow`: the row leaves the app's table; its metadata becomes a tombstone at the clock's next value. */\r\nexport async function removeLocalRow(connection: G9SqliteConnection, table: LocalTable, key: string): Promise<void> {\r\n for (const statement of removeLocalRowStatements(table, key, NEXT_SEQ, {})) await connection.exec(statement.script, statement.params);\r\n}\r\n\r\n// ================================================================ holding area and retained rows\r\n\r\nexport async function getQuarantined(store: StoreInternals): Promise<G9QuarantinedRow[]> {\r\n store.ensureInitialized();\r\n const rows = await store\r\n .reader()\r\n .query('SELECT t.local_name, q.pk, q.reason, q.rule, q.had_pending, q.row_json, q.at_utc FROM g9_quarantine q JOIN g9_tables t ON t.tid = q.tid ORDER BY q.at_utc');\r\n return rows.map((r) => ({\r\n localTable: asString(r[0]),\r\n key: asString(r[1]),\r\n reason: asNumber(r[2]) as G9ERevocationReason,\r\n rule: asOptionalString(r[3]),\r\n hadPendingChanges: asNumber(r[4]) !== 0,\r\n values: deserializeValues(asString(r[5])),\r\n atUtcMs: asNumber(r[6]),\r\n }));\r\n}\r\n\r\n/** Puts a quarantined row back as a pending local change (capture is ON: the restored values upload on the next push). */\r\nexport async function restoreQuarantined(store: StoreInternals, localTable: string, key: string): Promise<number> {\r\n store.ensureInitialized();\r\n const table = getLocal(store, localTable);\r\n return store.writeLock.run(() =>\r\n store.writer().transaction('immediate', async () => {\r\n const connection = store.writer();\r\n const rows = await connection.query('SELECT row_json, dirty_mask, had_pending FROM g9_quarantine WHERE tid = $t AND pk = $pk', { $t: table.tid, $pk: key });\r\n const first = rows[0];\r\n if (!first) return 0;\r\n const values = deserializeValues(asString(first[0]));\r\n const mask = asNumber(first[2]) !== 0 ? asLong(first[1]) : null;\r\n const exists = Object.keys(await readLocalValues(connection, table, key)).length > 0;\r\n const lookup = (name: string): string | undefined => Object.keys(values).find((c) => c.toLowerCase() === name.toLowerCase());\r\n if (exists) {\r\n // Only the columns the user had changed are written back, so newer server values of the others survive.\r\n const columns: string[] = [];\r\n table.model.columns.forEach((c, i) => {\r\n const actual = lookup(c.name);\r\n if (actual !== undefined && (mask === null || mask.isZero() || mask.testBit(i))) columns.push(actual);\r\n });\r\n if (columns.length > 0) {\r\n const params: { [name: string]: G9SqlValue } = { $k: keyValue(table, key) };\r\n columns.forEach((c, i) => (params['$v' + i] = values[c] as G9SqlValue));\r\n await connection.exec(`UPDATE ${table.quoted} SET ${columns.map((c, i) => quote(c) + ' = $v' + i).join(', ')} WHERE ${table.keyQuoted} = $k`, params);\r\n }\r\n } else {\r\n const columns = Object.keys(values);\r\n const params: { [name: string]: G9SqlValue } = {};\r\n columns.forEach((c, i) => (params['$v' + i] = values[c] as G9SqlValue));\r\n await connection.exec(`INSERT INTO ${table.quoted} (${columns.map(quote).join(', ')}) VALUES (${columns.map((_, i) => '$v' + i).join(', ')})`, params);\r\n }\r\n await connection.exec('DELETE FROM g9_quarantine WHERE tid = $t AND pk = $pk', { $t: table.tid, $pk: key });\r\n return 1;\r\n }),\r\n );\r\n}\r\n\r\nexport async function discardQuarantined(store: StoreInternals, localTable: string | null, key: string | null): Promise<number> {\r\n store.ensureInitialized();\r\n const tid = localTable === null ? null : getLocal(store, localTable).tid;\r\n return store.writeLock.run(() =>\r\n store.writer().exec('DELETE FROM g9_quarantine WHERE ($t IS NULL OR tid = $t) AND ($pk IS NULL OR pk = $pk)', { $t: tid, $pk: key }),\r\n );\r\n}\r\n\r\nexport async function getRetained(store: StoreInternals): Promise<G9RetainedRow[]> {\r\n store.ensureInitialized();\r\n const rows = await store.reader().query('SELECT t.local_name, r.pk, r.disposition, r.reason, r.rule, r.at_utc FROM g9_revoked r JOIN g9_tables t ON t.tid = r.tid ORDER BY r.at_utc');\r\n return rows.map((r) => ({\r\n localTable: asString(r[0]),\r\n key: asString(r[1]),\r\n disposition: asNumber(r[2]) as G9ERevocationDisposition,\r\n reason: asNumber(r[3]) as G9ERevocationReason,\r\n rule: asOptionalString(r[4]),\r\n atUtcMs: asNumber(r[5]),\r\n }));\r\n}\r\n\r\n/** Re-checks rows retained by a RetainWhile rule; deletes those no longer retained (`ReevaluateRetainedAsync`). */\r\nexport async function reevaluateRetained(store: StoreInternals): Promise<number> {\r\n store.ensureInitialized();\r\n return store.writeLock.run(() =>\r\n store.writer().transaction('immediate', async () => {\r\n const connection = store.writer();\r\n const retained = (await connection.query('SELECT tid, pk, reason, rule, disposition FROM g9_revoked')).map((r) => ({\r\n tid: asNumber(r[0]),\r\n key: asString(r[1]),\r\n reason: asNumber(r[2]),\r\n rule: asOptionalString(r[3]),\r\n disposition: asNumber(r[4]),\r\n }));\r\n if (retained.length === 0) return 0;\r\n await connection.exec('UPDATE g9_ctx SET applying = 1 WHERE id = 1');\r\n let deleted = 0;\r\n for (const entry of retained) {\r\n const table = byTid(store, entry.tid);\r\n if (!table) continue;\r\n const subs = asLong(\r\n await connection.scalar('SELECT coalesce(max(subs), 0) FROM g9_rows WHERE tid = $t AND pk = $pk AND deleted = 0', { $t: entry.tid, $pk: entry.key }),\r\n );\r\n if (!subs.isZero()) {\r\n // Visible again: no longer revoked, and a pending change parked by the revocation may upload again.\r\n await connection.exec(\r\n 'DELETE FROM g9_revoked WHERE tid = $t AND pk = $pk; DELETE FROM g9_rejections WHERE tid = $t AND pk = $pk AND code = $code; ' +\r\n 'UPDATE g9_rows SET rejected = 0 WHERE tid = $t AND pk = $pk AND NOT EXISTS (SELECT 1 FROM g9_rejections WHERE tid = $t AND pk = $pk)',\r\n { $t: entry.tid, $pk: entry.key, $code: REVOKED_REJECTION_CODE },\r\n );\r\n continue;\r\n }\r\n if (entry.disposition !== G9ERevocationDisposition.Retain) continue;\r\n const values = await readLocalValues(connection, table, entry.key);\r\n const rule = entry.rule === null ? null : store.options.revocation.find(entry.rule);\r\n const row: G9RevokedRow = {\r\n localTable: table.model.localName,\r\n key: entry.key,\r\n reason: entry.reason as G9ERevocationReason,\r\n subscriptionKey: null,\r\n hasPendingChanges: false,\r\n isRejected: false,\r\n values,\r\n };\r\n if (rule && rule.retainWhile && Object.keys(values).length > 0 && rule.retainWhile(row)) continue;\r\n await removeLocalRow(connection, table, entry.key);\r\n await connection.exec('UPDATE g9_clock SET seq = seq + 1 WHERE id = 1');\r\n deleted++;\r\n }\r\n await connection.exec('UPDATE g9_ctx SET applying = 0 WHERE id = 1');\r\n return deleted;\r\n }),\r\n );\r\n}\r\n"]}
1
+ {"version":3,"file":"revocation.js","sourceRoot":"","sources":["../../src/sqlite/revocation.ts"],"names":[],"mappings":"AAAA,yHAAyH;AACzH,yHAAyH;AACzH,6GAA6G;AAC7G,EAAE;AACF,qHAAqH;AACrH,0EAA0E;AAC1E,OAAO,EAAE,iBAAiB,EAAE,MAAM,0BAA0B,CAAC;AAC7D,OAAO,EAAE,MAAM,EAAE,MAAM,yBAAyB,CAAC;AACjD,OAAO,EACL,aAAa,EACb,wBAAwB,EACxB,mBAAmB,EACnB,oBAAoB,GAKrB,MAAM,yBAAyB,CAAC;AACjC,OAAO,EAAE,MAAM,EAAE,QAAQ,EAAE,gBAAgB,EAAE,QAAQ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AU,CAAC,IAAI,CAAC,gDAAgD,CAAC,CAAC;YACxE,OAAO,EAAE,CAAC;QACZ,CAAC;QACD,MAAM,UAAU,CAAC,IAAI,CAAC,6CAA6C,CAAC,CAAC;QACrE,OAAO,OAAO,CAAC;IACjB,CAAC,CAAC,CACH,CAAC;AACJ,CAAC","sourcesContent":["// Twin of G9SyncData.Client.Sqlite/G9CSqliteSyncStore.Revocation.cs: revocation dispositions (ADR-0026). Every path that\n// releases a row — a move-out in a pull or a reconciliation, an unsubscribe, an expired ephemeral subscription — ends in\n// disposeReleasedRow, which asks the revocation policy what to do with a row NO subscription holds any more.\n//\n// The local sequence such a row gets is the clock's next value, (SELECT seq FROM g9_clock) + 1; the CALLER moves the\n// clock afterwards (unconditionally, like the .NET store's `++sequence`).\nimport { G9ESyncColumnType } from '../abstractions/enums.js';\nimport { G9Long } from '../abstractions/long.js';\nimport {\n G9ApplyReport,\n G9ERevocationDisposition,\n G9ERevocationReason,\n G9ESubscriptionState,\n type G9QuarantinedRow,\n type G9RetainedRow,\n type G9RevokedRow,\n type G9RevokedRowEditor,\n} from '../client/storeTypes.js';\nimport { asLong, asNumber, asOptionalString, asString, G9StatementBatch, statementsOf, type G9Params, type G9SqliteConnection } from './connection.js';\nimport type { G9SqlValue } from './driver.js';\nimport { byTid, deserializeValues, getLocal, keyValue, nowMs, readLocalValues, serializeValues, type LocalTable, type StoreInternals } from './internals.js';\nimport { quote } from './sql.js';\n\nexport const REVOKED_REJECTION_CODE = 'G9S-REJ-REVOKED';\nconst NEXT_SEQ = '(SELECT seq FROM g9_clock WHERE id = 1) + 1';\n\nclass RowEditor implements G9RevokedRowEditor {\n readonly changed = new Map<string, string>();\n private readonly _values: { [column: string]: G9SqlValue };\n\n constructor(values: { [column: string]: G9SqlValue }) {\n this._values = values;\n }\n\n set(column: string, value: unknown): void {\n if (typeof column !== 'string' || column.trim() === '') throw new TypeError('A column is required.');\n const actual = Object.keys(this._values).find((c) => c.toLowerCase() === column.toLowerCase());\n if (actual === undefined) throw new RangeError(`'${column}' is not a column of the row.`);\n this._values[actual] = value as G9SqlValue;\n this.changed.set(actual.toLowerCase(), actual);\n }\n}\n\n/** What disposing a released row reads about it before anything is written. */\ninterface ReleasedRowState {\n /** Another subscription still holds the row. */\n held: boolean;\n dirty: number;\n dirtyMask: G9SqlValue;\n rejected: number;\n /** A pending command touches the row (only looked at when the row has no pending change). */\n pendingCommand: boolean;\n /** The app row; empty when it is gone. */\n values: { [column: string]: G9SqlValue };\n}\n\n/** A row with no metadata row: what the per-row path assumes when its first read finds nothing. */\nfunction emptyState(): ReleasedRowState {\n return { held: false, dirty: 0, dirtyMask: 0, rejected: 0, pendingCommand: false, values: {} };\n}\n\ninterface Statement {\n script: string;\n params: G9Params;\n}\n\n/**\n * The revocation decision for one released row, as the statements that carry it out, in the order the .NET store runs\n * them. `seq` is the SQL of the local sequence the row gets when it moves: NEXT_SEQ, or `$seq` with its value in `seqParams`.\n */\nfunction planDisposal(\n store: StoreInternals,\n table: LocalTable,\n key: string,\n state: ReleasedRowState,\n reason: G9ERevocationReason,\n subscriptionKey: string | null,\n report: G9ApplyReport | null,\n seq: string,\n seqParams: G9Params,\n): { removed: boolean; statements: Statement[] } {\n if (state.held) return { removed: false, statements: [] };\n // A row touched by a pending command is settled by that command's result, never disposed underneath it.\n if (state.dirty === 0 && state.pendingCommand) return { removed: false, statements: [] };\n\n const values = state.values;\n if (Object.keys(values).length === 0) {\n const script = 'UPDATE g9_rows SET deleted = 1, dirty = 0, dirty_mask = 0, rejected = 0, local_seq = ' + seq + ' WHERE tid = $t AND pk = $pk';\n return { removed: false, statements: [{ script, params: { ...seqParams, $t: table.tid, $pk: key } }] };\n }\n\n const editor = new RowEditor(values);\n const row: G9RevokedRow = {\n localTable: table.model.localName,\n key,\n reason,\n subscriptionKey,\n hasPendingChanges: state.dirty !== 0,\n isRejected: state.rejected !== 0,\n values,\n };\n const { rule, disposition } = store.options.revocation.decide(row, editor);\n const now = nowMs();\n const statements: Statement[] = [];\n\n switch (disposition) {\n case G9ERevocationDisposition.MarkRevoked:\n case G9ERevocationDisposition.Retain: {\n if (editor.changed.size > 0) {\n const columns = Array.from(editor.changed.values());\n const params: G9Params = { $k: keyValue(table, key) };\n columns.forEach((c, i) => (params['$v' + i] = values[c] as G9SqlValue));\n statements.push({ script: `UPDATE ${table.quoted} SET ${columns.map((c, i) => quote(c) + ' = $v' + i).join(', ')} WHERE ${table.keyQuoted} = $k`, params });\n }\n statements.push({\n script: 'INSERT OR REPLACE INTO g9_revoked (tid, pk, disposition, reason, rule, at_utc) VALUES ($t, $pk, $d, $r, $rule, $now)',\n params: { $t: table.tid, $pk: key, $d: disposition, $r: reason, $rule: rule ? rule.name : null, $now: now },\n });\n if (state.dirty !== 0) {\n // Its pending change can no longer be accepted: park it as rejected instead of uploading it on every push.\n statements.push({\n script:\n 'UPDATE g9_rows SET rejected = 1 WHERE tid = $t AND pk = $pk; ' +\n 'INSERT OR REPLACE INTO g9_rejections (tid, pk, code, message, at_utc) VALUES ($t, $pk, $code, $message, $now)',\n params: { $t: table.tid, $pk: key, $code: REVOKED_REJECTION_CODE, $message: 'The row is no longer visible to this device; its pending change was not uploaded.', $now: now },\n });\n }\n if (report) report.revokedRetained++;\n return { removed: false, statements };\n }\n case G9ERevocationDisposition.Quarantine:\n statements.push({\n script: 'INSERT OR REPLACE INTO g9_quarantine (tid, pk, reason, rule, row_json, had_pending, dirty_mask, at_utc) VALUES ($t, $pk, $r, $rule, $json, $p, $m, $now)',\n params: { $t: table.tid, $pk: key, $r: reason, $rule: rule ? rule.name : null, $json: serializeValues(values), $p: state.dirty !== 0 ? 1 : 0, $m: state.dirtyMask, $now: now },\n });\n statements.push(...removeLocalRowStatements(table, key, seq, seqParams));\n if (report) report.revokedQuarantined++;\n return { removed: true, statements };\n default:\n statements.push(...removeLocalRowStatements(table, key, seq, seqParams));\n if (report) report.revokedDeleted++;\n return { removed: true, statements };\n }\n}\n\n/**\n * Applies the revocation policy to a released row (`DisposeReleasedRow`). Rows still held by another subscription are\n * untouched. Returns true when the row left the app's table (deleted or quarantined). Reads the row first, so it sees\n * whatever the caller ran before it; a release of many rows goes through disposeReleasedRows.\n */\nexport async function disposeReleasedRow(\n store: StoreInternals,\n connection: G9SqliteConnection,\n table: LocalTable,\n key: string,\n reason: G9ERevocationReason,\n subscriptionKey: string | null,\n report: G9ApplyReport | null,\n): Promise<boolean> {\n const state = emptyState();\n const first = (await connection.query('SELECT subs, dirty, dirty_mask, rejected FROM g9_rows WHERE tid = $t AND pk = $pk AND deleted = 0', { $t: table.tid, $pk: key }))[0];\n if (first) {\n state.held = !asLong(first[0]).isZero();\n state.dirty = asNumber(first[1]);\n state.dirtyMask = first[2] as G9SqlValue;\n state.rejected = asNumber(first[3]);\n }\n if (state.held) return false;\n if (state.dirty === 0) {\n const commands = await connection.scalar(\n 'SELECT count(*) FROM g9_command_rows r JOIN g9_commands c ON c.command_id = r.command_id WHERE c.state = 0 AND r.tid = $t AND r.pk = $pk',\n { $t: table.tid, $pk: key },\n );\n state.pendingCommand = asNumber(commands) > 0;\n if (state.pendingCommand) return false;\n }\n state.values = await readLocalValues(connection, table, key);\n const plan = planDisposal(store, table, key, state, reason, subscriptionKey, report, NEXT_SEQ, {});\n for (const statement of plan.statements) await connection.exec(statement.script, statement.params);\n return plan.removed;\n}\n\n/**\n * `DisposeReleasedRow` for every row `releasedSql` selects (`SELECT tid, pk …`, in the order the .NET store walks them),\n * then the clock moves once per row of a known table — the database state the row-by-row path leaves, in a handful of\n * driver calls instead of ~6 per row (on Lynx every call crosses the bridge: 25,000 rows took 850 s row by row,\n * LES-0051). Everything is read before anything is written, which is exact because disposing a row writes nothing\n * another released row's decision reads: the store's connections run with foreign keys OFF, and the CALLER must take the\n * row-by-row path when the database holds a foreign trigger. Returns how many rows left the app's tables.\n */\nexport async function disposeReleasedRows(\n store: StoreInternals,\n connection: G9SqliteConnection,\n releasedSql: string,\n releasedParams: G9Params,\n reason: G9ERevocationReason,\n subscriptionKey: string | null,\n report: G9ApplyReport | null,\n onRemoved?: (tid: number, key: string) => void,\n): Promise<number> {\n const released = (await connection.query(releasedSql, releasedParams)).map((r) => ({ tid: asNumber(r[0]), key: asString(r[1]) }));\n if (released.length === 0) return 0;\n const id = (tid: number, key: string): string => tid + '\\u001f' + key;\n\n const states = new Map<string, ReleasedRowState>();\n const stateRows = await connection.query(\n 'SELECT r.tid, r.pk, r.subs, r.dirty, r.dirty_mask, r.rejected, ' +\n 'EXISTS (SELECT 1 FROM g9_command_rows cr JOIN g9_commands c ON c.command_id = cr.command_id WHERE c.state = 0 AND cr.tid = r.tid AND cr.pk = r.pk) ' +\n `FROM (${releasedSql}) g JOIN g9_rows r ON r.tid = g.tid AND r.pk = g.pk WHERE r.deleted = 0`,\n releasedParams,\n );\n for (const r of stateRows) {\n states.set(id(asNumber(r[0]), asString(r[1])), {\n held: !asLong(r[2]).isZero(),\n dirty: asNumber(r[3]),\n dirtyMask: r[4] as G9SqlValue,\n rejected: asNumber(r[5]),\n pendingCommand: asNumber(r[6]) !== 0,\n values: {},\n });\n }\n\n // The app rows, one query per table: `SELECT *` of exactly the rows the per-row path reads by key.\n for (const tid of new Set(released.map((r) => r.tid))) {\n const table = byTid(store, tid);\n if (!table) continue;\n const integerKey = table.model.keyType === G9ESyncColumnType.Int32 || table.model.keyType === G9ESyncColumnType.Int64;\n const sql = `SELECT g.pk, t.* FROM (${releasedSql}) g JOIN ${table.quoted} t ON t.${table.keyQuoted} = ${integerKey ? 'CAST(g.pk AS INTEGER)' : 'g.pk'} WHERE g.tid = ${tid}`;\n const result = (await connection.runStatements(statementsOf(sql, releasedParams)))[0];\n if (!result) continue;\n const columns = result.columns.slice(1);\n for (const row of result.rows) {\n const rowId = id(tid, asString(row[0] as G9SqlValue));\n const state = states.get(rowId) ?? emptyState();\n states.set(rowId, state);\n columns.forEach((name, i) => (state.values[name] = row[i + 1] as G9SqlValue));\n }\n }\n\n const batch = new G9StatementBatch(connection, store.options.statementsPerBatch);\n const base = asLong(await connection.scalar('SELECT seq FROM g9_clock WHERE id = 1'));\n let advanced = 0;\n let removed = 0;\n for (const row of released) {\n const table = byTid(store, 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 const state = states.get(id(row.tid, row.key)) ?? emptyState();\n const plan = planDisposal(store, table, row.key, state, reason, subscriptionKey, report, '$seq', { $seq: base.add(G9Long.fromNumber(++advanced)) });\n if (plan.removed) {\n removed++;\n onRemoved?.(row.tid, row.key);\n }\n for (const statement of plan.statements) if (batch.add(statement.script, statement.params)) await batch.flush();\n }\n await batch.flush();\n if (advanced > 0) await connection.exec('UPDATE g9_clock SET seq = seq + $n WHERE id = 1', { $n: advanced });\n return removed;\n}\n\nfunction removeLocalRowStatements(table: LocalTable, key: string, seq: string, seqParams: G9Params): Statement[] {\n return [\n { script: `DELETE FROM ${table.quoted} WHERE ${table.keyQuoted} = $k`, params: { $k: keyValue(table, key) } },\n {\n script:\n 'UPDATE g9_rows SET deleted = 1, dirty = 0, dirty_mask = 0, rejected = 0, local_seq = ' +\n seq +\n ' WHERE tid = $t AND pk = $pk; ' +\n 'DELETE FROM g9_rejections WHERE tid = $t AND pk = $pk; DELETE FROM g9_revoked WHERE tid = $t AND pk = $pk',\n params: { ...seqParams, $t: table.tid, $pk: key },\n },\n ];\n}\n\n/**\n * `RevertRejectedAsync` (LES-0070): gives up the local change of rejected rows and takes the server's copy. A row the server never had\n * (`server_ver = 0` and held by no subscription) is removed locally. Any other drops its pending change and gets `server_ver = -1`: the\n * digest hashes key + server_ver, not the values, and a server reports version 0 for every row unchanged since its tracking began, so\n * \"forget the version\" (0) would leave the hash equal and the local values in place for good. -1 is a version no server issues: the\n * reconcile fetches the row and the apply writes the server's values and real version. The subscriptions holding the row become\n * NeedsReconcile, so their next sync of any kind does it (offline now is fine). A library write: capture is silent, nothing uploads.\n */\nexport async function revertRejected(store: StoreInternals, localTable: string | null, key: string | null): Promise<number> {\n store.ensureInitialized();\n let where = 'rejected = 1';\n const params: G9Params = {};\n if (localTable !== null) {\n where += ' AND tid = $t';\n params.$t = getLocal(store, localTable).tid;\n }\n if (key !== null) {\n where += ' AND pk = $pk';\n params.$pk = key;\n }\n return store.writeLock.run(() =>\n store.writer().transaction('immediate', async () => {\n const connection = store.writer();\n const rows = await connection.query('SELECT tid, pk, (server_ver = 0 AND subs = 0) FROM g9_rows WHERE ' + where, params);\n if (rows.length === 0) return 0;\n await connection.exec('UPDATE g9_ctx SET applying = 1 WHERE id = 1');\n for (const r of rows) {\n const tid = asNumber(r[0]);\n const pk = asString(r[1]);\n const table = byTid(store, tid);\n if (!table) continue;\n if (asNumber(r[2]) === 1) {\n for (const statement of removeLocalRowStatements(table, pk, NEXT_SEQ, {})) await connection.exec(statement.script, statement.params);\n await connection.exec('UPDATE g9_clock SET seq = seq + 1 WHERE id = 1');\n continue;\n }\n await connection.exec(\n 'DELETE FROM g9_rejections WHERE tid = $t AND pk = $pk; ' +\n 'UPDATE g9_subscriptions SET state = $needs WHERE (((SELECT subs FROM g9_rows WHERE tid = $t AND pk = $pk) >> slot) & 1) = 1; ' +\n 'UPDATE g9_rows SET dirty = 0, dirty_mask = 0, rejected = 0, server_ver = -1 WHERE tid = $t AND pk = $pk',\n { $t: tid, $pk: pk, $needs: G9ESubscriptionState.NeedsReconcile },\n );\n }\n await connection.exec('UPDATE g9_ctx SET applying = 0 WHERE id = 1');\n return rows.length;\n }),\n );\n}\n\n/** `RemoveLocalRow`: the row leaves the app's table; its metadata becomes a tombstone at the clock's next value. */\nexport async function removeLocalRow(connection: G9SqliteConnection, table: LocalTable, key: string): Promise<void> {\n for (const statement of removeLocalRowStatements(table, key, NEXT_SEQ, {})) await connection.exec(statement.script, statement.params);\n}\n\n// ================================================================ holding area and retained rows\n\nexport async function getQuarantined(store: StoreInternals): Promise<G9QuarantinedRow[]> {\n store.ensureInitialized();\n const rows = await store\n .reader()\n .query('SELECT t.local_name, q.pk, q.reason, q.rule, q.had_pending, q.row_json, q.at_utc FROM g9_quarantine q JOIN g9_tables t ON t.tid = q.tid ORDER BY q.at_utc');\n return rows.map((r) => ({\n localTable: asString(r[0]),\n key: asString(r[1]),\n reason: asNumber(r[2]) as G9ERevocationReason,\n rule: asOptionalString(r[3]),\n hadPendingChanges: asNumber(r[4]) !== 0,\n values: deserializeValues(asString(r[5])),\n atUtcMs: asNumber(r[6]),\n }));\n}\n\n/** Puts a quarantined row back as a pending local change (capture is ON: the restored values upload on the next push). */\nexport async function restoreQuarantined(store: StoreInternals, localTable: string, key: string): Promise<number> {\n store.ensureInitialized();\n const table = getLocal(store, localTable);\n return store.writeLock.run(() =>\n store.writer().transaction('immediate', async () => {\n const connection = store.writer();\n const rows = await connection.query('SELECT row_json, dirty_mask, had_pending FROM g9_quarantine WHERE tid = $t AND pk = $pk', { $t: table.tid, $pk: key });\n const first = rows[0];\n if (!first) return 0;\n const values = deserializeValues(asString(first[0]));\n const mask = asNumber(first[2]) !== 0 ? asLong(first[1]) : null;\n const exists = Object.keys(await readLocalValues(connection, table, key)).length > 0;\n const lookup = (name: string): string | undefined => Object.keys(values).find((c) => c.toLowerCase() === name.toLowerCase());\n if (exists) {\n // Only the columns the user had changed are written back, so newer server values of the others survive.\n const columns: string[] = [];\n table.model.columns.forEach((c, i) => {\n const actual = lookup(c.name);\n if (actual !== undefined && (mask === null || mask.isZero() || mask.testBit(i))) columns.push(actual);\n });\n if (columns.length > 0) {\n const params: { [name: string]: G9SqlValue } = { $k: keyValue(table, key) };\n columns.forEach((c, i) => (params['$v' + i] = values[c] as G9SqlValue));\n await connection.exec(`UPDATE ${table.quoted} SET ${columns.map((c, i) => quote(c) + ' = $v' + i).join(', ')} WHERE ${table.keyQuoted} = $k`, params);\n }\n } else {\n const columns = Object.keys(values);\n const params: { [name: string]: G9SqlValue } = {};\n columns.forEach((c, i) => (params['$v' + i] = values[c] as G9SqlValue));\n await connection.exec(`INSERT INTO ${table.quoted} (${columns.map(quote).join(', ')}) VALUES (${columns.map((_, i) => '$v' + i).join(', ')})`, params);\n }\n await connection.exec('DELETE FROM g9_quarantine WHERE tid = $t AND pk = $pk', { $t: table.tid, $pk: key });\n return 1;\n }),\n );\n}\n\nexport async function discardQuarantined(store: StoreInternals, localTable: string | null, key: string | null): Promise<number> {\n store.ensureInitialized();\n const tid = localTable === null ? null : getLocal(store, localTable).tid;\n return store.writeLock.run(() =>\n store.writer().exec('DELETE FROM g9_quarantine WHERE ($t IS NULL OR tid = $t) AND ($pk IS NULL OR pk = $pk)', { $t: tid, $pk: key }),\n );\n}\n\nexport async function getRetained(store: StoreInternals): Promise<G9RetainedRow[]> {\n store.ensureInitialized();\n const rows = await store.reader().query('SELECT t.local_name, r.pk, r.disposition, r.reason, r.rule, r.at_utc FROM g9_revoked r JOIN g9_tables t ON t.tid = r.tid ORDER BY r.at_utc');\n return rows.map((r) => ({\n localTable: asString(r[0]),\n key: asString(r[1]),\n disposition: asNumber(r[2]) as G9ERevocationDisposition,\n reason: asNumber(r[3]) as G9ERevocationReason,\n rule: asOptionalString(r[4]),\n atUtcMs: asNumber(r[5]),\n }));\n}\n\n/** Re-checks rows retained by a RetainWhile rule; deletes those no longer retained (`ReevaluateRetainedAsync`). */\nexport async function reevaluateRetained(store: StoreInternals): Promise<number> {\n store.ensureInitialized();\n return store.writeLock.run(() =>\n store.writer().transaction('immediate', async () => {\n const connection = store.writer();\n const retained = (await connection.query('SELECT tid, pk, reason, rule, disposition FROM g9_revoked')).map((r) => ({\n tid: asNumber(r[0]),\n key: asString(r[1]),\n reason: asNumber(r[2]),\n rule: asOptionalString(r[3]),\n disposition: asNumber(r[4]),\n }));\n if (retained.length === 0) return 0;\n await connection.exec('UPDATE g9_ctx SET applying = 1 WHERE id = 1');\n let deleted = 0;\n for (const entry of retained) {\n const table = byTid(store, entry.tid);\n if (!table) continue;\n const subs = asLong(\n await connection.scalar('SELECT coalesce(max(subs), 0) FROM g9_rows WHERE tid = $t AND pk = $pk AND deleted = 0', { $t: entry.tid, $pk: entry.key }),\n );\n if (!subs.isZero()) {\n // Visible again: no longer revoked, and a pending change parked by the revocation may upload again.\n await connection.exec(\n 'DELETE FROM g9_revoked WHERE tid = $t AND pk = $pk; DELETE FROM g9_rejections WHERE tid = $t AND pk = $pk AND code = $code; ' +\n 'UPDATE g9_rows SET rejected = 0 WHERE tid = $t AND pk = $pk AND NOT EXISTS (SELECT 1 FROM g9_rejections WHERE tid = $t AND pk = $pk)',\n { $t: entry.tid, $pk: entry.key, $code: REVOKED_REJECTION_CODE },\n );\n continue;\n }\n if (entry.disposition !== G9ERevocationDisposition.Retain) continue;\n const values = await readLocalValues(connection, table, entry.key);\n const rule = entry.rule === null ? null : store.options.revocation.find(entry.rule);\n const row: G9RevokedRow = {\n localTable: table.model.localName,\n key: entry.key,\n reason: entry.reason as G9ERevocationReason,\n subscriptionKey: null,\n hasPendingChanges: false,\n isRejected: false,\n values,\n };\n if (rule && rule.retainWhile && Object.keys(values).length > 0 && rule.retainWhile(row)) continue;\n await removeLocalRow(connection, table, entry.key);\n await connection.exec('UPDATE g9_clock SET seq = seq + 1 WHERE id = 1');\n deleted++;\n }\n await connection.exec('UPDATE g9_ctx SET applying = 0 WHERE id = 1');\n return deleted;\n }),\n );\n}\n"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@g9tm/syncdata",
3
- "version": "1.5.3",
3
+ "version": "1.5.5",
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)",