@rocicorp/zero 1.11.0-canary.2 → 1.11.0-canary.4

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.
@@ -310,6 +310,7 @@ var CVRConfigDrivenUpdater = class extends CVRUpdater {
310
310
  *
311
311
  * * {@link trackQueries} for queries that are being executed or removed.
312
312
  * * {@link received} for all rows received from the executed queries
313
+ * * {@link removeTrackedQueries} for optional queries that did not execute
313
314
  * * {@link deleteUnreferencedRows} to remove any rows that have
314
315
  * fallen out of the query result view.
315
316
  * * {@link flush}
@@ -320,6 +321,7 @@ var CVRConfigDrivenUpdater = class extends CVRUpdater {
320
321
  */
321
322
  var CVRQueryDrivenUpdater = class extends CVRUpdater {
322
323
  #removedOrExecutedQueryIDs = /* @__PURE__ */ new Set();
324
+ #executedQueryIDs = /* @__PURE__ */ new Set();
323
325
  #receivedRows = new CustomKeyMap(rowIDString);
324
326
  #lastPatches = new CustomKeyMap(rowIDString);
325
327
  #rowSetSignature;
@@ -396,6 +398,7 @@ var CVRQueryDrivenUpdater = class extends CVRUpdater {
396
398
  return startSpan(tracer, "CVRQueryDrivenUpdater.#trackExecuted", () => {
397
399
  assert(!this.#removedOrExecutedQueryIDs.has(queryID), () => `Query ${queryID} already tracked as executed or removed`);
398
400
  this.#removedOrExecutedQueryIDs.add(queryID);
401
+ this.#executedQueryIDs.add(queryID);
399
402
  let gotQueryPatch;
400
403
  const query = this._cvr.queries[queryID];
401
404
  if (query.transformationHash !== transformationHash) {
@@ -416,6 +419,42 @@ var CVRQueryDrivenUpdater = class extends CVRUpdater {
416
419
  });
417
420
  }
418
421
  /**
422
+ * Converts queries that were tracked as executed into normal query
423
+ * removals. This is used when a hydration budget expires after
424
+ * `trackQueries()` has established the final poke version but before an
425
+ * optional query starts hydration.
426
+ *
427
+ * The query ID remains in `#removedOrExecutedQueryIDs`, so its row
428
+ * references are dropped by {@link deleteUnreferencedRows} exactly as they
429
+ * would be for a query removed up front. Never un-track a query here: rows
430
+ * already flushed by {@link received} have had its refCounts stripped and
431
+ * cannot be restored.
432
+ */
433
+ removeTrackedQueries(queryIDs) {
434
+ assert(this.#existingRows !== void 0, "trackQueries() was not called");
435
+ assert(cmpVersions(this._orig.version, this._cvr.version) < 0, "A final CVR version must be set before removing tracked queries");
436
+ const patches = [];
437
+ for (const queryID of queryIDs) {
438
+ assert(this.#executedQueryIDs.has(queryID), () => `Query ${queryID} was not tracked as executed`);
439
+ const query = must(this._cvr.queries[queryID]);
440
+ assertNotInternal(query);
441
+ assert(Object.values(query.clientState).every(({ inactivatedAt }) => inactivatedAt !== void 0), () => `Query ${queryID} is active`);
442
+ assert(query.patchVersion !== void 0, `Query ${queryID} is not gotten`);
443
+ delete this._cvr.queries[queryID];
444
+ const patch = {
445
+ type: "query",
446
+ op: "del",
447
+ id: queryID
448
+ };
449
+ this._cvrStore.markQueryAsDeleted(this._cvr.version, patch);
450
+ patches.push({
451
+ patch,
452
+ toVersion: this._cvr.version
453
+ });
454
+ }
455
+ return patches;
456
+ }
457
+ /**
419
458
  * Tracks a query removed from the "gotten" set. In addition to producing the
420
459
  * appropriate patches for deleting the query, the removed query is taken into
421
460
  * account when computing the final row records in
@@ -653,6 +692,40 @@ function getInactiveQueries(cvr) {
653
692
  return ttlClockAsNumber(a.inactivatedAt) + a.ttl - ttlClockAsNumber(b.inactivatedAt) - b.ttl;
654
693
  });
655
694
  }
695
+ /**
696
+ * Splits hydration candidates into required and optional queries. Optional
697
+ * queries are ordered from latest to earliest effective expiration; an
698
+ * ownerless query has the lowest priority.
699
+ */
700
+ function classifyQueriesForHydration(queries) {
701
+ const required = [];
702
+ const optionalWithExpiration = [];
703
+ for (const query of queries) {
704
+ if (query.type === "internal" || Object.values(query.clientState).some((state) => state.inactivatedAt === void 0)) {
705
+ required.push(query);
706
+ continue;
707
+ }
708
+ let expiration;
709
+ for (const { inactivatedAt, ttl } of Object.values(query.clientState)) {
710
+ assert(inactivatedAt !== void 0, "inactive query has active client");
711
+ const clientExpiration = ttlClockAsNumber(inactivatedAt) + clampTTL(ttl);
712
+ expiration = Math.max(expiration ?? -Infinity, clientExpiration);
713
+ }
714
+ optionalWithExpiration.push({
715
+ query,
716
+ expiration
717
+ });
718
+ }
719
+ optionalWithExpiration.sort((a, b) => {
720
+ if (a.expiration === void 0) return b.expiration === void 0 ? 0 : 1;
721
+ if (b.expiration === void 0) return -1;
722
+ return b.expiration - a.expiration;
723
+ });
724
+ return {
725
+ required,
726
+ optional: optionalWithExpiration.map(({ query }) => query)
727
+ };
728
+ }
656
729
  function nextEvictionTime(cvr) {
657
730
  let next;
658
731
  for (const { inactivatedAt, ttl } of getInactiveQueries(cvr)) {
@@ -681,6 +754,6 @@ function newQueryRecord(id, ast, name, args) {
681
754
  };
682
755
  }
683
756
  //#endregion
684
- export { CVRConfigDrivenUpdater, CVRQueryDrivenUpdater, nextEvictionTime };
757
+ export { CVRConfigDrivenUpdater, CVRQueryDrivenUpdater, classifyQueriesForHydration, nextEvictionTime };
685
758
 
686
759
  //# sourceMappingURL=cvr.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"cvr.js","names":["#shard","#deleteQueries","#removedOrExecutedQueryIDs","#receivedRows","#lastPatches","#rowSetSignature","#existingRows","#trackExecuted","#trackRemoved","#lookupRowsForExecutedAndRemovedQueries","#assertNewVersion","#deleteUnreferencedRow"],"sources":["../../../../../../zero-cache/src/services/view-syncer/cvr.ts"],"sourcesContent":["import type {LogContext} from '@rocicorp/logger';\nimport {startAsyncSpan, startSpan} from '../../../../otel/src/span.ts';\nimport {assert} from '../../../../shared/src/asserts.ts';\nimport {type JSONObject} from '../../../../shared/src/bigint-json.ts';\nimport {CustomKeyMap} from '../../../../shared/src/custom-key-map.ts';\nimport {toSorted} from '../../../../shared/src/iterables.ts';\nimport {\n deepEqual,\n type ReadonlyJSONValue,\n} from '../../../../shared/src/json.ts';\nimport {must} from '../../../../shared/src/must.ts';\nimport {\n difference,\n intersection,\n union,\n} from '../../../../shared/src/set-utils.ts';\nimport {stringCompare} from '../../../../shared/src/string-compare.ts';\nimport type {AST} from '../../../../zero-protocol/src/ast.ts';\nimport type {ClientSchema} from '../../../../zero-protocol/src/client-schema.ts';\nimport {ErrorOrigin} from '../../../../zero-protocol/src/error-origin.ts';\nimport {ProtocolError} from '../../../../zero-protocol/src/error.ts';\nimport {\n clampTTL,\n compareTTL,\n DEFAULT_TTL_MS,\n} from '../../../../zql/src/query/ttl.ts';\nimport {recordQuery} from '../../server/anonymous-otel-start.ts';\nimport type {LexiVersion} from '../../types/lexi-version.ts';\nimport {rowIDString} from '../../types/row-key.ts';\nimport {upstreamSchema, type ShardID} from '../../types/shards.ts';\nimport type {Patch, PatchToVersion} from './client-handler.ts';\nimport {type CVRFlushStats, type CVRStore} from './cvr-store.ts';\nimport {formatSignature, parseSignature} from './row-set-signature.ts';\nimport {\n cmpVersions,\n maxVersion,\n oneAfter,\n versionString,\n type ClientQueryRecord,\n type ClientRecord,\n type CustomQueryRecord,\n type CVRVersion,\n type InternalQueryRecord,\n type QueryRecord,\n type RowID,\n type RowRecord,\n} from './schema/types.ts';\nimport {tracer} from './tracer.ts';\nimport {ttlClockAsNumber, type TTLClock} from './ttl-clock.ts';\n\nexport type RowUpdate = {\n version?: string; // Undefined for an unref.\n contents?: JSONObject; // Undefined for an unref.\n refCounts: {[hash: string]: number}; // Counts are negative when a row is unrefed.\n};\n\n/** Internally used mutable CVR type. */\nexport type CVR = {\n id: string;\n version: CVRVersion;\n lastActive: number;\n ttlClock: TTLClock;\n replicaVersion: string | null;\n clients: Record<string, ClientRecord>;\n queries: Record<string, QueryRecord>;\n clientSchema: ClientSchema | null;\n profileID: string | null;\n};\n\n/** Exported immutable CVR type. */\n// TODO: Use Immutable<CVR> when the AST is immutable.\nexport type CVRSnapshot = {\n readonly id: string;\n readonly version: CVRVersion;\n readonly lastActive: number;\n readonly ttlClock: TTLClock;\n readonly replicaVersion: string | null;\n readonly clients: Readonly<Record<string, ClientRecord>>;\n readonly queries: Readonly<Record<string, QueryRecord>>;\n readonly clientSchema: ClientSchema | null;\n readonly profileID: string | null;\n};\n\nconst CLIENT_LMID_QUERY_ID = 'lmids';\nconst CLIENT_MUTATION_RESULTS_QUERY_ID = 'mutationResults';\n\nfunction assertNotInternal(\n query: QueryRecord,\n): asserts query is ClientQueryRecord {\n if (query.type === 'internal') {\n // This should never happen for behaving clients, as query ids should be hashes.\n throw new Error(`Query ID ${query.id} is reserved for internal use`);\n }\n}\n\nexport function getMutationResultsQuery(\n upstreamSchema: string,\n clientGroupID: string,\n): InternalQueryRecord {\n return {\n id: CLIENT_MUTATION_RESULTS_QUERY_ID,\n type: 'internal',\n ast: {\n schema: '',\n table: `${upstreamSchema}.mutations`,\n where: {\n type: 'and',\n conditions: [\n {\n type: 'simple',\n left: {\n type: 'column',\n name: 'clientGroupID',\n },\n op: '=',\n right: {\n type: 'literal',\n value: clientGroupID,\n },\n },\n ],\n },\n orderBy: [\n ['clientGroupID', 'asc'],\n ['clientID', 'asc'],\n ['mutationID', 'asc'],\n ],\n },\n };\n}\n\n/**\n * The base CVRUpdater contains logic common to the {@link CVRConfigDrivenUpdater} and\n * {@link CVRQueryDrivenUpdater}. The CVRUpdater class itself is exported for updating\n * the `lastActive` time of the CVR in the absence of any changes to the CVR contents.\n * Although activity is automatically tracked when the CVR contents change, there may be\n * edge cases in which a client actively connects to a CVR that doesn't itself change.\n * Calling `new CVRUpdater(...).flush()` will explicitly update the active index and\n * prevent the CVR from being garbage collected.\n */\nexport class CVRUpdater {\n protected readonly _orig: CVRSnapshot;\n protected readonly _cvr: CVR;\n\n protected readonly _cvrStore: CVRStore;\n\n /**\n * @param cvrStore The CVRStore to use for storage\n * @param cvr The current CVR\n */\n constructor(\n cvrStore: CVRStore,\n cvr: CVRSnapshot,\n replicaVersion: string | null,\n ) {\n this._cvrStore = cvrStore;\n this._orig = cvr;\n this._cvr = structuredClone(cvr) as CVR; // mutable deep copy\n this._cvr.replicaVersion = replicaVersion;\n }\n\n protected _setVersion(version: CVRVersion) {\n assert(\n cmpVersions(this._cvr.version, version) < 0,\n 'Expected new version to be greater than current version',\n );\n this._cvr.version = version;\n return version;\n }\n\n /**\n * Ensures that the new CVR has a higher version than the original.\n * This method is idempotent in that it will always return the same\n * (possibly bumped) version.\n */\n protected _ensureNewVersion(): CVRVersion {\n if (cmpVersions(this._orig.version, this._cvr.version) === 0) {\n this._setVersion(oneAfter(this._cvr.version));\n }\n return this._cvr.version;\n }\n\n async flush(\n lc: LogContext,\n lastConnectTime: number,\n lastActive: number,\n ttlClock: TTLClock,\n ): Promise<{\n cvr: CVRSnapshot;\n flushed: CVRFlushStats | false;\n }> {\n this._cvr.ttlClock = ttlClock;\n this._cvr.lastActive = lastActive;\n const flushed = await this._cvrStore.flush(\n lc,\n this._orig.version,\n this._cvr,\n lastConnectTime,\n );\n if (!flushed) {\n return {cvr: this._orig, flushed: false};\n }\n return {cvr: this._cvr, flushed};\n }\n}\n\n/**\n * A {@link CVRConfigDrivenUpdater} is used for updating a CVR with config-driven\n * changes. Note that this may result in row deletion (e.g. if queries get dropped),\n * but the `stateVersion` of the CVR does not change.\n */\nexport class CVRConfigDrivenUpdater extends CVRUpdater {\n readonly #shard: ShardID;\n\n constructor(cvrStore: CVRStore, cvr: CVRSnapshot, shard: ShardID) {\n super(cvrStore, cvr, cvr.replicaVersion);\n this.#shard = shard;\n }\n\n ensureClient(id: string): ClientRecord {\n return startSpan(tracer, 'CVRConfigDrivenUpdater.ensureClient', () => {\n let client = this._cvr.clients[id];\n if (client) {\n return client;\n }\n // Add the ClientRecord and PutPatch\n client = {id, desiredQueryIDs: []};\n this._cvr.clients[id] = client;\n\n this._ensureNewVersion();\n this._cvrStore.insertClient(client);\n\n if (!this._cvr.queries[CLIENT_LMID_QUERY_ID]) {\n const lmidsQuery: InternalQueryRecord = {\n id: CLIENT_LMID_QUERY_ID,\n ast: {\n schema: '',\n table: `${upstreamSchema(this.#shard)}.clients`,\n where: {\n type: 'simple',\n left: {\n type: 'column',\n name: 'clientGroupID',\n },\n op: '=',\n right: {\n type: 'literal',\n value: this._cvr.id,\n },\n },\n orderBy: [\n ['clientGroupID', 'asc'],\n ['clientID', 'asc'],\n ],\n },\n type: 'internal',\n };\n this._cvr.queries[CLIENT_LMID_QUERY_ID] = lmidsQuery;\n this._cvrStore.putQuery(lmidsQuery);\n }\n if (!this._cvr.queries[CLIENT_MUTATION_RESULTS_QUERY_ID]) {\n const mutationResultsQuery: InternalQueryRecord =\n getMutationResultsQuery(upstreamSchema(this.#shard), this._cvr.id);\n this._cvr.queries[CLIENT_MUTATION_RESULTS_QUERY_ID] =\n mutationResultsQuery;\n this._cvrStore.putQuery(mutationResultsQuery);\n }\n\n return client;\n });\n }\n\n setClientSchema(lc: LogContext, clientSchema: ClientSchema) {\n startSpan(tracer, 'CVRConfigDrivenUpdater.setClientSchema', () => {\n if (this._cvr.clientSchema === null) {\n this._cvr.clientSchema = clientSchema;\n this._cvrStore.putInstance(this._cvr);\n } else if (!deepEqual(this._cvr.clientSchema, clientSchema)) {\n // This should not be possible with a correct Zero client, as clients\n // of a CVR should all have the same schema (given that the schema hash\n // is part of the idb key). In fact, clients joining an existing group\n // (i.e. non-empty baseCookie) do not send the clientSchema message.\n lc.warn?.(\n `New schema ${JSON.stringify(\n clientSchema,\n )} does not match existing schema ${JSON.stringify(\n this._cvr.clientSchema,\n )}`,\n );\n throw new ProtocolError({\n kind: 'InvalidConnectionRequest',\n message: `Provided schema does not match previous schema`,\n origin: ErrorOrigin.ZeroCache,\n });\n }\n });\n }\n\n setProfileID(lc: LogContext, profileID: string) {\n if (this._cvr.profileID !== profileID) {\n if (\n this._cvr.profileID !== null &&\n !this._cvr.profileID.startsWith('cg')\n ) {\n // We expect profile ID's to change from null or from the back-filled\n // \"cg...\" value. Log a warning otherwise to surface unexpected or\n // pathological conditions.\n lc.warn?.(\n `changing profile ID from ${this._cvr.profileID} to ${profileID}`,\n );\n }\n this._cvr.profileID = profileID;\n this._cvrStore.putInstance(this._cvr);\n }\n }\n\n putDesiredQueries(\n clientID: string,\n queries: Readonly<{\n hash: string;\n ast?: AST | undefined;\n name?: string | undefined;\n args?: readonly ReadonlyJSONValue[] | undefined;\n ttl?: number | undefined;\n }>[],\n ): PatchToVersion[] {\n return startSpan(tracer, 'CVRConfigDrivenUpdater.putDesiredQueries', () => {\n const patches: PatchToVersion[] = [];\n const client = this.ensureClient(clientID);\n const current = new Set(client.desiredQueryIDs);\n\n // Find the new/changed desired queries.\n const needed: Set<string> = new Set();\n\n const recordQueryForTelemetry = (q: (typeof queries)[0]) => {\n const {ast, name, args} = q;\n if (ast) {\n recordQuery('crud');\n } else if (name && args) {\n recordQuery('custom');\n }\n };\n\n for (const q of queries) {\n const {hash, ttl = DEFAULT_TTL_MS} = q;\n const query = this._cvr.queries[hash];\n if (!query) {\n // New query - record for telemetry\n recordQueryForTelemetry(q);\n needed.add(hash);\n continue;\n }\n if (query.type === 'internal') {\n continue;\n }\n\n const oldClientState = query.clientState[clientID];\n // Old query was inactivated or never desired by this client.\n if (!oldClientState || oldClientState.inactivatedAt !== undefined) {\n // Reactivated query - record for telemetry\n recordQueryForTelemetry(q);\n needed.add(hash);\n continue;\n }\n\n if (compareTTL(ttl, oldClientState.ttl) > 0) {\n // TTL update only - don't record for telemetry\n needed.add(hash);\n }\n }\n\n if (needed.size === 0) {\n return patches;\n }\n const newVersion = this._ensureNewVersion();\n client.desiredQueryIDs = toSorted(union(current, needed), stringCompare);\n\n for (const id of needed) {\n const q = must(queries.find(({hash}) => hash === id));\n const {ast, name, args} = q;\n\n const ttl = clampTTL(q.ttl ?? DEFAULT_TTL_MS);\n const query =\n this._cvr.queries[id] ?? newQueryRecord(id, ast, name, args);\n assertNotInternal(query);\n\n const inactivatedAt = undefined;\n\n query.clientState[clientID] = {\n inactivatedAt,\n ttl,\n version: newVersion,\n };\n this._cvr.queries[id] = query;\n patches.push({\n toVersion: newVersion,\n patch: {type: 'query', op: 'put', id, clientID},\n });\n\n this._cvrStore.putQuery(query);\n this._cvrStore.putDesiredQuery(\n newVersion,\n query,\n client,\n false,\n inactivatedAt,\n ttl,\n );\n }\n return patches;\n });\n }\n\n markDesiredQueriesAsInactive(\n clientID: string,\n queryHashes: string[],\n ttlClock: TTLClock,\n ): PatchToVersion[] {\n return this.#deleteQueries(clientID, queryHashes, ttlClock);\n }\n\n deleteDesiredQueries(\n clientID: string,\n queryHashes: string[],\n ): PatchToVersion[] {\n return this.#deleteQueries(clientID, queryHashes, undefined);\n }\n\n #deleteQueries(\n clientID: string,\n queryHashes: string[],\n inactivatedAt: TTLClock | undefined,\n ): PatchToVersion[] {\n return startSpan(tracer, 'CVRConfigDrivenUpdater.#deleteQueries', () => {\n const patches: PatchToVersion[] = [];\n const client = this.ensureClient(clientID);\n const current = new Set(client.desiredQueryIDs);\n const unwanted = new Set(queryHashes);\n const remove = intersection(unwanted, current);\n if (remove.size === 0) {\n return patches;\n }\n\n const newVersion = this._ensureNewVersion();\n client.desiredQueryIDs = toSorted(\n difference(current, remove),\n stringCompare,\n );\n\n for (const id of remove) {\n const query = this._cvr.queries[id];\n if (!query) {\n continue; // Query itself has already been removed. Should not happen?\n }\n assertNotInternal(query);\n\n let ttl = DEFAULT_TTL_MS;\n if (inactivatedAt === undefined) {\n delete query.clientState[clientID];\n } else {\n // client state can be missing if the query never transformed so we never\n // recorded it.\n const clientState = query.clientState[clientID];\n if (clientState !== undefined) {\n assert(\n clientState.inactivatedAt === undefined,\n `Query ${id} is already inactivated`,\n );\n // Clamp TTL to ensure we don't propagate historical unclamped values.\n ttl = clampTTL(clientState.ttl);\n query.clientState[clientID] = {\n inactivatedAt,\n ttl,\n version: newVersion,\n };\n }\n }\n\n this._cvrStore.putQuery(query);\n this._cvrStore.putDesiredQuery(\n newVersion,\n query,\n client,\n true,\n inactivatedAt,\n ttl,\n );\n patches.push({\n toVersion: newVersion,\n patch: {type: 'query', op: 'del', id, clientID},\n });\n }\n return patches;\n });\n }\n\n clearDesiredQueries(clientID: string): PatchToVersion[] {\n const client = this.ensureClient(clientID);\n return this.#deleteQueries(clientID, client.desiredQueryIDs, undefined);\n }\n\n deleteClient(clientID: string, ttlClock: TTLClock): PatchToVersion[] {\n return startSpan(tracer, 'CVRConfigDrivenUpdater.deleteClient', () => {\n // clientID might not be part of this client group but if it is, this delete\n // may generate changes to the desired queries.\n\n const client = this._cvr.clients[clientID];\n if (!client) {\n // Clients in different client groups are no longer deleted, leaving\n // cleanup to inactive CVR purging logic.\n return [];\n }\n\n // When a client is deleted we mark all of its desired queries as inactive.\n // They will then be removed when the queries expire.\n const patches = this.markDesiredQueriesAsInactive(\n clientID,\n client.desiredQueryIDs,\n ttlClock,\n );\n delete this._cvr.clients[clientID];\n this._cvrStore.deleteClient(clientID);\n\n return patches;\n });\n }\n}\n\ntype Hash = string;\nexport type Column = string;\nexport type RefCounts = Record<Hash, number>;\n\ntype RowPatchInfo = {\n rowVersion: string | null; // null for a row-del\n toVersion: CVRVersion; // patchVersion\n};\n\n/**\n * Callback used by {@link CVRQueryDrivenUpdater.flush} to retrieve the\n * current row-set signature maintained by the pipeline driver for a given\n * query. Returning `undefined` means \"no pipeline for this query right now\" —\n * the stored signature on disk is left alone.\n */\nexport type RowSetSignatureProvider = (queryID: string) => bigint | undefined;\n\n/**\n * A {@link CVRQueryDrivenUpdater} is used for updating a CVR after making queries.\n * The caller should invoke:\n *\n * * {@link trackQueries} for queries that are being executed or removed.\n * * {@link received} for all rows received from the executed queries\n * * {@link deleteUnreferencedRows} to remove any rows that have\n * fallen out of the query result view.\n * * {@link flush}\n *\n * After flushing, the caller should perform any necessary catchup of\n * config and row patches for clients that are behind. See\n * {@link CVRStore.catchupConfigPatches} and {@link CVRStore.catchupRowPatches}.\n */\nexport class CVRQueryDrivenUpdater extends CVRUpdater {\n readonly #removedOrExecutedQueryIDs = new Set<string>();\n readonly #receivedRows = new CustomKeyMap<RowID, RefCounts | null>(\n rowIDString,\n );\n readonly #lastPatches = new CustomKeyMap<RowID, RowPatchInfo>(rowIDString);\n readonly #rowSetSignature: RowSetSignatureProvider | undefined;\n\n #existingRows: Promise<Iterable<RowRecord>> | undefined = undefined;\n\n /**\n * @param stateVersion The `stateVersion` at which the queries were executed.\n * @param rowSetSignature Optional callback that returns the current row-set\n * signature for a query, typically backed by\n * `PipelineDriver.rowSetSignature`. When provided, {@link flush}\n * persists any signature deltas it observes.\n */\n constructor(\n cvrStore: CVRStore,\n cvr: CVRSnapshot,\n stateVersion: LexiVersion,\n replicaVersion: string,\n rowSetSignature?: RowSetSignatureProvider,\n ) {\n super(cvrStore, cvr, replicaVersion);\n this.#rowSetSignature = rowSetSignature;\n\n assert(\n // We should either be setting the cvr.replicaVersion for the first time, or it should\n // be something newer than the current cvr.replicaVersion. Otherwise, the CVR should\n // have been rejected by the ViewSyncer.\n (cvr.replicaVersion ?? replicaVersion) <= replicaVersion,\n `Cannot sync from an older replicaVersion: CVR=${cvr.replicaVersion}, DB=${replicaVersion}`,\n );\n assert(\n stateVersion >= cvr.version.stateVersion,\n () =>\n `stateVersion (${stateVersion}) must be >= cvr.version.stateVersion (${cvr.version.stateVersion})`,\n );\n if (stateVersion > cvr.version.stateVersion) {\n this._setVersion({stateVersion});\n }\n }\n\n /**\n * Initiates the tracking of the specified `executed` and `removed` queries.\n * This kicks of a lookup of existing {@link RowRecord}s currently associated\n * with those queries, which will be used to reconcile the rows to keep\n * after all rows have been {@link received()}.\n *\n * \"transformed\" queries are queries that are currently\n * gotten and running in the pipeline driver but\n * received a new transformation hash due to an auth token\n * update.\n *\n * @returns The new CVRVersion to be used when all changes are committed.\n */\n trackQueries(\n lc: LogContext,\n executed: {id: string; transformationHash: string}[],\n removed: {id: string}[],\n ): {newVersion: CVRVersion; queryPatches: PatchToVersion[]} {\n return startSpan(tracer, 'CVRQueryDrivenUpdater.trackQueries', () => {\n assert(this.#existingRows === undefined, `trackQueries already called`);\n\n const queryPatches: Patch[] = [\n executed.map(q => this.#trackExecuted(q.id, q.transformationHash)),\n removed.map(q => this.#trackRemoved(q.id)),\n ].flat(2);\n\n this.#existingRows = this.#lookupRowsForExecutedAndRemovedQueries(lc);\n // Immediately attach a rejection handler to avoid unhandled rejections.\n // The error will surface when this.#existingRows is awaited.\n void this.#existingRows.then(() => {});\n\n const versionBumped =\n cmpVersions(this._orig.version, this._cvr.version) < 0;\n lc.info?.(\n `trackQueries: ${executed.length} executed, ${removed.length} removed, ` +\n `version ${versionBumped ? 'bumped' : 'unchanged'}`,\n );\n\n return {\n newVersion: this._cvr.version,\n queryPatches: queryPatches.map(patch => ({\n patch,\n toVersion: this._cvr.version,\n })),\n };\n });\n }\n\n #lookupRowsForExecutedAndRemovedQueries(\n lc: LogContext,\n ): Promise<Iterable<RowRecord>> {\n return startAsyncSpan(\n tracer,\n 'CVRQueryDrivenUpdater.#lookupRowsForExecutedAndRemovedQueries',\n async () => {\n const results = new CustomKeyMap<RowID, RowRecord>(rowIDString);\n\n if (this.#removedOrExecutedQueryIDs.size === 0) {\n // Query-less update. This can happen for config only changes.\n return [];\n }\n\n // Utilizes the in-memory RowCache.\n const allRowRecords = (await this._cvrStore.getRowRecords()).values();\n let total = 0;\n for (const existing of allRowRecords) {\n total++;\n assert(\n existing.refCounts !== null,\n 'allRowRecords should not include null refCounts',\n );\n for (const id of Object.keys(existing.refCounts)) {\n if (this.#removedOrExecutedQueryIDs.has(id)) {\n results.set(existing.id, existing);\n break;\n }\n }\n }\n\n lc.debug?.(\n `found ${\n results.size\n } (of ${total}) rows for executed / removed queries ${[\n ...this.#removedOrExecutedQueryIDs,\n ]}`,\n );\n return results.values();\n },\n );\n }\n\n /**\n * Tracks an executed query, ensures that it is marked as \"gotten\",\n * updating the CVR and creating put patches if necessary.\n *\n * This must be called for all executed queries.\n */\n #trackExecuted(queryID: string, transformationHash: string): Patch[] {\n return startSpan(tracer, 'CVRQueryDrivenUpdater.#trackExecuted', () => {\n assert(\n !this.#removedOrExecutedQueryIDs.has(queryID),\n () => `Query ${queryID} already tracked as executed or removed`,\n );\n this.#removedOrExecutedQueryIDs.add(queryID);\n\n let gotQueryPatch: Patch | undefined;\n const query = this._cvr.queries[queryID];\n if (query.transformationHash !== transformationHash) {\n const transformationVersion = this._ensureNewVersion();\n\n if (query.type !== 'internal' && query.patchVersion === undefined) {\n // client query: desired -> gotten\n query.patchVersion = transformationVersion;\n gotQueryPatch = {\n type: 'query',\n op: 'put',\n id: query.id,\n };\n }\n\n query.transformationHash = transformationHash;\n query.transformationVersion = transformationVersion;\n this._cvrStore.updateQuery(query);\n }\n return gotQueryPatch ? [gotQueryPatch] : [];\n });\n }\n\n /**\n * Tracks a query removed from the \"gotten\" set. In addition to producing the\n * appropriate patches for deleting the query, the removed query is taken into\n * account when computing the final row records in\n * {@link deleteUnreferencedRows}.\n * Namely, any rows with columns that are no longer referenced by a\n * query are deleted.\n *\n * This must only be called on queries that are not \"desired\" by any client.\n */\n #trackRemoved(queryID: string): Patch[] {\n return startSpan(tracer, 'CVRQueryDrivenUpdater.#trackRemoved', () => {\n const query = this._cvr.queries[queryID];\n assertNotInternal(query);\n\n assert(\n !this.#removedOrExecutedQueryIDs.has(queryID),\n () => `Query ${queryID} already tracked as executed or removed`,\n );\n this.#removedOrExecutedQueryIDs.add(queryID);\n delete this._cvr.queries[queryID];\n\n const newVersion = this._ensureNewVersion();\n const queryPatch = {type: 'query', op: 'del', id: queryID} as const;\n this._cvrStore.markQueryAsDeleted(newVersion, queryPatch);\n return [queryPatch];\n });\n }\n\n /**\n * Asserts that a new version has already been set.\n *\n * After {@link #executed} and {@link #removed} are called, we must have properly\n * decided on the final CVR version because the poke-start message declares the\n * final cookie (i.e. version), and that must be sent before any poke parts\n * generated from {@link received} are sent.\n */\n #assertNewVersion(\n rowID: RowID,\n existingVersion: string | undefined,\n newVersion: string | undefined,\n refCounts: RefCounts,\n ): CVRVersion {\n assert(\n cmpVersions(this._orig.version, this._cvr.version) < 0,\n () =>\n `Expected CVR version to have been bumped above original` +\n ` (orig=${versionString(this._orig.version)},` +\n ` curr=${versionString(this._cvr.version)}).` +\n ` Row ${JSON.stringify(rowID)}:` +\n ` existing=${existingVersion},` +\n ` new=${newVersion},` +\n ` queries=[${Object.keys(refCounts).join(',')}]`,\n );\n return this._cvr.version;\n }\n\n updatedVersion(): CVRVersion {\n return this._cvr.version;\n }\n\n /**\n * Public alias for {@link _ensureNewVersion}. Forces a `configVersion` bump\n * when the caller needs a new CVR version for reasons outside the built-in\n * tracking (e.g. rowSetSignature drift re-execution).\n */\n ensureNewVersion(): CVRVersion {\n return this._ensureNewVersion();\n }\n\n override flush(\n lc: LogContext,\n lastConnectTime: number,\n lastActive: number,\n ttlClock: TTLClock,\n ): Promise<{cvr: CVRSnapshot; flushed: CVRFlushStats | false}> {\n if (this.#rowSetSignature) {\n // Persist the per-query row-set signature for any query whose\n // pipeline-driver signature differs from what's on disk. Queries\n // without an active pipeline (provider returns undefined) keep their\n // stored value.\n for (const [queryID, query] of Object.entries(this._cvr.queries)) {\n const sig = this.#rowSetSignature(queryID);\n if (sig === undefined) {\n continue;\n }\n const stored = parseSignature(query.rowSetSignature);\n if (stored === sig) {\n continue;\n }\n const hex = formatSignature(sig);\n query.rowSetSignature = hex;\n this._cvrStore.updateRowSetSignature(queryID, hex);\n }\n }\n return super.flush(lc, lastConnectTime, lastActive, ttlClock);\n }\n\n /**\n * Tracks rows received from executing queries. This will update row records\n * and row patches if the received rows have a new version. The method also\n * returns (put) patches to be returned to update their state, versioned by\n * patchVersion so that only the patches new to the clients are sent.\n */\n received(\n _lc: LogContext,\n rows: Map<RowID, RowUpdate>,\n ): Promise<PatchToVersion[]> {\n return startAsyncSpan(\n tracer,\n 'CVRQueryDrivenUpdater.received',\n async () => {\n const patches: PatchToVersion[] = [];\n const existingRows = await this._cvrStore.getRowRecords();\n\n for (const [id, update] of rows.entries()) {\n const {contents, version, refCounts} = update;\n\n let existing = existingRows.get(id);\n // Accumulate all received refCounts to determine which rows to prune.\n const previouslyReceived = this.#receivedRows.get(id);\n\n const merged =\n previouslyReceived !== undefined\n ? mergeRefCounts(previouslyReceived, refCounts)\n : mergeRefCounts(\n existing?.refCounts,\n refCounts,\n this.#removedOrExecutedQueryIDs,\n );\n\n this.#receivedRows.set(id, merged);\n\n const newRowVersion = merged === null ? undefined : version;\n const patchVersion =\n existing && existing.rowVersion === newRowVersion\n ? existing.patchVersion // existing row is unchanged\n : this.#assertNewVersion(\n id,\n existing?.rowVersion,\n newRowVersion,\n refCounts,\n );\n\n // Note: for determining what to commit to the CVR store, use the\n // `version` of the update even if `merged` is null (i.e. don't\n // use `newRowVersion`). This will be deduped by the cvr-store flush\n // if it is redundant. In rare cases--namely, if the row key has\n // changed--we _do_ want to add row-put for the new row key with\n // `refCounts: null` in order to correctly record a delete patch\n // for that row, as the row with the old key will be removed.\n const rowVersion = version ?? existing?.rowVersion;\n if (rowVersion) {\n this._cvrStore.putRowRecord({\n id,\n rowVersion,\n patchVersion,\n refCounts: merged,\n });\n } else {\n // This means that a row that was not in the CVR was added during\n // this update, and then subsequently removed. Since there's no\n // corresponding row in the CVR itself, cancel the previous put.\n // Note that we still send a 'del' patch to the client in order to\n // cancel the previous 'put' patch.\n this._cvrStore.delRowRecord(id);\n }\n\n // Dedupe against the lastPatch sent for the row, and ensure that\n // toVersion never backtracks (lest it be undesirably filtered).\n const lastPatch = this.#lastPatches.get(id);\n const toVersion = maxVersion(patchVersion, lastPatch?.toVersion);\n\n if (merged === null) {\n // All refCounts have gone to zero, if row was previously synced\n // delete it.\n if (existing || previouslyReceived) {\n // dedupe\n if (lastPatch?.rowVersion !== null) {\n patches.push({\n patch: {\n type: 'row',\n op: 'del',\n id,\n },\n toVersion,\n });\n this.#lastPatches.set(id, {rowVersion: null, toVersion});\n }\n }\n } else if (contents) {\n assert(\n rowVersion,\n 'rowVersion is required when contents is present',\n );\n // dedupe\n if (!lastPatch?.rowVersion || lastPatch.rowVersion < rowVersion) {\n patches.push({\n patch: {\n type: 'row',\n op: 'put',\n id,\n contents,\n },\n toVersion,\n });\n this.#lastPatches.set(id, {rowVersion, toVersion});\n }\n }\n }\n return patches;\n },\n );\n }\n\n /**\n * Computes and updates the row records based on:\n * * The {@link #executed} queries\n * * The {@link #removed} queries\n * * The {@link received} rows\n *\n * Returns the final delete and patch ops that must be sent to the client\n * to delete rows that are no longer referenced by any query.\n *\n * This is Step [5] of the\n * [CVR Sync Algorithm](https://www.notion.so/replicache/Sync-and-Client-View-Records-CVR-a18e02ec3ec543449ea22070855ff33d?pvs=4#7874f9b80a514be2b8cd5cf538b88d37).\n */\n deleteUnreferencedRows(lc?: LogContext): Promise<PatchToVersion[]> {\n return startAsyncSpan(\n tracer,\n 'CVRQueryDrivenUpdater.deleteUnreferencedRows',\n async () => {\n if (this.#removedOrExecutedQueryIDs.size === 0) {\n // Query-less update. This can happen for config-only changes.\n assert(\n this.#receivedRows.size === 0,\n () =>\n `Expected no received rows for query-less update, got ${this.#receivedRows.size}`,\n );\n return [];\n }\n\n // patches to send to the client.\n const patches: PatchToVersion[] = [];\n\n const start = Date.now();\n assert(this.#existingRows, `trackQueries() was not called`);\n for (const existing of await this.#existingRows) {\n const deletedID = this.#deleteUnreferencedRow(existing);\n if (deletedID === null) {\n continue;\n }\n const lastPatch = this.#lastPatches.get(deletedID);\n if (lastPatch !== undefined && lastPatch.rowVersion === null) {\n continue;\n }\n const toVersion = maxVersion(this._cvr.version, lastPatch?.toVersion);\n patches.push({\n toVersion,\n patch: {type: 'row', op: 'del', id: deletedID},\n });\n this.#lastPatches.set(deletedID, {rowVersion: null, toVersion});\n }\n lc?.debug?.(\n `computed ${patches.length} delete patches (${Date.now() - start} ms)`,\n );\n\n return patches;\n },\n );\n }\n\n #deleteUnreferencedRow(existing: RowRecord): RowID | null {\n return startSpan(\n tracer,\n 'CVRQueryDrivenUpdater.#deleteUnreferencedRow',\n () => {\n if (this.#receivedRows.get(existing.id)) {\n return null;\n }\n\n const newRefCounts = mergeRefCounts(\n existing.refCounts,\n undefined,\n this.#removedOrExecutedQueryIDs,\n );\n\n // If a row is still referenced, we update the refCounts but not the\n // patchVersion (as the existence and contents of the row have not\n // changed from the clients' perspective). If the row is deleted, it\n // gets a new patchVersion (and corresponding poke).\n const patchVersion = newRefCounts\n ? existing.patchVersion\n : this.#assertNewVersion(\n existing.id,\n existing.rowVersion,\n undefined,\n existing.refCounts ?? {},\n );\n const rowRecord: RowRecord = {\n ...existing,\n patchVersion,\n refCounts: newRefCounts,\n };\n\n this._cvrStore.putRowRecord(rowRecord);\n\n // Return the id to delete if no longer referenced.\n return newRefCounts ? null : existing.id;\n },\n );\n }\n}\n\nfunction mergeRefCounts(\n existing: RefCounts | null | undefined,\n received: RefCounts | null | undefined,\n removeHashes?: Set<string>,\n): RefCounts | null {\n let merged: RefCounts = {};\n if (!existing) {\n merged = received ?? {};\n } else {\n [existing, received].forEach((refCounts, i) => {\n if (!refCounts) {\n return;\n }\n for (const [hash, count] of Object.entries(refCounts)) {\n if (i === 0 /* existing */ && removeHashes?.has(hash)) {\n continue; // removeHashes from existing row.\n }\n merged[hash] = (merged[hash] ?? 0) + count;\n if (merged[hash] === 0) {\n delete merged[hash];\n }\n }\n\n return merged;\n });\n }\n\n return Object.values(merged).some(v => v > 0) ? merged : null;\n}\n\n/**\n * The query must be inactive for all clients to be considered inactive.\n * This is because expiration is defined that way: a query is expired for a client group\n * only if it is expired for all clients in the group.\n *\n * If all clients have inactivated the query, we return\n * the one with the expiration furthest in the future.\n */\nexport function getInactiveQueries(cvr: CVR): {\n hash: string;\n inactivatedAt: TTLClock;\n ttl: number;\n}[] {\n // We no longer support a TTL larger than 10 minutes.\n const inactive: Map<\n string,\n {\n hash: string;\n inactivatedAt: TTLClock;\n ttl: number;\n }\n > = new Map();\n for (const [queryID, query] of Object.entries(cvr.queries)) {\n if (query.type === 'internal') {\n continue;\n }\n for (const clientState of Object.values(query.clientState)) {\n // 1. Take the longest TTL\n // 2. If the query is not inactivated (for any client), do not return it\n const {inactivatedAt, ttl} = clientState;\n const existing = inactive.get(queryID);\n if (inactivatedAt === undefined) {\n if (existing) {\n inactive.delete(queryID);\n }\n break;\n }\n\n const clampedTTL = clampTTL(ttl);\n if (existing) {\n // The stored one might be too large because from a previous version of\n // zero\n const existingTTL = clampTTL(existing.ttl);\n // Use the last eviction time.\n if (\n existingTTL + ttlClockAsNumber(existing.inactivatedAt) <\n ttlClockAsNumber(inactivatedAt) + clampedTTL\n ) {\n existing.ttl = clampedTTL;\n existing.inactivatedAt = inactivatedAt;\n }\n } else {\n inactive.set(queryID, {\n hash: queryID,\n inactivatedAt,\n ttl: clampedTTL,\n });\n }\n }\n }\n\n // First sort all the queries that have TTL. Oldest first.\n return toSorted(inactive.values(), (a, b) => {\n if (a.ttl === b.ttl) {\n return (\n ttlClockAsNumber(a.inactivatedAt) - ttlClockAsNumber(b.inactivatedAt)\n );\n }\n return (\n ttlClockAsNumber(a.inactivatedAt) +\n a.ttl -\n ttlClockAsNumber(b.inactivatedAt) -\n b.ttl\n );\n });\n}\n\nexport function nextEvictionTime(cvr: CVR): TTLClock | undefined {\n let next: number | undefined;\n for (const {inactivatedAt, ttl} of getInactiveQueries(cvr)) {\n const expire = ttlClockAsNumber(inactivatedAt) + ttl;\n if (next === undefined || expire < next) {\n next = expire;\n }\n }\n return next as TTLClock | undefined;\n}\n\nfunction newQueryRecord(\n id: string,\n ast: AST | undefined,\n name: string | undefined,\n args: readonly ReadonlyJSONValue[] | undefined,\n): ClientQueryRecord | CustomQueryRecord {\n if (ast !== undefined) {\n assert(\n name === undefined && args === undefined,\n 'Cannot provide name or args with ast',\n );\n return {\n id,\n type: 'client',\n ast,\n clientState: {},\n } satisfies ClientQueryRecord;\n }\n\n assert(\n name !== undefined && args !== undefined,\n 'Must provide name and args',\n );\n return {\n id,\n type: 'custom',\n name,\n args,\n clientState: {},\n } satisfies CustomQueryRecord;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;AAmFA,IAAM,uBAAuB;AAC7B,IAAM,mCAAmC;AAEzC,SAAS,kBACP,OACoC;CACpC,IAAI,MAAM,SAAS,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B,sCACF;EACA,OAAO;GACL;GACA,MAAM;GACN;GACA,aAAa,CAAC;EAChB;CACF;CAEA,OACE,SAAS,KAAA,KAAa,SAAS,KAAA,GAC/B,4BACF;CACA,OAAO;EACL;EACA,MAAM;EACN;EACA;EACA,aAAa,CAAC;CAChB;AACF"}
1
+ {"version":3,"file":"cvr.js","names":["#shard","#deleteQueries","#removedOrExecutedQueryIDs","#executedQueryIDs","#receivedRows","#lastPatches","#rowSetSignature","#existingRows","#trackExecuted","#trackRemoved","#lookupRowsForExecutedAndRemovedQueries","#assertNewVersion","#deleteUnreferencedRow"],"sources":["../../../../../../zero-cache/src/services/view-syncer/cvr.ts"],"sourcesContent":["import type {LogContext} from '@rocicorp/logger';\nimport {startAsyncSpan, startSpan} from '../../../../otel/src/span.ts';\nimport {assert} from '../../../../shared/src/asserts.ts';\nimport {type JSONObject} from '../../../../shared/src/bigint-json.ts';\nimport {CustomKeyMap} from '../../../../shared/src/custom-key-map.ts';\nimport {toSorted} from '../../../../shared/src/iterables.ts';\nimport {\n deepEqual,\n type ReadonlyJSONValue,\n} from '../../../../shared/src/json.ts';\nimport {must} from '../../../../shared/src/must.ts';\nimport {\n difference,\n intersection,\n union,\n} from '../../../../shared/src/set-utils.ts';\nimport {stringCompare} from '../../../../shared/src/string-compare.ts';\nimport type {AST} from '../../../../zero-protocol/src/ast.ts';\nimport type {ClientSchema} from '../../../../zero-protocol/src/client-schema.ts';\nimport {ErrorOrigin} from '../../../../zero-protocol/src/error-origin.ts';\nimport {ProtocolError} from '../../../../zero-protocol/src/error.ts';\nimport {\n clampTTL,\n compareTTL,\n DEFAULT_TTL_MS,\n} from '../../../../zql/src/query/ttl.ts';\nimport {recordQuery} from '../../server/anonymous-otel-start.ts';\nimport type {LexiVersion} from '../../types/lexi-version.ts';\nimport {rowIDString} from '../../types/row-key.ts';\nimport {upstreamSchema, type ShardID} from '../../types/shards.ts';\nimport type {Patch, PatchToVersion} from './client-handler.ts';\nimport {type CVRFlushStats, type CVRStore} from './cvr-store.ts';\nimport {formatSignature, parseSignature} from './row-set-signature.ts';\nimport {\n cmpVersions,\n maxVersion,\n oneAfter,\n versionString,\n type ClientQueryRecord,\n type ClientRecord,\n type CustomQueryRecord,\n type CVRVersion,\n type InternalQueryRecord,\n type QueryRecord,\n type RowID,\n type RowRecord,\n} from './schema/types.ts';\nimport {tracer} from './tracer.ts';\nimport {ttlClockAsNumber, type TTLClock} from './ttl-clock.ts';\n\nexport type RowUpdate = {\n version?: string; // Undefined for an unref.\n contents?: JSONObject; // Undefined for an unref.\n refCounts: {[hash: string]: number}; // Counts are negative when a row is unrefed.\n};\n\n/** Internally used mutable CVR type. */\nexport type CVR = {\n id: string;\n version: CVRVersion;\n lastActive: number;\n ttlClock: TTLClock;\n replicaVersion: string | null;\n clients: Record<string, ClientRecord>;\n queries: Record<string, QueryRecord>;\n clientSchema: ClientSchema | null;\n profileID: string | null;\n};\n\n/** Exported immutable CVR type. */\n// TODO: Use Immutable<CVR> when the AST is immutable.\nexport type CVRSnapshot = {\n readonly id: string;\n readonly version: CVRVersion;\n readonly lastActive: number;\n readonly ttlClock: TTLClock;\n readonly replicaVersion: string | null;\n readonly clients: Readonly<Record<string, ClientRecord>>;\n readonly queries: Readonly<Record<string, QueryRecord>>;\n readonly clientSchema: ClientSchema | null;\n readonly profileID: string | null;\n};\n\nconst CLIENT_LMID_QUERY_ID = 'lmids';\nconst CLIENT_MUTATION_RESULTS_QUERY_ID = 'mutationResults';\n\nfunction assertNotInternal(\n query: QueryRecord,\n): asserts query is ClientQueryRecord {\n if (query.type === 'internal') {\n // This should never happen for behaving clients, as query ids should be hashes.\n throw new Error(`Query ID ${query.id} is reserved for internal use`);\n }\n}\n\nexport function getMutationResultsQuery(\n upstreamSchema: string,\n clientGroupID: string,\n): InternalQueryRecord {\n return {\n id: CLIENT_MUTATION_RESULTS_QUERY_ID,\n type: 'internal',\n ast: {\n schema: '',\n table: `${upstreamSchema}.mutations`,\n where: {\n type: 'and',\n conditions: [\n {\n type: 'simple',\n left: {\n type: 'column',\n name: 'clientGroupID',\n },\n op: '=',\n right: {\n type: 'literal',\n value: clientGroupID,\n },\n },\n ],\n },\n orderBy: [\n ['clientGroupID', 'asc'],\n ['clientID', 'asc'],\n ['mutationID', 'asc'],\n ],\n },\n };\n}\n\n/**\n * The base CVRUpdater contains logic common to the {@link CVRConfigDrivenUpdater} and\n * {@link CVRQueryDrivenUpdater}. The CVRUpdater class itself is exported for updating\n * the `lastActive` time of the CVR in the absence of any changes to the CVR contents.\n * Although activity is automatically tracked when the CVR contents change, there may be\n * edge cases in which a client actively connects to a CVR that doesn't itself change.\n * Calling `new CVRUpdater(...).flush()` will explicitly update the active index and\n * prevent the CVR from being garbage collected.\n */\nexport class CVRUpdater {\n protected readonly _orig: CVRSnapshot;\n protected readonly _cvr: CVR;\n\n protected readonly _cvrStore: CVRStore;\n\n /**\n * @param cvrStore The CVRStore to use for storage\n * @param cvr The current CVR\n */\n constructor(\n cvrStore: CVRStore,\n cvr: CVRSnapshot,\n replicaVersion: string | null,\n ) {\n this._cvrStore = cvrStore;\n this._orig = cvr;\n this._cvr = structuredClone(cvr) as CVR; // mutable deep copy\n this._cvr.replicaVersion = replicaVersion;\n }\n\n protected _setVersion(version: CVRVersion) {\n assert(\n cmpVersions(this._cvr.version, version) < 0,\n 'Expected new version to be greater than current version',\n );\n this._cvr.version = version;\n return version;\n }\n\n /**\n * Ensures that the new CVR has a higher version than the original.\n * This method is idempotent in that it will always return the same\n * (possibly bumped) version.\n */\n protected _ensureNewVersion(): CVRVersion {\n if (cmpVersions(this._orig.version, this._cvr.version) === 0) {\n this._setVersion(oneAfter(this._cvr.version));\n }\n return this._cvr.version;\n }\n\n async flush(\n lc: LogContext,\n lastConnectTime: number,\n lastActive: number,\n ttlClock: TTLClock,\n ): Promise<{\n cvr: CVRSnapshot;\n flushed: CVRFlushStats | false;\n }> {\n this._cvr.ttlClock = ttlClock;\n this._cvr.lastActive = lastActive;\n const flushed = await this._cvrStore.flush(\n lc,\n this._orig.version,\n this._cvr,\n lastConnectTime,\n );\n if (!flushed) {\n return {cvr: this._orig, flushed: false};\n }\n return {cvr: this._cvr, flushed};\n }\n}\n\n/**\n * A {@link CVRConfigDrivenUpdater} is used for updating a CVR with config-driven\n * changes. Note that this may result in row deletion (e.g. if queries get dropped),\n * but the `stateVersion` of the CVR does not change.\n */\nexport class CVRConfigDrivenUpdater extends CVRUpdater {\n readonly #shard: ShardID;\n\n constructor(cvrStore: CVRStore, cvr: CVRSnapshot, shard: ShardID) {\n super(cvrStore, cvr, cvr.replicaVersion);\n this.#shard = shard;\n }\n\n ensureClient(id: string): ClientRecord {\n return startSpan(tracer, 'CVRConfigDrivenUpdater.ensureClient', () => {\n let client = this._cvr.clients[id];\n if (client) {\n return client;\n }\n // Add the ClientRecord and PutPatch\n client = {id, desiredQueryIDs: []};\n this._cvr.clients[id] = client;\n\n this._ensureNewVersion();\n this._cvrStore.insertClient(client);\n\n if (!this._cvr.queries[CLIENT_LMID_QUERY_ID]) {\n const lmidsQuery: InternalQueryRecord = {\n id: CLIENT_LMID_QUERY_ID,\n ast: {\n schema: '',\n table: `${upstreamSchema(this.#shard)}.clients`,\n where: {\n type: 'simple',\n left: {\n type: 'column',\n name: 'clientGroupID',\n },\n op: '=',\n right: {\n type: 'literal',\n value: this._cvr.id,\n },\n },\n orderBy: [\n ['clientGroupID', 'asc'],\n ['clientID', 'asc'],\n ],\n },\n type: 'internal',\n };\n this._cvr.queries[CLIENT_LMID_QUERY_ID] = lmidsQuery;\n this._cvrStore.putQuery(lmidsQuery);\n }\n if (!this._cvr.queries[CLIENT_MUTATION_RESULTS_QUERY_ID]) {\n const mutationResultsQuery: InternalQueryRecord =\n getMutationResultsQuery(upstreamSchema(this.#shard), this._cvr.id);\n this._cvr.queries[CLIENT_MUTATION_RESULTS_QUERY_ID] =\n mutationResultsQuery;\n this._cvrStore.putQuery(mutationResultsQuery);\n }\n\n return client;\n });\n }\n\n setClientSchema(lc: LogContext, clientSchema: ClientSchema) {\n startSpan(tracer, 'CVRConfigDrivenUpdater.setClientSchema', () => {\n if (this._cvr.clientSchema === null) {\n this._cvr.clientSchema = clientSchema;\n this._cvrStore.putInstance(this._cvr);\n } else if (!deepEqual(this._cvr.clientSchema, clientSchema)) {\n // This should not be possible with a correct Zero client, as clients\n // of a CVR should all have the same schema (given that the schema hash\n // is part of the idb key). In fact, clients joining an existing group\n // (i.e. non-empty baseCookie) do not send the clientSchema message.\n lc.warn?.(\n `New schema ${JSON.stringify(\n clientSchema,\n )} does not match existing schema ${JSON.stringify(\n this._cvr.clientSchema,\n )}`,\n );\n throw new ProtocolError({\n kind: 'InvalidConnectionRequest',\n message: `Provided schema does not match previous schema`,\n origin: ErrorOrigin.ZeroCache,\n });\n }\n });\n }\n\n setProfileID(lc: LogContext, profileID: string) {\n if (this._cvr.profileID !== profileID) {\n if (\n this._cvr.profileID !== null &&\n !this._cvr.profileID.startsWith('cg')\n ) {\n // We expect profile ID's to change from null or from the back-filled\n // \"cg...\" value. Log a warning otherwise to surface unexpected or\n // pathological conditions.\n lc.warn?.(\n `changing profile ID from ${this._cvr.profileID} to ${profileID}`,\n );\n }\n this._cvr.profileID = profileID;\n this._cvrStore.putInstance(this._cvr);\n }\n }\n\n putDesiredQueries(\n clientID: string,\n queries: Readonly<{\n hash: string;\n ast?: AST | undefined;\n name?: string | undefined;\n args?: readonly ReadonlyJSONValue[] | undefined;\n ttl?: number | undefined;\n }>[],\n ): PatchToVersion[] {\n return startSpan(tracer, 'CVRConfigDrivenUpdater.putDesiredQueries', () => {\n const patches: PatchToVersion[] = [];\n const client = this.ensureClient(clientID);\n const current = new Set(client.desiredQueryIDs);\n\n // Find the new/changed desired queries.\n const needed: Set<string> = new Set();\n\n const recordQueryForTelemetry = (q: (typeof queries)[0]) => {\n const {ast, name, args} = q;\n if (ast) {\n recordQuery('crud');\n } else if (name && args) {\n recordQuery('custom');\n }\n };\n\n for (const q of queries) {\n const {hash, ttl = DEFAULT_TTL_MS} = q;\n const query = this._cvr.queries[hash];\n if (!query) {\n // New query - record for telemetry\n recordQueryForTelemetry(q);\n needed.add(hash);\n continue;\n }\n if (query.type === 'internal') {\n continue;\n }\n\n const oldClientState = query.clientState[clientID];\n // Old query was inactivated or never desired by this client.\n if (!oldClientState || oldClientState.inactivatedAt !== undefined) {\n // Reactivated query - record for telemetry\n recordQueryForTelemetry(q);\n needed.add(hash);\n continue;\n }\n\n if (compareTTL(ttl, oldClientState.ttl) > 0) {\n // TTL update only - don't record for telemetry\n needed.add(hash);\n }\n }\n\n if (needed.size === 0) {\n return patches;\n }\n const newVersion = this._ensureNewVersion();\n client.desiredQueryIDs = toSorted(union(current, needed), stringCompare);\n\n for (const id of needed) {\n const q = must(queries.find(({hash}) => hash === id));\n const {ast, name, args} = q;\n\n const ttl = clampTTL(q.ttl ?? DEFAULT_TTL_MS);\n const query =\n this._cvr.queries[id] ?? newQueryRecord(id, ast, name, args);\n assertNotInternal(query);\n\n const inactivatedAt = undefined;\n\n query.clientState[clientID] = {\n inactivatedAt,\n ttl,\n version: newVersion,\n };\n this._cvr.queries[id] = query;\n patches.push({\n toVersion: newVersion,\n patch: {type: 'query', op: 'put', id, clientID},\n });\n\n this._cvrStore.putQuery(query);\n this._cvrStore.putDesiredQuery(\n newVersion,\n query,\n client,\n false,\n inactivatedAt,\n ttl,\n );\n }\n return patches;\n });\n }\n\n markDesiredQueriesAsInactive(\n clientID: string,\n queryHashes: string[],\n ttlClock: TTLClock,\n ): PatchToVersion[] {\n return this.#deleteQueries(clientID, queryHashes, ttlClock);\n }\n\n deleteDesiredQueries(\n clientID: string,\n queryHashes: string[],\n ): PatchToVersion[] {\n return this.#deleteQueries(clientID, queryHashes, undefined);\n }\n\n #deleteQueries(\n clientID: string,\n queryHashes: string[],\n inactivatedAt: TTLClock | undefined,\n ): PatchToVersion[] {\n return startSpan(tracer, 'CVRConfigDrivenUpdater.#deleteQueries', () => {\n const patches: PatchToVersion[] = [];\n const client = this.ensureClient(clientID);\n const current = new Set(client.desiredQueryIDs);\n const unwanted = new Set(queryHashes);\n const remove = intersection(unwanted, current);\n if (remove.size === 0) {\n return patches;\n }\n\n const newVersion = this._ensureNewVersion();\n client.desiredQueryIDs = toSorted(\n difference(current, remove),\n stringCompare,\n );\n\n for (const id of remove) {\n const query = this._cvr.queries[id];\n if (!query) {\n continue; // Query itself has already been removed. Should not happen?\n }\n assertNotInternal(query);\n\n let ttl = DEFAULT_TTL_MS;\n if (inactivatedAt === undefined) {\n delete query.clientState[clientID];\n } else {\n // client state can be missing if the query never transformed so we never\n // recorded it.\n const clientState = query.clientState[clientID];\n if (clientState !== undefined) {\n assert(\n clientState.inactivatedAt === undefined,\n `Query ${id} is already inactivated`,\n );\n // Clamp TTL to ensure we don't propagate historical unclamped values.\n ttl = clampTTL(clientState.ttl);\n query.clientState[clientID] = {\n inactivatedAt,\n ttl,\n version: newVersion,\n };\n }\n }\n\n this._cvrStore.putQuery(query);\n this._cvrStore.putDesiredQuery(\n newVersion,\n query,\n client,\n true,\n inactivatedAt,\n ttl,\n );\n patches.push({\n toVersion: newVersion,\n patch: {type: 'query', op: 'del', id, clientID},\n });\n }\n return patches;\n });\n }\n\n clearDesiredQueries(clientID: string): PatchToVersion[] {\n const client = this.ensureClient(clientID);\n return this.#deleteQueries(clientID, client.desiredQueryIDs, undefined);\n }\n\n deleteClient(clientID: string, ttlClock: TTLClock): PatchToVersion[] {\n return startSpan(tracer, 'CVRConfigDrivenUpdater.deleteClient', () => {\n // clientID might not be part of this client group but if it is, this delete\n // may generate changes to the desired queries.\n\n const client = this._cvr.clients[clientID];\n if (!client) {\n // Clients in different client groups are no longer deleted, leaving\n // cleanup to inactive CVR purging logic.\n return [];\n }\n\n // When a client is deleted we mark all of its desired queries as inactive.\n // They will then be removed when the queries expire.\n const patches = this.markDesiredQueriesAsInactive(\n clientID,\n client.desiredQueryIDs,\n ttlClock,\n );\n delete this._cvr.clients[clientID];\n this._cvrStore.deleteClient(clientID);\n\n return patches;\n });\n }\n}\n\ntype Hash = string;\nexport type Column = string;\nexport type RefCounts = Record<Hash, number>;\n\ntype RowPatchInfo = {\n rowVersion: string | null; // null for a row-del\n toVersion: CVRVersion; // patchVersion\n};\n\n/**\n * Callback used by {@link CVRQueryDrivenUpdater.flush} to retrieve the\n * current row-set signature maintained by the pipeline driver for a given\n * query. Returning `undefined` means \"no pipeline for this query right now\" —\n * the stored signature on disk is left alone.\n */\nexport type RowSetSignatureProvider = (queryID: string) => bigint | undefined;\n\n/**\n * A {@link CVRQueryDrivenUpdater} is used for updating a CVR after making queries.\n * The caller should invoke:\n *\n * * {@link trackQueries} for queries that are being executed or removed.\n * * {@link received} for all rows received from the executed queries\n * * {@link removeTrackedQueries} for optional queries that did not execute\n * * {@link deleteUnreferencedRows} to remove any rows that have\n * fallen out of the query result view.\n * * {@link flush}\n *\n * After flushing, the caller should perform any necessary catchup of\n * config and row patches for clients that are behind. See\n * {@link CVRStore.catchupConfigPatches} and {@link CVRStore.catchupRowPatches}.\n */\nexport class CVRQueryDrivenUpdater extends CVRUpdater {\n readonly #removedOrExecutedQueryIDs = new Set<string>();\n readonly #executedQueryIDs = new Set<string>();\n readonly #receivedRows = new CustomKeyMap<RowID, RefCounts | null>(\n rowIDString,\n );\n readonly #lastPatches = new CustomKeyMap<RowID, RowPatchInfo>(rowIDString);\n readonly #rowSetSignature: RowSetSignatureProvider | undefined;\n\n #existingRows: Promise<Iterable<RowRecord>> | undefined = undefined;\n\n /**\n * @param stateVersion The `stateVersion` at which the queries were executed.\n * @param rowSetSignature Optional callback that returns the current row-set\n * signature for a query, typically backed by\n * `PipelineDriver.rowSetSignature`. When provided, {@link flush}\n * persists any signature deltas it observes.\n */\n constructor(\n cvrStore: CVRStore,\n cvr: CVRSnapshot,\n stateVersion: LexiVersion,\n replicaVersion: string,\n rowSetSignature?: RowSetSignatureProvider,\n ) {\n super(cvrStore, cvr, replicaVersion);\n this.#rowSetSignature = rowSetSignature;\n\n assert(\n // We should either be setting the cvr.replicaVersion for the first time, or it should\n // be something newer than the current cvr.replicaVersion. Otherwise, the CVR should\n // have been rejected by the ViewSyncer.\n (cvr.replicaVersion ?? replicaVersion) <= replicaVersion,\n `Cannot sync from an older replicaVersion: CVR=${cvr.replicaVersion}, DB=${replicaVersion}`,\n );\n assert(\n stateVersion >= cvr.version.stateVersion,\n () =>\n `stateVersion (${stateVersion}) must be >= cvr.version.stateVersion (${cvr.version.stateVersion})`,\n );\n if (stateVersion > cvr.version.stateVersion) {\n this._setVersion({stateVersion});\n }\n }\n\n /**\n * Initiates the tracking of the specified `executed` and `removed` queries.\n * This kicks of a lookup of existing {@link RowRecord}s currently associated\n * with those queries, which will be used to reconcile the rows to keep\n * after all rows have been {@link received()}.\n *\n * \"transformed\" queries are queries that are currently\n * gotten and running in the pipeline driver but\n * received a new transformation hash due to an auth token\n * update.\n *\n * @returns The new CVRVersion to be used when all changes are committed.\n */\n trackQueries(\n lc: LogContext,\n executed: {id: string; transformationHash: string}[],\n removed: {id: string}[],\n ): {newVersion: CVRVersion; queryPatches: PatchToVersion[]} {\n return startSpan(tracer, 'CVRQueryDrivenUpdater.trackQueries', () => {\n assert(this.#existingRows === undefined, `trackQueries already called`);\n\n const queryPatches: Patch[] = [\n executed.map(q => this.#trackExecuted(q.id, q.transformationHash)),\n removed.map(q => this.#trackRemoved(q.id)),\n ].flat(2);\n\n this.#existingRows = this.#lookupRowsForExecutedAndRemovedQueries(lc);\n // Immediately attach a rejection handler to avoid unhandled rejections.\n // The error will surface when this.#existingRows is awaited.\n void this.#existingRows.then(() => {});\n\n const versionBumped =\n cmpVersions(this._orig.version, this._cvr.version) < 0;\n lc.info?.(\n `trackQueries: ${executed.length} executed, ${removed.length} removed, ` +\n `version ${versionBumped ? 'bumped' : 'unchanged'}`,\n );\n\n return {\n newVersion: this._cvr.version,\n queryPatches: queryPatches.map(patch => ({\n patch,\n toVersion: this._cvr.version,\n })),\n };\n });\n }\n\n #lookupRowsForExecutedAndRemovedQueries(\n lc: LogContext,\n ): Promise<Iterable<RowRecord>> {\n return startAsyncSpan(\n tracer,\n 'CVRQueryDrivenUpdater.#lookupRowsForExecutedAndRemovedQueries',\n async () => {\n const results = new CustomKeyMap<RowID, RowRecord>(rowIDString);\n\n if (this.#removedOrExecutedQueryIDs.size === 0) {\n // Query-less update. This can happen for config only changes.\n return [];\n }\n\n // Utilizes the in-memory RowCache.\n const allRowRecords = (await this._cvrStore.getRowRecords()).values();\n let total = 0;\n for (const existing of allRowRecords) {\n total++;\n assert(\n existing.refCounts !== null,\n 'allRowRecords should not include null refCounts',\n );\n for (const id of Object.keys(existing.refCounts)) {\n if (this.#removedOrExecutedQueryIDs.has(id)) {\n results.set(existing.id, existing);\n break;\n }\n }\n }\n\n lc.debug?.(\n `found ${\n results.size\n } (of ${total}) rows for executed / removed queries ${[\n ...this.#removedOrExecutedQueryIDs,\n ]}`,\n );\n return results.values();\n },\n );\n }\n\n /**\n * Tracks an executed query, ensures that it is marked as \"gotten\",\n * updating the CVR and creating put patches if necessary.\n *\n * This must be called for all executed queries.\n */\n #trackExecuted(queryID: string, transformationHash: string): Patch[] {\n return startSpan(tracer, 'CVRQueryDrivenUpdater.#trackExecuted', () => {\n assert(\n !this.#removedOrExecutedQueryIDs.has(queryID),\n () => `Query ${queryID} already tracked as executed or removed`,\n );\n this.#removedOrExecutedQueryIDs.add(queryID);\n this.#executedQueryIDs.add(queryID);\n\n let gotQueryPatch: Patch | undefined;\n const query = this._cvr.queries[queryID];\n if (query.transformationHash !== transformationHash) {\n const transformationVersion = this._ensureNewVersion();\n\n if (query.type !== 'internal' && query.patchVersion === undefined) {\n // client query: desired -> gotten\n query.patchVersion = transformationVersion;\n gotQueryPatch = {\n type: 'query',\n op: 'put',\n id: query.id,\n };\n }\n\n query.transformationHash = transformationHash;\n query.transformationVersion = transformationVersion;\n this._cvrStore.updateQuery(query);\n }\n return gotQueryPatch ? [gotQueryPatch] : [];\n });\n }\n\n /**\n * Converts queries that were tracked as executed into normal query\n * removals. This is used when a hydration budget expires after\n * `trackQueries()` has established the final poke version but before an\n * optional query starts hydration.\n *\n * The query ID remains in `#removedOrExecutedQueryIDs`, so its row\n * references are dropped by {@link deleteUnreferencedRows} exactly as they\n * would be for a query removed up front. Never un-track a query here: rows\n * already flushed by {@link received} have had its refCounts stripped and\n * cannot be restored.\n */\n removeTrackedQueries(queryIDs: Iterable<string>): PatchToVersion[] {\n assert(this.#existingRows !== undefined, 'trackQueries() was not called');\n assert(\n cmpVersions(this._orig.version, this._cvr.version) < 0,\n 'A final CVR version must be set before removing tracked queries',\n );\n\n const patches: PatchToVersion[] = [];\n for (const queryID of queryIDs) {\n assert(\n this.#executedQueryIDs.has(queryID),\n () => `Query ${queryID} was not tracked as executed`,\n );\n const query = must(this._cvr.queries[queryID]);\n assertNotInternal(query);\n assert(\n Object.values(query.clientState).every(\n ({inactivatedAt}) => inactivatedAt !== undefined,\n ),\n () => `Query ${queryID} is active`,\n );\n assert(\n query.patchVersion !== undefined,\n `Query ${queryID} is not gotten`,\n );\n\n delete this._cvr.queries[queryID];\n const patch = {type: 'query', op: 'del', id: queryID} as const;\n this._cvrStore.markQueryAsDeleted(this._cvr.version, patch);\n patches.push({patch, toVersion: this._cvr.version});\n }\n return patches;\n }\n\n /**\n * Tracks a query removed from the \"gotten\" set. In addition to producing the\n * appropriate patches for deleting the query, the removed query is taken into\n * account when computing the final row records in\n * {@link deleteUnreferencedRows}.\n * Namely, any rows with columns that are no longer referenced by a\n * query are deleted.\n *\n * This must only be called on queries that are not \"desired\" by any client.\n */\n #trackRemoved(queryID: string): Patch[] {\n return startSpan(tracer, 'CVRQueryDrivenUpdater.#trackRemoved', () => {\n const query = this._cvr.queries[queryID];\n assertNotInternal(query);\n\n assert(\n !this.#removedOrExecutedQueryIDs.has(queryID),\n () => `Query ${queryID} already tracked as executed or removed`,\n );\n this.#removedOrExecutedQueryIDs.add(queryID);\n delete this._cvr.queries[queryID];\n\n const newVersion = this._ensureNewVersion();\n const queryPatch = {type: 'query', op: 'del', id: queryID} as const;\n this._cvrStore.markQueryAsDeleted(newVersion, queryPatch);\n return [queryPatch];\n });\n }\n\n /**\n * Asserts that a new version has already been set.\n *\n * After {@link #executed} and {@link #removed} are called, we must have properly\n * decided on the final CVR version because the poke-start message declares the\n * final cookie (i.e. version), and that must be sent before any poke parts\n * generated from {@link received} are sent.\n */\n #assertNewVersion(\n rowID: RowID,\n existingVersion: string | undefined,\n newVersion: string | undefined,\n refCounts: RefCounts,\n ): CVRVersion {\n assert(\n cmpVersions(this._orig.version, this._cvr.version) < 0,\n () =>\n `Expected CVR version to have been bumped above original` +\n ` (orig=${versionString(this._orig.version)},` +\n ` curr=${versionString(this._cvr.version)}).` +\n ` Row ${JSON.stringify(rowID)}:` +\n ` existing=${existingVersion},` +\n ` new=${newVersion},` +\n ` queries=[${Object.keys(refCounts).join(',')}]`,\n );\n return this._cvr.version;\n }\n\n updatedVersion(): CVRVersion {\n return this._cvr.version;\n }\n\n /**\n * Public alias for {@link _ensureNewVersion}. Forces a `configVersion` bump\n * when the caller needs a new CVR version for reasons outside the built-in\n * tracking (e.g. rowSetSignature drift re-execution).\n */\n ensureNewVersion(): CVRVersion {\n return this._ensureNewVersion();\n }\n\n override flush(\n lc: LogContext,\n lastConnectTime: number,\n lastActive: number,\n ttlClock: TTLClock,\n ): Promise<{cvr: CVRSnapshot; flushed: CVRFlushStats | false}> {\n if (this.#rowSetSignature) {\n // Persist the per-query row-set signature for any query whose\n // pipeline-driver signature differs from what's on disk. Queries\n // without an active pipeline (provider returns undefined) keep their\n // stored value.\n for (const [queryID, query] of Object.entries(this._cvr.queries)) {\n const sig = this.#rowSetSignature(queryID);\n if (sig === undefined) {\n continue;\n }\n const stored = parseSignature(query.rowSetSignature);\n if (stored === sig) {\n continue;\n }\n const hex = formatSignature(sig);\n query.rowSetSignature = hex;\n this._cvrStore.updateRowSetSignature(queryID, hex);\n }\n }\n return super.flush(lc, lastConnectTime, lastActive, ttlClock);\n }\n\n /**\n * Tracks rows received from executing queries. This will update row records\n * and row patches if the received rows have a new version. The method also\n * returns (put) patches to be returned to update their state, versioned by\n * patchVersion so that only the patches new to the clients are sent.\n */\n received(\n _lc: LogContext,\n rows: Map<RowID, RowUpdate>,\n ): Promise<PatchToVersion[]> {\n return startAsyncSpan(\n tracer,\n 'CVRQueryDrivenUpdater.received',\n async () => {\n const patches: PatchToVersion[] = [];\n const existingRows = await this._cvrStore.getRowRecords();\n\n for (const [id, update] of rows.entries()) {\n const {contents, version, refCounts} = update;\n\n let existing = existingRows.get(id);\n // Accumulate all received refCounts to determine which rows to prune.\n const previouslyReceived = this.#receivedRows.get(id);\n\n const merged =\n previouslyReceived !== undefined\n ? mergeRefCounts(previouslyReceived, refCounts)\n : mergeRefCounts(\n existing?.refCounts,\n refCounts,\n this.#removedOrExecutedQueryIDs,\n );\n\n this.#receivedRows.set(id, merged);\n\n const newRowVersion = merged === null ? undefined : version;\n const patchVersion =\n existing && existing.rowVersion === newRowVersion\n ? existing.patchVersion // existing row is unchanged\n : this.#assertNewVersion(\n id,\n existing?.rowVersion,\n newRowVersion,\n refCounts,\n );\n\n // Note: for determining what to commit to the CVR store, use the\n // `version` of the update even if `merged` is null (i.e. don't\n // use `newRowVersion`). This will be deduped by the cvr-store flush\n // if it is redundant. In rare cases--namely, if the row key has\n // changed--we _do_ want to add row-put for the new row key with\n // `refCounts: null` in order to correctly record a delete patch\n // for that row, as the row with the old key will be removed.\n const rowVersion = version ?? existing?.rowVersion;\n if (rowVersion) {\n this._cvrStore.putRowRecord({\n id,\n rowVersion,\n patchVersion,\n refCounts: merged,\n });\n } else {\n // This means that a row that was not in the CVR was added during\n // this update, and then subsequently removed. Since there's no\n // corresponding row in the CVR itself, cancel the previous put.\n // Note that we still send a 'del' patch to the client in order to\n // cancel the previous 'put' patch.\n this._cvrStore.delRowRecord(id);\n }\n\n // Dedupe against the lastPatch sent for the row, and ensure that\n // toVersion never backtracks (lest it be undesirably filtered).\n const lastPatch = this.#lastPatches.get(id);\n const toVersion = maxVersion(patchVersion, lastPatch?.toVersion);\n\n if (merged === null) {\n // All refCounts have gone to zero, if row was previously synced\n // delete it.\n if (existing || previouslyReceived) {\n // dedupe\n if (lastPatch?.rowVersion !== null) {\n patches.push({\n patch: {\n type: 'row',\n op: 'del',\n id,\n },\n toVersion,\n });\n this.#lastPatches.set(id, {rowVersion: null, toVersion});\n }\n }\n } else if (contents) {\n assert(\n rowVersion,\n 'rowVersion is required when contents is present',\n );\n // dedupe\n if (!lastPatch?.rowVersion || lastPatch.rowVersion < rowVersion) {\n patches.push({\n patch: {\n type: 'row',\n op: 'put',\n id,\n contents,\n },\n toVersion,\n });\n this.#lastPatches.set(id, {rowVersion, toVersion});\n }\n }\n }\n return patches;\n },\n );\n }\n\n /**\n * Computes and updates the row records based on:\n * * The {@link #executed} queries\n * * The {@link #removed} queries\n * * The {@link received} rows\n *\n * Returns the final delete and patch ops that must be sent to the client\n * to delete rows that are no longer referenced by any query.\n *\n * This is Step [5] of the\n * [CVR Sync Algorithm](https://www.notion.so/replicache/Sync-and-Client-View-Records-CVR-a18e02ec3ec543449ea22070855ff33d?pvs=4#7874f9b80a514be2b8cd5cf538b88d37).\n */\n deleteUnreferencedRows(lc?: LogContext): Promise<PatchToVersion[]> {\n return startAsyncSpan(\n tracer,\n 'CVRQueryDrivenUpdater.deleteUnreferencedRows',\n async () => {\n if (this.#removedOrExecutedQueryIDs.size === 0) {\n // Query-less update. This can happen for config-only changes.\n assert(\n this.#receivedRows.size === 0,\n () =>\n `Expected no received rows for query-less update, got ${this.#receivedRows.size}`,\n );\n return [];\n }\n\n // patches to send to the client.\n const patches: PatchToVersion[] = [];\n\n const start = Date.now();\n assert(this.#existingRows, `trackQueries() was not called`);\n for (const existing of await this.#existingRows) {\n const deletedID = this.#deleteUnreferencedRow(existing);\n if (deletedID === null) {\n continue;\n }\n const lastPatch = this.#lastPatches.get(deletedID);\n if (lastPatch !== undefined && lastPatch.rowVersion === null) {\n continue;\n }\n const toVersion = maxVersion(this._cvr.version, lastPatch?.toVersion);\n patches.push({\n toVersion,\n patch: {type: 'row', op: 'del', id: deletedID},\n });\n this.#lastPatches.set(deletedID, {rowVersion: null, toVersion});\n }\n lc?.debug?.(\n `computed ${patches.length} delete patches (${Date.now() - start} ms)`,\n );\n\n return patches;\n },\n );\n }\n\n #deleteUnreferencedRow(existing: RowRecord): RowID | null {\n return startSpan(\n tracer,\n 'CVRQueryDrivenUpdater.#deleteUnreferencedRow',\n () => {\n if (this.#receivedRows.get(existing.id)) {\n return null;\n }\n\n const newRefCounts = mergeRefCounts(\n existing.refCounts,\n undefined,\n this.#removedOrExecutedQueryIDs,\n );\n\n // If a row is still referenced, we update the refCounts but not the\n // patchVersion (as the existence and contents of the row have not\n // changed from the clients' perspective). If the row is deleted, it\n // gets a new patchVersion (and corresponding poke).\n const patchVersion = newRefCounts\n ? existing.patchVersion\n : this.#assertNewVersion(\n existing.id,\n existing.rowVersion,\n undefined,\n existing.refCounts ?? {},\n );\n const rowRecord: RowRecord = {\n ...existing,\n patchVersion,\n refCounts: newRefCounts,\n };\n\n this._cvrStore.putRowRecord(rowRecord);\n\n // Return the id to delete if no longer referenced.\n return newRefCounts ? null : existing.id;\n },\n );\n }\n}\n\nfunction mergeRefCounts(\n existing: RefCounts | null | undefined,\n received: RefCounts | null | undefined,\n removeHashes?: Set<string>,\n): RefCounts | null {\n let merged: RefCounts = {};\n if (!existing) {\n merged = received ?? {};\n } else {\n [existing, received].forEach((refCounts, i) => {\n if (!refCounts) {\n return;\n }\n for (const [hash, count] of Object.entries(refCounts)) {\n if (i === 0 /* existing */ && removeHashes?.has(hash)) {\n continue; // removeHashes from existing row.\n }\n merged[hash] = (merged[hash] ?? 0) + count;\n if (merged[hash] === 0) {\n delete merged[hash];\n }\n }\n\n return merged;\n });\n }\n\n return Object.values(merged).some(v => v > 0) ? merged : null;\n}\n\n/**\n * The query must be inactive for all clients to be considered inactive.\n * This is because expiration is defined that way: a query is expired for a client group\n * only if it is expired for all clients in the group.\n *\n * If all clients have inactivated the query, we return\n * the one with the expiration furthest in the future.\n */\nexport function getInactiveQueries(cvr: CVR): {\n hash: string;\n inactivatedAt: TTLClock;\n ttl: number;\n}[] {\n // We no longer support a TTL larger than 10 minutes.\n const inactive: Map<\n string,\n {\n hash: string;\n inactivatedAt: TTLClock;\n ttl: number;\n }\n > = new Map();\n for (const [queryID, query] of Object.entries(cvr.queries)) {\n if (query.type === 'internal') {\n continue;\n }\n for (const clientState of Object.values(query.clientState)) {\n // 1. Take the longest TTL\n // 2. If the query is not inactivated (for any client), do not return it\n const {inactivatedAt, ttl} = clientState;\n const existing = inactive.get(queryID);\n if (inactivatedAt === undefined) {\n if (existing) {\n inactive.delete(queryID);\n }\n break;\n }\n\n const clampedTTL = clampTTL(ttl);\n if (existing) {\n // The stored one might be too large because from a previous version of\n // zero\n const existingTTL = clampTTL(existing.ttl);\n // Use the last eviction time.\n if (\n existingTTL + ttlClockAsNumber(existing.inactivatedAt) <\n ttlClockAsNumber(inactivatedAt) + clampedTTL\n ) {\n existing.ttl = clampedTTL;\n existing.inactivatedAt = inactivatedAt;\n }\n } else {\n inactive.set(queryID, {\n hash: queryID,\n inactivatedAt,\n ttl: clampedTTL,\n });\n }\n }\n }\n\n // First sort all the queries that have TTL. Oldest first.\n return toSorted(inactive.values(), (a, b) => {\n if (a.ttl === b.ttl) {\n return (\n ttlClockAsNumber(a.inactivatedAt) - ttlClockAsNumber(b.inactivatedAt)\n );\n }\n return (\n ttlClockAsNumber(a.inactivatedAt) +\n a.ttl -\n ttlClockAsNumber(b.inactivatedAt) -\n b.ttl\n );\n });\n}\n\nexport type HydrationQueryGroups<T extends QueryRecord = QueryRecord> = {\n required: T[];\n /**\n * Never contains an internal query: those are always required, so callers\n * can rely on `patchVersion` being present on the type.\n */\n optional: Exclude<T, InternalQueryRecord>[];\n};\n\n/**\n * Splits hydration candidates into required and optional queries. Optional\n * queries are ordered from latest to earliest effective expiration; an\n * ownerless query has the lowest priority.\n */\nexport function classifyQueriesForHydration<T extends QueryRecord>(\n queries: Iterable<T>,\n): HydrationQueryGroups<T> {\n type Optional = Exclude<T, InternalQueryRecord>;\n const required: T[] = [];\n const optionalWithExpiration: {\n query: Optional;\n expiration: number | undefined;\n }[] = [];\n\n for (const query of queries) {\n if (\n query.type === 'internal' ||\n Object.values(query.clientState).some(\n state => state.inactivatedAt === undefined,\n )\n ) {\n required.push(query);\n continue;\n }\n\n let expiration: number | undefined;\n for (const {inactivatedAt, ttl} of Object.values(query.clientState)) {\n assert(inactivatedAt !== undefined, 'inactive query has active client');\n const clientExpiration = ttlClockAsNumber(inactivatedAt) + clampTTL(ttl);\n expiration = Math.max(expiration ?? -Infinity, clientExpiration);\n }\n // Narrowed by the `type === 'internal'` branch above.\n optionalWithExpiration.push({query: query as Optional, expiration});\n }\n\n optionalWithExpiration.sort((a, b) => {\n if (a.expiration === undefined) {\n return b.expiration === undefined ? 0 : 1;\n }\n if (b.expiration === undefined) {\n return -1;\n }\n return b.expiration - a.expiration;\n });\n\n return {\n required,\n optional: optionalWithExpiration.map(({query}) => query),\n };\n}\n\nexport function nextEvictionTime(cvr: CVR): TTLClock | undefined {\n let next: number | undefined;\n for (const {inactivatedAt, ttl} of getInactiveQueries(cvr)) {\n const expire = ttlClockAsNumber(inactivatedAt) + ttl;\n if (next === undefined || expire < next) {\n next = expire;\n }\n }\n return next as TTLClock | undefined;\n}\n\nfunction newQueryRecord(\n id: string,\n ast: AST | undefined,\n name: string | undefined,\n args: readonly ReadonlyJSONValue[] | undefined,\n): ClientQueryRecord | CustomQueryRecord {\n if (ast !== undefined) {\n assert(\n name === undefined && args === undefined,\n 'Cannot provide name or args with ast',\n );\n return {\n id,\n type: 'client',\n ast,\n clientState: {},\n } satisfies ClientQueryRecord;\n }\n\n assert(\n name !== undefined && args !== undefined,\n 'Must provide name and args',\n );\n return {\n id,\n type: 'custom',\n name,\n args,\n clientState: {},\n } satisfies CustomQueryRecord;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;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KAAA,GACnB,OAAO;EAET,OAAO,EAAE,aAAa,EAAE;CAC1B,CAAC;CAED,OAAO;EACL;EACA,UAAU,uBAAuB,KAAK,EAAC,YAAW,KAAK;CACzD;AACF;AAEA,SAAgB,iBAAiB,KAAgC;CAC/D,IAAI;CACJ,KAAK,MAAM,EAAC,eAAe,SAAQ,mBAAmB,GAAG,GAAG;EAC1D,MAAM,SAAS,iBAAiB,aAAa,IAAI;EACjD,IAAI,SAAS,KAAA,KAAa,SAAS,MACjC,OAAO;CAEX;CACA,OAAO;AACT;AAEA,SAAS,eACP,IACA,KACA,MACA,MACuC;CACvC,IAAI,QAAQ,KAAA,GAAW;EACrB,OACE,SAAS,KAAA,KAAa,SAAS,KAAA,GAC/B,sCACF;EACA,OAAO;GACL;GACA,MAAM;GACN;GACA,aAAa,CAAC;EAChB;CACF;CAEA,OACE,SAAS,KAAA,KAAa,SAAS,KAAA,GAC/B,4BACF;CACA,OAAO;EACL;EACA,MAAM;EACN;EACA;EACA,aAAa,CAAC;CAChB;AACF"}
@@ -0,0 +1,33 @@
1
+ export type MonotonicClock = () => number;
2
+ /**
3
+ * A soft wall-clock budget for one view-syncer hydration pass.
4
+ *
5
+ * Callers check the budget only at query boundaries. Consequently, a query
6
+ * that starts before the limit is reached is always allowed to finish.
7
+ *
8
+ * The budget measures hydration work. Intervals that are not hydration --
9
+ * notably the remote custom-query transform round trips -- are discounted via
10
+ * {@link excluding}, so that endpoint latency cannot spend a budget that only
11
+ * evicting queries could recover.
12
+ */
13
+ export declare class HydrationBudget {
14
+ #private;
15
+ readonly limitMs: number;
16
+ constructor(limitMs: number, now?: MonotonicClock);
17
+ /**
18
+ * Runs `fn`, discounting the time it takes as non-hydration work. The
19
+ * interval is measured with this budget's own clock, so an injected clock
20
+ * governs both the elapsed time and what is excluded from it.
21
+ */
22
+ excluding<T>(fn: () => Promise<T>): Promise<T>;
23
+ elapsedMs(): number;
24
+ /**
25
+ * Whether the budget is spent. A disabled budget (`limitMs === 0`) is never
26
+ * exhausted. The elapsed time at the first exhausted check is retained in
27
+ * {@link exhaustedAtMs} so that reporting does not re-read the clock.
28
+ */
29
+ exhausted(): boolean;
30
+ /** The elapsed time at which {@link exhausted} first returned true. */
31
+ get exhaustedAtMs(): number | undefined;
32
+ }
33
+ //# sourceMappingURL=hydration-budget.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"hydration-budget.d.ts","sourceRoot":"","sources":["../../../../../../zero-cache/src/services/view-syncer/hydration-budget.ts"],"names":[],"mappings":"AAEA,MAAM,MAAM,cAAc,GAAG,MAAM,MAAM,CAAC;AAE1C;;;;;;;;;;GAUG;AACH,qBAAa,eAAe;;IAC1B,QAAQ,CAAC,OAAO,EAAE,MAAM,CAAC;IAMzB,YACE,OAAO,EAAE,MAAM,EACf,GAAG,GAAE,cAAkD,EASxD;IAED;;;;OAIG;IACG,SAAS,CAAC,CAAC,EAAE,EAAE,EAAE,MAAM,OAAO,CAAC,CAAC,CAAC,GAAG,OAAO,CAAC,CAAC,CAAC,CAOnD;IAED,SAAS,IAAI,MAAM,CAElB;IAED;;;;OAIG;IACH,SAAS,IAAI,OAAO,CAUnB;IAED,uEAAuE;IACvE,IAAI,aAAa,IAAI,MAAM,GAAG,SAAS,CAEtC;CACF"}
@@ -0,0 +1,62 @@
1
+ import { assert } from "../../../../shared/src/asserts.js";
2
+ //#region ../zero-cache/src/services/view-syncer/hydration-budget.ts
3
+ /**
4
+ * A soft wall-clock budget for one view-syncer hydration pass.
5
+ *
6
+ * Callers check the budget only at query boundaries. Consequently, a query
7
+ * that starts before the limit is reached is always allowed to finish.
8
+ *
9
+ * The budget measures hydration work. Intervals that are not hydration --
10
+ * notably the remote custom-query transform round trips -- are discounted via
11
+ * {@link excluding}, so that endpoint latency cannot spend a budget that only
12
+ * evicting queries could recover.
13
+ */
14
+ var HydrationBudget = class {
15
+ limitMs;
16
+ #now;
17
+ #startedAt;
18
+ #excludedMs = 0;
19
+ #exhaustedAtMs;
20
+ constructor(limitMs, now = performance.now.bind(performance)) {
21
+ assert(Number.isSafeInteger(limitMs) && limitMs >= 0, "Hydration budget must be a nonnegative integer");
22
+ this.limitMs = limitMs;
23
+ this.#now = now;
24
+ this.#startedAt = now();
25
+ }
26
+ /**
27
+ * Runs `fn`, discounting the time it takes as non-hydration work. The
28
+ * interval is measured with this budget's own clock, so an injected clock
29
+ * governs both the elapsed time and what is excluded from it.
30
+ */
31
+ async excluding(fn) {
32
+ const start = this.#now();
33
+ try {
34
+ return await fn();
35
+ } finally {
36
+ this.#excludedMs += this.#now() - start;
37
+ }
38
+ }
39
+ elapsedMs() {
40
+ return this.#now() - this.#startedAt - this.#excludedMs;
41
+ }
42
+ /**
43
+ * Whether the budget is spent. A disabled budget (`limitMs === 0`) is never
44
+ * exhausted. The elapsed time at the first exhausted check is retained in
45
+ * {@link exhaustedAtMs} so that reporting does not re-read the clock.
46
+ */
47
+ exhausted() {
48
+ if (this.limitMs === 0) return false;
49
+ const elapsed = this.elapsedMs();
50
+ if (elapsed < this.limitMs) return false;
51
+ this.#exhaustedAtMs ??= elapsed;
52
+ return true;
53
+ }
54
+ /** The elapsed time at which {@link exhausted} first returned true. */
55
+ get exhaustedAtMs() {
56
+ return this.#exhaustedAtMs;
57
+ }
58
+ };
59
+ //#endregion
60
+ export { HydrationBudget };
61
+
62
+ //# sourceMappingURL=hydration-budget.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"hydration-budget.js","names":["#now","#startedAt","#excludedMs","#exhaustedAtMs"],"sources":["../../../../../../zero-cache/src/services/view-syncer/hydration-budget.ts"],"sourcesContent":["import {assert} from '../../../../shared/src/asserts.ts';\n\nexport type MonotonicClock = () => number;\n\n/**\n * A soft wall-clock budget for one view-syncer hydration pass.\n *\n * Callers check the budget only at query boundaries. Consequently, a query\n * that starts before the limit is reached is always allowed to finish.\n *\n * The budget measures hydration work. Intervals that are not hydration --\n * notably the remote custom-query transform round trips -- are discounted via\n * {@link excluding}, so that endpoint latency cannot spend a budget that only\n * evicting queries could recover.\n */\nexport class HydrationBudget {\n readonly limitMs: number;\n readonly #now: MonotonicClock;\n readonly #startedAt: number;\n #excludedMs = 0;\n #exhaustedAtMs: number | undefined;\n\n constructor(\n limitMs: number,\n now: MonotonicClock = performance.now.bind(performance),\n ) {\n assert(\n Number.isSafeInteger(limitMs) && limitMs >= 0,\n 'Hydration budget must be a nonnegative integer',\n );\n this.limitMs = limitMs;\n this.#now = now;\n this.#startedAt = now();\n }\n\n /**\n * Runs `fn`, discounting the time it takes as non-hydration work. The\n * interval is measured with this budget's own clock, so an injected clock\n * governs both the elapsed time and what is excluded from it.\n */\n async excluding<T>(fn: () => Promise<T>): Promise<T> {\n const start = this.#now();\n try {\n return await fn();\n } finally {\n this.#excludedMs += this.#now() - start;\n }\n }\n\n elapsedMs(): number {\n return this.#now() - this.#startedAt - this.#excludedMs;\n }\n\n /**\n * Whether the budget is spent. A disabled budget (`limitMs === 0`) is never\n * exhausted. The elapsed time at the first exhausted check is retained in\n * {@link exhaustedAtMs} so that reporting does not re-read the clock.\n */\n exhausted(): boolean {\n if (this.limitMs === 0) {\n return false;\n }\n const elapsed = this.elapsedMs();\n if (elapsed < this.limitMs) {\n return false;\n }\n this.#exhaustedAtMs ??= elapsed;\n return true;\n }\n\n /** The elapsed time at which {@link exhausted} first returned true. */\n get exhaustedAtMs(): number | undefined {\n return this.#exhaustedAtMs;\n }\n}\n"],"mappings":";;;;;;;;;;;;;AAeA,IAAa,kBAAb,MAA6B;CAC3B;CACA;CACA;CACA,cAAc;CACd;CAEA,YACE,SACA,MAAsB,YAAY,IAAI,KAAK,WAAW,GACtD;EACA,OACE,OAAO,cAAc,OAAO,KAAK,WAAW,GAC5C,gDACF;EACA,KAAK,UAAU;EACf,KAAKA,OAAO;EACZ,KAAKC,aAAa,IAAI;CACxB;;;;;;CAOA,MAAM,UAAa,IAAkC;EACnD,MAAM,QAAQ,KAAKD,KAAK;EACxB,IAAI;GACF,OAAO,MAAM,GAAG;EAClB,UAAU;GACR,KAAKE,eAAe,KAAKF,KAAK,IAAI;EACpC;CACF;CAEA,YAAoB;EAClB,OAAO,KAAKA,KAAK,IAAI,KAAKC,aAAa,KAAKC;CAC9C;;;;;;CAOA,YAAqB;EACnB,IAAI,KAAK,YAAY,GACnB,OAAO;EAET,MAAM,UAAU,KAAK,UAAU;EAC/B,IAAI,UAAU,KAAK,SACjB,OAAO;EAET,KAAKC,mBAAmB;EACxB,OAAO;CACT;;CAGA,IAAI,gBAAoC;EACtC,OAAO,KAAKA;CACd;AACF"}
@@ -18,7 +18,10 @@ import type { ReplicaState } from '../replicator/replicator.ts';
18
18
  import type { ActivityBasedService } from '../service.ts';
19
19
  import type { ConnectionContextManager, ConnectionSelector } from './connection-context-manager.ts';
20
20
  import type { DrainCoordinator } from './drain-coordinator.ts';
21
+ import { type MonotonicClock } from './hydration-budget.ts';
21
22
  import type { PipelineDriver } from './pipeline-driver.ts';
23
+ import { type ClientQueryRecord, type CustomQueryRecord, type InternalQueryRecord } from './schema/types.ts';
24
+ import { type TTLClock } from './ttl-clock.ts';
22
25
  export interface ViewSyncer {
23
26
  initConnection(selector: ConnectionSelector, initConnectionMessage: InitConnectionMessage): Source<ViewSyncerDownstream>;
24
27
  changeDesiredQueries(selector: ConnectionSelector, msg: ChangeDesiredQueriesMessage): Promise<void>;
@@ -67,7 +70,7 @@ export declare class ViewSyncerService implements ViewSyncer, ActivityBasedServi
67
70
  readonly id: string;
68
71
  readonly createdAtMs: number;
69
72
  readonly connContextManager: ConnectionContextManager;
70
- constructor(config: NormalizedZeroConfig, lc: LogContext, shard: ShardID, taskID: string, clientGroupID: string, cvrDb: PostgresDB, pipelineDriver: PipelineDriver, versionChanges: Subscription<ReplicaState>, drainCoordinator: DrainCoordinator, slowHydrateThreshold: number, inspectorDelegate: InspectorDelegate, connContextManager: ConnectionContextManager, customQueryTransformer: CustomQueryTransformer | undefined, runPriorityOp: <T>(lc: LogContext, description: string, op: () => Promise<T>) => Promise<T>, keepaliveMs?: number, setTimeoutFn?: SetTimeout);
73
+ constructor(config: NormalizedZeroConfig, lc: LogContext, shard: ShardID, taskID: string, clientGroupID: string, cvrDb: PostgresDB, pipelineDriver: PipelineDriver, versionChanges: Subscription<ReplicaState>, drainCoordinator: DrainCoordinator, slowHydrateThreshold: number, inspectorDelegate: InspectorDelegate, connContextManager: ConnectionContextManager, customQueryTransformer: CustomQueryTransformer | undefined, runPriorityOp: <T>(lc: LogContext, description: string, op: () => Promise<T>) => Promise<T>, keepaliveMs?: number, setTimeoutFn?: SetTimeout, now?: MonotonicClock);
71
74
  readyState(): Promise<'initialized' | 'draining'>;
72
75
  run(): Promise<void>;
73
76
  get queryCount(): number;
@@ -98,6 +101,13 @@ export declare class ViewSyncerService implements ViewSyncer, ActivityBasedServi
98
101
  */
99
102
  markInitialized(): void;
100
103
  }
104
+ /**
105
+ * Whether a query's TTL has elapsed. A query must be expired for all clients
106
+ * in order to be considered expired.
107
+ *
108
+ * Exported for testing.
109
+ */
110
+ export declare function expired(ttlClock: TTLClock, q: InternalQueryRecord | ClientQueryRecord | CustomQueryRecord): boolean;
101
111
  export declare class TimeSliceTimer {
102
112
  #private;
103
113
  constructor(lc: LogContext);
@@ -1 +1 @@
1
- {"version":3,"file":"view-syncer.d.ts","sourceRoot":"","sources":["../../../../../../zero-cache/src/services/view-syncer/view-syncer.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAC,UAAU,EAAC,MAAM,kBAAkB,CAAC;AAcjD,OAAO,KAAK,EAAC,2BAA2B,EAAC,MAAM,yDAAyD,CAAC;AAKzG,OAAO,KAAK,EAEV,qBAAqB,EACtB,MAAM,0CAA0C,CAAC;AAElD,OAAO,KAAK,EAAC,oBAAoB,EAAC,MAAM,iDAAiD,CAAC;AAQ1F,OAAO,KAAK,EAEV,wBAAwB,EACzB,MAAM,6CAA6C,CAAC;AACrD,OAAO,KAAK,EAAC,iBAAiB,EAAC,MAAM,8CAA8C,CAAC;AAGpF,OAAO,EAAkB,KAAK,IAAI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