@rocicorp/zero 1.12.0 → 1.13.0-canary.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (177) hide show
  1. package/out/shared/src/bigint-json.d.ts +6 -0
  2. package/out/shared/src/bigint-json.d.ts.map +1 -1
  3. package/out/shared/src/bigint-json.js +14 -1
  4. package/out/shared/src/bigint-json.js.map +1 -1
  5. package/out/shared/src/objects.d.ts +7 -0
  6. package/out/shared/src/objects.d.ts.map +1 -1
  7. package/out/shared/src/objects.js +10 -1
  8. package/out/shared/src/objects.js.map +1 -1
  9. package/out/shared/src/resolver.d.ts.map +1 -1
  10. package/out/shared/src/resolver.js +12 -1
  11. package/out/shared/src/resolver.js.map +1 -1
  12. package/out/shared/src/valita.d.ts.map +1 -1
  13. package/out/shared/src/valita.js +2 -1
  14. package/out/shared/src/valita.js.map +1 -1
  15. package/out/z2s/src/compiler.d.ts.map +1 -1
  16. package/out/z2s/src/compiler.js +4 -2
  17. package/out/z2s/src/compiler.js.map +1 -1
  18. package/out/zero/package.js +2 -2
  19. package/out/zero/package.js.map +1 -1
  20. package/out/zero-cache/src/auth/write-authorizer.js +4 -3
  21. package/out/zero-cache/src/auth/write-authorizer.js.map +1 -1
  22. package/out/zero-cache/src/config/normalize.d.ts.map +1 -1
  23. package/out/zero-cache/src/config/normalize.js +3 -23
  24. package/out/zero-cache/src/config/normalize.js.map +1 -1
  25. package/out/zero-cache/src/config/zero-config.d.ts +1 -27
  26. package/out/zero-cache/src/config/zero-config.d.ts.map +1 -1
  27. package/out/zero-cache/src/config/zero-config.js +19 -47
  28. package/out/zero-cache/src/config/zero-config.js.map +1 -1
  29. package/out/zero-cache/src/custom/fetch.js +17 -2
  30. package/out/zero-cache/src/custom/fetch.js.map +1 -1
  31. package/out/zero-cache/src/db/create.js +45 -1
  32. package/out/zero-cache/src/db/create.js.map +1 -1
  33. package/out/zero-cache/src/db/lite-tables.d.ts.map +1 -1
  34. package/out/zero-cache/src/db/lite-tables.js +4 -3
  35. package/out/zero-cache/src/db/lite-tables.js.map +1 -1
  36. package/out/zero-cache/src/db/pg-copy-binary.js +61 -25
  37. package/out/zero-cache/src/db/pg-copy-binary.js.map +1 -1
  38. package/out/zero-cache/src/db/pg-to-lite.d.ts +17 -0
  39. package/out/zero-cache/src/db/pg-to-lite.d.ts.map +1 -1
  40. package/out/zero-cache/src/db/pg-to-lite.js +84 -1
  41. package/out/zero-cache/src/db/pg-to-lite.js.map +1 -1
  42. package/out/zero-cache/src/server/change-streamer.js +21 -30
  43. package/out/zero-cache/src/server/change-streamer.js.map +1 -1
  44. package/out/zero-cache/src/server/inspector-delegate.js +1 -1
  45. package/out/zero-cache/src/server/main.js +0 -1
  46. package/out/zero-cache/src/server/main.js.map +1 -1
  47. package/out/zero-cache/src/server/replicator.js +1 -1
  48. package/out/zero-cache/src/server/replicator.js.map +1 -1
  49. package/out/zero-cache/src/services/change-source/pg/backfill-stream.js +6 -5
  50. package/out/zero-cache/src/services/change-source/pg/backfill-stream.js.map +1 -1
  51. package/out/zero-cache/src/services/change-source/pg/change-source.js +50 -12
  52. package/out/zero-cache/src/services/change-source/pg/change-source.js.map +1 -1
  53. package/out/zero-cache/src/services/change-source/pg/initial-sync.js +64 -21
  54. package/out/zero-cache/src/services/change-source/pg/initial-sync.js.map +1 -1
  55. package/out/zero-cache/src/services/change-source/pg/replication-slots.js +11 -6
  56. package/out/zero-cache/src/services/change-source/pg/replication-slots.js.map +1 -1
  57. package/out/zero-cache/src/services/change-source/pg/schema/ddl.d.ts +13 -1
  58. package/out/zero-cache/src/services/change-source/pg/schema/ddl.d.ts.map +1 -1
  59. package/out/zero-cache/src/services/change-source/pg/schema/ddl.js +16 -3
  60. package/out/zero-cache/src/services/change-source/pg/schema/ddl.js.map +1 -1
  61. package/out/zero-cache/src/services/change-source/pg/schema/init.js +6 -4
  62. package/out/zero-cache/src/services/change-source/pg/schema/init.js.map +1 -1
  63. package/out/zero-cache/src/services/change-source/pg/schema/published.d.ts +1 -0
  64. package/out/zero-cache/src/services/change-source/pg/schema/published.d.ts.map +1 -1
  65. package/out/zero-cache/src/services/change-source/pg/schema/published.js +56 -12
  66. package/out/zero-cache/src/services/change-source/pg/schema/published.js.map +1 -1
  67. package/out/zero-cache/src/services/change-source/pg/schema/shard.d.ts +1 -0
  68. package/out/zero-cache/src/services/change-source/pg/schema/shard.d.ts.map +1 -1
  69. package/out/zero-cache/src/services/change-source/pg/schema/shard.js +35 -12
  70. package/out/zero-cache/src/services/change-source/pg/schema/shard.js.map +1 -1
  71. package/out/zero-cache/src/services/change-source/pg/schema/validation.d.ts +6 -1
  72. package/out/zero-cache/src/services/change-source/pg/schema/validation.d.ts.map +1 -1
  73. package/out/zero-cache/src/services/change-source/pg/schema/validation.js +25 -1
  74. package/out/zero-cache/src/services/change-source/pg/schema/validation.js.map +1 -1
  75. package/out/zero-cache/src/services/change-source/protocol/backfill-progress.js +6 -5
  76. package/out/zero-cache/src/services/change-source/protocol/backfill-progress.js.map +1 -1
  77. package/out/zero-cache/src/services/change-streamer/backfill-state.js +7 -6
  78. package/out/zero-cache/src/services/change-streamer/backfill-state.js.map +1 -1
  79. package/out/zero-cache/src/services/change-streamer/change-log-codec.js +2 -2
  80. package/out/zero-cache/src/services/change-streamer/change-log-codec.js.map +1 -1
  81. package/out/zero-cache/src/services/change-streamer/change-log-initializer.js +16 -199
  82. package/out/zero-cache/src/services/change-streamer/change-log-initializer.js.map +1 -1
  83. package/out/zero-cache/src/services/change-streamer/change-streamer-service.js +76 -127
  84. package/out/zero-cache/src/services/change-streamer/change-streamer-service.js.map +1 -1
  85. package/out/zero-cache/src/services/change-streamer/snapshot-reservations.js +1 -1
  86. package/out/zero-cache/src/services/change-streamer/snapshot-reservations.js.map +1 -1
  87. package/out/zero-cache/src/services/change-streamer/sqlite-change-log-catchup.js.map +1 -1
  88. package/out/zero-cache/src/services/change-streamer/sqlite-change-log-purge-scheduler.js +1 -1
  89. package/out/zero-cache/src/services/change-streamer/sqlite-change-log-read-router.js +15 -49
  90. package/out/zero-cache/src/services/change-streamer/sqlite-change-log-read-router.js.map +1 -1
  91. package/out/zero-cache/src/services/change-streamer/sqlite-change-log-reader.js +8 -2
  92. package/out/zero-cache/src/services/change-streamer/sqlite-change-log-reader.js.map +1 -1
  93. package/out/zero-cache/src/services/change-streamer/sqlite-change-log-writer.js +20 -36
  94. package/out/zero-cache/src/services/change-streamer/sqlite-change-log-writer.js.map +1 -1
  95. package/out/zero-cache/src/services/change-streamer/storer.js +32 -20
  96. package/out/zero-cache/src/services/change-streamer/storer.js.map +1 -1
  97. package/out/zero-cache/src/services/mutagen/mutagen.js +4 -2
  98. package/out/zero-cache/src/services/mutagen/mutagen.js.map +1 -1
  99. package/out/zero-cache/src/services/replicator/change-log-cookies.d.ts +0 -16
  100. package/out/zero-cache/src/services/replicator/change-log-cookies.d.ts.map +1 -1
  101. package/out/zero-cache/src/services/replicator/change-log-cookies.js +3 -95
  102. package/out/zero-cache/src/services/replicator/change-log-cookies.js.map +1 -1
  103. package/out/zero-cache/src/services/replicator/change-log-db.js +2 -2
  104. package/out/zero-cache/src/services/replicator/change-log-db.js.map +1 -1
  105. package/out/zero-cache/src/services/replicator/change-log-stream-writer.js +1 -30
  106. package/out/zero-cache/src/services/replicator/change-log-stream-writer.js.map +1 -1
  107. package/out/zero-cache/src/services/replicator/change-processor.js +83 -38
  108. package/out/zero-cache/src/services/replicator/change-processor.js.map +1 -1
  109. package/out/zero-cache/src/services/replicator/incremental-sync.js +7 -1
  110. package/out/zero-cache/src/services/replicator/incremental-sync.js.map +1 -1
  111. package/out/zero-cache/src/services/replicator/reporter/report-schema.d.ts +1 -0
  112. package/out/zero-cache/src/services/replicator/reporter/report-schema.d.ts.map +1 -1
  113. package/out/zero-cache/src/services/replicator/reporter/report-schema.js +4 -1
  114. package/out/zero-cache/src/services/replicator/reporter/report-schema.js.map +1 -1
  115. package/out/zero-cache/src/services/replicator/schema/change-log.d.ts.map +1 -1
  116. package/out/zero-cache/src/services/replicator/schema/change-log.js +2 -1
  117. package/out/zero-cache/src/services/replicator/schema/change-log.js.map +1 -1
  118. package/out/zero-cache/src/services/replicator/sqlite-change-log-observability.js +6 -102
  119. package/out/zero-cache/src/services/replicator/sqlite-change-log-observability.js.map +1 -1
  120. package/out/zero-cache/src/services/statz.d.ts.map +1 -1
  121. package/out/zero-cache/src/services/statz.js +1 -1
  122. package/out/zero-cache/src/services/statz.js.map +1 -1
  123. package/out/zero-cache/src/services/view-syncer/active-users-gauge.js +1 -1
  124. package/out/zero-cache/src/services/view-syncer/pipeline-driver.js +1 -1
  125. package/out/zero-cache/src/services/view-syncer/schema/init.js +3 -0
  126. package/out/zero-cache/src/services/view-syncer/schema/init.js.map +1 -1
  127. package/out/zero-cache/src/services/view-syncer/snapshot-row-cache.js +47 -3
  128. package/out/zero-cache/src/services/view-syncer/snapshot-row-cache.js.map +1 -1
  129. package/out/zero-cache/src/services/view-syncer/view-syncer.js +51 -6
  130. package/out/zero-cache/src/services/view-syncer/view-syncer.js.map +1 -1
  131. package/out/zero-cache/src/types/lite.d.ts +7 -0
  132. package/out/zero-cache/src/types/lite.d.ts.map +1 -1
  133. package/out/zero-cache/src/types/lite.js +12 -2
  134. package/out/zero-cache/src/types/lite.js.map +1 -1
  135. package/out/zero-cache/src/types/pg-types.d.ts +2 -1
  136. package/out/zero-cache/src/types/pg-types.d.ts.map +1 -1
  137. package/out/zero-cache/src/types/pg-types.js +2 -1
  138. package/out/zero-cache/src/types/pg-types.js.map +1 -1
  139. package/out/zero-cache/src/types/pg.d.ts +20 -0
  140. package/out/zero-cache/src/types/pg.d.ts.map +1 -1
  141. package/out/zero-cache/src/types/pg.js +64 -27
  142. package/out/zero-cache/src/types/pg.js.map +1 -1
  143. package/out/zero-cache/src/types/streams.d.ts +2 -0
  144. package/out/zero-cache/src/types/streams.d.ts.map +1 -1
  145. package/out/zero-cache/src/types/streams.js +2 -1
  146. package/out/zero-cache/src/types/streams.js.map +1 -1
  147. package/out/zero-cache/src/workers/replicator.js +7 -6
  148. package/out/zero-cache/src/workers/replicator.js.map +1 -1
  149. package/out/zero-cache/src/workers/syncer.js +18 -1
  150. package/out/zero-cache/src/workers/syncer.js.map +1 -1
  151. package/out/zero-client/src/client/crud-impl.js +1 -1
  152. package/out/zero-client/src/client/ivm-branch.js +1 -1
  153. package/out/zero-client/src/client/version.js +1 -1
  154. package/out/zero-protocol/src/client-schema.js +1 -1
  155. package/out/zero-protocol/src/down.d.ts +2 -2
  156. package/out/zero-schema/src/builder/schema-builder.js +1 -1
  157. package/out/zql/src/builder/builder.js +1 -1
  158. package/out/zql/src/ivm/aggregate.js +1 -1
  159. package/out/zql/src/ivm/flipped-join.js +1 -1
  160. package/out/zql/src/ivm/group-by.js +1 -1
  161. package/out/zql/src/ivm/join-index.js +1 -1
  162. package/out/zql/src/ivm/memory-source.js +1 -1
  163. package/out/zql/src/ivm/view-apply-change.js +1 -1
  164. package/out/zqlite/src/db.js +4 -1
  165. package/out/zqlite/src/db.js.map +1 -1
  166. package/out/zqlite/src/table-source.d.ts.map +1 -1
  167. package/out/zqlite/src/table-source.js +4 -2
  168. package/out/zqlite/src/table-source.js.map +1 -1
  169. package/package.json +2 -2
  170. package/out/zero-cache/src/services/change-streamer/change-log-compare-digest.js +0 -67
  171. package/out/zero-cache/src/services/change-streamer/change-log-compare-digest.js.map +0 -1
  172. package/out/zero-cache/src/services/change-streamer/change-log-transaction-hash.js +0 -39
  173. package/out/zero-cache/src/services/change-streamer/change-log-transaction-hash.js.map +0 -1
  174. package/out/zero-cache/src/services/change-streamer/shard-sampling.js +0 -19
  175. package/out/zero-cache/src/services/change-streamer/shard-sampling.js.map +0 -1
  176. package/out/zero-cache/src/services/change-streamer/sqlite-change-log-comparator.js +0 -417
  177. package/out/zero-cache/src/services/change-streamer/sqlite-change-log-comparator.js.map +0 -1
