@rocicorp/zero 1.6.0-canary.11 → 1.6.0-canary.12
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/out/_virtual/_rolldown/runtime.js +1 -12
- package/out/analyze-query/src/analyze-cli.js +3 -3
- package/out/analyze-query/src/analyze-cli.js.map +1 -1
- package/out/shared/src/iterables.d.ts +2 -0
- package/out/shared/src/iterables.d.ts.map +1 -1
- package/out/shared/src/iterables.js +9 -1
- package/out/shared/src/iterables.js.map +1 -1
- package/out/zero/package.js +13 -5
- package/out/zero/package.js.map +1 -1
- package/out/zero-cache/src/scripts/permissions.d.ts.map +1 -1
- package/out/zero-cache/src/scripts/permissions.js +1 -2
- package/out/zero-cache/src/scripts/permissions.js.map +1 -1
- package/out/zero-cache/src/server/anonymous-otel-start.js +3 -3
- package/out/zero-cache/src/server/otel-start.js +1 -1
- package/out/zero-cache/src/services/view-syncer/cvr-store.d.ts.map +1 -1
- package/out/zero-cache/src/services/view-syncer/cvr-store.js +2 -1
- package/out/zero-cache/src/services/view-syncer/cvr-store.js.map +1 -1
- package/out/zero-client/src/client/version.js +1 -1
- package/out/zero-react/src/use-connection-state.js +2 -4
- package/out/zero-react/src/use-connection-state.js.map +1 -1
- package/out/zero-react/src/use-query.js +4 -6
- package/out/zero-react/src/use-query.js.map +1 -1
- package/out/zero-react/src/use-zero-online.js +2 -4
- package/out/zero-react/src/use-zero-online.js.map +1 -1
- package/out/zero-react/src/zero-provider.js +12 -15
- package/out/zero-react/src/zero-provider.js.map +1 -1
- package/out/zero-server/src/adapters/pg.js +1 -1
- package/out/zero-solid/src/solid-view.js +1 -1
- package/out/zero-solid/src/use-connection-state.js +1 -1
- package/out/zero-solid/src/use-query.js +2 -2
- package/out/zero-solid/src/use-zero-online.js +1 -1
- package/out/zero-solid/src/use-zero.js +1 -1
- package/package.json +21 -5
- package/out/_virtual/__vite-optional-peer-dep_pg-native_pg.js +0 -13
- package/out/_virtual/__vite-optional-peer-dep_pg-native_pg.js.map +0 -1
- package/out/node_modules/.pnpm/@opentelemetry_semantic-conventions@1.41.1/node_modules/@opentelemetry/semantic-conventions/build/esm/stable_attributes.js +0 -12
- package/out/node_modules/.pnpm/@opentelemetry_semantic-conventions@1.41.1/node_modules/@opentelemetry/semantic-conventions/build/esm/stable_attributes.js.map +0 -1
- package/out/node_modules/.pnpm/pg-cloudflare@1.3.0/node_modules/pg-cloudflare/dist/empty.js +0 -11
- package/out/node_modules/.pnpm/pg-cloudflare@1.3.0/node_modules/pg-cloudflare/dist/empty.js.map +0 -1
- package/out/node_modules/.pnpm/pg-connection-string@2.12.0/node_modules/pg-connection-string/index.js +0 -130
- package/out/node_modules/.pnpm/pg-connection-string@2.12.0/node_modules/pg-connection-string/index.js.map +0 -1
- package/out/node_modules/.pnpm/pg-int8@1.0.1/node_modules/pg-int8/index.js +0 -62
- package/out/node_modules/.pnpm/pg-int8@1.0.1/node_modules/pg-int8/index.js.map +0 -1
- package/out/node_modules/.pnpm/pg-pool@3.13.0_pg@8.20.0/node_modules/pg-pool/index.js +0 -353
- package/out/node_modules/.pnpm/pg-pool@3.13.0_pg@8.20.0/node_modules/pg-pool/index.js.map +0 -1
- package/out/node_modules/.pnpm/pg-protocol@1.13.0/node_modules/pg-protocol/dist/buffer-reader.js +0 -60
- package/out/node_modules/.pnpm/pg-protocol@1.13.0/node_modules/pg-protocol/dist/buffer-reader.js.map +0 -1
- package/out/node_modules/.pnpm/pg-protocol@1.13.0/node_modules/pg-protocol/dist/buffer-writer.js +0 -81
- package/out/node_modules/.pnpm/pg-protocol@1.13.0/node_modules/pg-protocol/dist/buffer-writer.js.map +0 -1
- package/out/node_modules/.pnpm/pg-protocol@1.13.0/node_modules/pg-protocol/dist/index.js +0 -35
- package/out/node_modules/.pnpm/pg-protocol@1.13.0/node_modules/pg-protocol/dist/index.js.map +0 -1
- package/out/node_modules/.pnpm/pg-protocol@1.13.0/node_modules/pg-protocol/dist/messages.js +0 -167
- package/out/node_modules/.pnpm/pg-protocol@1.13.0/node_modules/pg-protocol/dist/messages.js.map +0 -1
- package/out/node_modules/.pnpm/pg-protocol@1.13.0/node_modules/pg-protocol/dist/parser.js +0 -288
- package/out/node_modules/.pnpm/pg-protocol@1.13.0/node_modules/pg-protocol/dist/parser.js.map +0 -1
- package/out/node_modules/.pnpm/pg-protocol@1.13.0/node_modules/pg-protocol/dist/serializer.js +0 -177
- package/out/node_modules/.pnpm/pg-protocol@1.13.0/node_modules/pg-protocol/dist/serializer.js.map +0 -1
- package/out/node_modules/.pnpm/pg-types@2.2.0/node_modules/pg-types/index.js +0 -46
- package/out/node_modules/.pnpm/pg-types@2.2.0/node_modules/pg-types/index.js.map +0 -1
- package/out/node_modules/.pnpm/pg-types@2.2.0/node_modules/pg-types/lib/arrayParser.js +0 -16
- package/out/node_modules/.pnpm/pg-types@2.2.0/node_modules/pg-types/lib/arrayParser.js.map +0 -1
- package/out/node_modules/.pnpm/pg-types@2.2.0/node_modules/pg-types/lib/binaryParsers.js +0 -165
- package/out/node_modules/.pnpm/pg-types@2.2.0/node_modules/pg-types/lib/binaryParsers.js.map +0 -1
- package/out/node_modules/.pnpm/pg-types@2.2.0/node_modules/pg-types/lib/builtins.js +0 -81
- package/out/node_modules/.pnpm/pg-types@2.2.0/node_modules/pg-types/lib/builtins.js.map +0 -1
- package/out/node_modules/.pnpm/pg-types@2.2.0/node_modules/pg-types/lib/textParsers.js +0 -167
- package/out/node_modules/.pnpm/pg-types@2.2.0/node_modules/pg-types/lib/textParsers.js.map +0 -1
- package/out/node_modules/.pnpm/pg@8.20.0/node_modules/pg/esm/index.js +0 -19
- package/out/node_modules/.pnpm/pg@8.20.0/node_modules/pg/esm/index.js.map +0 -1
- package/out/node_modules/.pnpm/pg@8.20.0/node_modules/pg/lib/client.js +0 -508
- package/out/node_modules/.pnpm/pg@8.20.0/node_modules/pg/lib/client.js.map +0 -1
- package/out/node_modules/.pnpm/pg@8.20.0/node_modules/pg/lib/connection-parameters.js +0 -104
- package/out/node_modules/.pnpm/pg@8.20.0/node_modules/pg/lib/connection-parameters.js.map +0 -1
- package/out/node_modules/.pnpm/pg@8.20.0/node_modules/pg/lib/connection.js +0 -160
- package/out/node_modules/.pnpm/pg@8.20.0/node_modules/pg/lib/connection.js.map +0 -1
- package/out/node_modules/.pnpm/pg@8.20.0/node_modules/pg/lib/crypto/cert-signatures.js +0 -97
- package/out/node_modules/.pnpm/pg@8.20.0/node_modules/pg/lib/crypto/cert-signatures.js.map +0 -1
- package/out/node_modules/.pnpm/pg@8.20.0/node_modules/pg/lib/crypto/sasl.js +0 -131
- package/out/node_modules/.pnpm/pg@8.20.0/node_modules/pg/lib/crypto/sasl.js.map +0 -1
- package/out/node_modules/.pnpm/pg@8.20.0/node_modules/pg/lib/crypto/utils-legacy.js +0 -39
- package/out/node_modules/.pnpm/pg@8.20.0/node_modules/pg/lib/crypto/utils-legacy.js.map +0 -1
- package/out/node_modules/.pnpm/pg@8.20.0/node_modules/pg/lib/crypto/utils-webcrypto.js +0 -89
- package/out/node_modules/.pnpm/pg@8.20.0/node_modules/pg/lib/crypto/utils-webcrypto.js.map +0 -1
- package/out/node_modules/.pnpm/pg@8.20.0/node_modules/pg/lib/crypto/utils.js +0 -13
- package/out/node_modules/.pnpm/pg@8.20.0/node_modules/pg/lib/crypto/utils.js.map +0 -1
- package/out/node_modules/.pnpm/pg@8.20.0/node_modules/pg/lib/defaults.js +0 -46
- package/out/node_modules/.pnpm/pg@8.20.0/node_modules/pg/lib/defaults.js.map +0 -1
- package/out/node_modules/.pnpm/pg@8.20.0/node_modules/pg/lib/index.js +0 -71
- package/out/node_modules/.pnpm/pg@8.20.0/node_modules/pg/lib/index.js.map +0 -1
- package/out/node_modules/.pnpm/pg@8.20.0/node_modules/pg/lib/native/client.js +0 -226
- package/out/node_modules/.pnpm/pg@8.20.0/node_modules/pg/lib/native/client.js.map +0 -1
- package/out/node_modules/.pnpm/pg@8.20.0/node_modules/pg/lib/native/index.js +0 -11
- package/out/node_modules/.pnpm/pg@8.20.0/node_modules/pg/lib/native/index.js.map +0 -1
- package/out/node_modules/.pnpm/pg@8.20.0/node_modules/pg/lib/native/query.js +0 -117
- package/out/node_modules/.pnpm/pg@8.20.0/node_modules/pg/lib/native/query.js.map +0 -1
- package/out/node_modules/.pnpm/pg@8.20.0/node_modules/pg/lib/query.js +0 -151
- package/out/node_modules/.pnpm/pg@8.20.0/node_modules/pg/lib/query.js.map +0 -1
- package/out/node_modules/.pnpm/pg@8.20.0/node_modules/pg/lib/result.js +0 -76
- package/out/node_modules/.pnpm/pg@8.20.0/node_modules/pg/lib/result.js.map +0 -1
- package/out/node_modules/.pnpm/pg@8.20.0/node_modules/pg/lib/stream.js +0 -73
- package/out/node_modules/.pnpm/pg@8.20.0/node_modules/pg/lib/stream.js.map +0 -1
- package/out/node_modules/.pnpm/pg@8.20.0/node_modules/pg/lib/type-overrides.js +0 -35
- package/out/node_modules/.pnpm/pg@8.20.0/node_modules/pg/lib/type-overrides.js.map +0 -1
- package/out/node_modules/.pnpm/pg@8.20.0/node_modules/pg/lib/utils.js +0 -118
- package/out/node_modules/.pnpm/pg@8.20.0/node_modules/pg/lib/utils.js.map +0 -1
- package/out/node_modules/.pnpm/pgpass@1.0.5/node_modules/pgpass/lib/helper.js +0 -147
- package/out/node_modules/.pnpm/pgpass@1.0.5/node_modules/pgpass/lib/helper.js.map +0 -1
- package/out/node_modules/.pnpm/pgpass@1.0.5/node_modules/pgpass/lib/index.js +0 -21
- package/out/node_modules/.pnpm/pgpass@1.0.5/node_modules/pgpass/lib/index.js.map +0 -1
- package/out/node_modules/.pnpm/postgres-array@2.0.0/node_modules/postgres-array/index.js +0 -84
- package/out/node_modules/.pnpm/postgres-array@2.0.0/node_modules/postgres-array/index.js.map +0 -1
- package/out/node_modules/.pnpm/postgres-bytea@1.0.1/node_modules/postgres-bytea/index.js +0 -28
- package/out/node_modules/.pnpm/postgres-bytea@1.0.1/node_modules/postgres-bytea/index.js.map +0 -1
- package/out/node_modules/.pnpm/postgres-date@1.0.7/node_modules/postgres-date/index.js +0 -65
- package/out/node_modules/.pnpm/postgres-date@1.0.7/node_modules/postgres-date/index.js.map +0 -1
- package/out/node_modules/.pnpm/postgres-interval@1.2.0/node_modules/postgres-interval/index.js +0 -107
- package/out/node_modules/.pnpm/postgres-interval@1.2.0/node_modules/postgres-interval/index.js.map +0 -1
- package/out/node_modules/.pnpm/react@18.3.1/node_modules/react/cjs/react-jsx-runtime.development.js +0 -696
- package/out/node_modules/.pnpm/react@18.3.1/node_modules/react/cjs/react-jsx-runtime.development.js.map +0 -1
- package/out/node_modules/.pnpm/react@18.3.1/node_modules/react/cjs/react-jsx-runtime.production.min.js +0 -44
- package/out/node_modules/.pnpm/react@18.3.1/node_modules/react/cjs/react-jsx-runtime.production.min.js.map +0 -1
- package/out/node_modules/.pnpm/react@18.3.1/node_modules/react/cjs/react.development.js +0 -1585
- package/out/node_modules/.pnpm/react@18.3.1/node_modules/react/cjs/react.development.js.map +0 -1
- package/out/node_modules/.pnpm/react@18.3.1/node_modules/react/cjs/react.production.min.js +0 -329
- package/out/node_modules/.pnpm/react@18.3.1/node_modules/react/cjs/react.production.min.js.map +0 -1
- package/out/node_modules/.pnpm/react@18.3.1/node_modules/react/index.js +0 -13
- package/out/node_modules/.pnpm/react@18.3.1/node_modules/react/index.js.map +0 -1
- package/out/node_modules/.pnpm/react@18.3.1/node_modules/react/jsx-runtime.js +0 -13
- package/out/node_modules/.pnpm/react@18.3.1/node_modules/react/jsx-runtime.js.map +0 -1
- package/out/node_modules/.pnpm/solid-js@1.9.13/node_modules/solid-js/dist/server.js +0 -131
- package/out/node_modules/.pnpm/solid-js@1.9.13/node_modules/solid-js/dist/server.js.map +0 -1
- package/out/node_modules/.pnpm/solid-js@1.9.13/node_modules/solid-js/store/dist/server.js +0 -96
- package/out/node_modules/.pnpm/solid-js@1.9.13/node_modules/solid-js/store/dist/server.js.map +0 -1
- package/out/node_modules/.pnpm/split2@4.2.0/node_modules/split2/index.js +0 -95
- package/out/node_modules/.pnpm/split2@4.2.0/node_modules/split2/index.js.map +0 -1
- package/out/node_modules/.pnpm/xtend@4.0.2/node_modules/xtend/mutable.js +0 -18
- package/out/node_modules/.pnpm/xtend@4.0.2/node_modules/xtend/mutable.js.map +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"cvr-store.js","names":["#schema","#taskID","#id","#failService","#db","#writes","#pendingRowRecordUpdates","#forceUpdates","#rowCache","#loadAttemptIntervalMs","#maxLoadAttempts","#pendingQueryUpdates","#pendingDesireUpdates","#pendingQueryPartialUpdates","#load","#cvr","#pendingInstanceWrite","#updateQueryFields","#checkVersionAndOwnership","#flush","#rowCount","#flushDesires","#flushQueries"],"sources":["../../../../../../zero-cache/src/services/view-syncer/cvr-store.ts"],"sourcesContent":["import {trace} from '@opentelemetry/api';\nimport type {LogContext} from '@rocicorp/logger';\nimport type {MaybeRow, PendingQuery, Row} from 'postgres';\nimport {startAsyncSpan} from '../../../../otel/src/span.ts';\nimport {version} from '../../../../otel/src/version.ts';\nimport {assert} from '../../../../shared/src/asserts.ts';\nimport {CustomKeyMap} from '../../../../shared/src/custom-key-map.ts';\nimport {CustomKeySet} from '../../../../shared/src/custom-key-set.ts';\nimport {\n deepEqual,\n type ReadonlyJSONValue,\n} from '../../../../shared/src/json.ts';\nimport {sleep} from '../../../../shared/src/sleep.ts';\nimport * as v from '../../../../shared/src/valita.ts';\nimport {astSchema} from '../../../../zero-protocol/src/ast.ts';\nimport {clientSchemaSchema} from '../../../../zero-protocol/src/client-schema.ts';\nimport {ErrorKind} from '../../../../zero-protocol/src/error-kind.ts';\nimport {ErrorOrigin} from '../../../../zero-protocol/src/error-origin.ts';\nimport type {InspectQueryRow} from '../../../../zero-protocol/src/inspect-down.ts';\nimport {clampTTL, DEFAULT_TTL_MS} from '../../../../zql/src/query/ttl.ts';\nimport * as Mode from '../../db/mode-enum.ts';\nimport {runTx} from '../../db/run-transaction.ts';\nimport {TransactionPool} from '../../db/transaction-pool.ts';\nimport {recordRowsSynced} from '../../server/anonymous-otel-start.ts';\nimport {ProtocolErrorWithLevel} from '../../types/error-with-level.ts';\nimport type {PostgresDB, PostgresTransaction} from '../../types/pg.ts';\nimport {rowIDString} from '../../types/row-key.ts';\nimport {cvrSchema, type ShardID} from '../../types/shards.ts';\nimport type {Patch, PatchToVersion} from './client-handler.ts';\nimport type {CVR, CVRSnapshot} from './cvr.ts';\nimport {RowRecordCache} from './row-record-cache.ts';\nimport {\n type ClientsRow,\n type DesiresRow,\n type InstancesRow,\n type QueriesRow,\n type RowsRow,\n} from './schema/cvr.ts';\nimport {\n type ClientQueryRecord,\n type ClientRecord,\n cmpVersions,\n type CustomQueryRecord,\n type CVRVersion,\n EMPTY_CVR_VERSION,\n type InternalQueryRecord,\n type NullableCVRVersion,\n type QueryPatch,\n type QueryRecord,\n queryRecordToQueryRow,\n type RowID,\n type RowRecord,\n versionFromString,\n versionString,\n} from './schema/types.ts';\nimport {\n type TTLClock,\n ttlClockAsNumber,\n ttlClockFromNumber,\n} from './ttl-clock.ts';\n\nexport type CVRFlushStats = {\n instances: number;\n queries: number;\n desires: number;\n clients: number;\n rows: number;\n rowsDeferred: number;\n statements: number;\n};\n\nlet flushCounter = 0;\n\n/**\n * Convert TTL/timestamp values for both old (seconds-based) and new (ms-based) columns.\n * Old columns: inactivatedAt (TIMESTAMPTZ), ttl (INTERVAL) - need conversion ms->seconds\n * New columns: inactivatedAtMs (DOUBLE PRECISION), ttlMs (DOUBLE PRECISION) - store ms directly\n */\nfunction convertTTLValues(\n inactivatedAt: TTLClock | undefined,\n ttl: number,\n): {\n ttlInterval: number | null;\n ttlMs: number | null;\n inactivatedAtTimestamp: TTLClock | null;\n inactivatedAtMs: TTLClock | null;\n} {\n return {\n ttlInterval: ttl < 0 ? null : ttl / 1000, // INTERVAL needs seconds\n ttlMs: ttl < 0 ? null : ttl, // New column stores ms directly\n inactivatedAtTimestamp:\n inactivatedAt === undefined\n ? null\n : ttlClockFromNumber(ttlClockAsNumber(inactivatedAt) / 1000),\n inactivatedAtMs: inactivatedAt ?? null,\n };\n}\n\nconst tracer = trace.getTracer('cvr-store', version);\n\n/**\n * QueriesRow with queryArgs as a stringified JSON value.\n * Used for batched config writes where queryArgs are pre-stringified\n * to handle the postgres.js boolean array bug.\n */\ntype StringifiedQueriesRow = Omit<QueriesRow, 'queryArgs'> & {\n queryArgs: string | null;\n};\n\nfunction asQuery(row: QueriesRow): QueryRecord {\n const maybeVersion = (s: string | null) =>\n s === null ? undefined : versionFromString(s);\n\n // Only attach rowSetSignature when the column is non-null, so existing\n // snapshots that don't include the field don't break.\n const sigField = row.rowSetSignature\n ? {rowSetSignature: row.rowSetSignature}\n : {};\n\n if (row.clientAST === null) {\n // custom query\n assert(\n row.queryName !== null && row.queryArgs !== null,\n 'queryName and queryArgs must be set for custom queries',\n );\n return {\n type: 'custom',\n id: row.queryHash,\n name: row.queryName,\n args: row.queryArgs,\n patchVersion: maybeVersion(row.patchVersion),\n clientState: {},\n transformationHash: row.transformationHash ?? undefined,\n transformationVersion: maybeVersion(row.transformationVersion),\n ...sigField,\n } satisfies CustomQueryRecord;\n }\n\n const ast = astSchema.parse(row.clientAST);\n return row.internal\n ? ({\n type: 'internal',\n id: row.queryHash,\n ast,\n transformationHash: row.transformationHash ?? undefined,\n transformationVersion: maybeVersion(row.transformationVersion),\n ...sigField,\n } satisfies InternalQueryRecord)\n : ({\n type: 'client',\n id: row.queryHash,\n ast,\n patchVersion: maybeVersion(row.patchVersion),\n clientState: {},\n transformationHash: row.transformationHash ?? undefined,\n transformationVersion: maybeVersion(row.transformationVersion),\n ...sigField,\n } satisfies ClientQueryRecord);\n}\n\n// The time to wait between load attempts.\nconst LOAD_ATTEMPT_INTERVAL_MS = 500;\n// The maximum number of load() attempts if the rowsVersion is behind.\n// This currently results in a maximum catchup time of ~5 seconds, after\n// which we give up and consider the CVR invalid.\n//\n// TODO: Make this configurable with something like --max-catchup-wait-ms,\n// as it is technically application specific.\nconst MAX_LOAD_ATTEMPTS = 10;\n\nexport class CVRStore {\n readonly #schema: string;\n readonly #taskID: string;\n readonly #id: string;\n readonly #failService: (e: unknown) => void;\n readonly #db: PostgresDB;\n readonly #writes: Set<{\n stats: Partial<CVRFlushStats>;\n write: (\n tx: PostgresTransaction,\n lastConnectTime: number,\n ) => PendingQuery<MaybeRow[]>;\n }> = new Set();\n // Stored separately so repeated putInstance() calls (e.g. setClientSchema,\n // setProfileID, and the final call in #flush) replace each other rather than\n // accumulating as independent statements in #writes.\n #pendingInstanceWrite:\n | ((\n tx: PostgresTransaction,\n lastConnectTime: number,\n ) => PendingQuery<MaybeRow[]>)\n | undefined = undefined;\n readonly #pendingRowRecordUpdates = new CustomKeyMap<RowID, RowRecord | null>(\n rowIDString,\n );\n readonly #forceUpdates = new CustomKeySet<RowID>(rowIDString);\n readonly #rowCache: RowRecordCache;\n readonly #loadAttemptIntervalMs: number;\n readonly #maxLoadAttempts: number;\n #rowCount: number = 0;\n readonly #pendingQueryUpdates = new Map<string, StringifiedQueriesRow>();\n readonly #pendingDesireUpdates = new Map<string, DesiresRow>();\n readonly #pendingQueryPartialUpdates = new Map<string, Partial<QueriesRow>>();\n\n constructor(\n lc: LogContext,\n cvrDb: PostgresDB,\n shard: ShardID,\n taskID: string,\n cvrID: string,\n failService: (e: unknown) => void,\n loadAttemptIntervalMs = LOAD_ATTEMPT_INTERVAL_MS,\n maxLoadAttempts = MAX_LOAD_ATTEMPTS,\n deferredRowFlushThreshold = 100, // somewhat arbitrary\n setTimeoutFn = setTimeout,\n ) {\n this.#failService = failService;\n this.#db = cvrDb;\n this.#schema = cvrSchema(shard);\n this.#taskID = taskID;\n this.#id = cvrID;\n this.#rowCache = new RowRecordCache(\n lc,\n cvrDb,\n shard,\n cvrID,\n failService,\n deferredRowFlushThreshold,\n setTimeoutFn,\n );\n this.#loadAttemptIntervalMs = loadAttemptIntervalMs;\n this.#maxLoadAttempts = maxLoadAttempts;\n }\n\n #cvr(table: string) {\n return this.#db(`${this.#schema}.${table}`);\n }\n\n #updateQueryFields(queryHash: string, fields: Partial<QueriesRow>): void {\n // Track as partial-only update for batched flush. Merge into any\n // pre-existing partial update for the same hash so independent callers\n // (e.g. updateQuery + updateRowSetSignature) don't clobber each other.\n const existing = this.#pendingQueryPartialUpdates.get(queryHash);\n this.#pendingQueryPartialUpdates.set(\n queryHash,\n existing ? {...existing, ...fields} : fields,\n );\n }\n\n load(lc: LogContext, lastConnectTime: number): Promise<CVR> {\n return startAsyncSpan(tracer, 'cvr.load', async () => {\n let err: RowsVersionBehindError | undefined;\n for (let i = 0; i < this.#maxLoadAttempts; i++) {\n if (i > 0) {\n await sleep(this.#loadAttemptIntervalMs);\n }\n const result = await this.#load(lc, lastConnectTime);\n if (result instanceof RowsVersionBehindError) {\n lc.info?.(`attempt ${i + 1}: ${String(result)}`);\n err = result;\n continue;\n }\n return result;\n }\n assert(err, 'Expected error to be set after retry loop exhausted');\n throw new ClientNotFoundError(\n `max attempts exceeded waiting for CVR@${err.cvrVersion} to catch up from ${err.rowsVersion}`,\n );\n });\n }\n\n async #load(\n lc: LogContext,\n lastConnectTime: number,\n ): Promise<CVR | RowsVersionBehindError> {\n const start = Date.now();\n\n const id = this.#id;\n const cvr: CVR = {\n id,\n version: EMPTY_CVR_VERSION,\n lastActive: 0,\n ttlClock: ttlClockFromNumber(0), // TTL clock starts at 0, not Date.now()\n replicaVersion: null,\n clients: {},\n queries: {},\n clientSchema: null,\n profileID: null,\n };\n\n const [instance, clientsRows, queryRows, desiresRows] = await runTx(\n this.#db,\n tx => {\n lc.debug?.(`CVR tx started after ${Date.now() - start} ms`);\n return [\n tx<\n (Omit<InstancesRow, 'clientGroupID'> & {\n profileID: string | null;\n deleted: boolean;\n rowsVersion: string | null;\n })[]\n >`SELECT cvr.\"version\",\n \"lastActive\",\n \"ttlClock\",\n \"replicaVersion\",\n \"owner\",\n \"grantedAt\",\n \"clientSchema\",\n \"profileID\",\n \"deleted\",\n rows.\"version\" as \"rowsVersion\"\n FROM ${this.#cvr('instances')} AS cvr\n LEFT JOIN ${this.#cvr('rowsVersion')} AS rows\n ON cvr.\"clientGroupID\" = rows.\"clientGroupID\"\n WHERE cvr.\"clientGroupID\" = ${id}`,\n tx<Pick<ClientsRow, 'clientID'>[]>`SELECT \"clientID\" FROM ${this.#cvr(\n 'clients',\n )}\n WHERE \"clientGroupID\" = ${id}`,\n tx<QueriesRow[]>`SELECT\n \"clientGroupID\",\n \"queryHash\",\n \"clientAST\",\n \"queryName\",\n \"queryArgs\",\n \"patchVersion\",\n \"transformationHash\",\n \"transformationVersion\",\n \"internal\",\n \"deleted\",\n \"rowSetSignature\"\n FROM ${this.#cvr('queries')}\n WHERE \"clientGroupID\" = ${id} AND deleted IS DISTINCT FROM true`,\n tx<DesiresRow[]>`SELECT\n \"clientGroupID\",\n \"clientID\",\n \"queryHash\",\n \"patchVersion\",\n \"deleted\",\n \"ttlMs\" AS \"ttl\",\n \"inactivatedAtMs\" AS \"inactivatedAt\"\n FROM ${this.#cvr('desires')}\n WHERE \"clientGroupID\" = ${id}`,\n ];\n },\n {mode: Mode.READONLY},\n );\n lc.debug?.(\n `CVR tx completed after ${Date.now() - start} ms ` +\n `(${clientsRows.length} clients, ${queryRows.length} queries, ${desiresRows.length} desires)`,\n );\n\n if (instance.length === 0) {\n // This is the first time we see this CVR.\n this.putInstance({\n version: cvr.version,\n lastActive: 0,\n ttlClock: ttlClockFromNumber(0), // TTL clock starts at 0 for new instances\n replicaVersion: null,\n clientSchema: null,\n profileID: null,\n });\n } else {\n assert(\n instance.length === 1,\n () => `Expected exactly one CVR instance, got ${instance.length}`,\n );\n const {\n version,\n lastActive,\n ttlClock,\n replicaVersion,\n owner,\n grantedAt,\n rowsVersion,\n clientSchema,\n profileID,\n deleted,\n } = instance[0];\n\n if (deleted) {\n throw new ClientNotFoundError(\n 'Client has been purged due to inactivity',\n );\n }\n\n if (owner !== this.#taskID) {\n if ((grantedAt ?? 0) > lastConnectTime) {\n throw new OwnershipError(owner, grantedAt, lastConnectTime);\n } else {\n // Fire-and-forget an ownership change to signal the current owner.\n // Note that the query is structured such that it only succeeds in the\n // correct conditions (i.e. gated on `grantedAt`).\n void this.#db`\n UPDATE ${this.#cvr('instances')} \n SET \"owner\" = ${this.#taskID}, \n \"grantedAt\" = ${lastConnectTime}\n WHERE \"clientGroupID\" = ${this.#id} AND\n (\"grantedAt\" IS NULL OR\n \"grantedAt\" <= to_timestamp(${lastConnectTime / 1000}))\n `\n .execute()\n .catch(this.#failService);\n }\n }\n\n if (version !== (rowsVersion ?? EMPTY_CVR_VERSION.stateVersion)) {\n // This will cause the load() method to wait for row catchup and retry.\n // Assuming the ownership signal succeeds, the current owner will stop\n // modifying the CVR and flush its pending row changes.\n return new RowsVersionBehindError(version, rowsVersion);\n }\n\n cvr.version = versionFromString(version);\n cvr.lastActive = lastActive;\n cvr.ttlClock = ttlClock;\n cvr.replicaVersion = replicaVersion;\n cvr.profileID = profileID;\n\n try {\n cvr.clientSchema =\n clientSchema === null\n ? null\n : v.parse(clientSchema, clientSchemaSchema);\n } catch (e) {\n throw new InvalidClientSchemaError(e);\n }\n }\n\n for (const row of clientsRows) {\n cvr.clients[row.clientID] = {\n id: row.clientID,\n desiredQueryIDs: [],\n };\n }\n\n for (const row of queryRows) {\n const query = asQuery(row);\n cvr.queries[row.queryHash] = query;\n }\n\n for (const row of desiresRows) {\n const client = cvr.clients[row.clientID];\n // Note: row.inactivatedAt is mapped from inactivatedAtMs in the SQL query\n if (!row.deleted && row.inactivatedAt === null) {\n if (client) {\n client.desiredQueryIDs.push(row.queryHash);\n } else {\n // This can happen if the client was deleted but the queries are still alive.\n lc.debug?.(\n `Not adding to desiredQueryIDs for client ${row.clientID} because it has been deleted.`,\n );\n }\n }\n\n const query = cvr.queries[row.queryHash];\n if (\n query &&\n query.type !== 'internal' &&\n (!row.deleted || row.inactivatedAt !== null)\n ) {\n query.clientState[row.clientID] = {\n inactivatedAt: row.inactivatedAt ?? undefined,\n ttl: clampTTL(row.ttl ?? DEFAULT_TTL_MS),\n version: versionFromString(row.patchVersion),\n };\n }\n }\n\n lc.info?.(\n `loaded cvr@${versionString(cvr.version)} (${Date.now() - start} ms)`,\n );\n\n // why do we not sort `desiredQueryIDs` here?\n\n return cvr;\n }\n\n getRowRecords(): Promise<ReadonlyMap<RowID, RowRecord>> {\n return this.#rowCache.getRowRecords();\n }\n\n putRowRecord(row: RowRecord): void {\n this.#pendingRowRecordUpdates.set(row.id, row);\n }\n\n /**\n * Note: Removing a row from the CVR should be represented by a\n * {@link putRowRecord()} with `refCounts: null` in order to properly\n * produce the appropriate delete patch when catching up old clients.\n *\n * This `delRowRecord()` method, on the other hand, is only used for\n * \"canceling\" the put of a row that was not in the CVR in the first place.\n */\n delRowRecord(id: RowID): void {\n this.#pendingRowRecordUpdates.set(id, null);\n }\n\n /**\n * Overrides the default logic that removes no-op writes and forces\n * the updates for the given row `ids`. This has no effect if there\n * are no corresponding puts or dels for the associated row records.\n */\n forceUpdates(...ids: RowID[]) {\n for (const id of ids) {\n this.#forceUpdates.add(id);\n }\n }\n\n /**\n * Updates the `ttlClock` of the CVR instance. The ttlClock starts at 0 when\n * the CVR instance is first created and increments based on elapsed time\n * since the base time established by the ViewSyncerService.\n */\n async updateTTLClock(ttlClock: TTLClock, lastActive: number): Promise<void> {\n await this.#db`UPDATE ${this.#cvr('instances')}\n SET \"lastActive\" = ${lastActive},\n \"ttlClock\" = ${ttlClock}\n WHERE \"clientGroupID\" = ${this.#id}`.execute();\n }\n\n /**\n * @returns This returns the current `ttlClock` of the CVR instance. The ttlClock\n * represents elapsed time since the instance was created (starting from 0).\n * If the CVR has never been initialized for this client group, it returns\n * `undefined`.\n */\n async getTTLClock(): Promise<TTLClock | undefined> {\n const result = await this.#db<Pick<InstancesRow, 'ttlClock'>[]>`\n SELECT \"ttlClock\" FROM ${this.#cvr('instances')}\n WHERE \"clientGroupID\" = ${this.#id}`.values();\n if (result.length === 0) {\n // This can happen if the CVR has not been initialized yet.\n return undefined;\n }\n assert(\n result.length === 1,\n () => `Expected exactly one rowsVersion result, got ${result.length}`,\n );\n return result[0][0];\n }\n\n putInstance({\n version,\n replicaVersion,\n lastActive,\n clientSchema,\n profileID,\n ttlClock,\n }: Pick<\n CVRSnapshot,\n | 'version'\n | 'replicaVersion'\n | 'lastActive'\n | 'clientSchema'\n | 'profileID'\n | 'ttlClock'\n >): void {\n // Overwrite any previously queued instance write — only the last call\n // matters since they all target the same row.\n this.#pendingInstanceWrite = (tx, lastConnectTime) => {\n const change: InstancesRow = {\n clientGroupID: this.#id,\n version: versionString(version),\n lastActive,\n ttlClock,\n replicaVersion,\n owner: this.#taskID,\n grantedAt: lastConnectTime,\n clientSchema,\n profileID,\n };\n return tx`\n INSERT INTO ${this.#cvr('instances')} ${tx(change)} \n ON CONFLICT (\"clientGroupID\") DO UPDATE SET ${tx(change)}`;\n };\n }\n\n markQueryAsDeleted(version: CVRVersion, queryPatch: QueryPatch): void {\n this.#updateQueryFields(queryPatch.id, {\n patchVersion: versionString(version),\n deleted: true,\n transformationHash: null,\n transformationVersion: null,\n });\n }\n\n putQuery(query: QueryRecord): void {\n const change = queryRecordToQueryRow(this.#id, query);\n\n const c = {\n ...change,\n // Pre-stringify queryArgs to handle postgres.js boolean array bug\n queryArgs:\n change.queryArgs !== null ? JSON.stringify(change.queryArgs) : null,\n transformationHash: change.transformationHash ?? null,\n transformationVersion: change.transformationVersion ?? null,\n deleted: change.deleted ?? false,\n };\n this.#pendingQueryUpdates.set(query.id, c);\n }\n\n updateQuery(query: QueryRecord) {\n const maybeVersionString = (v: CVRVersion | undefined) =>\n v ? versionString(v) : null;\n this.#updateQueryFields(query.id, {\n patchVersion:\n query.type === 'internal'\n ? null\n : maybeVersionString(query.patchVersion),\n transformationHash: query.transformationHash ?? null,\n transformationVersion: maybeVersionString(query.transformationVersion),\n deleted: false,\n });\n }\n\n updateRowSetSignature(queryHash: string, signature: string): void {\n this.#updateQueryFields(queryHash, {rowSetSignature: signature});\n }\n\n insertClient(client: ClientRecord): void {\n const change: ClientsRow = {\n clientGroupID: this.#id,\n clientID: client.id,\n };\n\n this.#writes.add({\n stats: {clients: 1},\n write: tx => tx`INSERT INTO ${this.#cvr('clients')} ${tx(change)}`,\n });\n }\n\n deleteClient(clientID: string) {\n this.#writes.add({\n stats: {clients: 1},\n write: sql =>\n sql`DELETE FROM ${this.#cvr('clients')}\n WHERE \"clientGroupID\" = ${this.#id}\n AND \"clientID\" = ${clientID}`,\n });\n }\n\n putDesiredQuery(\n newVersion: CVRVersion,\n query: {id: string},\n client: {id: string},\n deleted: boolean,\n inactivatedAt: TTLClock | undefined,\n ttl: number,\n ): void {\n const {ttlMs, inactivatedAtMs} = convertTTLValues(inactivatedAt, ttl);\n\n const change: DesiresRow = {\n clientGroupID: this.#id,\n clientID: client.id,\n deleted,\n inactivatedAt: inactivatedAtMs,\n patchVersion: versionString(newVersion),\n queryHash: query.id,\n ttl: ttlMs,\n };\n\n // Use composite key to deduplicate/replace entries for the same client-query pair\n const key = `${client.id}:${query.id}`;\n this.#pendingDesireUpdates.set(key, change);\n }\n\n catchupRowPatches(\n lc: LogContext,\n afterVersion: NullableCVRVersion,\n upToCVR: CVRSnapshot,\n current: CVRVersion,\n excludeQueryHashes: string[] = [],\n ): AsyncGenerator<RowsRow[], void, undefined> {\n return this.#rowCache.catchupRowPatches(\n lc,\n afterVersion,\n upToCVR,\n current,\n excludeQueryHashes,\n );\n }\n\n async catchupConfigPatches(\n lc: LogContext,\n afterVersion: NullableCVRVersion,\n upToCVR: CVRSnapshot,\n current: CVRVersion,\n ): Promise<PatchToVersion[]> {\n if (cmpVersions(afterVersion, upToCVR.version) >= 0) {\n return [];\n }\n\n const startMs = Date.now();\n const start = afterVersion ? versionString(afterVersion) : '';\n const end = versionString(upToCVR.version);\n lc.debug?.(`scanning config patches for clients from ${start}`);\n\n const reader = new TransactionPool(lc, {mode: Mode.READONLY}).run(this.#db);\n try {\n // Verify that we are reading the right version of the CVR.\n await reader.processReadTask(tx =>\n checkVersion(tx, this.#schema, this.#id, current),\n );\n\n const [allDesires, queryRows] = await reader.processReadTask(tx =>\n Promise.all([\n tx<DesiresRow[]>`\n SELECT\n \"clientGroupID\",\n \"clientID\",\n \"queryHash\",\n \"patchVersion\",\n \"deleted\",\n \"ttl\",\n \"inactivatedAt\"\n FROM ${this.#cvr('desires')}\n WHERE \"clientGroupID\" = ${this.#id}\n AND \"patchVersion\" > ${start}\n AND \"patchVersion\" <= ${end}`,\n tx<Pick<QueriesRow, 'deleted' | 'queryHash' | 'patchVersion'>[]>`\n SELECT deleted, \"queryHash\", \"patchVersion\" FROM ${this.#cvr('queries')}\n WHERE \"clientGroupID\" = ${this.#id}\n AND \"patchVersion\" > ${start}\n AND \"patchVersion\" <= ${end}`,\n ]),\n );\n\n const patches: PatchToVersion[] = [];\n for (const row of queryRows) {\n const {queryHash: id} = row;\n const patch: Patch = row.deleted\n ? {type: 'query', op: 'del', id}\n : {type: 'query', op: 'put', id};\n const v = row.patchVersion;\n assert(v, 'patchVersion must be set for query patches');\n patches.push({patch, toVersion: versionFromString(v)});\n }\n for (const row of allDesires) {\n const {clientID, queryHash: id} = row;\n const patch: Patch = row.deleted\n ? {type: 'query', op: 'del', id, clientID}\n : {type: 'query', op: 'put', id, clientID};\n patches.push({patch, toVersion: versionFromString(row.patchVersion)});\n }\n\n lc.debug?.(\n `${patches.length} config patches (${Date.now() - startMs} ms)`,\n );\n return patches;\n } finally {\n reader.setDone();\n }\n }\n\n #flushQueries(\n tx: PostgresTransaction,\n lc: LogContext,\n ): PendingQuery<Row[]>[] {\n // Merge partial updates into full updates\n const partialOnly = new Map<string, Partial<QueriesRow>>();\n for (const [queryHash, partial] of this.#pendingQueryPartialUpdates) {\n const existing = this.#pendingQueryUpdates.get(queryHash);\n if (existing) {\n // Merge partial into full update\n Object.assign(existing, partial);\n } else {\n // Track partial-only updates to batch separately\n partialOnly.set(queryHash, partial);\n }\n }\n\n const queries: PendingQuery<Row[]>[] = [];\n\n // Batch full updates\n if (this.#pendingQueryUpdates.size > 0) {\n const rows = [...this.#pendingQueryUpdates.values()];\n lc.debug?.(`Batch flushing ${rows.length} full query updates`);\n\n queries.push(tx`\n INSERT INTO ${this.#cvr('queries')} (\n \"clientGroupID\",\n \"queryHash\",\n \"clientAST\",\n \"queryName\",\n \"queryArgs\",\n \"patchVersion\",\n \"transformationHash\",\n \"transformationVersion\",\n \"internal\",\n \"deleted\",\n \"rowSetSignature\"\n )\n SELECT\n \"clientGroupID\",\n \"queryHash\",\n \"clientAST\",\n \"queryName\",\n CASE\n WHEN \"queryArgs\" IS NULL THEN NULL\n ELSE \"queryArgs\"::json\n END,\n \"patchVersion\",\n \"transformationHash\",\n \"transformationVersion\",\n \"internal\",\n \"deleted\",\n \"rowSetSignature\"\n FROM json_to_recordset(${rows}) AS x(\n \"clientGroupID\" TEXT,\n \"queryHash\" TEXT,\n \"clientAST\" JSONB,\n \"queryName\" TEXT,\n \"queryArgs\" TEXT,\n \"patchVersion\" TEXT,\n \"transformationHash\" TEXT,\n \"transformationVersion\" TEXT,\n \"internal\" BOOLEAN,\n \"deleted\" BOOLEAN,\n \"rowSetSignature\" TEXT\n )\n ON CONFLICT (\"clientGroupID\", \"queryHash\") DO UPDATE SET\n \"clientAST\" = excluded.\"clientAST\",\n \"queryName\" = excluded.\"queryName\",\n \"queryArgs\" = CASE\n WHEN excluded.\"queryArgs\" IS NULL THEN NULL\n ELSE excluded.\"queryArgs\"::json\n END,\n \"patchVersion\" = excluded.\"patchVersion\",\n \"transformationHash\" = excluded.\"transformationHash\",\n \"transformationVersion\" = excluded.\"transformationVersion\",\n \"internal\" = excluded.\"internal\",\n \"deleted\" = excluded.\"deleted\",\n \"rowSetSignature\" = excluded.\"rowSetSignature\"\n `);\n }\n\n // Batch partial-only updates\n if (partialOnly.size > 0) {\n lc.debug?.(`Batch flushing ${partialOnly.size} partial query updates`);\n const rows = Array.from(\n partialOnly.entries(),\n ([queryHash, partial]) => ({\n clientGroupID: this.#id,\n queryHash,\n patchVersionSet: partial.patchVersion !== undefined,\n patchVersion: partial.patchVersion ?? null,\n deletedSet: partial.deleted !== undefined,\n deleted: partial.deleted ?? null,\n transformationHashSet: partial.transformationHash !== undefined,\n transformationHash: partial.transformationHash ?? null,\n transformationVersionSet: partial.transformationVersion !== undefined,\n transformationVersion: partial.transformationVersion ?? null,\n rowSetSignatureSet: partial.rowSetSignature !== undefined,\n rowSetSignature: partial.rowSetSignature ?? null,\n }),\n );\n queries.push(tx`\n UPDATE ${this.#cvr('queries')} AS q\n SET\n \"patchVersion\" = CASE\n WHEN u.\"patchVersionSet\" THEN u.\"patchVersion\"\n ELSE q.\"patchVersion\"\n END,\n \"deleted\" = CASE\n WHEN u.\"deletedSet\" THEN u.\"deleted\"\n ELSE q.\"deleted\"\n END,\n \"transformationHash\" = CASE\n WHEN u.\"transformationHashSet\" THEN u.\"transformationHash\"\n ELSE q.\"transformationHash\"\n END,\n \"transformationVersion\" = CASE\n WHEN u.\"transformationVersionSet\" THEN u.\"transformationVersion\"\n ELSE q.\"transformationVersion\"\n END,\n \"rowSetSignature\" = CASE\n WHEN u.\"rowSetSignatureSet\" THEN u.\"rowSetSignature\"\n ELSE q.\"rowSetSignature\"\n END\n FROM json_to_recordset(${rows}) AS u(\n \"clientGroupID\" TEXT,\n \"queryHash\" TEXT,\n \"patchVersionSet\" BOOLEAN,\n \"patchVersion\" TEXT,\n \"deletedSet\" BOOLEAN,\n \"deleted\" BOOLEAN,\n \"transformationHashSet\" BOOLEAN,\n \"transformationHash\" TEXT,\n \"transformationVersionSet\" BOOLEAN,\n \"transformationVersion\" TEXT,\n \"rowSetSignatureSet\" BOOLEAN,\n \"rowSetSignature\" TEXT\n )\n WHERE q.\"clientGroupID\" = u.\"clientGroupID\"\n AND q.\"queryHash\" = u.\"queryHash\"\n `);\n }\n\n return queries;\n }\n\n #flushDesires(\n tx: PostgresTransaction,\n lc: LogContext,\n ): PendingQuery<Row[]> | null {\n if (this.#pendingDesireUpdates.size === 0) {\n return null;\n }\n\n const rows = Array.from(this.#pendingDesireUpdates.values(), row => {\n const {ttlInterval, ttlMs, inactivatedAtTimestamp, inactivatedAtMs} =\n convertTTLValues(row.inactivatedAt ?? undefined, row.ttl ?? -1);\n return {\n clientGroupID: row.clientGroupID,\n clientID: row.clientID,\n queryHash: row.queryHash,\n patchVersion: row.patchVersion,\n deleted: row.deleted,\n ttl: ttlInterval,\n ttlMs,\n inactivatedAt: inactivatedAtTimestamp,\n inactivatedAtMs,\n };\n });\n\n lc.debug?.(`Batch flushing ${rows.length} desire updates`);\n\n return tx`\n INSERT INTO ${this.#cvr('desires')} (\n \"clientGroupID\",\n \"clientID\",\n \"queryHash\",\n \"patchVersion\",\n \"deleted\",\n \"ttl\",\n \"ttlMs\",\n \"inactivatedAt\",\n \"inactivatedAtMs\"\n )\n SELECT\n \"clientGroupID\",\n \"clientID\",\n \"queryHash\",\n \"patchVersion\",\n \"deleted\",\n \"ttl\",\n \"ttlMs\",\n CASE\n WHEN \"inactivatedAt\" IS NULL THEN NULL\n -- Divide by 1000 because postgres.js serializeTimestamp treats numbers as ms\n -- and to_timestamp expects seconds. This matches non-batched behavior.\n ELSE to_timestamp(\"inactivatedAt\" / 1000.0)\n END,\n \"inactivatedAtMs\"\n FROM json_to_recordset(${rows}) AS x(\n \"clientGroupID\" TEXT,\n \"clientID\" TEXT,\n \"queryHash\" TEXT,\n \"patchVersion\" TEXT,\n \"deleted\" BOOLEAN,\n \"ttl\" INTERVAL,\n \"ttlMs\" DOUBLE PRECISION,\n \"inactivatedAt\" DOUBLE PRECISION,\n \"inactivatedAtMs\" DOUBLE PRECISION\n )\n ON CONFLICT (\"clientGroupID\", \"clientID\", \"queryHash\") DO UPDATE SET\n \"patchVersion\" = excluded.\"patchVersion\",\n \"deleted\" = excluded.\"deleted\",\n \"ttl\" = excluded.\"ttl\",\n \"ttlMs\" = excluded.\"ttlMs\",\n \"inactivatedAt\" = excluded.\"inactivatedAt\",\n \"inactivatedAtMs\" = excluded.\"inactivatedAtMs\"\n `;\n }\n\n async #checkVersionAndOwnership(\n lc: LogContext,\n tx: PostgresTransaction,\n expectedCurrentVersion: CVRVersion,\n lastConnectTime: number,\n ): Promise<void> {\n const start = Date.now();\n lc.debug?.('checking cvr version and ownership');\n const result = await tx<\n Pick<InstancesRow, 'version' | 'owner' | 'grantedAt'>[]\n >`SELECT \"version\", \"owner\", \"grantedAt\" FROM ${this.#cvr('instances')}\n WHERE \"clientGroupID\" = ${this.#id}\n FOR UPDATE`;\n const expected = versionString(expectedCurrentVersion);\n const {version, owner, grantedAt} =\n result.length > 0\n ? result[0]\n : {\n version: EMPTY_CVR_VERSION.stateVersion,\n owner: null,\n grantedAt: null,\n };\n lc.debug?.(\n 'checked cvr version and ownership in ' + (Date.now() - start) + ' ms',\n );\n if (owner !== this.#taskID && (grantedAt ?? 0) > lastConnectTime) {\n throw new OwnershipError(owner, grantedAt, lastConnectTime);\n }\n if (version !== expected) {\n throw new ConcurrentModificationException(expected, version);\n }\n }\n\n async #flush(\n lc: LogContext,\n expectedCurrentVersion: CVRVersion,\n cvr: CVRSnapshot,\n lastConnectTime: number,\n ): Promise<CVRFlushStats | null> {\n const stats: CVRFlushStats = {\n instances: 0,\n queries: 0,\n desires: 0,\n clients: 0,\n rows: 0,\n rowsDeferred: 0,\n statements: 0,\n };\n if (this.#pendingRowRecordUpdates.size) {\n const existingRowRecords = await this.getRowRecords();\n this.#rowCount = existingRowRecords.size;\n for (const [id, row] of this.#pendingRowRecordUpdates.entries()) {\n if (this.#forceUpdates.has(id)) {\n continue;\n }\n const existing = existingRowRecords.get(id);\n if (\n // Don't delete or add an unreferenced row if it's not in the CVR.\n (existing === undefined && !row?.refCounts) ||\n // Don't write a row record that exactly matches what's in the CVR.\n deepEqual(\n (row ?? undefined) as ReadonlyJSONValue | undefined,\n existing as ReadonlyJSONValue | undefined,\n )\n ) {\n this.#pendingRowRecordUpdates.delete(id);\n }\n }\n }\n if (\n this.#pendingRowRecordUpdates.size === 0 &&\n this.#writes.size === 0 &&\n this.#pendingInstanceWrite === undefined &&\n this.#pendingQueryUpdates.size === 0 &&\n this.#pendingQueryPartialUpdates.size === 0 &&\n this.#pendingDesireUpdates.size === 0\n ) {\n return null;\n }\n // Note: The CVR instance itself is only updated if there are material\n // changes (i.e. changes to the CVR contents) to flush.\n this.putInstance(cvr);\n const start = Date.now();\n lc.debug?.('flush tx beginning');\n\n // Use an async callback so we can await the version/ownership check and\n // validate it INSIDE the transaction. If validation fails, the exception\n // causes postgres.js to ROLLBACK, ensuring no writes are committed on error.\n const results = await runTx(\n this.#db,\n async tx => {\n lc.debug?.(`flush tx begun after ${Date.now() - start} ms`);\n\n // Acquire row-level lock and validate version/ownership before queuing writes.\n // Throwing here (inside the begin callback) rolls back the transaction so that\n // no writes are committed when concurrent modification or ownership errors occur.\n await this.#checkVersionAndOwnership(\n lc,\n tx,\n expectedCurrentVersion,\n lastConnectTime,\n );\n\n const writeQueries = [];\n if (this.#pendingInstanceWrite) {\n writeQueries.push(this.#pendingInstanceWrite(tx, lastConnectTime));\n stats.instances++;\n stats.statements++;\n }\n for (const write of this.#writes) {\n stats.clients += write.stats.clients ?? 0;\n stats.rows += write.stats.rows ?? 0;\n\n writeQueries.push(write.write(tx, lastConnectTime));\n stats.statements++;\n }\n\n // Batch flush config writes\n // Flush queries first (desires depend on queries via foreign key)\n const hasQueryUpdates =\n this.#pendingQueryUpdates.size > 0 ||\n this.#pendingQueryPartialUpdates.size > 0;\n\n const desireFlush = this.#flushDesires(tx, lc);\n\n let queryFlushes: PendingQuery<Row[]>[] = [];\n if (hasQueryUpdates) {\n queryFlushes = this.#flushQueries(tx, lc);\n\n // Count both full updates and partial-only updates\n const partialOnlyCount = [\n ...this.#pendingQueryPartialUpdates.keys(),\n ].filter(key => !this.#pendingQueryUpdates.has(key)).length;\n\n stats.queries = this.#pendingQueryUpdates.size + partialOnlyCount;\n stats.statements +=\n (this.#pendingQueryUpdates.size > 0 ? 1 : 0) +\n (partialOnlyCount > 0 ? 1 : 0);\n\n if (desireFlush) {\n stats.desires = this.#pendingDesireUpdates.size;\n stats.statements++;\n }\n } else if (desireFlush) {\n stats.desires = this.#pendingDesireUpdates.size;\n stats.statements++;\n }\n\n const rowUpdates = this.#rowCache.executeRowUpdates(\n tx,\n cvr.version,\n this.#pendingRowRecordUpdates,\n 'allow-defer',\n lc,\n );\n stats.statements += rowUpdates.length;\n\n // Pipeline writes now that the version check has passed.\n const pipelined = [\n ...writeQueries,\n ...queryFlushes,\n ...(desireFlush ? [desireFlush] : []),\n ...rowUpdates,\n ];\n\n lc.debug?.(`returning ${pipelined.length} queries for pipelining`);\n\n // Explicitly await all pipelined queries. When the begin callback is async,\n // postgres.js does not call Promise.all() on the return value the way it does\n // for sync callbacks, so we must do it ourselves.\n return Promise.all(pipelined);\n },\n {mode: Mode.READ_COMMITTED},\n );\n\n lc.debug?.(`flush tx completed after ${Date.now() - start} ms`);\n\n // Calculate how many row update queries were in the pipeline.\n // Note: the version check was awaited separately and is not in the results array.\n const baseQueries =\n (this.#pendingInstanceWrite ? 1 : 0) +\n this.#writes.size +\n (this.#pendingQueryUpdates.size > 0 ? 1 : 0) +\n ([...this.#pendingQueryPartialUpdates.keys()].filter(\n key => !this.#pendingQueryUpdates.has(key),\n ).length > 0\n ? 1\n : 0) +\n (this.#pendingDesireUpdates.size > 0 ? 1 : 0);\n const rowUpdateCount = results.length - baseQueries;\n\n const rowsFlushed = rowUpdateCount > 0;\n if (!rowsFlushed) {\n stats.rowsDeferred = this.#pendingRowRecordUpdates.size;\n } else {\n stats.rows += this.#pendingRowRecordUpdates.size;\n }\n\n this.#rowCount = await this.#rowCache.apply(\n this.#pendingRowRecordUpdates,\n cvr.version,\n rowsFlushed,\n );\n recordRowsSynced(this.#rowCount);\n\n return stats;\n }\n\n get rowCount(): number {\n return this.#rowCount;\n }\n\n async flush(\n lc: LogContext,\n expectedCurrentVersion: CVRVersion,\n cvr: CVRSnapshot,\n lastConnectTime: number,\n ): Promise<CVRFlushStats | null> {\n const start = performance.now();\n lc = lc.withContext('cvrFlushID', flushCounter++);\n try {\n const stats = await this.#flush(\n lc,\n expectedCurrentVersion,\n cvr,\n lastConnectTime,\n );\n if (stats) {\n const elapsed = performance.now() - start;\n lc.info?.(\n `flushed cvr@${versionString(cvr.version)} ` +\n `${JSON.stringify(stats)} in (${elapsed} ms)`,\n );\n this.#rowCache.recordSyncFlushStats(stats, elapsed);\n }\n return stats;\n } catch (e) {\n // Clear cached state if an error (e.g. ConcurrentModificationException) is encountered.\n this.#rowCache.clear();\n throw e;\n } finally {\n this.#writes.clear();\n this.#pendingInstanceWrite = undefined;\n this.#pendingRowRecordUpdates.clear();\n this.#forceUpdates.clear();\n this.#pendingQueryUpdates.clear();\n this.#pendingDesireUpdates.clear();\n this.#pendingQueryPartialUpdates.clear();\n }\n }\n\n hasPendingUpdates(): boolean {\n return this.#rowCache.hasPendingUpdates();\n }\n\n /** Resolves when all pending updates are flushed. */\n flushed(lc: LogContext): Promise<void> {\n return this.#rowCache.flushed(lc);\n }\n\n async inspectQueries(\n lc: LogContext,\n ttlClock: TTLClock,\n clientID?: string,\n ): Promise<InspectQueryRow[]> {\n const db = this.#db;\n const clientGroupID = this.#id;\n\n const reader = new TransactionPool(lc, {mode: Mode.READONLY}).run(db);\n try {\n return await reader.processReadTask(\n tx => tx<InspectQueryRow[]>`\n SELECT DISTINCT ON (d.\"clientID\", d.\"queryHash\")\n d.\"clientID\",\n d.\"queryHash\" AS \"queryID\",\n COALESCE(d.\"ttlMs\", ${DEFAULT_TTL_MS}) AS \"ttl\",\n d.\"inactivatedAtMs\" AS \"inactivatedAt\",\n (SELECT COUNT(*)::INT FROM ${this.#cvr('rows')} r \n WHERE r.\"clientGroupID\" = d.\"clientGroupID\" \n AND r.\"refCounts\" ? d.\"queryHash\") AS \"rowCount\",\n q.\"clientAST\" AS \"ast\",\n (q.\"patchVersion\" IS NOT NULL) AS \"got\",\n COALESCE(d.\"deleted\", FALSE) AS \"deleted\",\n q.\"queryName\" AS \"name\",\n q.\"queryArgs\" AS \"args\"\n FROM ${this.#cvr('desires')} d\n LEFT JOIN ${this.#cvr('queries')} q\n ON q.\"clientGroupID\" = d.\"clientGroupID\"\n AND q.\"queryHash\" = d.\"queryHash\"\n WHERE d.\"clientGroupID\" = ${clientGroupID}\n ${clientID ? tx`AND d.\"clientID\" = ${clientID}` : tx``}\n AND NOT (\n d.\"inactivatedAtMs\" IS NOT NULL \n AND d.\"ttlMs\" IS NOT NULL \n AND (d.\"inactivatedAtMs\" + d.\"ttlMs\") <= ${ttlClockAsNumber(ttlClock)}\n )\n ORDER BY d.\"clientID\", d.\"queryHash\"`,\n );\n } finally {\n reader.setDone();\n }\n }\n}\n\n/**\n * This is similar to {@link CVRStore.#checkVersionAndOwnership} except\n * that it only checks the version and is suitable for snapshot reads\n * (i.e. by doing a plain `SELECT` rather than a `SELECT ... FOR UPDATE`).\n */\nexport async function checkVersion(\n tx: PostgresTransaction,\n schema: string,\n clientGroupID: string,\n expectedCurrentVersion: CVRVersion,\n): Promise<void> {\n const expected = versionString(expectedCurrentVersion);\n const result = await tx<Pick<InstancesRow, 'version'>[]>`\n SELECT version FROM ${tx(schema)}.instances \n WHERE \"clientGroupID\" = ${clientGroupID}`;\n const {version} =\n result.length > 0 ? result[0] : {version: EMPTY_CVR_VERSION.stateVersion};\n if (version !== expected) {\n throw new ConcurrentModificationException(expected, version);\n }\n}\n\nexport class ClientNotFoundError extends ProtocolErrorWithLevel {\n constructor(message: string) {\n super(\n {\n kind: ErrorKind.ClientNotFound,\n message,\n origin: ErrorOrigin.ZeroCache,\n },\n 'warn',\n );\n }\n}\n\nexport class ConcurrentModificationException extends ProtocolErrorWithLevel {\n readonly name = 'ConcurrentModificationException';\n\n constructor(expectedVersion: string, actualVersion: string) {\n super(\n {\n kind: ErrorKind.Rehome,\n message: `CVR has been concurrently modified. Expected ${expectedVersion}, got ${actualVersion}`,\n origin: ErrorOrigin.ZeroCache,\n },\n 'warn',\n );\n }\n}\n\nexport class OwnershipError extends ProtocolErrorWithLevel {\n readonly name = 'OwnershipError';\n\n constructor(\n owner: string | null,\n grantedAt: number | null,\n lastConnectTime: number,\n ) {\n super(\n {\n kind: ErrorKind.Rehome,\n message:\n `CVR ownership was transferred to ${owner} at ` +\n `${new Date(grantedAt ?? 0).toISOString()} ` +\n `(last connect time: ${new Date(lastConnectTime).toISOString()})`,\n maxBackoffMs: 0,\n origin: ErrorOrigin.ZeroCache,\n },\n 'info',\n );\n }\n}\n\nexport class InvalidClientSchemaError extends ProtocolErrorWithLevel {\n readonly name = 'InvalidClientSchemaError';\n\n constructor(cause: unknown) {\n super(\n {\n kind: ErrorKind.SchemaVersionNotSupported,\n message: `Could not parse clientSchema stored in CVR: ${String(cause)}`,\n origin: ErrorOrigin.ZeroCache,\n },\n 'warn',\n {cause},\n );\n }\n}\n\nexport class RowsVersionBehindError extends Error {\n readonly name = 'RowsVersionBehindError';\n readonly cvrVersion: string;\n readonly rowsVersion: string | null;\n\n constructor(cvrVersion: string, rowsVersion: string | null) {\n super(`rowsVersion (${rowsVersion}) is behind CVR ${cvrVersion}`);\n this.cvrVersion = cvrVersion;\n this.rowsVersion = rowsVersion;\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;AAuEA,IAAI,eAAe;;;;;;AAOnB,SAAS,iBACP,eACA,KAMA;CACA,OAAO;EACL,aAAa,MAAM,IAAI,OAAO,MAAM;EACpC,OAAO,MAAM,IAAI,OAAO;EACxB,wBACE,kBAAkB,KAAA,IACd,OACA,mBAAmB,iBAAiB,aAAa,IAAI,GAAI;EAC/D,iBAAiB,iBAAiB;CACpC;AACF;AAEA,IAAM,SAAS,MAAM,UAAU,aAAa,OAAO;AAWnD,SAAS,QAAQ,KAA8B;CAC7C,MAAM,gBAAgB,MACpB,MAAM,OAAO,KAAA,IAAY,kBAAkB,CAAC;CAI9C,MAAM,WAAW,IAAI,kBACjB,EAAC,iBAAiB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AK,aAAa;EAClB,KAAK,cAAc;CACrB;AACF"}
|
|
1
|
+
{"version":3,"file":"cvr-store.js","names":["#schema","#taskID","#id","#failService","#db","#writes","#pendingRowRecordUpdates","#forceUpdates","#rowCache","#loadAttemptIntervalMs","#maxLoadAttempts","#pendingQueryUpdates","#pendingDesireUpdates","#pendingQueryPartialUpdates","#load","#cvr","#pendingInstanceWrite","#updateQueryFields","#checkVersionAndOwnership","#flush","#rowCount","#flushDesires","#flushQueries"],"sources":["../../../../../../zero-cache/src/services/view-syncer/cvr-store.ts"],"sourcesContent":["import {trace} from '@opentelemetry/api';\nimport type {LogContext} from '@rocicorp/logger';\nimport type {MaybeRow, PendingQuery, Row} from 'postgres';\nimport {startAsyncSpan} from '../../../../otel/src/span.ts';\nimport {version} from '../../../../otel/src/version.ts';\nimport {assert} from '../../../../shared/src/asserts.ts';\nimport {CustomKeyMap} from '../../../../shared/src/custom-key-map.ts';\nimport {CustomKeySet} from '../../../../shared/src/custom-key-set.ts';\nimport {some} from '../../../../shared/src/iterables.ts';\nimport {\n deepEqual,\n type ReadonlyJSONValue,\n} from '../../../../shared/src/json.ts';\nimport {sleep} from '../../../../shared/src/sleep.ts';\nimport * as v from '../../../../shared/src/valita.ts';\nimport {astSchema} from '../../../../zero-protocol/src/ast.ts';\nimport {clientSchemaSchema} from '../../../../zero-protocol/src/client-schema.ts';\nimport {ErrorKind} from '../../../../zero-protocol/src/error-kind.ts';\nimport {ErrorOrigin} from '../../../../zero-protocol/src/error-origin.ts';\nimport type {InspectQueryRow} from '../../../../zero-protocol/src/inspect-down.ts';\nimport {clampTTL, DEFAULT_TTL_MS} from '../../../../zql/src/query/ttl.ts';\nimport * as Mode from '../../db/mode-enum.ts';\nimport {runTx} from '../../db/run-transaction.ts';\nimport {TransactionPool} from '../../db/transaction-pool.ts';\nimport {recordRowsSynced} from '../../server/anonymous-otel-start.ts';\nimport {ProtocolErrorWithLevel} from '../../types/error-with-level.ts';\nimport type {PostgresDB, PostgresTransaction} from '../../types/pg.ts';\nimport {rowIDString} from '../../types/row-key.ts';\nimport {cvrSchema, type ShardID} from '../../types/shards.ts';\nimport type {Patch, PatchToVersion} from './client-handler.ts';\nimport type {CVR, CVRSnapshot} from './cvr.ts';\nimport {RowRecordCache} from './row-record-cache.ts';\nimport {\n type ClientsRow,\n type DesiresRow,\n type InstancesRow,\n type QueriesRow,\n type RowsRow,\n} from './schema/cvr.ts';\nimport {\n type ClientQueryRecord,\n type ClientRecord,\n cmpVersions,\n type CustomQueryRecord,\n type CVRVersion,\n EMPTY_CVR_VERSION,\n type InternalQueryRecord,\n type NullableCVRVersion,\n type QueryPatch,\n type QueryRecord,\n queryRecordToQueryRow,\n type RowID,\n type RowRecord,\n versionFromString,\n versionString,\n} from './schema/types.ts';\nimport {\n type TTLClock,\n ttlClockAsNumber,\n ttlClockFromNumber,\n} from './ttl-clock.ts';\n\nexport type CVRFlushStats = {\n instances: number;\n queries: number;\n desires: number;\n clients: number;\n rows: number;\n rowsDeferred: number;\n statements: number;\n};\n\nlet flushCounter = 0;\n\n/**\n * Convert TTL/timestamp values for both old (seconds-based) and new (ms-based) columns.\n * Old columns: inactivatedAt (TIMESTAMPTZ), ttl (INTERVAL) - need conversion ms->seconds\n * New columns: inactivatedAtMs (DOUBLE PRECISION), ttlMs (DOUBLE PRECISION) - store ms directly\n */\nfunction convertTTLValues(\n inactivatedAt: TTLClock | undefined,\n ttl: number,\n): {\n ttlInterval: number | null;\n ttlMs: number | null;\n inactivatedAtTimestamp: TTLClock | null;\n inactivatedAtMs: TTLClock | null;\n} {\n return {\n ttlInterval: ttl < 0 ? null : ttl / 1000, // INTERVAL needs seconds\n ttlMs: ttl < 0 ? null : ttl, // New column stores ms directly\n inactivatedAtTimestamp:\n inactivatedAt === undefined\n ? null\n : ttlClockFromNumber(ttlClockAsNumber(inactivatedAt) / 1000),\n inactivatedAtMs: inactivatedAt ?? null,\n };\n}\n\nconst tracer = trace.getTracer('cvr-store', version);\n\n/**\n * QueriesRow with queryArgs as a stringified JSON value.\n * Used for batched config writes where queryArgs are pre-stringified\n * to handle the postgres.js boolean array bug.\n */\ntype StringifiedQueriesRow = Omit<QueriesRow, 'queryArgs'> & {\n queryArgs: string | null;\n};\n\nfunction asQuery(row: QueriesRow): QueryRecord {\n const maybeVersion = (s: string | null) =>\n s === null ? undefined : versionFromString(s);\n\n // Only attach rowSetSignature when the column is non-null, so existing\n // snapshots that don't include the field don't break.\n const sigField = row.rowSetSignature\n ? {rowSetSignature: row.rowSetSignature}\n : {};\n\n if (row.clientAST === null) {\n // custom query\n assert(\n row.queryName !== null && row.queryArgs !== null,\n 'queryName and queryArgs must be set for custom queries',\n );\n return {\n type: 'custom',\n id: row.queryHash,\n name: row.queryName,\n args: row.queryArgs,\n patchVersion: maybeVersion(row.patchVersion),\n clientState: {},\n transformationHash: row.transformationHash ?? undefined,\n transformationVersion: maybeVersion(row.transformationVersion),\n ...sigField,\n } satisfies CustomQueryRecord;\n }\n\n const ast = astSchema.parse(row.clientAST);\n return row.internal\n ? ({\n type: 'internal',\n id: row.queryHash,\n ast,\n transformationHash: row.transformationHash ?? undefined,\n transformationVersion: maybeVersion(row.transformationVersion),\n ...sigField,\n } satisfies InternalQueryRecord)\n : ({\n type: 'client',\n id: row.queryHash,\n ast,\n patchVersion: maybeVersion(row.patchVersion),\n clientState: {},\n transformationHash: row.transformationHash ?? undefined,\n transformationVersion: maybeVersion(row.transformationVersion),\n ...sigField,\n } satisfies ClientQueryRecord);\n}\n\n// The time to wait between load attempts.\nconst LOAD_ATTEMPT_INTERVAL_MS = 500;\n// The maximum number of load() attempts if the rowsVersion is behind.\n// This currently results in a maximum catchup time of ~5 seconds, after\n// which we give up and consider the CVR invalid.\n//\n// TODO: Make this configurable with something like --max-catchup-wait-ms,\n// as it is technically application specific.\nconst MAX_LOAD_ATTEMPTS = 10;\n\nexport class CVRStore {\n readonly #schema: string;\n readonly #taskID: string;\n readonly #id: string;\n readonly #failService: (e: unknown) => void;\n readonly #db: PostgresDB;\n readonly #writes: Set<{\n stats: Partial<CVRFlushStats>;\n write: (\n tx: PostgresTransaction,\n lastConnectTime: number,\n ) => PendingQuery<MaybeRow[]>;\n }> = new Set();\n // Stored separately so repeated putInstance() calls (e.g. setClientSchema,\n // setProfileID, and the final call in #flush) replace each other rather than\n // accumulating as independent statements in #writes.\n #pendingInstanceWrite:\n | ((\n tx: PostgresTransaction,\n lastConnectTime: number,\n ) => PendingQuery<MaybeRow[]>)\n | undefined = undefined;\n readonly #pendingRowRecordUpdates = new CustomKeyMap<RowID, RowRecord | null>(\n rowIDString,\n );\n readonly #forceUpdates = new CustomKeySet<RowID>(rowIDString);\n readonly #rowCache: RowRecordCache;\n readonly #loadAttemptIntervalMs: number;\n readonly #maxLoadAttempts: number;\n #rowCount: number = 0;\n readonly #pendingQueryUpdates = new Map<string, StringifiedQueriesRow>();\n readonly #pendingDesireUpdates = new Map<string, DesiresRow>();\n readonly #pendingQueryPartialUpdates = new Map<string, Partial<QueriesRow>>();\n\n constructor(\n lc: LogContext,\n cvrDb: PostgresDB,\n shard: ShardID,\n taskID: string,\n cvrID: string,\n failService: (e: unknown) => void,\n loadAttemptIntervalMs = LOAD_ATTEMPT_INTERVAL_MS,\n maxLoadAttempts = MAX_LOAD_ATTEMPTS,\n deferredRowFlushThreshold = 100, // somewhat arbitrary\n setTimeoutFn = setTimeout,\n ) {\n this.#failService = failService;\n this.#db = cvrDb;\n this.#schema = cvrSchema(shard);\n this.#taskID = taskID;\n this.#id = cvrID;\n this.#rowCache = new RowRecordCache(\n lc,\n cvrDb,\n shard,\n cvrID,\n failService,\n deferredRowFlushThreshold,\n setTimeoutFn,\n );\n this.#loadAttemptIntervalMs = loadAttemptIntervalMs;\n this.#maxLoadAttempts = maxLoadAttempts;\n }\n\n #cvr(table: string) {\n return this.#db(`${this.#schema}.${table}`);\n }\n\n #updateQueryFields(queryHash: string, fields: Partial<QueriesRow>): void {\n // Track as partial-only update for batched flush. Merge into any\n // pre-existing partial update for the same hash so independent callers\n // (e.g. updateQuery + updateRowSetSignature) don't clobber each other.\n const existing = this.#pendingQueryPartialUpdates.get(queryHash);\n this.#pendingQueryPartialUpdates.set(\n queryHash,\n existing ? {...existing, ...fields} : fields,\n );\n }\n\n load(lc: LogContext, lastConnectTime: number): Promise<CVR> {\n return startAsyncSpan(tracer, 'cvr.load', async () => {\n let err: RowsVersionBehindError | undefined;\n for (let i = 0; i < this.#maxLoadAttempts; i++) {\n if (i > 0) {\n await sleep(this.#loadAttemptIntervalMs);\n }\n const result = await this.#load(lc, lastConnectTime);\n if (result instanceof RowsVersionBehindError) {\n lc.info?.(`attempt ${i + 1}: ${String(result)}`);\n err = result;\n continue;\n }\n return result;\n }\n assert(err, 'Expected error to be set after retry loop exhausted');\n throw new ClientNotFoundError(\n `max attempts exceeded waiting for CVR@${err.cvrVersion} to catch up from ${err.rowsVersion}`,\n );\n });\n }\n\n async #load(\n lc: LogContext,\n lastConnectTime: number,\n ): Promise<CVR | RowsVersionBehindError> {\n const start = Date.now();\n\n const id = this.#id;\n const cvr: CVR = {\n id,\n version: EMPTY_CVR_VERSION,\n lastActive: 0,\n ttlClock: ttlClockFromNumber(0), // TTL clock starts at 0, not Date.now()\n replicaVersion: null,\n clients: {},\n queries: {},\n clientSchema: null,\n profileID: null,\n };\n\n const [instance, clientsRows, queryRows, desiresRows] = await runTx(\n this.#db,\n tx => {\n lc.debug?.(`CVR tx started after ${Date.now() - start} ms`);\n return [\n tx<\n (Omit<InstancesRow, 'clientGroupID'> & {\n profileID: string | null;\n deleted: boolean;\n rowsVersion: string | null;\n })[]\n >`SELECT cvr.\"version\",\n \"lastActive\",\n \"ttlClock\",\n \"replicaVersion\",\n \"owner\",\n \"grantedAt\",\n \"clientSchema\",\n \"profileID\",\n \"deleted\",\n rows.\"version\" as \"rowsVersion\"\n FROM ${this.#cvr('instances')} AS cvr\n LEFT JOIN ${this.#cvr('rowsVersion')} AS rows\n ON cvr.\"clientGroupID\" = rows.\"clientGroupID\"\n WHERE cvr.\"clientGroupID\" = ${id}`,\n tx<Pick<ClientsRow, 'clientID'>[]>`SELECT \"clientID\" FROM ${this.#cvr(\n 'clients',\n )}\n WHERE \"clientGroupID\" = ${id}`,\n tx<QueriesRow[]>`SELECT\n \"clientGroupID\",\n \"queryHash\",\n \"clientAST\",\n \"queryName\",\n \"queryArgs\",\n \"patchVersion\",\n \"transformationHash\",\n \"transformationVersion\",\n \"internal\",\n \"deleted\",\n \"rowSetSignature\"\n FROM ${this.#cvr('queries')}\n WHERE \"clientGroupID\" = ${id} AND deleted IS DISTINCT FROM true`,\n tx<DesiresRow[]>`SELECT\n \"clientGroupID\",\n \"clientID\",\n \"queryHash\",\n \"patchVersion\",\n \"deleted\",\n \"ttlMs\" AS \"ttl\",\n \"inactivatedAtMs\" AS \"inactivatedAt\"\n FROM ${this.#cvr('desires')}\n WHERE \"clientGroupID\" = ${id}`,\n ];\n },\n {mode: Mode.READONLY},\n );\n lc.debug?.(\n `CVR tx completed after ${Date.now() - start} ms ` +\n `(${clientsRows.length} clients, ${queryRows.length} queries, ${desiresRows.length} desires)`,\n );\n\n if (instance.length === 0) {\n // This is the first time we see this CVR.\n this.putInstance({\n version: cvr.version,\n lastActive: 0,\n ttlClock: ttlClockFromNumber(0), // TTL clock starts at 0 for new instances\n replicaVersion: null,\n clientSchema: null,\n profileID: null,\n });\n } else {\n assert(\n instance.length === 1,\n () => `Expected exactly one CVR instance, got ${instance.length}`,\n );\n const {\n version,\n lastActive,\n ttlClock,\n replicaVersion,\n owner,\n grantedAt,\n rowsVersion,\n clientSchema,\n profileID,\n deleted,\n } = instance[0];\n\n if (deleted) {\n throw new ClientNotFoundError(\n 'Client has been purged due to inactivity',\n );\n }\n\n if (owner !== this.#taskID) {\n if ((grantedAt ?? 0) > lastConnectTime) {\n throw new OwnershipError(owner, grantedAt, lastConnectTime);\n } else {\n // Fire-and-forget an ownership change to signal the current owner.\n // Note that the query is structured such that it only succeeds in the\n // correct conditions (i.e. gated on `grantedAt`).\n void this.#db`\n UPDATE ${this.#cvr('instances')} \n SET \"owner\" = ${this.#taskID}, \n \"grantedAt\" = ${lastConnectTime}\n WHERE \"clientGroupID\" = ${this.#id} AND\n (\"grantedAt\" IS NULL OR\n \"grantedAt\" <= to_timestamp(${lastConnectTime / 1000}))\n `\n .execute()\n .catch(this.#failService);\n }\n }\n\n if (version !== (rowsVersion ?? EMPTY_CVR_VERSION.stateVersion)) {\n // This will cause the load() method to wait for row catchup and retry.\n // Assuming the ownership signal succeeds, the current owner will stop\n // modifying the CVR and flush its pending row changes.\n return new RowsVersionBehindError(version, rowsVersion);\n }\n\n cvr.version = versionFromString(version);\n cvr.lastActive = lastActive;\n cvr.ttlClock = ttlClock;\n cvr.replicaVersion = replicaVersion;\n cvr.profileID = profileID;\n\n try {\n cvr.clientSchema =\n clientSchema === null\n ? null\n : v.parse(clientSchema, clientSchemaSchema);\n } catch (e) {\n throw new InvalidClientSchemaError(e);\n }\n }\n\n for (const row of clientsRows) {\n cvr.clients[row.clientID] = {\n id: row.clientID,\n desiredQueryIDs: [],\n };\n }\n\n for (const row of queryRows) {\n const query = asQuery(row);\n cvr.queries[row.queryHash] = query;\n }\n\n for (const row of desiresRows) {\n const client = cvr.clients[row.clientID];\n // Note: row.inactivatedAt is mapped from inactivatedAtMs in the SQL query\n if (!row.deleted && row.inactivatedAt === null) {\n if (client) {\n client.desiredQueryIDs.push(row.queryHash);\n } else {\n // This can happen if the client was deleted but the queries are still alive.\n lc.debug?.(\n `Not adding to desiredQueryIDs for client ${row.clientID} because it has been deleted.`,\n );\n }\n }\n\n const query = cvr.queries[row.queryHash];\n if (\n query &&\n query.type !== 'internal' &&\n (!row.deleted || row.inactivatedAt !== null)\n ) {\n query.clientState[row.clientID] = {\n inactivatedAt: row.inactivatedAt ?? undefined,\n ttl: clampTTL(row.ttl ?? DEFAULT_TTL_MS),\n version: versionFromString(row.patchVersion),\n };\n }\n }\n\n lc.info?.(\n `loaded cvr@${versionString(cvr.version)} (${Date.now() - start} ms)`,\n );\n\n // why do we not sort `desiredQueryIDs` here?\n\n return cvr;\n }\n\n getRowRecords(): Promise<ReadonlyMap<RowID, RowRecord>> {\n return this.#rowCache.getRowRecords();\n }\n\n putRowRecord(row: RowRecord): void {\n this.#pendingRowRecordUpdates.set(row.id, row);\n }\n\n /**\n * Note: Removing a row from the CVR should be represented by a\n * {@link putRowRecord()} with `refCounts: null` in order to properly\n * produce the appropriate delete patch when catching up old clients.\n *\n * This `delRowRecord()` method, on the other hand, is only used for\n * \"canceling\" the put of a row that was not in the CVR in the first place.\n */\n delRowRecord(id: RowID): void {\n this.#pendingRowRecordUpdates.set(id, null);\n }\n\n /**\n * Overrides the default logic that removes no-op writes and forces\n * the updates for the given row `ids`. This has no effect if there\n * are no corresponding puts or dels for the associated row records.\n */\n forceUpdates(...ids: RowID[]) {\n for (const id of ids) {\n this.#forceUpdates.add(id);\n }\n }\n\n /**\n * Updates the `ttlClock` of the CVR instance. The ttlClock starts at 0 when\n * the CVR instance is first created and increments based on elapsed time\n * since the base time established by the ViewSyncerService.\n */\n async updateTTLClock(ttlClock: TTLClock, lastActive: number): Promise<void> {\n await this.#db`UPDATE ${this.#cvr('instances')}\n SET \"lastActive\" = ${lastActive},\n \"ttlClock\" = ${ttlClock}\n WHERE \"clientGroupID\" = ${this.#id}`.execute();\n }\n\n /**\n * @returns This returns the current `ttlClock` of the CVR instance. The ttlClock\n * represents elapsed time since the instance was created (starting from 0).\n * If the CVR has never been initialized for this client group, it returns\n * `undefined`.\n */\n async getTTLClock(): Promise<TTLClock | undefined> {\n const result = await this.#db<Pick<InstancesRow, 'ttlClock'>[]>`\n SELECT \"ttlClock\" FROM ${this.#cvr('instances')}\n WHERE \"clientGroupID\" = ${this.#id}`.values();\n if (result.length === 0) {\n // This can happen if the CVR has not been initialized yet.\n return undefined;\n }\n assert(\n result.length === 1,\n () => `Expected exactly one rowsVersion result, got ${result.length}`,\n );\n return result[0][0];\n }\n\n putInstance({\n version,\n replicaVersion,\n lastActive,\n clientSchema,\n profileID,\n ttlClock,\n }: Pick<\n CVRSnapshot,\n | 'version'\n | 'replicaVersion'\n | 'lastActive'\n | 'clientSchema'\n | 'profileID'\n | 'ttlClock'\n >): void {\n // Overwrite any previously queued instance write — only the last call\n // matters since they all target the same row.\n this.#pendingInstanceWrite = (tx, lastConnectTime) => {\n const change: InstancesRow = {\n clientGroupID: this.#id,\n version: versionString(version),\n lastActive,\n ttlClock,\n replicaVersion,\n owner: this.#taskID,\n grantedAt: lastConnectTime,\n clientSchema,\n profileID,\n };\n return tx`\n INSERT INTO ${this.#cvr('instances')} ${tx(change)} \n ON CONFLICT (\"clientGroupID\") DO UPDATE SET ${tx(change)}`;\n };\n }\n\n markQueryAsDeleted(version: CVRVersion, queryPatch: QueryPatch): void {\n this.#updateQueryFields(queryPatch.id, {\n patchVersion: versionString(version),\n deleted: true,\n transformationHash: null,\n transformationVersion: null,\n });\n }\n\n putQuery(query: QueryRecord): void {\n const change = queryRecordToQueryRow(this.#id, query);\n\n const c = {\n ...change,\n // Pre-stringify queryArgs to handle postgres.js boolean array bug\n queryArgs:\n change.queryArgs !== null ? JSON.stringify(change.queryArgs) : null,\n transformationHash: change.transformationHash ?? null,\n transformationVersion: change.transformationVersion ?? null,\n deleted: change.deleted ?? false,\n };\n this.#pendingQueryUpdates.set(query.id, c);\n }\n\n updateQuery(query: QueryRecord) {\n const maybeVersionString = (v: CVRVersion | undefined) =>\n v ? versionString(v) : null;\n this.#updateQueryFields(query.id, {\n patchVersion:\n query.type === 'internal'\n ? null\n : maybeVersionString(query.patchVersion),\n transformationHash: query.transformationHash ?? null,\n transformationVersion: maybeVersionString(query.transformationVersion),\n deleted: false,\n });\n }\n\n updateRowSetSignature(queryHash: string, signature: string): void {\n this.#updateQueryFields(queryHash, {rowSetSignature: signature});\n }\n\n insertClient(client: ClientRecord): void {\n const change: ClientsRow = {\n clientGroupID: this.#id,\n clientID: client.id,\n };\n\n this.#writes.add({\n stats: {clients: 1},\n write: tx => tx`INSERT INTO ${this.#cvr('clients')} ${tx(change)}`,\n });\n }\n\n deleteClient(clientID: string) {\n this.#writes.add({\n stats: {clients: 1},\n write: sql =>\n sql`DELETE FROM ${this.#cvr('clients')}\n WHERE \"clientGroupID\" = ${this.#id}\n AND \"clientID\" = ${clientID}`,\n });\n }\n\n putDesiredQuery(\n newVersion: CVRVersion,\n query: {id: string},\n client: {id: string},\n deleted: boolean,\n inactivatedAt: TTLClock | undefined,\n ttl: number,\n ): void {\n const {ttlMs, inactivatedAtMs} = convertTTLValues(inactivatedAt, ttl);\n\n const change: DesiresRow = {\n clientGroupID: this.#id,\n clientID: client.id,\n deleted,\n inactivatedAt: inactivatedAtMs,\n patchVersion: versionString(newVersion),\n queryHash: query.id,\n ttl: ttlMs,\n };\n\n // Use composite key to deduplicate/replace entries for the same client-query pair\n const key = `${client.id}:${query.id}`;\n this.#pendingDesireUpdates.set(key, change);\n }\n\n catchupRowPatches(\n lc: LogContext,\n afterVersion: NullableCVRVersion,\n upToCVR: CVRSnapshot,\n current: CVRVersion,\n excludeQueryHashes: string[] = [],\n ): AsyncGenerator<RowsRow[], void, undefined> {\n return this.#rowCache.catchupRowPatches(\n lc,\n afterVersion,\n upToCVR,\n current,\n excludeQueryHashes,\n );\n }\n\n async catchupConfigPatches(\n lc: LogContext,\n afterVersion: NullableCVRVersion,\n upToCVR: CVRSnapshot,\n current: CVRVersion,\n ): Promise<PatchToVersion[]> {\n if (cmpVersions(afterVersion, upToCVR.version) >= 0) {\n return [];\n }\n\n const startMs = Date.now();\n const start = afterVersion ? versionString(afterVersion) : '';\n const end = versionString(upToCVR.version);\n lc.debug?.(`scanning config patches for clients from ${start}`);\n\n const reader = new TransactionPool(lc, {mode: Mode.READONLY}).run(this.#db);\n try {\n // Verify that we are reading the right version of the CVR.\n await reader.processReadTask(tx =>\n checkVersion(tx, this.#schema, this.#id, current),\n );\n\n const [allDesires, queryRows] = await reader.processReadTask(tx =>\n Promise.all([\n tx<DesiresRow[]>`\n SELECT\n \"clientGroupID\",\n \"clientID\",\n \"queryHash\",\n \"patchVersion\",\n \"deleted\",\n \"ttl\",\n \"inactivatedAt\"\n FROM ${this.#cvr('desires')}\n WHERE \"clientGroupID\" = ${this.#id}\n AND \"patchVersion\" > ${start}\n AND \"patchVersion\" <= ${end}`,\n tx<Pick<QueriesRow, 'deleted' | 'queryHash' | 'patchVersion'>[]>`\n SELECT deleted, \"queryHash\", \"patchVersion\" FROM ${this.#cvr('queries')}\n WHERE \"clientGroupID\" = ${this.#id}\n AND \"patchVersion\" > ${start}\n AND \"patchVersion\" <= ${end}`,\n ]),\n );\n\n const patches: PatchToVersion[] = [];\n for (const row of queryRows) {\n const {queryHash: id} = row;\n const patch: Patch = row.deleted\n ? {type: 'query', op: 'del', id}\n : {type: 'query', op: 'put', id};\n const v = row.patchVersion;\n assert(v, 'patchVersion must be set for query patches');\n patches.push({patch, toVersion: versionFromString(v)});\n }\n for (const row of allDesires) {\n const {clientID, queryHash: id} = row;\n const patch: Patch = row.deleted\n ? {type: 'query', op: 'del', id, clientID}\n : {type: 'query', op: 'put', id, clientID};\n patches.push({patch, toVersion: versionFromString(row.patchVersion)});\n }\n\n lc.debug?.(\n `${patches.length} config patches (${Date.now() - startMs} ms)`,\n );\n return patches;\n } finally {\n reader.setDone();\n }\n }\n\n #flushQueries(\n tx: PostgresTransaction,\n lc: LogContext,\n ): PendingQuery<Row[]>[] {\n // Merge partial updates into full updates\n const partialOnly = new Map<string, Partial<QueriesRow>>();\n for (const [queryHash, partial] of this.#pendingQueryPartialUpdates) {\n const existing = this.#pendingQueryUpdates.get(queryHash);\n if (existing) {\n // Merge partial into full update\n Object.assign(existing, partial);\n } else {\n // Track partial-only updates to batch separately\n partialOnly.set(queryHash, partial);\n }\n }\n\n const queries: PendingQuery<Row[]>[] = [];\n\n // Batch full updates\n if (this.#pendingQueryUpdates.size > 0) {\n const rows = [...this.#pendingQueryUpdates.values()];\n lc.debug?.(`Batch flushing ${rows.length} full query updates`);\n\n queries.push(tx`\n INSERT INTO ${this.#cvr('queries')} (\n \"clientGroupID\",\n \"queryHash\",\n \"clientAST\",\n \"queryName\",\n \"queryArgs\",\n \"patchVersion\",\n \"transformationHash\",\n \"transformationVersion\",\n \"internal\",\n \"deleted\",\n \"rowSetSignature\"\n )\n SELECT\n \"clientGroupID\",\n \"queryHash\",\n \"clientAST\",\n \"queryName\",\n CASE\n WHEN \"queryArgs\" IS NULL THEN NULL\n ELSE \"queryArgs\"::json\n END,\n \"patchVersion\",\n \"transformationHash\",\n \"transformationVersion\",\n \"internal\",\n \"deleted\",\n \"rowSetSignature\"\n FROM json_to_recordset(${rows}) AS x(\n \"clientGroupID\" TEXT,\n \"queryHash\" TEXT,\n \"clientAST\" JSONB,\n \"queryName\" TEXT,\n \"queryArgs\" TEXT,\n \"patchVersion\" TEXT,\n \"transformationHash\" TEXT,\n \"transformationVersion\" TEXT,\n \"internal\" BOOLEAN,\n \"deleted\" BOOLEAN,\n \"rowSetSignature\" TEXT\n )\n ON CONFLICT (\"clientGroupID\", \"queryHash\") DO UPDATE SET\n \"clientAST\" = excluded.\"clientAST\",\n \"queryName\" = excluded.\"queryName\",\n \"queryArgs\" = CASE\n WHEN excluded.\"queryArgs\" IS NULL THEN NULL\n ELSE excluded.\"queryArgs\"::json\n END,\n \"patchVersion\" = excluded.\"patchVersion\",\n \"transformationHash\" = excluded.\"transformationHash\",\n \"transformationVersion\" = excluded.\"transformationVersion\",\n \"internal\" = excluded.\"internal\",\n \"deleted\" = excluded.\"deleted\",\n \"rowSetSignature\" = excluded.\"rowSetSignature\"\n `);\n }\n\n // Batch partial-only updates\n if (partialOnly.size > 0) {\n lc.debug?.(`Batch flushing ${partialOnly.size} partial query updates`);\n const rows = Array.from(\n partialOnly.entries(),\n ([queryHash, partial]) => ({\n clientGroupID: this.#id,\n queryHash,\n patchVersionSet: partial.patchVersion !== undefined,\n patchVersion: partial.patchVersion ?? null,\n deletedSet: partial.deleted !== undefined,\n deleted: partial.deleted ?? null,\n transformationHashSet: partial.transformationHash !== undefined,\n transformationHash: partial.transformationHash ?? null,\n transformationVersionSet: partial.transformationVersion !== undefined,\n transformationVersion: partial.transformationVersion ?? null,\n rowSetSignatureSet: partial.rowSetSignature !== undefined,\n rowSetSignature: partial.rowSetSignature ?? null,\n }),\n );\n queries.push(tx`\n UPDATE ${this.#cvr('queries')} AS q\n SET\n \"patchVersion\" = CASE\n WHEN u.\"patchVersionSet\" THEN u.\"patchVersion\"\n ELSE q.\"patchVersion\"\n END,\n \"deleted\" = CASE\n WHEN u.\"deletedSet\" THEN u.\"deleted\"\n ELSE q.\"deleted\"\n END,\n \"transformationHash\" = CASE\n WHEN u.\"transformationHashSet\" THEN u.\"transformationHash\"\n ELSE q.\"transformationHash\"\n END,\n \"transformationVersion\" = CASE\n WHEN u.\"transformationVersionSet\" THEN u.\"transformationVersion\"\n ELSE q.\"transformationVersion\"\n END,\n \"rowSetSignature\" = CASE\n WHEN u.\"rowSetSignatureSet\" THEN u.\"rowSetSignature\"\n ELSE q.\"rowSetSignature\"\n END\n FROM json_to_recordset(${rows}) AS u(\n \"clientGroupID\" TEXT,\n \"queryHash\" TEXT,\n \"patchVersionSet\" BOOLEAN,\n \"patchVersion\" TEXT,\n \"deletedSet\" BOOLEAN,\n \"deleted\" BOOLEAN,\n \"transformationHashSet\" BOOLEAN,\n \"transformationHash\" TEXT,\n \"transformationVersionSet\" BOOLEAN,\n \"transformationVersion\" TEXT,\n \"rowSetSignatureSet\" BOOLEAN,\n \"rowSetSignature\" TEXT\n )\n WHERE q.\"clientGroupID\" = u.\"clientGroupID\"\n AND q.\"queryHash\" = u.\"queryHash\"\n `);\n }\n\n return queries;\n }\n\n #flushDesires(\n tx: PostgresTransaction,\n lc: LogContext,\n ): PendingQuery<Row[]> | null {\n if (this.#pendingDesireUpdates.size === 0) {\n return null;\n }\n\n const rows = Array.from(this.#pendingDesireUpdates.values(), row => {\n const {ttlInterval, ttlMs, inactivatedAtTimestamp, inactivatedAtMs} =\n convertTTLValues(row.inactivatedAt ?? undefined, row.ttl ?? -1);\n return {\n clientGroupID: row.clientGroupID,\n clientID: row.clientID,\n queryHash: row.queryHash,\n patchVersion: row.patchVersion,\n deleted: row.deleted,\n ttl: ttlInterval,\n ttlMs,\n inactivatedAt: inactivatedAtTimestamp,\n inactivatedAtMs,\n };\n });\n\n lc.debug?.(`Batch flushing ${rows.length} desire updates`);\n\n return tx`\n INSERT INTO ${this.#cvr('desires')} (\n \"clientGroupID\",\n \"clientID\",\n \"queryHash\",\n \"patchVersion\",\n \"deleted\",\n \"ttl\",\n \"ttlMs\",\n \"inactivatedAt\",\n \"inactivatedAtMs\"\n )\n SELECT\n \"clientGroupID\",\n \"clientID\",\n \"queryHash\",\n \"patchVersion\",\n \"deleted\",\n \"ttl\",\n \"ttlMs\",\n CASE\n WHEN \"inactivatedAt\" IS NULL THEN NULL\n -- Divide by 1000 because postgres.js serializeTimestamp treats numbers as ms\n -- and to_timestamp expects seconds. This matches non-batched behavior.\n ELSE to_timestamp(\"inactivatedAt\" / 1000.0)\n END,\n \"inactivatedAtMs\"\n FROM json_to_recordset(${rows}) AS x(\n \"clientGroupID\" TEXT,\n \"clientID\" TEXT,\n \"queryHash\" TEXT,\n \"patchVersion\" TEXT,\n \"deleted\" BOOLEAN,\n \"ttl\" INTERVAL,\n \"ttlMs\" DOUBLE PRECISION,\n \"inactivatedAt\" DOUBLE PRECISION,\n \"inactivatedAtMs\" DOUBLE PRECISION\n )\n ON CONFLICT (\"clientGroupID\", \"clientID\", \"queryHash\") DO UPDATE SET\n \"patchVersion\" = excluded.\"patchVersion\",\n \"deleted\" = excluded.\"deleted\",\n \"ttl\" = excluded.\"ttl\",\n \"ttlMs\" = excluded.\"ttlMs\",\n \"inactivatedAt\" = excluded.\"inactivatedAt\",\n \"inactivatedAtMs\" = excluded.\"inactivatedAtMs\"\n `;\n }\n\n async #checkVersionAndOwnership(\n lc: LogContext,\n tx: PostgresTransaction,\n expectedCurrentVersion: CVRVersion,\n lastConnectTime: number,\n ): Promise<void> {\n const start = Date.now();\n lc.debug?.('checking cvr version and ownership');\n const result = await tx<\n Pick<InstancesRow, 'version' | 'owner' | 'grantedAt'>[]\n >`SELECT \"version\", \"owner\", \"grantedAt\" FROM ${this.#cvr('instances')}\n WHERE \"clientGroupID\" = ${this.#id}\n FOR UPDATE`;\n const expected = versionString(expectedCurrentVersion);\n const {version, owner, grantedAt} =\n result.length > 0\n ? result[0]\n : {\n version: EMPTY_CVR_VERSION.stateVersion,\n owner: null,\n grantedAt: null,\n };\n lc.debug?.(\n 'checked cvr version and ownership in ' + (Date.now() - start) + ' ms',\n );\n if (owner !== this.#taskID && (grantedAt ?? 0) > lastConnectTime) {\n throw new OwnershipError(owner, grantedAt, lastConnectTime);\n }\n if (version !== expected) {\n throw new ConcurrentModificationException(expected, version);\n }\n }\n\n async #flush(\n lc: LogContext,\n expectedCurrentVersion: CVRVersion,\n cvr: CVRSnapshot,\n lastConnectTime: number,\n ): Promise<CVRFlushStats | null> {\n const stats: CVRFlushStats = {\n instances: 0,\n queries: 0,\n desires: 0,\n clients: 0,\n rows: 0,\n rowsDeferred: 0,\n statements: 0,\n };\n if (this.#pendingRowRecordUpdates.size) {\n const existingRowRecords = await this.getRowRecords();\n this.#rowCount = existingRowRecords.size;\n for (const [id, row] of this.#pendingRowRecordUpdates.entries()) {\n if (this.#forceUpdates.has(id)) {\n continue;\n }\n const existing = existingRowRecords.get(id);\n if (\n // Don't delete or add an unreferenced row if it's not in the CVR.\n (existing === undefined && !row?.refCounts) ||\n // Don't write a row record that exactly matches what's in the CVR.\n deepEqual(\n (row ?? undefined) as ReadonlyJSONValue | undefined,\n existing as ReadonlyJSONValue | undefined,\n )\n ) {\n this.#pendingRowRecordUpdates.delete(id);\n }\n }\n }\n if (\n this.#pendingRowRecordUpdates.size === 0 &&\n this.#writes.size === 0 &&\n this.#pendingInstanceWrite === undefined &&\n this.#pendingQueryUpdates.size === 0 &&\n this.#pendingQueryPartialUpdates.size === 0 &&\n this.#pendingDesireUpdates.size === 0\n ) {\n return null;\n }\n // Note: The CVR instance itself is only updated if there are material\n // changes (i.e. changes to the CVR contents) to flush.\n this.putInstance(cvr);\n const start = Date.now();\n lc.debug?.('flush tx beginning');\n\n // Use an async callback so we can await the version/ownership check and\n // validate it INSIDE the transaction. If validation fails, the exception\n // causes postgres.js to ROLLBACK, ensuring no writes are committed on error.\n const results = await runTx(\n this.#db,\n async tx => {\n lc.debug?.(`flush tx begun after ${Date.now() - start} ms`);\n\n // Acquire row-level lock and validate version/ownership before queuing writes.\n // Throwing here (inside the begin callback) rolls back the transaction so that\n // no writes are committed when concurrent modification or ownership errors occur.\n await this.#checkVersionAndOwnership(\n lc,\n tx,\n expectedCurrentVersion,\n lastConnectTime,\n );\n\n const writeQueries = [];\n if (this.#pendingInstanceWrite) {\n writeQueries.push(this.#pendingInstanceWrite(tx, lastConnectTime));\n stats.instances++;\n stats.statements++;\n }\n for (const write of this.#writes) {\n stats.clients += write.stats.clients ?? 0;\n stats.rows += write.stats.rows ?? 0;\n\n writeQueries.push(write.write(tx, lastConnectTime));\n stats.statements++;\n }\n\n // Batch flush config writes\n // Flush queries first (desires depend on queries via foreign key)\n const hasQueryUpdates =\n this.#pendingQueryUpdates.size > 0 ||\n this.#pendingQueryPartialUpdates.size > 0;\n\n const desireFlush = this.#flushDesires(tx, lc);\n\n let queryFlushes: PendingQuery<Row[]>[] = [];\n if (hasQueryUpdates) {\n queryFlushes = this.#flushQueries(tx, lc);\n\n // Count both full updates and partial-only updates\n const partialOnlyCount = [\n ...this.#pendingQueryPartialUpdates.keys(),\n ].filter(key => !this.#pendingQueryUpdates.has(key)).length;\n\n stats.queries = this.#pendingQueryUpdates.size + partialOnlyCount;\n stats.statements +=\n (this.#pendingQueryUpdates.size > 0 ? 1 : 0) +\n (partialOnlyCount > 0 ? 1 : 0);\n\n if (desireFlush) {\n stats.desires = this.#pendingDesireUpdates.size;\n stats.statements++;\n }\n } else if (desireFlush) {\n stats.desires = this.#pendingDesireUpdates.size;\n stats.statements++;\n }\n\n const rowUpdates = this.#rowCache.executeRowUpdates(\n tx,\n cvr.version,\n this.#pendingRowRecordUpdates,\n 'allow-defer',\n lc,\n );\n stats.statements += rowUpdates.length;\n\n // Pipeline writes now that the version check has passed.\n const pipelined = [\n ...writeQueries,\n ...queryFlushes,\n ...(desireFlush ? [desireFlush] : []),\n ...rowUpdates,\n ];\n\n lc.debug?.(`returning ${pipelined.length} queries for pipelining`);\n\n // Explicitly await all pipelined queries. When the begin callback is async,\n // postgres.js does not call Promise.all() on the return value the way it does\n // for sync callbacks, so we must do it ourselves.\n return Promise.all(pipelined);\n },\n {mode: Mode.READ_COMMITTED},\n );\n\n lc.debug?.(`flush tx completed after ${Date.now() - start} ms`);\n\n // Calculate how many row update queries were in the pipeline.\n // Note: the version check was awaited separately and is not in the results array.\n const baseQueries =\n (this.#pendingInstanceWrite ? 1 : 0) +\n this.#writes.size +\n (this.#pendingQueryUpdates.size > 0 ? 1 : 0) +\n (some(\n this.#pendingQueryPartialUpdates.keys(),\n key => !this.#pendingQueryUpdates.has(key),\n )\n ? 1\n : 0) +\n (this.#pendingDesireUpdates.size > 0 ? 1 : 0);\n const rowUpdateCount = results.length - baseQueries;\n\n const rowsFlushed = rowUpdateCount > 0;\n if (!rowsFlushed) {\n stats.rowsDeferred = this.#pendingRowRecordUpdates.size;\n } else {\n stats.rows += this.#pendingRowRecordUpdates.size;\n }\n\n this.#rowCount = await this.#rowCache.apply(\n this.#pendingRowRecordUpdates,\n cvr.version,\n rowsFlushed,\n );\n recordRowsSynced(this.#rowCount);\n\n return stats;\n }\n\n get rowCount(): number {\n return this.#rowCount;\n }\n\n async flush(\n lc: LogContext,\n expectedCurrentVersion: CVRVersion,\n cvr: CVRSnapshot,\n lastConnectTime: number,\n ): Promise<CVRFlushStats | null> {\n const start = performance.now();\n lc = lc.withContext('cvrFlushID', flushCounter++);\n try {\n const stats = await this.#flush(\n lc,\n expectedCurrentVersion,\n cvr,\n lastConnectTime,\n );\n if (stats) {\n const elapsed = performance.now() - start;\n lc.info?.(\n `flushed cvr@${versionString(cvr.version)} ` +\n `${JSON.stringify(stats)} in (${elapsed} ms)`,\n );\n this.#rowCache.recordSyncFlushStats(stats, elapsed);\n }\n return stats;\n } catch (e) {\n // Clear cached state if an error (e.g. ConcurrentModificationException) is encountered.\n this.#rowCache.clear();\n throw e;\n } finally {\n this.#writes.clear();\n this.#pendingInstanceWrite = undefined;\n this.#pendingRowRecordUpdates.clear();\n this.#forceUpdates.clear();\n this.#pendingQueryUpdates.clear();\n this.#pendingDesireUpdates.clear();\n this.#pendingQueryPartialUpdates.clear();\n }\n }\n\n hasPendingUpdates(): boolean {\n return this.#rowCache.hasPendingUpdates();\n }\n\n /** Resolves when all pending updates are flushed. */\n flushed(lc: LogContext): Promise<void> {\n return this.#rowCache.flushed(lc);\n }\n\n async inspectQueries(\n lc: LogContext,\n ttlClock: TTLClock,\n clientID?: string,\n ): Promise<InspectQueryRow[]> {\n const db = this.#db;\n const clientGroupID = this.#id;\n\n const reader = new TransactionPool(lc, {mode: Mode.READONLY}).run(db);\n try {\n return await reader.processReadTask(\n tx => tx<InspectQueryRow[]>`\n SELECT DISTINCT ON (d.\"clientID\", d.\"queryHash\")\n d.\"clientID\",\n d.\"queryHash\" AS \"queryID\",\n COALESCE(d.\"ttlMs\", ${DEFAULT_TTL_MS}) AS \"ttl\",\n d.\"inactivatedAtMs\" AS \"inactivatedAt\",\n (SELECT COUNT(*)::INT FROM ${this.#cvr('rows')} r \n WHERE r.\"clientGroupID\" = d.\"clientGroupID\" \n AND r.\"refCounts\" ? d.\"queryHash\") AS \"rowCount\",\n q.\"clientAST\" AS \"ast\",\n (q.\"patchVersion\" IS NOT NULL) AS \"got\",\n COALESCE(d.\"deleted\", FALSE) AS \"deleted\",\n q.\"queryName\" AS \"name\",\n q.\"queryArgs\" AS \"args\"\n FROM ${this.#cvr('desires')} d\n LEFT JOIN ${this.#cvr('queries')} q\n ON q.\"clientGroupID\" = d.\"clientGroupID\"\n AND q.\"queryHash\" = d.\"queryHash\"\n WHERE d.\"clientGroupID\" = ${clientGroupID}\n ${clientID ? tx`AND d.\"clientID\" = ${clientID}` : tx``}\n AND NOT (\n d.\"inactivatedAtMs\" IS NOT NULL \n AND d.\"ttlMs\" IS NOT NULL \n AND (d.\"inactivatedAtMs\" + d.\"ttlMs\") <= ${ttlClockAsNumber(ttlClock)}\n )\n ORDER BY d.\"clientID\", d.\"queryHash\"`,\n );\n } finally {\n reader.setDone();\n }\n }\n}\n\n/**\n * This is similar to {@link CVRStore.#checkVersionAndOwnership} except\n * that it only checks the version and is suitable for snapshot reads\n * (i.e. by doing a plain `SELECT` rather than a `SELECT ... FOR UPDATE`).\n */\nexport async function checkVersion(\n tx: PostgresTransaction,\n schema: string,\n clientGroupID: string,\n expectedCurrentVersion: CVRVersion,\n): Promise<void> {\n const expected = versionString(expectedCurrentVersion);\n const result = await tx<Pick<InstancesRow, 'version'>[]>`\n SELECT version FROM ${tx(schema)}.instances \n WHERE \"clientGroupID\" = ${clientGroupID}`;\n const {version} =\n result.length > 0 ? result[0] : {version: EMPTY_CVR_VERSION.stateVersion};\n if (version !== expected) {\n throw new ConcurrentModificationException(expected, version);\n }\n}\n\nexport class ClientNotFoundError extends ProtocolErrorWithLevel {\n constructor(message: string) {\n super(\n {\n kind: ErrorKind.ClientNotFound,\n message,\n origin: ErrorOrigin.ZeroCache,\n },\n 'warn',\n );\n }\n}\n\nexport class ConcurrentModificationException extends ProtocolErrorWithLevel {\n readonly name = 'ConcurrentModificationException';\n\n constructor(expectedVersion: string, actualVersion: string) {\n super(\n {\n kind: ErrorKind.Rehome,\n message: `CVR has been concurrently modified. Expected ${expectedVersion}, got ${actualVersion}`,\n origin: ErrorOrigin.ZeroCache,\n },\n 'warn',\n );\n }\n}\n\nexport class OwnershipError extends ProtocolErrorWithLevel {\n readonly name = 'OwnershipError';\n\n constructor(\n owner: string | null,\n grantedAt: number | null,\n lastConnectTime: number,\n ) {\n super(\n {\n kind: ErrorKind.Rehome,\n message:\n `CVR ownership was transferred to ${owner} at ` +\n `${new Date(grantedAt ?? 0).toISOString()} ` +\n `(last connect time: ${new Date(lastConnectTime).toISOString()})`,\n maxBackoffMs: 0,\n origin: ErrorOrigin.ZeroCache,\n },\n 'info',\n );\n }\n}\n\nexport class InvalidClientSchemaError extends ProtocolErrorWithLevel {\n readonly name = 'InvalidClientSchemaError';\n\n constructor(cause: unknown) {\n super(\n {\n kind: ErrorKind.SchemaVersionNotSupported,\n message: `Could not parse clientSchema stored in CVR: ${String(cause)}`,\n origin: ErrorOrigin.ZeroCache,\n },\n 'warn',\n {cause},\n );\n }\n}\n\nexport class RowsVersionBehindError extends Error {\n readonly name = 'RowsVersionBehindError';\n readonly cvrVersion: string;\n readonly rowsVersion: string | null;\n\n constructor(cvrVersion: string, rowsVersion: string | null) {\n super(`rowsVersion (${rowsVersion}) is behind CVR ${cvrVersion}`);\n this.cvrVersion = cvrVersion;\n this.rowsVersion = rowsVersion;\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;AAwEA,IAAI,eAAe;;;;;;AAOnB,SAAS,iBACP,eACA,KAMA;CACA,OAAO;EACL,aAAa,MAAM,IAAI,OAAO,MAAM;EACpC,OAAO,MAAM,IAAI,OAAO;EACxB,wBACE,kBAAkB,KAAA,IACd,OACA,mBAAmB,iBAAiB,aAAa,IAAI,GAAI;EAC/D,iBAAiB,iBAAiB;CACpC;AACF;AAEA,IAAM,SAAS,MAAM,UAAU,aAAa,OAAO;AAWnD,SAAS,QAAQ,KAA8B;CAC7C,MAAM,gBAAgB,MACpB,MAAM,OAAO,KAAA,IAAY,kBAAkB,CAAC;CAI9C,MAAM,WAAW,IAAI,kBACjB,EAAC,iBAAiB,IAAI,gBAAe,IACrC,CAAC;CAEL,IAAI,IAAI,cAAc,MAAM;EAE1B,OACE,IAAI,cAAc,QAAQ,IAAI,cAAc,MAC5C,wDACF;EACA,OAAO;GACL,MAAM;G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MAAM,SAAS,MAAM,EAAmC;0BAChC,GAAG,MAAM,EAAE;gCACL;CAC9B,MAAM,EAAC,YACL,OAAO,SAAS,IAAI,OAAO,KAAK,EAAC,SAAS,kBAAkB,aAAY;CAC1E,IAAI,YAAY,UACd,MAAM,IAAI,gCAAgC,UAAU,OAAO;AAE/D;AAEA,IAAa,sBAAb,cAAyC,uBAAuB;CAC9D,YAAY,SAAiB;EAC3B,MACE;GACE,MAAM;GACN;GACA,QAAQ;EACV,GACA,MACF;CACF;AACF;AAEA,IAAa,kCAAb,cAAqD,uBAAuB;CAC1E,OAAgB;CAEhB,YAAY,iBAAyB,eAAuB;EAC1D,MACE;GACE,MAAM;GACN,SAAS,gDAAgD,gBAAgB,QAAQ;GACjF,QAAQ;EACV,GACA,MACF;CACF;AACF;AAEA,IAAa,iBAAb,cAAoC,uBAAuB;CACzD,OAAgB;CAEhB,YACE,OACA,WACA,iBACA;EACA,MACE;GACE,MAAM;GACN,SACE,oCAAoC,MAAM,MACvC,IAAI,KAAK,aAAa,CAAC,EAAE,YAAY,EAAE,uBACnB,IAAI,KAAK,eAAe,EAAE,YAAY,EAAE;GACjE,cAAc;GACd,QAAQ;EACV,GACA,MACF;CACF;AACF;AAEA,IAAa,2BAAb,cAA8C,uBAAuB;CACnE,OAAgB;CAEhB,YAAY,OAAgB;EAC1B,MACE;GACE,MAAM;GACN,SAAS,+CAA+C,OAAO,KAAK;GACpE,QAAQ;EACV,GACA,QACA,EAAC,MAAK,CACR;CACF;AACF;AAEA,IAAa,yBAAb,cAA4C,MAAM;CAChD,OAAgB;CAChB;CACA;CAEA,YAAY,YAAoB,aAA4B;EAC1D,MAAM,gBAAgB,YAAY,kBAAkB,YAAY;EAChE,KAAK,aAAa;EAClB,KAAK,cAAc;CACrB;AACF"}
|
|
@@ -1,8 +1,6 @@
|
|
|
1
|
-
import { __toESM } from "../../_virtual/_rolldown/runtime.js";
|
|
2
|
-
import { require_react } from "../../node_modules/.pnpm/react@18.3.1/node_modules/react/index.js";
|
|
3
1
|
import { useZero } from "./zero-provider.js";
|
|
2
|
+
import { useSyncExternalStore } from "react";
|
|
4
3
|
//#region ../zero-react/src/use-connection-state.tsx
|
|
5
|
-
var import_react = /* @__PURE__ */ __toESM(require_react(), 1);
|
|
6
4
|
/**
|
|
7
5
|
* Hook to subscribe to the connection status of the Zero instance.
|
|
8
6
|
*
|
|
@@ -11,7 +9,7 @@ var import_react = /* @__PURE__ */ __toESM(require_react(), 1);
|
|
|
11
9
|
*/
|
|
12
10
|
function useConnectionState() {
|
|
13
11
|
const zero = useZero();
|
|
14
|
-
return
|
|
12
|
+
return useSyncExternalStore(zero.connection.state.subscribe, () => zero.connection.state.current, () => zero.connection.state.current);
|
|
15
13
|
}
|
|
16
14
|
//#endregion
|
|
17
15
|
export { useConnectionState };
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"use-connection-state.js","names":[],"sources":["../../../../zero-react/src/use-connection-state.tsx"],"sourcesContent":["import {useSyncExternalStore} from 'react';\nimport {useZero} from './zero-provider.tsx';\nimport type {ConnectionState} from './zero.ts';\n\n/**\n * Hook to subscribe to the connection status of the Zero instance.\n *\n * @returns The connection status of the Zero instance.\n * @see {@link ConnectionState} for more details on the connection state.\n */\nexport function useConnectionState(): ConnectionState {\n const zero = useZero();\n return useSyncExternalStore(\n zero.connection.state.subscribe,\n () => zero.connection.state.current,\n () => zero.connection.state.current,\n );\n}\n"],"mappings":"
|
|
1
|
+
{"version":3,"file":"use-connection-state.js","names":[],"sources":["../../../../zero-react/src/use-connection-state.tsx"],"sourcesContent":["import {useSyncExternalStore} from 'react';\nimport {useZero} from './zero-provider.tsx';\nimport type {ConnectionState} from './zero.ts';\n\n/**\n * Hook to subscribe to the connection status of the Zero instance.\n *\n * @returns The connection status of the Zero instance.\n * @see {@link ConnectionState} for more details on the connection state.\n */\nexport function useConnectionState(): ConnectionState {\n const zero = useZero();\n return useSyncExternalStore(\n zero.connection.state.subscribe,\n () => zero.connection.state.current,\n () => zero.connection.state.current,\n );\n}\n"],"mappings":";;;;;;;;;AAUA,SAAgB,qBAAsC;CACpD,MAAM,OAAO,QAAQ;CACrB,OAAO,qBACL,KAAK,WAAW,MAAM,iBAChB,KAAK,WAAW,MAAM,eACtB,KAAK,WAAW,MAAM,OAC9B;AACF"}
|
|
@@ -1,15 +1,13 @@
|
|
|
1
|
-
import { __toESM } from "../../_virtual/_rolldown/runtime.js";
|
|
2
1
|
import { asQueryInternals } from "../../zql/src/query/query-internals.js";
|
|
3
2
|
import { addContextToQuery } from "../../zql/src/query/query-registry.js";
|
|
4
3
|
import { DEFAULT_TTL_MS } from "../../zql/src/query/ttl.js";
|
|
5
4
|
import { deepClone } from "../../shared/src/deep-clone.js";
|
|
6
|
-
import { require_react } from "../../node_modules/.pnpm/react@18.3.1/node_modules/react/index.js";
|
|
7
5
|
import { useZero } from "./zero-provider.js";
|
|
8
6
|
import "./bindings.js";
|
|
9
7
|
import { resolver } from "@rocicorp/resolver";
|
|
8
|
+
import React, { useSyncExternalStore } from "react";
|
|
10
9
|
//#region ../zero-react/src/use-query.tsx
|
|
11
|
-
var
|
|
12
|
-
var reactUse = import_react.default.use;
|
|
10
|
+
var reactUse = React.use;
|
|
13
11
|
var suspend = reactUse ? reactUse : (p) => {
|
|
14
12
|
throw p;
|
|
15
13
|
};
|
|
@@ -21,7 +19,7 @@ function useQuery(query, options) {
|
|
|
21
19
|
const zero = useZero();
|
|
22
20
|
const q = query ? addContextToQuery(query, zero.context) : void 0;
|
|
23
21
|
const view = q ? viewStore.getView(zero, q, enabled, ttl) : void 0;
|
|
24
|
-
return
|
|
22
|
+
return useSyncExternalStore(view?.subscribeReactInternals ?? disabledSubscriber, view?.getSnapshot ?? getDisabledSnapshot, view?.getSnapshot ?? getDisabledSnapshot);
|
|
25
23
|
}
|
|
26
24
|
function useSuspenseQuery(query, options) {
|
|
27
25
|
let enabled = true;
|
|
@@ -32,7 +30,7 @@ function useSuspenseQuery(query, options) {
|
|
|
32
30
|
const zero = useZero();
|
|
33
31
|
const q = query ? addContextToQuery(query, zero.context) : void 0;
|
|
34
32
|
const view = q ? viewStore.getView(zero, q, enabled, ttl) : void 0;
|
|
35
|
-
const snapshot =
|
|
33
|
+
const snapshot = useSyncExternalStore(view?.subscribeReactInternals ?? disabledSubscriber, view?.getSnapshot ?? getDisabledSnapshot, view?.getSnapshot ?? getDisabledSnapshot);
|
|
36
34
|
if (view && enabled) {
|
|
37
35
|
if (suspendUntil === "complete" && !view.complete) suspend(view.waitForComplete());
|
|
38
36
|
if (suspendUntil === "partial" && !view.nonEmpty) suspend(view.waitForNonEmpty());
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"use-query.js","names":["#views","#onDematerialized","#query","#reactInternals","#zero","#singular","#ttl","#snapshot","#materializeIfNeeded","#retry","#complete","#completeResolver","#nonEmpty","#nonEmptyResolver","#view","#onData","#destroyTimer"],"sources":["../../../../zero-react/src/use-query.tsx"],"sourcesContent":["import {resolver} from '@rocicorp/resolver';\nimport React, {useSyncExternalStore} from 'react';\nimport {TESTING} from '../../shared/src/testing.ts';\nimport {\n type Immutable,\n addContextToQuery,\n asQueryInternals,\n deepClone,\n DEFAULT_TTL_MS,\n} from './bindings.ts';\nimport {useZero} from './zero-provider.tsx';\nimport type {\n AnyMutatorRegistry,\n BaseDefaultContext,\n BaseDefaultSchema,\n CustomMutatorDefs,\n DefaultContext,\n DefaultSchema,\n ErroredQuery,\n Falsy,\n HumanReadable,\n PullRow,\n Query,\n QueryErrorDetails,\n QueryOrQueryRequest,\n QueryResultDetails,\n ReadonlyJSONValue,\n ResultType,\n TTL,\n TypedView,\n Zero,\n} from './zero.ts';\n\nexport type QueryResult<TReturn> = readonly [\n HumanReadable<TReturn>,\n QueryResultDetails & {},\n];\n\n/**\n * Result type for \"maybe queries\" - queries that may be falsy.\n * The data value can be undefined when the query is falsy/disabled.\n */\nexport type MaybeQueryResult<TReturn> = readonly [\n HumanReadable<TReturn> | undefined,\n QueryResultDetails & {},\n];\n\nexport type UseQueryOptions = {\n enabled?: boolean | undefined;\n /**\n * Time to live (TTL) in seconds. Controls how long query results are cached\n * after the query is removed. During this time, Zero continues to sync the query.\n * Default is 'never'.\n */\n ttl?: TTL | undefined;\n};\n\nexport type UseSuspenseQueryOptions = UseQueryOptions & {\n /**\n * Whether to suspend until:\n * - 'partial': the query has partial results (partial array or defined\n * value for singular results) which may be of result type 'unknown',\n * or the query result type is 'complete' (in which case results may be\n * empty). This is useful for suspending until there are partial\n * optimistic local results, or the query has completed loading from the\n * server.\n * - 'complete': the query result type is 'complete'.\n *\n * Default is 'partial'.\n */\n suspendUntil?: 'complete' | 'partial';\n};\n\nconst reactUse = (React as {use?: (p: Promise<unknown>) => void}).use;\nconst suspend: (p: Promise<unknown>) => void = reactUse\n ? reactUse\n : p => {\n throw p;\n };\n\n// Overload 1: Query\nexport function useQuery<\n TTable extends keyof TSchema['tables'] & string,\n TInput extends ReadonlyJSONValue | undefined,\n TOutput extends ReadonlyJSONValue | undefined,\n TSchema extends BaseDefaultSchema = DefaultSchema,\n TReturn = PullRow<TTable, TSchema>,\n TContext extends BaseDefaultContext = DefaultContext,\n>(\n query: QueryOrQueryRequest<\n TTable,\n TInput,\n TOutput,\n TSchema,\n TReturn,\n TContext\n >,\n options?: UseQueryOptions | boolean,\n): QueryResult<TReturn>;\n\n// Overload 2: Maybe query\nexport function useQuery<\n TTable extends keyof TSchema['tables'] & string,\n TInput extends ReadonlyJSONValue | undefined,\n TOutput extends ReadonlyJSONValue | undefined,\n TSchema extends BaseDefaultSchema = DefaultSchema,\n TReturn = PullRow<TTable, TSchema>,\n TContext extends BaseDefaultContext = DefaultContext,\n>(\n query:\n | QueryOrQueryRequest<TTable, TInput, TOutput, TSchema, TReturn, TContext>\n | Falsy,\n options?: UseQueryOptions | boolean,\n): MaybeQueryResult<TReturn>;\n\n// Implementation\nexport function useQuery<\n TTable extends keyof TSchema['tables'] & string,\n TInput extends ReadonlyJSONValue | undefined,\n TOutput extends ReadonlyJSONValue | undefined,\n TSchema extends BaseDefaultSchema = DefaultSchema,\n TReturn = PullRow<TTable, TSchema>,\n TContext extends BaseDefaultContext = DefaultContext,\n>(\n query:\n | QueryOrQueryRequest<TTable, TInput, TOutput, TSchema, TReturn, TContext>\n | Falsy,\n options?: UseQueryOptions | boolean,\n): QueryResult<TReturn> | MaybeQueryResult<TReturn> {\n let enabled = true;\n let ttl: TTL = DEFAULT_TTL_MS;\n if (typeof options === 'boolean') {\n enabled = options;\n } else if (options) {\n ({enabled = true, ttl = DEFAULT_TTL_MS} = options);\n }\n\n const zero = useZero<TSchema, undefined, TContext>();\n\n // When query is falsy, use disabled subscriber/snapshot to maintain hook order\n const q = query ? addContextToQuery(query, zero.context) : undefined;\n const view = q ? viewStore.getView(zero, q, enabled, ttl) : undefined;\n\n // https://react.dev/reference/react/useSyncExternalStore\n // Always call useSyncExternalStore to maintain consistent hook order\n return useSyncExternalStore(\n view?.subscribeReactInternals ?? disabledSubscriber,\n view?.getSnapshot ??\n (getDisabledSnapshot as () => MaybeQueryResult<TReturn>),\n view?.getSnapshot ??\n (getDisabledSnapshot as () => MaybeQueryResult<TReturn>),\n );\n}\n\n// Overload 1: Query\nexport function useSuspenseQuery<\n TTable extends keyof TSchema['tables'] & string,\n TInput extends ReadonlyJSONValue | undefined,\n TOutput extends ReadonlyJSONValue | undefined,\n TSchema extends BaseDefaultSchema = DefaultSchema,\n TReturn = PullRow<TTable, TSchema>,\n TContext extends BaseDefaultContext = DefaultContext,\n>(\n query: QueryOrQueryRequest<\n TTable,\n TInput,\n TOutput,\n TSchema,\n TReturn,\n TContext\n >,\n options?: UseSuspenseQueryOptions | boolean,\n): QueryResult<TReturn>;\n\n// Overload 2: Maybe query\nexport function useSuspenseQuery<\n TTable extends keyof TSchema['tables'] & string,\n TInput extends ReadonlyJSONValue | undefined,\n TOutput extends ReadonlyJSONValue | undefined,\n TSchema extends BaseDefaultSchema = DefaultSchema,\n TReturn = PullRow<TTable, TSchema>,\n TContext extends BaseDefaultContext = DefaultContext,\n>(\n query:\n | QueryOrQueryRequest<TTable, TInput, TOutput, TSchema, TReturn, TContext>\n | Falsy,\n options?: UseSuspenseQueryOptions | boolean,\n): MaybeQueryResult<TReturn>;\n\n// Implementation\nexport function useSuspenseQuery<\n TTable extends keyof TSchema['tables'] & string,\n TInput extends ReadonlyJSONValue | undefined,\n TOutput extends ReadonlyJSONValue | undefined,\n TSchema extends BaseDefaultSchema = DefaultSchema,\n TReturn = PullRow<TTable, TSchema>,\n TContext extends BaseDefaultContext = DefaultContext,\n>(\n query:\n | QueryOrQueryRequest<TTable, TInput, TOutput, TSchema, TReturn, TContext>\n | Falsy,\n options?: UseSuspenseQueryOptions | boolean,\n): QueryResult<TReturn> | MaybeQueryResult<TReturn> {\n let enabled = true;\n let ttl: TTL = DEFAULT_TTL_MS;\n let suspendUntil: 'complete' | 'partial' = 'partial';\n if (typeof options === 'boolean') {\n enabled = options;\n } else if (options) {\n ({\n enabled = true,\n ttl = DEFAULT_TTL_MS,\n suspendUntil = 'complete',\n } = options);\n }\n\n const zero = useZero<TSchema, undefined, TContext>();\n\n // When query is falsy, use disabled subscriber/snapshot to maintain hook order\n const q = query ? addContextToQuery(query, zero.context) : undefined;\n const view = q ? viewStore.getView(zero, q, enabled, ttl) : undefined;\n\n // https://react.dev/reference/react/useSyncExternalStore\n // Always call useSyncExternalStore to maintain consistent hook order\n const snapshot = useSyncExternalStore(\n view?.subscribeReactInternals ?? disabledSubscriber,\n view?.getSnapshot ??\n (getDisabledSnapshot as () => MaybeQueryResult<TReturn>),\n view?.getSnapshot ??\n (getDisabledSnapshot as () => MaybeQueryResult<TReturn>),\n );\n\n if (view && enabled) {\n if (suspendUntil === 'complete' && !view.complete) {\n suspend(view.waitForComplete());\n }\n\n if (suspendUntil === 'partial' && !view.nonEmpty) {\n suspend(view.waitForNonEmpty());\n }\n }\n\n return snapshot;\n}\n\nconst emptyArray: unknown[] = [];\nconst disabledSubscriber = () => () => {};\n\nconst resultTypeUnknown = {type: 'unknown'} as const;\nconst resultTypeComplete = {type: 'complete'} as const;\nconst resultTypeError = {type: 'error'} as const;\n\nconst disabledQuerySnapshot = [undefined, resultTypeUnknown] as const;\nconst getDisabledSnapshot = () => disabledQuerySnapshot;\n\nconst emptySnapshotSingularUnknown = [undefined, resultTypeUnknown] as const;\nconst emptySnapshotSingularComplete = [undefined, resultTypeComplete] as const;\nconst emptySnapshotSingularErrorUnknown = [undefined, resultTypeError] as const;\nconst emptySnapshotPluralUnknown = [emptyArray, resultTypeUnknown] as const;\nconst emptySnapshotPluralComplete = [emptyArray, resultTypeComplete] as const;\nconst emptySnapshotErrorUnknown = [emptyArray, resultTypeError] as const;\n\nfunction getDefaultSnapshot<TReturn>(singular: boolean): QueryResult<TReturn> {\n return (\n singular ? emptySnapshotSingularUnknown : emptySnapshotPluralUnknown\n ) as QueryResult<TReturn>;\n}\n\n/**\n * Returns a new snapshot or one of the empty predefined ones. Returning the\n * predefined ones is important to prevent unnecessary re-renders in React.\n */\nfunction getSnapshot<TReturn>(\n singular: boolean,\n data: HumanReadable<TReturn>,\n resultType: ResultType,\n retryFn: () => void,\n error?: ErroredQuery,\n): QueryResult<TReturn> {\n if (singular && data === undefined) {\n switch (resultType) {\n case 'error':\n if (error) {\n return [\n undefined,\n makeError(retryFn, error),\n ] as unknown as QueryResult<TReturn>;\n }\n return emptySnapshotSingularErrorUnknown as unknown as QueryResult<TReturn>;\n case 'complete':\n return emptySnapshotSingularComplete as unknown as QueryResult<TReturn>;\n case 'unknown':\n return emptySnapshotSingularUnknown as unknown as QueryResult<TReturn>;\n }\n }\n\n if (!singular && (data as unknown[]).length === 0) {\n switch (resultType) {\n case 'error':\n if (error) {\n return [\n emptyArray,\n makeError(retryFn, error),\n ] as unknown as QueryResult<TReturn>;\n }\n return emptySnapshotErrorUnknown as unknown as QueryResult<TReturn>;\n case 'complete':\n return emptySnapshotPluralComplete as unknown as QueryResult<TReturn>;\n case 'unknown':\n return emptySnapshotPluralUnknown as unknown as QueryResult<TReturn>;\n }\n }\n\n switch (resultType) {\n case 'error':\n if (error) {\n return [data, makeError(retryFn, error)];\n }\n return [\n data,\n makeError(retryFn, {\n error: 'app',\n id: 'unknown',\n name: 'unknown',\n message: 'An unknown error occurred',\n }),\n ];\n case 'complete':\n return [data, resultTypeComplete];\n case 'unknown':\n return [data, resultTypeUnknown];\n }\n}\n\nfunction makeError(retry: () => void, error: ErroredQuery): QueryErrorDetails {\n const message = error.message ?? 'An unknown error occurred';\n return {\n type: 'error',\n retry,\n refetch: retry,\n error: {\n type: error.error,\n message,\n ...(error.details ? {details: error.details} : {}),\n },\n };\n}\n\n// oxlint-disable-next-line @typescript-eslint/no-explicit-any\ntype AnyViewWrapper = ViewWrapper<any, any, any, any, any>;\n\nconst allViews = new WeakMap<ViewStore, Map<string, AnyViewWrapper>>();\n\nexport function getAllViewsSizeForTesting(store: ViewStore): number {\n if (TESTING) {\n return allViews.get(store)?.size ?? 0;\n }\n return 0;\n}\n\n/**\n * A global store of all active views.\n *\n * React subscribes and unsubscribes to these views\n * via `useSyncExternalStore`.\n *\n * Managing views through `useEffect` or `useLayoutEffect` causes\n * inconsistencies because effects run after render.\n *\n * For example, if useQuery used use*Effect in the component below:\n * ```ts\n * function Foo({issueID}) {\n * const issue = useQuery(z.query.issue.where('id', issueID).one());\n * if (issue?.id !== undefined && issue.id !== issueID) {\n * console.log('MISMATCH!', issue.id, issueID);\n * }\n * }\n * ```\n *\n * `MISMATCH` will be printed whenever the `issueID` prop changes.\n *\n * This is because the component will render once with\n * the old state returned from `useQuery`. Then the effect inside\n * `useQuery` will run. The component will render again with the new\n * state. This inconsistent transition can cause unexpected results.\n *\n * Emulating `useEffect` via `useState` and `if` causes resource leaks.\n * That is:\n *\n * ```ts\n * function useQuery(q) {\n * const [oldHash, setOldHash] = useState();\n * if (hash(q) !== oldHash) {\n * // make new view\n * }\n *\n * useEffect(() => {\n * return () => view.destroy();\n * }, []);\n * }\n * ```\n *\n * I'm not sure why but in strict mode the cleanup function\n * fails to be called for the first instance of the view and only\n * cleans up later instances.\n *\n * Swapping `useState` to `useRef` has similar problems.\n */\nexport class ViewStore {\n #views = new Map<string, AnyViewWrapper>();\n\n constructor() {\n if (TESTING) {\n allViews.set(this, this.#views);\n }\n }\n\n getView<\n TTable extends keyof TSchema['tables'] & string,\n TSchema extends BaseDefaultSchema,\n TReturn,\n MD extends CustomMutatorDefs | undefined,\n TContext extends BaseDefaultContext,\n >(\n zero: Zero<TSchema, MD, TContext>,\n q: Query<TTable, TSchema, TReturn>,\n enabled: boolean,\n ttl: TTL,\n ): {\n getSnapshot: () => QueryResult<TReturn>;\n subscribeReactInternals: (internals: () => void) => () => void;\n updateTTL: (ttl: TTL) => void;\n waitForComplete: () => Promise<void>;\n waitForNonEmpty: () => Promise<void>;\n complete: boolean;\n nonEmpty: boolean;\n } {\n const qi = asQueryInternals(q);\n\n if (!enabled) {\n return {\n getSnapshot: () => getDefaultSnapshot(qi.format.singular),\n subscribeReactInternals: disabledSubscriber,\n updateTTL: () => {},\n waitForComplete: () => Promise.resolve(),\n waitForNonEmpty: () => Promise.resolve(),\n complete: false,\n nonEmpty: false,\n };\n }\n\n const hash = qi.hash() + zero.clientID;\n let existing = this.#views.get(hash);\n if (!existing) {\n existing = new ViewWrapper(q, zero, ttl, view => {\n const currentView = this.#views.get(hash);\n if (currentView && currentView !== view) {\n // we replaced the view with a new one already.\n return;\n }\n this.#views.delete(hash);\n });\n this.#views.set(hash, existing);\n } else {\n existing.updateTTL(ttl);\n }\n return existing as ViewWrapper<TTable, TSchema, TReturn, MD, TContext>;\n }\n}\n\nconst viewStore = new ViewStore();\n\n/**\n * This wraps and ref counts a view.\n *\n * The only signal we have from React as to whether or not it is\n * done with a view is when it calls `unsubscribe`.\n *\n * In non-strict-mode we can clean up the view as soon\n * as the listener count goes to 0.\n *\n * In strict-mode, the listener count will go to 0 then a\n * new listener for the same view is immediately added back.\n *\n * This is why the `onMaterialized` and `onDematerialized` callbacks exist --\n * they allow a view which React is still referencing to be added\n * back into the store when React re-subscribes to it.\n *\n * This wrapper also exists to deal with the various\n * `useSyncExternalStore` caveats that cause excessive\n * re-renders and materializations.\n *\n * See: https://react.dev/reference/react/useSyncExternalStore#caveats\n * Especially:\n * 1. The store snapshot returned by getSnapshot must be immutable. If the underlying store has mutable data, return a new immutable snapshot if the data has changed. Otherwise, return a cached last snapshot.\n * 2. If a different subscribe function is passed during a re-render, React will re-subscribe to the store using the newly passed subscribe function. You can prevent this by declaring subscribe outside the component.\n */\nclass ViewWrapper<\n TTable extends keyof TSchema['tables'] & string,\n TSchema extends BaseDefaultSchema,\n TReturn,\n MD extends AnyMutatorRegistry | CustomMutatorDefs | undefined,\n TContext extends BaseDefaultContext,\n> {\n #view: TypedView<HumanReadable<TReturn>> | undefined;\n readonly #onDematerialized;\n readonly #query: Query<TTable, TSchema, TReturn>;\n #snapshot: QueryResult<TReturn>;\n readonly #reactInternals: Set<() => void> = new Set();\n #ttl: TTL;\n #complete = false;\n #completeResolver = resolver<void>();\n #nonEmpty = false;\n #nonEmptyResolver = resolver<void>();\n readonly #zero: Pick<Zero<TSchema, undefined, TContext>, 'materialize'>;\n readonly #singular: boolean;\n #destroyTimer: ReturnType<typeof setTimeout> | undefined;\n\n constructor(\n query: Query<TTable, TSchema, TReturn>,\n zero: Pick<Zero<TSchema, undefined, TContext>, 'materialize'>,\n ttl: TTL,\n onDematerialized: (\n view: ViewWrapper<TTable, TSchema, TReturn, MD, TContext>,\n ) => void,\n ) {\n this.#query = query;\n this.#zero = zero;\n this.#ttl = ttl;\n this.#onDematerialized = onDematerialized;\n const {singular} = asQueryInternals(query).format;\n this.#singular = singular;\n this.#snapshot = getDefaultSnapshot(singular);\n this.#materializeIfNeeded();\n }\n\n #onData = (\n snap: Immutable<HumanReadable<TReturn>>,\n resultType: ResultType,\n error?: ErroredQuery,\n ) => {\n const data =\n snap === undefined\n ? snap\n : (deepClone(snap as ReadonlyJSONValue) as HumanReadable<TReturn>);\n this.#snapshot = getSnapshot(\n this.#singular,\n data,\n resultType,\n this.#retry,\n error,\n );\n if (resultType === 'complete' || resultType === 'error') {\n this.#complete = true;\n this.#completeResolver.resolve();\n this.#nonEmpty = true;\n this.#nonEmptyResolver.resolve();\n }\n\n if (\n this.#singular\n ? this.#snapshot[0] !== undefined\n : (this.#snapshot[0] as unknown[]).length !== 0\n ) {\n this.#nonEmpty = true;\n this.#nonEmptyResolver.resolve();\n }\n\n for (const internals of this.#reactInternals) {\n internals();\n }\n };\n\n /**\n * Called by the user to force a retry of the query\n * in the case the query errored.\n */\n #retry = () => {\n this.#view?.destroy();\n this.#view = undefined;\n this.#materializeIfNeeded();\n };\n\n #materializeIfNeeded = () => {\n if (this.#view) {\n return;\n }\n this.#view = this.#zero.materialize(this.#query, {\n ttl: this.#ttl,\n });\n this.#view.addListener(this.#onData);\n };\n\n getSnapshot = () => this.#snapshot;\n\n subscribeReactInternals = (internals: () => void): (() => void) => {\n this.#reactInternals.add(internals);\n // Cancel any pending destroy timer from a previous unsubscribe.\n // Without this, rapid unsub/resub cycles accumulate stale timers\n // that can fire during a gap between unsubscribe and resubscribe,\n // destroying the view even though it was actively used.\n if (this.#destroyTimer !== undefined) {\n clearTimeout(this.#destroyTimer);\n this.#destroyTimer = undefined;\n }\n this.#materializeIfNeeded();\n return () => {\n this.#reactInternals.delete(internals);\n\n // only schedule a cleanup task if we have no listeners left\n if (this.#reactInternals.size === 0) {\n this.#destroyTimer = setTimeout(() => {\n this.#destroyTimer = undefined;\n\n // We already destroyed the view\n if (this.#view === undefined) {\n return;\n }\n\n // Someone re-registered a listener on this view before the timeout elapsed.\n // This happens often in strict-mode which forces a component\n // to mount, unmount, remount.\n if (this.#reactInternals.size > 0) {\n return;\n }\n\n this.#view.destroy();\n this.#view = undefined;\n this.#complete = false;\n this.#completeResolver = resolver();\n this.#nonEmpty = false;\n this.#nonEmptyResolver = resolver();\n this.#onDematerialized(this);\n }, 10);\n }\n };\n };\n\n updateTTL(ttl: TTL): void {\n this.#ttl = ttl;\n this.#view?.updateTTL(ttl);\n }\n\n get complete() {\n return this.#complete;\n }\n\n waitForComplete(): Promise<void> {\n return this.#completeResolver.promise;\n }\n\n get nonEmpty() {\n return this.#nonEmpty;\n }\n\n waitForNonEmpty(): Promise<void> {\n return this.#nonEmptyResolver.promise;\n }\n}\n"],"mappings":";;;;;;;;;;;AAyEA,IAAM,WAAY,aAAA,QAAgD;AAClE,IAAM,UAAyC,WAC3C,YACA,MAAK;CACH,MAAM;AACR;AAsCJ,SAAgB,SAQd,OAGA,SACkD;CAClD,IAAI,UAAU;CACd,IAAI,MAAW;CACf,IAAI,OAAO,YAAY,WACrB,UAAU;MACL,IAAI,SACT,CAAC,CAAC,UAAU,MAAM,MAAM,kBAAkB;CAG5C,MAAM,OAAO,QAAsC;CAGnD,MAAM,IAAI,QAAQ,kBAAkB,OAAO,KAAK,OAAO,IAAI,KAAA;CAC3D,MAAM,OAAO,IAAI,UAAU,QAAQ,MAAM,GAAG,SAAS,GAAG,IAAI,KAAA;CAI5D,QAAA,GAAA,aAAA,sBACE,MAAM,2BAA2B,oBACjC,MAAM,eACH,qBACH,MAAM,eACH,mBACL;AACF;AAsCA,SAAgB,iBAQd,OAGA,SACkD;CAClD,IAAI,UAAU;CACd,IAAI,MAAW;CACf,IAAI,eAAuC;CAC3C,IAAI,OAAO,YAAY,WACrB,UAAU;MACL,IAAI,SACT,CAAC,CACC,UAAU,MACV,MAAM,gBACN,eAAe,cACb;CAGN,MAAM,OAAO,QAAsC;CAGnD,MAAM,IAAI,QAAQ,kBAAkB,OAAO,KAAK,OAAO,IAAI,KAAA;CAC3D,MAAM,OAAO,IAAI,UAAU,QAAQ,MAAM,GAAG,SAAS,GAAG,IAAI,KAAA;CAI5D,MAAM,YAAA,GAAA,aAAA,sBACJ,MAAM,2BAA2B,oBACjC,MAAM,eACH,qBACH,MAAM,eACH,mBACL;CAEA,IAAI,QAAQ,SAAS;EACnB,IAAI,iBAAiB,cAAc,CAA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GAC/B,KAAKA,gBAAgB,KAAA;EACvB;EACA,KAAKR,qBAAqB;EAC1B,aAAa;GACX,KAAKL,gBAAgB,OAAO,SAAS;GAGrC,IAAI,KAAKA,gBAAgB,SAAS,GAChC,KAAKa,gBAAgB,iBAAiB;IACpC,KAAKA,gBAAgB,KAAA;IAGrB,IAAI,KAAKF,UAAU,KAAA,GACjB;IAMF,IAAI,KAAKX,gBAAgB,OAAO,GAC9B;IAGF,KAAKW,MAAM,QAAQ;IACnB,KAAKA,QAAQ,KAAA;IACb,KAAKJ,YAAY;IACjB,KAAKC,oBAAoB,SAAS;IAClC,KAAKC,YAAY;IACjB,KAAKC,oBAAoB,SAAS;IAClC,KAAKZ,kBAAkB,IAAI;GAC7B,GAAG,EAAE;EAET;CACF;CAEA,UAAU,KAAgB;EACxB,KAAKK,OAAO;EACZ,KAAKQ,OAAO,UAAU,GAAG;CAC3B;CAEA,IAAI,WAAW;EACb,OAAO,KAAKJ;CACd;CAEA,kBAAiC;EAC/B,OAAO,KAAKC,kBAAkB;CAChC;CAEA,IAAI,WAAW;EACb,OAAO,KAAKC;CACd;CAEA,kBAAiC;EAC/B,OAAO,KAAKC,kBAAkB;CAChC;AACF"}
|
|
1
|
+
{"version":3,"file":"use-query.js","names":["#views","#onDematerialized","#query","#reactInternals","#zero","#singular","#ttl","#snapshot","#materializeIfNeeded","#retry","#complete","#completeResolver","#nonEmpty","#nonEmptyResolver","#view","#onData","#destroyTimer"],"sources":["../../../../zero-react/src/use-query.tsx"],"sourcesContent":["import {resolver} from '@rocicorp/resolver';\nimport React, {useSyncExternalStore} from 'react';\nimport {TESTING} from '../../shared/src/testing.ts';\nimport {\n type Immutable,\n addContextToQuery,\n asQueryInternals,\n deepClone,\n DEFAULT_TTL_MS,\n} from './bindings.ts';\nimport {useZero} from './zero-provider.tsx';\nimport type {\n AnyMutatorRegistry,\n BaseDefaultContext,\n BaseDefaultSchema,\n CustomMutatorDefs,\n DefaultContext,\n DefaultSchema,\n ErroredQuery,\n Falsy,\n HumanReadable,\n PullRow,\n Query,\n QueryErrorDetails,\n QueryOrQueryRequest,\n QueryResultDetails,\n ReadonlyJSONValue,\n ResultType,\n TTL,\n TypedView,\n Zero,\n} from './zero.ts';\n\nexport type QueryResult<TReturn> = readonly [\n HumanReadable<TReturn>,\n QueryResultDetails & {},\n];\n\n/**\n * Result type for \"maybe queries\" - queries that may be falsy.\n * The data value can be undefined when the query is falsy/disabled.\n */\nexport type MaybeQueryResult<TReturn> = readonly [\n HumanReadable<TReturn> | undefined,\n QueryResultDetails & {},\n];\n\nexport type UseQueryOptions = {\n enabled?: boolean | undefined;\n /**\n * Time to live (TTL) in seconds. Controls how long query results are cached\n * after the query is removed. During this time, Zero continues to sync the query.\n * Default is 'never'.\n */\n ttl?: TTL | undefined;\n};\n\nexport type UseSuspenseQueryOptions = UseQueryOptions & {\n /**\n * Whether to suspend until:\n * - 'partial': the query has partial results (partial array or defined\n * value for singular results) which may be of result type 'unknown',\n * or the query result type is 'complete' (in which case results may be\n * empty). This is useful for suspending until there are partial\n * optimistic local results, or the query has completed loading from the\n * server.\n * - 'complete': the query result type is 'complete'.\n *\n * Default is 'partial'.\n */\n suspendUntil?: 'complete' | 'partial';\n};\n\nconst reactUse = (React as {use?: (p: Promise<unknown>) => void}).use;\nconst suspend: (p: Promise<unknown>) => void = reactUse\n ? reactUse\n : p => {\n throw p;\n };\n\n// Overload 1: Query\nexport function useQuery<\n TTable extends keyof TSchema['tables'] & string,\n TInput extends ReadonlyJSONValue | undefined,\n TOutput extends ReadonlyJSONValue | undefined,\n TSchema extends BaseDefaultSchema = DefaultSchema,\n TReturn = PullRow<TTable, TSchema>,\n TContext extends BaseDefaultContext = DefaultContext,\n>(\n query: QueryOrQueryRequest<\n TTable,\n TInput,\n TOutput,\n TSchema,\n TReturn,\n TContext\n >,\n options?: UseQueryOptions | boolean,\n): QueryResult<TReturn>;\n\n// Overload 2: Maybe query\nexport function useQuery<\n TTable extends keyof TSchema['tables'] & string,\n TInput extends ReadonlyJSONValue | undefined,\n TOutput extends ReadonlyJSONValue | undefined,\n TSchema extends BaseDefaultSchema = DefaultSchema,\n TReturn = PullRow<TTable, TSchema>,\n TContext extends BaseDefaultContext = DefaultContext,\n>(\n query:\n | QueryOrQueryRequest<TTable, TInput, TOutput, TSchema, TReturn, TContext>\n | Falsy,\n options?: UseQueryOptions | boolean,\n): MaybeQueryResult<TReturn>;\n\n// Implementation\nexport function useQuery<\n TTable extends keyof TSchema['tables'] & string,\n TInput extends ReadonlyJSONValue | undefined,\n TOutput extends ReadonlyJSONValue | undefined,\n TSchema extends BaseDefaultSchema = DefaultSchema,\n TReturn = PullRow<TTable, TSchema>,\n TContext extends BaseDefaultContext = DefaultContext,\n>(\n query:\n | QueryOrQueryRequest<TTable, TInput, TOutput, TSchema, TReturn, TContext>\n | Falsy,\n options?: UseQueryOptions | boolean,\n): QueryResult<TReturn> | MaybeQueryResult<TReturn> {\n let enabled = true;\n let ttl: TTL = DEFAULT_TTL_MS;\n if (typeof options === 'boolean') {\n enabled = options;\n } else if (options) {\n ({enabled = true, ttl = DEFAULT_TTL_MS} = options);\n }\n\n const zero = useZero<TSchema, undefined, TContext>();\n\n // When query is falsy, use disabled subscriber/snapshot to maintain hook order\n const q = query ? addContextToQuery(query, zero.context) : undefined;\n const view = q ? viewStore.getView(zero, q, enabled, ttl) : undefined;\n\n // https://react.dev/reference/react/useSyncExternalStore\n // Always call useSyncExternalStore to maintain consistent hook order\n return useSyncExternalStore(\n view?.subscribeReactInternals ?? disabledSubscriber,\n view?.getSnapshot ??\n (getDisabledSnapshot as () => MaybeQueryResult<TReturn>),\n view?.getSnapshot ??\n (getDisabledSnapshot as () => MaybeQueryResult<TReturn>),\n );\n}\n\n// Overload 1: Query\nexport function useSuspenseQuery<\n TTable extends keyof TSchema['tables'] & string,\n TInput extends ReadonlyJSONValue | undefined,\n TOutput extends ReadonlyJSONValue | undefined,\n TSchema extends BaseDefaultSchema = DefaultSchema,\n TReturn = PullRow<TTable, TSchema>,\n TContext extends BaseDefaultContext = DefaultContext,\n>(\n query: QueryOrQueryRequest<\n TTable,\n TInput,\n TOutput,\n TSchema,\n TReturn,\n TContext\n >,\n options?: UseSuspenseQueryOptions | boolean,\n): QueryResult<TReturn>;\n\n// Overload 2: Maybe query\nexport function useSuspenseQuery<\n TTable extends keyof TSchema['tables'] & string,\n TInput extends ReadonlyJSONValue | undefined,\n TOutput extends ReadonlyJSONValue | undefined,\n TSchema extends BaseDefaultSchema = DefaultSchema,\n TReturn = PullRow<TTable, TSchema>,\n TContext extends BaseDefaultContext = DefaultContext,\n>(\n query:\n | QueryOrQueryRequest<TTable, TInput, TOutput, TSchema, TReturn, TContext>\n | Falsy,\n options?: UseSuspenseQueryOptions | boolean,\n): MaybeQueryResult<TReturn>;\n\n// Implementation\nexport function useSuspenseQuery<\n TTable extends keyof TSchema['tables'] & string,\n TInput extends ReadonlyJSONValue | undefined,\n TOutput extends ReadonlyJSONValue | undefined,\n TSchema extends BaseDefaultSchema = DefaultSchema,\n TReturn = PullRow<TTable, TSchema>,\n TContext extends BaseDefaultContext = DefaultContext,\n>(\n query:\n | QueryOrQueryRequest<TTable, TInput, TOutput, TSchema, TReturn, TContext>\n | Falsy,\n options?: UseSuspenseQueryOptions | boolean,\n): QueryResult<TReturn> | MaybeQueryResult<TReturn> {\n let enabled = true;\n let ttl: TTL = DEFAULT_TTL_MS;\n let suspendUntil: 'complete' | 'partial' = 'partial';\n if (typeof options === 'boolean') {\n enabled = options;\n } else if (options) {\n ({\n enabled = true,\n ttl = DEFAULT_TTL_MS,\n suspendUntil = 'complete',\n } = options);\n }\n\n const zero = useZero<TSchema, undefined, TContext>();\n\n // When query is falsy, use disabled subscriber/snapshot to maintain hook order\n const q = query ? addContextToQuery(query, zero.context) : undefined;\n const view = q ? viewStore.getView(zero, q, enabled, ttl) : undefined;\n\n // https://react.dev/reference/react/useSyncExternalStore\n // Always call useSyncExternalStore to maintain consistent hook order\n const snapshot = useSyncExternalStore(\n view?.subscribeReactInternals ?? disabledSubscriber,\n view?.getSnapshot ??\n (getDisabledSnapshot as () => MaybeQueryResult<TReturn>),\n view?.getSnapshot ??\n (getDisabledSnapshot as () => MaybeQueryResult<TReturn>),\n );\n\n if (view && enabled) {\n if (suspendUntil === 'complete' && !view.complete) {\n suspend(view.waitForComplete());\n }\n\n if (suspendUntil === 'partial' && !view.nonEmpty) {\n suspend(view.waitForNonEmpty());\n }\n }\n\n return snapshot;\n}\n\nconst emptyArray: unknown[] = [];\nconst disabledSubscriber = () => () => {};\n\nconst resultTypeUnknown = {type: 'unknown'} as const;\nconst resultTypeComplete = {type: 'complete'} as const;\nconst resultTypeError = {type: 'error'} as const;\n\nconst disabledQuerySnapshot = [undefined, resultTypeUnknown] as const;\nconst getDisabledSnapshot = () => disabledQuerySnapshot;\n\nconst emptySnapshotSingularUnknown = [undefined, resultTypeUnknown] as const;\nconst emptySnapshotSingularComplete = [undefined, resultTypeComplete] as const;\nconst emptySnapshotSingularErrorUnknown = [undefined, resultTypeError] as const;\nconst emptySnapshotPluralUnknown = [emptyArray, resultTypeUnknown] as const;\nconst emptySnapshotPluralComplete = [emptyArray, resultTypeComplete] as const;\nconst emptySnapshotErrorUnknown = [emptyArray, resultTypeError] as const;\n\nfunction getDefaultSnapshot<TReturn>(singular: boolean): QueryResult<TReturn> {\n return (\n singular ? emptySnapshotSingularUnknown : emptySnapshotPluralUnknown\n ) as QueryResult<TReturn>;\n}\n\n/**\n * Returns a new snapshot or one of the empty predefined ones. Returning the\n * predefined ones is important to prevent unnecessary re-renders in React.\n */\nfunction getSnapshot<TReturn>(\n singular: boolean,\n data: HumanReadable<TReturn>,\n resultType: ResultType,\n retryFn: () => void,\n error?: ErroredQuery,\n): QueryResult<TReturn> {\n if (singular && data === undefined) {\n switch (resultType) {\n case 'error':\n if (error) {\n return [\n undefined,\n makeError(retryFn, error),\n ] as unknown as QueryResult<TReturn>;\n }\n return emptySnapshotSingularErrorUnknown as unknown as QueryResult<TReturn>;\n case 'complete':\n return emptySnapshotSingularComplete as unknown as QueryResult<TReturn>;\n case 'unknown':\n return emptySnapshotSingularUnknown as unknown as QueryResult<TReturn>;\n }\n }\n\n if (!singular && (data as unknown[]).length === 0) {\n switch (resultType) {\n case 'error':\n if (error) {\n return [\n emptyArray,\n makeError(retryFn, error),\n ] as unknown as QueryResult<TReturn>;\n }\n return emptySnapshotErrorUnknown as unknown as QueryResult<TReturn>;\n case 'complete':\n return emptySnapshotPluralComplete as unknown as QueryResult<TReturn>;\n case 'unknown':\n return emptySnapshotPluralUnknown as unknown as QueryResult<TReturn>;\n }\n }\n\n switch (resultType) {\n case 'error':\n if (error) {\n return [data, makeError(retryFn, error)];\n }\n return [\n data,\n makeError(retryFn, {\n error: 'app',\n id: 'unknown',\n name: 'unknown',\n message: 'An unknown error occurred',\n }),\n ];\n case 'complete':\n return [data, resultTypeComplete];\n case 'unknown':\n return [data, resultTypeUnknown];\n }\n}\n\nfunction makeError(retry: () => void, error: ErroredQuery): QueryErrorDetails {\n const message = error.message ?? 'An unknown error occurred';\n return {\n type: 'error',\n retry,\n refetch: retry,\n error: {\n type: error.error,\n message,\n ...(error.details ? {details: error.details} : {}),\n },\n };\n}\n\n// oxlint-disable-next-line @typescript-eslint/no-explicit-any\ntype AnyViewWrapper = ViewWrapper<any, any, any, any, any>;\n\nconst allViews = new WeakMap<ViewStore, Map<string, AnyViewWrapper>>();\n\nexport function getAllViewsSizeForTesting(store: ViewStore): number {\n if (TESTING) {\n return allViews.get(store)?.size ?? 0;\n }\n return 0;\n}\n\n/**\n * A global store of all active views.\n *\n * React subscribes and unsubscribes to these views\n * via `useSyncExternalStore`.\n *\n * Managing views through `useEffect` or `useLayoutEffect` causes\n * inconsistencies because effects run after render.\n *\n * For example, if useQuery used use*Effect in the component below:\n * ```ts\n * function Foo({issueID}) {\n * const issue = useQuery(z.query.issue.where('id', issueID).one());\n * if (issue?.id !== undefined && issue.id !== issueID) {\n * console.log('MISMATCH!', issue.id, issueID);\n * }\n * }\n * ```\n *\n * `MISMATCH` will be printed whenever the `issueID` prop changes.\n *\n * This is because the component will render once with\n * the old state returned from `useQuery`. Then the effect inside\n * `useQuery` will run. The component will render again with the new\n * state. This inconsistent transition can cause unexpected results.\n *\n * Emulating `useEffect` via `useState` and `if` causes resource leaks.\n * That is:\n *\n * ```ts\n * function useQuery(q) {\n * const [oldHash, setOldHash] = useState();\n * if (hash(q) !== oldHash) {\n * // make new view\n * }\n *\n * useEffect(() => {\n * return () => view.destroy();\n * }, []);\n * }\n * ```\n *\n * I'm not sure why but in strict mode the cleanup function\n * fails to be called for the first instance of the view and only\n * cleans up later instances.\n *\n * Swapping `useState` to `useRef` has similar problems.\n */\nexport class ViewStore {\n #views = new Map<string, AnyViewWrapper>();\n\n constructor() {\n if (TESTING) {\n allViews.set(this, this.#views);\n }\n }\n\n getView<\n TTable extends keyof TSchema['tables'] & string,\n TSchema extends BaseDefaultSchema,\n TReturn,\n MD extends CustomMutatorDefs | undefined,\n TContext extends BaseDefaultContext,\n >(\n zero: Zero<TSchema, MD, TContext>,\n q: Query<TTable, TSchema, TReturn>,\n enabled: boolean,\n ttl: TTL,\n ): {\n getSnapshot: () => QueryResult<TReturn>;\n subscribeReactInternals: (internals: () => void) => () => void;\n updateTTL: (ttl: TTL) => void;\n waitForComplete: () => Promise<void>;\n waitForNonEmpty: () => Promise<void>;\n complete: boolean;\n nonEmpty: boolean;\n } {\n const qi = asQueryInternals(q);\n\n if (!enabled) {\n return {\n getSnapshot: () => getDefaultSnapshot(qi.format.singular),\n subscribeReactInternals: disabledSubscriber,\n updateTTL: () => {},\n waitForComplete: () => Promise.resolve(),\n waitForNonEmpty: () => Promise.resolve(),\n complete: false,\n nonEmpty: false,\n };\n }\n\n const hash = qi.hash() + zero.clientID;\n let existing = this.#views.get(hash);\n if (!existing) {\n existing = new ViewWrapper(q, zero, ttl, view => {\n const currentView = this.#views.get(hash);\n if (currentView && currentView !== view) {\n // we replaced the view with a new one already.\n return;\n }\n this.#views.delete(hash);\n });\n this.#views.set(hash, existing);\n } else {\n existing.updateTTL(ttl);\n }\n return existing as ViewWrapper<TTable, TSchema, TReturn, MD, TContext>;\n }\n}\n\nconst viewStore = new ViewStore();\n\n/**\n * This wraps and ref counts a view.\n *\n * The only signal we have from React as to whether or not it is\n * done with a view is when it calls `unsubscribe`.\n *\n * In non-strict-mode we can clean up the view as soon\n * as the listener count goes to 0.\n *\n * In strict-mode, the listener count will go to 0 then a\n * new listener for the same view is immediately added back.\n *\n * This is why the `onMaterialized` and `onDematerialized` callbacks exist --\n * they allow a view which React is still referencing to be added\n * back into the store when React re-subscribes to it.\n *\n * This wrapper also exists to deal with the various\n * `useSyncExternalStore` caveats that cause excessive\n * re-renders and materializations.\n *\n * See: https://react.dev/reference/react/useSyncExternalStore#caveats\n * Especially:\n * 1. The store snapshot returned by getSnapshot must be immutable. If the underlying store has mutable data, return a new immutable snapshot if the data has changed. Otherwise, return a cached last snapshot.\n * 2. If a different subscribe function is passed during a re-render, React will re-subscribe to the store using the newly passed subscribe function. You can prevent this by declaring subscribe outside the component.\n */\nclass ViewWrapper<\n TTable extends keyof TSchema['tables'] & string,\n TSchema extends BaseDefaultSchema,\n TReturn,\n MD extends AnyMutatorRegistry | CustomMutatorDefs | undefined,\n TContext extends BaseDefaultContext,\n> {\n #view: TypedView<HumanReadable<TReturn>> | undefined;\n readonly #onDematerialized;\n readonly #query: Query<TTable, TSchema, TReturn>;\n #snapshot: QueryResult<TReturn>;\n readonly #reactInternals: Set<() => void> = new Set();\n #ttl: TTL;\n #complete = false;\n #completeResolver = resolver<void>();\n #nonEmpty = false;\n #nonEmptyResolver = resolver<void>();\n readonly #zero: Pick<Zero<TSchema, undefined, TContext>, 'materialize'>;\n readonly #singular: boolean;\n #destroyTimer: ReturnType<typeof setTimeout> | undefined;\n\n constructor(\n query: Query<TTable, TSchema, TReturn>,\n zero: Pick<Zero<TSchema, undefined, TContext>, 'materialize'>,\n ttl: TTL,\n onDematerialized: (\n view: ViewWrapper<TTable, TSchema, TReturn, MD, TContext>,\n ) => void,\n ) {\n this.#query = query;\n this.#zero = zero;\n this.#ttl = ttl;\n this.#onDematerialized = onDematerialized;\n const {singular} = asQueryInternals(query).format;\n this.#singular = singular;\n this.#snapshot = getDefaultSnapshot(singular);\n this.#materializeIfNeeded();\n }\n\n #onData = (\n snap: Immutable<HumanReadable<TReturn>>,\n resultType: ResultType,\n error?: ErroredQuery,\n ) => {\n const data =\n snap === undefined\n ? snap\n : (deepClone(snap as ReadonlyJSONValue) as HumanReadable<TReturn>);\n this.#snapshot = getSnapshot(\n this.#singular,\n data,\n resultType,\n this.#retry,\n error,\n );\n if (resultType === 'complete' || resultType === 'error') {\n this.#complete = true;\n this.#completeResolver.resolve();\n this.#nonEmpty = true;\n this.#nonEmptyResolver.resolve();\n }\n\n if (\n this.#singular\n ? this.#snapshot[0] !== undefined\n : (this.#snapshot[0] as unknown[]).length !== 0\n ) {\n this.#nonEmpty = true;\n this.#nonEmptyResolver.resolve();\n }\n\n for (const internals of this.#reactInternals) {\n internals();\n }\n };\n\n /**\n * Called by the user to force a retry of the query\n * in the case the query errored.\n */\n #retry = () => {\n this.#view?.destroy();\n this.#view = undefined;\n this.#materializeIfNeeded();\n };\n\n #materializeIfNeeded = () => {\n if (this.#view) {\n return;\n }\n this.#view = this.#zero.materialize(this.#query, {\n ttl: this.#ttl,\n });\n this.#view.addListener(this.#onData);\n };\n\n getSnapshot = () => this.#snapshot;\n\n subscribeReactInternals = (internals: () => void): (() => void) => {\n this.#reactInternals.add(internals);\n // Cancel any pending destroy timer from a previous unsubscribe.\n // Without this, rapid unsub/resub cycles accumulate stale timers\n // that can fire during a gap between unsubscribe and resubscribe,\n // destroying the view even though it was actively used.\n if (this.#destroyTimer !== undefined) {\n clearTimeout(this.#destroyTimer);\n this.#destroyTimer = undefined;\n }\n this.#materializeIfNeeded();\n return () => {\n this.#reactInternals.delete(internals);\n\n // only schedule a cleanup task if we have no listeners left\n if (this.#reactInternals.size === 0) {\n this.#destroyTimer = setTimeout(() => {\n this.#destroyTimer = undefined;\n\n // We already destroyed the view\n if (this.#view === undefined) {\n return;\n }\n\n // Someone re-registered a listener on this view before the timeout elapsed.\n // This happens often in strict-mode which forces a component\n // to mount, unmount, remount.\n if (this.#reactInternals.size > 0) {\n return;\n }\n\n this.#view.destroy();\n this.#view = undefined;\n this.#complete = false;\n this.#completeResolver = resolver();\n this.#nonEmpty = false;\n this.#nonEmptyResolver = resolver();\n this.#onDematerialized(this);\n }, 10);\n }\n };\n };\n\n updateTTL(ttl: TTL): void {\n this.#ttl = ttl;\n this.#view?.updateTTL(ttl);\n }\n\n get complete() {\n return this.#complete;\n }\n\n waitForComplete(): Promise<void> {\n return this.#completeResolver.promise;\n }\n\n get nonEmpty() {\n return this.#nonEmpty;\n }\n\n waitForNonEmpty(): Promise<void> {\n return this.#nonEmptyResolver.promise;\n }\n}\n"],"mappings":";;;;;;;;;AAyEA,IAAM,WAAY,MAAgD;AAClE,IAAM,UAAyC,WAC3C,YACA,MAAK;CACH,MAAM;AACR;AAsCJ,SAAgB,SAQd,OAGA,SACkD;CAClD,IAAI,UAAU;CACd,IAAI,MAAW;CACf,IAAI,OAAO,YAAY,WACrB,UAAU;MACL,IAAI,SACT,CAAC,CAAC,UAAU,MAAM,MAAM,kBAAkB;CAG5C,MAAM,OAAO,QAAsC;CAGnD,MAAM,IAAI,QAAQ,kBAAkB,OAAO,KAAK,OAAO,IAAI,KAAA;CAC3D,MAAM,OAAO,IAAI,UAAU,QAAQ,MAAM,GAAG,SAAS,GAAG,IAAI,KAAA;CAI5D,OAAO,qBACL,MAAM,2BAA2B,oBACjC,MAAM,eACH,qBACH,MAAM,eACH,mBACL;AACF;AAsCA,SAAgB,iBAQd,OAGA,SACkD;CAClD,IAAI,UAAU;CACd,IAAI,MAAW;CACf,IAAI,eAAuC;CAC3C,IAAI,OAAO,YAAY,WACrB,UAAU;MACL,IAAI,SACT,CAAC,CACC,UAAU,MACV,MAAM,gBACN,eAAe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A6B;EAC3B,IAAI,KAAKM,OACP;EAEF,KAAKA,QAAQ,KAAKV,MAAM,YAAY,KAAKF,QAAQ,EAC/C,KAAK,KAAKI,KACZ,CAAC;EACD,KAAKQ,MAAM,YAAY,KAAKC,OAAO;CACrC;CAEA,oBAAoB,KAAKR;CAEzB,2BAA2B,cAAwC;EACjE,KAAKJ,gBAAgB,IAAI,SAAS;EAKlC,IAAI,KAAKa,kBAAkB,KAAA,GAAW;GACpC,aAAa,KAAKA,aAAa;GAC/B,KAAKA,gBAAgB,KAAA;EACvB;EACA,KAAKR,qBAAqB;EAC1B,aAAa;GACX,KAAKL,gBAAgB,OAAO,SAAS;GAGrC,IAAI,KAAKA,gBAAgB,SAAS,GAChC,KAAKa,gBAAgB,iBAAiB;IACpC,KAAKA,gBAAgB,KAAA;IAGrB,IAAI,KAAKF,UAAU,KAAA,GACjB;IAMF,IAAI,KAAKX,gBAAgB,OAAO,GAC9B;IAGF,KAAKW,MAAM,QAAQ;IACnB,KAAKA,QAAQ,KAAA;IACb,KAAKJ,YAAY;IACjB,KAAKC,oBAAoB,SAAS;IAClC,KAAKC,YAAY;IACjB,KAAKC,oBAAoB,SAAS;IAClC,KAAKZ,kBAAkB,IAAI;GAC7B,GAAG,EAAE;EAET;CACF;CAEA,UAAU,KAAgB;EACxB,KAAKK,OAAO;EACZ,KAAKQ,OAAO,UAAU,GAAG;CAC3B;CAEA,IAAI,WAAW;EACb,OAAO,KAAKJ;CACd;CAEA,kBAAiC;EAC/B,OAAO,KAAKC,kBAAkB;CAChC;CAEA,IAAI,WAAW;EACb,OAAO,KAAKC;CACd;CAEA,kBAAiC;EAC/B,OAAO,KAAKC,kBAAkB;CAChC;AACF"}
|
|
@@ -1,8 +1,6 @@
|
|
|
1
|
-
import { __toESM } from "../../_virtual/_rolldown/runtime.js";
|
|
2
|
-
import { require_react } from "../../node_modules/.pnpm/react@18.3.1/node_modules/react/index.js";
|
|
3
1
|
import { useZero } from "./zero-provider.js";
|
|
2
|
+
import { useSyncExternalStore } from "react";
|
|
4
3
|
//#region ../zero-react/src/use-zero-online.tsx
|
|
5
|
-
var import_react = /* @__PURE__ */ __toESM(require_react(), 1);
|
|
6
4
|
/**
|
|
7
5
|
* Hook to subscribe to the online status of the Zero instance.
|
|
8
6
|
*
|
|
@@ -14,7 +12,7 @@ var import_react = /* @__PURE__ */ __toESM(require_react(), 1);
|
|
|
14
12
|
*/
|
|
15
13
|
function useZeroOnline() {
|
|
16
14
|
const zero = useZero();
|
|
17
|
-
return
|
|
15
|
+
return useSyncExternalStore(zero.onOnline, () => zero.online, () => zero.online);
|
|
18
16
|
}
|
|
19
17
|
//#endregion
|
|
20
18
|
export { useZeroOnline };
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"use-zero-online.js","names":[],"sources":["../../../../zero-react/src/use-zero-online.tsx"],"sourcesContent":["import {useSyncExternalStore} from 'react';\nimport {useZero} from './zero-provider.tsx';\n\n/**\n * Hook to subscribe to the online status of the Zero instance.\n *\n * This is useful when you want to update state based on the online status.\n *\n * @returns The online status of the Zero instance.\n *\n * @deprecated Use {@linkcode useConnectionState} instead, which provides more detailed connection state.\n */\nexport function useZeroOnline(): boolean {\n const zero = useZero();\n return useSyncExternalStore(\n zero.onOnline,\n () => zero.online,\n () => zero.online,\n );\n}\n"],"mappings":"
|
|
1
|
+
{"version":3,"file":"use-zero-online.js","names":[],"sources":["../../../../zero-react/src/use-zero-online.tsx"],"sourcesContent":["import {useSyncExternalStore} from 'react';\nimport {useZero} from './zero-provider.tsx';\n\n/**\n * Hook to subscribe to the online status of the Zero instance.\n *\n * This is useful when you want to update state based on the online status.\n *\n * @returns The online status of the Zero instance.\n *\n * @deprecated Use {@linkcode useConnectionState} instead, which provides more detailed connection state.\n */\nexport function useZeroOnline(): boolean {\n const zero = useZero();\n return useSyncExternalStore(\n zero.onOnline,\n () => zero.online,\n () => zero.online,\n );\n}\n"],"mappings":";;;;;;;;;;;;AAYA,SAAgB,gBAAyB;CACvC,MAAM,OAAO,QAAQ;CACrB,OAAO,qBACL,KAAK,gBACC,KAAK,cACL,KAAK,MACb;AACF"}
|