@g9tm/syncdata 1.2.2 → 1.3.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/PARITY.md +26 -2
- package/dist/abstractions/errors.d.ts +4 -0
- package/dist/abstractions/errors.js +4 -0
- package/dist/abstractions/errors.js.map +1 -1
- package/dist/client/engine.js +93 -51
- package/dist/client/engine.js.map +1 -1
- package/dist/client/runs.d.ts +5 -0
- package/dist/client/runs.js +8 -7
- package/dist/client/runs.js.map +1 -1
- package/dist/client/storeTypes.d.ts +22 -1
- package/dist/client/storeTypes.js +27 -0
- package/dist/client/storeTypes.js.map +1 -1
- package/dist/index.d.ts +1 -1
- package/dist/index.js +1 -1
- package/dist/index.js.map +1 -1
- package/dist/node/index.d.ts +1 -0
- package/dist/node/index.js +1 -0
- package/dist/node/index.js.map +1 -1
- package/dist/node/snapshotFileSink.d.ts +3 -0
- package/dist/node/snapshotFileSink.js +79 -0
- package/dist/node/snapshotFileSink.js.map +1 -0
- package/dist/protocol/dtos.d.ts +76 -0
- package/dist/protocol/dtos.js +2 -0
- package/dist/protocol/dtos.js.map +1 -1
- package/dist/protocol/wire.d.ts +3 -1
- package/dist/protocol/wire.js +49 -0
- package/dist/protocol/wire.js.map +1 -1
- package/dist/sqlite/apply.d.ts +21 -1
- package/dist/sqlite/apply.js +218 -114
- package/dist/sqlite/apply.js.map +1 -1
- package/dist/sqlite/connection.d.ts +5 -0
- package/dist/sqlite/connection.js +17 -0
- package/dist/sqlite/connection.js.map +1 -1
- package/dist/sqlite/index.d.ts +2 -1
- package/dist/sqlite/index.js +1 -0
- package/dist/sqlite/index.js.map +1 -1
- package/dist/sqlite/options.d.ts +39 -1
- package/dist/sqlite/options.js +5 -1
- package/dist/sqlite/options.js.map +1 -1
- package/dist/sqlite/push.js +4 -1
- package/dist/sqlite/push.js.map +1 -1
- package/dist/sqlite/query.js +44 -15
- package/dist/sqlite/query.js.map +1 -1
- package/dist/sqlite/revocation.d.ts +1 -1
- package/dist/sqlite/revocation.js +4 -2
- package/dist/sqlite/revocation.js.map +1 -1
- package/dist/sqlite/snapshotFiles.d.ts +51 -0
- package/dist/sqlite/snapshotFiles.js +516 -0
- package/dist/sqlite/snapshotFiles.js.map +1 -0
- package/dist/sqlite/sql.d.ts +1 -1
- package/dist/sqlite/sql.js +4 -0
- package/dist/sqlite/sql.js.map +1 -1
- package/dist/sqlite/store.d.ts +20 -2
- package/dist/sqlite/store.js +147 -78
- package/dist/sqlite/store.js.map +1 -1
- package/package.json +3 -3
package/dist/client/runs.js.map
CHANGED
|
@@ -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;A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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.\nimport type { G9ESyncColumnType } from '../abstractions/enums.js';\nimport { G9SyncErrorCodes, G9SyncException, isSyncException } from '../abstractions/errors.js';\nimport { newGuid } from '../abstractions/guid.js';\nimport { G9SyncProtocol } from '../protocol/protocol.js';\nimport type { G9DtSubscriptionState } from '../protocol/dtos.js';\nimport { G9RowBatchFormatError } from '../protocol/rowBatch/format.js';\nimport { columnTypeName } from '../abstractions/enums.js';\nimport { createAbortController, type G9AbortController } from '../internal/abort.js';\nimport type { G9DtSyncProgress, G9ESyncPhase } from './progress.js';\nimport {\n G9ApplyReport,\n G9ELocalStoreFailure,\n isLocalStoreFailure,\n type G9ApplySlice,\n type G9PendingSummary,\n type G9SyncRunReport,\n type G9SyncSubscriptionRecord,\n} from './storeTypes.js';\n\n/** Scheduling priority (`G9ESyncPriority`). A higher priority pre-empts a running background run. */\nexport const G9ESyncPriority = {\n Background: 0,\n Foreground: 1,\n UserInteractive: 2,\n} as const;\nexport type G9ESyncPriority = (typeof G9ESyncPriority)[keyof typeof G9ESyncPriority];\n\nconst PRIORITY_NAMES = ['Background', 'Foreground', 'UserInteractive'];\nexport function priorityName(priority: number): string {\n return PRIORITY_NAMES[priority] ?? String(priority);\n}\n\n/** `G9ESyncOutcome`. */\nexport const G9ESyncOutcome = {\n Succeeded: 0,\n /** Data moved, but some rows were rejected or some subscriptions reported problems. */\n CompletedWithRejections: 1,\n Failed: 2,\n Canceled: 3,\n} as const;\nexport type G9ESyncOutcome = (typeof G9ESyncOutcome)[keyof typeof G9ESyncOutcome];\n\nconst OUTCOME_NAMES = ['Succeeded', 'CompletedWithRejections', 'Failed', 'Canceled'];\nexport function outcomeName(outcome: number): string {\n return OUTCOME_NAMES[outcome] ?? String(outcome);\n}\n\n/** Context handed to an app-owned post step (`G9CSyncPostStepContext`). */\nexport interface G9SyncPostStepContext {\n run: G9SyncRun;\n /** Everything this run changed so far. */\n changes: G9ApplyReport;\n /** Report 0..1 of the step; mapped into the step's slice of the bar. */\n progress: (fraction: number) => void;\n}\n\n/** An app-owned step that runs after the data applied and owns a slice of the progress bar (`G9CSyncPostStep`). */\nexport class G9SyncPostStep {\n readonly name: string;\n readonly weightHint: number;\n readonly action: (context: G9SyncPostStepContext, signal: AbortSignal) => Promise<void>;\n\n constructor(name: string, weightHint: number, action: (context: G9SyncPostStepContext, signal: AbortSignal) => Promise<void>) {\n if (typeof name !== 'string' || name.trim() === '') throw new TypeError('A post step needs a name.');\n if (typeof action !== 'function') throw new TypeError('A post step needs an action.');\n this.name = name;\n this.weightHint = Math.min(Math.max(weightHint, 0), 0.9);\n this.action = action;\n }\n}\n\n/** A sync request (`G9CSyncRequest`). */\nexport interface G9SyncRequest {\n /** Subscription keys or names to pull; omitted = every local subscription (background runs skip heavy ones). */\n subscriptions?: readonly string[] | null;\n push?: boolean;\n pull?: boolean;\n /** Reconcile the selected subscriptions even when nothing asks for it. */\n forceReconcile?: boolean;\n priority?: G9ESyncPriority;\n postSteps?: readonly G9SyncPostStep[];\n progress?: ((progress: G9DtSyncProgress) => void) | null;\n signal?: AbortSignal | null;\n}\n\n/** The request with its defaults filled in. */\nexport interface G9ResolvedSyncRequest {\n subscriptions: readonly string[] | null;\n push: boolean;\n pull: boolean;\n forceReconcile: boolean;\n priority: G9ESyncPriority;\n postSteps: readonly G9SyncPostStep[];\n progress: ((progress: G9DtSyncProgress) => void) | null;\n signal: AbortSignal | null;\n}\n\nexport function resolveRequest(request: G9SyncRequest | null | undefined): G9ResolvedSyncRequest {\n return {\n subscriptions: request?.subscriptions ?? null,\n push: request?.push ?? true,\n pull: request?.pull ?? true,\n forceReconcile: request?.forceReconcile ?? false,\n priority: request?.priority ?? 1,\n postSteps: request?.postSteps ?? [],\n progress: request?.progress ?? null,\n signal: request?.signal ?? null,\n };\n}\n\n/** `G9CSyncRequest.CanCoalesce`. */\nexport function canCoalesce(request: G9ResolvedSyncRequest): boolean {\n return request.postSteps.length === 0 && request.progress === null && request.signal === null;\n}\n\n/** `G9CSyncRequest.Signature`. */\nexport function requestSignature(request: G9ResolvedSyncRequest): string {\n const subscriptions = request.subscriptions === null ? '*' : request.subscriptions.slice().sort((a, b) => (a < b ? -1 : a > b ? 1 : 0)).join(',');\n return `${request.push ? 'True' : 'False'}|${request.pull ? 'True' : 'False'}|${request.forceReconcile ? 'True' : 'False'}|${subscriptions}`;\n}\n\n/** One defect of the client model, as the server sees it (`G9CSyncModelProblem`). */\nexport interface G9SyncModelProblem {\n code: string;\n table: string;\n column: string;\n clientType: G9ESyncColumnType;\n serverType: G9ESyncColumnType;\n}\n\nexport function describeModelProblem(problem: G9SyncModelProblem): string {\n return `${problem.table}.${problem.column} is ${columnTypeName(problem.clientType)} on the client and ${columnTypeName(problem.serverType)} on the server`;\n}\n\n/** The result of a run (`G9CSyncRunResult`). */\nexport interface G9SyncRunResult {\n runId: string;\n outcome: G9ESyncOutcome;\n error: G9SyncException | null;\n pushed: number;\n rejected: number;\n conflicts: number;\n downloaded: number;\n applied: number;\n durationMs: number;\n /** Milliseconds spent in each phase of this run, keyed by phase name. */\n phaseMs: { [phase: string]: number };\n subscriptions: string[];\n /** Subscriptions that could not sync, with the server's reason. */\n problems: G9DtSubscriptionState[];\n /** Defects of the client model the server reported in this run's hello (ADR-0061). */\n modelProblems: G9SyncModelProblem[];\n changes: G9ApplyReport;\n isSuccess: boolean;\n}\n\nexport function makeRunResult(fields: Partial<G9SyncRunResult> & { runId: string; outcome: G9ESyncOutcome }): G9SyncRunResult {\n return {\n error: null,\n pushed: 0,\n rejected: 0,\n conflicts: 0,\n downloaded: 0,\n applied: 0,\n durationMs: 0,\n phaseMs: {},\n subscriptions: [],\n problems: [],\n modelProblems: [],\n changes: new G9ApplyReport(),\n ...fields,\n isSuccess: fields.outcome === G9ESyncOutcome.Succeeded || fields.outcome === G9ESyncOutcome.CompletedWithRejections,\n };\n}\n\n/** A queued or running sync (`G9CSyncRun`). Await {@link completion}; read progress with {@link onProgress} or {@link progress}. */\nexport class G9SyncRun {\n readonly runId: string = newGuid();\n readonly request: G9ResolvedSyncRequest;\n readonly completion: Promise<G9SyncRunResult>;\n latestProgress: G9DtSyncProgress | null = null;\n isStarted = false;\n\n /** @internal */\n readonly cancellation: G9AbortController;\n /** @internal */\n preempted = false;\n\n private _resolve!: (result: G9SyncRunResult) => void;\n private readonly _listeners: ((progress: G9DtSyncProgress) => void)[] = [];\n private readonly _buffer: G9DtSyncProgress[] = [];\n private readonly _waiters: ((value: IteratorResult<G9DtSyncProgress>) => void)[] = [];\n private _done = false;\n private _unlink: () => void = () => undefined;\n\n constructor(request: G9ResolvedSyncRequest) {\n this.request = request;\n this.completion = new Promise<G9SyncRunResult>((resolve) => {\n this._resolve = resolve;\n });\n this.cancellation = createAbortController();\n const external = request.signal;\n if (external) {\n if (external.aborted) this.cancellation.abort();\n else {\n const listener = (): void => this.cancellation.abort();\n external.addEventListener('abort', listener);\n this._unlink = () => external.removeEventListener('abort', listener);\n }\n }\n }\n\n /** Requests cancellation. Network phases stop at once; an apply in progress finishes atomically first. */\n cancel(): void {\n this.cancellation.abort();\n }\n\n /** Subscribes to progress samples; returns the unsubscribe function. */\n onProgress(listener: (progress: G9DtSyncProgress) => void): () => void {\n this._listeners.push(listener);\n return () => {\n const index = this._listeners.indexOf(listener);\n if (index >= 0) this._listeners.splice(index, 1);\n };\n }\n\n /** The progress stream (bounded: the oldest samples are dropped when a reader falls 64 behind), ending with the run. */\n progress(): AsyncIterable<G9DtSyncProgress> {\n // eslint-disable-next-line @typescript-eslint/no-this-alias\n const run = this;\n return {\n [Symbol.asyncIterator](): AsyncIterator<G9DtSyncProgress> {\n return {\n next(): Promise<IteratorResult<G9DtSyncProgress>> {\n const value = run._buffer.shift();\n if (value) return Promise.resolve({ value, done: false });\n if (run._done) return Promise.resolve({ value: undefined as unknown as G9DtSyncProgress, done: true });\n return new Promise((resolve) => run._waiters.push(resolve));\n },\n };\n },\n };\n }\n\n /** @internal */\n publish(progress: G9DtSyncProgress): void {\n this.latestProgress = progress;\n const waiter = this._waiters.shift();\n if (waiter) waiter({ value: progress, done: false });\n else {\n this._buffer.push(progress);\n if (this._buffer.length > 64) this._buffer.shift();\n }\n for (const listener of this._listeners.slice()) {\n try {\n listener(progress);\n } catch {\n // A progress consumer must never break the sync.\n }\n }\n try {\n this.request.progress?.(progress);\n } catch {\n // A progress consumer must never break the sync.\n }\n }\n\n /** @internal */\n complete(result: G9SyncRunResult): void {\n if (this._done) return;\n this._done = true;\n for (const waiter of this._waiters.splice(0, this._waiters.length)) waiter({ value: undefined as unknown as G9DtSyncProgress, done: true });\n this._unlink();\n this._resolve(result);\n }\n}\n\n/** `G9CSubscriptionOptions`. */\nexport interface G9SubscriptionOptions {\n /** Overrides the server definition's ephemeral flag. */\n ephemeral?: boolean;\n ttlMs?: number;\n /** The rows already exist locally: reconcile instead of downloading a snapshot. Call adoptExistingRows first. */\n adoptExistingRows?: boolean;\n}\n\n/** Engine options (`G9CSyncEngineOptions`). Durations are milliseconds. */\nexport interface G9SyncEngineOptions {\n /** Sent at Hello; the server's connect gates may refuse old versions. */\n appVersion?: string | null;\n pushBatchRows?: number;\n /** Transient failures retried inside one run. */\n maxRetries?: number;\n retryBaseDelayMs?: number;\n /** Queue a background pull when the server pokes about changed tables. */\n pullOnChangesAvailable?: boolean;\n changesDebounceMs?: number;\n progressMaxHz?: number;\n fetchKeysPerRequest?: number;\n /** Rows a reconciliation fetches before it applies them (ADR-0066). */\n reconcileApplyRows?: number;\n /** A reconciliation that would fetch at least this many rows of one table hands them to a staged snapshot (ADR-0066). 0 = never. */\n reconcileSnapshotThreshold?: number;\n /** The largest decoded body accepted from one server frame (ADR-0051). */\n maxDecodedFrameBytes?: number;\n /** The newest G9RowBatch body layout to ask the server for (ADR-0040). */\n maxFrameVersion?: number;\n /** Fail a run when the server reports a client column whose type differs (ADR-0061). */\n failOnTypeMismatch?: boolean;\n /** A staged pull older than this is discarded instead of resumed. */\n stagedPullMaxAgeMs?: number;\n /** Most payload bytes kept in stages other than the one a run resumes (ADR-0060). */\n stagedPullsMaxBytes?: number;\n keepDeletedFeedEntries?: number;\n keepRunReports?: number;\n /** Where the engine logs (the ILogger twin); silent when omitted. */\n logger?: G9SyncLogger | null;\n /** Platform integration (foreground service, keep-awake, connectivity). */\n hooks?: G9SyncHostHooks | null;\n}\n\nexport type G9ResolvedEngineOptions = Required<Omit<G9SyncEngineOptions, 'appVersion' | 'logger' | 'hooks'>> & {\n appVersion: string | null;\n logger: G9SyncLogger | null;\n hooks: G9SyncHostHooks | null;\n};\n\nexport function resolveEngineOptions(options: G9SyncEngineOptions | null | undefined): G9ResolvedEngineOptions {\n return {\n appVersion: options?.appVersion ?? null,\n pushBatchRows: options?.pushBatchRows ?? 2000,\n maxRetries: options?.maxRetries ?? 5,\n retryBaseDelayMs: options?.retryBaseDelayMs ?? 1000,\n pullOnChangesAvailable: options?.pullOnChangesAvailable ?? true,\n changesDebounceMs: options?.changesDebounceMs ?? 2000,\n progressMaxHz: options?.progressMaxHz ?? 10,\n fetchKeysPerRequest: options?.fetchKeysPerRequest ?? 2000,\n reconcileApplyRows: options?.reconcileApplyRows ?? 20000,\n reconcileSnapshotThreshold: options?.reconcileSnapshotThreshold ?? 100000,\n maxDecodedFrameBytes: options?.maxDecodedFrameBytes ?? 64 * 1024 * 1024,\n maxFrameVersion: options?.maxFrameVersion ?? G9SyncProtocol.MaxFrameVersion,\n failOnTypeMismatch: options?.failOnTypeMismatch ?? false,\n stagedPullMaxAgeMs: options?.stagedPullMaxAgeMs ?? 90 * 60 * 1000,\n stagedPullsMaxBytes: options?.stagedPullsMaxBytes ?? 64 * 1024 * 1024,\n keepDeletedFeedEntries: options?.keepDeletedFeedEntries ?? 50000,\n keepRunReports: options?.keepRunReports ?? 50,\n logger: options?.logger ?? null,\n hooks: options?.hooks ?? null,\n };\n}\n\n/** Log levels of {@link G9SyncLogger} (Microsoft.Extensions.Logging's). */\nexport type G9SyncLogLevel = 'debug' | 'information' | 'warning' | 'error';\n\n/** Where the library logs. `eventId` is the .NET LoggerMessage event id of the same message. */\nexport interface G9SyncLogger {\n log(level: G9SyncLogLevel, eventId: number, message: string, error?: unknown): void;\n}\n\n/** Platform integration points (`IG9SyncHostHooks`). */\nexport interface G9SyncHostHooks {\n /** Called when a run starts executing; the returned scope's `dispose` runs when it ends. */\n beginRun(run: G9SyncRun, signal: AbortSignal): Promise<{ dispose(): void | Promise<void> } | null>;\n /** False skips automatic background runs. */\n readonly isNetworkAvailable: boolean;\n}\n\n/** `G9CSyncHealth`. */\nexport interface G9SyncHealth {\n clientId: string;\n isConnected: boolean;\n isRunning: boolean;\n queuedRuns: number;\n serverEpoch: string | null;\n lastHelloUtcMs: number | null;\n pending: G9PendingSummary;\n subscriptions: G9SyncSubscriptionRecord[];\n recentRuns: G9SyncRunReport[];\n}\n\n/** `G9CRowsAppliedEventArgs`. */\nexport interface G9RowsAppliedEvent {\n report: G9ApplyReport;\n source: G9ESyncPhase;\n /** Set for a staged pull applied in slices (ADR-0053). */\n slice: G9ApplySlice | null;\n}\n\n/** `G9CSyncErrors.Normalize`: every failure becomes a G9SyncException with a stable code. */\nexport function normalizeError(error: unknown): G9SyncException {\n if (isSyncException(error)) return error as G9SyncException;\n const message = error instanceof Error ? error.message : String(error);\n if (error instanceof Error && error.name === 'AbortError') return new G9SyncException(G9SyncErrorCodes.Canceled, 'The sync was canceled.', { cause: error });\n if (isLocalStoreFailure(error)) {\n const code =\n error.localStoreFailure === G9ELocalStoreFailure.Corrupt\n ? G9SyncErrorCodes.LocalStoreCorrupt\n : error.localStoreFailure === G9ELocalStoreFailure.DiskFull\n ? G9SyncErrorCodes.LocalStoreDiskFull\n : error.localStoreFailure === G9ELocalStoreFailure.Busy\n ? G9SyncErrorCodes.LocalStoreBusy\n : G9SyncErrorCodes.LocalStoreError;\n return new G9SyncException(code, message, { cause: error });\n }\n if (error instanceof G9RowBatchFormatError) return new G9SyncException(G9SyncErrorCodes.Unknown, message, { cause: error });\n if (error instanceof Error && (error.name === 'TimeoutError' || /network|socket|websocket|connection/i.test(error.name))) {\n return new G9SyncException(G9SyncErrorCodes.NetworkFailure, message, { cause: error });\n }\n return new G9SyncException(G9SyncErrorCodes.Unknown, message, { cause: error });\n}\n\n/** `G9CSyncErrors.IsTransient`. */\nexport function isTransientError(error: unknown): boolean {\n const code = normalizeError(error).code;\n return code === G9SyncErrorCodes.NetworkFailure || code === G9SyncErrorCodes.ServerError || code === G9SyncErrorCodes.ServerBusy;\n}\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,E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AAI,CAAC,KAAK,CAAC,IAAI,KAAK,cAAc,IAAI,sCAAsC,CAAC,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC,EAAE,CAAC;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.\nimport type { G9ESyncColumnType } from '../abstractions/enums.js';\nimport { G9SyncErrorCodes, G9SyncException, isSyncException } from '../abstractions/errors.js';\nimport { newGuid } from '../abstractions/guid.js';\nimport { G9SyncProtocol } from '../protocol/protocol.js';\nimport type { G9DtSubscriptionState } from '../protocol/dtos.js';\nimport { G9RowBatchFormatError } from '../protocol/rowBatch/format.js';\nimport { columnTypeName } from '../abstractions/enums.js';\nimport { createAbortController, type G9AbortController } from '../internal/abort.js';\nimport type { G9DtSyncProgress, G9ESyncPhase } from './progress.js';\nimport {\n G9ApplyReport,\n G9ELocalStoreFailure,\n isLocalStoreFailure,\n type G9ApplySlice,\n type G9PendingSummary,\n type G9SyncRunReport,\n type G9SyncSubscriptionRecord,\n} from './storeTypes.js';\n\n/** Scheduling priority (`G9ESyncPriority`). A higher priority pre-empts a running background run. */\nexport const G9ESyncPriority = {\n Background: 0,\n Foreground: 1,\n UserInteractive: 2,\n} as const;\nexport type G9ESyncPriority = (typeof G9ESyncPriority)[keyof typeof G9ESyncPriority];\n\nconst PRIORITY_NAMES = ['Background', 'Foreground', 'UserInteractive'];\nexport function priorityName(priority: number): string {\n return PRIORITY_NAMES[priority] ?? String(priority);\n}\n\n/** `G9ESyncOutcome`. */\nexport const G9ESyncOutcome = {\n Succeeded: 0,\n /** Data moved, but some rows were rejected or some subscriptions reported problems. */\n CompletedWithRejections: 1,\n Failed: 2,\n Canceled: 3,\n} as const;\nexport type G9ESyncOutcome = (typeof G9ESyncOutcome)[keyof typeof G9ESyncOutcome];\n\nconst OUTCOME_NAMES = ['Succeeded', 'CompletedWithRejections', 'Failed', 'Canceled'];\nexport function outcomeName(outcome: number): string {\n return OUTCOME_NAMES[outcome] ?? String(outcome);\n}\n\n/** Context handed to an app-owned post step (`G9CSyncPostStepContext`). */\nexport interface G9SyncPostStepContext {\n run: G9SyncRun;\n /** Everything this run changed so far. */\n changes: G9ApplyReport;\n /** Report 0..1 of the step; mapped into the step's slice of the bar. */\n progress: (fraction: number) => void;\n}\n\n/** An app-owned step that runs after the data applied and owns a slice of the progress bar (`G9CSyncPostStep`). */\nexport class G9SyncPostStep {\n readonly name: string;\n readonly weightHint: number;\n readonly action: (context: G9SyncPostStepContext, signal: AbortSignal) => Promise<void>;\n\n constructor(name: string, weightHint: number, action: (context: G9SyncPostStepContext, signal: AbortSignal) => Promise<void>) {\n if (typeof name !== 'string' || name.trim() === '') throw new TypeError('A post step needs a name.');\n if (typeof action !== 'function') throw new TypeError('A post step needs an action.');\n this.name = name;\n this.weightHint = Math.min(Math.max(weightHint, 0), 0.9);\n this.action = action;\n }\n}\n\n/** A sync request (`G9CSyncRequest`). */\nexport interface G9SyncRequest {\n /** Subscription keys or names to pull; omitted = every local subscription (background runs skip heavy ones). */\n subscriptions?: readonly string[] | null;\n push?: boolean;\n pull?: boolean;\n /** Reconcile the selected subscriptions even when nothing asks for it. */\n forceReconcile?: boolean;\n priority?: G9ESyncPriority;\n postSteps?: readonly G9SyncPostStep[];\n progress?: ((progress: G9DtSyncProgress) => void) | null;\n signal?: AbortSignal | null;\n}\n\n/** The request with its defaults filled in. */\nexport interface G9ResolvedSyncRequest {\n subscriptions: readonly string[] | null;\n push: boolean;\n pull: boolean;\n forceReconcile: boolean;\n priority: G9ESyncPriority;\n postSteps: readonly G9SyncPostStep[];\n progress: ((progress: G9DtSyncProgress) => void) | null;\n signal: AbortSignal | null;\n}\n\nexport function resolveRequest(request: G9SyncRequest | null | undefined): G9ResolvedSyncRequest {\n return {\n subscriptions: request?.subscriptions ?? null,\n push: request?.push ?? true,\n pull: request?.pull ?? true,\n forceReconcile: request?.forceReconcile ?? false,\n priority: request?.priority ?? 1,\n postSteps: request?.postSteps ?? [],\n progress: request?.progress ?? null,\n signal: request?.signal ?? null,\n };\n}\n\n/** `G9CSyncRequest.CanCoalesce`. */\nexport function canCoalesce(request: G9ResolvedSyncRequest): boolean {\n return request.postSteps.length === 0 && request.progress === null && request.signal === null;\n}\n\n/** `G9CSyncRequest.Signature`. */\nexport function requestSignature(request: G9ResolvedSyncRequest): string {\n const subscriptions = request.subscriptions === null ? '*' : request.subscriptions.slice().sort((a, b) => (a < b ? -1 : a > b ? 1 : 0)).join(',');\n return `${request.push ? 'True' : 'False'}|${request.pull ? 'True' : 'False'}|${request.forceReconcile ? 'True' : 'False'}|${subscriptions}`;\n}\n\n/** One defect of the client model, as the server sees it (`G9CSyncModelProblem`). */\nexport interface G9SyncModelProblem {\n code: string;\n table: string;\n column: string;\n clientType: G9ESyncColumnType;\n serverType: G9ESyncColumnType;\n}\n\nexport function describeModelProblem(problem: G9SyncModelProblem): string {\n return `${problem.table}.${problem.column} is ${columnTypeName(problem.clientType)} on the client and ${columnTypeName(problem.serverType)} on the server`;\n}\n\n/** The result of a run (`G9CSyncRunResult`). */\nexport interface G9SyncRunResult {\n runId: string;\n outcome: G9ESyncOutcome;\n error: G9SyncException | null;\n pushed: number;\n rejected: number;\n conflicts: number;\n downloaded: number;\n applied: number;\n durationMs: number;\n /** Milliseconds spent in each phase of this run, keyed by phase name. */\n phaseMs: { [phase: string]: number };\n subscriptions: string[];\n /** Subscriptions that could not sync, with the server's reason. */\n problems: G9DtSubscriptionState[];\n /** Defects of the client model the server reported in this run's hello (ADR-0061). */\n modelProblems: G9SyncModelProblem[];\n changes: G9ApplyReport;\n isSuccess: boolean;\n}\n\nexport function makeRunResult(fields: Partial<G9SyncRunResult> & { runId: string; outcome: G9ESyncOutcome }): G9SyncRunResult {\n return {\n error: null,\n pushed: 0,\n rejected: 0,\n conflicts: 0,\n downloaded: 0,\n applied: 0,\n durationMs: 0,\n phaseMs: {},\n subscriptions: [],\n problems: [],\n modelProblems: [],\n changes: new G9ApplyReport(),\n ...fields,\n isSuccess: fields.outcome === G9ESyncOutcome.Succeeded || fields.outcome === G9ESyncOutcome.CompletedWithRejections,\n };\n}\n\n/** A queued or running sync (`G9CSyncRun`). Await {@link completion}; read progress with {@link onProgress} or {@link progress}. */\nexport class G9SyncRun {\n readonly runId: string = newGuid();\n readonly request: G9ResolvedSyncRequest;\n readonly completion: Promise<G9SyncRunResult>;\n latestProgress: G9DtSyncProgress | null = null;\n isStarted = false;\n\n /** @internal */\n readonly cancellation: G9AbortController;\n /** @internal */\n preempted = false;\n\n private _resolve!: (result: G9SyncRunResult) => void;\n private readonly _listeners: ((progress: G9DtSyncProgress) => void)[] = [];\n private readonly _buffer: G9DtSyncProgress[] = [];\n private readonly _waiters: ((value: IteratorResult<G9DtSyncProgress>) => void)[] = [];\n private _done = false;\n private _unlink: () => void = () => undefined;\n\n constructor(request: G9ResolvedSyncRequest) {\n this.request = request;\n this.completion = new Promise<G9SyncRunResult>((resolve) => {\n this._resolve = resolve;\n });\n this.cancellation = createAbortController();\n const external = request.signal;\n if (external) {\n if (external.aborted) this.cancellation.abort();\n else {\n const listener = (): void => this.cancellation.abort();\n external.addEventListener('abort', listener);\n this._unlink = () => external.removeEventListener('abort', listener);\n }\n }\n }\n\n /** Requests cancellation. Network phases stop at once; an apply in progress finishes atomically first. */\n cancel(): void {\n this.cancellation.abort();\n }\n\n /** Subscribes to progress samples; returns the unsubscribe function. */\n onProgress(listener: (progress: G9DtSyncProgress) => void): () => void {\n this._listeners.push(listener);\n return () => {\n const index = this._listeners.indexOf(listener);\n if (index >= 0) this._listeners.splice(index, 1);\n };\n }\n\n /** The progress stream (bounded: the oldest samples are dropped when a reader falls 64 behind), ending with the run. */\n progress(): AsyncIterable<G9DtSyncProgress> {\n // eslint-disable-next-line @typescript-eslint/no-this-alias\n const run = this;\n return {\n [Symbol.asyncIterator](): AsyncIterator<G9DtSyncProgress> {\n return {\n next(): Promise<IteratorResult<G9DtSyncProgress>> {\n const value = run._buffer.shift();\n if (value) return Promise.resolve({ value, done: false });\n if (run._done) return Promise.resolve({ value: undefined as unknown as G9DtSyncProgress, done: true });\n return new Promise((resolve) => run._waiters.push(resolve));\n },\n };\n },\n };\n }\n\n /** @internal */\n publish(progress: G9DtSyncProgress): void {\n this.latestProgress = progress;\n const waiter = this._waiters.shift();\n if (waiter) waiter({ value: progress, done: false });\n else {\n this._buffer.push(progress);\n if (this._buffer.length > 64) this._buffer.shift();\n }\n for (const listener of this._listeners.slice()) {\n try {\n listener(progress);\n } catch {\n // A progress consumer must never break the sync.\n }\n }\n try {\n this.request.progress?.(progress);\n } catch {\n // A progress consumer must never break the sync.\n }\n }\n\n /** @internal */\n complete(result: G9SyncRunResult): void {\n if (this._done) return;\n this._done = true;\n for (const waiter of this._waiters.splice(0, this._waiters.length)) waiter({ value: undefined as unknown as G9DtSyncProgress, done: true });\n this._unlink();\n this._resolve(result);\n }\n}\n\n/** `G9CSubscriptionOptions`. */\nexport interface G9SubscriptionOptions {\n /** Overrides the server definition's ephemeral flag. */\n ephemeral?: boolean;\n ttlMs?: number;\n /** The rows already exist locally: reconcile instead of downloading a snapshot. Call adoptExistingRows first. */\n adoptExistingRows?: boolean;\n}\n\n/** Engine options (`G9CSyncEngineOptions`). Durations are milliseconds. */\nexport interface G9SyncEngineOptions {\n /** Sent at Hello; the server's connect gates may refuse old versions. */\n appVersion?: string | null;\n pushBatchRows?: number;\n /** Transient failures retried inside one run. */\n maxRetries?: number;\n retryBaseDelayMs?: number;\n /** Queue a background pull when the server pokes about changed tables. */\n pullOnChangesAvailable?: boolean;\n changesDebounceMs?: number;\n progressMaxHz?: number;\n fetchKeysPerRequest?: number;\n /** Rows a reconciliation fetches before it applies them (ADR-0066). */\n reconcileApplyRows?: number;\n /** A reconciliation that would fetch at least this many rows of one table hands them to a staged snapshot (ADR-0066). 0 = never. */\n reconcileSnapshotThreshold?: number;\n /** The largest decoded body accepted from one server frame (ADR-0051). */\n maxDecodedFrameBytes?: number;\n /** The newest G9RowBatch body layout to ask the server for (ADR-0040). */\n maxFrameVersion?: number;\n /** Fail a run when the server reports a client column whose type differs (ADR-0061). */\n failOnTypeMismatch?: boolean;\n /**\n * Offer the server to send large first downloads as SQLite snapshot files (ADR-0072), when the store can take them (a store\n * with a `snapshotFiles` sink). Default true. A file that fails is replaced by the same pull as rows, in the same run.\n */\n acceptSnapshotFiles?: boolean;\n /** A staged pull older than this is discarded instead of resumed. */\n stagedPullMaxAgeMs?: number;\n /** Most payload bytes kept in stages other than the one a run resumes (ADR-0060). */\n stagedPullsMaxBytes?: number;\n keepDeletedFeedEntries?: number;\n keepRunReports?: number;\n /** Where the engine logs (the ILogger twin); silent when omitted. */\n logger?: G9SyncLogger | null;\n /** Platform integration (foreground service, keep-awake, connectivity). */\n hooks?: G9SyncHostHooks | null;\n}\n\nexport type G9ResolvedEngineOptions = Required<Omit<G9SyncEngineOptions, 'appVersion' | 'logger' | 'hooks'>> & {\n appVersion: string | null;\n logger: G9SyncLogger | null;\n hooks: G9SyncHostHooks | null;\n};\n\nexport function resolveEngineOptions(options: G9SyncEngineOptions | null | undefined): G9ResolvedEngineOptions {\n return {\n appVersion: options?.appVersion ?? null,\n pushBatchRows: options?.pushBatchRows ?? 2000,\n maxRetries: options?.maxRetries ?? 5,\n retryBaseDelayMs: options?.retryBaseDelayMs ?? 1000,\n pullOnChangesAvailable: options?.pullOnChangesAvailable ?? true,\n changesDebounceMs: options?.changesDebounceMs ?? 2000,\n progressMaxHz: options?.progressMaxHz ?? 10,\n fetchKeysPerRequest: options?.fetchKeysPerRequest ?? 2000,\n reconcileApplyRows: options?.reconcileApplyRows ?? 20000,\n reconcileSnapshotThreshold: options?.reconcileSnapshotThreshold ?? 100000,\n maxDecodedFrameBytes: options?.maxDecodedFrameBytes ?? 64 * 1024 * 1024,\n maxFrameVersion: options?.maxFrameVersion ?? G9SyncProtocol.MaxFrameVersion,\n failOnTypeMismatch: options?.failOnTypeMismatch ?? false,\n acceptSnapshotFiles: options?.acceptSnapshotFiles ?? true,\n stagedPullMaxAgeMs: options?.stagedPullMaxAgeMs ?? 90 * 60 * 1000,\n stagedPullsMaxBytes: options?.stagedPullsMaxBytes ?? 64 * 1024 * 1024,\n keepDeletedFeedEntries: options?.keepDeletedFeedEntries ?? 50000,\n keepRunReports: options?.keepRunReports ?? 50,\n logger: options?.logger ?? null,\n hooks: options?.hooks ?? null,\n };\n}\n\n/** Log levels of {@link G9SyncLogger} (Microsoft.Extensions.Logging's). */\nexport type G9SyncLogLevel = 'debug' | 'information' | 'warning' | 'error';\n\n/** Where the library logs. `eventId` is the .NET LoggerMessage event id of the same message. */\nexport interface G9SyncLogger {\n log(level: G9SyncLogLevel, eventId: number, message: string, error?: unknown): void;\n}\n\n/** Platform integration points (`IG9SyncHostHooks`). */\nexport interface G9SyncHostHooks {\n /** Called when a run starts executing; the returned scope's `dispose` runs when it ends. */\n beginRun(run: G9SyncRun, signal: AbortSignal): Promise<{ dispose(): void | Promise<void> } | null>;\n /** False skips automatic background runs. */\n readonly isNetworkAvailable: boolean;\n}\n\n/** `G9CSyncHealth`. */\nexport interface G9SyncHealth {\n clientId: string;\n isConnected: boolean;\n isRunning: boolean;\n queuedRuns: number;\n serverEpoch: string | null;\n lastHelloUtcMs: number | null;\n pending: G9PendingSummary;\n subscriptions: G9SyncSubscriptionRecord[];\n recentRuns: G9SyncRunReport[];\n}\n\n/** `G9CRowsAppliedEventArgs`. */\nexport interface G9RowsAppliedEvent {\n report: G9ApplyReport;\n source: G9ESyncPhase;\n /** Set for a staged pull applied in slices (ADR-0053). */\n slice: G9ApplySlice | null;\n}\n\n/** `G9CSyncErrors.Normalize`: every failure becomes a G9SyncException with a stable code. */\nexport function normalizeError(error: unknown): G9SyncException {\n if (isSyncException(error)) return error as G9SyncException;\n const message = error instanceof Error ? error.message : String(error);\n if (error instanceof Error && error.name === 'AbortError') return new G9SyncException(G9SyncErrorCodes.Canceled, 'The sync was canceled.', { cause: error });\n if (isLocalStoreFailure(error)) {\n const code =\n error.localStoreFailure === G9ELocalStoreFailure.Corrupt\n ? G9SyncErrorCodes.LocalStoreCorrupt\n : error.localStoreFailure === G9ELocalStoreFailure.DiskFull\n ? G9SyncErrorCodes.LocalStoreDiskFull\n : error.localStoreFailure === G9ELocalStoreFailure.Busy\n ? G9SyncErrorCodes.LocalStoreBusy\n : G9SyncErrorCodes.LocalStoreError;\n return new G9SyncException(code, message, { cause: error });\n }\n if (error instanceof G9RowBatchFormatError) return new G9SyncException(G9SyncErrorCodes.Unknown, message, { cause: error });\n if (error instanceof Error && (error.name === 'TimeoutError' || /network|socket|websocket|connection/i.test(error.name))) {\n return new G9SyncException(G9SyncErrorCodes.NetworkFailure, message, { cause: error });\n }\n return new G9SyncException(G9SyncErrorCodes.Unknown, message, { cause: error });\n}\n\n/** `G9CSyncErrors.IsTransient`. */\nexport function isTransientError(error: unknown): boolean {\n const code = normalizeError(error).code;\n return code === G9SyncErrorCodes.NetworkFailure || code === G9SyncErrorCodes.ServerError || code === G9SyncErrorCodes.ServerBusy;\n}\n"]}
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import type { G9EMoveOutPolicy } from '../abstractions/enums.js';
|
|
2
2
|
import type { G9Long } from '../abstractions/long.js';
|
|
3
3
|
import type { G9SyncParameters } from '../abstractions/parameters.js';
|
|
4
|
-
import type { G9DtBackfillRequest, G9DtCommand, G9DtHelloResult, G9DtNegotiatedTable, G9DtPullContinuation, G9DtPullPlan, G9DtPushResult, G9DtSubscriptionDefinition, G9DtSubscriptionRef, G9DtSyncChunk, G9DtTableColumns, G9DtTableDigest } from '../protocol/dtos.js';
|
|
4
|
+
import type { G9DtBackfillRequest, G9DtCommand, G9DtHelloResult, G9DtNegotiatedTable, G9DtPullContinuation, G9DtPullPlan, G9DtPushResult, G9DtSnapshotFileRequest, G9DtSubscriptionDefinition, G9DtSubscriptionRef, G9DtSyncChunk, G9DtTableColumns, G9DtTableDigest } from '../protocol/dtos.js';
|
|
5
5
|
import type { G9SyncClientModel } from './model.js';
|
|
6
6
|
/** What the client last learned from the server (`G9CClientServerState`). */
|
|
7
7
|
export interface G9ClientServerState {
|
|
@@ -103,6 +103,12 @@ export interface G9ResumePoint {
|
|
|
103
103
|
/** Why a table large enough for index deferral kept its indexes live. */
|
|
104
104
|
export declare const REASON_TABLE_NOT_EMPTY = "table-not-empty";
|
|
105
105
|
/** How an apply ran, as opposed to what it changed (`G9CApplyDiagnostics`, ADR-0058). */
|
|
106
|
+
/** A file table copied record for record into an empty table with identical columns (the transfer optimisation). */
|
|
107
|
+
export declare const FILE_MODE_COPY = "copy";
|
|
108
|
+
/** A file table copied into an empty table by column name. */
|
|
109
|
+
export declare const FILE_MODE_COLUMNS = "columns";
|
|
110
|
+
/** A file table merged into a table that held rows or protected rows: changed rows only. */
|
|
111
|
+
export declare const FILE_MODE_MERGE = "merge";
|
|
106
112
|
export declare class G9ApplyDiagnostics {
|
|
107
113
|
transactions: number;
|
|
108
114
|
transactionsWithTriggersSkipped: number;
|
|
@@ -121,6 +127,16 @@ export declare class G9ApplyDiagnostics {
|
|
|
121
127
|
};
|
|
122
128
|
indexRebuildMs: number;
|
|
123
129
|
elapsedMs: number;
|
|
130
|
+
/** Snapshot files copied in (ADR-0072). */
|
|
131
|
+
snapshotFiles: number;
|
|
132
|
+
/** Rows that arrived through snapshot files. */
|
|
133
|
+
fileRows: number;
|
|
134
|
+
/** Milliseconds spent copying snapshot files, metadata included. */
|
|
135
|
+
fileCopyMs: number;
|
|
136
|
+
/** How each table came out of a snapshot file: `copy`, `columns` or `merge` (see FILE_MODE_*). */
|
|
137
|
+
readonly fileTables: {
|
|
138
|
+
[table: string]: string;
|
|
139
|
+
};
|
|
124
140
|
/** True when every transaction ran with trigger execution off, false when any ran with it on, null when nothing was applied. */
|
|
125
141
|
get triggersSkipped(): boolean | null;
|
|
126
142
|
get deferredIndexCount(): number;
|
|
@@ -394,6 +410,11 @@ export interface G9SyncClientStore {
|
|
|
394
410
|
pruneStagedPulls(olderThanUtcMs: number, maxBytes: number, keepGeneration: string | null, signal?: AbortSignal): Promise<number>;
|
|
395
411
|
discardAllStagedPulls(signal?: AbortSignal): Promise<number>;
|
|
396
412
|
stageChunk(runId: string, chunk: G9DtSyncChunk, signal?: AbortSignal): Promise<void>;
|
|
413
|
+
/**
|
|
414
|
+
* The store's offer to receive large first downloads as SQLite snapshot files (ADR-0072), or null for rows only. A store that
|
|
415
|
+
* makes an offer stages file segments (`chunk.file`) in `stageChunk` and copies the files in `applyStagedPull`.
|
|
416
|
+
*/
|
|
417
|
+
describeSnapshotFiles?(negotiated: readonly G9DtNegotiatedTable[]): G9DtSnapshotFileRequest | null;
|
|
397
418
|
getResumePoint(runId: string, signal?: AbortSignal): Promise<G9ResumePoint>;
|
|
398
419
|
applyStagedPull(runId: string, rowsApplied: ((rows: number) => void) | null, slices: ((slice: G9ApplySlice) => void) | null, signal?: AbortSignal): Promise<G9ApplyReport>;
|
|
399
420
|
discardStagedPull(runId: string, signal?: AbortSignal): Promise<void>;
|
|
@@ -19,6 +19,12 @@ export function toSubscriptionRef(record) {
|
|
|
19
19
|
export const REASON_TABLE_NOT_EMPTY = 'table-not-empty';
|
|
20
20
|
const MAX_FOREIGN_TRIGGER_NAMES = 10;
|
|
21
21
|
/** How an apply ran, as opposed to what it changed (`G9CApplyDiagnostics`, ADR-0058). */
|
|
22
|
+
/** A file table copied record for record into an empty table with identical columns (the transfer optimisation). */
|
|
23
|
+
export const FILE_MODE_COPY = 'copy';
|
|
24
|
+
/** A file table copied into an empty table by column name. */
|
|
25
|
+
export const FILE_MODE_COLUMNS = 'columns';
|
|
26
|
+
/** A file table merged into a table that held rows or protected rows: changed rows only. */
|
|
27
|
+
export const FILE_MODE_MERGE = 'merge';
|
|
22
28
|
export class G9ApplyDiagnostics {
|
|
23
29
|
constructor() {
|
|
24
30
|
this.transactions = 0;
|
|
@@ -30,6 +36,14 @@ export class G9ApplyDiagnostics {
|
|
|
30
36
|
this.msByTable = {};
|
|
31
37
|
this.indexRebuildMs = 0;
|
|
32
38
|
this.elapsedMs = 0;
|
|
39
|
+
/** Snapshot files copied in (ADR-0072). */
|
|
40
|
+
this.snapshotFiles = 0;
|
|
41
|
+
/** Rows that arrived through snapshot files. */
|
|
42
|
+
this.fileRows = 0;
|
|
43
|
+
/** Milliseconds spent copying snapshot files, metadata included. */
|
|
44
|
+
this.fileCopyMs = 0;
|
|
45
|
+
/** How each table came out of a snapshot file: `copy`, `columns` or `merge` (see FILE_MODE_*). */
|
|
46
|
+
this.fileTables = {};
|
|
33
47
|
}
|
|
34
48
|
/** True when every transaction ran with trigger execution off, false when any ran with it on, null when nothing was applied. */
|
|
35
49
|
get triggersSkipped() {
|
|
@@ -46,6 +60,11 @@ export class G9ApplyDiagnostics {
|
|
|
46
60
|
this.transactionsWithTriggersSkipped += other.transactionsWithTriggersSkipped;
|
|
47
61
|
this.indexRebuildMs += other.indexRebuildMs;
|
|
48
62
|
this.elapsedMs += other.elapsedMs;
|
|
63
|
+
this.snapshotFiles += other.snapshotFiles;
|
|
64
|
+
this.fileRows += other.fileRows;
|
|
65
|
+
this.fileCopyMs += other.fileCopyMs;
|
|
66
|
+
for (const key of Object.keys(other.fileTables))
|
|
67
|
+
this.fileTables[key] = other.fileTables[key];
|
|
49
68
|
for (const name of other.foreignTriggers) {
|
|
50
69
|
if (this.foreignTriggers.length >= MAX_FOREIGN_TRIGGER_NAMES)
|
|
51
70
|
break;
|
|
@@ -78,6 +97,14 @@ export class G9ApplyDiagnostics {
|
|
|
78
97
|
const live = Object.keys(this.liveIndexReasons);
|
|
79
98
|
if (live.length > 0)
|
|
80
99
|
text += '; live indexes on ' + live.map((t) => t + ' (' + this.liveIndexReasons[t] + ')').join(', ');
|
|
100
|
+
if (this.snapshotFiles > 0) {
|
|
101
|
+
text +=
|
|
102
|
+
`; ${this.snapshotFiles} snapshot file(s), ${this.fileRows} rows copied in ${this.fileCopyMs} ms (` +
|
|
103
|
+
Object.keys(this.fileTables)
|
|
104
|
+
.map((t) => t + ':' + this.fileTables[t])
|
|
105
|
+
.join(', ') +
|
|
106
|
+
')';
|
|
107
|
+
}
|
|
81
108
|
const slowest = Object.keys(this.msByTable)
|
|
82
109
|
.sort((a, b) => this.msByTable[b] - this.msByTable[a])
|
|
83
110
|
.slice(0, 4);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"storeTypes.js","sourceRoot":"","sources":["../../src/client/storeTypes.ts"],"names":[],"mappings":"AAiCA,8BAA8B;AAC9B,MAAM,CAAC,MAAM,oBAAoB,GAAG;IAClC,MAAM,EAAE,CAAC;IACT,cAAc,EAAE,CAAC;IACjB,MAAM,EAAE,CAAC;CACD,CAAC;AAyBX,iDAAiD;AACjD,MAAM,UAAU,iBAAiB,CAAC,MAAgC;IAChE,OAAO;QACL,IAAI,EAAE,MAAM,CAAC,IAAI;QACjB,UAAU,EAAE,MAAM,CAAC,UAAU,CAAC,MAAM;QACpC,MAAM,EAAE,MAAM,CAAC,MAAM;QACrB,cAAc,EAAE,MAAM,CAAC,cAAc;QACrC,QAAQ,EAAE,MAAM,CAAC,QAAQ;KAC1B,CAAC;AACJ,CAAC;AAiED,2EAA2E;AAE3E,yEAAyE;AACzE,MAAM,CAAC,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,KAAc;IAChD,OAAO,OAAO,KAAK,KAAK,QAAQ,IAAI,KAAK,KAAK,IAAI,IAAI,OAAQ,KAAyC,CAAC,iBAAiB,KAAK,QAAQ,CAAC;AACzI,CAAC","sourcesContent":["// Twins of G9SyncData.Client/Storage/*.cs: the client store contract, its records, local commands, revocation rules\n// and apply diagnostics. The engine is store-agnostic; `@g9tm/syncdata/sqlite` is the implementation.\nimport type { G9EMoveOutPolicy } from '../abstractions/enums.js';\nimport type { G9Long } from '../abstractions/long.js';\nimport type { G9SyncParameters } from '../abstractions/parameters.js';\nimport type {\n G9DtBackfillRequest,\n G9DtCommand,\n G9DtHelloResult,\n G9DtNegotiatedTable,\n G9DtPullContinuation,\n G9DtPullPlan,\n G9DtPushResult,\n G9DtSubscriptionDefinition,\n G9DtSubscriptionRef,\n G9DtSyncChunk,\n G9DtTableColumns,\n G9DtTableDigest,\n} from '../protocol/dtos.js';\nimport type { G9SyncClientModel } from './model.js';\n\n// ---------------------------------------------------------------- server state and subscriptions\n\n/** What the client last learned from the server (`G9CClientServerState`). */\nexport interface G9ClientServerState {\n epoch: string | null;\n lastHelloUtcMs: number | null;\n /** Server clock minus device clock, ms. */\n serverClockOffsetMs: number;\n tables: G9DtNegotiatedTable[];\n definitions: G9DtSubscriptionDefinition[];\n}\n\n/** `G9ESubscriptionState`. */\nexport const G9ESubscriptionState = {\n Active: 0,\n NeedsReconcile: 1,\n Failed: 2,\n} as const;\nexport type G9ESubscriptionState = (typeof G9ESubscriptionState)[keyof typeof G9ESubscriptionState];\n\n/** A local subscription (`G9CSyncSubscriptionRecord`). Times are epoch milliseconds UTC. */\nexport interface G9SyncSubscriptionRecord {\n key: string;\n name: string;\n parameters: G9SyncParameters;\n /** Membership slot (bit) for persistent subscriptions; the shared ephemeral slot otherwise. */\n slot: number;\n ephemeral: boolean;\n ttlMs: number | null;\n cursor: string | null;\n /** The move-out policy the server last announced; kept so it still applies once access is gone. */\n moveOutPolicy: G9EMoveOutPolicy | null;\n definitionHash: string | null;\n authHash: string | null;\n state: G9ESubscriptionState;\n lastErrorCode: string | null;\n createdUtcMs: number;\n lastSuccessUtcMs: number | null;\n lastReconcileUtcMs: number | null;\n lastAccessUtcMs: number | null;\n}\n\n/** `G9CSyncSubscriptionRecord.ToReference()`. */\nexport function toSubscriptionRef(record: G9SyncSubscriptionRecord): G9DtSubscriptionRef {\n return {\n name: record.name,\n parameters: record.parameters.values,\n cursor: record.cursor,\n definitionHash: record.definitionHash,\n authHash: record.authHash,\n };\n}\n\n/** A partial update of a subscription record; absent members are left unchanged (`G9CSubscriptionUpdate`). */\nexport interface G9SubscriptionUpdate {\n cursor?: string | null;\n definitionHash?: string | null;\n authHash?: string | null;\n state?: G9ESubscriptionState | null;\n errorCode?: string | null;\n clearError?: boolean;\n succeeded?: boolean;\n reconciled?: boolean;\n accessed?: boolean;\n clearCursor?: boolean;\n}\n\n// ---------------------------------------------------------------- push and pull\n\n/** A push batch built from dirty rows (`G9CPushBatch`). */\nexport interface G9PushBatch {\n batchId: number;\n /** Highest local change sequence included; rows changed after it stay dirty after the acknowledgement. */\n maxSequence: number;\n frames: Uint8Array[];\n tables: G9DtTableColumns[];\n rowCount: number;\n /** True when the byte budget ended the batch early: more pending rows follow. */\n truncated: boolean;\n /** Rows rejected on the device while building the batch (G9S-REJ-TOO-LARGE). */\n rejectedLocally: number;\n /** Commands carried by this batch, in device order. */\n commands: G9DtCommand[];\n}\n\n/** A pull being staged, persisted across restarts (`G9CStagedPull`). */\nexport interface G9StagedPull {\n runId: string;\n plan: G9DtPullPlan;\n createdUtcMs: number;\n backfills: G9DtBackfillRequest[];\n /** What the world looked like when the plan was made (ADR-0046); a run only resumes a stage whose generation matches. */\n generation: string | null;\n /** The cursor each planned subscription had when the plan was made, by subscription key (ADR-0060). */\n plannedFromCursors: { [subscriptionKey: string]: string | null };\n /** The device clock when the stage began, assigned by the store. */\n stageSequence: number;\n}\n\n/** One committed slice of a staged pull (`G9CApplySlice`). */\nexport interface G9ApplySlice {\n report: G9ApplyReport;\n rowsApplied: number;\n rowsAppliedTotal: number;\n rowsPlanned: number;\n isFinal: boolean;\n}\n\n/** `G9CResumePoint`. */\nexport interface G9ResumePoint {\n continuation: G9DtPullContinuation | null;\n stagedRows: number;\n stagedBytes: number;\n complete: boolean;\n}\n\n// ---------------------------------------------------------------- reports\n\n/** Why a table large enough for index deferral kept its indexes live. */\nexport const REASON_TABLE_NOT_EMPTY = 'table-not-empty';\nconst MAX_FOREIGN_TRIGGER_NAMES = 10;\n\n/** How an apply ran, as opposed to what it changed (`G9CApplyDiagnostics`, ADR-0058). */\nexport class G9ApplyDiagnostics {\n transactions = 0;\n transactionsWithTriggersSkipped = 0;\n readonly foreignTriggers: string[] = [];\n readonly deferredIndexes: { [table: string]: number } = {};\n readonly liveIndexReasons: { [table: string]: string } = {};\n readonly rowsByTable: { [table: string]: number } = {};\n readonly msByTable: { [table: string]: number } = {};\n indexRebuildMs = 0;\n elapsedMs = 0;\n\n /** True when every transaction ran with trigger execution off, false when any ran with it on, null when nothing was applied. */\n get triggersSkipped(): boolean | null {\n return this.transactions === 0 ? null : this.transactionsWithTriggersSkipped === this.transactions;\n }\n\n get deferredIndexCount(): number {\n let total = 0;\n for (const key of Object.keys(this.deferredIndexes)) total += this.deferredIndexes[key] as number;\n return total;\n }\n\n merge(other: G9ApplyDiagnostics): void {\n this.transactions += other.transactions;\n this.transactionsWithTriggersSkipped += other.transactionsWithTriggersSkipped;\n this.indexRebuildMs += other.indexRebuildMs;\n this.elapsedMs += other.elapsedMs;\n for (const name of other.foreignTriggers) {\n if (this.foreignTriggers.length >= MAX_FOREIGN_TRIGGER_NAMES) break;\n if (!this.foreignTriggers.some((n) => n.toLowerCase() === name.toLowerCase())) this.foreignTriggers.push(name);\n }\n addAll(this.deferredIndexes, other.deferredIndexes);\n for (const key of Object.keys(other.liveIndexReasons)) this.liveIndexReasons[key] = other.liveIndexReasons[key] as string;\n addAll(this.rowsByTable, other.rowsByTable);\n addAll(this.msByTable, other.msByTable);\n }\n\n /** One line for a log: what engaged, what did not and why, and the tables that took the time. */\n toString(): string {\n if (this.transactions === 0) return 'nothing applied';\n let text = `${this.transactions} transaction(s) in ${this.elapsedMs} ms; triggers `;\n text +=\n this.triggersSkipped === true\n ? 'skipped'\n : this.transactionsWithTriggersSkipped === 0\n ? 'LIVE'\n : `skipped in ${this.transactionsWithTriggersSkipped} of ${this.transactions}`;\n if (this.foreignTriggers.length > 0) text += ' (foreign: ' + this.foreignTriggers.join(', ') + ')';\n const deferred = Object.keys(this.deferredIndexes);\n if (deferred.length > 0) {\n text += `; ${this.deferredIndexCount} index(es) rebuilt after the load in ${this.indexRebuildMs} ms (` + deferred.map((t) => t + ':' + this.deferredIndexes[t]).join(', ') + ')';\n }\n const live = Object.keys(this.liveIndexReasons);\n if (live.length > 0) text += '; live indexes on ' + live.map((t) => t + ' (' + this.liveIndexReasons[t] + ')').join(', ');\n const slowest = Object.keys(this.msByTable)\n .sort((a, b) => (this.msByTable[b] as number) - (this.msByTable[a] as number))\n .slice(0, 4);\n if (slowest.length > 0) {\n text +=\n '; ' +\n slowest\n .map((t) => {\n const ms = this.msByTable[t] as number;\n const rows = this.rowsByTable[t] ?? 0;\n const rate = ms > 0 ? Math.floor((rows * 1000) / ms) : rows;\n return `${t} ${rows} rows in ${ms} ms (${rate}/s)`;\n })\n .join(', ');\n }\n return text;\n }\n}\n\nfunction addAll(target: { [key: string]: number }, source: { [key: string]: number }): void {\n for (const key of Object.keys(source)) target[key] = (target[key] ?? 0) + (source[key] as number);\n}\n\n/** What an apply changed (`G9CApplyReport`). */\nexport class G9ApplyReport {\n upserts = 0;\n deletes = 0;\n moveOuts = 0;\n membershipAdded = 0;\n /** Rows skipped because they carry a pending local change. */\n skippedDirty = 0;\n accepted = 0;\n rejected = 0;\n conflicts = 0;\n commandsCompleted = 0;\n revokedDeleted = 0;\n revokedQuarantined = 0;\n revokedRetained = 0;\n /** Changed keys per local table (capped per table). */\n readonly changedKeys: { [localTable: string]: string[] } = {};\n /** Upserts whose row already held exactly the incoming values (ADR-0058). */\n unchangedRows = 0;\n readonly diagnostics = new G9ApplyDiagnostics();\n\n get total(): number {\n return this.upserts + this.deletes + this.moveOuts;\n }\n\n merge(other: G9ApplyReport): void {\n this.unchangedRows += other.unchangedRows;\n this.diagnostics.merge(other.diagnostics);\n this.upserts += other.upserts;\n this.deletes += other.deletes;\n this.moveOuts += other.moveOuts;\n this.membershipAdded += other.membershipAdded;\n this.skippedDirty += other.skippedDirty;\n this.accepted += other.accepted;\n this.rejected += other.rejected;\n this.conflicts += other.conflicts;\n this.commandsCompleted += other.commandsCompleted;\n this.revokedDeleted += other.revokedDeleted;\n this.revokedQuarantined += other.revokedQuarantined;\n this.revokedRetained += other.revokedRetained;\n for (const table of Object.keys(other.changedKeys)) {\n const list = this.changedKeys[table] ?? (this.changedKeys[table] = []);\n for (const key of other.changedKeys[table] as string[]) list.push(key);\n }\n }\n}\n\n/** A local row as seen by reconciliation (`G9CLocalRowEntry`). */\nexport interface G9LocalRowEntry {\n key: string;\n bucket: number;\n version: number;\n hash: G9Long;\n member: boolean;\n dirty: boolean;\n}\n\nexport interface G9PendingTable {\n localTable: string;\n upserts: number;\n deletes: number;\n rejected: number;\n}\n\nexport interface G9PendingSummary {\n totalRows: number;\n rejectedRows: number;\n /** Commands recorded on the device and not yet executed by the server. */\n pendingCommands: number;\n tables: G9PendingTable[];\n}\n\n/** One entry of the local change feed (`G9CChangeFeedEntry`). */\nexport interface G9ChangeFeedEntry {\n sequence: number;\n key: string;\n deleted: boolean;\n localPending: boolean;\n}\n\nexport interface G9SyncRejection {\n localTable: string;\n key: string;\n code: string;\n message: string | null;\n sqlState: string | null;\n constraint: string | null;\n column: string | null;\n details: string | null;\n atUtcMs: number;\n}\n\n/** A persisted summary of one run (`G9CSyncRunReport`); serialized with the .NET JSON names into g9_runs. */\nexport interface G9SyncRunReport {\n runId: string;\n startedUtcMs: number;\n durationMs: number;\n outcome: string;\n priority: string;\n errorCode: string | null;\n errorMessage: string | null;\n pushed: number;\n rejected: number;\n conflicts: number;\n downloaded: number;\n applied: number;\n downloadedBytes: number;\n subscriptions: string[];\n phaseMs: { [phase: string]: number };\n triggersSkipped: boolean | null;\n foreignTriggers: string[];\n applyTransactions: number;\n indexesDeferred: number;\n indexRebuildMs: number;\n liveIndexReasons: { [table: string]: string };\n unchangedRows: number;\n}\n\n// ---------------------------------------------------------------- local commands (ADR-0025)\n\n/** `G9ELocalCommandState`. */\nexport const G9ELocalCommandState = {\n Pending: 0,\n Ok: 1,\n Rejected: 2,\n Superseded: 3,\n} as const;\nexport type G9ELocalCommandState = (typeof G9ELocalCommandState)[keyof typeof G9ELocalCommandState];\n\n/** A command recorded on this device (`G9CLocalCommand`). */\nexport interface G9LocalCommand {\n commandId: string;\n sequence: number;\n name: string;\n version: number;\n payload: string;\n createdUtcMs: number;\n state: G9ELocalCommandState;\n code: string | null;\n message: string | null;\n result: string | null;\n completedUtcMs: number | null;\n}\n\n/** What to record (`G9CCommandRequest`). */\nexport interface G9CommandRequest {\n name: string;\n version?: number;\n /** JSON payload for the server's handler. */\n payload: string;\n}\n\n/** A value an app binds through {@link G9LocalCommandWriter}: the SQLite driver's value forms, plus booleans. */\nexport type G9LocalSqlArgument = null | number | string | boolean | ArrayBuffer | Uint8Array | { int64: string } | G9Long;\n\n/**\n * Writes a command's local effects in the transaction that records it (`IG9LocalCommandWriter`). Rows written here are\n * not uploaded as row changes; they are protected from pulls until the server's result arrives.\n */\nexport interface G9LocalCommandWriter {\n /** Executes SQL; parameters bind positionally as `$p0`, `$p1`, … */\n execute(sql: string, ...args: G9LocalSqlArgument[]): Promise<number>;\n scalar(sql: string, ...args: G9LocalSqlArgument[]): Promise<unknown>;\n}\n\n// ---------------------------------------------------------------- revocation (ADR-0026)\n\n/** `G9ERevocationReason`. */\nexport const G9ERevocationReason = {\n LeftScope: 0,\n Unsubscribed: 1,\n Expired: 2,\n AccessRevoked: 3,\n} as const;\nexport type G9ERevocationReason = (typeof G9ERevocationReason)[keyof typeof G9ERevocationReason];\n\n/** `G9ERevocationDisposition`. */\nexport const G9ERevocationDisposition = {\n Delete: 0,\n MarkRevoked: 1,\n Quarantine: 2,\n Retain: 3,\n} as const;\nexport type G9ERevocationDisposition = (typeof G9ERevocationDisposition)[keyof typeof G9ERevocationDisposition];\n\n/** A row no subscription holds any more, as a revocation rule sees it (`G9CRevokedRow`). */\nexport interface G9RevokedRow {\n localTable: string;\n key: string;\n reason: G9ERevocationReason;\n subscriptionKey: string | null;\n hasPendingChanges: boolean;\n isRejected: boolean;\n /** Column values (key included) as stored locally; empty when the row no longer exists locally. */\n values: { [column: string]: unknown };\n}\n\n/** Lets a custom rule change the row before its disposition applies. */\nexport interface G9RevokedRowEditor {\n set(column: string, value: unknown): void;\n}\n\nexport interface G9RevocationRule {\n readonly name: string;\n readonly condition: (row: G9RevokedRow) => boolean;\n readonly decide: (row: G9RevokedRow, editor: G9RevokedRowEditor) => G9ERevocationDisposition;\n readonly retainWhile: ((row: G9RevokedRow) => boolean) | null;\n}\n\n/** Ordered revocation rules (`G9CRevocationPolicy`): the first matching rule decides. */\nexport class G9RevocationPolicy {\n readonly rules: readonly G9RevocationRule[];\n\n private constructor(rules: readonly G9RevocationRule[]) {\n this.rules = rules;\n }\n\n /** No rules: delete clean rows, quarantine rows with pending changes. */\n static readonly default = new G9RevocationPolicy([]);\n\n static create(configure: (builder: G9RevocationPolicyBuilder) => void): G9RevocationPolicy {\n const builder = new G9RevocationPolicyBuilder();\n configure(builder);\n return new G9RevocationPolicy(builder.rules.slice());\n }\n\n decide(row: G9RevokedRow, editor: G9RevokedRowEditor): { rule: G9RevocationRule | null; disposition: G9ERevocationDisposition } {\n for (const rule of this.rules) {\n if (rule.condition(row)) return { rule, disposition: rule.decide(row, editor) };\n }\n return { rule: null, disposition: row.hasPendingChanges ? G9ERevocationDisposition.Quarantine : G9ERevocationDisposition.Delete };\n }\n\n find(name: string): G9RevocationRule | null {\n for (const rule of this.rules) if (rule.name === name) return rule;\n return null;\n }\n}\n\nexport class G9RevocationPolicyBuilder {\n readonly rules: G9RevocationRule[] = [];\n\n when(name: string, condition: (row: G9RevokedRow) => boolean): G9RevocationActionBuilder {\n if (typeof name !== 'string' || name.trim() === '') throw new TypeError('A rule needs a name.');\n if (this.rules.some((r) => r.name === name)) throw new RangeError(`Revocation rule '${name}' is declared twice.`);\n return new G9RevocationActionBuilder(this, name, condition);\n }\n\n /** Rows of one local table. */\n forTable(name: string, localTable: string, condition?: (row: G9RevokedRow) => boolean): G9RevocationActionBuilder {\n const table = localTable.toLowerCase();\n return this.when(name, (row) => row.localTable.toLowerCase() === table && (condition ? condition(row) : true));\n }\n}\n\nexport class G9RevocationActionBuilder {\n private readonly _owner: G9RevocationPolicyBuilder;\n private readonly _name: string;\n private readonly _condition: (row: G9RevokedRow) => boolean;\n\n constructor(owner: G9RevocationPolicyBuilder, name: string, condition: (row: G9RevokedRow) => boolean) {\n this._owner = owner;\n this._name = name;\n this._condition = condition;\n }\n\n delete(): G9RevocationPolicyBuilder {\n return this._add(() => G9ERevocationDisposition.Delete, null);\n }\n\n markRevoked(): G9RevocationPolicyBuilder {\n return this._add(() => G9ERevocationDisposition.MarkRevoked, null);\n }\n\n quarantine(): G9RevocationPolicyBuilder {\n return this._add(() => G9ERevocationDisposition.Quarantine, null);\n }\n\n retainWhile(retainWhile: (row: G9RevokedRow) => boolean): G9RevocationPolicyBuilder {\n return this._add(() => G9ERevocationDisposition.Retain, retainWhile);\n }\n\n custom(decide: (row: G9RevokedRow, editor: G9RevokedRowEditor) => G9ERevocationDisposition): G9RevocationPolicyBuilder {\n return this._add(decide, null);\n }\n\n private _add(\n decide: (row: G9RevokedRow, editor: G9RevokedRowEditor) => G9ERevocationDisposition,\n retainWhile: ((row: G9RevokedRow) => boolean) | null,\n ): G9RevocationPolicyBuilder {\n this._owner.rules.push({ name: this._name, condition: this._condition, decide, retainWhile });\n return this._owner;\n }\n}\n\n/** A row in the holding area (`G9CQuarantinedRow`). */\nexport interface G9QuarantinedRow {\n localTable: string;\n key: string;\n reason: G9ERevocationReason;\n rule: string | null;\n hadPendingChanges: boolean;\n values: { [column: string]: unknown };\n atUtcMs: number;\n}\n\n/** A row kept in the app's table after revocation (`G9CRetainedRow`). */\nexport interface G9RetainedRow {\n localTable: string;\n key: string;\n disposition: G9ERevocationDisposition;\n reason: G9ERevocationReason;\n rule: string | null;\n atUtcMs: number;\n}\n\n// ---------------------------------------------------------------- failures\n\n/** What went wrong inside a client store, in terms an application can act on (`G9ELocalStoreFailure`). */\nexport const G9ELocalStoreFailure = {\n Other: 0,\n Corrupt: 1,\n DiskFull: 2,\n Busy: 3,\n} as const;\nexport type G9ELocalStoreFailure = (typeof G9ELocalStoreFailure)[keyof typeof G9ELocalStoreFailure];\n\n/** Implemented by a store's errors so the engine can give a run's failure a stable code (`IG9SyncLocalStoreFailure`). */\nexport interface G9SyncLocalStoreFailure {\n readonly localStoreFailure: G9ELocalStoreFailure;\n}\n\nexport function isLocalStoreFailure(error: unknown): error is G9SyncLocalStoreFailure {\n return typeof error === 'object' && error !== null && typeof (error as { localStoreFailure?: unknown }).localStoreFailure === 'number';\n}\n\n// ---------------------------------------------------------------- the store contract\n\n/**\n * The client storage provider (`IG9SyncClientStore`): local tables, change capture, subscription membership,\n * staging, apply and metadata. Every method takes an optional AbortSignal (the CancellationToken twin).\n */\nexport interface G9SyncClientStore {\n initialize(model: G9SyncClientModel, signal?: AbortSignal): Promise<void>;\n getClientId(signal?: AbortSignal): Promise<string>;\n getServerState(signal?: AbortSignal): Promise<G9ClientServerState>;\n saveHello(hello: G9DtHelloResult, signal?: AbortSignal): Promise<void>;\n getPendingBackfills(signal?: AbortSignal): Promise<G9DtBackfillRequest[]>;\n\n getSubscriptions(signal?: AbortSignal): Promise<G9SyncSubscriptionRecord[]>;\n ensureSubscription(\n name: string,\n parameters: G9SyncParameters,\n ephemeral: boolean,\n ttlMs: number | null,\n adoptExistingRows: boolean,\n signal?: AbortSignal,\n ): Promise<G9SyncSubscriptionRecord>;\n removeSubscription(key: string, policy: G9EMoveOutPolicy, signal?: AbortSignal): Promise<void>;\n releaseSubscriptionRows(key: string, signal?: AbortSignal): Promise<G9ApplyReport>;\n updateSubscription(key: string, update: G9SubscriptionUpdate, signal?: AbortSignal): Promise<void>;\n collectExpiredEphemeral(utcNowMs: number, signal?: AbortSignal): Promise<number>;\n\n buildPushBatch(tables: readonly G9DtNegotiatedTable[], maxRows: number, maxBytes: number, signal?: AbortSignal): Promise<G9PushBatch | null>;\n forgetUploadedRows(localTable: string, keys: readonly string[] | null, signal?: AbortSignal): Promise<number>;\n applyPushResult(batch: G9PushBatch, result: G9DtPushResult, signal?: AbortSignal): Promise<G9ApplyReport>;\n\n getStagedPull(signal?: AbortSignal): Promise<G9StagedPull | null>;\n /** The newest staged pull planned under exactly this generation, or null (ADR-0060). */\n getStagedPullForGeneration(generation: string, signal?: AbortSignal): Promise<G9StagedPull | null>;\n beginStagedPull(pull: G9StagedPull, signal?: AbortSignal): Promise<void>;\n pruneStagedPulls(olderThanUtcMs: number, maxBytes: number, keepGeneration: string | null, signal?: AbortSignal): Promise<number>;\n discardAllStagedPulls(signal?: AbortSignal): Promise<number>;\n stageChunk(runId: string, chunk: G9DtSyncChunk, signal?: AbortSignal): Promise<void>;\n getResumePoint(runId: string, signal?: AbortSignal): Promise<G9ResumePoint>;\n applyStagedPull(\n runId: string,\n rowsApplied: ((rows: number) => void) | null,\n slices: ((slice: G9ApplySlice) => void) | null,\n signal?: AbortSignal,\n ): Promise<G9ApplyReport>;\n discardStagedPull(runId: string, signal?: AbortSignal): Promise<void>;\n\n computeDigest(subscriptionKey: string, table: G9DtNegotiatedTable, signal?: AbortSignal): Promise<G9DtTableDigest>;\n readLocalEntries(\n subscriptionKey: string,\n table: G9DtNegotiatedTable,\n buckets: ReadonlySet<number>,\n serverKeys: ReadonlySet<string>,\n signal?: AbortSignal,\n ): Promise<G9LocalRowEntry[]>;\n applyReconcile(\n subscriptionKey: string,\n table: G9DtNegotiatedTable,\n fetchedFrames: readonly Uint8Array[],\n addMembership: readonly string[],\n moveOut: readonly string[],\n policy: G9EMoveOutPolicy,\n signal?: AbortSignal,\n ): Promise<G9ApplyReport>;\n\n getPendingSummary(signal?: AbortSignal): Promise<G9PendingSummary>;\n enqueueCommand(\n request: G9CommandRequest,\n applyLocally: ((writer: G9LocalCommandWriter, signal?: AbortSignal) => Promise<void>) | null,\n signal?: AbortSignal,\n ): Promise<G9LocalCommand>;\n getQuarantined(signal?: AbortSignal): Promise<G9QuarantinedRow[]>;\n restoreQuarantined(localTable: string, key: string, signal?: AbortSignal): Promise<number>;\n discardQuarantined(localTable: string | null, key: string | null, signal?: AbortSignal): Promise<number>;\n getRetained(signal?: AbortSignal): Promise<G9RetainedRow[]>;\n reevaluateRetained(signal?: AbortSignal): Promise<number>;\n getCommands(state: G9ELocalCommandState | null, limit: number, signal?: AbortSignal): Promise<G9LocalCommand[]>;\n readChangeFeed(localTable: string, afterSequence: number, limit: number, signal?: AbortSignal): Promise<G9ChangeFeedEntry[]>;\n getChangeSequence(signal?: AbortSignal): Promise<number>;\n getChangeFeedFloor(signal?: AbortSignal): Promise<number>;\n getRejections(signal?: AbortSignal): Promise<G9SyncRejection[]>;\n retryRejected(localTable: string | null, key: string | null, signal?: AbortSignal): Promise<number>;\n markDirty(localTable: string, keys: readonly string[], signal?: AbortSignal): Promise<number>;\n adoptExistingRows(signal?: AbortSignal): Promise<number>;\n saveRunReport(report: G9SyncRunReport, keep: number, signal?: AbortSignal): Promise<void>;\n getRecentRunReports(count: number, signal?: AbortSignal): Promise<G9SyncRunReport[]>;\n getPhaseStatistics(signal?: AbortSignal): Promise<{ [key: string]: number }>;\n recordPhaseStatistics(samples: { [key: string]: number }, signal?: AbortSignal): Promise<void>;\n purgeDeletedFeed(keep: number, signal?: AbortSignal): Promise<number>;\n dispose(): Promise<void>;\n}\n"]}
|
|
1
|
+
{"version":3,"file":"storeTypes.js","sourceRoot":"","sources":["../../src/client/stor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E,IAAI,CAAC,KAAK,EAAE,SAAS,EAAE,IAAI,CAAC,UAAU,EAAE,MAAM,EAAE,WAAW,EAAE,CAAC,CAAC;QAC9F,OAAO,IAAI,CAAC,MAAM,CAAC;IACrB,CAAC;CACF;AAuBD,4EAA4E;AAE5E,0GAA0G;AAC1G,MAAM,CAAC,MAAM,oBAAoB,GAAG;IAClC,KAAK,EAAE,CAAC;IACR,OAAO,EAAE,CAAC;IACV,QAAQ,EAAE,CAAC;IACX,IAAI,EAAE,CAAC;CACC,CAAC;AAQX,MAAM,UAAU,mBAAmB,CAAC,KAAc;IAChD,OAAO,OAAO,KAAK,KAAK,QAAQ,IAAI,KAAK,KAAK,IAAI,IAAI,OAAQ,KAAyC,CAAC,iBAAiB,KAAK,QAAQ,CAAC;AACzI,CAAC","sourcesContent":["// Twins of G9SyncData.Client/Storage/*.cs: the client store contract, its records, local commands, revocation rules\n// and apply diagnostics. The engine is store-agnostic; `@g9tm/syncdata/sqlite` is the implementation.\nimport type { G9EMoveOutPolicy } from '../abstractions/enums.js';\nimport type { G9Long } from '../abstractions/long.js';\nimport type { G9SyncParameters } from '../abstractions/parameters.js';\nimport type {\n G9DtBackfillRequest,\n G9DtCommand,\n G9DtHelloResult,\n G9DtNegotiatedTable,\n G9DtPullContinuation,\n G9DtPullPlan,\n G9DtPushResult,\n G9DtSnapshotFileRequest,\n G9DtSubscriptionDefinition,\n G9DtSubscriptionRef,\n G9DtSyncChunk,\n G9DtTableColumns,\n G9DtTableDigest,\n} from '../protocol/dtos.js';\nimport type { G9SyncClientModel } from './model.js';\n\n// ---------------------------------------------------------------- server state and subscriptions\n\n/** What the client last learned from the server (`G9CClientServerState`). */\nexport interface G9ClientServerState {\n epoch: string | null;\n lastHelloUtcMs: number | null;\n /** Server clock minus device clock, ms. */\n serverClockOffsetMs: number;\n tables: G9DtNegotiatedTable[];\n definitions: G9DtSubscriptionDefinition[];\n}\n\n/** `G9ESubscriptionState`. */\nexport const G9ESubscriptionState = {\n Active: 0,\n NeedsReconcile: 1,\n Failed: 2,\n} as const;\nexport type G9ESubscriptionState = (typeof G9ESubscriptionState)[keyof typeof G9ESubscriptionState];\n\n/** A local subscription (`G9CSyncSubscriptionRecord`). Times are epoch milliseconds UTC. */\nexport interface G9SyncSubscriptionRecord {\n key: string;\n name: string;\n parameters: G9SyncParameters;\n /** Membership slot (bit) for persistent subscriptions; the shared ephemeral slot otherwise. */\n slot: number;\n ephemeral: boolean;\n ttlMs: number | null;\n cursor: string | null;\n /** The move-out policy the server last announced; kept so it still applies once access is gone. */\n moveOutPolicy: G9EMoveOutPolicy | null;\n definitionHash: string | null;\n authHash: string | null;\n state: G9ESubscriptionState;\n lastErrorCode: string | null;\n createdUtcMs: number;\n lastSuccessUtcMs: number | null;\n lastReconcileUtcMs: number | null;\n lastAccessUtcMs: number | null;\n}\n\n/** `G9CSyncSubscriptionRecord.ToReference()`. */\nexport function toSubscriptionRef(record: G9SyncSubscriptionRecord): G9DtSubscriptionRef {\n return {\n name: record.name,\n parameters: record.parameters.values,\n cursor: record.cursor,\n definitionHash: record.definitionHash,\n authHash: record.authHash,\n };\n}\n\n/** A partial update of a subscription record; absent members are left unchanged (`G9CSubscriptionUpdate`). */\nexport interface G9SubscriptionUpdate {\n cursor?: string | null;\n definitionHash?: string | null;\n authHash?: string | null;\n state?: G9ESubscriptionState | null;\n errorCode?: string | null;\n clearError?: boolean;\n succeeded?: boolean;\n reconciled?: boolean;\n accessed?: boolean;\n clearCursor?: boolean;\n}\n\n// ---------------------------------------------------------------- push and pull\n\n/** A push batch built from dirty rows (`G9CPushBatch`). */\nexport interface G9PushBatch {\n batchId: number;\n /** Highest local change sequence included; rows changed after it stay dirty after the acknowledgement. */\n maxSequence: number;\n frames: Uint8Array[];\n tables: G9DtTableColumns[];\n rowCount: number;\n /** True when the byte budget ended the batch early: more pending rows follow. */\n truncated: boolean;\n /** Rows rejected on the device while building the batch (G9S-REJ-TOO-LARGE). */\n rejectedLocally: number;\n /** Commands carried by this batch, in device order. */\n commands: G9DtCommand[];\n}\n\n/** A pull being staged, persisted across restarts (`G9CStagedPull`). */\nexport interface G9StagedPull {\n runId: string;\n plan: G9DtPullPlan;\n createdUtcMs: number;\n backfills: G9DtBackfillRequest[];\n /** What the world looked like when the plan was made (ADR-0046); a run only resumes a stage whose generation matches. */\n generation: string | null;\n /** The cursor each planned subscription had when the plan was made, by subscription key (ADR-0060). */\n plannedFromCursors: { [subscriptionKey: string]: string | null };\n /** The device clock when the stage began, assigned by the store. */\n stageSequence: number;\n}\n\n/** One committed slice of a staged pull (`G9CApplySlice`). */\nexport interface G9ApplySlice {\n report: G9ApplyReport;\n rowsApplied: number;\n rowsAppliedTotal: number;\n rowsPlanned: number;\n isFinal: boolean;\n}\n\n/** `G9CResumePoint`. */\nexport interface G9ResumePoint {\n continuation: G9DtPullContinuation | null;\n stagedRows: number;\n stagedBytes: number;\n complete: boolean;\n}\n\n// ---------------------------------------------------------------- reports\n\n/** Why a table large enough for index deferral kept its indexes live. */\nexport const REASON_TABLE_NOT_EMPTY = 'table-not-empty';\nconst MAX_FOREIGN_TRIGGER_NAMES = 10;\n\n/** How an apply ran, as opposed to what it changed (`G9CApplyDiagnostics`, ADR-0058). */\n/** A file table copied record for record into an empty table with identical columns (the transfer optimisation). */\nexport const FILE_MODE_COPY = 'copy';\n/** A file table copied into an empty table by column name. */\nexport const FILE_MODE_COLUMNS = 'columns';\n/** A file table merged into a table that held rows or protected rows: changed rows only. */\nexport const FILE_MODE_MERGE = 'merge';\n\nexport class G9ApplyDiagnostics {\n transactions = 0;\n transactionsWithTriggersSkipped = 0;\n readonly foreignTriggers: string[] = [];\n readonly deferredIndexes: { [table: string]: number } = {};\n readonly liveIndexReasons: { [table: string]: string } = {};\n readonly rowsByTable: { [table: string]: number } = {};\n readonly msByTable: { [table: string]: number } = {};\n indexRebuildMs = 0;\n elapsedMs = 0;\n /** Snapshot files copied in (ADR-0072). */\n snapshotFiles = 0;\n /** Rows that arrived through snapshot files. */\n fileRows = 0;\n /** Milliseconds spent copying snapshot files, metadata included. */\n fileCopyMs = 0;\n /** How each table came out of a snapshot file: `copy`, `columns` or `merge` (see FILE_MODE_*). */\n readonly fileTables: { [table: string]: string } = {};\n\n /** True when every transaction ran with trigger execution off, false when any ran with it on, null when nothing was applied. */\n get triggersSkipped(): boolean | null {\n return this.transactions === 0 ? null : this.transactionsWithTriggersSkipped === this.transactions;\n }\n\n get deferredIndexCount(): number {\n let total = 0;\n for (const key of Object.keys(this.deferredIndexes)) total += this.deferredIndexes[key] as number;\n return total;\n }\n\n merge(other: G9ApplyDiagnostics): void {\n this.transactions += other.transactions;\n this.transactionsWithTriggersSkipped += other.transactionsWithTriggersSkipped;\n this.indexRebuildMs += other.indexRebuildMs;\n this.elapsedMs += other.elapsedMs;\n this.snapshotFiles += other.snapshotFiles;\n this.fileRows += other.fileRows;\n this.fileCopyMs += other.fileCopyMs;\n for (const key of Object.keys(other.fileTables)) this.fileTables[key] = other.fileTables[key] as string;\n for (const name of other.foreignTriggers) {\n if (this.foreignTriggers.length >= MAX_FOREIGN_TRIGGER_NAMES) break;\n if (!this.foreignTriggers.some((n) => n.toLowerCase() === name.toLowerCase())) this.foreignTriggers.push(name);\n }\n addAll(this.deferredIndexes, other.deferredIndexes);\n for (const key of Object.keys(other.liveIndexReasons)) this.liveIndexReasons[key] = other.liveIndexReasons[key] as string;\n addAll(this.rowsByTable, other.rowsByTable);\n addAll(this.msByTable, other.msByTable);\n }\n\n /** One line for a log: what engaged, what did not and why, and the tables that took the time. */\n toString(): string {\n if (this.transactions === 0) return 'nothing applied';\n let text = `${this.transactions} transaction(s) in ${this.elapsedMs} ms; triggers `;\n text +=\n this.triggersSkipped === true\n ? 'skipped'\n : this.transactionsWithTriggersSkipped === 0\n ? 'LIVE'\n : `skipped in ${this.transactionsWithTriggersSkipped} of ${this.transactions}`;\n if (this.foreignTriggers.length > 0) text += ' (foreign: ' + this.foreignTriggers.join(', ') + ')';\n const deferred = Object.keys(this.deferredIndexes);\n if (deferred.length > 0) {\n text += `; ${this.deferredIndexCount} index(es) rebuilt after the load in ${this.indexRebuildMs} ms (` + deferred.map((t) => t + ':' + this.deferredIndexes[t]).join(', ') + ')';\n }\n const live = Object.keys(this.liveIndexReasons);\n if (live.length > 0) text += '; live indexes on ' + live.map((t) => t + ' (' + this.liveIndexReasons[t] + ')').join(', ');\n if (this.snapshotFiles > 0) {\n text +=\n `; ${this.snapshotFiles} snapshot file(s), ${this.fileRows} rows copied in ${this.fileCopyMs} ms (` +\n Object.keys(this.fileTables)\n .map((t) => t + ':' + this.fileTables[t])\n .join(', ') +\n ')';\n }\n const slowest = Object.keys(this.msByTable)\n .sort((a, b) => (this.msByTable[b] as number) - (this.msByTable[a] as number))\n .slice(0, 4);\n if (slowest.length > 0) {\n text +=\n '; ' +\n slowest\n .map((t) => {\n const ms = this.msByTable[t] as number;\n const rows = this.rowsByTable[t] ?? 0;\n const rate = ms > 0 ? Math.floor((rows * 1000) / ms) : rows;\n return `${t} ${rows} rows in ${ms} ms (${rate}/s)`;\n })\n .join(', ');\n }\n return text;\n }\n}\n\nfunction addAll(target: { [key: string]: number }, source: { [key: string]: number }): void {\n for (const key of Object.keys(source)) target[key] = (target[key] ?? 0) + (source[key] as number);\n}\n\n/** What an apply changed (`G9CApplyReport`). */\nexport class G9ApplyReport {\n upserts = 0;\n deletes = 0;\n moveOuts = 0;\n membershipAdded = 0;\n /** Rows skipped because they carry a pending local change. */\n skippedDirty = 0;\n accepted = 0;\n rejected = 0;\n conflicts = 0;\n commandsCompleted = 0;\n revokedDeleted = 0;\n revokedQuarantined = 0;\n revokedRetained = 0;\n /** Changed keys per local table (capped per table). */\n readonly changedKeys: { [localTable: string]: string[] } = {};\n /** Upserts whose row already held exactly the incoming values (ADR-0058). */\n unchangedRows = 0;\n readonly diagnostics = new G9ApplyDiagnostics();\n\n get total(): number {\n return this.upserts + this.deletes + this.moveOuts;\n }\n\n merge(other: G9ApplyReport): void {\n this.unchangedRows += other.unchangedRows;\n this.diagnostics.merge(other.diagnostics);\n this.upserts += other.upserts;\n this.deletes += other.deletes;\n this.moveOuts += other.moveOuts;\n this.membershipAdded += other.membershipAdded;\n this.skippedDirty += other.skippedDirty;\n this.accepted += other.accepted;\n this.rejected += other.rejected;\n this.conflicts += other.conflicts;\n this.commandsCompleted += other.commandsCompleted;\n this.revokedDeleted += other.revokedDeleted;\n this.revokedQuarantined += other.revokedQuarantined;\n this.revokedRetained += other.revokedRetained;\n for (const table of Object.keys(other.changedKeys)) {\n const list = this.changedKeys[table] ?? (this.changedKeys[table] = []);\n for (const key of other.changedKeys[table] as string[]) list.push(key);\n }\n }\n}\n\n/** A local row as seen by reconciliation (`G9CLocalRowEntry`). */\nexport interface G9LocalRowEntry {\n key: string;\n bucket: number;\n version: number;\n hash: G9Long;\n member: boolean;\n dirty: boolean;\n}\n\nexport interface G9PendingTable {\n localTable: string;\n upserts: number;\n deletes: number;\n rejected: number;\n}\n\nexport interface G9PendingSummary {\n totalRows: number;\n rejectedRows: number;\n /** Commands recorded on the device and not yet executed by the server. */\n pendingCommands: number;\n tables: G9PendingTable[];\n}\n\n/** One entry of the local change feed (`G9CChangeFeedEntry`). */\nexport interface G9ChangeFeedEntry {\n sequence: number;\n key: string;\n deleted: boolean;\n localPending: boolean;\n}\n\nexport interface G9SyncRejection {\n localTable: string;\n key: string;\n code: string;\n message: string | null;\n sqlState: string | null;\n constraint: string | null;\n column: string | null;\n details: string | null;\n atUtcMs: number;\n}\n\n/** A persisted summary of one run (`G9CSyncRunReport`); serialized with the .NET JSON names into g9_runs. */\nexport interface G9SyncRunReport {\n runId: string;\n startedUtcMs: number;\n durationMs: number;\n outcome: string;\n priority: string;\n errorCode: string | null;\n errorMessage: string | null;\n pushed: number;\n rejected: number;\n conflicts: number;\n downloaded: number;\n applied: number;\n downloadedBytes: number;\n subscriptions: string[];\n phaseMs: { [phase: string]: number };\n triggersSkipped: boolean | null;\n foreignTriggers: string[];\n applyTransactions: number;\n indexesDeferred: number;\n indexRebuildMs: number;\n liveIndexReasons: { [table: string]: string };\n unchangedRows: number;\n}\n\n// ---------------------------------------------------------------- local commands (ADR-0025)\n\n/** `G9ELocalCommandState`. */\nexport const G9ELocalCommandState = {\n Pending: 0,\n Ok: 1,\n Rejected: 2,\n Superseded: 3,\n} as const;\nexport type G9ELocalCommandState = (typeof G9ELocalCommandState)[keyof typeof G9ELocalCommandState];\n\n/** A command recorded on this device (`G9CLocalCommand`). */\nexport interface G9LocalCommand {\n commandId: string;\n sequence: number;\n name: string;\n version: number;\n payload: string;\n createdUtcMs: number;\n state: G9ELocalCommandState;\n code: string | null;\n message: string | null;\n result: string | null;\n completedUtcMs: number | null;\n}\n\n/** What to record (`G9CCommandRequest`). */\nexport interface G9CommandRequest {\n name: string;\n version?: number;\n /** JSON payload for the server's handler. */\n payload: string;\n}\n\n/** A value an app binds through {@link G9LocalCommandWriter}: the SQLite driver's value forms, plus booleans. */\nexport type G9LocalSqlArgument = null | number | string | boolean | ArrayBuffer | Uint8Array | { int64: string } | G9Long;\n\n/**\n * Writes a command's local effects in the transaction that records it (`IG9LocalCommandWriter`). Rows written here are\n * not uploaded as row changes; they are protected from pulls until the server's result arrives.\n */\nexport interface G9LocalCommandWriter {\n /** Executes SQL; parameters bind positionally as `$p0`, `$p1`, … */\n execute(sql: string, ...args: G9LocalSqlArgument[]): Promise<number>;\n scalar(sql: string, ...args: G9LocalSqlArgument[]): Promise<unknown>;\n}\n\n// ---------------------------------------------------------------- revocation (ADR-0026)\n\n/** `G9ERevocationReason`. */\nexport const G9ERevocationReason = {\n LeftScope: 0,\n Unsubscribed: 1,\n Expired: 2,\n AccessRevoked: 3,\n} as const;\nexport type G9ERevocationReason = (typeof G9ERevocationReason)[keyof typeof G9ERevocationReason];\n\n/** `G9ERevocationDisposition`. */\nexport const G9ERevocationDisposition = {\n Delete: 0,\n MarkRevoked: 1,\n Quarantine: 2,\n Retain: 3,\n} as const;\nexport type G9ERevocationDisposition = (typeof G9ERevocationDisposition)[keyof typeof G9ERevocationDisposition];\n\n/** A row no subscription holds any more, as a revocation rule sees it (`G9CRevokedRow`). */\nexport interface G9RevokedRow {\n localTable: string;\n key: string;\n reason: G9ERevocationReason;\n subscriptionKey: string | null;\n hasPendingChanges: boolean;\n isRejected: boolean;\n /** Column values (key included) as stored locally; empty when the row no longer exists locally. */\n values: { [column: string]: unknown };\n}\n\n/** Lets a custom rule change the row before its disposition applies. */\nexport interface G9RevokedRowEditor {\n set(column: string, value: unknown): void;\n}\n\nexport interface G9RevocationRule {\n readonly name: string;\n readonly condition: (row: G9RevokedRow) => boolean;\n readonly decide: (row: G9RevokedRow, editor: G9RevokedRowEditor) => G9ERevocationDisposition;\n readonly retainWhile: ((row: G9RevokedRow) => boolean) | null;\n}\n\n/** Ordered revocation rules (`G9CRevocationPolicy`): the first matching rule decides. */\nexport class G9RevocationPolicy {\n readonly rules: readonly G9RevocationRule[];\n\n private constructor(rules: readonly G9RevocationRule[]) {\n this.rules = rules;\n }\n\n /** No rules: delete clean rows, quarantine rows with pending changes. */\n static readonly default = new G9RevocationPolicy([]);\n\n static create(configure: (builder: G9RevocationPolicyBuilder) => void): G9RevocationPolicy {\n const builder = new G9RevocationPolicyBuilder();\n configure(builder);\n return new G9RevocationPolicy(builder.rules.slice());\n }\n\n decide(row: G9RevokedRow, editor: G9RevokedRowEditor): { rule: G9RevocationRule | null; disposition: G9ERevocationDisposition } {\n for (const rule of this.rules) {\n if (rule.condition(row)) return { rule, disposition: rule.decide(row, editor) };\n }\n return { rule: null, disposition: row.hasPendingChanges ? G9ERevocationDisposition.Quarantine : G9ERevocationDisposition.Delete };\n }\n\n find(name: string): G9RevocationRule | null {\n for (const rule of this.rules) if (rule.name === name) return rule;\n return null;\n }\n}\n\nexport class G9RevocationPolicyBuilder {\n readonly rules: G9RevocationRule[] = [];\n\n when(name: string, condition: (row: G9RevokedRow) => boolean): G9RevocationActionBuilder {\n if (typeof name !== 'string' || name.trim() === '') throw new TypeError('A rule needs a name.');\n if (this.rules.some((r) => r.name === name)) throw new RangeError(`Revocation rule '${name}' is declared twice.`);\n return new G9RevocationActionBuilder(this, name, condition);\n }\n\n /** Rows of one local table. */\n forTable(name: string, localTable: string, condition?: (row: G9RevokedRow) => boolean): G9RevocationActionBuilder {\n const table = localTable.toLowerCase();\n return this.when(name, (row) => row.localTable.toLowerCase() === table && (condition ? condition(row) : true));\n }\n}\n\nexport class G9RevocationActionBuilder {\n private readonly _owner: G9RevocationPolicyBuilder;\n private readonly _name: string;\n private readonly _condition: (row: G9RevokedRow) => boolean;\n\n constructor(owner: G9RevocationPolicyBuilder, name: string, condition: (row: G9RevokedRow) => boolean) {\n this._owner = owner;\n this._name = name;\n this._condition = condition;\n }\n\n delete(): G9RevocationPolicyBuilder {\n return this._add(() => G9ERevocationDisposition.Delete, null);\n }\n\n markRevoked(): G9RevocationPolicyBuilder {\n return this._add(() => G9ERevocationDisposition.MarkRevoked, null);\n }\n\n quarantine(): G9RevocationPolicyBuilder {\n return this._add(() => G9ERevocationDisposition.Quarantine, null);\n }\n\n retainWhile(retainWhile: (row: G9RevokedRow) => boolean): G9RevocationPolicyBuilder {\n return this._add(() => G9ERevocationDisposition.Retain, retainWhile);\n }\n\n custom(decide: (row: G9RevokedRow, editor: G9RevokedRowEditor) => G9ERevocationDisposition): G9RevocationPolicyBuilder {\n return this._add(decide, null);\n }\n\n private _add(\n decide: (row: G9RevokedRow, editor: G9RevokedRowEditor) => G9ERevocationDisposition,\n retainWhile: ((row: G9RevokedRow) => boolean) | null,\n ): G9RevocationPolicyBuilder {\n this._owner.rules.push({ name: this._name, condition: this._condition, decide, retainWhile });\n return this._owner;\n }\n}\n\n/** A row in the holding area (`G9CQuarantinedRow`). */\nexport interface G9QuarantinedRow {\n localTable: string;\n key: string;\n reason: G9ERevocationReason;\n rule: string | null;\n hadPendingChanges: boolean;\n values: { [column: string]: unknown };\n atUtcMs: number;\n}\n\n/** A row kept in the app's table after revocation (`G9CRetainedRow`). */\nexport interface G9RetainedRow {\n localTable: string;\n key: string;\n disposition: G9ERevocationDisposition;\n reason: G9ERevocationReason;\n rule: string | null;\n atUtcMs: number;\n}\n\n// ---------------------------------------------------------------- failures\n\n/** What went wrong inside a client store, in terms an application can act on (`G9ELocalStoreFailure`). */\nexport const G9ELocalStoreFailure = {\n Other: 0,\n Corrupt: 1,\n DiskFull: 2,\n Busy: 3,\n} as const;\nexport type G9ELocalStoreFailure = (typeof G9ELocalStoreFailure)[keyof typeof G9ELocalStoreFailure];\n\n/** Implemented by a store's errors so the engine can give a run's failure a stable code (`IG9SyncLocalStoreFailure`). */\nexport interface G9SyncLocalStoreFailure {\n readonly localStoreFailure: G9ELocalStoreFailure;\n}\n\nexport function isLocalStoreFailure(error: unknown): error is G9SyncLocalStoreFailure {\n return typeof error === 'object' && error !== null && typeof (error as { localStoreFailure?: unknown }).localStoreFailure === 'number';\n}\n\n// ---------------------------------------------------------------- the store contract\n\n/**\n * The client storage provider (`IG9SyncClientStore`): local tables, change capture, subscription membership,\n * staging, apply and metadata. Every method takes an optional AbortSignal (the CancellationToken twin).\n */\nexport interface G9SyncClientStore {\n initialize(model: G9SyncClientModel, signal?: AbortSignal): Promise<void>;\n getClientId(signal?: AbortSignal): Promise<string>;\n getServerState(signal?: AbortSignal): Promise<G9ClientServerState>;\n saveHello(hello: G9DtHelloResult, signal?: AbortSignal): Promise<void>;\n getPendingBackfills(signal?: AbortSignal): Promise<G9DtBackfillRequest[]>;\n\n getSubscriptions(signal?: AbortSignal): Promise<G9SyncSubscriptionRecord[]>;\n ensureSubscription(\n name: string,\n parameters: G9SyncParameters,\n ephemeral: boolean,\n ttlMs: number | null,\n adoptExistingRows: boolean,\n signal?: AbortSignal,\n ): Promise<G9SyncSubscriptionRecord>;\n removeSubscription(key: string, policy: G9EMoveOutPolicy, signal?: AbortSignal): Promise<void>;\n releaseSubscriptionRows(key: string, signal?: AbortSignal): Promise<G9ApplyReport>;\n updateSubscription(key: string, update: G9SubscriptionUpdate, signal?: AbortSignal): Promise<void>;\n collectExpiredEphemeral(utcNowMs: number, signal?: AbortSignal): Promise<number>;\n\n buildPushBatch(tables: readonly G9DtNegotiatedTable[], maxRows: number, maxBytes: number, signal?: AbortSignal): Promise<G9PushBatch | null>;\n forgetUploadedRows(localTable: string, keys: readonly string[] | null, signal?: AbortSignal): Promise<number>;\n applyPushResult(batch: G9PushBatch, result: G9DtPushResult, signal?: AbortSignal): Promise<G9ApplyReport>;\n\n getStagedPull(signal?: AbortSignal): Promise<G9StagedPull | null>;\n /** The newest staged pull planned under exactly this generation, or null (ADR-0060). */\n getStagedPullForGeneration(generation: string, signal?: AbortSignal): Promise<G9StagedPull | null>;\n beginStagedPull(pull: G9StagedPull, signal?: AbortSignal): Promise<void>;\n pruneStagedPulls(olderThanUtcMs: number, maxBytes: number, keepGeneration: string | null, signal?: AbortSignal): Promise<number>;\n discardAllStagedPulls(signal?: AbortSignal): Promise<number>;\n stageChunk(runId: string, chunk: G9DtSyncChunk, signal?: AbortSignal): Promise<void>;\n /**\n * The store's offer to receive large first downloads as SQLite snapshot files (ADR-0072), or null for rows only. A store that\n * makes an offer stages file segments (`chunk.file`) in `stageChunk` and copies the files in `applyStagedPull`.\n */\n describeSnapshotFiles?(negotiated: readonly G9DtNegotiatedTable[]): G9DtSnapshotFileRequest | null;\n getResumePoint(runId: string, signal?: AbortSignal): Promise<G9ResumePoint>;\n applyStagedPull(\n runId: string,\n rowsApplied: ((rows: number) => void) | null,\n slices: ((slice: G9ApplySlice) => void) | null,\n signal?: AbortSignal,\n ): Promise<G9ApplyReport>;\n discardStagedPull(runId: string, signal?: AbortSignal): Promise<void>;\n\n computeDigest(subscriptionKey: string, table: G9DtNegotiatedTable, signal?: AbortSignal): Promise<G9DtTableDigest>;\n readLocalEntries(\n subscriptionKey: string,\n table: G9DtNegotiatedTable,\n buckets: ReadonlySet<number>,\n serverKeys: ReadonlySet<string>,\n signal?: AbortSignal,\n ): Promise<G9LocalRowEntry[]>;\n applyReconcile(\n subscriptionKey: string,\n table: G9DtNegotiatedTable,\n fetchedFrames: readonly Uint8Array[],\n addMembership: readonly string[],\n moveOut: readonly string[],\n policy: G9EMoveOutPolicy,\n signal?: AbortSignal,\n ): Promise<G9ApplyReport>;\n\n getPendingSummary(signal?: AbortSignal): Promise<G9PendingSummary>;\n enqueueCommand(\n request: G9CommandRequest,\n applyLocally: ((writer: G9LocalCommandWriter, signal?: AbortSignal) => Promise<void>) | null,\n signal?: AbortSignal,\n ): Promise<G9LocalCommand>;\n getQuarantined(signal?: AbortSignal): Promise<G9QuarantinedRow[]>;\n restoreQuarantined(localTable: string, key: string, signal?: AbortSignal): Promise<number>;\n discardQuarantined(localTable: string | null, key: string | null, signal?: AbortSignal): Promise<number>;\n getRetained(signal?: AbortSignal): Promise<G9RetainedRow[]>;\n reevaluateRetained(signal?: AbortSignal): Promise<number>;\n getCommands(state: G9ELocalCommandState | null, limit: number, signal?: AbortSignal): Promise<G9LocalCommand[]>;\n readChangeFeed(localTable: string, afterSequence: number, limit: number, signal?: AbortSignal): Promise<G9ChangeFeedEntry[]>;\n getChangeSequence(signal?: AbortSignal): Promise<number>;\n getChangeFeedFloor(signal?: AbortSignal): Promise<number>;\n getRejections(signal?: AbortSignal): Promise<G9SyncRejection[]>;\n retryRejected(localTable: string | null, key: string | null, signal?: AbortSignal): Promise<number>;\n markDirty(localTable: string, keys: readonly string[], signal?: AbortSignal): Promise<number>;\n adoptExistingRows(signal?: AbortSignal): Promise<number>;\n saveRunReport(report: G9SyncRunReport, keep: number, signal?: AbortSignal): Promise<void>;\n getRecentRunReports(count: number, signal?: AbortSignal): Promise<G9SyncRunReport[]>;\n getPhaseStatistics(signal?: AbortSignal): Promise<{ [key: string]: number }>;\n recordPhaseStatistics(samples: { [key: string]: number }, signal?: AbortSignal): Promise<void>;\n purgeDeletedFeed(keep: number, signal?: AbortSignal): Promise<number>;\n dispose(): Promise<void>;\n}\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.
|
|
2
|
+
export declare const VERSION = "1.3.1";
|
|
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.
|
|
6
|
+
export const VERSION = '1.3.1';
|
|
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,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AAC9K,cAAc,wBAAwB,CAAC;AAEvC,OAAO,EAAE,YAAY,EAAE,qBAAqB,EAAE,SAAS,EAAyB,MAAM,sBAAsB,CAAC;AAC7G,OAAO,EACL,cAAc,EACd,eAAe,EACf,cAAc,EACd,SAAS,EACT,oBAAoB,EACpB,gBAAgB,EAChB,cAAc,EACd,WAAW,EACX,YAAY,EACZ,oBAAoB,GAYrB,MAAM,kBAAkB,CAAC;AAC1B,OAAO,EAAE,YAAY,EAAE,eAAe,EAAE,MAAM,oBAAoB,CAAC;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.
|
|
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,OA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aAAa,EAAE,YAAY,EAAE,YAAY,EAAqB,MAAM,4BAA4B,CAAC;AAE3H,SAAS;AACT,OAAO,EAAE,iBAAiB,EAAE,wBAAwB,EAAE,iBAAiB,EAAE,wBAAwB,EAAmD,MAAM,mBAAmB,CAAC;AAC9K,cAAc,wBAAwB,CAAC;AAEvC,OAAO,EAAE,YAAY,EAAE,qBAAqB,EAAE,SAAS,EAAyB,MAAM,sBAAsB,CAAC;AAC7G,OAAO,EACL,cAAc,EACd,eAAe,EACf,cAAc,EACd,SAAS,EACT,oBAAoB,EACpB,gBAAgB,EAChB,cAAc,EACd,WAAW,EACX,YAAY,EACZ,oBAAoB,GAYrB,MAAM,kBAAkB,CAAC;AAC1B,OAAO,EAAE,YAAY,EAAE,eAAe,EAAE,MAAM,oBAAoB,CAAC;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.3.1';\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"]}
|
package/dist/node/index.d.ts
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { type G9FrameDecompressor } from '../protocol/rowBatch/reader.js';
|
|
2
2
|
import type { G9FrameCompressor } from '../protocol/rowBatch/writer.js';
|
|
3
3
|
export { nodeSqliteDriver, G9NodeSqliteError } from './sqliteDriver.js';
|
|
4
|
+
export { nodeSnapshotFileSink } from './snapshotFileSink.js';
|
|
4
5
|
/** A frame decompressor over node:zlib. */
|
|
5
6
|
export declare function nodeBrotliDecompressor(): G9FrameDecompressor;
|
|
6
7
|
/** A push-frame compressor over node:zlib. */
|
package/dist/node/index.js
CHANGED
|
@@ -4,6 +4,7 @@
|
|
|
4
4
|
import { brotliCompressSync, brotliDecompressSync, constants } from 'node:zlib';
|
|
5
5
|
import { setDefaultFrameDecompressor } from '../protocol/rowBatch/reader.js';
|
|
6
6
|
export { nodeSqliteDriver, G9NodeSqliteError } from './sqliteDriver.js';
|
|
7
|
+
export { nodeSnapshotFileSink } from './snapshotFileSink.js';
|
|
7
8
|
/** A frame decompressor over node:zlib. */
|
|
8
9
|
export function nodeBrotliDecompressor() {
|
|
9
10
|
return {
|
package/dist/node/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/node/index.ts"],"names":[],"mappings":"AAAA,8BAA8B;AAC9B,8GAA8G;AAC9G,+CAA+C;AAC/C,OAAO,EAAE,kBAAkB,EAAE,oBAAoB,EAAE,SAAS,EAAE,MAAM,WAAW,CAAC;AAChF,OAAO,EAAE,2BAA2B,EAA4B,MAAM,gCAAgC,CAAC;AAGvG,OAAO,EAAE,gBAAgB,EAAE,iBAAiB,EAAE,MAAM,mBAAmB,CAAC;
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/node/index.ts"],"names":[],"mappings":"AAAA,8BAA8B;AAC9B,8GAA8G;AAC9G,+CAA+C;AAC/C,OAAO,EAAE,kBAAkB,EAAE,oBAAoB,EAAE,SAAS,EAAE,MAAM,WAAW,CAAC;AAChF,OAAO,EAAE,2BAA2B,EAA4B,MAAM,gCAAgC,CAAC;AAGvG,OAAO,EAAE,gBAAgB,EAAE,iBAAiB,EAAE,MAAM,mBAAmB,CAAC;AACxE,OAAO,EAAE,oBAAoB,EAAE,MAAM,uBAAuB,CAAC;AAE7D,2CAA2C;AAC3C,MAAM,UAAU,sBAAsB;IACpC,OAAO;QACL,UAAU,CAAC,UAAsB,EAAE,cAAsB;YACvD,MAAM,GAAG,GAAG,oBAAoB,CAAC,UAAU,EAAE,EAAE,eAAe,EAAE,IAAI,CAAC,GAAG,CAAC,CAAC,EAAE,cAAc,GAAG,CAAC,CAAC,EAAE,CAAC,CAAC;YACnG,IAAI,GAAG,CAAC,MAAM,KAAK,cAAc;gBAAE,MAAM,IAAI,KAAK,CAAC,0BAA0B,GAAG,CAAC,MAAM,WAAW,cAAc,YAAY,CAAC,CAAC;YAC9H,OAAO,IAAI,UAAU,CAAC,GAAG,CAAC,MAAM,EAAE,GAAG,CAAC,UAAU,EAAE,GAAG,CAAC,MAAM,CAAC,CAAC;QAChE,CAAC;KACF,CAAC;AACJ,CAAC;AAED,8CAA8C;AAC9C,MAAM,UAAU,oBAAoB;IAClC,OAAO;QACL,QAAQ,CAAC,IAAgB,EAAE,OAAe,EAAE,MAAc;YACxD,MAAM,GAAG,GAAG,kBAAkB,CAAC,IAAI,EAAE;gBACnC,MAAM,EAAE,EAAE,CAAC,SAAS,CAAC,oBAAoB,CAAC,EAAE,OAAO,EAAE,CAAC,SAAS,CAAC,kBAAkB,CAAC,EAAE,MAAM,EAAE,CAAC,SAAS,CAAC,sBAAsB,CAAC,EAAE,IAAI,CAAC,MAAM,EAAE;aAC/I,CAAC,CAAC;YACH,OAAO,IAAI,UAAU,CAAC,GAAG,CAAC,MAAM,EAAE,GAAG,CAAC,UAAU,EAAE,GAAG,CAAC,MAAM,CAAC,CAAC;QAChE,CAAC;KACF,CAAC;AACJ,CAAC;AAED,yFAAyF;AACzF,MAAM,UAAU,aAAa;IAC3B,MAAM,YAAY,GAAG,sBAAsB,EAAE,CAAC;IAC9C,2BAA2B,CAAC,YAAY,CAAC,CAAC;IAC1C,OAAO,YAAY,CAAC;AACtB,CAAC","sourcesContent":["/// <reference types=\"node\" />\n// @g9tm/syncdata/node — Node helpers: the node:sqlite reference driver and Brotli through node:zlib (the same\n// quality 4 / window 22 the .NET writer uses).\nimport { brotliCompressSync, brotliDecompressSync, constants } from 'node:zlib';\nimport { setDefaultFrameDecompressor, type G9FrameDecompressor } from '../protocol/rowBatch/reader.js';\nimport type { G9FrameCompressor } from '../protocol/rowBatch/writer.js';\n\nexport { nodeSqliteDriver, G9NodeSqliteError } from './sqliteDriver.js';\nexport { nodeSnapshotFileSink } from './snapshotFileSink.js';\n\n/** A frame decompressor over node:zlib. */\nexport function nodeBrotliDecompressor(): G9FrameDecompressor {\n return {\n decompress(compressed: Uint8Array, expectedLength: number): Uint8Array {\n const out = brotliDecompressSync(compressed, { maxOutputLength: Math.max(1, expectedLength + 1) });\n if (out.length !== expectedLength) throw new Error(`Brotli body decoded to ${out.length} bytes, ${expectedLength} expected.`);\n return new Uint8Array(out.buffer, out.byteOffset, out.length);\n },\n };\n}\n\n/** A push-frame compressor over node:zlib. */\nexport function nodeBrotliCompressor(): G9FrameCompressor {\n return {\n compress(body: Uint8Array, quality: number, window: number): Uint8Array {\n const out = brotliCompressSync(body, {\n params: { [constants.BROTLI_PARAM_QUALITY]: quality, [constants.BROTLI_PARAM_LGWIN]: window, [constants.BROTLI_PARAM_SIZE_HINT]: body.length },\n });\n return new Uint8Array(out.buffer, out.byteOffset, out.length);\n },\n };\n}\n\n/** Makes node:zlib the process-wide frame decompressor (setDefaultFrameDecompressor). */\nexport function useNodeBrotli(): G9FrameDecompressor {\n const decompressor = nodeBrotliDecompressor();\n setDefaultFrameDecompressor(decompressor);\n return decompressor;\n}\n"]}
|
|
@@ -0,0 +1,79 @@
|
|
|
1
|
+
/// <reference types="node" />
|
|
2
|
+
// The Node implementation of G9SnapshotFileSink (ADR-0072): Brotli through node:zlib, SHA-256 through node:crypto, positional
|
|
3
|
+
// writes through node:fs. The Lynx package implements the same contract natively; the store never sees the bytes of a file.
|
|
4
|
+
import { createHash } from 'node:crypto';
|
|
5
|
+
import { closeSync, fsyncSync, mkdirSync, openSync, readdirSync, readSync, rmSync, statSync, writeSync, ftruncateSync } from 'node:fs';
|
|
6
|
+
import { join } from 'node:path';
|
|
7
|
+
import { brotliDecompressSync } from 'node:zlib';
|
|
8
|
+
/** A snapshot-file sink writing into `directory` (created when missing). */
|
|
9
|
+
export function nodeSnapshotFileSink(directory) {
|
|
10
|
+
return {
|
|
11
|
+
directory,
|
|
12
|
+
async create(path, size) {
|
|
13
|
+
mkdirSync(directory, { recursive: true });
|
|
14
|
+
const fd = openSync(path, 'w');
|
|
15
|
+
try {
|
|
16
|
+
ftruncateSync(fd, size);
|
|
17
|
+
}
|
|
18
|
+
finally {
|
|
19
|
+
closeSync(fd);
|
|
20
|
+
}
|
|
21
|
+
},
|
|
22
|
+
async writeSegment(path, offset, compressed, length, sha256, sync) {
|
|
23
|
+
const raw = brotliDecompressSync(compressed, { maxOutputLength: Math.max(1, length + 1) });
|
|
24
|
+
if (raw.length !== length)
|
|
25
|
+
throw new Error(`The segment decompressed to ${raw.length} bytes, ${length} expected.`);
|
|
26
|
+
const hash = createHash('sha256').update(raw).digest('hex');
|
|
27
|
+
if (hash !== sha256)
|
|
28
|
+
throw new Error('The segment fails its SHA-256.');
|
|
29
|
+
const fd = openSync(path, 'r+');
|
|
30
|
+
try {
|
|
31
|
+
let written = 0;
|
|
32
|
+
while (written < raw.length)
|
|
33
|
+
written += writeSync(fd, raw, written, raw.length - written, offset + written);
|
|
34
|
+
if (sync)
|
|
35
|
+
fsyncSync(fd);
|
|
36
|
+
}
|
|
37
|
+
finally {
|
|
38
|
+
closeSync(fd);
|
|
39
|
+
}
|
|
40
|
+
},
|
|
41
|
+
async size(path) {
|
|
42
|
+
try {
|
|
43
|
+
return statSync(path).size;
|
|
44
|
+
}
|
|
45
|
+
catch {
|
|
46
|
+
return null;
|
|
47
|
+
}
|
|
48
|
+
},
|
|
49
|
+
async head(path, length) {
|
|
50
|
+
const out = new Uint8Array(length);
|
|
51
|
+
const fd = openSync(path, 'r');
|
|
52
|
+
try {
|
|
53
|
+
let read = 0;
|
|
54
|
+
while (read < length) {
|
|
55
|
+
const n = readSync(fd, out, read, length - read, read);
|
|
56
|
+
if (n === 0)
|
|
57
|
+
break;
|
|
58
|
+
read += n;
|
|
59
|
+
}
|
|
60
|
+
return read === length ? out : out.subarray(0, read);
|
|
61
|
+
}
|
|
62
|
+
finally {
|
|
63
|
+
closeSync(fd);
|
|
64
|
+
}
|
|
65
|
+
},
|
|
66
|
+
async remove(path) {
|
|
67
|
+
rmSync(path, { force: true });
|
|
68
|
+
},
|
|
69
|
+
async list(target) {
|
|
70
|
+
try {
|
|
71
|
+
return readdirSync(target).map((name) => join(target, name));
|
|
72
|
+
}
|
|
73
|
+
catch {
|
|
74
|
+
return [];
|
|
75
|
+
}
|
|
76
|
+
},
|
|
77
|
+
};
|
|
78
|
+
}
|
|
79
|
+
//# sourceMappingURL=snapshotFileSink.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"snapshotFileSink.js","sourceRoot":"","sources":["../../src/node/snapshotFileSink.ts"],"names":[],"mappings":"AAAA,8BAA8B;AAC9B,8HAA8H;AAC9H,4HAA4H;AAC5H,OAAO,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AACzC,OAAO,EAAE,SAAS,EAAE,SAAS,EAAE,SAAS,EAAE,QAAQ,EAAE,WAAW,EAAE,QAAQ,EAAE,MAAM,EAAE,QAAQ,EAAE,SAAS,EAAE,aAAa,EAAE,MAAM,SAAS,CAAC;AACvI,OAAO,EAAE,IAAI,EAAE,MAAM,WAAW,CAAC;AACjC,OAAO,EAAE,oBAAoB,EAAE,MAAM,WAAW,CAAC;AAGjD,4EAA4E;AAC5E,MAAM,UAAU,oBAAoB,CAAC,SAAiB;IACpD,OAAO;QACL,SAAS;QAET,KAAK,CAAC,MAAM,CAAC,IAAY,EAAE,IAAY;YACrC,SAAS,CAAC,SAAS,EAAE,EAAE,SAAS,EAAE,IAAI,EAAE,CAAC,CAAC;YAC1C,MAAM,EAAE,GAAG,QAAQ,CAAC,IAAI,EAAE,GAAG,CAAC,CAAC;YAC/B,IAAI,CAAC;gBACH,aAAa,CAAC,EAAE,EAAE,IAAI,CAAC,CAAC;YAC1B,CAAC;oBAAS,CAAC;gBACT,SAAS,CAAC,EAAE,CAAC,CAAC;YAChB,CAAC;QACH,CAAC;QAED,KAAK,CAAC,YAAY,CAAC,IAAY,EAAE,MAAc,EAAE,UAAsB,EAAE,MAAc,EAAE,MAAc,EAAE,IAAa;YACpH,MAAM,GAAG,GAAG,oBAAoB,CAAC,UAAU,EAAE,EAAE,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I,CAAC;gBACH,IAAI,IAAI,GAAG,CAAC,CAAC;gBACb,OAAO,IAAI,GAAG,MAAM,EAAE,CAAC;oBACrB,MAAM,CAAC,GAAG,QAAQ,CAAC,EAAE,EAAE,GAAG,EAAE,IAAI,EAAE,MAAM,GAAG,IAAI,EAAE,IAAI,CAAC,CAAC;oBACvD,IAAI,CAAC,KAAK,CAAC;wBAAE,MAAM;oBACnB,IAAI,IAAI,CAAC,CAAC;gBACZ,CAAC;gBACD,OAAO,IAAI,KAAK,MAAM,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,GAAG,CAAC,QAAQ,CAAC,CAAC,EAAE,IAAI,CAAC,CAAC;YACvD,CAAC;oBAAS,CAAC;gBACT,SAAS,CAAC,EAAE,CAAC,CAAC;YAChB,CAAC;QACH,CAAC;QAED,KAAK,CAAC,MAAM,CAAC,IAAY;YACvB,MAAM,CAAC,IAAI,EAAE,EAAE,KAAK,EAAE,IAAI,EAAE,CAAC,CAAC;QAChC,CAAC;QAED,KAAK,CAAC,IAAI,CAAC,MAAc;YACvB,IAAI,CAAC;gBACH,OAAO,WAAW,CAAC,MAAM,CAAC,CAAC,GAAG,CAAC,CAAC,IAAI,EAAE,EAAE,CAAC,IAAI,CAAC,MAAM,EAAE,IAAI,CAAC,CAAC,CAAC;YAC/D,CAAC;YAAC,MAAM,CAAC;gBACP,OAAO,EAAE,CAAC;YACZ,CAAC;QACH,CAAC;KACF,CAAC;AACJ,CAAC","sourcesContent":["/// <reference types=\"node\" />\n// The Node implementation of G9SnapshotFileSink (ADR-0072): Brotli through node:zlib, SHA-256 through node:crypto, positional\n// writes through node:fs. The Lynx package implements the same contract natively; the store never sees the bytes of a file.\nimport { createHash } from 'node:crypto';\nimport { closeSync, fsyncSync, mkdirSync, openSync, readdirSync, readSync, rmSync, statSync, writeSync, ftruncateSync } from 'node:fs';\nimport { join } from 'node:path';\nimport { brotliDecompressSync } from 'node:zlib';\nimport type { G9SnapshotFileSink } from '../sqlite/options.js';\n\n/** A snapshot-file sink writing into `directory` (created when missing). */\nexport function nodeSnapshotFileSink(directory: string): G9SnapshotFileSink {\n return {\n directory,\n\n async create(path: string, size: number): Promise<void> {\n mkdirSync(directory, { recursive: true });\n const fd = openSync(path, 'w');\n try {\n ftruncateSync(fd, size);\n } finally {\n closeSync(fd);\n }\n },\n\n async writeSegment(path: string, offset: number, compressed: Uint8Array, length: number, sha256: string, sync: boolean): Promise<void> {\n const raw = brotliDecompressSync(compressed, { maxOutputLength: Math.max(1, length + 1) });\n if (raw.length !== length) throw new Error(`The segment decompressed to ${raw.length} bytes, ${length} expected.`);\n const hash = createHash('sha256').update(raw).digest('hex');\n if (hash !== sha256) throw new Error('The segment fails its SHA-256.');\n const fd = openSync(path, 'r+');\n try {\n let written = 0;\n while (written < raw.length) written += writeSync(fd, raw, written, raw.length - written, offset + written);\n if (sync) fsyncSync(fd);\n } finally {\n closeSync(fd);\n }\n },\n\n async size(path: string): Promise<number | null> {\n try {\n return statSync(path).size;\n } catch {\n return null;\n }\n },\n\n async head(path: string, length: number): Promise<Uint8Array> {\n const out = new Uint8Array(length);\n const fd = openSync(path, 'r');\n try {\n let read = 0;\n while (read < length) {\n const n = readSync(fd, out, read, length - read, read);\n if (n === 0) break;\n read += n;\n }\n return read === length ? out : out.subarray(0, read);\n } finally {\n closeSync(fd);\n }\n },\n\n async remove(path: string): Promise<void> {\n rmSync(path, { force: true });\n },\n\n async list(target: string): Promise<string[]> {\n try {\n return readdirSync(target).map((name) => join(target, name));\n } catch {\n return [];\n }\n },\n };\n}\n"]}
|