@@ -1 +1 @@
1
- {"version":3,"file":"shard.js","names":["v","v.parse"],"sources":["../../../../../../../../zero-cache/src/services/change-source/pg/schema/shard.ts"],"sourcesContent":["import {PG_INSUFFICIENT_PRIVILEGE} from '@drdgvhbh/postgres-error-codes';\nimport type {LogContext} from '@rocicorp/logger';\nimport {literal} from 'pg-format';\nimport postgres from 'postgres';\nimport {assert} from '../../../../../../shared/src/asserts.ts';\nimport {\n jsonObjectSchema,\n stringify,\n type JSONObject,\n} from '../../../../../../shared/src/bigint-json.ts';\nimport * as v from '../../../../../../shared/src/valita.ts';\nimport {Default} from '../../../../db/postgres-replica-identity-enum.ts';\nimport type {PostgresDB, PostgresTransaction} from '../../../../types/pg.ts';\nimport type {AppID, ShardConfig, ShardID} from '../../../../types/shards.ts';\nimport {appSchema, check, upstreamSchema} from '../../../../types/shards.ts';\nimport {id} from '../../../../types/sql.ts';\nimport {\n createEventFunctionStatements,\n createEventTriggerStatements,\n} from './ddl.ts';\nimport {\n getPublicationInfo,\n publishedSchema,\n type PublicationInfo,\n type PublishedSchema,\n} from './published.ts';\nimport {\n InitialSync,\n replicaStageSchema,\n type ReplicaStage,\n} from './replica-stage-enum.ts';\nimport {validate} from './validation.ts';\n\n/**\n * PostgreSQL unquoted identifiers must start with a letter or underscore\n * and contain only letters, digits, and underscores.\n */\nconst VALID_PUBLICATION_NAME = /^[a-zA-Z_][a-zA-Z0-9_]*$/;\n\n/**\n * Validates that a publication name is a valid PostgreSQL identifier.\n * This provides defense-in-depth against SQL injection when publication\n * names are used in replication commands.\n */\nexport function validatePublicationName(name: string): void {\n if (!VALID_PUBLICATION_NAME.test(name)) {\n throw new Error(\n `Invalid publication name \"${name}\". Publication names must start with a letter or underscore ` +\n `and contain only letters, digits, and underscores.`,\n );\n }\n if (name.length > 63) {\n throw new Error(\n `Publication name \"${name}\" exceeds PostgreSQL's 63-character identifier limit.`,\n );\n }\n}\n\nexport function internalPublicationPrefix({appID}: AppID) {\n return `_${appID}_`;\n}\n\nexport function legacyReplicationSlot({appID, shardNum}: ShardID) {\n return `${appID}_${shardNum}`;\n}\n\nexport function replicationSlotPrefix(shard: ShardID) {\n const {appID, shardNum} = check(shard);\n return `${appID}_${shardNum}_`;\n}\n\n/**\n * An expression used to match replication slots in the shard\n * in a Postgres `LIKE` operator.\n */\nexport function replicationSlotExpression(shard: ShardID) {\n // Underscores have a special meaning in LIKE values\n // so they have to be escaped.\n return `${replicationSlotPrefix(shard)}%`.replaceAll('_', '\\\\_');\n}\n\nfunction defaultPublicationName(appID: string, shardID: string | number) {\n return `_${appID}_public_${shardID}`;\n}\n\nexport function metadataPublicationName(\n appID: string,\n shardID: string | number,\n) {\n return `_${appID}_metadata_${shardID}`;\n}\n\n// The GLOBAL_SETUP must be idempotent as it can be run multiple times for different shards.\nfunction globalSetup(appID: AppID): string {\n const app = id(appSchema(appID));\n\n return /*sql*/ `\n CREATE SCHEMA IF NOT EXISTS ${app};\n\n CREATE TABLE IF NOT EXISTS ${app}.permissions (\n \"permissions\" JSONB,\n \"hash\" TEXT,\n\n -- Ensure that there is only a single row in the table.\n -- Application code can be agnostic to this column, and\n -- simply invoke UPDATE statements on the version columns.\n \"lock\" BOOL PRIMARY KEY DEFAULT true CHECK (lock)\n );\n\n CREATE OR REPLACE FUNCTION ${app}.set_permissions_hash()\n RETURNS TRIGGER AS $$\n BEGIN\n NEW.hash = md5(NEW.permissions::text);\n RETURN NEW;\n END;\n $$ LANGUAGE plpgsql;\n\n CREATE OR REPLACE TRIGGER on_set_permissions \n BEFORE INSERT OR UPDATE ON ${app}.permissions\n FOR EACH ROW\n EXECUTE FUNCTION ${app}.set_permissions_hash();\n\n INSERT INTO ${app}.permissions (permissions) VALUES (NULL) ON CONFLICT DO NOTHING;\n`;\n}\n\nexport async function ensureGlobalTables(db: PostgresDB, appID: AppID) {\n await db.unsafe(globalSetup(appID));\n}\n\nexport function getClientsTableDefinition(schema: string) {\n return /*sql*/ `\n CREATE TABLE ${schema}.\"clients\" (\n \"clientGroupID\" TEXT NOT NULL,\n \"clientID\" TEXT NOT NULL,\n \"lastMutationID\" BIGINT NOT NULL,\n \"userID\" TEXT,\n PRIMARY KEY(\"clientGroupID\", \"clientID\")\n );`;\n}\n\n/**\n * Tracks the results of mutations.\n * 1. It is an error for the same mutation ID to be used twice.\n * 2. The result is JSONB to allow for arbitrary results.\n *\n * The tables must be cleaned up as the clients\n * receive the mutation responses and as clients are removed.\n */\nexport function getMutationsTableDefinition(schema: string) {\n return /*sql*/ `\n CREATE TABLE ${schema}.\"mutations\" (\n \"clientGroupID\" TEXT NOT NULL,\n \"clientID\" TEXT NOT NULL,\n \"mutationID\" BIGINT NOT NULL,\n \"result\" JSON NOT NULL,\n PRIMARY KEY(\"clientGroupID\", \"clientID\", \"mutationID\")\n );`;\n}\n\nexport const SHARD_CONFIG_TABLE = 'shardConfig';\n\nexport function shardSetup(\n shardConfig: ShardConfig,\n metadataPublication: string,\n): string {\n const app = id(appSchema(shardConfig));\n const shard = id(upstreamSchema(shardConfig));\n\n const pubs = shardConfig.publications.toSorted();\n assert(\n pubs.includes(metadataPublication),\n () => `Publications must include ${metadataPublication}`,\n );\n\n return /*sql*/ `\n CREATE SCHEMA IF NOT EXISTS ${shard};\n\n ${getClientsTableDefinition(shard)}\n ${getMutationsTableDefinition(shard)}\n\n CREATE TABLE ${shard}.\"${SHARD_CONFIG_TABLE}\" (\n \"publications\" TEXT[] NOT NULL,\n \"ddlDetection\" BOOL NOT NULL,\n\n -- Ensure that there is only a single row in the table.\n \"lock\" BOOL PRIMARY KEY DEFAULT true CHECK (lock)\n );\n\n INSERT INTO ${shard}.\"${SHARD_CONFIG_TABLE}\" (\n \"publications\",\n \"ddlDetection\" \n ) VALUES (\n ARRAY[${literal(pubs)}], \n false -- set in SAVEPOINT with triggerSetup() statements\n );\n\n CREATE TABLE ${shard}.replicas (\n -- The DEFAULT exists purely for backwards compatibility support.\n -- New code always specifies a value based on Date.now().\n \"id\" TEXT PRIMARY KEY DEFAULT replace(gen_random_uuid()::text, '-', ''),\n \"rank\" BIGSERIAL,\n \"slot\" TEXT NOT NULL,\n \"version\" TEXT, -- replaced by generation, slated for deletion\n \"epoch\" INT4 DEFAULT 0,\n \"generation\" TEXT NOT NULL,\n \"stage\" INT4 DEFAULT ${InitialSync},\n \"backupPath\" TEXT, -- subpath within the litestream backup URL\n \"backupV5\" BOOL DEFAULT false,\n -- Whether the slot is acked only after storing in the PG change log.\n \"pgChangeLog\" BOOL DEFAULT false,\n \"initialSchema\" JSON, -- set after initial sync\n \"initialSyncContext\" JSON,\n \"subscriberContext\" JSON\n );\n\n DROP PUBLICATION IF EXISTS ${id(metadataPublication)};\n CREATE PUBLICATION ${id(metadataPublication)}\n FOR TABLE ${app}.\"permissions\", \n TABLE ${shard}.\"clients\", \n ${shard}.\"mutations\", \n ${shard}.\"replicas\" (id); -- advance the LSN/version with new replicas\n `;\n}\n\nexport function dropShard(appID: string, shardID: string | number): string {\n const schema = `${appID}_${shardID}`;\n const metadataPublication = metadataPublicationName(appID, shardID);\n const defaultPublication = defaultPublicationName(appID, shardID);\n\n // DROP SCHEMA ... CASCADE does not drop dependent PUBLICATIONS,\n // so PUBLICATIONs must be dropped explicitly.\n return /*sql*/ `\n DROP PUBLICATION IF EXISTS ${id(defaultPublication)};\n DROP PUBLICATION IF EXISTS ${id(metadataPublication)};\n DROP SCHEMA IF EXISTS ${id(schema)} CASCADE;\n `;\n}\n\nconst internalShardConfigSchema = v.object({\n publications: v.array(v.string()),\n ddlDetection: v.boolean(),\n // The secret that the shard's upstream functions include in ddl events,\n // and the WAL position before which events are accepted without one.\n // See `createEventFunctionStatements()`.\n ddlSecret: v.string().nullable().optional(),\n ddlSecretLsn: v.string().nullable().optional(),\n});\n\nexport type InternalShardConfig = v.Infer<typeof internalShardConfigSchema>;\n\nconst replicaInfoSchema = v.object({\n id: v.string(),\n rank: v.bigint(),\n slot: v.string(),\n epoch: v.number(),\n generation: v.string(),\n stage: replicaStageSchema,\n backupPath: v.string().nullable(),\n backupV5: v.boolean(),\n /**\n * Whether the replication-manager that took over the replica's slot acks it\n * only after storing transactions in the PG change log (i.e. RMv1.5). The\n * slot's position past the change log's head then reflects acked\n * keepalives, rather than transactions missing from the change log.\n * False if unknown.\n */\n pgChangeLog: v.boolean(),\n});\n\nconst fullReplicaRowSchema = replicaInfoSchema.extend({\n initialSchema: publishedSchema,\n initialSyncContext: jsonObjectSchema.nullable(),\n subscriberContext: jsonObjectSchema.nullable(),\n});\n\nconst replicaSchema = internalShardConfigSchema.extend(\n fullReplicaRowSchema.shape,\n);\n\nexport type Replica = v.Infer<typeof replicaSchema>;\n\nconst replicationSlotStateSchema = v.object({\n active: v.boolean(),\n confirmedFlushLsn: v.string(),\n});\n\nconst replicaStateSchema = replicaInfoSchema.extend(\n replicationSlotStateSchema.shape,\n);\n\nexport type ReplicaState = v.Infer<typeof replicaStateSchema>;\n\n// triggerSetup is run separately in a sub-transaction (i.e. SAVEPOINT) so\n// that a failure (e.g. due to lack of superuser permissions) can be handled\n// by continuing in a degraded mode (ddlDetection = false).\nfunction triggerSetup(shard: ShardConfig): string {\n const schema = id(upstreamSchema(shard));\n return (\n createEventTriggerStatements(shard) +\n /*sql*/ `UPDATE ${schema}.\"shardConfig\" SET \"ddlDetection\" = true;`\n );\n}\n\nexport type BackupOptions = {\n backupPath: string | null;\n backupV5: boolean;\n /** See `pgChangeLog` in {@link ReplicaState}. */\n pgChangeLog: boolean;\n};\n\n/**\n * Creates a new replica to mark it as the owner of a specified `slot`.\n * This should be done with an advisory lock for replica/slot management\n * to ensure that the slot does not get dropped by concurrent cleanup\n * logic.\n *\n * Once initial sync is complete, {@link initInitialSyncReplica} should be called to\n * make the replica usable for incremental sync.\n */\nexport async function createReplica(\n sql: PostgresDB,\n shard: ShardID,\n id: string,\n slot: string,\n epoch: number,\n replicaVersion: string,\n {backupPath, backupV5, pgChangeLog}: BackupOptions,\n stage: ReplicaStage,\n) {\n const schema = upstreamSchema(shard);\n const values: Partial<v.Infer<typeof fullReplicaRowSchema>> & {\n version: string;\n } = {\n id,\n slot,\n epoch,\n generation: replicaVersion,\n // No longer read, but zero-cache 1.10 fails to start on a NULL \"version\",\n // so it is still written for rollbacks to 1.10.\n version: replicaVersion,\n backupPath,\n backupV5,\n pgChangeLog,\n stage,\n };\n await sql`INSERT INTO ${sql(schema)}.replicas ${sql(values)}`;\n}\n\n// Called in initial-sync to store the exact schema that was initially synced.\nexport async function initInitialSyncReplica(\n sql: PostgresDB,\n shard: ShardID,\n id: string,\n {tables, indexes}: PublishedSchema,\n initialSyncContext: JSONObject,\n) {\n const schema = upstreamSchema(shard);\n const synced: PublishedSchema = {tables, indexes};\n const values = {initialSchema: synced, initialSyncContext};\n await sql`UPDATE ${sql(schema)}.replicas SET ${sql(values)} WHERE id = ${id}`;\n}\n\n// Called to initialize a Restore replica (`destID`) with the generation\n// and initial sync context of the `sourceID` replica.\nexport async function initRestoreReplica(\n sql: PostgresDB,\n shard: ShardID,\n {sourceID, destID}: {sourceID: string; destID: string},\n): Promise<ReplicaState | null> {\n const schema = upstreamSchema(shard);\n await sql`\n UPDATE ${sql(schema)}.replicas dest \n SET \"generation\" = source.\"generation\",\n \"version\" = source.\"generation\",\n \"initialSchema\" = source.\"initialSchema\",\n \"initialSyncContext\" = source.\"initialSyncContext\"\n FROM ${sql(schema)}.replicas source\n WHERE source.id = ${sourceID} AND dest.id = ${destID};\n `;\n return getReplicaState(sql, shard, destID);\n}\n\n/**\n * Gets at the given version and optional ID. If no ID is specified, gets\n * the latest (i.e. highest rank) replica with that version.\n */\nexport async function getReplicaAtVersion(\n lc: LogContext,\n sql: PostgresDB,\n shard: ShardID,\n replicaVersion: string,\n id: string | null = null,\n context?: JSONObject,\n): Promise<Replica | null> {\n const schema = sql(upstreamSchema(shard));\n const result = await sql`\n SELECT\n replicas.\"id\",\n replicas.\"rank\",\n replicas.\"slot\",\n replicas.\"epoch\",\n replicas.\"generation\",\n replicas.\"stage\",\n replicas.\"backupPath\",\n replicas.\"backupV5\",\n replicas.\"pgChangeLog\",\n replicas.\"initialSchema\",\n replicas.\"initialSyncContext\",\n replicas.\"subscriberContext\",\n \"shardConfig\".\"publications\",\n \"shardConfig\".\"ddlDetection\"\n FROM ${schema}.replicas JOIN ${schema}.\"shardConfig\" ON true\n WHERE generation = ${replicaVersion} AND \"initialSyncContext\" IS NOT NULL\n AND id = COALESCE(${id}, id)\n ORDER BY rank DESC LIMIT 1;\n `;\n if (result.length === 0) {\n // log out all the replicas and the joined shardConfig\n const allReplicas = await sql`\n SELECT id, slot, generation, \"initialSyncContext\", \"subscriberContext\" \n FROM ${schema}.replicas`;\n lc.info?.(\n `Replica ${id}@${replicaVersion}` +\n (context ? `(context: ${stringify(context)}) ` : '') +\n `not found in: ${stringify(allReplicas)}`,\n );\n return null;\n }\n return v.parse(result[0], replicaSchema, 'passthrough');\n}\n\nexport async function getActiveReplicas(\n lc: LogContext,\n sql: PostgresDB,\n shard: ShardID,\n): Promise<ReplicaState[]> {\n const schema = sql(upstreamSchema(shard));\n const results = await sql`\n SELECT\n replicas.\"id\",\n replicas.\"rank\",\n replicas.\"slot\",\n replicas.\"epoch\",\n replicas.\"generation\",\n replicas.\"stage\",\n replicas.\"backupPath\",\n replicas.\"backupV5\",\n replicas.\"pgChangeLog\",\n slots.\"active\",\n slots.\"confirmed_flush_lsn\" as \"confirmedFlushLsn\"\n FROM ${schema}.replicas JOIN pg_replication_slots slots ON slot = slot_name\n WHERE \"initialSyncContext\" IS NOT NULL\n -- Exclude replicas whose slot has been invalidated (e.g. for exceeding\n -- max_slot_wal_keep_size). Such a replica can never be resumed, and\n -- restoring it just results in an AutoResetSignal on every attempt.\n AND slots.restart_lsn IS NOT NULL\n AND slots.wal_status IS DISTINCT FROM 'lost'\n ORDER BY generation DESC, confirmed_flush_lsn DESC;\n `;\n const replicas = v.parse(results, v.array(replicaStateSchema), 'passthrough');\n lc.info?.(`current replicas`, {replicas});\n return replicas;\n}\n\n/**\n * Returns candidates for restoring a new replica from. These include\n * all replicas in the newest `generation` of the given `epoch`, in order\n * of earliest available backup:\n * - An active InitialSync replica, which will be the only replica in\n * its generation by definition. Orphaned/inactive initial syncs are skipped.\n * - Replicas in the Replicate stage, active first.\n * - Replicas in the Restore stage, potentially available for resumption\n * as a last resort.\n */\nexport async function getRestoreCandidates(\n sql: PostgresDB,\n shard: ShardID,\n epoch: number,\n): Promise<ReplicaState[]> {\n const schema = sql(upstreamSchema(shard));\n const results = await sql`\n SELECT\n replicas.\"id\",\n replicas.\"rank\",\n replicas.\"slot\",\n replicas.\"epoch\",\n replicas.\"generation\",\n replicas.\"stage\",\n replicas.\"backupPath\",\n replicas.\"backupV5\",\n replicas.\"pgChangeLog\",\n slots.\"active\",\n slots.\"confirmed_flush_lsn\" as \"confirmedFlushLsn\"\n FROM ${schema}.replicas JOIN pg_replication_slots slots ON slot = slot_name\n\n -- coalesce on the newest generation in the epoch\n WHERE generation = (\n SELECT MAX(r.generation)\n FROM ${schema}.replicas r\n JOIN pg_replication_slots s ON r.slot = s.slot_name\n WHERE r.\"epoch\" = ${epoch} AND r.\"backupV5\"\n -- ignore orphaned InitialSyncs, which cannot be restored from\n AND (s.\"active\" OR r.\"stage\" != ${InitialSync})\n AND s.restart_lsn IS NOT NULL\n AND s.wal_status IS DISTINCT FROM 'lost'\n )\n AND \"epoch\" = ${epoch} AND \"backupV5\"\n AND (slots.active OR \"stage\" != ${InitialSync})\n AND slots.restart_lsn IS NOT NULL\n AND slots.wal_status IS DISTINCT FROM 'lost'\n\n ORDER BY \n stage ASC, -- ordered by backup availalibility\n active DESC, -- prefer active slots (fork over resume)\n confirmed_flush_lsn DESC; -- prefer replicas further ahead\n `;\n return v.parse(results, v.array(replicaStateSchema), 'passthrough');\n}\n\nexport async function getReplicaState(\n sql: PostgresDB,\n shard: ShardID,\n id: string,\n): Promise<ReplicaState | null> {\n const schema = sql(upstreamSchema(shard));\n const results = await sql`\n SELECT\n replicas.\"id\",\n replicas.\"rank\",\n replicas.\"slot\",\n replicas.\"epoch\",\n replicas.\"generation\",\n replicas.\"stage\",\n replicas.\"backupPath\",\n replicas.\"backupV5\",\n replicas.\"pgChangeLog\",\n slots.\"active\",\n slots.\"confirmed_flush_lsn\" as \"confirmedFlushLsn\"\n FROM ${schema}.replicas JOIN pg_replication_slots slots ON slot = slot_name\n WHERE \"id\" = ${id};\n `;\n return results.length\n ? v.parse(results[0], replicaStateSchema, 'passthrough')\n : null;\n}\n\nexport async function getInternalShardConfig(\n sql: PostgresDB,\n shard: ShardID,\n): Promise<InternalShardConfig> {\n const schema = sql(upstreamSchema(shard));\n const result = await sql`\n SELECT \"shardConfig\".\"publications\",\n \"shardConfig\".\"ddlDetection\",\n \"publishedSchema\".\"secret\" AS \"ddlSecret\",\n \"publishedSchema\".\"secretLsn\" AS \"ddlSecretLsn\"\n FROM ${schema}.\"shardConfig\"\n LEFT JOIN ${schema}.\"publishedSchema\" ON true;\n `;\n assert(\n result.length === 1,\n () => `Expected exactly one shardConfig row, got ${result.length}`,\n );\n return v.parse(result[0], internalShardConfigSchema, 'passthrough');\n}\n\n/**\n * Sets up and returns all publications (including internal ones) for\n * the given shard.\n */\nexport async function setupTablesAndReplication(\n lc: LogContext,\n sql: PostgresTransaction,\n requested: ShardConfig,\n includePartialIndexes = true,\n) {\n const {publications} = requested;\n // Validate requested publications.\n for (const pub of publications) {\n validatePublicationName(pub);\n if (pub.startsWith('_')) {\n throw new Error(\n `Publication names starting with \"_\" are reserved for internal use.\\n` +\n `Please use a different name for publication \"${pub}\".`,\n );\n }\n }\n const allPublications: string[] = [];\n\n // Setup application publications.\n if (publications.length) {\n const results = await sql<{pubname: string}[]>`\n SELECT pubname from pg_publication WHERE pubname IN ${sql(\n publications,\n )}`.values();\n\n if (results.length !== publications.length) {\n throw new Error(\n `Unknown or invalid publications. Specified: [${publications}]. Found: [${results.flat()}]`,\n );\n }\n allPublications.push(...publications);\n } else {\n const defaultPublication = defaultPublicationName(\n requested.appID,\n requested.shardNum,\n );\n await sql`\n DROP PUBLICATION IF EXISTS ${sql(defaultPublication)}`;\n await sql`\n CREATE PUBLICATION ${sql(defaultPublication)} \n FOR TABLES IN SCHEMA public\n WITH (publish_via_partition_root = true)`;\n allPublications.push(defaultPublication);\n }\n\n const metadataPublication = metadataPublicationName(\n requested.appID,\n requested.shardNum,\n );\n allPublications.push(metadataPublication);\n\n const shard = {...requested, publications: allPublications};\n\n // Setup the global tables and shard tables / publications.\n await sql.unsafe(globalSetup(shard) + shardSetup(shard, metadataPublication));\n\n const pubs = await getPublicationInfo(sql, allPublications);\n await replicaIdentitiesForTablesWithoutPrimaryKeys(pubs)?.apply(lc, sql);\n\n await setupTriggers(lc, sql, shard, includePartialIndexes);\n}\n\nexport async function setupTriggers(\n lc: LogContext,\n tx: PostgresTransaction,\n shard: ShardConfig,\n includePartialIndexes = true,\n) {\n const schema = upstreamSchema(shard);\n const [{ddlDetection}] = await tx<InternalShardConfig[]> /*sql*/ `\n SELECT \"ddlDetection\" FROM ${tx(schema)}.\"shardConfig\"`;\n\n // The functions invoked by event triggers are installed even if\n // event triggers are not supported/allowed by the db provider.\n // This allows users to manually invoke the update_schemas() function\n // as a workaround.\n await tx.unsafe(createEventFunctionStatements(shard, includePartialIndexes));\n try {\n await tx.savepoint(sub => sub.unsafe(triggerSetup(shard)));\n } catch (e) {\n if (ddlDetection) {\n // If ddlDetection has already been enabled, subsequent failures to\n // upgrade the trigger should be propagated rather than swallowed.\n throw e;\n }\n if (\n !(\n e instanceof postgres.PostgresError &&\n e.code === PG_INSUFFICIENT_PRIVILEGE\n )\n ) {\n throw e;\n }\n // If triggerSetup() fails, replication continues in ddlDetection=false mode.\n lc.warn?.(\n `Unable to create event triggers for schema change detection:\\n\\n` +\n `\"${e.hint ?? e.message}\"\\n\\n` +\n `Proceeding in degraded mode: schema changes will halt replication,\\n` +\n `requiring the replica to be reset (manually or with --auto-reset).`,\n );\n }\n}\n\nexport function validatePublications(\n lc: LogContext,\n published: PublicationInfo,\n) {\n // Verify that all publications export the proper events.\n published.publications.forEach(pub => {\n if (\n !pub.pubinsert ||\n !pub.pubupdate ||\n !pub.pubdelete ||\n !pub.pubtruncate\n ) {\n // TODO: Make APIError?\n throw new Error(\n `PUBLICATION ${pub.pubname} must publish insert, update, delete, and truncate`,\n );\n }\n });\n\n published.tables.forEach(table => validate(lc, table));\n}\n\ntype ReplicaIdentities = {\n apply(lc: LogContext, db: PostgresDB): Promise<void>;\n};\n\nexport function replicaIdentitiesForTablesWithoutPrimaryKeys(\n pubs: PublishedSchema,\n): ReplicaIdentities | undefined {\n const replicaIdentities: {\n schema: string;\n tableName: string;\n indexName: string;\n }[] = [];\n for (const table of pubs.tables) {\n if (!table.primaryKey?.length && table.replicaIdentity === Default) {\n // Look for an index that can serve as the REPLICA IDENTITY USING INDEX. It must be:\n // - UNIQUE\n // - NOT NULL columns\n // - not deferrable (i.e. isImmediate)\n // - not partial\n //\n // https://www.postgresql.org/docs/current/sql-altertable.html#SQL-ALTERTABLE-REPLICA-IDENTITY\n const {schema, name: tableName} = table;\n for (const {columns, name: indexName} of pubs.indexes.filter(\n idx =>\n idx.schema === schema &&\n idx.tableName === tableName &&\n idx.unique &&\n idx.isImmediate &&\n idx.predicate === undefined,\n )) {\n if (Object.keys(columns).some(col => !table.columns[col].notNull)) {\n continue; // Only indexes with all NOT NULL columns are suitable.\n }\n replicaIdentities.push({schema, tableName, indexName});\n break;\n }\n }\n }\n\n if (replicaIdentities.length === 0) {\n return undefined;\n }\n return {\n apply: async (lc: LogContext, sql: PostgresDB) => {\n for (const {schema, tableName, indexName} of replicaIdentities) {\n lc.info?.(\n `setting \"${indexName}\" as the REPLICA IDENTITY for \"${tableName}\"`,\n );\n await sql`\n ALTER TABLE ${sql(schema)}.${sql(tableName)} \n REPLICA IDENTITY USING INDEX ${sql(indexName)}`;\n }\n },\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;AAqCA,IAAM,yBAAyB;;;;;;AAO/B,SAAgB,wBAAwB,MAAoB;CAC1D,IAAI,CAAC,uBAAuB,KAAK,IAAI,GACnC,MAAM,IAAI,MACR,6BAA6B,KAAK,+GAEpC;CAEF,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F;AACF"}
1
+ {"version":3,"file":"shard.js","names":["v","v.parse"],"sources":["../../../../../../../../zero-cache/src/services/change-source/pg/schema/shard.ts"],"sourcesContent":["import {PG_INSUFFICIENT_PRIVILEGE} from '@drdgvhbh/postgres-error-codes';\nimport type {LogContext} from '@rocicorp/logger';\nimport {literal} from 'pg-format';\nimport postgres from 'postgres';\nimport {assert} from '../../../../../../shared/src/asserts.ts';\nimport {\n jsonObjectSchema,\n stringify,\n type JSONObject,\n} from '../../../../../../shared/src/bigint-json.ts';\nimport * as v from '../../../../../../shared/src/valita.ts';\nimport {Default, Full} from '../../../../db/postgres-replica-identity-enum.ts';\nimport type {PostgresDB, PostgresTransaction} from '../../../../types/pg.ts';\nimport type {AppID, ShardConfig, ShardID} from '../../../../types/shards.ts';\nimport {appSchema, check, upstreamSchema} from '../../../../types/shards.ts';\nimport {id} from '../../../../types/sql.ts';\nimport {\n createEventFunctionStatements,\n createEventTriggerStatements,\n} from './ddl.ts';\nimport {\n getPublicationInfo,\n publishedSchema,\n type PublicationInfo,\n type PublishedSchema,\n} from './published.ts';\nimport {\n InitialSync,\n replicaStageSchema,\n type ReplicaStage,\n} from './replica-stage-enum.ts';\nimport {validate, validateRelationNames} from './validation.ts';\n\n/**\n * PostgreSQL unquoted identifiers must start with a letter or underscore\n * and contain only letters, digits, and underscores.\n */\nconst VALID_PUBLICATION_NAME = /^[a-zA-Z_][a-zA-Z0-9_]*$/;\n\n/**\n * Validates that a publication name is a valid PostgreSQL identifier.\n * This provides defense-in-depth against SQL injection when publication\n * names are used in replication commands.\n */\nexport function validatePublicationName(name: string): void {\n if (!VALID_PUBLICATION_NAME.test(name)) {\n throw new Error(\n `Invalid publication name \"${name}\". Publication names must start with a letter or underscore ` +\n `and contain only letters, digits, and underscores.`,\n );\n }\n if (name.length > 63) {\n throw new Error(\n `Publication name \"${name}\" exceeds PostgreSQL's 63-character identifier limit.`,\n );\n }\n}\n\nexport function internalPublicationPrefix({appID}: AppID) {\n return `_${appID}_`;\n}\n\nexport function legacyReplicationSlot({appID, shardNum}: ShardID) {\n return `${appID}_${shardNum}`;\n}\n\nexport function replicationSlotPrefix(shard: ShardID) {\n const {appID, shardNum} = check(shard);\n return `${appID}_${shardNum}_`;\n}\n\n/**\n * An expression used to match replication slots in the shard\n * in a Postgres `LIKE` operator.\n */\nexport function replicationSlotExpression(shard: ShardID) {\n // Underscores have a special meaning in LIKE values\n // so they have to be escaped.\n return `${replicationSlotPrefix(shard)}%`.replaceAll('_', '\\\\_');\n}\n\nfunction defaultPublicationName(appID: string, shardID: string | number) {\n return `_${appID}_public_${shardID}`;\n}\n\nexport function metadataPublicationName(\n appID: string,\n shardID: string | number,\n) {\n return `_${appID}_metadata_${shardID}`;\n}\n\n// The GLOBAL_SETUP must be idempotent as it can be run multiple times for different shards.\nfunction globalSetup(appID: AppID): string {\n const app = id(appSchema(appID));\n\n return /*sql*/ `\n CREATE SCHEMA IF NOT EXISTS ${app};\n\n CREATE TABLE IF NOT EXISTS ${app}.permissions (\n \"permissions\" JSONB,\n \"hash\" TEXT,\n\n -- Ensure that there is only a single row in the table.\n -- Application code can be agnostic to this column, and\n -- simply invoke UPDATE statements on the version columns.\n \"lock\" BOOL PRIMARY KEY DEFAULT true CHECK (lock)\n );\n\n CREATE OR REPLACE FUNCTION ${app}.set_permissions_hash()\n RETURNS TRIGGER AS $$\n BEGIN\n NEW.hash = md5(NEW.permissions::text);\n RETURN NEW;\n END;\n $$ LANGUAGE plpgsql;\n\n CREATE OR REPLACE TRIGGER on_set_permissions \n BEFORE INSERT OR UPDATE ON ${app}.permissions\n FOR EACH ROW\n EXECUTE FUNCTION ${app}.set_permissions_hash();\n\n INSERT INTO ${app}.permissions (permissions) VALUES (NULL) ON CONFLICT DO NOTHING;\n`;\n}\n\nexport async function ensureGlobalTables(db: PostgresDB, appID: AppID) {\n await db.unsafe(globalSetup(appID));\n}\n\nexport function getClientsTableDefinition(schema: string) {\n return /*sql*/ `\n CREATE TABLE ${schema}.\"clients\" (\n \"clientGroupID\" TEXT NOT NULL,\n \"clientID\" TEXT NOT NULL,\n \"lastMutationID\" BIGINT NOT NULL,\n \"userID\" TEXT,\n PRIMARY KEY(\"clientGroupID\", \"clientID\")\n );`;\n}\n\n/**\n * Tracks the results of mutations.\n * 1. It is an error for the same mutation ID to be used twice.\n * 2. The result is JSONB to allow for arbitrary results.\n *\n * The tables must be cleaned up as the clients\n * receive the mutation responses and as clients are removed.\n */\nexport function getMutationsTableDefinition(schema: string) {\n return /*sql*/ `\n CREATE TABLE ${schema}.\"mutations\" (\n \"clientGroupID\" TEXT NOT NULL,\n \"clientID\" TEXT NOT NULL,\n \"mutationID\" BIGINT NOT NULL,\n \"result\" JSON NOT NULL,\n PRIMARY KEY(\"clientGroupID\", \"clientID\", \"mutationID\")\n );`;\n}\n\nexport const SHARD_CONFIG_TABLE = 'shardConfig';\n\nexport function shardSetup(\n shardConfig: ShardConfig,\n metadataPublication: string,\n): string {\n const app = id(appSchema(shardConfig));\n const shard = id(upstreamSchema(shardConfig));\n\n const pubs = shardConfig.publications.toSorted();\n assert(\n pubs.includes(metadataPublication),\n () => `Publications must include ${metadataPublication}`,\n );\n\n return /*sql*/ `\n CREATE SCHEMA IF NOT EXISTS ${shard};\n\n ${getClientsTableDefinition(shard)}\n ${getMutationsTableDefinition(shard)}\n\n CREATE TABLE ${shard}.\"${SHARD_CONFIG_TABLE}\" (\n \"publications\" TEXT[] NOT NULL,\n \"ddlDetection\" BOOL NOT NULL,\n\n -- Ensure that there is only a single row in the table.\n \"lock\" BOOL PRIMARY KEY DEFAULT true CHECK (lock)\n );\n\n INSERT INTO ${shard}.\"${SHARD_CONFIG_TABLE}\" (\n \"publications\",\n \"ddlDetection\" \n ) VALUES (\n ARRAY[${literal(pubs)}], \n false -- set in SAVEPOINT with triggerSetup() statements\n );\n\n CREATE TABLE ${shard}.replicas (\n -- The DEFAULT exists purely for backwards compatibility support.\n -- New code always specifies a value based on Date.now().\n \"id\" TEXT PRIMARY KEY DEFAULT replace(gen_random_uuid()::text, '-', ''),\n \"rank\" BIGSERIAL,\n \"slot\" TEXT NOT NULL,\n \"version\" TEXT, -- replaced by generation, slated for deletion\n \"epoch\" INT4 DEFAULT 0,\n \"generation\" TEXT NOT NULL,\n \"stage\" INT4 DEFAULT ${InitialSync},\n \"backupPath\" TEXT, -- subpath within the litestream backup URL\n \"backupV5\" BOOL DEFAULT false,\n -- Whether the slot is acked only after storing in the PG change log.\n \"pgChangeLog\" BOOL DEFAULT false,\n \"initialSchema\" JSON, -- set after initial sync\n \"initialSyncContext\" JSON,\n \"subscriberContext\" JSON\n );\n\n DROP PUBLICATION IF EXISTS ${id(metadataPublication)};\n CREATE PUBLICATION ${id(metadataPublication)}\n FOR TABLE ${app}.\"permissions\", \n TABLE ${shard}.\"clients\", \n ${shard}.\"mutations\", \n ${shard}.\"replicas\" (id); -- advance the LSN/version with new replicas\n `;\n}\n\nexport function dropShard(appID: string, shardID: string | number): string {\n const schema = `${appID}_${shardID}`;\n const metadataPublication = metadataPublicationName(appID, shardID);\n const defaultPublication = defaultPublicationName(appID, shardID);\n\n // DROP SCHEMA ... CASCADE does not drop dependent PUBLICATIONS,\n // so PUBLICATIONs must be dropped explicitly.\n return /*sql*/ `\n DROP PUBLICATION IF EXISTS ${id(defaultPublication)};\n DROP PUBLICATION IF EXISTS ${id(metadataPublication)};\n DROP SCHEMA IF EXISTS ${id(schema)} CASCADE;\n `;\n}\n\nconst internalShardConfigSchema = v.object({\n publications: v.array(v.string()),\n ddlDetection: v.boolean(),\n // The secret that the shard's upstream functions include in ddl events,\n // and the WAL position before which events are accepted without one.\n // See `createEventFunctionStatements()`.\n ddlSecret: v.string().nullable().optional(),\n ddlSecretLsn: v.string().nullable().optional(),\n});\n\nexport type InternalShardConfig = v.Infer<typeof internalShardConfigSchema>;\n\nconst replicaInfoSchema = v.object({\n id: v.string(),\n rank: v.bigint(),\n slot: v.string(),\n epoch: v.number(),\n generation: v.string(),\n stage: replicaStageSchema,\n backupPath: v.string().nullable(),\n backupV5: v.boolean(),\n /**\n * Whether the replication-manager that took over the replica's slot acks it\n * only after storing transactions in the PG change log (i.e. RMv1.5). The\n * slot's position past the change log's head then reflects acked\n * keepalives, rather than transactions missing from the change log.\n * False if unknown.\n */\n pgChangeLog: v.boolean(),\n});\n\nconst fullReplicaRowSchema = replicaInfoSchema.extend({\n initialSchema: publishedSchema,\n initialSyncContext: jsonObjectSchema.nullable(),\n subscriberContext: jsonObjectSchema.nullable(),\n});\n\nconst replicaSchema = internalShardConfigSchema.extend(\n fullReplicaRowSchema.shape,\n);\n\nexport type Replica = v.Infer<typeof replicaSchema>;\n\nconst replicationSlotStateSchema = v.object({\n active: v.boolean(),\n confirmedFlushLsn: v.string(),\n});\n\nconst replicaStateSchema = replicaInfoSchema.extend(\n replicationSlotStateSchema.shape,\n);\n\nexport type ReplicaState = v.Infer<typeof replicaStateSchema>;\n\n// triggerSetup is run separately in a sub-transaction (i.e. SAVEPOINT) so\n// that a failure (e.g. due to lack of superuser permissions) can be handled\n// by continuing in a degraded mode (ddlDetection = false).\nfunction triggerSetup(shard: ShardConfig): string {\n const schema = id(upstreamSchema(shard));\n return (\n createEventTriggerStatements(shard) +\n /*sql*/ `UPDATE ${schema}.\"shardConfig\" SET \"ddlDetection\" = true;`\n );\n}\n\nexport type BackupOptions = {\n backupPath: string | null;\n backupV5: boolean;\n /** See `pgChangeLog` in {@link ReplicaState}. */\n pgChangeLog: boolean;\n};\n\n/**\n * Creates a new replica to mark it as the owner of a specified `slot`.\n * This should be done with an advisory lock for replica/slot management\n * to ensure that the slot does not get dropped by concurrent cleanup\n * logic.\n *\n * Once initial sync is complete, {@link initInitialSyncReplica} should be called to\n * make the replica usable for incremental sync.\n */\nexport async function createReplica(\n sql: PostgresDB,\n shard: ShardID,\n id: string,\n slot: string,\n epoch: number,\n replicaVersion: string,\n {backupPath, backupV5, pgChangeLog}: BackupOptions,\n stage: ReplicaStage,\n) {\n const schema = upstreamSchema(shard);\n const values: Partial<v.Infer<typeof fullReplicaRowSchema>> & {\n version: string;\n } = {\n id,\n slot,\n epoch,\n generation: replicaVersion,\n // No longer read, but zero-cache 1.10 fails to start on a NULL \"version\",\n // so it is still written for rollbacks to 1.10.\n version: replicaVersion,\n backupPath,\n backupV5,\n pgChangeLog,\n stage,\n };\n await sql`INSERT INTO ${sql(schema)}.replicas ${sql(values)}`;\n}\n\n// Called in initial-sync to store the exact schema that was initially synced.\nexport async function initInitialSyncReplica(\n sql: PostgresDB,\n shard: ShardID,\n id: string,\n {tables, indexes}: PublishedSchema,\n initialSyncContext: JSONObject,\n) {\n const schema = upstreamSchema(shard);\n const synced: PublishedSchema = {tables, indexes};\n const values = {initialSchema: synced, initialSyncContext};\n await sql`UPDATE ${sql(schema)}.replicas SET ${sql(values)} WHERE id = ${id}`;\n}\n\n// Called to initialize a Restore replica (`destID`) with the generation\n// and initial sync context of the `sourceID` replica.\nexport async function initRestoreReplica(\n sql: PostgresDB,\n shard: ShardID,\n {sourceID, destID}: {sourceID: string; destID: string},\n): Promise<ReplicaState | null> {\n const schema = upstreamSchema(shard);\n await sql`\n UPDATE ${sql(schema)}.replicas dest \n SET \"generation\" = source.\"generation\",\n \"version\" = source.\"generation\",\n \"initialSchema\" = source.\"initialSchema\",\n \"initialSyncContext\" = source.\"initialSyncContext\"\n FROM ${sql(schema)}.replicas source\n WHERE source.id = ${sourceID} AND dest.id = ${destID};\n `;\n return getReplicaState(sql, shard, destID);\n}\n\n/**\n * Gets at the given version and optional ID. If no ID is specified, gets\n * the latest (i.e. highest rank) replica with that version.\n */\nexport async function getReplicaAtVersion(\n lc: LogContext,\n sql: PostgresDB,\n shard: ShardID,\n replicaVersion: string,\n id: string | null = null,\n context?: JSONObject,\n): Promise<Replica | null> {\n const schema = sql(upstreamSchema(shard));\n const result = await sql`\n SELECT\n replicas.\"id\",\n replicas.\"rank\",\n replicas.\"slot\",\n replicas.\"epoch\",\n replicas.\"generation\",\n replicas.\"stage\",\n replicas.\"backupPath\",\n replicas.\"backupV5\",\n replicas.\"pgChangeLog\",\n replicas.\"initialSchema\",\n replicas.\"initialSyncContext\",\n replicas.\"subscriberContext\",\n \"shardConfig\".\"publications\",\n \"shardConfig\".\"ddlDetection\"\n FROM ${schema}.replicas JOIN ${schema}.\"shardConfig\" ON true\n WHERE generation = ${replicaVersion} AND \"initialSyncContext\" IS NOT NULL\n AND id = COALESCE(${id}, id)\n ORDER BY rank DESC LIMIT 1;\n `;\n if (result.length === 0) {\n // log out all the replicas and the joined shardConfig\n const allReplicas = await sql`\n SELECT id, slot, generation, \"initialSyncContext\", \"subscriberContext\" \n FROM ${schema}.replicas`;\n lc.info?.(\n `Replica ${id}@${replicaVersion}` +\n (context ? `(context: ${stringify(context)}) ` : '') +\n `not found in: ${stringify(allReplicas)}`,\n );\n return null;\n }\n return v.parse(result[0], replicaSchema, 'passthrough');\n}\n\nexport async function getActiveReplicas(\n lc: LogContext,\n sql: PostgresDB,\n shard: ShardID,\n): Promise<ReplicaState[]> {\n const schema = sql(upstreamSchema(shard));\n const results = await sql`\n SELECT\n replicas.\"id\",\n replicas.\"rank\",\n replicas.\"slot\",\n replicas.\"epoch\",\n replicas.\"generation\",\n replicas.\"stage\",\n replicas.\"backupPath\",\n replicas.\"backupV5\",\n replicas.\"pgChangeLog\",\n slots.\"active\",\n slots.\"confirmed_flush_lsn\" as \"confirmedFlushLsn\"\n FROM ${schema}.replicas JOIN pg_replication_slots slots ON slot = slot_name\n WHERE \"initialSyncContext\" IS NOT NULL\n -- Exclude replicas whose slot has been invalidated (e.g. for exceeding\n -- max_slot_wal_keep_size). Such a replica can never be resumed, and\n -- restoring it just results in an AutoResetSignal on every attempt.\n AND slots.restart_lsn IS NOT NULL\n AND slots.wal_status IS DISTINCT FROM 'lost'\n ORDER BY generation DESC, confirmed_flush_lsn DESC;\n `;\n const replicas = v.parse(results, v.array(replicaStateSchema), 'passthrough');\n lc.info?.(`current replicas`, {replicas});\n return replicas;\n}\n\n/**\n * Returns candidates for restoring a new replica from. These include\n * all replicas in the newest `generation` of the given `epoch`, in order\n * of earliest available backup:\n * - An active InitialSync replica, which will be the only replica in\n * its generation by definition. Orphaned/inactive initial syncs are skipped.\n * - Replicas in the Replicate stage, active first.\n * - Replicas in the Restore stage, potentially available for resumption\n * as a last resort.\n */\nexport async function getRestoreCandidates(\n sql: PostgresDB,\n shard: ShardID,\n epoch: number,\n): Promise<ReplicaState[]> {\n const schema = sql(upstreamSchema(shard));\n const results = await sql`\n SELECT\n replicas.\"id\",\n replicas.\"rank\",\n replicas.\"slot\",\n replicas.\"epoch\",\n replicas.\"generation\",\n replicas.\"stage\",\n replicas.\"backupPath\",\n replicas.\"backupV5\",\n replicas.\"pgChangeLog\",\n slots.\"active\",\n slots.\"confirmed_flush_lsn\" as \"confirmedFlushLsn\"\n FROM ${schema}.replicas JOIN pg_replication_slots slots ON slot = slot_name\n\n -- coalesce on the newest generation in the epoch\n WHERE generation = (\n SELECT MAX(r.generation)\n FROM ${schema}.replicas r\n JOIN pg_replication_slots s ON r.slot = s.slot_name\n WHERE r.\"epoch\" = ${epoch} AND r.\"backupV5\"\n -- ignore orphaned InitialSyncs, which cannot be restored from\n AND (s.\"active\" OR r.\"stage\" != ${InitialSync})\n AND s.restart_lsn IS NOT NULL\n AND s.wal_status IS DISTINCT FROM 'lost'\n )\n AND \"epoch\" = ${epoch} AND \"backupV5\"\n AND (slots.active OR \"stage\" != ${InitialSync})\n AND slots.restart_lsn IS NOT NULL\n AND slots.wal_status IS DISTINCT FROM 'lost'\n\n ORDER BY \n stage ASC, -- ordered by backup availalibility\n active DESC, -- prefer active slots (fork over resume)\n confirmed_flush_lsn DESC; -- prefer replicas further ahead\n `;\n return v.parse(results, v.array(replicaStateSchema), 'passthrough');\n}\n\nexport async function getReplicaState(\n sql: PostgresDB,\n shard: ShardID,\n id: string,\n): Promise<ReplicaState | null> {\n const schema = sql(upstreamSchema(shard));\n const results = await sql`\n SELECT\n replicas.\"id\",\n replicas.\"rank\",\n replicas.\"slot\",\n replicas.\"epoch\",\n replicas.\"generation\",\n replicas.\"stage\",\n replicas.\"backupPath\",\n replicas.\"backupV5\",\n replicas.\"pgChangeLog\",\n slots.\"active\",\n slots.\"confirmed_flush_lsn\" as \"confirmedFlushLsn\"\n FROM ${schema}.replicas JOIN pg_replication_slots slots ON slot = slot_name\n WHERE \"id\" = ${id};\n `;\n return results.length\n ? v.parse(results[0], replicaStateSchema, 'passthrough')\n : null;\n}\n\nexport async function getInternalShardConfig(\n sql: PostgresDB,\n shard: ShardID,\n): Promise<InternalShardConfig> {\n const schema = sql(upstreamSchema(shard));\n const result = await sql`\n SELECT \"shardConfig\".\"publications\",\n \"shardConfig\".\"ddlDetection\",\n \"publishedSchema\".\"secret\" AS \"ddlSecret\",\n \"publishedSchema\".\"secretLsn\" AS \"ddlSecretLsn\"\n FROM ${schema}.\"shardConfig\"\n LEFT JOIN ${schema}.\"publishedSchema\" ON true;\n `;\n assert(\n result.length === 1,\n () => `Expected exactly one shardConfig row, got ${result.length}`,\n );\n return v.parse(result[0], internalShardConfigSchema, 'passthrough');\n}\n\n/**\n * Sets up and returns all publications (including internal ones) for\n * the given shard.\n */\nexport async function setupTablesAndReplication(\n lc: LogContext,\n sql: PostgresTransaction,\n requested: ShardConfig,\n includePartialIndexes = true,\n) {\n const {publications} = requested;\n // Validate requested publications.\n for (const pub of publications) {\n validatePublicationName(pub);\n if (pub.startsWith('_')) {\n throw new Error(\n `Publication names starting with \"_\" are reserved for internal use.\\n` +\n `Please use a different name for publication \"${pub}\".`,\n );\n }\n }\n const allPublications: string[] = [];\n\n // Setup application publications.\n if (publications.length) {\n const results = await sql<{pubname: string}[]>`\n SELECT pubname from pg_publication WHERE pubname IN ${sql(\n publications,\n )}`.values();\n\n if (results.length !== publications.length) {\n throw new Error(\n `Unknown or invalid publications. Specified: [${publications}]. Found: [${results.flat()}]`,\n );\n }\n allPublications.push(...publications);\n } else {\n const defaultPublication = defaultPublicationName(\n requested.appID,\n requested.shardNum,\n );\n await sql`\n DROP PUBLICATION IF EXISTS ${sql(defaultPublication)}`;\n await sql`\n CREATE PUBLICATION ${sql(defaultPublication)} \n FOR TABLES IN SCHEMA public\n WITH (publish_via_partition_root = true)`;\n allPublications.push(defaultPublication);\n }\n\n const metadataPublication = metadataPublicationName(\n requested.appID,\n requested.shardNum,\n );\n allPublications.push(metadataPublication);\n\n const shard = {...requested, publications: allPublications};\n\n // Setup the global tables and shard tables / publications.\n await sql.unsafe(globalSetup(shard) + shardSetup(shard, metadataPublication));\n\n const pubs = await getPublicationInfo(sql, allPublications);\n await replicaIdentitiesForTablesWithoutPrimaryKeys(pubs)?.apply(lc, sql);\n\n await setupTriggers(lc, sql, shard, includePartialIndexes);\n}\n\nexport async function setupTriggers(\n lc: LogContext,\n tx: PostgresTransaction,\n shard: ShardConfig,\n includePartialIndexes = true,\n) {\n const schema = upstreamSchema(shard);\n const [{ddlDetection}] = await tx<InternalShardConfig[]> /*sql*/ `\n SELECT \"ddlDetection\" FROM ${tx(schema)}.\"shardConfig\"`;\n\n // The functions invoked by event triggers are installed even if\n // event triggers are not supported/allowed by the db provider.\n // This allows users to manually invoke the update_schemas() function\n // as a workaround.\n await tx.unsafe(createEventFunctionStatements(shard, includePartialIndexes));\n try {\n await tx.savepoint(sub => sub.unsafe(triggerSetup(shard)));\n } catch (e) {\n if (ddlDetection) {\n // If ddlDetection has already been enabled, subsequent failures to\n // upgrade the trigger should be propagated rather than swallowed.\n throw e;\n }\n if (\n !(\n e instanceof postgres.PostgresError &&\n e.code === PG_INSUFFICIENT_PRIVILEGE\n )\n ) {\n throw e;\n }\n // If triggerSetup() fails, replication continues in ddlDetection=false mode.\n lc.warn?.(\n `Unable to create event triggers for schema change detection:\\n\\n` +\n `\"${e.hint ?? e.message}\"\\n\\n` +\n `Proceeding in degraded mode: schema changes will halt replication,\\n` +\n `requiring the replica to be reset (manually or with --auto-reset).`,\n );\n }\n}\n\nexport function validatePublications(\n lc: LogContext,\n published: PublicationInfo,\n) {\n // Verify that all publications export the proper events.\n published.publications.forEach(pub => {\n if (\n !pub.pubinsert ||\n !pub.pubupdate ||\n !pub.pubdelete ||\n !pub.pubtruncate\n ) {\n // TODO: Make APIError?\n throw new Error(\n `PUBLICATION ${pub.pubname} must publish insert, update, delete, and truncate`,\n );\n }\n });\n\n published.tables.forEach(table => validate(lc, table));\n validateRelationNames(published);\n}\n\ntype ReplicaIdentities = {\n apply(lc: LogContext, db: PostgresDB): Promise<void>;\n};\n\nexport function replicaIdentitiesForTablesWithoutPrimaryKeys(\n pubs: PublishedSchema,\n): ReplicaIdentities | undefined {\n const replicaIdentities: {\n schema: string;\n tableName: string;\n indexName: string;\n }[] = [];\n // Tables with no index to use, which may have a primary key that is not\n // published. A partition has a replica identity of its own, which is what\n // Postgres goes by for the rows in it.\n const withoutIndex: number[] = [];\n for (const table of pubs.tables) {\n if (table.primaryKey?.length) {\n continue;\n }\n if (table.replicaIdentity === Full) {\n // Its partitions may have been added since it was set.\n withoutIndex.push(...(table.partitions ?? []));\n } else if (table.replicaIdentity === Default) {\n const numIdentities = replicaIdentities.length;\n // Look for an index that can serve as the REPLICA IDENTITY USING INDEX. It must be:\n // - UNIQUE\n // - NOT NULL columns\n // - not deferrable (i.e. isImmediate)\n // - not partial\n //\n // https://www.postgresql.org/docs/current/sql-altertable.html#SQL-ALTERTABLE-REPLICA-IDENTITY\n const {schema, name: tableName} = table;\n for (const {columns, name: indexName} of pubs.indexes.filter(\n idx =>\n idx.schema === schema &&\n idx.tableName === tableName &&\n idx.unique &&\n idx.isImmediate &&\n idx.predicate === undefined,\n )) {\n if (Object.keys(columns).some(col => !table.columns[col].notNull)) {\n continue; // Only indexes with all NOT NULL columns are suitable.\n }\n replicaIdentities.push({schema, tableName, indexName});\n break;\n }\n if (replicaIdentities.length === numIdentities) {\n withoutIndex.push(table.oid, ...(table.partitions ?? []));\n }\n }\n }\n\n if (replicaIdentities.length === 0 && withoutIndex.length === 0) {\n return undefined;\n }\n return {\n apply: async (lc: LogContext, sql: PostgresDB) => {\n // Postgres does not send a generated column unless it is published,\n // which only Postgres 18 can do, so a primary key with one identifies no\n // row in an UPDATE or DELETE. Before 18 Postgres sends those anyway.\n // REPLICA IDENTITY FULL identifies the row by its other columns.\n const generatedKeys = withoutIndex.length\n ? await sql<{schema: string; tableName: string}[]>`\n SELECT ns.nspname AS \"schema\", c.relname AS \"tableName\"\n FROM pg_class c JOIN pg_namespace ns ON ns.oid = c.relnamespace\n WHERE c.oid = ANY (${withoutIndex}::oid[]) AND c.relreplident = 'd'\n AND EXISTS (\n SELECT 1 FROM pg_index i\n JOIN pg_attribute a\n ON a.attrelid = i.indrelid AND a.attnum = ANY (i.indkey)\n WHERE i.indrelid = c.oid AND i.indisprimary\n AND a.attgenerated != '')`\n : [];\n for (const {schema, tableName} of generatedKeys) {\n lc.info?.(\n `setting REPLICA IDENTITY FULL for \"${tableName}\", ` +\n `which has a generated column in its primary key`,\n );\n await sql`\n ALTER TABLE ${sql(schema)}.${sql(tableName)} REPLICA IDENTITY FULL`;\n }\n for (const {schema, tableName, indexName} of replicaIdentities) {\n lc.info?.(\n `setting \"${indexName}\" as the REPLICA IDENTITY for \"${tableName}\"`,\n );\n await sql`\n ALTER TABLE ${sql(schema)}.${sql(tableName)} \n REPLICA IDENTITY USING INDEX ${sql(indexName)}`;\n }\n },\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;AAqCA,IAAM,yBAAyB;;;;;;AAO/B,SAAgB,wBAAwB,MAAoB;CAC1D,IAAI,CAAC,uBAAuB,KAAK,IAAI,GACnC,MAAM,IAAI,MACR,6BAA6B,KAAK,+GAEpC;CAEF,IAAI,KAAK,SAAS,IAChB,MAAM,IAAI,MACR,qBAAqB,KAAK,sDAC5B;AAEJ;AAEA,SAAgB,0BAA0B,EAAC,SAAe;CACxD,OAAO,IAAI,MAAM;AACnB;AAEA,SAAgB,sBAAsB,EAAC,OAAO,YAAoB;CAChE,OAAO,GAAG,MAAM,GAAG;AACrB;AAEA,SAAgB,sB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sC,UAAU,mDAElD;GACA,MAAM,GAAG;sBACK,IAAI,MAAM,EAAE,GAAG,IAAI,SAAS,EAAE;EAC9C;EACA,KAAK,MAAM,EAAC,QAAQ,WAAW,eAAc,mBAAmB;GAC9D,GAAG,OACD,YAAY,UAAU,iCAAiC,UAAU,EACnE;GACA,MAAM,GAAG;sBACK,IAAI,MAAM,EAAE,GAAG,IAAI,SAAS,EAAE;yCACX,IAAI,SAAS;EAChD;CACF,EACF;AACF"}
@@ -1,6 +1,11 @@
1
1
  import type { LogContext } from '@rocicorp/logger';
2
- import type { PublishedTableWithReplicaIdentity } from './published.ts';
2
+ import type { PublishedSchema, PublishedTableWithReplicaIdentity } from './published.ts';
3
3
  export declare function validate(lc: LogContext, table: PublishedTableWithReplicaIdentity): void;
4
+ /**
5
+ * Checks the names that share a namespace on the replica, which unlike
6
+ * Postgres holds tables and indexes of all schemas in one namespace.
7
+ */
8
+ export declare function validateRelationNames({ tables, indexes }: PublishedSchema): void;
4
9
  export declare class UnsupportedTableSchemaError extends Error {
5
10
  readonly name = "UnsupportedTableSchemaError";
6
11
  constructor(msg: string);
@@ -1 +1 @@
1
- {"version":3,"file":"validation.d.ts","sourceRoot":"","sources":["../../../../../../../../zero-cache/src/services/change-source/pg/schema/validation.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAC,UAAU,EAAC,MAAM,kBAAkB,CAAC;AAWjD,OAAO,KAAK,EAAC,iCAAiC,EAAC,MAAM,gBAAgB,CAAC;AAQtE,wBAAgB,QAAQ,CACtB,EAAE,EAAE,UAAU,EACd,KAAK,EAAE,iCAAiC,QAyCzC;AAED,qBAAa,2BAA4B,SAAQ,KAAK;IACpD,QAAQ,CAAC,IAAI,iCAAiC;IAE9C,YAAY,GAAG,EAAE,MAAM,EAEtB;CACF"}
1
+ {"version":3,"file":"validation.d.ts","sourceRoot":"","sources":["../../../../../../../../zero-cache/src/services/change-source/pg/schema/validation.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAC,UAAU,EAAC,MAAM,kBAAkB,CAAC;AAYjD,OAAO,KAAK,EACV,eAAe,EACf,iCAAiC,EAClC,MAAM,gBAAgB,CAAC;AAQxB,wBAAgB,QAAQ,CACtB,EAAE,EAAE,UAAU,EACd,KAAK,EAAE,iCAAiC,QAiDzC;AAOD;;;GAGG;AACH,wBAAgB,qBAAqB,CAAC,EAAC,MAAM,EAAE,OAAO,EAAC,EAAE,eAAe,QAmBvE;AAED,qBAAa,2BAA4B,SAAQ,KAAK;IACpD,QAAQ,CAAC,IAAI,iCAAiC;IAE9C,YAAY,GAAG,EAAE,MAAM,EAEtB;CACF"}
@@ -1,4 +1,5 @@
1
1
  import { ZERO_VERSION_COLUMN_NAME } from "../../../replicator/schema/constants.js";
2
+ import { liteTableName } from "../../../../types/names.js";
2
3
  import { mapPostgresToLite, warnIfDataTypeSupported } from "../../../../db/pg-to-lite.js";
3
4
  //#region ../zero-cache/src/services/change-source/pg/schema/validation.ts
4
5
  var ALLOWED_TABLE_CHARS = /^[A-Za-z_]+[A-Za-z0-9_-]*$/;
@@ -9,11 +10,34 @@ function validate(lc, table) {
9
10
  if (table.replicaIdentity === "n") throw new UnsupportedTableSchemaError(`Table "${table.name}" with REPLICA IDENTITY NOTHING cannot be replicated`);
10
11
  if (table.replicaIdentity === "i" && table.replicaIdentityColumns.length === 0) throw new UnsupportedTableSchemaError(`Table "${table.name}" is missing its REPLICA IDENTITY INDEX`);
11
12
  if (!ALLOWED_TABLE_CHARS.test(table.name)) throw new UnsupportedTableSchemaError(`Table "${table.name}" has invalid characters.`);
13
+ const columnNames = /* @__PURE__ */ new Map();
12
14
  for (const [col, spec] of Object.entries(mapPostgresToLite(table).columns)) {
13
15
  if (!ALLOWED_COLUMN_CHARS.test(col)) throw new UnsupportedTableSchemaError(`Column "${col}" in table "${table.name}" has invalid characters.`);
16
+ const other = columnNames.get(foldCase(col));
17
+ if (other !== void 0) throw new UnsupportedTableSchemaError(`Columns "${other}" and "${col}" in table "${table.name}" differ only by case, which the replica cannot represent.`);
18
+ columnNames.set(foldCase(col), col);
14
19
  warnIfDataTypeSupported(lc, spec.dataType, table.name, col);
15
20
  }
16
21
  }
22
+ function foldCase(name) {
23
+ return name.replace(/[A-Z]/g, (c) => c.toLowerCase());
24
+ }
25
+ /**
26
+ * Checks the names that share a namespace on the replica, which unlike
27
+ * Postgres holds tables and indexes of all schemas in one namespace.
28
+ */
29
+ function validateRelationNames({ tables, indexes }) {
30
+ const names = /* @__PURE__ */ new Map();
31
+ for (const name of [...tables.map((t) => liteTableName(t)), ...indexes.map((i) => liteTableName({
32
+ schema: i.schema,
33
+ name: i.name
34
+ }))]) {
35
+ if (foldCase(name).startsWith("sqlite_")) throw new UnsupportedTableSchemaError(`"${name}" starts with "sqlite_", which the replica reserves.`);
36
+ const other = names.get(foldCase(name));
37
+ if (other !== void 0) throw new UnsupportedTableSchemaError(`"${other}" and "${name}" have the same name on the replica, which does not distinguish case or tables from indexes.`);
38
+ names.set(foldCase(name), name);
39
+ }
40
+ }
17
41
  var UnsupportedTableSchemaError = class extends Error {
18
42
  name = "UnsupportedTableSchemaError";
19
43
  constructor(msg) {
@@ -21,6 +45,6 @@ var UnsupportedTableSchemaError = class extends Error {
21
45
  }
22
46
  };
23
47
  //#endregion
24
- export { UnsupportedTableSchemaError, validate };
48
+ export { UnsupportedTableSchemaError, validate, validateRelationNames };
25
49
 
26
50
  //# sourceMappingURL=validation.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"validation.js","names":[],"sources":["../../../../../../../../zero-cache/src/services/change-source/pg/schema/validation.ts"],"sourcesContent":["import type {LogContext} from '@rocicorp/logger';\nimport {\n mapPostgresToLite,\n warnIfDataTypeSupported,\n} from '../../../../db/pg-to-lite.ts';\nimport {\n Default,\n Index,\n Nothing,\n} from '../../../../db/postgres-replica-identity-enum.ts';\nimport {ZERO_VERSION_COLUMN_NAME} from '../../../replicator/schema/constants.ts';\nimport type {PublishedTableWithReplicaIdentity} from './published.ts';\n\nconst ALLOWED_TABLE_CHARS = /^[A-Za-z_]+[A-Za-z0-9_-]*$/;\n\n// Dots are allowed in column names since there is no need for\n// a schema/table delimiter when mapped to SQLite names.\nconst ALLOWED_COLUMN_CHARS = /^[A-Za-z_]+[.A-Za-z0-9_-]*$/;\n\nexport function validate(\n lc: LogContext,\n table: PublishedTableWithReplicaIdentity,\n) {\n if (ZERO_VERSION_COLUMN_NAME in table.columns) {\n throw new UnsupportedTableSchemaError(\n `Table \"${table.name}\" uses reserved column name \"${ZERO_VERSION_COLUMN_NAME}\"`,\n );\n }\n if (!table.primaryKey?.length && table.replicaIdentity === Default) {\n lc.warn?.(\n `\\n\\n\\n` +\n `Table \"${table.name}\" needs a primary key in order to be synced to clients. ` +\n `Add one with 'ALTER TABLE \"${table.name}\" ADD PRIMARY KEY (...)'.` +\n `\\n\\n\\n`,\n );\n }\n if (table.replicaIdentity === Nothing) {\n throw new UnsupportedTableSchemaError(\n `Table \"${table.name}\" with REPLICA IDENTITY NOTHING cannot be replicated`,\n );\n }\n if (\n table.replicaIdentity === Index &&\n table.replicaIdentityColumns.length === 0\n ) {\n throw new UnsupportedTableSchemaError(\n `Table \"${table.name}\" is missing its REPLICA IDENTITY INDEX`,\n );\n }\n if (!ALLOWED_TABLE_CHARS.test(table.name)) {\n throw new UnsupportedTableSchemaError(\n `Table \"${table.name}\" has invalid characters.`,\n );\n }\n for (const [col, spec] of Object.entries(mapPostgresToLite(table).columns)) {\n if (!ALLOWED_COLUMN_CHARS.test(col)) {\n throw new UnsupportedTableSchemaError(\n `Column \"${col}\" in table \"${table.name}\" has invalid characters.`,\n );\n }\n warnIfDataTypeSupported(lc, spec.dataType, table.name, col);\n }\n}\n\nexport class UnsupportedTableSchemaError extends Error {\n readonly name = 'UnsupportedTableSchemaError';\n\n constructor(msg: string) {\n super(msg);\n }\n}\n"],"mappings":";;;AAaA,IAAM,sBAAsB;AAI5B,IAAM,uBAAuB;AAE7B,SAAgB,SACd,IACA,OACA;CACA,IAAA,gBAAgC,MAAM,SACpC,MAAM,IAAI,4BACR,UAAU,MAAM,KAAK,+BAA+B,yBAAyB,EAC/E;CAEF,IAAI,CAAC,MAAM,YAAY,UAAU,MAAM,oBAAA,KACrC,GAAG,OACD,gBACY,MAAM,KAAK,qFACS,MAAM,KAAK,gCAE7C;CAEF,IAAI,MAAM,oBAAA,KACR,MAAM,IAAI,4BACR,UAAU,MAAM,KAAK,qDACvB;CAEF,IACE,MAAM,oBAAA,OACN,MAAM,uBAAuB,WAAW,GAExC,MAAM,IAAI,4BACR,UAAU,MAAM,KAAK,wCACvB;CAEF,IAAI,CAAC,oBAAoB,KAAK,MAAM,IAAI,GACtC,MAAM,IAAI,4BACR,UAAU,MAAM,KAAK,0BACvB;CAEF,KAAK,MAAM,CAAC,KAAK,SAAS,OAAO,QAAQ,kBAAkB,KAAK,CAAC,CAAC,OAAO,GAAG;EAC1E,IAAI,CAAC,qBAAqB,KAAK,GAAG,GAChC,MAAM,IAAI,4BACR,WAAW,IAAI,cAAc,MAAM,KAAK,0BAC1C;EAEF,wBAAwB,IAAI,KAAK,UAAU,MAAM,MAAM,GAAG;CAC5D;AACF;AAEA,IAAa,8BAAb,cAAiD,MAAM;CACrD,OAAgB;CAEhB,YAAY,KAAa;EACvB,MAAM,GAAG;CACX;AACF"}
1
+ {"version":3,"file":"validation.js","names":[],"sources":["../../../../../../../../zero-cache/src/services/change-source/pg/schema/validation.ts"],"sourcesContent":["import type {LogContext} from '@rocicorp/logger';\nimport {\n mapPostgresToLite,\n warnIfDataTypeSupported,\n} from '../../../../db/pg-to-lite.ts';\nimport {\n Default,\n Index,\n Nothing,\n} from '../../../../db/postgres-replica-identity-enum.ts';\nimport {liteTableName} from '../../../../types/names.ts';\nimport {ZERO_VERSION_COLUMN_NAME} from '../../../replicator/schema/constants.ts';\nimport type {\n PublishedSchema,\n PublishedTableWithReplicaIdentity,\n} from './published.ts';\n\nconst ALLOWED_TABLE_CHARS = /^[A-Za-z_]+[A-Za-z0-9_-]*$/;\n\n// Dots are allowed in column names since there is no need for\n// a schema/table delimiter when mapped to SQLite names.\nconst ALLOWED_COLUMN_CHARS = /^[A-Za-z_]+[.A-Za-z0-9_-]*$/;\n\nexport function validate(\n lc: LogContext,\n table: PublishedTableWithReplicaIdentity,\n) {\n if (ZERO_VERSION_COLUMN_NAME in table.columns) {\n throw new UnsupportedTableSchemaError(\n `Table \"${table.name}\" uses reserved column name \"${ZERO_VERSION_COLUMN_NAME}\"`,\n );\n }\n if (!table.primaryKey?.length && table.replicaIdentity === Default) {\n lc.warn?.(\n `\\n\\n\\n` +\n `Table \"${table.name}\" needs a primary key in order to be synced to clients. ` +\n `Add one with 'ALTER TABLE \"${table.name}\" ADD PRIMARY KEY (...)'.` +\n `\\n\\n\\n`,\n );\n }\n if (table.replicaIdentity === Nothing) {\n throw new UnsupportedTableSchemaError(\n `Table \"${table.name}\" with REPLICA IDENTITY NOTHING cannot be replicated`,\n );\n }\n if (\n table.replicaIdentity === Index &&\n table.replicaIdentityColumns.length === 0\n ) {\n throw new UnsupportedTableSchemaError(\n `Table \"${table.name}\" is missing its REPLICA IDENTITY INDEX`,\n );\n }\n if (!ALLOWED_TABLE_CHARS.test(table.name)) {\n throw new UnsupportedTableSchemaError(\n `Table \"${table.name}\" has invalid characters.`,\n );\n }\n const columnNames = new Map<string, string>();\n for (const [col, spec] of Object.entries(mapPostgresToLite(table).columns)) {\n if (!ALLOWED_COLUMN_CHARS.test(col)) {\n throw new UnsupportedTableSchemaError(\n `Column \"${col}\" in table \"${table.name}\" has invalid characters.`,\n );\n }\n const other = columnNames.get(foldCase(col));\n if (other !== undefined) {\n throw new UnsupportedTableSchemaError(\n `Columns \"${other}\" and \"${col}\" in table \"${table.name}\" differ only by case, which the replica cannot represent.`,\n );\n }\n columnNames.set(foldCase(col), col);\n warnIfDataTypeSupported(lc, spec.dataType, table.name, col);\n }\n}\n\n// SQLite compares names without regard to the case of ASCII letters.\nfunction foldCase(name: string): string {\n return name.replace(/[A-Z]/g, c => c.toLowerCase());\n}\n\n/**\n * Checks the names that share a namespace on the replica, which unlike\n * Postgres holds tables and indexes of all schemas in one namespace.\n */\nexport function validateRelationNames({tables, indexes}: PublishedSchema) {\n const names = new Map<string, string>();\n for (const name of [\n ...tables.map(t => liteTableName(t)),\n ...indexes.map(i => liteTableName({schema: i.schema, name: i.name})),\n ]) {\n if (foldCase(name).startsWith('sqlite_')) {\n throw new UnsupportedTableSchemaError(\n `\"${name}\" starts with \"sqlite_\", which the replica reserves.`,\n );\n }\n const other = names.get(foldCase(name));\n if (other !== undefined) {\n throw new UnsupportedTableSchemaError(\n `\"${other}\" and \"${name}\" have the same name on the replica, which does not distinguish case or tables from indexes.`,\n );\n }\n names.set(foldCase(name), name);\n }\n}\n\nexport class UnsupportedTableSchemaError extends Error {\n readonly name = 'UnsupportedTableSchemaError';\n\n constructor(msg: string) {\n super(msg);\n }\n}\n"],"mappings":";;;;AAiBA,IAAM,sBAAsB;AAI5B,IAAM,uBAAuB;AAE7B,SAAgB,SACd,IACA,OACA;CACA,IAAA,gBAAgC,MAAM,SACpC,MAAM,IAAI,4BACR,UAAU,MAAM,KAAK,+BAA+B,yBAAyB,EAC/E;CAEF,IAAI,CAAC,MAAM,YAAY,UAAU,MAAM,oBAAA,KACrC,GAAG,OACD,gBACY,MAAM,KAAK,qFACS,MAAM,KAAK,gCAE7C;CAEF,IAAI,MAAM,oBAAA,KACR,MAAM,IAAI,4BACR,UAAU,MAAM,KAAK,qDACvB;CAEF,IACE,MAAM,oBAAA,OACN,MAAM,uBAAuB,WAAW,GAExC,MAAM,IAAI,4BACR,UAAU,MAAM,KAAK,wCACvB;CAEF,IAAI,CAAC,oBAAoB,KAAK,MAAM,IAAI,GACtC,MAAM,IAAI,4BACR,UAAU,MAAM,KAAK,0BACvB;CAEF,MAAM,8BAAc,IAAI,IAAoB;CAC5C,KAAK,MAAM,CAAC,KAAK,SAAS,OAAO,QAAQ,kBAAkB,KAAK,CAAC,CAAC,OAAO,GAAG;EAC1E,IAAI,CAAC,qBAAqB,KAAK,GAAG,GAChC,MAAM,IAAI,4BACR,WAAW,IAAI,cAAc,MAAM,KAAK,0BAC1C;EAEF,MAAM,QAAQ,YAAY,IAAI,SAAS,GAAG,CAAC;EAC3C,IAAI,UAAU,KAAA,GACZ,MAAM,IAAI,4BACR,YAAY,MAAM,SAAS,IAAI,cAAc,MAAM,KAAK,2DAC1D;EAEF,YAAY,IAAI,SAAS,GAAG,GAAG,GAAG;EAClC,wBAAwB,IAAI,KAAK,UAAU,MAAM,MAAM,GAAG;CAC5D;AACF;AAGA,SAAS,SAAS,MAAsB;CACtC,OAAO,KAAK,QAAQ,WAAU,MAAK,EAAE,YAAY,CAAC;AACpD;;;;;AAMA,SAAgB,sBAAsB,EAAC,QAAQ,WAA2B;CACxE,MAAM,wBAAQ,IAAI,IAAoB;CACtC,KAAK,MAAM,QAAQ,CACjB,GAAG,OAAO,KAAI,MAAK,cAAc,CAAC,CAAC,GACnC,GAAG,QAAQ,KAAI,MAAK,cAAc;EAAC,QAAQ,EAAE;EAAQ,MAAM,EAAE;CAAI,CAAC,CAAC,CACrE,GAAG;EACD,IAAI,SAAS,IAAI,CAAC,CAAC,WAAW,SAAS,GACrC,MAAM,IAAI,4BACR,IAAI,KAAK,qDACX;EAEF,MAAM,QAAQ,MAAM,IAAI,SAAS,IAAI,CAAC;EACtC,IAAI,UAAU,KAAA,GACZ,MAAM,IAAI,4BACR,IAAI,MAAM,SAAS,KAAK,6FAC1B;EAEF,MAAM,IAAI,SAAS,IAAI,GAAG,IAAI;CAChC;AACF;AAEA,IAAa,8BAAb,cAAiD,MAAM;CACrD,OAAgB;CAEhB,YAAY,KAAa;EACvB,MAAM,GAAG;CACX;AACF"}
@@ -1,4 +1,5 @@
1
1
  import { deepEqual } from "../../../../../shared/src/json.js";
2
+ import { assignProperty, getOwnProperty } from "../../../../../shared/src/objects.js";
2
3
  //#region ../zero-cache/src/services/change-source/protocol/backfill-progress.ts
3
4
  /**
4
5
  * Whether two progress marks are on the same timeline, and are thus comparable.
@@ -99,17 +100,17 @@ function withResumePoint(req) {
99
100
  function getTableSuperset(req1, req2) {
100
101
  const columns = { ...req1.columns };
101
102
  for (const [name, col] of Object.entries(req2.columns)) {
102
- const exists = columns[name];
103
+ const exists = getOwnProperty(columns, name);
103
104
  if (!exists) {
104
- columns[name] = col;
105
+ assignProperty(columns, name, col);
105
106
  continue;
106
107
  }
107
108
  const { id, progress } = exists;
108
- if (progress === void 0 || col.progress === void 0 || !sameTimeline(progress, col.progress) || !deepEqual(id, col.id)) columns[name] = { id };
109
- else columns[name] = {
109
+ if (progress === void 0 || col.progress === void 0 || !sameTimeline(progress, col.progress) || !deepEqual(id, col.id)) assignProperty(columns, name, { id });
110
+ else assignProperty(columns, name, {
110
111
  id,
111
112
  progress: earlier(progress, col.progress)
112
- };
113
+ });
113
114
  }
114
115
  return {
115
116
  table: {
@@ -1 +1 @@
1
- {"version":3,"file":"backfill-progress.js","names":[],"sources":["../../../../../../../zero-cache/src/services/change-source/protocol/backfill-progress.ts"],"sourcesContent":["import {deepEqual} from '../../../../../shared/src/json.ts';\nimport type {\n BackfillProgressMark,\n BackfillRequest,\n Identifier,\n} from './current.ts';\n\n/**\n * Whether two progress marks are on the same timeline, and are thus comparable.\n */\nfunction sameTimeline(a: BackfillProgressMark, b: BackfillProgressMark) {\n return a.timeline === b.timeline;\n}\n\n/** Returns the earlier of two marks on the same timeline. */\nfunction earlier(\n a: BackfillProgressMark,\n b: BackfillProgressMark,\n): BackfillProgressMark {\n return b.progressMark < a.progressMark ? b : a;\n}\n\n/** Returns the later of two marks on the same timeline. */\nfunction later(\n a: BackfillProgressMark,\n b: BackfillProgressMark,\n): BackfillProgressMark {\n return b.progressMark > a.progressMark ? b : a;\n}\n\n/**\n * The result of applying a backfill message to a column's tracked progress.\n * If `accept` is true, `progress` is the column's new progress.\n */\nexport type AcceptResult =\n | {accept: true; progress: BackfillProgressMark | undefined}\n | {accept: false};\n\n/**\n * Applies the continuity policy of `backfill` (and `backfill-completed`)\n * messages to a column's `own` tracked progress, where `undefined` means that\n * the column has not received any backfill data (i.e. it needs a backfill\n * from scratch).\n *\n * * Messages without `progressMarks` are from pre-v8 replication-managers\n * and are accepted unconditionally (i.e. the legacy behavior), with no\n * change to the tracked progress.\n * * A message without a `previous` mark starts a backfill from scratch (or on\n * a new timeline), and is always accepted.\n * * Otherwise, the message is only accepted if it is on the same timeline as\n * `own`, and continues from a position at or before `own` (i.e. it does not\n * create a gap).\n *\n * `current` is unset for `backfill-completed` messages, which do not advance\n * the progress.\n */\nexport function acceptBackfill(\n own: BackfillProgressMark | undefined,\n marks:\n | {\n previous?: BackfillProgressMark | undefined;\n current?: BackfillProgressMark;\n }\n | undefined,\n): AcceptResult {\n if (marks === undefined) {\n return {accept: true, progress: own}; // legacy (pre-v8)\n }\n const {previous, current} = marks;\n // Starting from scratch is always accepted, as there can be no gap.\n if (previous === undefined) {\n return {accept: true, progress: current};\n }\n if (\n own === undefined ||\n !sameTimeline(own, previous) ||\n previous.progressMark > own.progressMark\n ) {\n return {accept: false};\n }\n return {\n accept: true,\n progress:\n current === undefined\n ? own\n : sameTimeline(own, current)\n ? later(own, current)\n : current,\n };\n}\n\n/**\n * Returns whether a stream whose progress (for a column) is at `stream`\n * will deliver all of the data needed by a subscriber whose progress (for the\n * same column) is at `subscriber`. A `stream` progress of `undefined` indicates\n * a backfill that will start from scratch, which covers all subscribers.\n */\nexport function covers(\n stream: BackfillProgressMark | undefined,\n subscriber: BackfillProgressMark | undefined,\n): boolean {\n return (\n stream === undefined ||\n (subscriber !== undefined &&\n sameTimeline(stream, subscriber) &&\n stream.progressMark <= subscriber.progressMark)\n );\n}\n\n/**\n * Returns the position from which a backfill for the `req` must start\n * in order to satisfy the progress of all of its columns, i.e. the earliest\n * progress mark, or `undefined` (i.e. from scratch) if any column has no\n * progress or if the columns are on different timelines.\n */\nexport function resumePoint(\n req: BackfillRequest,\n): BackfillProgressMark | undefined {\n let point: BackfillProgressMark | undefined;\n for (const {progress} of Object.values(req.columns)) {\n if (progress === undefined) {\n return undefined;\n }\n if (point === undefined) {\n point = progress;\n } else if (!sameTimeline(point, progress)) {\n return undefined;\n } else {\n point = earlier(point, progress);\n }\n }\n return point;\n}\n\n/**\n * Returns a copy of the `req` with the progress of every column set to\n * the request's {@link resumePoint}, i.e. the position from which the\n * backfill of the request will actually start.\n */\nexport function withResumePoint(req: BackfillRequest): BackfillRequest {\n const progress = resumePoint(req);\n return {\n table: req.table,\n columns: Object.fromEntries(\n Object.entries(req.columns).map(([col, {id}]) => [\n col,\n progress === undefined ? {id} : {id, progress},\n ]),\n ),\n };\n}\n\n/**\n * Merges two BackfillRequests for the same table into one that satisfies\n * both. Both requests are expected to reflect the same (current) upstream\n * schema. For columns in both requests, the earlier progress mark is chosen,\n * or no progress mark (i.e. from scratch) if they are on different timelines.\n * If a column's backfill IDs differ (which is unexpected), the ID of `req1`\n * is chosen, and the column is backfilled from scratch.\n */\nexport function getTableSuperset(\n req1: BackfillRequest,\n req2: BackfillRequest,\n): BackfillRequest {\n const columns = {...req1.columns};\n for (const [name, col] of Object.entries(req2.columns)) {\n const exists = columns[name];\n if (!exists) {\n columns[name] = col;\n continue;\n }\n const {id, progress} = exists;\n if (\n progress === undefined ||\n col.progress === undefined ||\n !sameTimeline(progress, col.progress) ||\n !deepEqual(id, col.id)\n ) {\n // Different timelines (or IDs). Start from scratch.\n columns[name] = {id};\n } else {\n columns[name] = {id, progress: earlier(progress, col.progress)};\n }\n }\n return {\n table: {\n ...req1.table,\n metadata: req1.table.metadata ?? req2.table.metadata,\n },\n columns,\n };\n}\n\nfunction tableKey({schema, name}: Identifier) {\n return JSON.stringify([schema, name]);\n}\n\n/**\n * Merges the BackfillRequests of multiple parties (e.g. subscribers) into\n * one request per table, using {@link getTableSuperset}.\n */\nexport function getSuperset(\n ...requestSets: Iterable<BackfillRequest>[]\n): BackfillRequest[] {\n const merged = new Map<string, BackfillRequest>();\n for (const requests of requestSets) {\n for (const req of requests) {\n const key = tableKey(req.table);\n const existing = merged.get(key);\n merged.set(key, existing ? getTableSuperset(existing, req) : req);\n }\n }\n return [...merged.values()];\n}\n"],"mappings":";;;;;AAUA,SAAS,aAAa,GAAyB,GAAyB;CACtE,OAAO,EAAE,aAAa,EAAE;AAC1B;;AAGA,SAAS,QACP,GACA,GACsB;CACtB,OAAO,EAAE,eAAe,EAAE,eAAe,IAAI;AAC/C;;AAGA,SAAS,MACP,GACA,GACsB;CACtB,OAAO,EAAE,eAAe,EAAE,eAAe,IAAI;AAC/C;;;;;;;;;;;;;;;;;;;AA4BA,SAAgB,eACd,KACA,OAMc;CACd,IAAI,UAAU,KAAA,GACZ,OAAO;EAAC,QAAQ;EAAM,UAAU;CAAG;CAErC,MAAM,EAAC,UAAU,YAAW;CAE5B,IAAI,aAAa,KAAA,GACf,OAAO;EAAC,QAAQ;EAAM,UAAU;CAAO;CAEzC,IACE,QAAQ,KAAA,KACR,CAAC,aAAa,KAAK,QAAQ,KAC3B,SAAS,eAAe,IAAI,cAE5B,OAAO,EAAC,QAAQ,MAAK;CAEvB,OAAO;EACL,QAAQ;EACR,UACE,YAAY,KAAA,IACR,MACA,aAAa,KAAK,OAAO,IACvB,MAAM,KAAK,OAAO,IAClB;CACV;AACF;;;;;;;AAQA,SAAgB,OACd,QACA,YACS;CACT,OACE,WAAW,KAAA,KACV,eAAe,KAAA,KACd,aAAa,QAAQ,UAAU,KAC/B,OAAO,gBAAgB,WAAW;AAExC;;;;;;;AAQA,SAAgB,YACd,KACkC;CAClC,IAAI;CACJ,KAAK,MAAM,EAAC,cAAa,OAAO,OAAO,IAAI,OAAO,GAAG;EACnD,IAAI,aAAa,KAAA,GACf;EAEF,IAAI,UAAU,KAAA,GACZ,QAAQ;OACH,IAAI,CAAC,aAAa,OAAO,QAAQ,GACtC;OAEA,QAAQ,QAAQ,OAAO,QAAQ;CAEnC;CACA,OAAO;AACT;;;;;;AAOA,SAAgB,gBAAgB,KAAuC;CACrE,MAAM,WAAW,YA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{"version":3,"file":"backfill-progress.js","names":[],"sources":["../../../../../../../zero-cache/src/services/change-source/protocol/backfill-progress.ts"],"sourcesContent":["import {deepEqual} from '../../../../../shared/src/json.ts';\nimport {\n assignProperty,\n getOwnProperty,\n} from '../../../../../shared/src/objects.ts';\nimport type {\n BackfillProgressMark,\n BackfillRequest,\n Identifier,\n} from './current.ts';\n\n/**\n * Whether two progress marks are on the same timeline, and are thus comparable.\n */\nfunction sameTimeline(a: BackfillProgressMark, b: BackfillProgressMark) {\n return a.timeline === b.timeline;\n}\n\n/** Returns the earlier of two marks on the same timeline. */\nfunction earlier(\n a: BackfillProgressMark,\n b: BackfillProgressMark,\n): BackfillProgressMark {\n return b.progressMark < a.progressMark ? b : a;\n}\n\n/** Returns the later of two marks on the same timeline. */\nfunction later(\n a: BackfillProgressMark,\n b: BackfillProgressMark,\n): BackfillProgressMark {\n return b.progressMark > a.progressMark ? b : a;\n}\n\n/**\n * The result of applying a backfill message to a column's tracked progress.\n * If `accept` is true, `progress` is the column's new progress.\n */\nexport type AcceptResult =\n | {accept: true; progress: BackfillProgressMark | undefined}\n | {accept: false};\n\n/**\n * Applies the continuity policy of `backfill` (and `backfill-completed`)\n * messages to a column's `own` tracked progress, where `undefined` means that\n * the column has not received any backfill data (i.e. it needs a backfill\n * from scratch).\n *\n * * Messages without `progressMarks` are from pre-v8 replication-managers\n * and are accepted unconditionally (i.e. the legacy behavior), with no\n * change to the tracked progress.\n * * A message without a `previous` mark starts a backfill from scratch (or on\n * a new timeline), and is always accepted.\n * * Otherwise, the message is only accepted if it is on the same timeline as\n * `own`, and continues from a position at or before `own` (i.e. it does not\n * create a gap).\n *\n * `current` is unset for `backfill-completed` messages, which do not advance\n * the progress.\n */\nexport function acceptBackfill(\n own: BackfillProgressMark | undefined,\n marks:\n | {\n previous?: BackfillProgressMark | undefined;\n current?: BackfillProgressMark;\n }\n | undefined,\n): AcceptResult {\n if (marks === undefined) {\n return {accept: true, progress: own}; // legacy (pre-v8)\n }\n const {previous, current} = marks;\n // Starting from scratch is always accepted, as there can be no gap.\n if (previous === undefined) {\n return {accept: true, progress: current};\n }\n if (\n own === undefined ||\n !sameTimeline(own, previous) ||\n previous.progressMark > own.progressMark\n ) {\n return {accept: false};\n }\n return {\n accept: true,\n progress:\n current === undefined\n ? own\n : sameTimeline(own, current)\n ? later(own, current)\n : current,\n };\n}\n\n/**\n * Returns whether a stream whose progress (for a column) is at `stream`\n * will deliver all of the data needed by a subscriber whose progress (for the\n * same column) is at `subscriber`. A `stream` progress of `undefined` indicates\n * a backfill that will start from scratch, which covers all subscribers.\n */\nexport function covers(\n stream: BackfillProgressMark | undefined,\n subscriber: BackfillProgressMark | undefined,\n): boolean {\n return (\n stream === undefined ||\n (subscriber !== undefined &&\n sameTimeline(stream, subscriber) &&\n stream.progressMark <= subscriber.progressMark)\n );\n}\n\n/**\n * Returns the position from which a backfill for the `req` must start\n * in order to satisfy the progress of all of its columns, i.e. the earliest\n * progress mark, or `undefined` (i.e. from scratch) if any column has no\n * progress or if the columns are on different timelines.\n */\nexport function resumePoint(\n req: BackfillRequest,\n): BackfillProgressMark | undefined {\n let point: BackfillProgressMark | undefined;\n for (const {progress} of Object.values(req.columns)) {\n if (progress === undefined) {\n return undefined;\n }\n if (point === undefined) {\n point = progress;\n } else if (!sameTimeline(point, progress)) {\n return undefined;\n } else {\n point = earlier(point, progress);\n }\n }\n return point;\n}\n\n/**\n * Returns a copy of the `req` with the progress of every column set to\n * the request's {@link resumePoint}, i.e. the position from which the\n * backfill of the request will actually start.\n */\nexport function withResumePoint(req: BackfillRequest): BackfillRequest {\n const progress = resumePoint(req);\n return {\n table: req.table,\n columns: Object.fromEntries(\n Object.entries(req.columns).map(([col, {id}]) => [\n col,\n progress === undefined ? {id} : {id, progress},\n ]),\n ),\n };\n}\n\n/**\n * Merges two BackfillRequests for the same table into one that satisfies\n * both. Both requests are expected to reflect the same (current) upstream\n * schema. For columns in both requests, the earlier progress mark is chosen,\n * or no progress mark (i.e. from scratch) if they are on different timelines.\n * If a column's backfill IDs differ (which is unexpected), the ID of `req1`\n * is chosen, and the column is backfilled from scratch.\n */\nexport function getTableSuperset(\n req1: BackfillRequest,\n req2: BackfillRequest,\n): BackfillRequest {\n const columns = {...req1.columns};\n for (const [name, col] of Object.entries(req2.columns)) {\n // Not columns[name], which is Object.prototype for a column named\n // __proto__ that is missing from req1.\n const exists = getOwnProperty(columns, name);\n if (!exists) {\n assignProperty(columns, name, col);\n continue;\n }\n const {id, progress} = exists;\n if (\n progress === undefined ||\n col.progress === undefined ||\n !sameTimeline(progress, col.progress) ||\n !deepEqual(id, col.id)\n ) {\n // Different timelines (or IDs). Start from scratch.\n assignProperty(columns, name, {id});\n } else {\n assignProperty(columns, name, {\n id,\n progress: earlier(progress, col.progress),\n });\n }\n }\n return {\n table: {\n ...req1.table,\n metadata: req1.table.metadata ?? req2.table.metadata,\n },\n columns,\n };\n}\n\nfunction tableKey({schema, name}: Identifier) {\n return JSON.stringify([schema, name]);\n}\n\n/**\n * Merges the BackfillRequests of multiple parties (e.g. subscribers) into\n * one request per table, using {@link getTableSuperset}.\n */\nexport function getSuperset(\n ...requestSets: Iterable<BackfillRequest>[]\n): BackfillRequest[] {\n const merged = new Map<string, BackfillRequest>();\n for (const requests of requestSets) {\n for (const req of requests) {\n const key = tableKey(req.table);\n const existing = merged.get(key);\n merged.set(key, existing ? getTableSuperset(existing, req) : req);\n }\n }\n return [...merged.values()];\n}\n"],"mappings":";;;;;;AAcA,SAAS,aAAa,GAAyB,GAAyB;CACtE,OAAO,EAAE,aAAa,EAAE;AAC1B;;AAGA,SAAS,QACP,GACA,GACsB;CACtB,OAAO,EAAE,eAAe,EAAE,eAAe,IAAI;AAC/C;;AAGA,SAAS,MACP,GACA,GACsB;CACtB,OAAO,EAAE,eAAe,EAAE,eAAe,IAAI;AAC/C;;;;;;;;;;;;;;;;;;;AA4BA,SAAgB,eACd,KACA,OAMc;CACd,IAAI,UAAU,KAAA,GACZ,OAAO;EAAC,QAA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AAQ;GACX,eAAe,SAAS,MAAM,GAAG;GACjC;EACF;EACA,MAAM,EAAC,IAAI,aAAY;EACvB,IACE,aAAa,KAAA,KACb,IAAI,aAAa,KAAA,KACjB,CAAC,aAAa,UAAU,IAAI,QAAQ,KACpC,CAAC,UAAU,IAAI,IAAI,EAAE,GAGrB,eAAe,SAAS,MAAM,EAAC,GAAE,CAAC;OAElC,eAAe,SAAS,MAAM;GAC5B;GACA,UAAU,QAAQ,UAAU,IAAI,QAAQ;EAC1C,CAAC;CAEL;CACA,OAAO;EACL,OAAO;GACL,GAAG,KAAK;GACR,UAAU,KAAK,MAAM,YAAY,KAAK,MAAM;EAC9C;EACA;CACF;AACF;AAEA,SAAS,SAAS,EAAC,QAAQ,QAAmB;CAC5C,OAAO,KAAK,UAAU,CAAC,QAAQ,IAAI,CAAC;AACtC;;;;;AAMA,SAAgB,YACd,GAAG,aACgB;CACnB,MAAM,yBAAS,IAAI,IAA6B;CAChD,KAAK,MAAM,YAAY,aACrB,KAAK,MAAM,OAAO,UAAU;EAC1B,MAAM,MAAM,SAAS,IAAI,KAAK;EAC9B,MAAM,WAAW,OAAO,IAAI,GAAG;EAC/B,OAAO,IAAI,KAAK,WAAW,iBAAiB,UAAU,GAAG,IAAI,GAAG;CAClE;CAEF,OAAO,CAAC,GAAG,OAAO,OAAO,CAAC;AAC5B"}
@@ -1,5 +1,6 @@
1
1
  import { unreachable } from "../../../../shared/src/asserts.js";
2
2
  import { deepEqual } from "../../../../shared/src/json.js";
3
+ import { assignProperty, getOwnProperty } from "../../../../shared/src/objects.js";
3
4
  import { BigIntJSON } from "../../../../shared/src/bigint-json.js";
4
5
  import { schemaChangeTags } from "../change-source/protocol/current/schema-change-tags.js";
5
6
  import { cookieOps } from "../replicator/change-log-cookies.js";
@@ -178,11 +179,11 @@ var BackfillState = class {
178
179
  if (!backfill) return [];
179
180
  const ignored = [];
180
181
  for (const name of [...relation.rowKey.columns, ...columns]) {
181
- const col = backfill.columns[name];
182
+ const col = getOwnProperty(backfill.columns, name);
182
183
  if (!col) continue;
183
184
  const updated = { ...col };
184
185
  if (apply(col.progress, updated, name)) {
185
- if (name in backfill.columns) backfill.columns[name] = updated;
186
+ if (Object.hasOwn(backfill.columns, name)) assignProperty(backfill.columns, name, updated);
186
187
  } else ignored.push(`${relation.schema}.${relation.name}.${name}`);
187
188
  }
188
189
  return ignored;
@@ -211,7 +212,7 @@ var BackfillState = class {
211
212
  };
212
213
  this.#state.set(key, backfill);
213
214
  }
214
- backfill.columns[op.column] = { id: op.backfill };
215
+ assignProperty(backfill.columns, op.column, { id: op.backfill });
215
216
  break;
216
217
  }
217
218
  case "rename-table": {
@@ -229,10 +230,10 @@ var BackfillState = class {
229
230
  break;
230
231
  case "rename-column": {
231
232
  const backfill = this.#state.get(tableKey(op.table));
232
- const col = backfill?.columns[op.old];
233
- if (backfill && col) {
233
+ if (backfill && Object.hasOwn(backfill.columns, op.old)) {
234
+ const col = backfill.columns[op.old];
234
235
  delete backfill.columns[op.old];
235
- backfill.columns[op.new] = col;
236
+ assignProperty(backfill.columns, op.new, col);
236
237
  }
237
238
  break;
238
239
  }
@@ -1 +1 @@
1
- {"version":3,"file":"backfill-state.js","names":[],"sources":["../../../../../../zero-cache/src/services/change-streamer/backfill-state.ts"],"sourcesContent":["import {unreachable} from '../../../../shared/src/asserts.ts';\nimport {BigIntJSON} from '../../../../shared/src/bigint-json.ts';\nimport {deepEqual} from '../../../../shared/src/json.ts';\nimport {\n acceptBackfill,\n covers,\n} from '../change-source/protocol/backfill-progress.ts';\nimport type {\n BackfillRequest,\n ChangeStreamData,\n Identifier,\n SchemaChange,\n TableMetadata,\n} from '../change-source/protocol/current.ts';\nimport {schemaChangeTags} from '../change-source/protocol/current/schema-change-tags.ts';\nimport {cookieOps} from '../replicator/change-log-cookies.ts';\nimport type {ChangeTag, WatermarkedChange} from './change-streamer.ts';\n\nfunction tableKey({schema, name}: Identifier) {\n return JSON.stringify([schema, name]);\n}\n\ntype Column = BackfillRequest['columns'][string];\n\n/** A mutable BackfillRequest. */\ntype Backfill = {\n table: {schema: string; name: string; metadata: TableMetadata | null};\n columns: Record<string, Column>;\n};\n\ntype State = Map<string, Backfill>;\n\nfunction clone(state: State): State {\n return new Map(\n Array.from(state, ([key, {table, columns}]) => [\n key,\n {table: {...table}, columns: {...columns}},\n ]),\n );\n}\n\n/**\n * Tags of messages that affect the backfill state. Other messages need not be\n * parsed.\n */\nconst RELEVANT_TAGS = new Set<ChangeTag>([\n 'backfill',\n ...schemaChangeTags.filter(t => t !== 'create-index' && t !== 'drop-index'),\n]);\n\n// Serialized changes are typically forwarded (as the same string) to every\n// subscriber, so a single entry cache avoids re-parsing the same message for\n// each subscriber.\nlet lastParsed: {json: string; change: ChangeStreamData} | undefined;\n\nfunction parse(json: string): ChangeStreamData {\n if (lastParsed?.json !== json) {\n lastParsed = {json, change: BigIntJSON.parse(json) as ChangeStreamData};\n }\n return lastParsed.change;\n}\n\n/**\n * Tracks the state of the pending backfills (and their progress) of a party\n * in the replication stream (e.g. a subscriber, or the change-log itself), by\n * applying the same policies that a subscriber applies to its replica:\n * schema changes are folded with the {@link cookieOps} shared by the\n * cookie jars, and `backfill` / `backfill-completed` messages are accepted\n * or ignored with the continuity policy of {@link acceptBackfill}.\n *\n * Changes are applied transactionally: the changes of a transaction are\n * discarded if it is rolled back, and {@link requests()} only reflects\n * committed transactions.\n */\nexport class BackfillState {\n #state: State;\n #beforeTx: State | null = null;\n\n constructor(requests: readonly BackfillRequest[] = []) {\n this.#state = new Map(\n requests\n .filter(req => Object.keys(req.columns).length > 0)\n .map(({table, columns}) => [\n tableKey(table),\n {table: {...table}, columns: {...columns}},\n ]),\n );\n }\n\n get #committed(): State {\n return this.#beforeTx ?? this.#state;\n }\n\n /** The (committed) pending backfills. */\n requests(): BackfillRequest[] {\n return [...clone(this.#committed).values()];\n }\n\n /**\n * Returns the `requests` with the (committed) progress of this state\n * applied to the columns that are pending in both, i.e. same table, column,\n * and backfill ID. Other columns have no progress (i.e. from scratch).\n */\n withProgress(requests: readonly BackfillRequest[]): BackfillRequest[] {\n const state = this.#committed;\n return requests.map(({table, columns}) => {\n const tracked = state.get(tableKey(table))?.columns;\n return {\n table,\n columns: Object.fromEntries(\n Object.entries(columns).map(([name, {id}]) => {\n const col = tracked?.[name];\n return [\n name,\n col?.progress && deepEqual(col.id, id)\n ? {id, progress: col.progress}\n : {id},\n ];\n }),\n ),\n };\n });\n }\n\n /** Whether there are no (committed) pending backfills. */\n get empty(): boolean {\n return this.#committed.size === 0;\n }\n\n /**\n * Returns the columns (as `schema.table.column` strings) with (committed)\n * pending backfills that are not covered by the (committed) progress of the\n * `stream`, i.e. columns for which the `stream` will not deliver all of the\n * necessary data.\n */\n uncovered(stream: BackfillState): string[] {\n const uncovered: string[] = [];\n const streamState = stream.#committed;\n for (const [key, {table, columns}] of this.#committed) {\n const streamColumns = streamState.get(key)?.columns;\n for (const [name, {id, progress}] of Object.entries(columns)) {\n const s = streamColumns?.[name];\n if (!s || !deepEqual(s.id, id) || !covers(s.progress, progress)) {\n uncovered.push(`${table.schema}.${table.name}.${name}`);\n }\n }\n }\n return uncovered;\n }\n\n /**\n * Applies a serialized change, parsing it only if it is relevant.\n *\n * @returns The columns (as `schema.table.column` strings) of a backfill\n * message that were ignored due to the continuity policy.\n */\n applySerialized([, tag, json]: WatermarkedChange): string[] {\n switch (tag) {\n case 'begin':\n this.#begin();\n return [];\n case 'commit':\n this.#commit();\n return [];\n case 'rollback':\n this.#rollback();\n return [];\n }\n if (!RELEVANT_TAGS.has(tag)) {\n return [];\n }\n return this.apply(parse(json));\n }\n\n /**\n * Applies a change.\n *\n * @returns The columns (as `schema.table.column` strings) of a backfill\n * message that were ignored due to the continuity policy.\n */\n apply(change: ChangeStreamData): string[] {\n switch (change[0]) {\n case 'begin':\n this.#begin();\n return [];\n case 'commit':\n this.#commit();\n return [];\n case 'rollback':\n this.#rollback();\n return [];\n }\n const msg = change[1];\n switch (msg.tag) {\n case 'backfill': {\n const {relation, columns, progressMarks} = msg;\n return this.#applyBackfill(relation, columns, (progress, col) => {\n const result = acceptBackfill(progress, progressMarks);\n if (result.accept) {\n col.progress = result.progress;\n if (col.progress === undefined) {\n delete col.progress;\n }\n }\n return result.accept;\n });\n }\n case 'backfill-completed': {\n const {relation, columns, progressMarks} = msg;\n const backfill = this.#state.get(tableKey(relation));\n const ignored = this.#applyBackfill(\n relation,\n columns,\n (progress, _, name) => {\n const {accept} = acceptBackfill(\n progress,\n progressMarks && {previous: progressMarks.previous},\n );\n if (accept && backfill) {\n delete backfill.columns[name];\n }\n return accept;\n },\n );\n if (backfill && Object.keys(backfill.columns).length === 0) {\n this.#state.delete(tableKey(relation));\n }\n return ignored;\n }\n case 'create-table':\n case 'rename-table':\n case 'update-table-metadata':\n case 'add-column':\n case 'update-column':\n case 'drop-column':\n case 'drop-table':\n this.#applySchemaChange(msg);\n return [];\n }\n return [];\n }\n\n #applyBackfill(\n relation: {schema: string; name: string; rowKey: {columns: string[]}},\n columns: readonly string[],\n apply: (progress: Column['progress'], col: Column, name: string) => boolean,\n ): string[] {\n const backfill = this.#state.get(tableKey(relation));\n if (!backfill) {\n return [];\n }\n const ignored: string[] = [];\n // rowKey columns are excluded from `columns` but are backfilled with them\n // (e.g. for a new table).\n for (const name of [...relation.rowKey.columns, ...columns]) {\n const col = backfill.columns[name];\n if (!col) {\n continue;\n }\n // Copy-on-write, since the column object may be shared with the\n // pre-transaction state.\n const updated = {...col};\n if (apply(col.progress, updated, name)) {\n if (name in backfill.columns) {\n backfill.columns[name] = updated;\n }\n } else {\n ignored.push(`${relation.schema}.${relation.name}.${name}`);\n }\n }\n return ignored;\n }\n\n #applySchemaChange(change: SchemaChange) {\n // Table metadata specified in the same change (e.g. a `create-table` or\n // `add-column`), for backfills of tables that are not yet tracked.\n const metadata = new Map<string, TableMetadata>();\n\n for (const op of cookieOps(change)) {\n switch (op.op) {\n case 'upsert-metadata': {\n const key = tableKey(op.table);\n metadata.set(key, op.metadata);\n const backfill = this.#state.get(key);\n if (backfill) {\n backfill.table.metadata = op.metadata;\n }\n break;\n }\n case 'upsert-backfill': {\n const key = tableKey(op.table);\n let backfill = this.#state.get(key);\n if (!backfill) {\n backfill = {\n table: {\n schema: op.table.schema,\n name: op.table.name,\n metadata: metadata.get(key) ?? null,\n },\n columns: {},\n };\n this.#state.set(key, backfill);\n }\n // A new backfill always starts from scratch.\n backfill.columns[op.column] = {id: op.backfill};\n break;\n }\n case 'rename-table': {\n const backfill = this.#state.get(tableKey(op.old));\n if (backfill) {\n this.#state.delete(tableKey(op.old));\n backfill.table.schema = op.new.schema;\n backfill.table.name = op.new.name;\n this.#state.set(tableKey(op.new), backfill);\n }\n break;\n }\n case 'drop-table':\n this.#state.delete(tableKey(op.table));\n break;\n case 'rename-column': {\n const backfill = this.#state.get(tableKey(op.table));\n const col = backfill?.columns[op.old];\n if (backfill && col) {\n delete backfill.columns[op.old];\n backfill.columns[op.new] = col;\n }\n break;\n }\n case 'drop-column': {\n const key = tableKey(op.table);\n const backfill = this.#state.get(key);\n if (backfill) {\n delete backfill.columns[op.column];\n if (Object.keys(backfill.columns).length === 0) {\n this.#state.delete(key);\n }\n }\n break;\n }\n case 'complete-backfill':\n // Only produced for `backfill-completed`, which is handled\n // separately (with the continuity policy).\n throw new Error(`unexpected ${op.op} op`);\n default:\n unreachable(op);\n }\n }\n }\n\n #begin() {\n // Tolerate a missing commit/rollback, e.g. from an interrupted stream.\n this.#beforeTx ??= clone(this.#state);\n }\n\n #commit() {\n this.#beforeTx = null;\n }\n\n #rollback() {\n if (this.#beforeTx) {\n this.#state = this.#beforeTx;\n this.#beforeTx = null;\n }\n }\n}\n"],"mappings":";;;;;;;AAkBA,SAAS,SAAS,EAAC,QAAQ,QAAmB;CAC5C,OAAO,KAAK,UAAU,CAAC,QAAQ,IAAI,CAAC;AACtC;AAYA,SAAS,MAAM,OAAqB;CAClC,OAAO,IAAI,IACT,MAAM,KAAK,QAAQ,CAAC,KAAK,EAAC,OAAO,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C3B,SAAS,QAAQ,GAAG,OAAO;IAC7B;IACA;GACF;GACA,KAAK,eAAe;IAClB,MAAM,MAAM,SAAS,GAAG,KAAK;IAC7B,MAAM,WAAW,KAAK,OAAO,IAAI,GAAG;IACpC,IAAI,UAAU;KACZ,OAAO,SAAS,QAAQ,GAAG;KAC3B,IAAI,OAAO,KAAK,SAAS,OAAO,CAAC,CAAC,WAAW,GAC3C,KAAK,OAAO,OAAO,GAAG;IAE1B;IACA;GACF;GACA,KAAK,qBAGH,MAAM,IAAI,MAAM,cAAc,GAAG,GAAG,IAAI;GAC1C,SACE,YAAY,EAAE;EAClB;CAEJ;CAEA,SAAS;EAEP,KAAK,cAAc,MAAM,KAAK,MAAM;CACtC;CAEA,UAAU;EACR,KAAK,YAAY;CACnB;CAEA,YAAY;EACV,IAAI,KAAK,WAAW;GAClB,KAAK,SAAS,KAAK;GACnB,KAAK,YAAY;EACnB;CACF;AACF"}
1
+ {"version":3,"file":"backfill-state.js","names":[],"sources":["../../../../../../zero-cache/src/services/change-streamer/backfill-state.ts"],"sourcesContent":["import {unreachable} from '../../../../shared/src/asserts.ts';\nimport {BigIntJSON} from '../../../../shared/src/bigint-json.ts';\nimport {deepEqual} from '../../../../shared/src/json.ts';\nimport {\n assignProperty,\n getOwnProperty,\n} from '../../../../shared/src/objects.ts';\nimport {\n acceptBackfill,\n covers,\n} from '../change-source/protocol/backfill-progress.ts';\nimport type {\n BackfillRequest,\n ChangeStreamData,\n Identifier,\n SchemaChange,\n TableMetadata,\n} from '../change-source/protocol/current.ts';\nimport {schemaChangeTags} from '../change-source/protocol/current/schema-change-tags.ts';\nimport {cookieOps} from '../replicator/change-log-cookies.ts';\nimport type {ChangeTag, WatermarkedChange} from './change-streamer.ts';\n\nfunction tableKey({schema, name}: Identifier) {\n return JSON.stringify([schema, name]);\n}\n\ntype Column = BackfillRequest['columns'][string];\n\n/** A mutable BackfillRequest. */\ntype Backfill = {\n table: {schema: string; name: string; metadata: TableMetadata | null};\n columns: Record<string, Column>;\n};\n\ntype State = Map<string, Backfill>;\n\nfunction clone(state: State): State {\n return new Map(\n Array.from(state, ([key, {table, columns}]) => [\n key,\n {table: {...table}, columns: {...columns}},\n ]),\n );\n}\n\n/**\n * Tags of messages that affect the backfill state. Other messages need not be\n * parsed.\n */\nconst RELEVANT_TAGS = new Set<ChangeTag>([\n 'backfill',\n ...schemaChangeTags.filter(t => t !== 'create-index' && t !== 'drop-index'),\n]);\n\n// Serialized changes are typically forwarded (as the same string) to every\n// subscriber, so a single entry cache avoids re-parsing the same message for\n// each subscriber.\nlet lastParsed: {json: string; change: ChangeStreamData} | undefined;\n\nfunction parse(json: string): ChangeStreamData {\n if (lastParsed?.json !== json) {\n lastParsed = {json, change: BigIntJSON.parse(json) as ChangeStreamData};\n }\n return lastParsed.change;\n}\n\n/**\n * Tracks the state of the pending backfills (and their progress) of a party\n * in the replication stream (e.g. a subscriber, or the change-log itself), by\n * applying the same policies that a subscriber applies to its replica:\n * schema changes are folded with the {@link cookieOps} shared by the\n * cookie jars, and `backfill` / `backfill-completed` messages are accepted\n * or ignored with the continuity policy of {@link acceptBackfill}.\n *\n * Changes are applied transactionally: the changes of a transaction are\n * discarded if it is rolled back, and {@link requests()} only reflects\n * committed transactions.\n */\nexport class BackfillState {\n #state: State;\n #beforeTx: State | null = null;\n\n constructor(requests: readonly BackfillRequest[] = []) {\n this.#state = new Map(\n requests\n .filter(req => Object.keys(req.columns).length > 0)\n .map(({table, columns}) => [\n tableKey(table),\n {table: {...table}, columns: {...columns}},\n ]),\n );\n }\n\n get #committed(): State {\n return this.#beforeTx ?? this.#state;\n }\n\n /** The (committed) pending backfills. */\n requests(): BackfillRequest[] {\n return [...clone(this.#committed).values()];\n }\n\n /**\n * Returns the `requests` with the (committed) progress of this state\n * applied to the columns that are pending in both, i.e. same table, column,\n * and backfill ID. Other columns have no progress (i.e. from scratch).\n */\n withProgress(requests: readonly BackfillRequest[]): BackfillRequest[] {\n const state = this.#committed;\n return requests.map(({table, columns}) => {\n const tracked = state.get(tableKey(table))?.columns;\n return {\n table,\n columns: Object.fromEntries(\n Object.entries(columns).map(([name, {id}]) => {\n const col = tracked?.[name];\n return [\n name,\n col?.progress && deepEqual(col.id, id)\n ? {id, progress: col.progress}\n : {id},\n ];\n }),\n ),\n };\n });\n }\n\n /** Whether there are no (committed) pending backfills. */\n get empty(): boolean {\n return this.#committed.size === 0;\n }\n\n /**\n * Returns the columns (as `schema.table.column` strings) with (committed)\n * pending backfills that are not covered by the (committed) progress of the\n * `stream`, i.e. columns for which the `stream` will not deliver all of the\n * necessary data.\n */\n uncovered(stream: BackfillState): string[] {\n const uncovered: string[] = [];\n const streamState = stream.#committed;\n for (const [key, {table, columns}] of this.#committed) {\n const streamColumns = streamState.get(key)?.columns;\n for (const [name, {id, progress}] of Object.entries(columns)) {\n const s = streamColumns?.[name];\n if (!s || !deepEqual(s.id, id) || !covers(s.progress, progress)) {\n uncovered.push(`${table.schema}.${table.name}.${name}`);\n }\n }\n }\n return uncovered;\n }\n\n /**\n * Applies a serialized change, parsing it only if it is relevant.\n *\n * @returns The columns (as `schema.table.column` strings) of a backfill\n * message that were ignored due to the continuity policy.\n */\n applySerialized([, tag, json]: WatermarkedChange): string[] {\n switch (tag) {\n case 'begin':\n this.#begin();\n return [];\n case 'commit':\n this.#commit();\n return [];\n case 'rollback':\n this.#rollback();\n return [];\n }\n if (!RELEVANT_TAGS.has(tag)) {\n return [];\n }\n return this.apply(parse(json));\n }\n\n /**\n * Applies a change.\n *\n * @returns The columns (as `schema.table.column` strings) of a backfill\n * message that were ignored due to the continuity policy.\n */\n apply(change: ChangeStreamData): string[] {\n switch (change[0]) {\n case 'begin':\n this.#begin();\n return [];\n case 'commit':\n this.#commit();\n return [];\n case 'rollback':\n this.#rollback();\n return [];\n }\n const msg = change[1];\n switch (msg.tag) {\n case 'backfill': {\n const {relation, columns, progressMarks} = msg;\n return this.#applyBackfill(relation, columns, (progress, col) => {\n const result = acceptBackfill(progress, progressMarks);\n if (result.accept) {\n col.progress = result.progress;\n if (col.progress === undefined) {\n delete col.progress;\n }\n }\n return result.accept;\n });\n }\n case 'backfill-completed': {\n const {relation, columns, progressMarks} = msg;\n const backfill = this.#state.get(tableKey(relation));\n const ignored = this.#applyBackfill(\n relation,\n columns,\n (progress, _, name) => {\n const {accept} = acceptBackfill(\n progress,\n progressMarks && {previous: progressMarks.previous},\n );\n if (accept && backfill) {\n delete backfill.columns[name];\n }\n return accept;\n },\n );\n if (backfill && Object.keys(backfill.columns).length === 0) {\n this.#state.delete(tableKey(relation));\n }\n return ignored;\n }\n case 'create-table':\n case 'rename-table':\n case 'update-table-metadata':\n case 'add-column':\n case 'update-column':\n case 'drop-column':\n case 'drop-table':\n this.#applySchemaChange(msg);\n return [];\n }\n return [];\n }\n\n #applyBackfill(\n relation: {schema: string; name: string; rowKey: {columns: string[]}},\n columns: readonly string[],\n apply: (progress: Column['progress'], col: Column, name: string) => boolean,\n ): string[] {\n const backfill = this.#state.get(tableKey(relation));\n if (!backfill) {\n return [];\n }\n const ignored: string[] = [];\n // rowKey columns are excluded from `columns` but are backfilled with them\n // (e.g. for a new table).\n for (const name of [...relation.rowKey.columns, ...columns]) {\n // Not backfill.columns[name], which is Object.prototype for a column\n // named __proto__ that is not being backfilled.\n const col = getOwnProperty(backfill.columns, name);\n if (!col) {\n continue;\n }\n // Copy-on-write, since the column object may be shared with the\n // pre-transaction state.\n const updated = {...col};\n if (apply(col.progress, updated, name)) {\n if (Object.hasOwn(backfill.columns, name)) {\n assignProperty(backfill.columns, name, updated);\n }\n } else {\n ignored.push(`${relation.schema}.${relation.name}.${name}`);\n }\n }\n return ignored;\n }\n\n #applySchemaChange(change: SchemaChange) {\n // Table metadata specified in the same change (e.g. a `create-table` or\n // `add-column`), for backfills of tables that are not yet tracked.\n const metadata = new Map<string, TableMetadata>();\n\n for (const op of cookieOps(change)) {\n switch (op.op) {\n case 'upsert-metadata': {\n const key = tableKey(op.table);\n metadata.set(key, op.metadata);\n const backfill = this.#state.get(key);\n if (backfill) {\n backfill.table.metadata = op.metadata;\n }\n break;\n }\n case 'upsert-backfill': {\n const key = tableKey(op.table);\n let backfill = this.#state.get(key);\n if (!backfill) {\n backfill = {\n table: {\n schema: op.table.schema,\n name: op.table.name,\n metadata: metadata.get(key) ?? null,\n },\n columns: {},\n };\n this.#state.set(key, backfill);\n }\n // A new backfill always starts from scratch.\n assignProperty(backfill.columns, op.column, {id: op.backfill});\n break;\n }\n case 'rename-table': {\n const backfill = this.#state.get(tableKey(op.old));\n if (backfill) {\n this.#state.delete(tableKey(op.old));\n backfill.table.schema = op.new.schema;\n backfill.table.name = op.new.name;\n this.#state.set(tableKey(op.new), backfill);\n }\n break;\n }\n case 'drop-table':\n this.#state.delete(tableKey(op.table));\n break;\n case 'rename-column': {\n const backfill = this.#state.get(tableKey(op.table));\n if (backfill && Object.hasOwn(backfill.columns, op.old)) {\n const col = backfill.columns[op.old];\n delete backfill.columns[op.old];\n assignProperty(backfill.columns, op.new, col);\n }\n break;\n }\n case 'drop-column': {\n const key = tableKey(op.table);\n const backfill = this.#state.get(key);\n if (backfill) {\n delete backfill.columns[op.column];\n if (Object.keys(backfill.columns).length === 0) {\n this.#state.delete(key);\n }\n }\n break;\n }\n case 'complete-backfill':\n // Only produced for `backfill-completed`, which is handled\n // separately (with the continuity policy).\n throw new Error(`unexpected ${op.op} op`);\n default:\n unreachable(op);\n }\n }\n }\n\n #begin() {\n // Tolerate a missing commit/rollback, e.g. from an interrupted stream.\n this.#beforeTx ??= clone(this.#state);\n }\n\n #commit() {\n this.#beforeTx = null;\n }\n\n #rollback() {\n if (this.#beforeTx) {\n this.#state = this.#beforeTx;\n this.#beforeTx = null;\n }\n }\n}\n"],"mappings":";;;;;;;;AAsBA,SAAS,SAAS,EAAC,QAAQ,QAAmB;CAC5C,OAAO,KAAK,UAAU,CAAC,QAAQ,IAAI,CAAC;AACtC;AAYA,SAAS,MAAM,OAAqB;CAClC,OAAO,IAAI,IACT,MAAM,KAAK,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Y,OAAO,OAAO,SAAS,SAAS,GAAG,GAAG,GAAG;KACvD,MAAM,MAAM,SAAS,QAAQ,GAAG;KAChC,OAAO,SAAS,QAAQ,GAAG;KAC3B,eAAe,SAAS,SAAS,GAAG,KAAK,GAAG;IAC9C;IACA;GACF;GACA,KAAK,eAAe;IAClB,MAAM,MAAM,SAAS,GAAG,KAAK;IAC7B,MAAM,WAAW,KAAK,OAAO,IAAI,GAAG;IACpC,IAAI,UAAU;KACZ,OAAO,SAAS,QAAQ,GAAG;KAC3B,IAAI,OAAO,KAAK,SAAS,OAAO,CAAC,CAAC,WAAW,GAC3C,KAAK,OAAO,OAAO,GAAG;IAE1B;IACA;GACF;GACA,KAAK,qBAGH,MAAM,IAAI,MAAM,cAAc,GAAG,GAAG,IAAI;GAC1C,SACE,YAAY,EAAE;EAClB;CAEJ;CAEA,SAAS;EAEP,KAAK,cAAc,MAAM,KAAK,MAAM;CACtC;CAEA,UAAU;EACR,KAAK,YAAY;CACnB;CAEA,YAAY;EACV,IAAI,KAAK,WAAW;GAClB,KAAK,SAAS,KAAK;GACnB,KAAK,YAAY;EACnB;CACF;AACF"}
@@ -1,4 +1,4 @@
1
- import { BigIntJSON } from "../../../../shared/src/bigint-json.js";
1
+ import { BigIntJSON, stringifyWithInfinity } from "../../../../shared/src/bigint-json.js";
2
2
  //#region ../zero-cache/src/services/change-streamer/change-log-codec.ts
3
3
  /**
4
4
  * Serializes a data-plane message and its stored change payload in one pass.
@@ -9,7 +9,7 @@ import { BigIntJSON } from "../../../../shared/src/bigint-json.js";
9
9
  * replication hot path.
10
10
  */
11
11
  function serializeChangeStreamDataWithChange(data) {
12
- const change = BigIntJSON.stringify(data[1]);
12
+ const change = stringifyWithInfinity(data[1]);
13
13
  const type = data[0];
14
14
  switch (type) {
15
15
  case "begin":
@@ -1 +1 @@
1
- {"version":3,"file":"change-log-codec.js","names":[],"sources":["../../../../../../zero-cache/src/services/change-streamer/change-log-codec.ts"],"sourcesContent":["import {BigIntJSON} from '../../../../shared/src/bigint-json.ts';\nimport type {ChangeStreamData} from '../change-source/protocol/current/downstream.ts';\nimport type {ChangeTag, WatermarkedChange} from './change-streamer.ts';\n\nexport type ChangeLogEntry = {\n watermark: string;\n tag: string;\n change: string;\n};\n\nexport type SerializedChangeStreamData = {\n /** The canonical downstream representation forwarded to subscribers. */\n readonly json: string;\n /** The already-serialized change tuple element stored in change logs. */\n readonly change: string;\n};\n\n/**\n * Serializes a data-plane message and its stored change payload in one pass.\n *\n * Change logs retain only the second tuple element for backwards\n * compatibility. Serializing that element first avoids stringifying the full\n * message and then copying the payload back out of the resulting string on the\n * replication hot path.\n */\nexport function serializeChangeStreamDataWithChange(\n data: ChangeStreamData,\n): SerializedChangeStreamData {\n const change = BigIntJSON.stringify(data[1]);\n const type = data[0];\n switch (type) {\n case 'begin':\n case 'commit':\n return {\n json: `[${JSON.stringify(type)},${change},${BigIntJSON.stringify(data[2])}]`,\n change,\n };\n case 'data':\n case 'rollback':\n return {json: `[${JSON.stringify(type)},${change}]`, change};\n }\n}\n\n/** Serializes a data-plane message to the canonical downstream JSON form. */\nexport function serializeChangeStreamData(data: ChangeStreamData): string {\n return serializeChangeStreamDataWithChange(data).json;\n}\n\n/**\n * Extracts the second tuple element for callers that only have the canonical\n * downstream JSON. The live write path uses\n * {@link serializeChangeStreamDataWithChange} and does not scan or copy the\n * completed message.\n */\nexport function extractChangeSubstring(\n streamMessageJSON: string,\n tag: ChangeTag | undefined,\n): string {\n switch (tag) {\n case 'begin':\n case 'commit':\n // e.g.\n // [\"begin\",<message-json>,{\"commitWatermark\":\"92fj2d0s\"}]\n // [\"commit\",<message-json>,{\"watermark\":\"92fj2d0s\"}]\n return streamMessageJSON.substring(\n streamMessageJSON.indexOf(',') + 1,\n streamMessageJSON.lastIndexOf(','),\n );\n default:\n // [\"data\",<message-json>]\n return streamMessageJSON.substring(\n streamMessageJSON.indexOf(',') + 1,\n streamMessageJSON.lastIndexOf(']'),\n );\n }\n}\n\n/** Reconstructs the canonical downstream JSON around a stored change. */\nexport function reconstructWatermarkedChange(\n watermark: string,\n entryTag: string,\n change: string,\n): WatermarkedChange {\n const tag = entryTag as ChangeTag;\n switch (tag) {\n case 'begin':\n return [\n watermark,\n tag,\n `[\"begin\",${change},{\"commitWatermark\":\"${watermark}\"}]`,\n ];\n case 'commit':\n return [\n watermark,\n tag,\n `[\"commit\",${change},{\"watermark\":\"${watermark}\"}]`,\n ];\n case 'rollback':\n return [watermark, tag, `[\"rollback\",${change}]`];\n default:\n return [watermark, tag, `[\"data\",${change}]`];\n }\n}\n"],"mappings":";;;;;;;;;;AAyBA,SAAgB,oCACd,MAC4B;CAC5B,MAAM,SAAS,WAAW,UAAU,KAAK,EAAE;CAC3C,MAAM,OAAO,KAAK;CAClB,QAAQ,MAAR;EACE,KAAK;EACL,KAAK,UACH,OAAO;GACL,MAAM,IAAI,KAAK,UAAU,IAAI,EAAE,GAAG,OAAO,GAAG,WAAW,UAAU,KAAK,EAAE,EAAE;GAC1E;EACF;EACF,KAAK;EACL,KAAK,YACH,OAAO;GAAC,MAAM,IAAI,KAAK,UAAU,IAAI,EAAE,GAAG,OAAO;GAAI;EAAM;CAC/D;AACF;;;;;;;AAaA,SAAgB,uBACd,mBACA,KACQ;CACR,QAAQ,KAAR;EACE,KAAK;EACL,KAAK,UAIH,OAAO,kBAAkB,UACvB,kBAAkB,QAAQ,GAAG,IAAI,GACjC,kBAAkB,YAAY,GAAG,CACnC;EACF,SAEE,OAAO,kBAAkB,UACvB,kBAAkB,QAAQ,GAAG,IAAI,GACjC,kBAAkB,YAAY,GAAG,CACnC;CACJ;AACF;;AAGA,SAAgB,6BACd,WACA,UACA,QACmB;CACnB,MAAM,MAAM;CACZ,QAAQ,KAAR;EACE,KAAK,SACH,OAAO;GACL;GACA;GACA,YAAY,OAAO,uBAAuB,UAAU;EACtD;EACF,KAAK,UACH,OAAO;GACL;GACA;GACA,aAAa,OAAO,iBAAiB,UAAU;EACjD;EACF,KAAK,YACH,OAAO;GAAC;GAAW;GAAK,eAAe,OAAO;EAAE;EAClD,SACE,OAAO;GAAC;GAAW;GAAK,WAAW,OAAO;EAAE;CAChD;AACF"}
1
+ {"version":3,"file":"change-log-codec.js","names":[],"sources":["../../../../../../zero-cache/src/services/change-streamer/change-log-codec.ts"],"sourcesContent":["import {\n BigIntJSON,\n stringifyWithInfinity,\n} from '../../../../shared/src/bigint-json.ts';\nimport type {ChangeStreamData} from '../change-source/protocol/current/downstream.ts';\nimport type {ChangeTag, WatermarkedChange} from './change-streamer.ts';\n\nexport type ChangeLogEntry = {\n watermark: string;\n tag: string;\n change: string;\n};\n\nexport type SerializedChangeStreamData = {\n /** The canonical downstream representation forwarded to subscribers. */\n readonly json: string;\n /** The already-serialized change tuple element stored in change logs. */\n readonly change: string;\n};\n\n/**\n * Serializes a data-plane message and its stored change payload in one pass.\n *\n * Change logs retain only the second tuple element for backwards\n * compatibility. Serializing that element first avoids stringifying the full\n * message and then copying the payload back out of the resulting string on the\n * replication hot path.\n */\nexport function serializeChangeStreamDataWithChange(\n data: ChangeStreamData,\n): SerializedChangeStreamData {\n // A row can hold an infinite number, e.g. from a float or timestamp column.\n const change = stringifyWithInfinity(data[1]);\n const type = data[0];\n switch (type) {\n case 'begin':\n case 'commit':\n return {\n json: `[${JSON.stringify(type)},${change},${BigIntJSON.stringify(data[2])}]`,\n change,\n };\n case 'data':\n case 'rollback':\n return {json: `[${JSON.stringify(type)},${change}]`, change};\n }\n}\n\n/** Serializes a data-plane message to the canonical downstream JSON form. */\nexport function serializeChangeStreamData(data: ChangeStreamData): string {\n return serializeChangeStreamDataWithChange(data).json;\n}\n\n/**\n * Extracts the second tuple element for callers that only have the canonical\n * downstream JSON. The live write path uses\n * {@link serializeChangeStreamDataWithChange} and does not scan or copy the\n * completed message.\n */\nexport function extractChangeSubstring(\n streamMessageJSON: string,\n tag: ChangeTag | undefined,\n): string {\n switch (tag) {\n case 'begin':\n case 'commit':\n // e.g.\n // [\"begin\",<message-json>,{\"commitWatermark\":\"92fj2d0s\"}]\n // [\"commit\",<message-json>,{\"watermark\":\"92fj2d0s\"}]\n return streamMessageJSON.substring(\n streamMessageJSON.indexOf(',') + 1,\n streamMessageJSON.lastIndexOf(','),\n );\n default:\n // [\"data\",<message-json>]\n return streamMessageJSON.substring(\n streamMessageJSON.indexOf(',') + 1,\n streamMessageJSON.lastIndexOf(']'),\n );\n }\n}\n\n/** Reconstructs the canonical downstream JSON around a stored change. */\nexport function reconstructWatermarkedChange(\n watermark: string,\n entryTag: string,\n change: string,\n): WatermarkedChange {\n const tag = entryTag as ChangeTag;\n switch (tag) {\n case 'begin':\n return [\n watermark,\n tag,\n `[\"begin\",${change},{\"commitWatermark\":\"${watermark}\"}]`,\n ];\n case 'commit':\n return [\n watermark,\n tag,\n `[\"commit\",${change},{\"watermark\":\"${watermark}\"}]`,\n ];\n case 'rollback':\n return [watermark, tag, `[\"rollback\",${change}]`];\n default:\n return [watermark, tag, `[\"data\",${change}]`];\n }\n}\n"],"mappings":";;;;;;;;;;AA4BA,SAAgB,oCACd,MAC4B;CAE5B,MAAM,SAAS,sBAAsB,KAAK,EAAE;CAC5C,MAAM,OAAO,KAAK;CAClB,QAAQ,MAAR;EACE,KAAK;EACL,KAAK,UACH,OAAO;GACL,MAAM,IAAI,KAAK,UAAU,IAAI,EAAE,GAAG,OAAO,GAAG,WAAW,UAAU,KAAK,EAAE,EAAE;GAC1E;EACF;EACF,KAAK;EACL,KAAK,YACH,OAAO;GAAC,MAAM,IAAI,KAAK,UAAU,IAAI,EAAE,GAAG,OAAO;GAAI;EAAM;CAC/D;AACF;;;;;;;AAaA,SAAgB,uBACd,mBACA,KACQ;CACR,QAAQ,KAAR;EACE,KAAK;EACL,KAAK,UAIH,OAAO,kBAAkB,UACvB,kBAAkB,QAAQ,GAAG,IAAI,GACjC,kBAAkB,YAAY,GAAG,CACnC;EACF,SAEE,OAAO,kBAAkB,UACvB,kBAAkB,QAAQ,GAAG,IAAI,GACjC,kBAAkB,YAAY,GAAG,CACnC;CACJ;AACF;;AAGA,SAAgB,6BACd,WACA,UACA,QACmB;CACnB,MAAM,MAAM;CACZ,QAAQ,KAAR;EACE,KAAK,SACH,OAAO;GACL;GACA;GACA,YAAY,OAAO,uBAAuB,UAAU;EACtD;EACF,KAAK,UACH,OAAO;GACL;GACA;GACA,aAAa,OAAO,iBAAiB,UAAU;EACjD;EACF,KAAK,YACH,OAAO;GAAC;GAAW;GAAK,eAAe,OAAO;EAAE;EAClD,SACE,OAAO;GAAC;GAAW;GAAK,WAAW,OAAO;EAAE;CAChD;AACF"}