@rocicorp/zero 0.26.1-canary.2 → 0.26.1-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.
- package/out/analyze-query/src/run-ast.d.ts.map +1 -1
- package/out/analyze-query/src/run-ast.js +4 -1
- package/out/analyze-query/src/run-ast.js.map +1 -1
- package/out/replicache/src/btree/node.js +4 -4
- package/out/replicache/src/btree/node.js.map +1 -1
- package/out/replicache/src/btree/write.js +2 -2
- package/out/replicache/src/btree/write.js.map +1 -1
- package/out/replicache/src/dag/gc.js +5 -2
- package/out/replicache/src/dag/gc.js.map +1 -1
- package/out/replicache/src/db/write.d.ts.map +1 -1
- package/out/replicache/src/db/write.js +21 -6
- package/out/replicache/src/db/write.js.map +1 -1
- package/out/replicache/src/error-responses.d.ts.map +1 -1
- package/out/replicache/src/error-responses.js +4 -1
- package/out/replicache/src/error-responses.js.map +1 -1
- package/out/replicache/src/persist/clients.d.ts.map +1 -1
- package/out/replicache/src/persist/clients.js +4 -1
- package/out/replicache/src/persist/clients.js.map +1 -1
- package/out/replicache/src/persist/collect-idb-databases.d.ts.map +1 -1
- package/out/replicache/src/persist/collect-idb-databases.js +2 -1
- package/out/replicache/src/persist/collect-idb-databases.js.map +1 -1
- package/out/replicache/src/persist/idb-databases-store.d.ts.map +1 -1
- package/out/replicache/src/persist/idb-databases-store.js +4 -1
- package/out/replicache/src/persist/idb-databases-store.js.map +1 -1
- package/out/replicache/src/process-scheduler.js +4 -1
- package/out/replicache/src/process-scheduler.js.map +1 -1
- package/out/replicache/src/replicache-impl.js +2 -2
- package/out/replicache/src/replicache-impl.js.map +1 -1
- package/out/replicache/src/subscriptions.d.ts.map +1 -1
- package/out/replicache/src/subscriptions.js +5 -2
- package/out/replicache/src/subscriptions.js.map +1 -1
- package/out/replicache/src/sync/diff.d.ts.map +1 -1
- package/out/replicache/src/sync/diff.js +4 -1
- package/out/replicache/src/sync/diff.js.map +1 -1
- package/out/replicache/src/sync/pull.d.ts.map +1 -1
- package/out/replicache/src/sync/pull.js +4 -1
- package/out/replicache/src/sync/pull.js.map +1 -1
- package/out/replicache/src/sync/push.d.ts.map +1 -1
- package/out/replicache/src/sync/push.js +5 -2
- package/out/replicache/src/sync/push.js.map +1 -1
- package/out/shared/src/asserts.d.ts +1 -1
- package/out/shared/src/asserts.d.ts.map +1 -1
- package/out/shared/src/asserts.js +1 -1
- package/out/shared/src/asserts.js.map +1 -1
- package/out/z2s/src/compiler.d.ts.map +1 -1
- package/out/z2s/src/compiler.js +8 -2
- package/out/z2s/src/compiler.js.map +1 -1
- package/out/zero/package.json.js +1 -1
- package/out/zero-cache/src/services/analyze.js +1 -0
- package/out/zero-cache/src/services/analyze.js.map +1 -1
- package/out/zero-cache/src/services/change-source/pg/schema/ddl.d.ts.map +1 -1
- package/out/zero-cache/src/services/change-source/pg/schema/ddl.js +6 -1
- package/out/zero-cache/src/services/change-source/pg/schema/ddl.js.map +1 -1
- package/out/zero-cache/src/services/change-source/pg/schema/init.d.ts.map +1 -1
- package/out/zero-cache/src/services/change-source/pg/schema/init.js +12 -8
- package/out/zero-cache/src/services/change-source/pg/schema/init.js.map +1 -1
- package/out/zero-cache/src/services/run-ast.d.ts.map +1 -1
- package/out/zero-cache/src/services/run-ast.js +22 -2
- package/out/zero-cache/src/services/run-ast.js.map +1 -1
- package/out/zero-cache/src/services/view-syncer/cvr.d.ts.map +1 -1
- package/out/zero-cache/src/services/view-syncer/cvr.js +8 -2
- package/out/zero-cache/src/services/view-syncer/cvr.js.map +1 -1
- package/out/zero-cache/src/services/view-syncer/pipeline-driver.d.ts.map +1 -1
- package/out/zero-cache/src/services/view-syncer/pipeline-driver.js +10 -1
- package/out/zero-cache/src/services/view-syncer/pipeline-driver.js.map +1 -1
- package/out/zero-cache/src/services/view-syncer/snapshotter.d.ts +1 -1
- package/out/zero-cache/src/services/view-syncer/snapshotter.d.ts.map +1 -1
- package/out/zero-cache/src/services/view-syncer/snapshotter.js +15 -7
- package/out/zero-cache/src/services/view-syncer/snapshotter.js.map +1 -1
- package/out/zero-client/src/client/http-string.js.map +1 -1
- package/out/zero-client/src/client/version.js +1 -1
- package/out/zero-client/src/client/zero.js.map +1 -1
- package/out/zero-schema/src/permissions.d.ts.map +1 -1
- package/out/zero-schema/src/permissions.js +4 -1
- package/out/zero-schema/src/permissions.js.map +1 -1
- package/out/zql/src/builder/filter.d.ts.map +1 -1
- package/out/zql/src/builder/filter.js +5 -2
- package/out/zql/src/builder/filter.js.map +1 -1
- package/out/zql/src/ivm/constraint.js.map +1 -1
- package/package.json +1 -1
|
@@ -178,14 +178,8 @@ function getIncrementalMigrations(shard, replicaVersion) {
|
|
|
178
178
|
}
|
|
179
179
|
},
|
|
180
180
|
// Upgrade DDL trigger to log more info to PG logs.
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
const [{ publications }] = await sql`
|
|
184
|
-
SELECT publications FROM ${sql(shardConfigTable)}`;
|
|
185
|
-
await setupTriggers(lc, sql, { ...shard, publications });
|
|
186
|
-
lc.info?.(`Upgraded DDL event triggers`);
|
|
187
|
-
}
|
|
188
|
-
},
|
|
181
|
+
// (subsumed by v16)
|
|
182
|
+
14: {},
|
|
189
183
|
// Add initialSyncContext column to replicas table.
|
|
190
184
|
15: {
|
|
191
185
|
migrateSchema: async (_, sql) => {
|
|
@@ -195,6 +189,16 @@ function getIncrementalMigrations(shard, replicaVersion) {
|
|
|
195
189
|
ADD COLUMN "subscriberContext" JSON
|
|
196
190
|
`;
|
|
197
191
|
}
|
|
192
|
+
},
|
|
193
|
+
// Upgrade DDL trigger to fire on all ALTER TABLE statements
|
|
194
|
+
// to catch the *removal* of a table from the published set.
|
|
195
|
+
16: {
|
|
196
|
+
migrateSchema: async (lc, sql) => {
|
|
197
|
+
const [{ publications }] = await sql`
|
|
198
|
+
SELECT publications FROM ${sql(shardConfigTable)}`;
|
|
199
|
+
await setupTriggers(lc, sql, { ...shard, publications });
|
|
200
|
+
lc.info?.(`Upgraded DDL event triggers`);
|
|
201
|
+
}
|
|
198
202
|
}
|
|
199
203
|
};
|
|
200
204
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"init.js","sources":["../../../../../../../../zero-cache/src/services/change-source/pg/schema/init.ts"],"sourcesContent":["import type {LogContext} from '@rocicorp/logger';\nimport {assert} from '../../../../../../shared/src/asserts.ts';\nimport * as v from '../../../../../../shared/src/valita.ts';\nimport {\n getVersionHistory,\n runSchemaMigrations,\n type IncrementalMigrationMap,\n type Migration,\n} from '../../../../db/migration.ts';\nimport type {PostgresDB} from '../../../../types/pg.ts';\nimport {upstreamSchema, type ShardConfig} from '../../../../types/shards.ts';\nimport {id} from '../../../../types/sql.ts';\nimport {AutoResetSignal} from '../../../change-streamer/schema/tables.ts';\nimport {decommissionShard} from '../decommission.ts';\nimport {publishedSchema} from './published.ts';\nimport {\n getMutationsTableDefinition,\n legacyReplicationSlot,\n metadataPublicationName,\n setupTablesAndReplication,\n setupTriggers,\n} from './shard.ts';\n\n/**\n * Ensures that a shard is set up for initial sync.\n */\nexport async function ensureShardSchema(\n lc: LogContext,\n db: PostgresDB,\n shard: ShardConfig,\n): Promise<void> {\n const initialSetup: Migration = {\n migrateSchema: (lc, tx) => setupTablesAndReplication(lc, tx, shard),\n minSafeVersion: 1,\n };\n await runSchemaMigrations(\n lc,\n `upstream-shard-${shard.appID}`,\n upstreamSchema(shard),\n db,\n initialSetup,\n // The incremental migration of any existing replicas will be replaced by\n // the incoming replica being synced, so the replicaVersion here is\n // unnecessary.\n getIncrementalMigrations(shard, 'obsolete'),\n );\n}\n\n/**\n * Updates the schema for an existing shard.\n */\nexport async function updateShardSchema(\n lc: LogContext,\n db: PostgresDB,\n shard: ShardConfig,\n replicaVersion: string,\n): Promise<void> {\n await runSchemaMigrations(\n lc,\n `upstream-shard-${shard.appID}`,\n upstreamSchema(shard),\n db,\n {\n // If the expected existing shard is absent, throw an\n // AutoResetSignal to backtrack and initial sync.\n migrateSchema: () => {\n throw new AutoResetSignal(\n `upstream shard ${upstreamSchema(shard)} is not initialized`,\n );\n },\n },\n getIncrementalMigrations(shard, replicaVersion),\n );\n\n // The decommission check is run in updateShardSchema so that it happens\n // after initial sync, and not when the shard schema is initially set up.\n await decommissionLegacyShard(lc, db, shard);\n}\n\nfunction getIncrementalMigrations(\n shard: ShardConfig,\n replicaVersion?: string,\n): IncrementalMigrationMap {\n const shardConfigTable = `${upstreamSchema(shard)}.shardConfig`;\n\n return {\n 4: {\n migrateSchema: () => {\n throw new AutoResetSignal('resetting to upgrade shard schema');\n },\n minSafeVersion: 3,\n },\n\n // v5 changes the upstream schema organization from \"zero_{SHARD_ID}\" to\n // the \"{APP_ID}_0\". An incremental migration indicates that the previous\n // SHARD_ID was \"0\" and the new APP_ID is \"zero\" (i.e. the default values\n // for those options). In this case, the upstream format is identical, and\n // no migration is necessary. However, the version is bumped to v5 to\n // indicate that it was created with the {APP_ID} configuration and should\n // not be decommissioned as a legacy shard.\n 5: {},\n\n 6: {\n migrateSchema: async (lc, sql) => {\n assert(\n replicaVersion,\n `replicaVersion is always passed for incremental migrations`,\n );\n await Promise.all([\n sql`\n ALTER TABLE ${sql(shardConfigTable)} ADD \"replicaVersion\" TEXT`,\n sql`\n UPDATE ${sql(shardConfigTable)} SET ${sql({replicaVersion})}`,\n ]);\n lc.info?.(\n `Recorded replicaVersion ${replicaVersion} in upstream shardConfig`,\n );\n },\n },\n\n // Updates the DDL event trigger protocol to v2, and adds support for\n // ALTER SCHEMA x RENAME TO y\n 7: {\n migrateSchema: async (lc, sql) => {\n const [{publications}] = await sql<{publications: string[]}[]>`\n SELECT publications FROM ${sql(shardConfigTable)}`;\n await setupTriggers(lc, sql, {...shard, publications});\n lc.info?.(`Upgraded to v2 event triggers`);\n },\n },\n\n // Adds support for non-disruptive resyncs, which tracks multiple\n // replicas with different slot names.\n 8: {\n migrateSchema: async (lc, sql) => {\n const legacyShardConfigSchema = v.object({\n replicaVersion: v.string().nullable(),\n initialSchema: publishedSchema.nullable(),\n });\n const result = await sql`\n SELECT \"replicaVersion\", \"initialSchema\" FROM ${sql(shardConfigTable)}`;\n assert(\n result.length === 1,\n () => `Expected exactly one shardConfig row, got ${result.length}`,\n );\n const {replicaVersion, initialSchema} = v.parse(\n result[0],\n legacyShardConfigSchema,\n 'passthrough',\n );\n\n await Promise.all([\n sql`\n CREATE TABLE ${sql(upstreamSchema(shard))}.replicas (\n \"slot\" TEXT PRIMARY KEY,\n \"version\" TEXT NOT NULL,\n \"initialSchema\" JSON NOT NULL\n );\n `,\n sql`\n INSERT INTO ${sql(upstreamSchema(shard))}.replicas ${sql({\n slot: legacyReplicationSlot(shard),\n version: replicaVersion,\n initialSchema,\n })}\n `,\n sql`\n ALTER TABLE ${sql(shardConfigTable)} DROP \"replicaVersion\", DROP \"initialSchema\"\n `,\n ]);\n lc.info?.(`Upgraded schema to support non-disruptive resyncs`);\n },\n },\n\n // Fixes field ordering of compound indexes. This incremental migration\n // only fixes indexes resulting from new schema changes. A full resync is\n // required to fix existing indexes.\n //\n // The migration has been subsumed by the identical logic for migrating\n // to v12 (i.e. a trigger upgrade).\n 9: {},\n\n // Adds the `mutations` table used to track mutation results.\n 10: {\n migrateSchema: async (lc, sql) => {\n await sql.unsafe(/*sql*/ `\n ${getMutationsTableDefinition(upstreamSchema(shard))}\n ALTER PUBLICATION ${id(metadataPublicationName(shard.appID, shard.shardNum))} ADD TABLE ${id(upstreamSchema(shard))}.\"mutations\";\n `);\n lc.info?.('Upgraded schema with new mutations table');\n },\n },\n\n // Formerly dropped the schemaVersions table, but restored in the v13\n // migration for rollback safety.\n 11: {},\n\n // Upgrade DDL trigger to query schemaOID, needed information for auto-backfill.\n // (subsumed by v14)\n 12: {},\n\n // Recreates the legacy schemaVersions table that was prematurely dropped\n // in the (former) v11 migration. It needs to remain present for at least one\n // release in order to be rollback safe.\n //\n // TODO: Drop the table once a release that no longer reads the table has\n // been rolled out.\n 13: {\n migrateSchema: async (_, sql) => {\n await sql`\n CREATE TABLE IF NOT EXISTS ${sql(upstreamSchema(shard))}.\"schemaVersions\" (\n \"minSupportedVersion\" INT4,\n \"maxSupportedVersion\" INT4,\n \"lock\" BOOL PRIMARY KEY DEFAULT true CHECK (lock)\n );`;\n await sql`\n INSERT INTO ${sql(upstreamSchema(shard))}.\"schemaVersions\" \n (\"lock\", \"minSupportedVersion\", \"maxSupportedVersion\")\n VALUES (true, 1, 1)\n ON CONFLICT DO NOTHING;\n `;\n },\n },\n\n // Upgrade DDL trigger to log more info to PG logs.\n 14: {\n migrateSchema: async (lc, sql) => {\n const [{publications}] = await sql<{publications: string[]}[]>`\n SELECT publications FROM ${sql(shardConfigTable)}`;\n await setupTriggers(lc, sql, {...shard, publications});\n lc.info?.(`Upgraded DDL event triggers`);\n },\n },\n\n // Add initialSyncContext column to replicas table.\n 15: {\n migrateSchema: async (_, sql) => {\n await sql`\n ALTER TABLE ${sql(upstreamSchema(shard))}.replicas\n ADD COLUMN \"initialSyncContext\" JSON,\n ADD COLUMN \"subscriberContext\" JSON\n `;\n },\n },\n };\n}\n\nexport async function decommissionLegacyShard(\n lc: LogContext,\n db: PostgresDB,\n shard: ShardConfig,\n) {\n if (shard.appID !== 'zero') {\n // When migration from non-default shard ids, e.g. \"zero_prod\" => \"prod_0\",\n // clean up the old \"zero_prod\" shard if it is pre-v5. Note that the v5\n // check is important to guard against cleaning up a **new** \"zero_0\" app\n // that coexists with the current App (with app-id === \"0\").\n const versionHistory = await getVersionHistory(db, `zero_${shard.appID}`);\n if (versionHistory !== null && versionHistory.schemaVersion < 5) {\n await decommissionShard(lc, db, 'zero', shard.appID);\n }\n }\n}\n"],"names":["lc","v.object","v.string","replicaVersion","v.parse"],"mappings":";;;;;;;;;;AA0BA,eAAsB,kBACpB,IACA,IACA,OACe;AACf,QAAM,eAA0B;AAAA,IAC9B,eAAe,CAACA,KAAI,OAAO,0BAA0BA,KAAI,IAAI,KAAK;AAAA,IAClE,gBAAgB;AAAA,EAAA;AAElB,QAAM;AAAA,I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c,GAAG,eAAe,KAAK,CAAC,CAAC;AAAA;AAAA,QAAA;AAErH,WAAG,OAAO,0CAA0C;AAAA,MACtD;AAAA,IAAA;AAAA;AAAA;AAAA,IAKF,IAAI,CAAA;AAAA;AAAA;AAAA,IAIJ,IAAI,CAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,IAQJ,IAAI;AAAA,MACF,eAAe,OAAO,GAAG,QAAQ;AAC/B,cAAM;AAAA,uCACyB,IAAI,eAAe,KAAK,CAAC,CAAC;AAAA;AAAA;AAAA;AAAA;AAKzD,cAAM;AAAA,wBACU,IAAI,eAAe,KAAK,CAAC,CAAC;AAAA;AAAA;AAAA;AAAA;AAAA,MAK5C;AAAA,IAAA;AAAA;AAAA,IAIF,IAAI;AAAA,MACF,eAAe,OAAO,IAAI,QAAQ;AAChC,cAAM,CAAC,EAAC,cAAa,IAAI,MAAM;AAAA,qCACF,IAAI,gBAAgB,CAAC;AAClD,cAAM,cAAc,IAAI,KAAK,EAAC,GAAG,OAAO,cAAa;AACrD,WAAG,OAAO,6BAA6B;AAAA,MACzC;AAAA,IAAA;AAAA;AAAA,IAIF,IAAI;AAAA,MACF,eAAe,OAAO,GAAG,QAAQ;AAC/B,cAAM;AAAA,wBACU,IAAI,eAAe,KAAK,CAAC,CAAC;AAAA;AAAA;AAAA;AAAA,MAI5C;AAAA,IAAA;AAAA,EACF;AAEJ;AAEA,eAAsB,wBACpB,IACA,IACA,OACA;AACA,MAAI,MAAM,UAAU,QAAQ;AAK1B,UAAM,iBAAiB,MAAM,kBAAkB,IAAI,QAAQ,MAAM,KAAK,EAAE;AACxE,QAAI,mBAAmB,QAAQ,eAAe,gBAAgB,GAAG;AAC/D,YAAM,kBAAkB,IAAI,IAAI,QAAQ,MAAM,KAAK;AAAA,IACrD;AAAA,EACF;AACF;"}
|
|
1
|
+
{"version":3,"file":"init.js","sources":["../../../../../../../../zero-cache/src/services/change-source/pg/schema/init.ts"],"sourcesContent":["import type {LogContext} from '@rocicorp/logger';\nimport {assert} from '../../../../../../shared/src/asserts.ts';\nimport * as v from '../../../../../../shared/src/valita.ts';\nimport {\n getVersionHistory,\n runSchemaMigrations,\n type IncrementalMigrationMap,\n type Migration,\n} from '../../../../db/migration.ts';\nimport type {PostgresDB} from '../../../../types/pg.ts';\nimport {upstreamSchema, type ShardConfig} from '../../../../types/shards.ts';\nimport {id} from '../../../../types/sql.ts';\nimport {AutoResetSignal} from '../../../change-streamer/schema/tables.ts';\nimport {decommissionShard} from '../decommission.ts';\nimport {publishedSchema} from './published.ts';\nimport {\n getMutationsTableDefinition,\n legacyReplicationSlot,\n metadataPublicationName,\n setupTablesAndReplication,\n setupTriggers,\n} from './shard.ts';\n\n/**\n * Ensures that a shard is set up for initial sync.\n */\nexport async function ensureShardSchema(\n lc: LogContext,\n db: PostgresDB,\n shard: ShardConfig,\n): Promise<void> {\n const initialSetup: Migration = {\n migrateSchema: (lc, tx) => setupTablesAndReplication(lc, tx, shard),\n minSafeVersion: 1,\n };\n await runSchemaMigrations(\n lc,\n `upstream-shard-${shard.appID}`,\n upstreamSchema(shard),\n db,\n initialSetup,\n // The incremental migration of any existing replicas will be replaced by\n // the incoming replica being synced, so the replicaVersion here is\n // unnecessary.\n getIncrementalMigrations(shard, 'obsolete'),\n );\n}\n\n/**\n * Updates the schema for an existing shard.\n */\nexport async function updateShardSchema(\n lc: LogContext,\n db: PostgresDB,\n shard: ShardConfig,\n replicaVersion: string,\n): Promise<void> {\n await runSchemaMigrations(\n lc,\n `upstream-shard-${shard.appID}`,\n upstreamSchema(shard),\n db,\n {\n // If the expected existing shard is absent, throw an\n // AutoResetSignal to backtrack and initial sync.\n migrateSchema: () => {\n throw new AutoResetSignal(\n `upstream shard ${upstreamSchema(shard)} is not initialized`,\n );\n },\n },\n getIncrementalMigrations(shard, replicaVersion),\n );\n\n // The decommission check is run in updateShardSchema so that it happens\n // after initial sync, and not when the shard schema is initially set up.\n await decommissionLegacyShard(lc, db, shard);\n}\n\nfunction getIncrementalMigrations(\n shard: ShardConfig,\n replicaVersion?: string,\n): IncrementalMigrationMap {\n const shardConfigTable = `${upstreamSchema(shard)}.shardConfig`;\n\n return {\n 4: {\n migrateSchema: () => {\n throw new AutoResetSignal('resetting to upgrade shard schema');\n },\n minSafeVersion: 3,\n },\n\n // v5 changes the upstream schema organization from \"zero_{SHARD_ID}\" to\n // the \"{APP_ID}_0\". An incremental migration indicates that the previous\n // SHARD_ID was \"0\" and the new APP_ID is \"zero\" (i.e. the default values\n // for those options). In this case, the upstream format is identical, and\n // no migration is necessary. However, the version is bumped to v5 to\n // indicate that it was created with the {APP_ID} configuration and should\n // not be decommissioned as a legacy shard.\n 5: {},\n\n 6: {\n migrateSchema: async (lc, sql) => {\n assert(\n replicaVersion,\n `replicaVersion is always passed for incremental migrations`,\n );\n await Promise.all([\n sql`\n ALTER TABLE ${sql(shardConfigTable)} ADD \"replicaVersion\" TEXT`,\n sql`\n UPDATE ${sql(shardConfigTable)} SET ${sql({replicaVersion})}`,\n ]);\n lc.info?.(\n `Recorded replicaVersion ${replicaVersion} in upstream shardConfig`,\n );\n },\n },\n\n // Updates the DDL event trigger protocol to v2, and adds support for\n // ALTER SCHEMA x RENAME TO y\n 7: {\n migrateSchema: async (lc, sql) => {\n const [{publications}] = await sql<{publications: string[]}[]>`\n SELECT publications FROM ${sql(shardConfigTable)}`;\n await setupTriggers(lc, sql, {...shard, publications});\n lc.info?.(`Upgraded to v2 event triggers`);\n },\n },\n\n // Adds support for non-disruptive resyncs, which tracks multiple\n // replicas with different slot names.\n 8: {\n migrateSchema: async (lc, sql) => {\n const legacyShardConfigSchema = v.object({\n replicaVersion: v.string().nullable(),\n initialSchema: publishedSchema.nullable(),\n });\n const result = await sql`\n SELECT \"replicaVersion\", \"initialSchema\" FROM ${sql(shardConfigTable)}`;\n assert(\n result.length === 1,\n () => `Expected exactly one shardConfig row, got ${result.length}`,\n );\n const {replicaVersion, initialSchema} = v.parse(\n result[0],\n legacyShardConfigSchema,\n 'passthrough',\n );\n\n await Promise.all([\n sql`\n CREATE TABLE ${sql(upstreamSchema(shard))}.replicas (\n \"slot\" TEXT PRIMARY KEY,\n \"version\" TEXT NOT NULL,\n \"initialSchema\" JSON NOT NULL\n );\n `,\n sql`\n INSERT INTO ${sql(upstreamSchema(shard))}.replicas ${sql({\n slot: legacyReplicationSlot(shard),\n version: replicaVersion,\n initialSchema,\n })}\n `,\n sql`\n ALTER TABLE ${sql(shardConfigTable)} DROP \"replicaVersion\", DROP \"initialSchema\"\n `,\n ]);\n lc.info?.(`Upgraded schema to support non-disruptive resyncs`);\n },\n },\n\n // Fixes field ordering of compound indexes. This incremental migration\n // only fixes indexes resulting from new schema changes. A full resync is\n // required to fix existing indexes.\n //\n // The migration has been subsumed by the identical logic for migrating\n // to v12 (i.e. a trigger upgrade).\n 9: {},\n\n // Adds the `mutations` table used to track mutation results.\n 10: {\n migrateSchema: async (lc, sql) => {\n await sql.unsafe(/*sql*/ `\n ${getMutationsTableDefinition(upstreamSchema(shard))}\n ALTER PUBLICATION ${id(metadataPublicationName(shard.appID, shard.shardNum))} ADD TABLE ${id(upstreamSchema(shard))}.\"mutations\";\n `);\n lc.info?.('Upgraded schema with new mutations table');\n },\n },\n\n // Formerly dropped the schemaVersions table, but restored in the v13\n // migration for rollback safety.\n 11: {},\n\n // Upgrade DDL trigger to query schemaOID, needed information for auto-backfill.\n // (subsumed by v14)\n 12: {},\n\n // Recreates the legacy schemaVersions table that was prematurely dropped\n // in the (former) v11 migration. It needs to remain present for at least one\n // release in order to be rollback safe.\n //\n // TODO: Drop the table once a release that no longer reads the table has\n // been rolled out.\n 13: {\n migrateSchema: async (_, sql) => {\n await sql`\n CREATE TABLE IF NOT EXISTS ${sql(upstreamSchema(shard))}.\"schemaVersions\" (\n \"minSupportedVersion\" INT4,\n \"maxSupportedVersion\" INT4,\n \"lock\" BOOL PRIMARY KEY DEFAULT true CHECK (lock)\n );`;\n await sql`\n INSERT INTO ${sql(upstreamSchema(shard))}.\"schemaVersions\" \n (\"lock\", \"minSupportedVersion\", \"maxSupportedVersion\")\n VALUES (true, 1, 1)\n ON CONFLICT DO NOTHING;\n `;\n },\n },\n\n // Upgrade DDL trigger to log more info to PG logs.\n // (subsumed by v16)\n 14: {},\n\n // Add initialSyncContext column to replicas table.\n 15: {\n migrateSchema: async (_, sql) => {\n await sql`\n ALTER TABLE ${sql(upstreamSchema(shard))}.replicas\n ADD COLUMN \"initialSyncContext\" JSON,\n ADD COLUMN \"subscriberContext\" JSON\n `;\n },\n },\n\n // Upgrade DDL trigger to fire on all ALTER TABLE statements\n // to catch the *removal* of a table from the published set.\n 16: {\n migrateSchema: async (lc, sql) => {\n const [{publications}] = await sql<{publications: string[]}[]>`\n SELECT publications FROM ${sql(shardConfigTable)}`;\n await setupTriggers(lc, sql, {...shard, publications});\n lc.info?.(`Upgraded DDL event triggers`);\n },\n },\n };\n}\n\nexport async function decommissionLegacyShard(\n lc: LogContext,\n db: PostgresDB,\n shard: ShardConfig,\n) {\n if (shard.appID !== 'zero') {\n // When migration from non-default shard ids, e.g. \"zero_prod\" => \"prod_0\",\n // clean up the old \"zero_prod\" shard if it is pre-v5. Note that the v5\n // check is important to guard against cleaning up a **new** \"zero_0\" app\n // that coexists with the current App (with app-id === \"0\").\n const versionHistory = await getVersionHistory(db, `zero_${shard.appID}`);\n if (versionHistory !== null && versionHistory.schemaVersion < 5) {\n await decommissionShard(lc, db, 'zero', shard.appID);\n }\n }\n}\n"],"names":["lc","v.object","v.string","replicaVersion","v.parse"],"mappings":";;;;;;;;;;AA0BA,eAAsB,kBACpB,IACA,IACA,OACe;AACf,QAAM,eAA0B;AAAA,IAC9B,eAAe,CAACA,KAAI,OAAO,0BAA0BA,KAAI,IAAI,KAAK;AAAA,IAClE,gBAAgB;AAAA,EAAA;AAElB,QAAM;AAAA,IACJ;AAAA,IACA,kBAAkB,MAAM,KAAK;AAAA,IAC7B,eAAe,KAAK;AAAA,IACpB;AAAA,IACA;AAAA;AAAA;AAAA;A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S,CAAC;IAC5C,YAAY,CAAC,EAAE,YAAY,GAAG,SAAS,CAAC;IACxC,UAAU,CAAC,EAAE,OAAO,GAAG,SAAS,CAAC;IACjC,UAAU,EAAE,GAAG,CAAC,MAAM,EAAE,cAAc,CAAC,CAAC;IACxC,UAAU,CAAC,EAAE,OAAO,GAAG,SAAS,CAAC;CAClC,CAAC;AAEF,wBAAsB,MAAM,CAC1B,EAAE,EAAE,UAAU,EACd,YAAY,EAAE,YAAY,EAC1B,GAAG,EAAE,GAAG,EACR,aAAa,EAAE,OAAO,EACtB,OAAO,EAAE,aAAa,EACtB,YAAY,EAAE,MAAM,OAAO,CAAC,IAAI,CAAC,GAChC,OAAO,CAAC,kBAAkB,CAAC,CAwI7B"}
|
|
@@ -6,6 +6,8 @@ import { sleep } from "../../../shared/src/sleep.js";
|
|
|
6
6
|
import "../../../zero-protocol/src/ast.js";
|
|
7
7
|
import { hashOfAST } from "../../../zero-protocol/src/query-hash.js";
|
|
8
8
|
import { buildPipeline } from "../../../zql/src/builder/builder.js";
|
|
9
|
+
import { skipYields } from "../../../zql/src/ivm/operator.js";
|
|
10
|
+
import { resolveSimpleScalarSubqueries } from "../../../zqlite/src/resolve-scalar-subqueries.js";
|
|
9
11
|
import { transformAndHashQuery } from "../auth/read-authorizer.js";
|
|
10
12
|
import { hydrate } from "./view-syncer/pipeline-driver.js";
|
|
11
13
|
async function runAst(lc, clientSchema, ast, isTransformed, options, yieldProcess) {
|
|
@@ -39,8 +41,22 @@ async function runAst(lc, clientSchema, ast, isTransformed, options, yieldProces
|
|
|
39
41
|
).transformedAst;
|
|
40
42
|
result.afterPermissions = await formatOutput(ast.table + astToZQL(ast));
|
|
41
43
|
}
|
|
42
|
-
const
|
|
44
|
+
const executor = (subqueryAST, childField) => {
|
|
45
|
+
const input = buildPipeline(subqueryAST, host, "scalar-subquery");
|
|
46
|
+
let node;
|
|
47
|
+
for (const n of skipYields(input.fetch({}))) {
|
|
48
|
+
node ??= n;
|
|
49
|
+
}
|
|
50
|
+
input.destroy();
|
|
51
|
+
return node ? node.row[childField] ?? null : void 0;
|
|
52
|
+
};
|
|
53
|
+
const { ast: resolvedAst } = resolveSimpleScalarSubqueries(
|
|
43
54
|
ast,
|
|
55
|
+
options.tableSpecs,
|
|
56
|
+
executor
|
|
57
|
+
);
|
|
58
|
+
const pipeline = buildPipeline(
|
|
59
|
+
resolvedAst,
|
|
44
60
|
host,
|
|
45
61
|
"query-id",
|
|
46
62
|
options.costModel,
|
|
@@ -51,7 +67,11 @@ async function runAst(lc, clientSchema, ast, isTransformed, options, yieldProces
|
|
|
51
67
|
let syncedRowCount = 0;
|
|
52
68
|
const rowsByTable = {};
|
|
53
69
|
const seenByTable = /* @__PURE__ */ new Set();
|
|
54
|
-
for (const rowChange of hydrate(
|
|
70
|
+
for (const rowChange of hydrate(
|
|
71
|
+
pipeline,
|
|
72
|
+
hashOfAST(resolvedAst),
|
|
73
|
+
clientSchema
|
|
74
|
+
)) {
|
|
55
75
|
if (rowChange === "yield") {
|
|
56
76
|
await yieldProcess();
|
|
57
77
|
continue;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"run-ast.js","sources":["../../../../../zero-cache/src/services/run-ast.ts"],"sourcesContent":["import type {LogContext} from '@rocicorp/logger';\n// @circular-dep-ignore\nimport {astToZQL} from '../../../ast-to-zql/src/ast-to-zql.ts';\n// @circular-dep-ignore\nimport {formatOutput} from '../../../ast-to-zql/src/format.ts';\nimport {assert} from '../../../shared/src/asserts.ts';\nimport {must} from '../../../shared/src/must.ts';\nimport {sleep} from '../../../shared/src/sleep.ts';\nimport type {AnalyzeQueryResult} from '../../../zero-protocol/src/analyze-query-result.ts';\nimport type {AST} from '../../../zero-protocol/src/ast.ts';\nimport {mapAST} from '../../../zero-protocol/src/ast.ts';\nimport type {ClientSchema} from '../../../zero-protocol/src/client-schema.ts';\nimport type {Row} from '../../../zero-protocol/src/data.ts';\nimport {hashOfAST} from '../../../zero-protocol/src/query-hash.ts';\nimport type {PermissionsConfig} from '../../../zero-schema/src/compiled-permissions.ts';\nimport type {NameMapper} from '../../../zero-schema/src/name-mapper.ts';\nimport {\n buildPipeline,\n type BuilderDelegate,\n} from '../../../zql/src/builder/builder.ts';\nimport type {ConnectionCostModel} from '../../../zql/src/planner/planner-connection.ts';\nimport type {PlanDebugger} from '../../../zql/src/planner/planner-debug.ts';\nimport type {Database} from '../../../zqlite/src/db.ts';\nimport type {JWTAuth} from '../auth/auth.ts';\nimport {transformAndHashQuery} from '../auth/read-authorizer.ts';\nimport type {LiteAndZqlSpec} from '../db/specs.ts';\nimport {hydrate} from './view-syncer/pipeline-driver.ts';\n\nexport type RunAstOptions = {\n applyPermissions?: boolean | undefined;\n auth?: JWTAuth | undefined;\n clientToServerMapper?: NameMapper | undefined;\n costModel?: ConnectionCostModel | undefined;\n db: Database;\n host: BuilderDelegate;\n permissions?: PermissionsConfig | undefined;\n planDebugger?: PlanDebugger | undefined;\n syncedRows?: boolean | undefined;\n tableSpecs: Map<string, LiteAndZqlSpec>;\n vendedRows?: boolean | undefined;\n};\n\nexport async function runAst(\n lc: LogContext,\n clientSchema: ClientSchema,\n ast: AST,\n isTransformed: boolean,\n options: RunAstOptions,\n yieldProcess: () => Promise<void>,\n): Promise<AnalyzeQueryResult> {\n const {clientToServerMapper, permissions, host} = options;\n const result: AnalyzeQueryResult = {\n warnings: [],\n syncedRows: undefined,\n syncedRowCount: 0,\n start: 0,\n end: 0,\n elapsed: 0,\n afterPermissions: undefined,\n readRows: undefined,\n readRowCountsByQuery: {},\n readRowCount: undefined,\n };\n\n if (!isTransformed) {\n // map the AST to server names if not already transformed\n ast = mapAST(ast, must(clientToServerMapper));\n }\n if (options.applyPermissions) {\n const auth = options.auth;\n if (!auth) {\n result.warnings.push(\n 'No auth data provided. Permission rules will compare to `NULL` wherever an auth data field is referenced.',\n );\n }\n ast = transformAndHashQuery(\n lc,\n 'clientGroupIDForAnalyze',\n ast,\n must(permissions),\n auth,\n false,\n ).transformedAst;\n result.afterPermissions = await formatOutput(ast.table + astToZQL(ast));\n }\n\n const
|
|
1
|
+
{"version":3,"file":"run-ast.js","sources":["../../../../../zero-cache/src/services/run-ast.ts"],"sourcesContent":["import type {LogContext} from '@rocicorp/logger';\n// @circular-dep-ignore\nimport {astToZQL} from '../../../ast-to-zql/src/ast-to-zql.ts';\n// @circular-dep-ignore\nimport {formatOutput} from '../../../ast-to-zql/src/format.ts';\nimport {assert} from '../../../shared/src/asserts.ts';\nimport {must} from '../../../shared/src/must.ts';\nimport {sleep} from '../../../shared/src/sleep.ts';\nimport type {AnalyzeQueryResult} from '../../../zero-protocol/src/analyze-query-result.ts';\nimport type {AST, LiteralValue} from '../../../zero-protocol/src/ast.ts';\nimport {mapAST} from '../../../zero-protocol/src/ast.ts';\nimport type {ClientSchema} from '../../../zero-protocol/src/client-schema.ts';\nimport type {Row} from '../../../zero-protocol/src/data.ts';\nimport {hashOfAST} from '../../../zero-protocol/src/query-hash.ts';\nimport type {PermissionsConfig} from '../../../zero-schema/src/compiled-permissions.ts';\nimport type {NameMapper} from '../../../zero-schema/src/name-mapper.ts';\nimport {\n buildPipeline,\n type BuilderDelegate,\n} from '../../../zql/src/builder/builder.ts';\nimport type {Node} from '../../../zql/src/ivm/data.ts';\nimport {skipYields} from '../../../zql/src/ivm/operator.ts';\nimport type {ConnectionCostModel} from '../../../zql/src/planner/planner-connection.ts';\nimport type {PlanDebugger} from '../../../zql/src/planner/planner-debug.ts';\nimport type {Database} from '../../../zqlite/src/db.ts';\nimport {resolveSimpleScalarSubqueries} from '../../../zqlite/src/resolve-scalar-subqueries.ts';\nimport type {JWTAuth} from '../auth/auth.ts';\nimport {transformAndHashQuery} from '../auth/read-authorizer.ts';\nimport type {LiteAndZqlSpec} from '../db/specs.ts';\nimport {hydrate} from './view-syncer/pipeline-driver.ts';\n\nexport type RunAstOptions = {\n applyPermissions?: boolean | undefined;\n auth?: JWTAuth | undefined;\n clientToServerMapper?: NameMapper | undefined;\n costModel?: ConnectionCostModel | undefined;\n db: Database;\n host: BuilderDelegate;\n permissions?: PermissionsConfig | undefined;\n planDebugger?: PlanDebugger | undefined;\n syncedRows?: boolean | undefined;\n tableSpecs: Map<string, LiteAndZqlSpec>;\n vendedRows?: boolean | undefined;\n};\n\nexport async function runAst(\n lc: LogContext,\n clientSchema: ClientSchema,\n ast: AST,\n isTransformed: boolean,\n options: RunAstOptions,\n yieldProcess: () => Promise<void>,\n): Promise<AnalyzeQueryResult> {\n const {clientToServerMapper, permissions, host} = options;\n const result: AnalyzeQueryResult = {\n warnings: [],\n syncedRows: undefined,\n syncedRowCount: 0,\n start: 0,\n end: 0,\n elapsed: 0,\n afterPermissions: undefined,\n readRows: undefined,\n readRowCountsByQuery: {},\n readRowCount: undefined,\n };\n\n if (!isTransformed) {\n // map the AST to server names if not already transformed\n ast = mapAST(ast, must(clientToServerMapper));\n }\n if (options.applyPermissions) {\n const auth = options.auth;\n if (!auth) {\n result.warnings.push(\n 'No auth data provided. Permission rules will compare to `NULL` wherever an auth data field is referenced.',\n );\n }\n ast = transformAndHashQuery(\n lc,\n 'clientGroupIDForAnalyze',\n ast,\n must(permissions),\n auth,\n false,\n ).transformedAst;\n result.afterPermissions = await formatOutput(ast.table + astToZQL(ast));\n }\n\n // Resolve scalar subqueries (e.g. whereExists with {scalar: true}) to\n // literal equality conditions so that SQLite can use indexes effectively.\n // Without this, correlated subqueries get stripped from SQL filters and\n // queries on large tables fall back to full table scans.\n const executor = (\n subqueryAST: AST,\n childField: string,\n ): LiteralValue | null | undefined => {\n const input = buildPipeline(subqueryAST, host, 'scalar-subquery');\n // Consume the full stream rather than using first() to avoid\n // triggering early return on Take's #initialFetch assertion.\n // The subquery AST already has limit: 1, so at most one row is produced.\n let node: Node | undefined;\n for (const n of skipYields(input.fetch({}))) {\n node ??= n;\n }\n input.destroy();\n return node ? ((node.row[childField] as LiteralValue) ?? null) : undefined;\n };\n\n const {ast: resolvedAst} = resolveSimpleScalarSubqueries(\n ast,\n options.tableSpecs,\n executor,\n );\n\n const pipeline = buildPipeline(\n resolvedAst,\n host,\n 'query-id',\n options.costModel,\n lc,\n options.planDebugger,\n );\n\n const start = performance.now();\n\n let syncedRowCount = 0;\n const rowsByTable: Record<string, Row[]> = {};\n const seenByTable: Set<string> = new Set();\n for (const rowChange of hydrate(\n pipeline,\n hashOfAST(resolvedAst),\n clientSchema,\n )) {\n if (rowChange === 'yield') {\n await yieldProcess();\n continue;\n }\n assert(rowChange.type === 'add', 'Hydration only handles add row changes');\n\n // yield to other tasks to avoid blocking for too long\n if (syncedRowCount % 10 === 0) {\n await Promise.resolve();\n }\n if (syncedRowCount % 100 === 0) {\n await sleep(1);\n }\n\n let rows: Row[] = rowsByTable[rowChange.table];\n const s = rowChange.table + '.' + JSON.stringify(rowChange.row);\n if (seenByTable.has(s)) {\n continue; // skip duplicates\n }\n syncedRowCount++;\n seenByTable.add(s);\n if (options.syncedRows) {\n if (!rows) {\n rows = [];\n rowsByTable[rowChange.table] = rows;\n }\n rows.push(rowChange.row);\n }\n }\n\n const end = performance.now();\n if (options.syncedRows) {\n result.syncedRows = rowsByTable;\n }\n result.start = start;\n result.end = end;\n result.elapsed = end - start;\n\n // Always include the count of synced and vended rows.\n result.syncedRowCount = syncedRowCount;\n result.readRowCountsByQuery = host.debug?.getVendedRowCounts() ?? {};\n let readRowCount = 0;\n for (const c of Object.values(result.readRowCountsByQuery)) {\n for (const v of Object.values(c)) {\n readRowCount += v;\n }\n }\n result.readRowCount = readRowCount;\n result.dbScansByQuery = host.debug?.getNVisitCounts() ?? {};\n\n if (options.vendedRows) {\n result.readRows = host.debug?.getVendedRows();\n }\n return result;\n}\n"],"names":[],"mappings":";;;;;;;;;;;;AA6CA,eAAsB,OACpB,IACA,cACA,KACA,eACA,SACA,cAC6B;AAC7B,QAAM,EAAuB,aAAa,KAAA,IAAQ;AAClD,QAAM,SAA6B;AAAA,IACjC,UAAU,CAAA;AAAA,IACV,YAAY;AAAA,IACZ,gBAAgB;AAAA,I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"Expected new version to be greater than current version"
|
|
76
|
+
);
|
|
74
77
|
this._cvr.version = version;
|
|
75
78
|
return version;
|
|
76
79
|
}
|
|
@@ -495,7 +498,10 @@ class CVRQueryDrivenUpdater extends CVRUpdater {
|
|
|
495
498
|
* generated from {@link received} are sent.
|
|
496
499
|
*/
|
|
497
500
|
#assertNewVersion() {
|
|
498
|
-
assert(
|
|
501
|
+
assert(
|
|
502
|
+
cmpVersions(this._orig.version, this._cvr.version) < 0,
|
|
503
|
+
"Expected CVR version to have been bumped above original"
|
|
504
|
+
);
|
|
499
505
|
return this._cvr.version;
|
|
500
506
|
}
|
|
501
507
|
updatedVersion() {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"cvr.js","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 {\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 {\n cmpVersions,\n maxVersion,\n oneAfter,\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(cmpVersions(this._cvr.version, version) < 0);\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 = [...union(current, needed)].sort(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 = [...difference(current, remove)].sort(\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 * 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\n #existingRows: Promise<Iterable<RowRecord>> | undefined = undefined;\n\n /**\n * @param stateVersion The `stateVersion` at which the queries were executed.\n */\n constructor(\n cvrStore: CVRStore,\n cvr: CVRSnapshot,\n stateVersion: LexiVersion,\n replicaVersion: string,\n ) {\n super(cvrStore, cvr, replicaVersion);\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 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(): CVRVersion {\n assert(cmpVersions(this._orig.version, this._cvr.version) < 0);\n return this._cvr.version;\n }\n\n updatedVersion(): CVRVersion {\n return this._cvr.version;\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\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 patches.push({\n toVersion: this._cvr.version,\n patch: {type: 'row', op: 'del', id: deletedID},\n });\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 // 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 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 [...inactive.values()].sort((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"],"names":["upstreamSchema","ErrorOrigin.ZeroCache"],"mappings":";;;;;;;;;;;;;;;;;;AAgFA,MAAM,uBAAuB;AAC7B,MAAM,mCAAmC;AAEzC,SAAS,kBACP,OACoC;AACpC,MAAI,MAAM,SAAS,YAAY;AAE7B,UAAM,IAAI,MAAM,YAAY,MAAM,EAAE,+BAA+B;AAAA,EACrE;AACF;AAEO,SAAS,wBACdA,iBACA,eACqB;AACrB,SAAO;AAAA,IACL,IAAI;AAAA,IACJ,MAAM;AAAA,IACN,KAAK;AAAA,MACH,QAAQ;AAAA,MACR,OAAO,GAAGA,eAAc;AAAA,MACxB,OAAO;AAAA,QACL,MAAM;AAAA,QACN,YAAY;AAAA,UACV;AAAA,YACE,MAAM;AAAA,YACN,MAAM;AAAA,cACJ,MAAM;AAAA,cACN,MAAM;AAAA,YAAA;AAAA,YAER,IAAI;AAAA,YACJ,OAAO;AAAA,cACL,MAAM;AAAA,cACN,OAAO;AAAA,YAAA;AAAA,UACT;AAAA,QACF;AAAA,MACF;AAAA,MAEF,SAAS;AAAA,QACP,CAAC,iBAAiB,KAAK;AAAA,QACvB,CAAC,YAAY,KAAK;AAAA,QAClB,CAAC,cAAc,KAAK;AAAA,MAAA;AAAA,IACtB;AAAA,EACF;AAEJ;AAWO,MAAM,WAAW;AAAA,EACH;AAAA,EACA;AAAA,EAEA;AAAA;AAAA;AAAA;AAAA;AAAA,EAMnB,YACE,UACA,KACA,gBACA;AACA,SAAK,YAAY;AACjB,SAAK,QAAQ;AACb,SAAK,OAAO,gBAAgB,GAAG;AAC/B,SAAK,KAAK,iBAAiB;AAAA,EAC7B;AA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;AAEF,SAAO;AAAA,IACL;AAAA,IACA,MAAM;AAAA,IACN;AAAA,IACA;AAAA,IACA,aAAa,CAAA;AAAA,EAAC;AAElB;"}
|
|
1
|
+
{"version":3,"file":"cvr.js","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 {\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 {\n cmpVersions,\n maxVersion,\n oneAfter,\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 = [...union(current, needed)].sort(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 = [...difference(current, remove)].sort(\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 * 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\n #existingRows: Promise<Iterable<RowRecord>> | undefined = undefined;\n\n /**\n * @param stateVersion The `stateVersion` at which the queries were executed.\n */\n constructor(\n cvrStore: CVRStore,\n cvr: CVRSnapshot,\n stateVersion: LexiVersion,\n replicaVersion: string,\n ) {\n super(cvrStore, cvr, replicaVersion);\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 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(): CVRVersion {\n assert(\n cmpVersions(this._orig.version, this._cvr.version) < 0,\n 'Expected CVR version to have been bumped above original',\n );\n return this._cvr.version;\n }\n\n updatedVersion(): CVRVersion {\n return this._cvr.version;\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\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 patches.push({\n toVersion: this._cvr.version,\n patch: {type: 'row', op: 'del', id: deletedID},\n });\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 // 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 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 [...inactive.values()].sort((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"],"names":["upstreamSchema","ErrorOrigin.ZeroC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S,aAAa,IACrD,iBAAiB,aAAa,IAAI,YAClC;AACA,mBAAS,MAAM;AACf,mBAAS,gBAAgB;AAAA,QAC3B;AAAA,MACF,OAAO;AACL,iBAAS,IAAI,SAAS;AAAA,UACpB,MAAM;AAAA,UACN;AAAA,UACA,KAAK;AAAA,QAAA,CACN;AAAA,MACH;AAAA,IACF;AAAA,EACF;AAGA,SAAO,CAAC,GAAG,SAAS,OAAA,CAAQ,EAAE,KAAK,CAAC,GAAG,MAAM;AAC3C,QAAI,EAAE,QAAQ,EAAE,KAAK;AACnB,aACE,iBAAiB,EAAE,aAAa,IAAI,iBAAiB,EAAE,aAAa;AAAA,IAExE;AACA,WACE,iBAAiB,EAAE,aAAa,IAChC,EAAE,MACF,iBAAiB,EAAE,aAAa,IAChC,EAAE;AAAA,EAEN,CAAC;AACH;AAEO,SAAS,iBAAiB,KAAgC;AAC/D,MAAI;AACJ,aAAW,EAAC,eAAe,IAAA,KAAQ,mBAAmB,GAAG,GAAG;AAC1D,UAAM,SAAS,iBAAiB,aAAa,IAAI;AACjD,QAAI,SAAS,UAAa,SAAS,MAAM;AACvC,aAAO;AAAA,IACT;AAAA,EACF;AACA,SAAO;AACT;AAEA,SAAS,eACP,IACA,KACA,MACA,MACuC;AACvC,MAAI,QAAQ,QAAW;AACrB;AAAA,MACE,SAAS,UAAa,SAAS;AAAA,MAC/B;AAAA,IAAA;AAEF,WAAO;AAAA,MACL;AAAA,MACA,MAAM;AAAA,MACN;AAAA,MACA,aAAa,CAAA;AAAA,IAAC;AAAA,EAElB;AAEA;AAAA,IACE,SAAS,UAAa,SAAS;AAAA,IAC/B;AAAA,EAAA;AAEF,SAAO;AAAA,IACL;AAAA,IACA,MAAM;AAAA,IACN;AAAA,IACA;AAAA,IACA,aAAa,CAAA;AAAA,EAAC;AAElB;"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"pipeline-driver.d.ts","sourceRoot":"","sources":["../../../../../../zero-cache/src/services/view-syncer/pipeline-driver.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAC,UAAU,EAAC,MAAM,kBAAkB,CAAC;AAIjD,OAAO,KAAK,EAAC,GAAG,EAAe,MAAM,sCAAsC,CAAC;AAC5E,OAAO,KAAK,EAAC,YAAY,EAAC,MAAM,gDAAgD,CAAC;AACjF,OAAO,KAAK,EAAC,GAAG,EAAC,MAAM,uCAAuC,CAAC;AAC/D,OAAO,KAAK,EAAC,UAAU,EAAC,MAAM,8CAA8C,CAAC;AAQ7E,OAAO,
|
|
1
|
+
{"version":3,"file":"pipeline-driver.d.ts","sourceRoot":"","sources":["../../../../../../zero-cache/src/services/view-syncer/pipeline-driver.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAC,UAAU,EAAC,MAAM,kBAAkB,CAAC;AAIjD,OAAO,KAAK,EAAC,GAAG,EAAe,MAAM,sCAAsC,CAAC;AAC5E,OAAO,KAAK,EAAC,YAAY,EAAC,MAAM,gDAAgD,CAAC;AACjF,OAAO,KAAK,EAAC,GAAG,EAAC,MAAM,uCAAuC,CAAC;AAC/D,OAAO,KAAK,EAAC,UAAU,EAAC,MAAM,8CAA8C,CAAC;AAQ7E,OAAO,EAEL,KAAK,KAAK,EAEX,MAAM,qCAAqC,CAAC;AAS7C,OAAO,KAAK,EAAC,kBAAkB,EAAC,MAAM,4CAA4C,CAAC;AAQnF,OAAO,EAEL,KAAK,iBAAiB,EACvB,MAAM,gCAAgC,CAAC;AACxC,OAAO,KAAK,EAAC,SAAS,EAAE,UAAU,EAAC,MAAM,6BAA6B,CAAC;AAOvE,OAAO,KAAK,EAAC,iBAAiB,EAAC,MAAM,oCAAoC,CAAC;AAC1E,OAAO,EAAC,KAAK,MAAM,EAAC,MAAM,wBAAwB,CAAC;AACnD,OAAO,EAAiB,KAAK,OAAO,EAAC,MAAM,uBAAuB,CAAC;AAGnE,OAAO,KAAK,EAAC,WAAW,EAAC,MAAM,kBAAkB,CAAC;AAGlD,MAAM,MAAM,MAAM,GAAG;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ACzB,QAAQ,CAAC,SAAS,GAAG,OAAO,CAAC,CAQ/B;AAED,wBAAiB,eAAe,CAC9B,KAAK,EAAE,KAAK,EACZ,IAAI,EAAE,MAAM,EACZ,WAAW,EAAE,GAAG,CAAC,MAAM,EAAE,UAAU,CAAC,GACnC,QAAQ,CAAC,SAAS,GAAG,OAAO,CAAC,CAQ/B"}
|
|
@@ -29,6 +29,7 @@ class PipelineDriver {
|
|
|
29
29
|
#logConfig;
|
|
30
30
|
#config;
|
|
31
31
|
#tableSpecs = /* @__PURE__ */ new Map();
|
|
32
|
+
#allTableNames = /* @__PURE__ */ new Set();
|
|
32
33
|
#costModels;
|
|
33
34
|
#yieldThresholdMs;
|
|
34
35
|
#streamer = null;
|
|
@@ -89,6 +90,7 @@ class PipelineDriver {
|
|
|
89
90
|
}
|
|
90
91
|
this.#pipelines.clear();
|
|
91
92
|
this.#tables.clear();
|
|
93
|
+
this.#allTableNames.clear();
|
|
92
94
|
this.#initAndResetCommon(clientSchema);
|
|
93
95
|
}
|
|
94
96
|
#initAndResetCommon(clientSchema) {
|
|
@@ -107,6 +109,10 @@ class PipelineDriver {
|
|
|
107
109
|
this.#tableSpecs,
|
|
108
110
|
fullTables
|
|
109
111
|
);
|
|
112
|
+
this.#allTableNames.clear();
|
|
113
|
+
for (const table of fullTables.keys()) {
|
|
114
|
+
this.#allTableNames.add(table);
|
|
115
|
+
}
|
|
110
116
|
const primaryKeys = this.#primaryKeys ?? /* @__PURE__ */ new Map();
|
|
111
117
|
this.#primaryKeys = primaryKeys;
|
|
112
118
|
primaryKeys.clear();
|
|
@@ -414,7 +420,10 @@ class PipelineDriver {
|
|
|
414
420
|
this.initialized(),
|
|
415
421
|
"Pipeline driver must be initialized before advancing"
|
|
416
422
|
);
|
|
417
|
-
const diff = this.#snapshotter.advance(
|
|
423
|
+
const diff = this.#snapshotter.advance(
|
|
424
|
+
this.#tableSpecs,
|
|
425
|
+
this.#allTableNames
|
|
426
|
+
);
|
|
418
427
|
const { prev, curr, changes } = diff;
|
|
419
428
|
this.#lc.debug?.(
|
|
420
429
|
`advance ${prev.version} => ${curr.version}: ${changes} changes`
|