@rocicorp/zero 1.12.0 → 1.13.0-canary.0

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 (153) 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/zero/package.js +1 -1
  13. package/out/zero/package.js.map +1 -1
  14. package/out/zero-cache/src/auth/write-authorizer.js +4 -3
  15. package/out/zero-cache/src/auth/write-authorizer.js.map +1 -1
  16. package/out/zero-cache/src/config/normalize.d.ts.map +1 -1
  17. package/out/zero-cache/src/config/normalize.js +3 -23
  18. package/out/zero-cache/src/config/normalize.js.map +1 -1
  19. package/out/zero-cache/src/config/zero-config.d.ts +1 -27
  20. package/out/zero-cache/src/config/zero-config.d.ts.map +1 -1
  21. package/out/zero-cache/src/config/zero-config.js +19 -47
  22. package/out/zero-cache/src/config/zero-config.js.map +1 -1
  23. package/out/zero-cache/src/custom/fetch.js +17 -2
  24. package/out/zero-cache/src/custom/fetch.js.map +1 -1
  25. package/out/zero-cache/src/db/create.js +45 -1
  26. package/out/zero-cache/src/db/create.js.map +1 -1
  27. package/out/zero-cache/src/db/lite-tables.d.ts.map +1 -1
  28. package/out/zero-cache/src/db/lite-tables.js +4 -3
  29. package/out/zero-cache/src/db/lite-tables.js.map +1 -1
  30. package/out/zero-cache/src/db/pg-copy-binary.js +61 -25
  31. package/out/zero-cache/src/db/pg-copy-binary.js.map +1 -1
  32. package/out/zero-cache/src/db/pg-to-lite.d.ts +17 -0
  33. package/out/zero-cache/src/db/pg-to-lite.d.ts.map +1 -1
  34. package/out/zero-cache/src/db/pg-to-lite.js +84 -1
  35. package/out/zero-cache/src/db/pg-to-lite.js.map +1 -1
  36. package/out/zero-cache/src/server/change-streamer.js +21 -30
  37. package/out/zero-cache/src/server/change-streamer.js.map +1 -1
  38. package/out/zero-cache/src/server/main.js +0 -1
  39. package/out/zero-cache/src/server/main.js.map +1 -1
  40. package/out/zero-cache/src/server/replicator.js +1 -1
  41. package/out/zero-cache/src/server/replicator.js.map +1 -1
  42. package/out/zero-cache/src/services/change-source/pg/backfill-stream.js +6 -5
  43. package/out/zero-cache/src/services/change-source/pg/backfill-stream.js.map +1 -1
  44. package/out/zero-cache/src/services/change-source/pg/change-source.js +49 -11
  45. package/out/zero-cache/src/services/change-source/pg/change-source.js.map +1 -1
  46. package/out/zero-cache/src/services/change-source/pg/initial-sync.js +64 -21
  47. package/out/zero-cache/src/services/change-source/pg/initial-sync.js.map +1 -1
  48. package/out/zero-cache/src/services/change-source/pg/replication-slots.js +11 -6
  49. package/out/zero-cache/src/services/change-source/pg/replication-slots.js.map +1 -1
  50. package/out/zero-cache/src/services/change-source/pg/schema/ddl.d.ts +13 -1
  51. package/out/zero-cache/src/services/change-source/pg/schema/ddl.d.ts.map +1 -1
  52. package/out/zero-cache/src/services/change-source/pg/schema/ddl.js +16 -3
  53. package/out/zero-cache/src/services/change-source/pg/schema/ddl.js.map +1 -1
  54. package/out/zero-cache/src/services/change-source/pg/schema/init.js +59 -3
  55. package/out/zero-cache/src/services/change-source/pg/schema/init.js.map +1 -1
  56. package/out/zero-cache/src/services/change-source/pg/schema/published.d.ts +1 -0
  57. package/out/zero-cache/src/services/change-source/pg/schema/published.d.ts.map +1 -1
  58. package/out/zero-cache/src/services/change-source/pg/schema/published.js +56 -12
  59. package/out/zero-cache/src/services/change-source/pg/schema/published.js.map +1 -1
  60. package/out/zero-cache/src/services/change-source/pg/schema/shard.d.ts +1 -0
  61. package/out/zero-cache/src/services/change-source/pg/schema/shard.d.ts.map +1 -1
  62. package/out/zero-cache/src/services/change-source/pg/schema/shard.js +35 -12
  63. package/out/zero-cache/src/services/change-source/pg/schema/shard.js.map +1 -1
  64. package/out/zero-cache/src/services/change-source/pg/schema/validation.d.ts +6 -1
  65. package/out/zero-cache/src/services/change-source/pg/schema/validation.d.ts.map +1 -1
  66. package/out/zero-cache/src/services/change-source/pg/schema/validation.js +25 -1
  67. package/out/zero-cache/src/services/change-source/pg/schema/validation.js.map +1 -1
  68. package/out/zero-cache/src/services/change-source/protocol/backfill-progress.js +6 -5
  69. package/out/zero-cache/src/services/change-source/protocol/backfill-progress.js.map +1 -1
  70. package/out/zero-cache/src/services/change-streamer/backfill-state.js +7 -6
  71. package/out/zero-cache/src/services/change-streamer/backfill-state.js.map +1 -1
  72. package/out/zero-cache/src/services/change-streamer/change-log-codec.js +2 -2
  73. package/out/zero-cache/src/services/change-streamer/change-log-codec.js.map +1 -1
  74. package/out/zero-cache/src/services/change-streamer/change-log-initializer.js +16 -199
  75. package/out/zero-cache/src/services/change-streamer/change-log-initializer.js.map +1 -1
  76. package/out/zero-cache/src/services/change-streamer/change-streamer-service.js +76 -127
  77. package/out/zero-cache/src/services/change-streamer/change-streamer-service.js.map +1 -1
  78. package/out/zero-cache/src/services/change-streamer/snapshot-reservations.js +1 -1
  79. package/out/zero-cache/src/services/change-streamer/snapshot-reservations.js.map +1 -1
  80. package/out/zero-cache/src/services/change-streamer/sqlite-change-log-catchup.js.map +1 -1
  81. package/out/zero-cache/src/services/change-streamer/sqlite-change-log-purge-scheduler.js +1 -1
  82. package/out/zero-cache/src/services/change-streamer/sqlite-change-log-read-router.js +15 -49
  83. package/out/zero-cache/src/services/change-streamer/sqlite-change-log-read-router.js.map +1 -1
  84. package/out/zero-cache/src/services/change-streamer/sqlite-change-log-reader.js +8 -2
  85. package/out/zero-cache/src/services/change-streamer/sqlite-change-log-reader.js.map +1 -1
  86. package/out/zero-cache/src/services/change-streamer/sqlite-change-log-writer.js +20 -36
  87. package/out/zero-cache/src/services/change-streamer/sqlite-change-log-writer.js.map +1 -1
  88. package/out/zero-cache/src/services/change-streamer/storer.js +32 -20
  89. package/out/zero-cache/src/services/change-streamer/storer.js.map +1 -1
  90. package/out/zero-cache/src/services/mutagen/mutagen.js +4 -2
  91. package/out/zero-cache/src/services/mutagen/mutagen.js.map +1 -1
  92. package/out/zero-cache/src/services/replicator/change-log-cookies.d.ts +0 -16
  93. package/out/zero-cache/src/services/replicator/change-log-cookies.d.ts.map +1 -1
  94. package/out/zero-cache/src/services/replicator/change-log-cookies.js +3 -95
  95. package/out/zero-cache/src/services/replicator/change-log-cookies.js.map +1 -1
  96. package/out/zero-cache/src/services/replicator/change-log-db.js +2 -2
  97. package/out/zero-cache/src/services/replicator/change-log-db.js.map +1 -1
  98. package/out/zero-cache/src/services/replicator/change-log-stream-writer.js +1 -30
  99. package/out/zero-cache/src/services/replicator/change-log-stream-writer.js.map +1 -1
  100. package/out/zero-cache/src/services/replicator/change-processor.js +82 -9
  101. package/out/zero-cache/src/services/replicator/change-processor.js.map +1 -1
  102. package/out/zero-cache/src/services/replicator/incremental-sync.js +7 -1
  103. package/out/zero-cache/src/services/replicator/incremental-sync.js.map +1 -1
  104. package/out/zero-cache/src/services/replicator/reporter/report-schema.d.ts +1 -0
  105. package/out/zero-cache/src/services/replicator/reporter/report-schema.d.ts.map +1 -1
  106. package/out/zero-cache/src/services/replicator/reporter/report-schema.js +4 -1
  107. package/out/zero-cache/src/services/replicator/reporter/report-schema.js.map +1 -1
  108. package/out/zero-cache/src/services/replicator/schema/change-log.d.ts.map +1 -1
  109. package/out/zero-cache/src/services/replicator/schema/change-log.js +2 -1
  110. package/out/zero-cache/src/services/replicator/schema/change-log.js.map +1 -1
  111. package/out/zero-cache/src/services/replicator/sqlite-change-log-observability.js +6 -102
  112. package/out/zero-cache/src/services/replicator/sqlite-change-log-observability.js.map +1 -1
  113. package/out/zero-cache/src/services/statz.d.ts.map +1 -1
  114. package/out/zero-cache/src/services/statz.js +1 -1
  115. package/out/zero-cache/src/services/statz.js.map +1 -1
  116. package/out/zero-cache/src/services/view-syncer/schema/init.js +3 -0
  117. package/out/zero-cache/src/services/view-syncer/schema/init.js.map +1 -1
  118. package/out/zero-cache/src/services/view-syncer/snapshot-row-cache.js +47 -3
  119. package/out/zero-cache/src/services/view-syncer/snapshot-row-cache.js.map +1 -1
  120. package/out/zero-cache/src/services/view-syncer/view-syncer.js +51 -6
  121. package/out/zero-cache/src/services/view-syncer/view-syncer.js.map +1 -1
  122. package/out/zero-cache/src/types/lite.d.ts +7 -0
  123. package/out/zero-cache/src/types/lite.d.ts.map +1 -1
  124. package/out/zero-cache/src/types/lite.js +12 -2
  125. package/out/zero-cache/src/types/lite.js.map +1 -1
  126. package/out/zero-cache/src/types/pg-types.d.ts +2 -1
  127. package/out/zero-cache/src/types/pg-types.d.ts.map +1 -1
  128. package/out/zero-cache/src/types/pg-types.js +2 -1
  129. package/out/zero-cache/src/types/pg-types.js.map +1 -1
  130. package/out/zero-cache/src/types/pg.d.ts +20 -0
  131. package/out/zero-cache/src/types/pg.d.ts.map +1 -1
  132. package/out/zero-cache/src/types/pg.js +64 -27
  133. package/out/zero-cache/src/types/pg.js.map +1 -1
  134. package/out/zero-cache/src/types/streams.d.ts +2 -0
  135. package/out/zero-cache/src/types/streams.d.ts.map +1 -1
  136. package/out/zero-cache/src/types/streams.js +2 -1
  137. package/out/zero-cache/src/types/streams.js.map +1 -1
  138. package/out/zero-cache/src/workers/replicator.js +7 -6
  139. package/out/zero-cache/src/workers/replicator.js.map +1 -1
  140. package/out/zero-cache/src/workers/syncer.js +18 -1
  141. package/out/zero-cache/src/workers/syncer.js.map +1 -1
  142. package/out/zero-client/src/client/version.js +1 -1
  143. package/out/zqlite/src/db.js +4 -1
  144. package/out/zqlite/src/db.js.map +1 -1
  145. package/package.json +1 -1
  146. package/out/zero-cache/src/services/change-streamer/change-log-compare-digest.js +0 -67
  147. package/out/zero-cache/src/services/change-streamer/change-log-compare-digest.js.map +0 -1
  148. package/out/zero-cache/src/services/change-streamer/change-log-transaction-hash.js +0 -39
  149. package/out/zero-cache/src/services/change-streamer/change-log-transaction-hash.js.map +0 -1
  150. package/out/zero-cache/src/services/change-streamer/shard-sampling.js +0 -19
  151. package/out/zero-cache/src/services/change-streamer/shard-sampling.js.map +0 -1
  152. package/out/zero-cache/src/services/change-streamer/sqlite-change-log-comparator.js +0 -417
  153. package/out/zero-cache/src/services/change-streamer/sqlite-change-log-comparator.js.map +0 -1
@@ -1 +1 @@
1
- {"version":3,"file":"change-log.js","names":["parse","v","v.literalUnion","v.parse"],"sources":["../../../../../../../zero-cache/src/services/replicator/schema/change-log.ts"],"sourcesContent":["import {assert} from '../../../../../shared/src/asserts.ts';\nimport {\n parse,\n stringify,\n type JSONValue,\n} from '../../../../../shared/src/bigint-json.ts';\nimport * as v from '../../../../../shared/src/valita.ts';\nimport type {Database, Statement} from '../../../../../zqlite/src/db.ts';\nimport type {LexiVersion} from '../../../types/lexi-version.ts';\nimport type {LiteRowKey} from '../../../types/lite.ts';\nimport {normalizedKeyOrder} from '../../../types/row-key.ts';\n\n/**\n * The Change Log tracks the last operation (set or delete) for each row in the\n * data base, ordered by state version; in other words, a cross-table\n * index of row changes ordered by version. This facilitates a minimal \"diff\"\n * of row changes needed to advance a pipeline from one state version to another.\n *\n * The Change Log stores identifiers only, i.e. it does not store contents.\n * A database snapshot at the previous version can be used to query a row's\n * old contents, if any, and the current snapshot can be used to query a row's\n * new contents. (In the common case, the new contents will have just been applied\n * and thus has a high likelihood of being in the SQLite cache.)\n *\n * There are two table-wide operations:\n * - `t` corresponds to the postgres `TRUNCATE` operation\n * - `r` represents any schema (i.e. column) change\n *\n * For both operations, the corresponding row changes are not explicitly included\n * in the change log. The consumer has the option of simulating them be reading\n * from pre- and post- snapshots, or resetting their state entirely with the current\n * snapshot.\n *\n * To achieve the desired ordering semantics when processing tables that have been\n * truncated, reset, and modified, the \"rowKey\" is set to `null` for resets and\n * the empty string `\"\"` for truncates. This means that resets will be encountered\n * before truncates, which will be processed before any subsequent row changes.\n *\n * This ordering is chosen because resets are currently the more \"destructive\" op\n * and result in aborting the processing (and starting from scratch); doing this\n * earlier reduces wasted work.\n */\n\nexport const SET_OP = 's';\nexport const DEL_OP = 'd';\nexport const TRUNCATE_OP = 't';\nexport const RESET_OP = 'r';\n\n// Exported for testing (and migrations)\nexport const CREATE_CHANGELOG_SCHEMA =\n // stateVersion : a.k.a. row version\n // pos : order in which to process the change (within the version)\n // table : The table associated with the change\n // rowKey : JSON row key for a row change. For table-wide changes RESET\n // and TRUNCATE, there is no associated row; instead, `pos` is\n // set to -1 and the rowKey is set to the stateVersion,\n // guaranteeing when attempting to process the transaction,\n // the pipeline is reset (and the change log traversal\n // aborted).\n // op : 's' for set (insert/update)\n // : 'd' for delete\n // : 'r' for table reset (schema change)\n // : 't' for table truncation (which also resets the pipeline)\n // backfillingColumnVersions\n // : A JSON mapping from column name to stateVersion tracked\n // for replicated writes of columns that are being backfilled.\n // This is used to prevent backfill data, which is at a\n // fixed snapshot/version outside of the replication stream,\n // from overwriting newer column values.\n //\n // Naming note: To maintain compatibility between a new replication-manager\n // and old view-syncers, the previous _zero.changeLog table is preserved\n // and its replacement given a new name \"changeLog2\".\n `\n CREATE TABLE \"_zero.changeLog2\" (\n \"stateVersion\" TEXT NOT NULL,\n \"pos\" INT NOT NULL,\n \"table\" TEXT NOT NULL,\n \"rowKey\" TEXT NOT NULL,\n \"op\" TEXT NOT NULL,\n \"backfillingColumnVersions\" TEXT DEFAULT '{}',\n PRIMARY KEY(\"stateVersion\", \"pos\"),\n UNIQUE(\"table\", \"rowKey\")\n );\n `;\n\n/**\n * Contains the changeLog fields relevant for computing the diff between\n * two snapshots of a replica. The `pos` and `backfillingColumnVersions`\n * fields are excluded, though the query should be ordered by\n * `<stateVersion, pos>`.\n */\nexport type ChangeLogEntry =\n | {\n readonly stateVersion: string;\n readonly table: string;\n readonly rowKey: Readonly<Record<string, JSONValue>>;\n readonly op: typeof SET_OP | typeof DEL_OP;\n }\n | {\n readonly stateVersion: string;\n readonly table: string;\n // Table-wide ops have no row.\n readonly rowKey: null;\n readonly op: typeof TRUNCATE_OP | typeof RESET_OP;\n };\n\n/**\n * The {@link ChangeLogEntry} for the columns of a change log row. This does\n * not validate what zero-cache itself wrote: the columns are\n * `TEXT NOT NULL`, and `rowKey` is the JSON of an object (see\n * {@link ChangeLog}).\n */\nexport function parseChangeLogEntry(\n stateVersion: string,\n table: string,\n rowKey: string,\n op: string,\n): ChangeLogEntry {\n switch (op) {\n case SET_OP:\n case DEL_OP:\n return {stateVersion, table, rowKey: parseRowKey(rowKey), op};\n case TRUNCATE_OP:\n case RESET_OP:\n return {stateVersion, table, rowKey: null, op};\n default:\n throw new Error(`Invalid change log op \"${op}\" for table \"${table}\"`);\n }\n}\n\nfunction parseRowKey(rowKey: string): Readonly<Record<string, JSONValue>> {\n const key = parse(rowKey);\n assert(\n typeof key === 'object' && key !== null && !Array.isArray(key),\n () => `Invalid change log rowKey ${rowKey}`,\n );\n return key as Readonly<Record<string, JSONValue>>;\n}\n\nconst rawChangeLogEntrySchema = v.object({\n stateVersion: v.string(),\n table: v.string(),\n rowKey: v.string(),\n op: v.literalUnion(SET_OP, DEL_OP, TRUNCATE_OP, RESET_OP),\n backfillingColumnVersions: v\n .string()\n .map(val => v.record(v.string()).parse(JSON.parse(val))),\n});\n\nexport class ChangeLog {\n readonly #logRowOpStmt: Statement;\n readonly #logRowOpWithBackfillStmt: Statement;\n readonly #logTableWideOpStmt;\n readonly #getRowOpStmt: Statement;\n\n constructor(db: Database) {\n this.#logRowOpStmt = db.prepare(/*sql*/ `\n INSERT OR REPLACE INTO \"_zero.changeLog2\" \n (stateVersion, pos, \"table\", rowKey, op)\n VALUES (@version, @pos, @table, JSON(@rowKey), @op)\n `);\n\n this.#logRowOpWithBackfillStmt = db.prepare(/*sql*/ `\n INSERT INTO \"_zero.changeLog2\" \n (stateVersion, pos, \"table\", rowKey, op, backfillingColumnVersions)\n VALUES (@version, @pos, @table, JSON(@rowKey), @op, \n JSON(@backfillingColumnVersions))\n ON CONFLICT (\"table\", rowKey) DO UPDATE \n SET stateVersion = excluded.stateVersion,\n pos = excluded.pos,\n op = excluded.op,\n backfillingColumnVersions = json_patch(\n backfillingColumnVersions, excluded.backfillingColumnVersions)\n `);\n\n // Because table-wide ops result in aborting an incremental update\n // and rehydrating all queries at \"head\", they are assigned pos = -1\n // as an optimization to abort as early as possible to skip unnecessary\n // updates.\n //\n // However, changeLog entries that are destined to be \"skipped\" are\n // nonetheless kept for the purpose of tracking backfillingColumnVersions.\n this.#logTableWideOpStmt = db.prepare(/*sql*/ `\n INSERT OR REPLACE INTO \"_zero.changeLog2\" \n (stateVersion, pos, \"table\", rowKey, op) \n VALUES (@version, -1, @table, @version, @op)\n `);\n\n // oxlint-disable-next-line zero/no-select-star -- Local SQLite replica query; not run through pg prepared statements.\n this.#getRowOpStmt = db.prepare(/*sql*/ `\n SELECT * FROM \"_zero.changeLog2\" WHERE \"table\" = ? AND \"rowKey\" = JSON(?)\n `);\n }\n\n /**\n *\n * @param backfilled The backfilling columns for which values were set. Note\n * that an empty list and the `undefined` value mean different things;\n * * An empty list indicates that a backfill is in progress but no\n * backfilling values were set. In this case, existing\n * backfillingColumnVersions are preserved.\n * * `undefined` indicates that there are no columns being backfilled.\n * In this case, any vestigial `backfillingColumnVersions` value\n * is cleared.\n */\n logSetOp(\n version: LexiVersion,\n pos: number,\n table: string,\n row: LiteRowKey,\n backfilled: string[] | undefined,\n ): string {\n return this.#logRowOp(version, pos, table, row, SET_OP, backfilled);\n }\n\n logDeleteOp(\n version: LexiVersion,\n pos: number,\n table: string,\n row: LiteRowKey,\n ): string {\n // Note: For delete ops, it is always safe to clear the\n // backfillingColumnVersions because the backfill algorithm\n // understands that deletes apply to the whole row.\n return this.#logRowOp(version, pos, table, row, DEL_OP, undefined);\n }\n\n getLatestRowOp(table: string, row: LiteRowKey) {\n const rowKey = stringify(normalizedKeyOrder(row));\n const result = this.#getRowOpStmt.get(table, rowKey);\n return result === undefined\n ? undefined\n : v.parse(result, rawChangeLogEntrySchema, 'passthrough');\n }\n\n #logRowOp(\n version: LexiVersion,\n pos: number,\n table: string,\n row: LiteRowKey,\n op: string,\n backfilled: string[] | undefined,\n ): string {\n const rowKey = stringify(normalizedKeyOrder(row));\n if (backfilled === undefined) {\n this.#logRowOpStmt.run({version, pos, table, rowKey, op});\n } else {\n const versions: Record<string, string> = {};\n for (const col of backfilled) {\n versions[col] = version;\n }\n this.#logRowOpWithBackfillStmt.run({\n version,\n pos,\n table,\n rowKey,\n op,\n backfillingColumnVersions: JSON.stringify(versions),\n });\n }\n return rowKey;\n }\n\n logTruncateOp(version: LexiVersion, table: string) {\n this.#logTableWideOpStmt.run({version, table, op: TRUNCATE_OP});\n }\n\n logResetOp(version: LexiVersion, table: string) {\n this.#logTableWideOpStmt.run({version, table, op: RESET_OP});\n }\n}\n"],"mappings":";;;;AAiDA,IAAa,0BAwBX;;;;;;;;;;;;;;;;;;AAwCF,SAAgB,oBACd,cACA,OACA,QACA,IACgB;CAChB,QAAQ,IAAR;EACE,KAAA;EACA,KAAA,KACE,OAAO;GAAC;GAAc;GAAO,QAAQ,YAAY,MAAM;GAAG;EAAE;EAC9D,KAAA;EACA,KAAA,KACE,OAAO;GAAC;GAAc;GAAO,QAAQ;GAAM;EAAE;EAC/C,SACE,MAAM,IAAI,MAAM,0BAA0B,GAAG,eAAe,MAAM,EAAE;CACxE;AACF;AAEA,SAAS,YAAY,QAAqD;CACxE,MAAM,MAAMA,QAAM,MAAM;CACxB,OACE,OAAO,QAAQ,YAAY,QAAQ,QAAQ,CAAC,MAAM,QAAQ,GAAG,SACvD,6BAA6B,QACrC;CACA,OAAO;AACT;AAEA,IAAM,0BAA0BC,eAAE,OAAO;CACvC,cAAcA,eAAE,OAAO;CACvB,OAAOA,eAAE,OAAO;CAChB,QAAQA,eAAE,OAAO;CACjB,IAAIC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Ae;EACjD,KAAK,oBAAoB,IAAI;GAAC;GAAS;GAAO,IAAA;EAAe,CAAC;CAChE;CAEA,WAAW,SAAsB,OAAe;EAC9C,KAAK,oBAAoB,IAAI;GAAC;GAAS;GAAO,IAAA;EAAY,CAAC;CAC7D;AACF"}
1
+ {"version":3,"file":"change-log.js","names":["parse","v","v.literalUnion","v.parse"],"sources":["../../../../../../../zero-cache/src/services/replicator/schema/change-log.ts"],"sourcesContent":["import {assert} from '../../../../../shared/src/asserts.ts';\nimport {\n parse,\n stringify,\n type JSONValue,\n} from '../../../../../shared/src/bigint-json.ts';\nimport {assignProperty} from '../../../../../shared/src/objects.ts';\nimport * as v from '../../../../../shared/src/valita.ts';\nimport type {Database, Statement} from '../../../../../zqlite/src/db.ts';\nimport type {LexiVersion} from '../../../types/lexi-version.ts';\nimport type {LiteRowKey} from '../../../types/lite.ts';\nimport {normalizedKeyOrder} from '../../../types/row-key.ts';\n\n/**\n * The Change Log tracks the last operation (set or delete) for each row in the\n * data base, ordered by state version; in other words, a cross-table\n * index of row changes ordered by version. This facilitates a minimal \"diff\"\n * of row changes needed to advance a pipeline from one state version to another.\n *\n * The Change Log stores identifiers only, i.e. it does not store contents.\n * A database snapshot at the previous version can be used to query a row's\n * old contents, if any, and the current snapshot can be used to query a row's\n * new contents. (In the common case, the new contents will have just been applied\n * and thus has a high likelihood of being in the SQLite cache.)\n *\n * There are two table-wide operations:\n * - `t` corresponds to the postgres `TRUNCATE` operation\n * - `r` represents any schema (i.e. column) change\n *\n * For both operations, the corresponding row changes are not explicitly included\n * in the change log. The consumer has the option of simulating them be reading\n * from pre- and post- snapshots, or resetting their state entirely with the current\n * snapshot.\n *\n * To achieve the desired ordering semantics when processing tables that have been\n * truncated, reset, and modified, the \"rowKey\" is set to `null` for resets and\n * the empty string `\"\"` for truncates. This means that resets will be encountered\n * before truncates, which will be processed before any subsequent row changes.\n *\n * This ordering is chosen because resets are currently the more \"destructive\" op\n * and result in aborting the processing (and starting from scratch); doing this\n * earlier reduces wasted work.\n */\n\nexport const SET_OP = 's';\nexport const DEL_OP = 'd';\nexport const TRUNCATE_OP = 't';\nexport const RESET_OP = 'r';\n\n// Exported for testing (and migrations)\nexport const CREATE_CHANGELOG_SCHEMA =\n // stateVersion : a.k.a. row version\n // pos : order in which to process the change (within the version)\n // table : The table associated with the change\n // rowKey : JSON row key for a row change. For table-wide changes RESET\n // and TRUNCATE, there is no associated row; instead, `pos` is\n // set to -1 and the rowKey is set to the stateVersion,\n // guaranteeing when attempting to process the transaction,\n // the pipeline is reset (and the change log traversal\n // aborted).\n // op : 's' for set (insert/update)\n // : 'd' for delete\n // : 'r' for table reset (schema change)\n // : 't' for table truncation (which also resets the pipeline)\n // backfillingColumnVersions\n // : A JSON mapping from column name to stateVersion tracked\n // for replicated writes of columns that are being backfilled.\n // This is used to prevent backfill data, which is at a\n // fixed snapshot/version outside of the replication stream,\n // from overwriting newer column values.\n //\n // Naming note: To maintain compatibility between a new replication-manager\n // and old view-syncers, the previous _zero.changeLog table is preserved\n // and its replacement given a new name \"changeLog2\".\n `\n CREATE TABLE \"_zero.changeLog2\" (\n \"stateVersion\" TEXT NOT NULL,\n \"pos\" INT NOT NULL,\n \"table\" TEXT NOT NULL,\n \"rowKey\" TEXT NOT NULL,\n \"op\" TEXT NOT NULL,\n \"backfillingColumnVersions\" TEXT DEFAULT '{}',\n PRIMARY KEY(\"stateVersion\", \"pos\"),\n UNIQUE(\"table\", \"rowKey\")\n );\n `;\n\n/**\n * Contains the changeLog fields relevant for computing the diff between\n * two snapshots of a replica. The `pos` and `backfillingColumnVersions`\n * fields are excluded, though the query should be ordered by\n * `<stateVersion, pos>`.\n */\nexport type ChangeLogEntry =\n | {\n readonly stateVersion: string;\n readonly table: string;\n readonly rowKey: Readonly<Record<string, JSONValue>>;\n readonly op: typeof SET_OP | typeof DEL_OP;\n }\n | {\n readonly stateVersion: string;\n readonly table: string;\n // Table-wide ops have no row.\n readonly rowKey: null;\n readonly op: typeof TRUNCATE_OP | typeof RESET_OP;\n };\n\n/**\n * The {@link ChangeLogEntry} for the columns of a change log row. This does\n * not validate what zero-cache itself wrote: the columns are\n * `TEXT NOT NULL`, and `rowKey` is the JSON of an object (see\n * {@link ChangeLog}).\n */\nexport function parseChangeLogEntry(\n stateVersion: string,\n table: string,\n rowKey: string,\n op: string,\n): ChangeLogEntry {\n switch (op) {\n case SET_OP:\n case DEL_OP:\n return {stateVersion, table, rowKey: parseRowKey(rowKey), op};\n case TRUNCATE_OP:\n case RESET_OP:\n return {stateVersion, table, rowKey: null, op};\n default:\n throw new Error(`Invalid change log op \"${op}\" for table \"${table}\"`);\n }\n}\n\nfunction parseRowKey(rowKey: string): Readonly<Record<string, JSONValue>> {\n const key = parse(rowKey);\n assert(\n typeof key === 'object' && key !== null && !Array.isArray(key),\n () => `Invalid change log rowKey ${rowKey}`,\n );\n return key as Readonly<Record<string, JSONValue>>;\n}\n\nconst rawChangeLogEntrySchema = v.object({\n stateVersion: v.string(),\n table: v.string(),\n rowKey: v.string(),\n op: v.literalUnion(SET_OP, DEL_OP, TRUNCATE_OP, RESET_OP),\n backfillingColumnVersions: v\n .string()\n .map(val => v.record(v.string()).parse(JSON.parse(val))),\n});\n\nexport class ChangeLog {\n readonly #logRowOpStmt: Statement;\n readonly #logRowOpWithBackfillStmt: Statement;\n readonly #logTableWideOpStmt;\n readonly #getRowOpStmt: Statement;\n\n constructor(db: Database) {\n this.#logRowOpStmt = db.prepare(/*sql*/ `\n INSERT OR REPLACE INTO \"_zero.changeLog2\" \n (stateVersion, pos, \"table\", rowKey, op)\n VALUES (@version, @pos, @table, JSON(@rowKey), @op)\n `);\n\n this.#logRowOpWithBackfillStmt = db.prepare(/*sql*/ `\n INSERT INTO \"_zero.changeLog2\" \n (stateVersion, pos, \"table\", rowKey, op, backfillingColumnVersions)\n VALUES (@version, @pos, @table, JSON(@rowKey), @op, \n JSON(@backfillingColumnVersions))\n ON CONFLICT (\"table\", rowKey) DO UPDATE \n SET stateVersion = excluded.stateVersion,\n pos = excluded.pos,\n op = excluded.op,\n backfillingColumnVersions = json_patch(\n backfillingColumnVersions, excluded.backfillingColumnVersions)\n `);\n\n // Because table-wide ops result in aborting an incremental update\n // and rehydrating all queries at \"head\", they are assigned pos = -1\n // as an optimization to abort as early as possible to skip unnecessary\n // updates.\n //\n // However, changeLog entries that are destined to be \"skipped\" are\n // nonetheless kept for the purpose of tracking backfillingColumnVersions.\n this.#logTableWideOpStmt = db.prepare(/*sql*/ `\n INSERT OR REPLACE INTO \"_zero.changeLog2\" \n (stateVersion, pos, \"table\", rowKey, op) \n VALUES (@version, -1, @table, @version, @op)\n `);\n\n // oxlint-disable-next-line zero/no-select-star -- Local SQLite replica query; not run through pg prepared statements.\n this.#getRowOpStmt = db.prepare(/*sql*/ `\n SELECT * FROM \"_zero.changeLog2\" WHERE \"table\" = ? AND \"rowKey\" = JSON(?)\n `);\n }\n\n /**\n *\n * @param backfilled The backfilling columns for which values were set. Note\n * that an empty list and the `undefined` value mean different things;\n * * An empty list indicates that a backfill is in progress but no\n * backfilling values were set. In this case, existing\n * backfillingColumnVersions are preserved.\n * * `undefined` indicates that there are no columns being backfilled.\n * In this case, any vestigial `backfillingColumnVersions` value\n * is cleared.\n */\n logSetOp(\n version: LexiVersion,\n pos: number,\n table: string,\n row: LiteRowKey,\n backfilled: string[] | undefined,\n ): string {\n return this.#logRowOp(version, pos, table, row, SET_OP, backfilled);\n }\n\n logDeleteOp(\n version: LexiVersion,\n pos: number,\n table: string,\n row: LiteRowKey,\n ): string {\n // Note: For delete ops, it is always safe to clear the\n // backfillingColumnVersions because the backfill algorithm\n // understands that deletes apply to the whole row.\n return this.#logRowOp(version, pos, table, row, DEL_OP, undefined);\n }\n\n getLatestRowOp(table: string, row: LiteRowKey) {\n const rowKey = stringify(normalizedKeyOrder(row));\n const result = this.#getRowOpStmt.get(table, rowKey);\n return result === undefined\n ? undefined\n : v.parse(result, rawChangeLogEntrySchema, 'passthrough');\n }\n\n #logRowOp(\n version: LexiVersion,\n pos: number,\n table: string,\n row: LiteRowKey,\n op: string,\n backfilled: string[] | undefined,\n ): string {\n const rowKey = stringify(normalizedKeyOrder(row));\n if (backfilled === undefined) {\n this.#logRowOpStmt.run({version, pos, table, rowKey, op});\n } else {\n const versions: Record<string, string> = {};\n for (const col of backfilled) {\n assignProperty(versions, col, version);\n }\n this.#logRowOpWithBackfillStmt.run({\n version,\n pos,\n table,\n rowKey,\n op,\n backfillingColumnVersions: JSON.stringify(versions),\n });\n }\n return rowKey;\n }\n\n logTruncateOp(version: LexiVersion, table: string) {\n this.#logTableWideOpStmt.run({version, table, op: TRUNCATE_OP});\n }\n\n logResetOp(version: LexiVersion, table: string) {\n this.#logTableWideOpStmt.run({version, table, op: RESET_OP});\n }\n}\n"],"mappings":";;;;;AAkDA,IAAa,0BAwBX;;;;;;;;;;;;;;;;;;AAwCF,SAAgB,oBACd,cACA,OACA,QACA,IACgB;CAChB,QAAQ,IAAR;EACE,KAAA;EACA,KAAA,KACE,OAAO;GAAC;GAAc;GAAO,QAAQ,YAAY,MAAM;GAAG;EAAE;EAC9D,KAAA;EACA,KAAA,KACE,OAAO;GAAC;GAAc;GAAO,QAAQ;GAAM;EAAE;EAC/C,SACE,MAAM,IAAI,MAAM,0BAA0B,GAAG,eAAe,MAAM,EAAE;CACxE;AACF;AAEA,SAAS,YAAY,QAAqD;CACxE,MAAM,MAAMA,QAAM,MAAM;CACxB,OACE,OAAO,QAAQ,YAAY,QAAQ,QAAQ,CAAC,MAAM,QAAQ,GAAG,SACvD,6BAA6B,QACrC;CACA,OAAO;AACT;AAEA,IAAM,0BAA0BC,eAAE,OAAO;CACvC,cAAcA,eAAE,OAAO;CACvB,OAAOA,eAAE,OAAO;CAChB,QAAQA,eAAE,OAAO;CACjB,IAAIC,aAAAA,KAAAA,KAAAA,KAAAA,GAAoD;CACxD,2BAA2BD,eACxB,OAAO,CAAC,CACR,KAAI,QAAOA,eAAE,OAAOA,eAAE,OAAO,CAAC,CAAC,CAA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B,IAAI;GAAC;GAAS;GAAO,IAAA;EAAY,CAAC;CAC7D;AACF"}
@@ -3,8 +3,6 @@ import { getOrCreateCounter, getOrCreateGauge, getOrCreateLatencyHistogram, getO
3
3
  import { readCookieRowCounts } from "./change-log-cookies.js";
4
4
  import { versionFromLexi } from "../../types/lexi-version.js";
5
5
  import { CHANGE_LOG_STREAM_TABLE, readChangeLogBounds, readChangeLogMeta } from "./change-log-db.js";
6
- import { extractChangeSubstring } from "../change-streamer/change-log-codec.js";
7
- import { ChangeLogTransactionHasher } from "../change-streamer/change-log-transaction-hash.js";
8
6
  import { stat } from "node:fs/promises";
9
7
  //#region ../zero-cache/src/services/replicator/sqlite-change-log-observability.ts
10
8
  /**
@@ -146,8 +144,6 @@ var SQLiteChangeLogObserver = class {
146
144
  });
147
145
  #rollbackCounter = getOrCreateCounter("replica", "sqlite_change_log.rollbacks", "SQLite change-log transactions rolled back before commit.");
148
146
  #invariantFailureCounter = getOrCreateCounter("replica", "sqlite_change_log.invariant_failures", "Detected SQLite change-log writer invariant failures.");
149
- #hashComparisonCounter = getOrCreateCounter("replica", "sqlite_change_log.hash_comparisons", "Sampled ephemeral transaction hash comparisons between the received change stream and SQLite change-log writes.");
150
- #hashUnpairedCounter = getOrCreateCounter("replica", "sqlite_change_log.hash_unpaired", "Committed change-log transactions without both ephemeral hashes available for comparison.");
151
147
  #cookieMutationCounter = getOrCreateCounter("replica", "sqlite_change_log.cookie_mutations", "Change-log cookie mutations folded from schema changes, by operation.");
152
148
  #receivedHead;
153
149
  #sqliteHead;
@@ -156,14 +152,8 @@ var SQLiteChangeLogObserver = class {
156
152
  #cookieRows;
157
153
  #cookieMutations = 0;
158
154
  #transactionWatermark;
159
- #sourceHasher;
160
- #sourcePos = 0;
161
- #sourceCommitHash;
162
155
  #rollbacks = 0;
163
156
  #invariantFailures = 0;
164
- #hashMatches = 0;
165
- #hashMismatches = 0;
166
- #hashUnpaired = 0;
167
157
  constructor(lc, info) {
168
158
  this.#lc = lc.withContext("component", "sqlite-change-log-observer");
169
159
  this.#receivedHead = info.headWatermark;
@@ -190,50 +180,11 @@ var SQLiteChangeLogObserver = class {
190
180
  });
191
181
  }
192
182
  /**
193
- * Called as each message arrives, before it is written. For a sampled
194
- * transaction, hashes the *received* stream and compares it with the hash the
195
- * writer computes over what it *stored*.
183
+ * Called as each message arrives, before it is written, so that the head
184
+ * lag includes a transaction that is in flight.
196
185
  */
197
- messageReceived(data, json, validateHash = true, storedChange = extractChangeSubstring(json, data[1].tag)) {
198
- const tag = data[1].tag;
199
- if (data[0] === "begin") {
200
- if (this.#sourceHasher !== void 0) this.#invariantFailure("Received change-log begin while a source hash is already open", { receivedWatermark: data[2].commitWatermark });
201
- const watermark = data[2].commitWatermark;
202
- this.#sourceHasher = validateHash ? new ChangeLogTransactionHasher() : void 0;
203
- this.#sourcePos = 0;
204
- this.#sourceCommitHash = void 0;
205
- this.#sourceHasher?.add({
206
- watermark,
207
- pos: this.#sourcePos,
208
- tag,
209
- change: storedChange,
210
- precommit: null
211
- });
212
- return;
213
- }
214
- if (tag === "rollback") {
215
- this.#resetSourceHash();
216
- return;
217
- }
186
+ messageReceived(data) {
218
187
  if (data[0] === "commit") this.#receivedHead = data[2].watermark;
219
- if (!validateHash) return;
220
- const watermark = this.#transactionWatermark;
221
- if (this.#sourceHasher === void 0 || watermark === void 0) {
222
- this.#invariantFailure("Received change-log message without an observed transaction", { tag });
223
- return;
224
- }
225
- const commitWatermark = data[0] === "commit" ? data[2].watermark : watermark;
226
- this.#sourceHasher.add({
227
- watermark: commitWatermark,
228
- pos: ++this.#sourcePos,
229
- tag,
230
- change: storedChange,
231
- precommit: data[0] === "commit" ? watermark : null
232
- });
233
- if (data[0] === "commit") {
234
- this.#sourceCommitHash = this.#sourceHasher.digest();
235
- this.#sourceHasher = void 0;
236
- }
237
188
  }
238
189
  /** Called after the message has been written to the log. */
239
190
  messageProcessed(data, commit, durationMs) {
@@ -253,7 +204,6 @@ var SQLiteChangeLogObserver = class {
253
204
  if (tag === "rollback") {
254
205
  this.#recordRollback("upstream");
255
206
  this.#transactionWatermark = void 0;
256
- this.#resetSourceHash();
257
207
  return;
258
208
  }
259
209
  if (data[0] !== "commit") return;
@@ -263,10 +213,8 @@ var SQLiteChangeLogObserver = class {
263
213
  openWatermark: this.#transactionWatermark,
264
214
  commitWatermark: watermark
265
215
  });
266
- if (commit === null) {
267
- this.#invariantFailure("SQLite change-log commit result is missing writer statistics", { commitWatermark: watermark });
268
- this.#recordUnpaired(watermark, "missing-sqlite-hash");
269
- } else {
216
+ if (commit === null) this.#invariantFailure("SQLite change-log commit result is missing writer statistics", { commitWatermark: watermark });
217
+ else {
270
218
  if (commit.watermark !== watermark) this.#invariantFailure("SQLite change-log commit result has an unexpected watermark", {
271
219
  commitWatermark: watermark,
272
220
  resultWatermark: commit.watermark
@@ -274,7 +222,6 @@ var SQLiteChangeLogObserver = class {
274
222
  this.#rows += commit.stats.rows;
275
223
  this.#estimatedBytes += commit.stats.estimatedBytes;
276
224
  this.#transactionRows.record(commit.stats.rows);
277
- if (this.#sourceCommitHash !== void 0 || commit.stats.hash !== void 0) this.#compareHashes(watermark, this.#sourceCommitHash, commit.stats.hash);
278
225
  }
279
226
  if (watermark < this.#sqliteHead) this.#invariantFailure("SQLite change-log head regressed", {
280
227
  previousHead: this.#sqliteHead,
@@ -282,7 +229,6 @@ var SQLiteChangeLogObserver = class {
282
229
  });
283
230
  this.#sqliteHead = watermark;
284
231
  this.#transactionWatermark = void 0;
285
- this.#resetSourceHash();
286
232
  }
287
233
  messageFailed(data, error, durationMs) {
288
234
  const tag = data[1].tag;
@@ -290,11 +236,9 @@ var SQLiteChangeLogObserver = class {
290
236
  tag,
291
237
  outcome: "error"
292
238
  });
293
- if (data[0] === "commit" && this.#sourceCommitHash !== void 0) this.#recordUnpaired(data[2].watermark, "sqlite-commit-failed");
294
239
  if (error instanceof Error && error.name === "ChangeLogStreamInvariantError") this.#invariantFailure(error.message);
295
240
  if (this.#transactionWatermark !== void 0 || data[0] === "begin") this.#recordRollback("processing-error");
296
241
  this.#transactionWatermark = void 0;
297
- this.#resetSourceHash();
298
242
  }
299
243
  /**
300
244
  * A committed transaction folded schema changes into the cookie jar. Reported
@@ -323,7 +267,6 @@ var SQLiteChangeLogObserver = class {
323
267
  this.#recordRollback("source-interruption");
324
268
  this.#transactionWatermark = void 0;
325
269
  }
326
- this.#resetSourceHash();
327
270
  }
328
271
  /** Reconciliation moved the head, so the observer's totals are restated. */
329
272
  reconciled(info) {
@@ -333,7 +276,6 @@ var SQLiteChangeLogObserver = class {
333
276
  this.#estimatedBytes = info.estimatedBytes;
334
277
  this.#cookieRows = info.cookieRows;
335
278
  this.#transactionWatermark = void 0;
336
- this.#resetSourceHash();
337
279
  }
338
280
  state() {
339
281
  return {
@@ -345,10 +287,7 @@ var SQLiteChangeLogObserver = class {
345
287
  cookieRows: this.#cookieRows,
346
288
  cookieMutations: this.#cookieMutations,
347
289
  rollbacks: this.#rollbacks,
348
- invariantFailures: this.#invariantFailures,
349
- hashMatches: this.#hashMatches,
350
- hashMismatches: this.#hashMismatches,
351
- hashUnpaired: this.#hashUnpaired
290
+ invariantFailures: this.#invariantFailures
352
291
  };
353
292
  }
354
293
  #recordRollback(reason) {
@@ -360,41 +299,6 @@ var SQLiteChangeLogObserver = class {
360
299
  this.#invariantFailureCounter.add(1);
361
300
  this.#lc.error?.(message, details);
362
301
  }
363
- #compareHashes(watermark, sourceHash, sqliteHash) {
364
- if (sourceHash === void 0) {
365
- this.#recordUnpaired(watermark, "missing-source-hash");
366
- return;
367
- }
368
- if (sqliteHash === void 0) {
369
- this.#recordUnpaired(watermark, "missing-sqlite-hash");
370
- return;
371
- }
372
- if (sourceHash === sqliteHash) {
373
- this.#hashMatches++;
374
- this.#hashComparisonCounter.add(1, { outcome: "match" });
375
- return;
376
- }
377
- this.#hashMismatches++;
378
- this.#hashComparisonCounter.add(1, { outcome: "mismatch" });
379
- this.#lc.error?.("SQLite change-log transaction hash mismatch", { sqliteChangeLogHashComparison: {
380
- watermark,
381
- sourceHash: sourceHash.slice(0, 16),
382
- sqliteHash: sqliteHash.slice(0, 16)
383
- } });
384
- }
385
- #recordUnpaired(watermark, reason) {
386
- this.#hashUnpaired++;
387
- this.#hashUnpairedCounter.add(1, { reason });
388
- this.#lc.warn?.("SQLite change-log transaction hash was not compared", { sqliteChangeLogHashComparison: {
389
- watermark,
390
- reason
391
- } });
392
- }
393
- #resetSourceHash() {
394
- this.#sourceHasher = void 0;
395
- this.#sourcePos = 0;
396
- this.#sourceCommitHash = void 0;
397
- }
398
302
  };
399
303
  function watermarkValue(watermark) {
400
304
  try {
@@ -1 +1 @@
1
- {"version":3,"file":"sqlite-change-log-observability.js","names":[],"sources":["../../../../../../zero-cache/src/services/replicator/sqlite-change-log-observability.ts"],"sourcesContent":["/**\n * Observability for the SQLite change log.\n *\n * Everything here now runs in the **change-streamer** process, which is where\n * the writer lives. The module stays beside the rest of the change-log code\n * under `services/replicator/` for the same reason `change-log-db.ts` and\n * `change-log-stream-writer.ts` do: moving files would obscure the topology\n * diff, and the writer's home is a property of who calls it rather than of\n * where it sits. Metric names are unchanged from 7H — only their emitting\n * process, and therefore their resource attributes, moved.\n */\n\nimport {stat} from 'node:fs/promises';\nimport type {LogContext} from '@rocicorp/logger';\nimport {unreachable} from '../../../../shared/src/asserts.ts';\nimport type {Database} from '../../../../zqlite/src/db.ts';\nimport {\n getOrCreateCounter,\n getOrCreateGauge,\n getOrCreateLatencyHistogram,\n getOrCreateValueHistogram,\n} from '../../observability/metrics.ts';\nimport {versionFromLexi} from '../../types/lexi-version.ts';\nimport type {ChangeStreamData} from '../change-source/protocol/current/downstream.ts';\nimport {extractChangeSubstring} from '../change-streamer/change-log-codec.ts';\nimport {ChangeLogTransactionHasher} from '../change-streamer/change-log-transaction-hash.ts';\nimport {\n readCookieRowCounts,\n type CookieOpTag,\n type CookieRowCounts,\n} from './change-log-cookies.ts';\nimport {\n CHANGE_LOG_STREAM_TABLE,\n readChangeLogBounds,\n readChangeLogMeta,\n type ChangeLogMeta,\n type ReconcileResult,\n} from './change-log-db.ts';\nimport type {ChangeLogStreamTransactionStats} from './change-log-stream-writer.ts';\n\n/**\n * Reports the reconciliation of the change-log database against the watermark\n * the stream connection resumes from. This runs once per stream connection, so\n * a reconnect storm is visible here as well as a restart.\n *\n * A wipe is not an error — it is how every abnormal change-log state is\n * collapsed into a correct one — but each wipe costs the retention window, so\n * every reconnecting subscriber below the head gets `too-old`. The `gap` reason\n * in particular means the log neither held the resume watermark nor could be\n * truncated to it, so a nonzero rate in steady state is an alert, not a\n * statistic.\n */\nexport function recordSQLiteChangeLogReconcile(\n lc: LogContext,\n result: ReconcileResult,\n): void {\n switch (result.action) {\n case 'truncated':\n getOrCreateCounter(\n 'replica',\n 'sqlite_change_log.reconcile_truncated_rows',\n 'Phantom change-log rows removed at reconciliation, i.e. rows above ' +\n 'the watermark the change stream resumed from.',\n ).add(result.rows);\n break;\n case 'reseeded':\n getOrCreateCounter(\n 'replica',\n 'sqlite_change_log.reconcile_wipes',\n 'Change-log wipes at reconciliation, by reason. Each one resets the ' +\n 'retention window, so subscribers below the head get `too-old`.',\n ).add(1, {reason: result.reason});\n break;\n case 'none':\n break;\n default:\n unreachable(result);\n }\n if (result.cookiesStale) {\n // The invariant-17 counter: after any reconcile that moved the head, the\n // log's cookie set has to be replaced with the one that belongs to the\n // resume watermark. A nonzero `truncated` series in steady state means\n // phantom truncation is happening on a shard where it should not.\n getOrCreateCounter(\n 'replica',\n 'sqlite_change_log.cookie_reseed',\n 'Change-log cookie sets invalidated at reconciliation, by the ' +\n 'reconcile action that invalidated them.',\n ).add(1, {action: result.action});\n }\n lc.debug?.('SQLite change-log reconciliation', {\n sqliteChangeLogReconcile: result,\n });\n}\n\n/**\n * What the log says about itself. Nothing here reads the replica: after the\n * writer moved to the change-streamer, the replica's state version is a\n * consequence of this log rather than a fact about it.\n */\nexport type SQLiteChangeLogStartupInfo = ChangeLogMeta & {\n readonly minWatermark: string;\n readonly headWatermark: string;\n};\n\nexport type SQLiteChangeLogInfo = SQLiteChangeLogStartupInfo & {\n readonly rows: number;\n readonly estimatedBytes: number;\n readonly cookieRows: CookieRowCounts;\n};\n\n/**\n * Reads the meta row and covered range. Unlike {@link getSQLiteChangeLogInfo}\n * this does not scan the log; see {@link readChangeLogBounds}.\n *\n * Call this after reconciliation, which is the only point at which the head is\n * known to be the resume watermark.\n */\nexport function getSQLiteChangeLogStartupInfo(\n changeLog: Database,\n): SQLiteChangeLogStartupInfo {\n const meta = readChangeLogMeta(changeLog);\n const {minWatermark, headWatermark} = readChangeLogBounds(changeLog);\n if (minWatermark === null || headWatermark === null) {\n throw new Error('the SQLite change log must contain its seed transaction');\n }\n return {...meta, minWatermark, headWatermark};\n}\n\n/**\n * Extends {@link getSQLiteChangeLogStartupInfo} with the retained row and\n * estimated byte totals. Computing these scans the entire change-log table, so\n * only call it when the totals are consumed, i.e. when the writer (and thus the\n * observer) is enabled.\n */\nexport function getSQLiteChangeLogInfo(\n changeLog: Database,\n): SQLiteChangeLogInfo {\n const startup = getSQLiteChangeLogStartupInfo(changeLog);\n const aggregate = changeLog\n .prepare(/*sql*/ `\n SELECT count(*) AS \"rows\",\n coalesce(sum(\"estimatedBytes\"), 0) AS \"estimatedBytes\"\n FROM \"${CHANGE_LOG_STREAM_TABLE}\"\n `)\n .get<{rows: number; estimatedBytes: number}>();\n\n return {\n ...startup,\n rows: aggregate.rows,\n estimatedBytes: aggregate.estimatedBytes,\n cookieRows: readCookieRowCounts(changeLog),\n };\n}\n\nexport function logSQLiteChangeLogStartup(\n lc: LogContext,\n file: string,\n info: SQLiteChangeLogStartupInfo,\n): void {\n lc.info?.('SQLite change-log startup', {\n sqliteChangeLog: {\n file,\n epoch: info.epoch,\n generation: info.generation,\n replicaID: info.replicaID,\n schemaVersion: info.schemaVersion,\n seedWatermark: info.seedWatermark,\n seededAtMs: info.seededAtMs,\n minWatermark: info.minWatermark,\n headWatermark: info.headWatermark,\n },\n });\n}\n\n/**\n * The on-disk footprint of a SQLite database: its main file plus its `-wal` and\n * `-wal2` sidecars, whichever exist. `-shm` is excluded — it is a\n * shared-memory index rather than retained bytes.\n *\n * A missing file counts as zero rather than warning. Which sidecars exist\n * depends on the journal mode, and the change-log database is absent entirely\n * until the writer creates it.\n */\nexport async function sqliteFileBytes(\n lc: LogContext,\n file: string,\n): Promise<number> {\n const sizes = await Promise.all(\n [file, `${file}-wal`, `${file}-wal2`].map(async path => {\n try {\n return (await stat(path)).size;\n } catch (e) {\n if ((e as NodeJS.ErrnoException).code !== 'ENOENT') {\n lc.warn?.(`unable to stat ${path} for size metrics`, e);\n }\n return 0;\n }\n }),\n );\n return sizes.reduce((total, size) => total + size, 0);\n}\n\n/** What the writer reports back for a committed transaction. */\nexport type ChangeLogCommit = {\n readonly watermark: string;\n readonly stats: ChangeLogStreamTransactionStats;\n /**\n * Appending the commit row and committing the log's transaction. This is the\n * cost that sits on the forward path, once per upstream transaction.\n */\n readonly logCommitMs: number;\n};\n\nexport type SQLiteChangeLogObservabilityState = {\n readonly receivedHead: string;\n readonly sqliteHead: string;\n readonly headLag: number | undefined;\n readonly rows: number;\n readonly estimatedBytes: number;\n readonly cookieRows: CookieRowCounts;\n readonly cookieMutations: number;\n readonly rollbacks: number;\n readonly invariantFailures: number;\n readonly hashMatches: number;\n readonly hashMismatches: number;\n readonly hashUnpaired: number;\n};\n\nconst TRANSACTION_ROW_BUCKETS = [2, 3, 5, 10, 25, 50, 100, 250, 1000, 5000];\n\n/**\n * Records writer metrics in the change-streamer process. State changes only\n * after the corresponding write succeeds, except receivedHead, which advances\n * when a commit message arrives so that transient lag behind the log is\n * observable.\n */\nexport class SQLiteChangeLogObserver {\n readonly #lc: LogContext;\n readonly #messageProcessing = getOrCreateLatencyHistogram(\n 'replica',\n 'sqlite_change_log.message_processing_duration',\n 'Sampled time to write a replication message to the SQLite change log.',\n );\n // The commit that sits on the forward path. There is no second commit to\n // order against any more: the replica's belongs to a subscriber downstream of\n // this loop, so `sqlite_change_log.replica_commit_duration` and the phantom\n // window it measured are gone. Sampled failed commits are still timed by\n // `message_processing_duration` keyed `tag=\"commit\"`.\n readonly #logCommitDuration = getOrCreateLatencyHistogram(\n 'replica',\n 'sqlite_change_log.log_commit_duration',\n 'Time to append the commit row to the SQLite change log and commit its ' +\n 'transaction. This is on the forward path: it precedes the forward of ' +\n \"that transaction's commit message.\",\n );\n readonly #transactionRows = getOrCreateValueHistogram(\n 'replica',\n 'sqlite_change_log.transaction_rows',\n {\n description: 'Rows stored per committed SQLite change-log transaction.',\n unit: '{row}',\n bucketBoundaries: TRANSACTION_ROW_BUCKETS,\n },\n );\n readonly #rollbackCounter = getOrCreateCounter(\n 'replica',\n 'sqlite_change_log.rollbacks',\n 'SQLite change-log transactions rolled back before commit.',\n );\n readonly #invariantFailureCounter = getOrCreateCounter(\n 'replica',\n 'sqlite_change_log.invariant_failures',\n 'Detected SQLite change-log writer invariant failures.',\n );\n readonly #hashComparisonCounter = getOrCreateCounter(\n 'replica',\n 'sqlite_change_log.hash_comparisons',\n 'Sampled ephemeral transaction hash comparisons between the received change stream and SQLite change-log writes.',\n );\n readonly #hashUnpairedCounter = getOrCreateCounter(\n 'replica',\n 'sqlite_change_log.hash_unpaired',\n 'Committed change-log transactions without both ephemeral hashes available for comparison.',\n );\n // Near zero at steady state: cookie state only moves on schema changes.\n readonly #cookieMutationCounter = getOrCreateCounter(\n 'replica',\n 'sqlite_change_log.cookie_mutations',\n 'Change-log cookie mutations folded from schema changes, by operation.',\n );\n\n #receivedHead: string;\n #sqliteHead: string;\n #rows: number;\n #estimatedBytes: number;\n #cookieRows: CookieRowCounts;\n #cookieMutations = 0;\n #transactionWatermark: string | undefined;\n #sourceHasher: ChangeLogTransactionHasher | undefined;\n #sourcePos = 0;\n #sourceCommitHash: string | undefined;\n #rollbacks = 0;\n #invariantFailures = 0;\n #hashMatches = 0;\n #hashMismatches = 0;\n #hashUnpaired = 0;\n\n constructor(lc: LogContext, info: SQLiteChangeLogInfo) {\n this.#lc = lc.withContext('component', 'sqlite-change-log-observer');\n // Reconciliation has just put the head at the resume watermark, which is\n // also the point the stream is about to be received from.\n this.#receivedHead = info.headWatermark;\n this.#sqliteHead = info.headWatermark;\n this.#rows = info.rows;\n this.#estimatedBytes = info.estimatedBytes;\n this.#cookieRows = info.cookieRows;\n\n getOrCreateGauge(\n 'replica',\n 'sqlite_change_log.rows',\n 'Rows retained in the SQLite change log.',\n ).addCallback(result => result.observe(this.#rows));\n // Nonzero with no backfill in flight is a leaked cookie, i.e. a backfill\n // that will be re-requested forever.\n getOrCreateGauge(\n 'replica',\n 'sqlite_change_log.cookie_rows',\n 'Cookie rows retained in the SQLite change log, by cookie table.',\n ).addCallback(result => {\n result.observe(this.#cookieRows.tableMetadata, {table: 'tableMetadata'});\n result.observe(this.#cookieRows.backfilling, {table: 'backfilling'});\n });\n getOrCreateGauge('replica', 'sqlite_change_log.retained_bytes', {\n description:\n 'Estimated UTF-8 payload bytes retained in the SQLite change log.',\n unit: 'By',\n }).addCallback(result => result.observe(this.#estimatedBytes));\n getOrCreateGauge(\n 'replica',\n 'sqlite_change_log.head',\n 'SQLite change-log head converted from its lexicographic watermark.',\n ).addCallback(result => {\n const head = watermarkValue(this.#sqliteHead);\n if (head !== undefined) {\n result.observe(head);\n }\n });\n getOrCreateGauge(\n 'replica',\n 'sqlite_change_log.head_lag',\n 'Distance from the latest received commit to the SQLite change-log ' +\n 'head. The log commits before the forward, so this is zero except ' +\n 'within a transaction.',\n ).addCallback(result => {\n const lag = watermarkDistance(this.#receivedHead, this.#sqliteHead);\n if (lag !== undefined) {\n result.observe(lag);\n }\n });\n }\n\n /**\n * Called as each message arrives, before it is written. For a sampled\n * transaction, hashes the *received* stream and compares it with the hash the\n * writer computes over what it *stored*.\n */\n messageReceived(\n data: ChangeStreamData,\n json: string,\n validateHash = true,\n storedChange = extractChangeSubstring(json, data[1].tag),\n ): void {\n const tag = data[1].tag;\n if (data[0] === 'begin') {\n if (this.#sourceHasher !== undefined) {\n this.#invariantFailure(\n 'Received change-log begin while a source hash is already open',\n {receivedWatermark: data[2].commitWatermark},\n );\n }\n const watermark = data[2].commitWatermark;\n this.#sourceHasher = validateHash\n ? new ChangeLogTransactionHasher()\n : undefined;\n this.#sourcePos = 0;\n this.#sourceCommitHash = undefined;\n this.#sourceHasher?.add({\n watermark,\n pos: this.#sourcePos,\n tag,\n change: storedChange,\n precommit: null,\n });\n return;\n }\n\n if (tag === 'rollback') {\n this.#resetSourceHash();\n return;\n }\n\n if (data[0] === 'commit') {\n this.#receivedHead = data[2].watermark;\n }\n\n if (!validateHash) {\n return;\n }\n\n const watermark = this.#transactionWatermark;\n if (this.#sourceHasher === undefined || watermark === undefined) {\n this.#invariantFailure(\n 'Received change-log message without an observed transaction',\n {tag},\n );\n return;\n }\n\n const commitWatermark =\n data[0] === 'commit' ? data[2].watermark : watermark;\n this.#sourceHasher.add({\n watermark: commitWatermark,\n pos: ++this.#sourcePos,\n tag,\n change: storedChange,\n precommit: data[0] === 'commit' ? watermark : null,\n });\n if (data[0] === 'commit') {\n this.#sourceCommitHash = this.#sourceHasher.digest();\n this.#sourceHasher = undefined;\n }\n }\n\n /** Called after the message has been written to the log. */\n messageProcessed(\n data: ChangeStreamData,\n commit: ChangeLogCommit | null,\n durationMs: number | undefined,\n ): void {\n const tag = data[1].tag;\n if (durationMs !== undefined) {\n this.#messageProcessing.recordMs(durationMs, {tag, outcome: 'success'});\n }\n\n if (data[0] === 'begin') {\n if (this.#transactionWatermark !== undefined) {\n this.#invariantFailure('SQLite change-log transaction already open', {\n openWatermark: this.#transactionWatermark,\n receivedWatermark: data[2].commitWatermark,\n });\n }\n this.#transactionWatermark = data[2].commitWatermark;\n return;\n }\n\n if (tag === 'rollback') {\n this.#recordRollback('upstream');\n this.#transactionWatermark = undefined;\n this.#resetSourceHash();\n return;\n }\n\n if (data[0] !== 'commit') {\n return;\n }\n\n const watermark = data[2].watermark;\n if (commit !== null) {\n this.#logCommitDuration.recordMs(commit.logCommitMs);\n }\n if (this.#transactionWatermark !== watermark) {\n this.#invariantFailure(\n 'SQLite change-log commit does not match the observed begin',\n {openWatermark: this.#transactionWatermark, commitWatermark: watermark},\n );\n }\n if (commit === null) {\n this.#invariantFailure(\n 'SQLite change-log commit result is missing writer statistics',\n {commitWatermark: watermark},\n );\n this.#recordUnpaired(watermark, 'missing-sqlite-hash');\n } else {\n if (commit.watermark !== watermark) {\n this.#invariantFailure(\n 'SQLite change-log commit result has an unexpected watermark',\n {commitWatermark: watermark, resultWatermark: commit.watermark},\n );\n }\n this.#rows += commit.stats.rows;\n this.#estimatedBytes += commit.stats.estimatedBytes;\n this.#transactionRows.record(commit.stats.rows);\n if (\n this.#sourceCommitHash !== undefined ||\n commit.stats.hash !== undefined\n ) {\n this.#compareHashes(\n watermark,\n this.#sourceCommitHash,\n commit.stats.hash,\n );\n }\n }\n if (watermark < this.#sqliteHead) {\n this.#invariantFailure('SQLite change-log head regressed', {\n previousHead: this.#sqliteHead,\n commitWatermark: watermark,\n });\n }\n this.#sqliteHead = watermark;\n this.#transactionWatermark = undefined;\n this.#resetSourceHash();\n }\n\n messageFailed(\n data: ChangeStreamData,\n error: unknown,\n durationMs: number | undefined,\n ): void {\n const tag = data[1].tag;\n if (durationMs !== undefined) {\n this.#messageProcessing.recordMs(durationMs, {tag, outcome: 'error'});\n }\n if (data[0] === 'commit' && this.#sourceCommitHash !== undefined) {\n // No commit duration here: a failed commit produces no statistics, so\n // there is nothing to attribute. The attempt is timed by\n // `message_processing_duration{tag=\"commit\",outcome=\"error\"}` above.\n this.#recordUnpaired(data[2].watermark, 'sqlite-commit-failed');\n }\n if (\n error instanceof Error &&\n error.name === 'ChangeLogStreamInvariantError'\n ) {\n this.#invariantFailure(error.message);\n }\n if (this.#transactionWatermark !== undefined || data[0] === 'begin') {\n this.#recordRollback('processing-error');\n }\n this.#transactionWatermark = undefined;\n this.#resetSourceHash();\n }\n\n /**\n * A committed transaction folded schema changes into the cookie jar. Reported\n * separately from {@link messageProcessed} because it costs a read of the\n * cookie tables, which is only worth taking when they actually moved.\n */\n cookiesMutated(ops: readonly CookieOpTag[], rows: CookieRowCounts): void {\n for (const op of ops) {\n this.#cookieMutations++;\n this.#cookieMutationCounter.add(1, {op});\n }\n this.#cookieRows = rows;\n }\n\n /**\n * A missed truncate-above surfaces as a constraint violation on the writer's\n * plain `INSERT`, which the fail-soft policy would otherwise absorb quietly.\n * Classifying it as an invariant failure is what keeps a reconciliation bug\n * from looking like a lost cache.\n */\n invariantFailure(message: string, details?: Record<string, unknown>): void {\n this.#invariantFailure(message, details);\n }\n\n /** The source interrupted the stream mid-transaction. */\n abort(): void {\n if (this.#transactionWatermark !== undefined) {\n this.#recordRollback('source-interruption');\n this.#transactionWatermark = undefined;\n }\n this.#resetSourceHash();\n }\n\n /** Reconciliation moved the head, so the observer's totals are restated. */\n reconciled(info: SQLiteChangeLogInfo): void {\n this.#receivedHead = info.headWatermark;\n this.#sqliteHead = info.headWatermark;\n this.#rows = info.rows;\n this.#estimatedBytes = info.estimatedBytes;\n this.#cookieRows = info.cookieRows;\n this.#transactionWatermark = undefined;\n this.#resetSourceHash();\n }\n\n state(): SQLiteChangeLogObservabilityState {\n return {\n receivedHead: this.#receivedHead,\n sqliteHead: this.#sqliteHead,\n headLag: watermarkDistance(this.#receivedHead, this.#sqliteHead),\n rows: this.#rows,\n estimatedBytes: this.#estimatedBytes,\n cookieRows: this.#cookieRows,\n cookieMutations: this.#cookieMutations,\n rollbacks: this.#rollbacks,\n invariantFailures: this.#invariantFailures,\n hashMatches: this.#hashMatches,\n hashMismatches: this.#hashMismatches,\n hashUnpaired: this.#hashUnpaired,\n };\n }\n\n #recordRollback(\n reason: 'upstream' | 'processing-error' | 'source-interruption',\n ) {\n this.#rollbacks++;\n this.#rollbackCounter.add(1, {reason});\n }\n\n #invariantFailure(message: string, details?: Record<string, unknown>) {\n this.#invariantFailures++;\n this.#invariantFailureCounter.add(1);\n this.#lc.error?.(message, details);\n }\n\n #compareHashes(\n watermark: string,\n sourceHash: string | undefined,\n sqliteHash: string | undefined,\n ): void {\n if (sourceHash === undefined) {\n this.#recordUnpaired(watermark, 'missing-source-hash');\n return;\n }\n if (sqliteHash === undefined) {\n this.#recordUnpaired(watermark, 'missing-sqlite-hash');\n return;\n }\n if (sourceHash === sqliteHash) {\n this.#hashMatches++;\n this.#hashComparisonCounter.add(1, {outcome: 'match'});\n return;\n }\n this.#hashMismatches++;\n this.#hashComparisonCounter.add(1, {outcome: 'mismatch'});\n this.#lc.error?.('SQLite change-log transaction hash mismatch', {\n sqliteChangeLogHashComparison: {\n watermark,\n sourceHash: sourceHash.slice(0, 16),\n sqliteHash: sqliteHash.slice(0, 16),\n },\n });\n }\n\n #recordUnpaired(\n watermark: string,\n reason:\n | 'missing-source-hash'\n | 'missing-sqlite-hash'\n | 'sqlite-commit-failed',\n ): void {\n this.#hashUnpaired++;\n this.#hashUnpairedCounter.add(1, {reason});\n this.#lc.warn?.('SQLite change-log transaction hash was not compared', {\n sqliteChangeLogHashComparison: {watermark, reason},\n });\n }\n\n #resetSourceHash(): void {\n this.#sourceHasher = undefined;\n this.#sourcePos = 0;\n this.#sourceCommitHash = undefined;\n }\n}\n\nfunction watermarkValue(watermark: string): number | undefined {\n try {\n const value = Number(versionFromLexi(watermark));\n return Number.isFinite(value) ? value : undefined;\n } catch {\n return undefined;\n }\n}\n\nfunction watermarkDistance(\n receivedHead: string,\n sqliteHead: string,\n): number | undefined {\n if (receivedHead <= sqliteHead) {\n return 0;\n }\n try {\n const distance =\n versionFromLexi(receivedHead) - versionFromLexi(sqliteHead);\n const value = Number(distance);\n return Number.isFinite(value) ? value : undefined;\n } catch {\n return undefined;\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAoDA,SAAgB,+BACd,IACA,QACM;CACN,QAAQ,OAAO,QAAf;EACE,KAAK;GACH,mBACE,WACA,8CACA,kHAEF,CAAC,CAAC,IAAI,OAAO,IAAI;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C;EACzC,KAAK,IAAI,OAAO,uDAAuD,EACrE,+BAA+B;GAAC;GAAW;EAAM,EACnD,CAAC;CACH;CAEA,mBAAyB;EACvB,KAAK,gBAAgB,KAAA;EACrB,KAAK,aAAa;EAClB,KAAK,oBAAoB,KAAA;CAC3B;AACF;AAEA,SAAS,eAAe,WAAuC;CAC7D,IAAI;EACF,MAAM,QAAQ,OAAO,gBAAgB,SAAS,CAAC;EAC/C,OAAO,OAAO,SAAS,KAAK,IAAI,QAAQ,KAAA;CAC1C,QAAQ;EACN;CACF;AACF;AAEA,SAAS,kBACP,cACA,YACoB;CACpB,IAAI,gBAAgB,YAClB,OAAO;CAET,IAAI;EACF,MAAM,WACJ,gBAAgB,YAAY,IAAI,gBAAgB,UAAU;EAC5D,MAAM,QAAQ,OAAO,QAAQ;EAC7B,OAAO,OAAO,SAAS,KAAK,IAAI,QAAQ,KAAA;CAC1C,QAAQ;EACN;CACF;AACF"}
1
+ {"version":3,"file":"sqlite-change-log-observability.js","names":[],"sources":["../../../../../../zero-cache/src/services/replicator/sqlite-change-log-observability.ts"],"sourcesContent":["/**\n * Observability for the SQLite change log.\n *\n * Everything here now runs in the **change-streamer** process, which is where\n * the writer lives. The module stays beside the rest of the change-log code\n * under `services/replicator/` for the same reason `change-log-db.ts` and\n * `change-log-stream-writer.ts` do: moving files would obscure the topology\n * diff, and the writer's home is a property of who calls it rather than of\n * where it sits. Metric names are unchanged from 7H — only their emitting\n * process, and therefore their resource attributes, moved.\n */\n\nimport {stat} from 'node:fs/promises';\nimport type {LogContext} from '@rocicorp/logger';\nimport {unreachable} from '../../../../shared/src/asserts.ts';\nimport type {Database} from '../../../../zqlite/src/db.ts';\nimport {\n getOrCreateCounter,\n getOrCreateGauge,\n getOrCreateLatencyHistogram,\n getOrCreateValueHistogram,\n} from '../../observability/metrics.ts';\nimport {versionFromLexi} from '../../types/lexi-version.ts';\nimport type {ChangeStreamData} from '../change-source/protocol/current/downstream.ts';\nimport {\n readCookieRowCounts,\n type CookieOpTag,\n type CookieRowCounts,\n} from './change-log-cookies.ts';\nimport {\n CHANGE_LOG_STREAM_TABLE,\n readChangeLogBounds,\n readChangeLogMeta,\n type ChangeLogMeta,\n type ReconcileResult,\n} from './change-log-db.ts';\nimport type {ChangeLogStreamTransactionStats} from './change-log-stream-writer.ts';\n\n/**\n * Reports the reconciliation of the change-log database against the watermark\n * the stream connection resumes from. This runs once per stream connection, so\n * a reconnect storm is visible here as well as a restart.\n *\n * A wipe is not an error — it is how every abnormal change-log state is\n * collapsed into a correct one — but each wipe costs the retention window, so\n * every reconnecting subscriber below the head gets `too-old`. The `gap` reason\n * in particular means the log neither held the resume watermark nor could be\n * truncated to it, so a nonzero rate in steady state is an alert, not a\n * statistic.\n */\nexport function recordSQLiteChangeLogReconcile(\n lc: LogContext,\n result: ReconcileResult,\n): void {\n switch (result.action) {\n case 'truncated':\n getOrCreateCounter(\n 'replica',\n 'sqlite_change_log.reconcile_truncated_rows',\n 'Phantom change-log rows removed at reconciliation, i.e. rows above ' +\n 'the watermark the change stream resumed from.',\n ).add(result.rows);\n break;\n case 'reseeded':\n getOrCreateCounter(\n 'replica',\n 'sqlite_change_log.reconcile_wipes',\n 'Change-log wipes at reconciliation, by reason. Each one resets the ' +\n 'retention window, so subscribers below the head get `too-old`.',\n ).add(1, {reason: result.reason});\n break;\n case 'none':\n break;\n default:\n unreachable(result);\n }\n if (result.cookiesStale) {\n // The invariant-17 counter: after any reconcile that moved the head, the\n // log's cookie set has to be replaced with the one that belongs to the\n // resume watermark. A nonzero `truncated` series in steady state means\n // phantom truncation is happening on a shard where it should not.\n getOrCreateCounter(\n 'replica',\n 'sqlite_change_log.cookie_reseed',\n 'Change-log cookie sets invalidated at reconciliation, by the ' +\n 'reconcile action that invalidated them.',\n ).add(1, {action: result.action});\n }\n lc.debug?.('SQLite change-log reconciliation', {\n sqliteChangeLogReconcile: result,\n });\n}\n\n/**\n * What the log says about itself. Nothing here reads the replica: after the\n * writer moved to the change-streamer, the replica's state version is a\n * consequence of this log rather than a fact about it.\n */\nexport type SQLiteChangeLogStartupInfo = ChangeLogMeta & {\n readonly minWatermark: string;\n readonly headWatermark: string;\n};\n\nexport type SQLiteChangeLogInfo = SQLiteChangeLogStartupInfo & {\n readonly rows: number;\n readonly estimatedBytes: number;\n readonly cookieRows: CookieRowCounts;\n};\n\n/**\n * Reads the meta row and covered range. Unlike {@link getSQLiteChangeLogInfo}\n * this does not scan the log; see {@link readChangeLogBounds}.\n *\n * Call this after reconciliation, which is the only point at which the head is\n * known to be the resume watermark.\n */\nexport function getSQLiteChangeLogStartupInfo(\n changeLog: Database,\n): SQLiteChangeLogStartupInfo {\n const meta = readChangeLogMeta(changeLog);\n const {minWatermark, headWatermark} = readChangeLogBounds(changeLog);\n if (minWatermark === null || headWatermark === null) {\n throw new Error('the SQLite change log must contain its seed transaction');\n }\n return {...meta, minWatermark, headWatermark};\n}\n\n/**\n * Extends {@link getSQLiteChangeLogStartupInfo} with the retained row and\n * estimated byte totals. Computing these scans the entire change-log table, so\n * only call it when the totals are consumed, i.e. when the writer (and thus the\n * observer) is enabled.\n */\nexport function getSQLiteChangeLogInfo(\n changeLog: Database,\n): SQLiteChangeLogInfo {\n const startup = getSQLiteChangeLogStartupInfo(changeLog);\n const aggregate = changeLog\n .prepare(/*sql*/ `\n SELECT count(*) AS \"rows\",\n coalesce(sum(\"estimatedBytes\"), 0) AS \"estimatedBytes\"\n FROM \"${CHANGE_LOG_STREAM_TABLE}\"\n `)\n .get<{rows: number; estimatedBytes: number}>();\n\n return {\n ...startup,\n rows: aggregate.rows,\n estimatedBytes: aggregate.estimatedBytes,\n cookieRows: readCookieRowCounts(changeLog),\n };\n}\n\nexport function logSQLiteChangeLogStartup(\n lc: LogContext,\n file: string,\n info: SQLiteChangeLogStartupInfo,\n): void {\n lc.info?.('SQLite change-log startup', {\n sqliteChangeLog: {\n file,\n epoch: info.epoch,\n generation: info.generation,\n replicaID: info.replicaID,\n schemaVersion: info.schemaVersion,\n seedWatermark: info.seedWatermark,\n seededAtMs: info.seededAtMs,\n minWatermark: info.minWatermark,\n headWatermark: info.headWatermark,\n },\n });\n}\n\n/**\n * The on-disk footprint of a SQLite database: its main file plus its `-wal` and\n * `-wal2` sidecars, whichever exist. `-shm` is excluded — it is a\n * shared-memory index rather than retained bytes.\n *\n * A missing file counts as zero rather than warning. Which sidecars exist\n * depends on the journal mode, and the change-log database is absent entirely\n * until the writer creates it.\n */\nexport async function sqliteFileBytes(\n lc: LogContext,\n file: string,\n): Promise<number> {\n const sizes = await Promise.all(\n [file, `${file}-wal`, `${file}-wal2`].map(async path => {\n try {\n return (await stat(path)).size;\n } catch (e) {\n if ((e as NodeJS.ErrnoException).code !== 'ENOENT') {\n lc.warn?.(`unable to stat ${path} for size metrics`, e);\n }\n return 0;\n }\n }),\n );\n return sizes.reduce((total, size) => total + size, 0);\n}\n\n/** What the writer reports back for a committed transaction. */\nexport type ChangeLogCommit = {\n readonly watermark: string;\n readonly stats: ChangeLogStreamTransactionStats;\n /**\n * Appending the commit row and committing the log's transaction. This is the\n * cost that sits on the forward path, once per upstream transaction.\n */\n readonly logCommitMs: number;\n};\n\nexport type SQLiteChangeLogObservabilityState = {\n readonly receivedHead: string;\n readonly sqliteHead: string;\n readonly headLag: number | undefined;\n readonly rows: number;\n readonly estimatedBytes: number;\n readonly cookieRows: CookieRowCounts;\n readonly cookieMutations: number;\n readonly rollbacks: number;\n readonly invariantFailures: number;\n};\n\nconst TRANSACTION_ROW_BUCKETS = [2, 3, 5, 10, 25, 50, 100, 250, 1000, 5000];\n\n/**\n * Records writer metrics in the change-streamer process. State changes only\n * after the corresponding write succeeds, except receivedHead, which advances\n * when a commit message arrives so that transient lag behind the log is\n * observable.\n */\nexport class SQLiteChangeLogObserver {\n readonly #lc: LogContext;\n readonly #messageProcessing = getOrCreateLatencyHistogram(\n 'replica',\n 'sqlite_change_log.message_processing_duration',\n 'Sampled time to write a replication message to the SQLite change log.',\n );\n // The commit that sits on the forward path. There is no second commit to\n // order against any more: the replica's belongs to a subscriber downstream of\n // this loop, so `sqlite_change_log.replica_commit_duration` and the phantom\n // window it measured are gone. Sampled failed commits are still timed by\n // `message_processing_duration` keyed `tag=\"commit\"`.\n readonly #logCommitDuration = getOrCreateLatencyHistogram(\n 'replica',\n 'sqlite_change_log.log_commit_duration',\n 'Time to append the commit row to the SQLite change log and commit its ' +\n 'transaction. This is on the forward path: it precedes the forward of ' +\n \"that transaction's commit message.\",\n );\n readonly #transactionRows = getOrCreateValueHistogram(\n 'replica',\n 'sqlite_change_log.transaction_rows',\n {\n description: 'Rows stored per committed SQLite change-log transaction.',\n unit: '{row}',\n bucketBoundaries: TRANSACTION_ROW_BUCKETS,\n },\n );\n readonly #rollbackCounter = getOrCreateCounter(\n 'replica',\n 'sqlite_change_log.rollbacks',\n 'SQLite change-log transactions rolled back before commit.',\n );\n readonly #invariantFailureCounter = getOrCreateCounter(\n 'replica',\n 'sqlite_change_log.invariant_failures',\n 'Detected SQLite change-log writer invariant failures.',\n );\n // Near zero at steady state: cookie state only moves on schema changes.\n readonly #cookieMutationCounter = getOrCreateCounter(\n 'replica',\n 'sqlite_change_log.cookie_mutations',\n 'Change-log cookie mutations folded from schema changes, by operation.',\n );\n\n #receivedHead: string;\n #sqliteHead: string;\n #rows: number;\n #estimatedBytes: number;\n #cookieRows: CookieRowCounts;\n #cookieMutations = 0;\n #transactionWatermark: string | undefined;\n #rollbacks = 0;\n #invariantFailures = 0;\n\n constructor(lc: LogContext, info: SQLiteChangeLogInfo) {\n this.#lc = lc.withContext('component', 'sqlite-change-log-observer');\n // Reconciliation has just put the head at the resume watermark, which is\n // also the point the stream is about to be received from.\n this.#receivedHead = info.headWatermark;\n this.#sqliteHead = info.headWatermark;\n this.#rows = info.rows;\n this.#estimatedBytes = info.estimatedBytes;\n this.#cookieRows = info.cookieRows;\n\n getOrCreateGauge(\n 'replica',\n 'sqlite_change_log.rows',\n 'Rows retained in the SQLite change log.',\n ).addCallback(result => result.observe(this.#rows));\n // Nonzero with no backfill in flight is a leaked cookie, i.e. a backfill\n // that will be re-requested forever.\n getOrCreateGauge(\n 'replica',\n 'sqlite_change_log.cookie_rows',\n 'Cookie rows retained in the SQLite change log, by cookie table.',\n ).addCallback(result => {\n result.observe(this.#cookieRows.tableMetadata, {table: 'tableMetadata'});\n result.observe(this.#cookieRows.backfilling, {table: 'backfilling'});\n });\n getOrCreateGauge('replica', 'sqlite_change_log.retained_bytes', {\n description:\n 'Estimated UTF-8 payload bytes retained in the SQLite change log.',\n unit: 'By',\n }).addCallback(result => result.observe(this.#estimatedBytes));\n getOrCreateGauge(\n 'replica',\n 'sqlite_change_log.head',\n 'SQLite change-log head converted from its lexicographic watermark.',\n ).addCallback(result => {\n const head = watermarkValue(this.#sqliteHead);\n if (head !== undefined) {\n result.observe(head);\n }\n });\n getOrCreateGauge(\n 'replica',\n 'sqlite_change_log.head_lag',\n 'Distance from the latest received commit to the SQLite change-log ' +\n 'head. The log commits before the forward, so this is zero except ' +\n 'within a transaction.',\n ).addCallback(result => {\n const lag = watermarkDistance(this.#receivedHead, this.#sqliteHead);\n if (lag !== undefined) {\n result.observe(lag);\n }\n });\n }\n\n /**\n * Called as each message arrives, before it is written, so that the head\n * lag includes a transaction that is in flight.\n */\n messageReceived(data: ChangeStreamData): void {\n if (data[0] === 'commit') {\n this.#receivedHead = data[2].watermark;\n }\n }\n\n /** Called after the message has been written to the log. */\n messageProcessed(\n data: ChangeStreamData,\n commit: ChangeLogCommit | null,\n durationMs: number | undefined,\n ): void {\n const tag = data[1].tag;\n if (durationMs !== undefined) {\n this.#messageProcessing.recordMs(durationMs, {tag, outcome: 'success'});\n }\n\n if (data[0] === 'begin') {\n if (this.#transactionWatermark !== undefined) {\n this.#invariantFailure('SQLite change-log transaction already open', {\n openWatermark: this.#transactionWatermark,\n receivedWatermark: data[2].commitWatermark,\n });\n }\n this.#transactionWatermark = data[2].commitWatermark;\n return;\n }\n\n if (tag === 'rollback') {\n this.#recordRollback('upstream');\n this.#transactionWatermark = undefined;\n return;\n }\n\n if (data[0] !== 'commit') {\n return;\n }\n\n const watermark = data[2].watermark;\n if (commit !== null) {\n this.#logCommitDuration.recordMs(commit.logCommitMs);\n }\n if (this.#transactionWatermark !== watermark) {\n this.#invariantFailure(\n 'SQLite change-log commit does not match the observed begin',\n {openWatermark: this.#transactionWatermark, commitWatermark: watermark},\n );\n }\n if (commit === null) {\n this.#invariantFailure(\n 'SQLite change-log commit result is missing writer statistics',\n {commitWatermark: watermark},\n );\n } else {\n if (commit.watermark !== watermark) {\n this.#invariantFailure(\n 'SQLite change-log commit result has an unexpected watermark',\n {commitWatermark: watermark, resultWatermark: commit.watermark},\n );\n }\n this.#rows += commit.stats.rows;\n this.#estimatedBytes += commit.stats.estimatedBytes;\n this.#transactionRows.record(commit.stats.rows);\n }\n if (watermark < this.#sqliteHead) {\n this.#invariantFailure('SQLite change-log head regressed', {\n previousHead: this.#sqliteHead,\n commitWatermark: watermark,\n });\n }\n this.#sqliteHead = watermark;\n this.#transactionWatermark = undefined;\n }\n\n messageFailed(\n data: ChangeStreamData,\n error: unknown,\n durationMs: number | undefined,\n ): void {\n const tag = data[1].tag;\n if (durationMs !== undefined) {\n this.#messageProcessing.recordMs(durationMs, {tag, outcome: 'error'});\n }\n if (\n error instanceof Error &&\n error.name === 'ChangeLogStreamInvariantError'\n ) {\n this.#invariantFailure(error.message);\n }\n if (this.#transactionWatermark !== undefined || data[0] === 'begin') {\n this.#recordRollback('processing-error');\n }\n this.#transactionWatermark = undefined;\n }\n\n /**\n * A committed transaction folded schema changes into the cookie jar. Reported\n * separately from {@link messageProcessed} because it costs a read of the\n * cookie tables, which is only worth taking when they actually moved.\n */\n cookiesMutated(ops: readonly CookieOpTag[], rows: CookieRowCounts): void {\n for (const op of ops) {\n this.#cookieMutations++;\n this.#cookieMutationCounter.add(1, {op});\n }\n this.#cookieRows = rows;\n }\n\n /**\n * A missed truncate-above surfaces as a constraint violation on the writer's\n * plain `INSERT`, which the fail-soft policy would otherwise absorb quietly.\n * Classifying it as an invariant failure is what keeps a reconciliation bug\n * from looking like a lost cache.\n */\n invariantFailure(message: string, details?: Record<string, unknown>): void {\n this.#invariantFailure(message, details);\n }\n\n /** The source interrupted the stream mid-transaction. */\n abort(): void {\n if (this.#transactionWatermark !== undefined) {\n this.#recordRollback('source-interruption');\n this.#transactionWatermark = undefined;\n }\n }\n\n /** Reconciliation moved the head, so the observer's totals are restated. */\n reconciled(info: SQLiteChangeLogInfo): void {\n this.#receivedHead = info.headWatermark;\n this.#sqliteHead = info.headWatermark;\n this.#rows = info.rows;\n this.#estimatedBytes = info.estimatedBytes;\n this.#cookieRows = info.cookieRows;\n this.#transactionWatermark = undefined;\n }\n\n state(): SQLiteChangeLogObservabilityState {\n return {\n receivedHead: this.#receivedHead,\n sqliteHead: this.#sqliteHead,\n headLag: watermarkDistance(this.#receivedHead, this.#sqliteHead),\n rows: this.#rows,\n estimatedBytes: this.#estimatedBytes,\n cookieRows: this.#cookieRows,\n cookieMutations: this.#cookieMutations,\n rollbacks: this.#rollbacks,\n invariantFailures: this.#invariantFailures,\n };\n }\n\n #recordRollback(\n reason: 'upstream' | 'processing-error' | 'source-interruption',\n ) {\n this.#rollbacks++;\n this.#rollbackCounter.add(1, {reason});\n }\n\n #invariantFailure(message: string, details?: Record<string, unknown>) {\n this.#invariantFailures++;\n this.#invariantFailureCounter.add(1);\n this.#lc.error?.(message, details);\n }\n}\n\nfunction watermarkValue(watermark: string): number | undefined {\n try {\n const value = Number(versionFromLexi(watermark));\n return Number.isFinite(value) ? value : undefined;\n } catch {\n return undefined;\n }\n}\n\nfunction watermarkDistance(\n receivedHead: string,\n sqliteHead: string,\n): number | undefined {\n if (receivedHead <= sqliteHead) {\n return 0;\n }\n try {\n const distance =\n versionFromLexi(receivedHead) - versionFromLexi(sqliteHead);\n const value = Number(distance);\n return Number.isFinite(value) ? value : undefined;\n } catch {\n return undefined;\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;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AkB,CACtC,EAAE,EAAE,UAAU,EACd,MAAM,EAAE,UAAU,EAClB,GAAG,EAAE,cAAc,EACnB,GAAG,EAAE,YAAY,iBA8DlB"}
1
+ {"version":3,"file":"statz.d.ts","sourceRoot":"","sources":["../../../../../zero-cache/src/services/statz.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAC,UAAU,EAAC,MAAM,kBAAkB,CAAC;AACjD,OAAO,KAAK,EAAC,YAAY,EAAE,cAAc,EAAC,MAAM,SAAS,CAAC;AAG1D,OAAO,KAAK,EAAC,oBAAoB,IAAI,UAAU,EAAC,MAAM,wBAAwB,CAAC;AAiT/E;;;;;;;;;GASG;AACH,wBAAsB,kBAAkB,CACtC,EAAE,EAAE,UAAU,EACd,MAAM,EAAE,UAAU,EAClB,GAAG,EAAE,cAAc,EACnB,GAAG,EAAE,YAAY,iBA+DlB"}
@@ -224,7 +224,7 @@ async function handleStatzRequest(lc, config, req, res) {
224
224
  const statsFns = {
225
225
  upstream: () => upstreamStats(lc, config),
226
226
  cvr: () => cvrStats(lc, config),
227
- ...config.changeStreamer.pgChangeLogEnabled ? { changeLog: () => changeLogStats(lc, config) } : {},
227
+ ...config.upstream.pgHighAvailabilityReplication ? {} : { changeLog: () => changeLogStats(lc, config) },
228
228
  replica: () => replicaStats(lc, config),
229
229
  replication: () => replicationStats(lc, config),
230
230
  os: () => osStats()
@@ -1 +1 @@
1
- {"version":3,"file":"statz.js","names":[],"sources":["../../../../../zero-cache/src/services/statz.ts"],"sourcesContent":["import fs from 'fs';\nimport os from 'os';\nimport type {LogContext} from '@rocicorp/logger';\nimport type {FastifyReply, FastifyRequest} from 'fastify';\nimport {BigIntJSON} from '../../../shared/src/bigint-json.ts';\nimport {Database} from '../../../zqlite/src/db.ts';\nimport type {NormalizedZeroConfig as ZeroConfig} from '../config/normalize.ts';\nimport {StatementRunner} from '../db/statements.ts';\nimport {pgClient} from '../types/pg.ts';\nimport {getShardID, upstreamSchema} from '../types/shards.ts';\nimport {authorizeAdminRequest} from './admin-auth.ts';\nimport {fromStateVersionString} from './change-source/pg/lsn.ts';\nimport {getReplicationState} from './replicator/schema/replication-state.ts';\n\nasync function upstreamStats(lc: LogContext, config: ZeroConfig) {\n const schema = upstreamSchema(getShardID(config));\n const sql = pgClient(lc, config.upstream.db, 'statz-upstream');\n try {\n return await getPgStats([\n [\n 'numReplicas',\n sql`SELECT COUNT(*) as \"c\" FROM ${sql(schema)}.\"replicas\"`,\n ],\n [\n 'numClientsWithMutations',\n sql`SELECT COUNT(*) as \"c\" FROM ${sql(schema)}.\"clients\"`,\n ],\n [\n 'numMutationsProcessed',\n sql`SELECT SUM(\"lastMutationID\") as \"c\" FROM ${sql(schema)}.\"clients\"`,\n ],\n ]);\n } finally {\n await sql.end();\n }\n}\n\nasync function cvrStats(lc: LogContext, config: ZeroConfig) {\n const schema = upstreamSchema(getShardID(config)) + '/cvr';\n const sql = pgClient(lc, config.cvr.db, 'statz-cvr');\n\n function numQueriesPerClientGroup(\n active: boolean,\n ): ReturnType<ReturnType<typeof pgClient>> {\n const filter = active\n ? sql`WHERE \"inactivatedAt\" IS NULL AND deleted = false`\n : sql`WHERE \"inactivatedAt\" IS NOT NULL AND (\"inactivatedAt\" + \"ttl\") > NOW()`;\n return sql`WITH\n group_counts AS (\n SELECT\n \"clientGroupID\",\n COUNT(*) AS num_queries\n FROM ${sql(schema)}.\"desires\"\n ${filter}\n GROUP BY \"clientGroupID\"\n ),\n -- Count distinct clientIDs per clientGroupID\n client_per_group_counts AS (\n SELECT\n \"clientGroupID\",\n COUNT(DISTINCT \"clientID\") AS num_clients\n FROM ${sql(schema)}.\"desires\"\n ${filter}\n GROUP BY \"clientGroupID\"\n )\n -- Combine all the information\n SELECT\n g.\"clientGroupID\",\n cpg.num_clients,\n g.num_queries\n FROM group_counts g\n JOIN client_per_group_counts cpg ON g.\"clientGroupID\" = cpg.\"clientGroupID\"\n ORDER BY g.num_queries DESC;`;\n }\n\n try {\n return await getPgStats([\n [\n 'totalNumQueries',\n sql`SELECT COUNT(*) as \"c\" FROM ${sql(schema)}.\"desires\"`,\n ],\n [\n 'numUniqueQueryHashes',\n sql`SELECT COUNT(DISTINCT \"queryHash\") as \"c\" FROM ${sql(\n schema,\n )}.\"desires\"`,\n ],\n [\n 'numActiveQueries',\n sql`SELECT COUNT(*) as \"c\" FROM ${sql(schema)}.\"desires\" WHERE \"inactivatedAt\" IS NULL AND \"deleted\" = false`,\n ],\n [\n 'numInactiveQueries',\n sql`SELECT COUNT(*) as \"c\" FROM ${sql(schema)}.\"desires\" WHERE \"inactivatedAt\" IS NOT NULL AND (\"inactivatedAt\" + \"ttl\") > NOW()`,\n ],\n [\n 'numDeletedQueries',\n sql`SELECT COUNT(*) as \"c\" FROM ${sql(schema)}.\"desires\" WHERE \"deleted\" = true`,\n ],\n [\n 'freshQueriesPercentiles',\n sql`WITH client_group_counts AS (\n -- Count inactive desires per clientGroupID\n SELECT\n \"clientGroupID\",\n COUNT(*) AS fresh_count\n FROM ${sql(schema)}.\"desires\"\n WHERE\n (\"inactivatedAt\" IS NOT NULL\n AND (\"inactivatedAt\" + \"ttl\") > NOW()) OR (\"inactivatedAt\" IS NULL\n AND deleted = false)\n GROUP BY \"clientGroupID\"\n )\n\n SELECT\n percentile_cont(0.50) WITHIN GROUP (ORDER BY fresh_count) AS \"p50\",\n percentile_cont(0.75) WITHIN GROUP (ORDER BY fresh_count) AS \"p75\",\n percentile_cont(0.90) WITHIN GROUP (ORDER BY fresh_count) AS \"p90\",\n percentile_cont(0.95) WITHIN GROUP (ORDER BY fresh_count) AS \"p95\",\n percentile_cont(0.99) WITHIN GROUP (ORDER BY fresh_count) AS \"p99\",\n MIN(fresh_count) AS \"min\",\n MAX(fresh_count) AS \"max\",\n AVG(fresh_count) AS \"avg\"\n FROM client_group_counts;`,\n ],\n [\n 'rowsPerClientGroupPercentiles',\n sql`WITH client_group_counts AS (\n -- Count inactive desires per clientGroupID\n SELECT\n \"clientGroupID\",\n COUNT(*) AS row_count\n FROM ${sql(schema)}.\"rows\"\n GROUP BY \"clientGroupID\"\n )\n SELECT\n percentile_cont(0.50) WITHIN GROUP (ORDER BY row_count) AS \"p50\",\n percentile_cont(0.75) WITHIN GROUP (ORDER BY row_count) AS \"p75\",\n percentile_cont(0.90) WITHIN GROUP (ORDER BY row_count) AS \"p90\",\n percentile_cont(0.95) WITHIN GROUP (ORDER BY row_count) AS \"p95\",\n percentile_cont(0.99) WITHIN GROUP (ORDER BY row_count) AS \"p99\",\n MIN(row_count) AS \"min\",\n MAX(row_count) AS \"max\",\n AVG(row_count) AS \"avg\"\n FROM client_group_counts;`,\n ],\n [\n // check for AST blowup due to DNF conversion.\n 'astSizes',\n sql`SELECT\n percentile_cont(0.25) WITHIN GROUP (ORDER BY length(\"clientAST\"::text)) AS \"25th_percentile\",\n percentile_cont(0.5) WITHIN GROUP (ORDER BY length(\"clientAST\"::text)) AS \"50th_percentile\",\n percentile_cont(0.75) WITHIN GROUP (ORDER BY length(\"clientAST\"::text)) AS \"75th_percentile\",\n percentile_cont(0.9) WITHIN GROUP (ORDER BY length(\"clientAST\"::text)) AS \"90th_percentile\",\n percentile_cont(0.95) WITHIN GROUP (ORDER BY length(\"clientAST\"::text)) AS \"95th_percentile\",\n percentile_cont(0.99) WITHIN GROUP (ORDER BY length(\"clientAST\"::text)) AS \"99th_percentile\",\n MIN(length(\"clientAST\"::text)) AS \"minimum_length\",\n MAX(length(\"clientAST\"::text)) AS \"maximum_length\",\n AVG(length(\"clientAST\"::text))::integer AS \"average_length\",\n COUNT(*) AS \"total_records\"\n FROM ${sql(schema)}.\"queries\";`,\n ],\n [\n // output the hash of the largest AST\n 'biggestAstHash',\n sql`SELECT \"queryHash\", length(\"clientAST\"::text) AS \"ast_length\"\n FROM ${sql(schema)}.\"queries\"\n ORDER BY length(\"clientAST\"::text) DESC\n LIMIT 1;`,\n ],\n [\n 'totalActiveQueriesPerClientAndClientGroup',\n numQueriesPerClientGroup(true),\n ],\n [\n 'totalInactiveQueriesPerClientAndClientGroup',\n numQueriesPerClientGroup(false),\n ],\n [\n 'totalRowsPerClientGroup',\n sql`SELECT \"clientGroupID\", COUNT(*) as \"c\" FROM ${sql(\n schema,\n )}.\"rows\" GROUP BY \"clientGroupID\" ORDER BY \"c\" DESC`,\n ],\n [\n 'numRowsPerQuery',\n sql`SELECT\n k.key AS \"queryHash\",\n COUNT(*) AS row_count\n FROM ${sql(schema)}.\"rows\" r,\n LATERAL jsonb_each(r.\"refCounts\") k\n GROUP BY k.key\n ORDER BY row_count DESC;`,\n ],\n ] satisfies [\n name: string,\n query: ReturnType<ReturnType<typeof pgClient>>,\n ][]);\n } finally {\n await sql.end();\n }\n}\n\nasync function changeLogStats(lc: LogContext, config: ZeroConfig) {\n const schema = upstreamSchema(getShardID(config)) + '/cdc';\n const sql = pgClient(lc, config.change.db, 'statz-change');\n\n try {\n return await getPgStats([\n [\n 'changeLogSize',\n sql`SELECT COUNT(*) as \"change_log_size\" FROM ${sql(schema)}.\"changeLog\"`,\n ],\n ]);\n } finally {\n await sql.end();\n }\n}\n\n// The replica is opened read-only: /statz is available to the operator\n// password, and must not change the replica. Among other things, a writable\n// connection would run `PRAGMA optimize` when closed.\nfunction replicaStats(lc: LogContext, config: ZeroConfig) {\n const db = new Database(lc, config.replica.file, {readonly: true});\n try {\n return Object.fromEntries([\n ['wal file sizes', walFileSizes(config.replica.file)],\n ['page count', pick(first(db.pragma('PAGE_COUNT')))],\n ['page size', pick(first(db.pragma('PAGE_SIZE')))],\n ['journal mode', pick(first(db.pragma('JOURNAL_MODE')))],\n ['synchronous', pick(first(db.pragma('SYNCHRONOUS')))],\n ['cache size', pick(first(db.pragma('CACHE_SIZE')))],\n ['auto vacuum', pick(first(db.pragma('AUTO_VACUUM')))],\n ['freelist count', pick(first(db.pragma('FREELIST_COUNT')))],\n ['wal autocheckpoint', pick(first(db.pragma('WAL_AUTOCHECKPOINT')))],\n ['db file stats', fs.statSync(config.replica.file)],\n ] as const);\n } finally {\n db.close();\n }\n}\n\nfunction replicationStats(lc: LogContext, config: ZeroConfig) {\n const db = new Database(lc, config.replica.file, {readonly: true});\n try {\n return getReplicationStats(db);\n } finally {\n db.close();\n }\n}\n\n/**\n * The sizes of the replica's WAL files, by suffix, read from the filesystem.\n * `PRAGMA wal_checkpoint` would report the WAL's frame counts, but it runs a\n * checkpoint to do so, and fails on a read-only connection in WAL mode.\n */\nfunction walFileSizes(file: string): Record<string, number> {\n const sizes: Record<string, number> = {};\n // `-wal` is used in WAL mode, and both files in WAL2 mode.\n for (const suffix of ['-wal', '-wal2']) {\n const stats = fs.statSync(file + suffix, {throwIfNoEntry: false});\n if (stats) {\n sizes[suffix] = stats.size;\n }\n }\n return sizes;\n}\n\nfunction getReplicationStats(db: Database) {\n const {stateVersion} = getReplicationState(new StatementRunner(db));\n const lsn = fromStateVersionString(stateVersion);\n return {lsn};\n}\n\nfunction osStats() {\n return Object.fromEntries([\n ['load avg', os.loadavg()],\n ['uptime', os.uptime()],\n ['total mem', os.totalmem()],\n ['free mem', os.freemem()],\n ['cpus', os.cpus().length],\n ['available parallelism', os.availableParallelism()],\n ['platform', os.platform()],\n ['arch', os.arch()],\n ['release', os.release()],\n ] as const);\n}\n\nasync function getPgStats(\n pendingQueries: [\n name: string,\n query: ReturnType<ReturnType<typeof pgClient>>,\n ][],\n) {\n const results = await Promise.all(\n pendingQueries.map(async ([name, query]) => [name, await query] as const),\n );\n return Object.fromEntries(results);\n}\n\ntype StatsObject = Record<string, unknown>;\n\nfunction printStats(group: string, statsObject: StatsObject): string {\n const lines: string[] = ['\\n' + header(group)];\n for (const [name, result] of Object.entries(statsObject)) {\n lines.push('\\n' + name + ': ' + BigIntJSON.stringify(result, null, 2));\n }\n lines.push('\\n');\n return lines.join('');\n}\n\n/**\n * Serves counts and sizes. This is available to the operator password as well\n * as the admin password (see `--operator-password`), so it must never return\n * application data: no row values, query ASTs or query arguments.\n *\n * HTTP query parameters:\n * * `group`: restricts the groups for which stats are computed\n * * `format=json`: returns the stats as a JSON object\n * * `pretty`: formats the JSON object with indentation\n */\nexport async function handleStatzRequest(\n lc: LogContext,\n config: ZeroConfig,\n req: FastifyRequest,\n res: FastifyReply,\n) {\n if (\n authorizeAdminRequest(\n lc,\n config,\n req,\n res,\n 'Statz Protected Area',\n 'operator',\n ) === undefined\n ) {\n return;\n }\n\n const statsFns: Record<string, () => Promise<StatsObject> | StatsObject> = {\n upstream: () => upstreamStats(lc, config),\n cvr: () => cvrStats(lc, config),\n // The PG change log (and thus the change DB) is not used when disabled.\n ...(config.changeStreamer.pgChangeLogEnabled\n ? {changeLog: () => changeLogStats(lc, config)}\n : {}),\n replica: () => replicaStats(lc, config),\n replication: () => replicationStats(lc, config),\n os: () => osStats(),\n };\n\n async function computeStats(group: string): Promise<[string, StatsObject]> {\n try {\n return [group, await statsFns[group]()];\n } catch (e) {\n lc.error?.(`error computing ${group} stats`, e);\n return [group, {error: String(e)}];\n }\n }\n\n const query = req.query as Record<string, unknown>;\n const groups =\n typeof query.group === 'string'\n ? query.group.split(',')\n : Array.isArray(query.group)\n ? query.group\n : undefined;\n\n const stats = await Promise.all(\n groups\n ? groups.filter(g => g in statsFns).map(computeStats)\n : Object.keys(statsFns).map(computeStats),\n );\n\n if (query.format === 'json') {\n const indent = query.pretty !== undefined ? 2 : undefined;\n await res\n .header('Content-Type', 'application/json')\n .send(BigIntJSON.stringify(Object.fromEntries(stats), null, indent));\n return;\n } else {\n const body = stats\n .map(([group, statsObject]) => printStats(group, statsObject))\n .join('');\n await res.header('Content-Type', 'text/plain; charset=utf-8').send(body);\n }\n}\n\nfunction first(x: object[]): object {\n return x[0];\n}\n\nfunction pick(x: object): unknown {\n return Object.values(x)[0];\n}\n\nfunction header(name: string): string {\n return `=== ${name} ===\\n`;\n}\n"],"mappings":";;;;;;;;;;;AAcA,eAAe,cAAc,IAAgB,QAAoB;CAC/D,MAAM,SAAS,eAAe,WAAW,MAAM,CAAC;CAChD,MAAM,MAAM,SAAS,IAAI,OAAO,SAAS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IAAY,IAAI,KAAA;EAChD,MAAM,IACH,OAAO,gBAAgB,kBAAkB,CAAC,CAC1C,KAAK,WAAW,UAAU,OAAO,YAAY,KAAK,GAAG,MAAM,MAAM,CAAC;EACrE;CACF,OAAO;EACL,MAAM,OAAO,MACV,KAAK,CAAC,OAAO,iBAAiB,WAAW,OAAO,WAAW,CAAC,CAAC,CAC7D,KAAK,EAAE;EACV,MAAM,IAAI,OAAO,gBAAgB,2BAA2B,CAAC,CAAC,KAAK,IAAI;CACzE;AACF;AAEA,SAAS,MAAM,GAAqB;CAClC,OAAO,EAAE;AACX;AAEA,SAAS,KAAK,GAAoB;CAChC,OAAO,OAAO,OAAO,CAAC,CAAC,CAAC;AAC1B;AAEA,SAAS,OAAO,MAAsB;CACpC,OAAO,OAAO,KAAK;AACrB"}
1
+ {"version":3,"file":"statz.js","names":[],"sources":["../../../../../zero-cache/src/services/statz.ts"],"sourcesContent":["import fs from 'fs';\nimport os from 'os';\nimport type {LogContext} from '@rocicorp/logger';\nimport type {FastifyReply, FastifyRequest} from 'fastify';\nimport {BigIntJSON} from '../../../shared/src/bigint-json.ts';\nimport {Database} from '../../../zqlite/src/db.ts';\nimport type {NormalizedZeroConfig as ZeroConfig} from '../config/normalize.ts';\nimport {StatementRunner} from '../db/statements.ts';\nimport {pgClient} from '../types/pg.ts';\nimport {getShardID, upstreamSchema} from '../types/shards.ts';\nimport {authorizeAdminRequest} from './admin-auth.ts';\nimport {fromStateVersionString} from './change-source/pg/lsn.ts';\nimport {getReplicationState} from './replicator/schema/replication-state.ts';\n\nasync function upstreamStats(lc: LogContext, config: ZeroConfig) {\n const schema = upstreamSchema(getShardID(config));\n const sql = pgClient(lc, config.upstream.db, 'statz-upstream');\n try {\n return await getPgStats([\n [\n 'numReplicas',\n sql`SELECT COUNT(*) as \"c\" FROM ${sql(schema)}.\"replicas\"`,\n ],\n [\n 'numClientsWithMutations',\n sql`SELECT COUNT(*) as \"c\" FROM ${sql(schema)}.\"clients\"`,\n ],\n [\n 'numMutationsProcessed',\n sql`SELECT SUM(\"lastMutationID\") as \"c\" FROM ${sql(schema)}.\"clients\"`,\n ],\n ]);\n } finally {\n await sql.end();\n }\n}\n\nasync function cvrStats(lc: LogContext, config: ZeroConfig) {\n const schema = upstreamSchema(getShardID(config)) + '/cvr';\n const sql = pgClient(lc, config.cvr.db, 'statz-cvr');\n\n function numQueriesPerClientGroup(\n active: boolean,\n ): ReturnType<ReturnType<typeof pgClient>> {\n const filter = active\n ? sql`WHERE \"inactivatedAt\" IS NULL AND deleted = false`\n : sql`WHERE \"inactivatedAt\" IS NOT NULL AND (\"inactivatedAt\" + \"ttl\") > NOW()`;\n return sql`WITH\n group_counts AS (\n SELECT\n \"clientGroupID\",\n COUNT(*) AS num_queries\n FROM ${sql(schema)}.\"desires\"\n ${filter}\n GROUP BY \"clientGroupID\"\n ),\n -- Count distinct clientIDs per clientGroupID\n client_per_group_counts AS (\n SELECT\n \"clientGroupID\",\n COUNT(DISTINCT \"clientID\") AS num_clients\n FROM ${sql(schema)}.\"desires\"\n ${filter}\n GROUP BY \"clientGroupID\"\n )\n -- Combine all the information\n SELECT\n g.\"clientGroupID\",\n cpg.num_clients,\n g.num_queries\n FROM group_counts g\n JOIN client_per_group_counts cpg ON g.\"clientGroupID\" = cpg.\"clientGroupID\"\n ORDER BY g.num_queries DESC;`;\n }\n\n try {\n return await getPgStats([\n [\n 'totalNumQueries',\n sql`SELECT COUNT(*) as \"c\" FROM ${sql(schema)}.\"desires\"`,\n ],\n [\n 'numUniqueQueryHashes',\n sql`SELECT COUNT(DISTINCT \"queryHash\") as \"c\" FROM ${sql(\n schema,\n )}.\"desires\"`,\n ],\n [\n 'numActiveQueries',\n sql`SELECT COUNT(*) as \"c\" FROM ${sql(schema)}.\"desires\" WHERE \"inactivatedAt\" IS NULL AND \"deleted\" = false`,\n ],\n [\n 'numInactiveQueries',\n sql`SELECT COUNT(*) as \"c\" FROM ${sql(schema)}.\"desires\" WHERE \"inactivatedAt\" IS NOT NULL AND (\"inactivatedAt\" + \"ttl\") > NOW()`,\n ],\n [\n 'numDeletedQueries',\n sql`SELECT COUNT(*) as \"c\" FROM ${sql(schema)}.\"desires\" WHERE \"deleted\" = true`,\n ],\n [\n 'freshQueriesPercentiles',\n sql`WITH client_group_counts AS (\n -- Count inactive desires per clientGroupID\n SELECT\n \"clientGroupID\",\n COUNT(*) AS fresh_count\n FROM ${sql(schema)}.\"desires\"\n WHERE\n (\"inactivatedAt\" IS NOT NULL\n AND (\"inactivatedAt\" + \"ttl\") > NOW()) OR (\"inactivatedAt\" IS NULL\n AND deleted = false)\n GROUP BY \"clientGroupID\"\n )\n\n SELECT\n percentile_cont(0.50) WITHIN GROUP (ORDER BY fresh_count) AS \"p50\",\n percentile_cont(0.75) WITHIN GROUP (ORDER BY fresh_count) AS \"p75\",\n percentile_cont(0.90) WITHIN GROUP (ORDER BY fresh_count) AS \"p90\",\n percentile_cont(0.95) WITHIN GROUP (ORDER BY fresh_count) AS \"p95\",\n percentile_cont(0.99) WITHIN GROUP (ORDER BY fresh_count) AS \"p99\",\n MIN(fresh_count) AS \"min\",\n MAX(fresh_count) AS \"max\",\n AVG(fresh_count) AS \"avg\"\n FROM client_group_counts;`,\n ],\n [\n 'rowsPerClientGroupPercentiles',\n sql`WITH client_group_counts AS (\n -- Count inactive desires per clientGroupID\n SELECT\n \"clientGroupID\",\n COUNT(*) AS row_count\n FROM ${sql(schema)}.\"rows\"\n GROUP BY \"clientGroupID\"\n )\n SELECT\n percentile_cont(0.50) WITHIN GROUP (ORDER BY row_count) AS \"p50\",\n percentile_cont(0.75) WITHIN GROUP (ORDER BY row_count) AS \"p75\",\n percentile_cont(0.90) WITHIN GROUP (ORDER BY row_count) AS \"p90\",\n percentile_cont(0.95) WITHIN GROUP (ORDER BY row_count) AS \"p95\",\n percentile_cont(0.99) WITHIN GROUP (ORDER BY row_count) AS \"p99\",\n MIN(row_count) AS \"min\",\n MAX(row_count) AS \"max\",\n AVG(row_count) AS \"avg\"\n FROM client_group_counts;`,\n ],\n [\n // check for AST blowup due to DNF conversion.\n 'astSizes',\n sql`SELECT\n percentile_cont(0.25) WITHIN GROUP (ORDER BY length(\"clientAST\"::text)) AS \"25th_percentile\",\n percentile_cont(0.5) WITHIN GROUP (ORDER BY length(\"clientAST\"::text)) AS \"50th_percentile\",\n percentile_cont(0.75) WITHIN GROUP (ORDER BY length(\"clientAST\"::text)) AS \"75th_percentile\",\n percentile_cont(0.9) WITHIN GROUP (ORDER BY length(\"clientAST\"::text)) AS \"90th_percentile\",\n percentile_cont(0.95) WITHIN GROUP (ORDER BY length(\"clientAST\"::text)) AS \"95th_percentile\",\n percentile_cont(0.99) WITHIN GROUP (ORDER BY length(\"clientAST\"::text)) AS \"99th_percentile\",\n MIN(length(\"clientAST\"::text)) AS \"minimum_length\",\n MAX(length(\"clientAST\"::text)) AS \"maximum_length\",\n AVG(length(\"clientAST\"::text))::integer AS \"average_length\",\n COUNT(*) AS \"total_records\"\n FROM ${sql(schema)}.\"queries\";`,\n ],\n [\n // output the hash of the largest AST\n 'biggestAstHash',\n sql`SELECT \"queryHash\", length(\"clientAST\"::text) AS \"ast_length\"\n FROM ${sql(schema)}.\"queries\"\n ORDER BY length(\"clientAST\"::text) DESC\n LIMIT 1;`,\n ],\n [\n 'totalActiveQueriesPerClientAndClientGroup',\n numQueriesPerClientGroup(true),\n ],\n [\n 'totalInactiveQueriesPerClientAndClientGroup',\n numQueriesPerClientGroup(false),\n ],\n [\n 'totalRowsPerClientGroup',\n sql`SELECT \"clientGroupID\", COUNT(*) as \"c\" FROM ${sql(\n schema,\n )}.\"rows\" GROUP BY \"clientGroupID\" ORDER BY \"c\" DESC`,\n ],\n [\n 'numRowsPerQuery',\n sql`SELECT\n k.key AS \"queryHash\",\n COUNT(*) AS row_count\n FROM ${sql(schema)}.\"rows\" r,\n LATERAL jsonb_each(r.\"refCounts\") k\n GROUP BY k.key\n ORDER BY row_count DESC;`,\n ],\n ] satisfies [\n name: string,\n query: ReturnType<ReturnType<typeof pgClient>>,\n ][]);\n } finally {\n await sql.end();\n }\n}\n\nasync function changeLogStats(lc: LogContext, config: ZeroConfig) {\n const schema = upstreamSchema(getShardID(config)) + '/cdc';\n const sql = pgClient(lc, config.change.db, 'statz-change');\n\n try {\n return await getPgStats([\n [\n 'changeLogSize',\n sql`SELECT COUNT(*) as \"change_log_size\" FROM ${sql(schema)}.\"changeLog\"`,\n ],\n ]);\n } finally {\n await sql.end();\n }\n}\n\n// The replica is opened read-only: /statz is available to the operator\n// password, and must not change the replica. Among other things, a writable\n// connection would run `PRAGMA optimize` when closed.\nfunction replicaStats(lc: LogContext, config: ZeroConfig) {\n const db = new Database(lc, config.replica.file, {readonly: true});\n try {\n return Object.fromEntries([\n ['wal file sizes', walFileSizes(config.replica.file)],\n ['page count', pick(first(db.pragma('PAGE_COUNT')))],\n ['page size', pick(first(db.pragma('PAGE_SIZE')))],\n ['journal mode', pick(first(db.pragma('JOURNAL_MODE')))],\n ['synchronous', pick(first(db.pragma('SYNCHRONOUS')))],\n ['cache size', pick(first(db.pragma('CACHE_SIZE')))],\n ['auto vacuum', pick(first(db.pragma('AUTO_VACUUM')))],\n ['freelist count', pick(first(db.pragma('FREELIST_COUNT')))],\n ['wal autocheckpoint', pick(first(db.pragma('WAL_AUTOCHECKPOINT')))],\n ['db file stats', fs.statSync(config.replica.file)],\n ] as const);\n } finally {\n db.close();\n }\n}\n\nfunction replicationStats(lc: LogContext, config: ZeroConfig) {\n const db = new Database(lc, config.replica.file, {readonly: true});\n try {\n return getReplicationStats(db);\n } finally {\n db.close();\n }\n}\n\n/**\n * The sizes of the replica's WAL files, by suffix, read from the filesystem.\n * `PRAGMA wal_checkpoint` would report the WAL's frame counts, but it runs a\n * checkpoint to do so, and fails on a read-only connection in WAL mode.\n */\nfunction walFileSizes(file: string): Record<string, number> {\n const sizes: Record<string, number> = {};\n // `-wal` is used in WAL mode, and both files in WAL2 mode.\n for (const suffix of ['-wal', '-wal2']) {\n const stats = fs.statSync(file + suffix, {throwIfNoEntry: false});\n if (stats) {\n sizes[suffix] = stats.size;\n }\n }\n return sizes;\n}\n\nfunction getReplicationStats(db: Database) {\n const {stateVersion} = getReplicationState(new StatementRunner(db));\n const lsn = fromStateVersionString(stateVersion);\n return {lsn};\n}\n\nfunction osStats() {\n return Object.fromEntries([\n ['load avg', os.loadavg()],\n ['uptime', os.uptime()],\n ['total mem', os.totalmem()],\n ['free mem', os.freemem()],\n ['cpus', os.cpus().length],\n ['available parallelism', os.availableParallelism()],\n ['platform', os.platform()],\n ['arch', os.arch()],\n ['release', os.release()],\n ] as const);\n}\n\nasync function getPgStats(\n pendingQueries: [\n name: string,\n query: ReturnType<ReturnType<typeof pgClient>>,\n ][],\n) {\n const results = await Promise.all(\n pendingQueries.map(async ([name, query]) => [name, await query] as const),\n );\n return Object.fromEntries(results);\n}\n\ntype StatsObject = Record<string, unknown>;\n\nfunction printStats(group: string, statsObject: StatsObject): string {\n const lines: string[] = ['\\n' + header(group)];\n for (const [name, result] of Object.entries(statsObject)) {\n lines.push('\\n' + name + ': ' + BigIntJSON.stringify(result, null, 2));\n }\n lines.push('\\n');\n return lines.join('');\n}\n\n/**\n * Serves counts and sizes. This is available to the operator password as well\n * as the admin password (see `--operator-password`), so it must never return\n * application data: no row values, query ASTs or query arguments.\n *\n * HTTP query parameters:\n * * `group`: restricts the groups for which stats are computed\n * * `format=json`: returns the stats as a JSON object\n * * `pretty`: formats the JSON object with indentation\n */\nexport async function handleStatzRequest(\n lc: LogContext,\n config: ZeroConfig,\n req: FastifyRequest,\n res: FastifyReply,\n) {\n if (\n authorizeAdminRequest(\n lc,\n config,\n req,\n res,\n 'Statz Protected Area',\n 'operator',\n ) === undefined\n ) {\n return;\n }\n\n const statsFns: Record<string, () => Promise<StatsObject> | StatsObject> = {\n upstream: () => upstreamStats(lc, config),\n cvr: () => cvrStats(lc, config),\n // The PG change log (and thus the change DB) is not used in\n // high-availability mode.\n ...(config.upstream.pgHighAvailabilityReplication\n ? {}\n : {changeLog: () => changeLogStats(lc, config)}),\n replica: () => replicaStats(lc, config),\n replication: () => replicationStats(lc, config),\n os: () => osStats(),\n };\n\n async function computeStats(group: string): Promise<[string, StatsObject]> {\n try {\n return [group, await statsFns[group]()];\n } catch (e) {\n lc.error?.(`error computing ${group} stats`, e);\n return [group, {error: String(e)}];\n }\n }\n\n const query = req.query as Record<string, unknown>;\n const groups =\n typeof query.group === 'string'\n ? query.group.split(',')\n : Array.isArray(query.group)\n ? query.group\n : undefined;\n\n const stats = await Promise.all(\n groups\n ? groups.filter(g => g in statsFns).map(computeStats)\n : Object.keys(statsFns).map(computeStats),\n );\n\n if (query.format === 'json') {\n const indent = query.pretty !== undefined ? 2 : undefined;\n await res\n .header('Content-Type', 'application/json')\n .send(BigIntJSON.stringify(Object.fromEntries(stats), null, indent));\n return;\n } else {\n const body = stats\n .map(([group, statsObject]) => printStats(group, statsObject))\n .join('');\n await res.header('Content-Type', 'text/plain; charset=utf-8').send(body);\n }\n}\n\nfunction first(x: object[]): object {\n return x[0];\n}\n\nfunction pick(x: object): unknown {\n return Object.values(x)[0];\n}\n\nfunction header(name: string): string {\n return `=== ${name} ===\\n`;\n}\n"],"mappings":";;;;;;;;;;;AAcA,eAAe,cAAc,IAAgB,QAAoB;CAC/D,MAAM,SAAS,eAAe,WAAW,MAAM,CAAC;CAChD,MAAM,MAAM,SAAS,IAAI,OAAO,SAAS,IAAI,gBAAgB;CAC7D,IAAI;EACF,OAAO,MAAM,WAAW;GACtB,CACE,eACA,GAAG,+BAA+B,IAAI,MAAM,EAAE,YAChD;GACA,CACE,2BACA,GAAG,+BAA+B,IAAI,MAAM,EAAE,WAChD;GACA,CACE,yBACA,GAAG,4CAA4C,IAAI,MAAM,EAAE,WAC7D;EACF,CAAC;CACH,UAAU;EACR,MAAM,IAAI,IAAI;CAChB;AACF;AAEA,eAAe,SAAS,IAAgB,QAAoB;CAC1D,MAAM,SAAS,eAAe,WAAW,MAAM,CAAC,IAAI;CACpD,M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E;AACX;AAEA,SAAS,KAAK,GAAoB;CAChC,OAAO,OAAO,OAAO,CAAC,CAAC,CAAC;AAC1B;AAEA,SAAS,OAAO,MAAsB;CACpC,OAAO,OAAO,KAAK;AACrB"}
@@ -136,6 +136,9 @@ async function initViewSyncerSchema(log, db, shard) {
136
136
  } },
137
137
  18: { migrateSchema: async (_, sql) => {
138
138
  await sql`ALTER TABLE ${sql(schema)}.instances ADD COLUMN "pinnedUser" JSONB`;
139
+ } },
140
+ 19: { migrateSchema: async (_, sql) => {
141
+ await sql`ALTER TABLE ${sql(schema)}.instances ALTER COLUMN "ttlClock" SET DEFAULT 0`;
139
142
  } }
140
143
  });
141
144
  }
@@ -1 +1 @@
1
- {"version":3,"file":"init.js","names":[],"sources":["../../../../../../../zero-cache/src/services/view-syncer/schema/init.ts"],"sourcesContent":["import type {LogContext} from '@rocicorp/logger';\nimport type {PendingQuery, Row} from 'postgres';\nimport {\n runSchemaMigrations,\n type IncrementalMigrationMap,\n type Migration,\n} from '../../../db/migration.ts';\nimport type {PostgresDB} from '../../../types/pg.ts';\nimport {cvrSchema, type ShardID} from '../../../types/shards.ts';\nimport {createRowsVersionTable, setupCVRTables} from './cvr.ts';\n\nexport async function initViewSyncerSchema(\n log: LogContext,\n db: PostgresDB,\n shard: ShardID,\n): Promise<void> {\n const schema = cvrSchema(shard);\n\n const setupMigration: Migration = {\n migrateSchema: (lc, tx) => setupCVRTables(lc, tx, shard),\n minSafeVersion: 1,\n };\n\n const migrateV1toV2: Migration = {\n migrateSchema: async (_, tx) => {\n await tx`ALTER TABLE ${tx(schema)}.instances ADD \"replicaVersion\" TEXT`;\n },\n };\n\n const migrateV2ToV3: Migration = {\n migrateSchema: async (_, tx) => {\n await tx.unsafe(createRowsVersionTable(shard));\n },\n\n /** Populates the cvr.rowsVersion table with versions from cvr.instances. */\n migrateData: async (lc, tx) => {\n const pending: PendingQuery<Row[]>[] = [];\n for await (const versions of tx<\n {clientGroupID: string; version: string}[]\n >`\n SELECT \"clientGroupID\", \"version\" FROM ${tx(schema)}.instances`.cursor(\n 5000,\n )) {\n for (const version of versions) {\n pending.push(\n tx`INSERT INTO ${tx(schema)}.\"rowsVersion\" ${tx(version)} \n ON CONFLICT (\"clientGroupID\")\n DO UPDATE SET ${tx(version)}`.execute(),\n );\n }\n }\n lc.info?.(`initializing rowsVersion for ${pending.length} cvrs`);\n await Promise.all(pending);\n },\n };\n\n const migrateV3ToV4: Migration = {\n migrateSchema: async (_, tx) => {\n await tx`ALTER TABLE ${tx(schema)}.instances ADD \"owner\" TEXT`;\n await tx`ALTER TABLE ${tx(schema)}.instances ADD \"grantedAt\" TIMESTAMPTZ`;\n },\n };\n\n const migrateV5ToV6: Migration = {\n migrateSchema: async (_, tx) => {\n await tx`\n ALTER TABLE ${tx(schema)}.\"rows\"\n DROP CONSTRAINT fk_rows_client_group`;\n await tx`\n ALTER TABLE ${tx(schema)}.\"rowsVersion\"\n DROP CONSTRAINT fk_rows_version_client_group`;\n },\n };\n\n const migrateV6ToV7: Migration = {\n migrateSchema: async (_, tx) => {\n await tx`ALTER TABLE ${tx(schema)}.desires ADD \"expiresAt\" TIMESTAMPTZ`;\n await tx`ALTER TABLE ${tx(\n schema,\n )}.desires ADD \"inactivatedAt\" TIMESTAMPTZ`;\n await tx`ALTER TABLE ${tx(schema)}.desires ADD \"ttl\" INTERVAL`;\n\n await tx`CREATE INDEX desires_expires_at ON ${tx(\n schema,\n )}.desires (\"expiresAt\")`;\n await tx`CREATE INDEX desires_inactivated_at ON ${tx(\n schema,\n )}.desires (\"inactivatedAt\")`;\n },\n };\n\n const migrateV7ToV8: Migration = {\n migrateSchema: async (_, tx) => {\n await tx`ALTER TABLE ${tx(\n schema,\n )}.\"desires\" DROP CONSTRAINT fk_desires_client`;\n },\n };\n\n const migrateV8ToV9: Migration = {\n migrateSchema: async (_, tx) => {\n await tx`ALTER TABLE ${tx(schema)}.instances ADD \"clientSchema\" JSONB`;\n },\n };\n\n const migrateV9ToV10: Migration = {\n migrateSchema: async (_, tx) => {\n await tx`ALTER TABLE ${tx(schema)}.queries ADD \"queryName\" TEXT`;\n await tx`ALTER TABLE ${tx(schema)}.queries ADD \"queryArgs\" JSONB`;\n await tx`ALTER TABLE ${tx(schema)}.queries ALTER COLUMN \"clientAST\" DROP NOT NULL`;\n },\n };\n\n const migrateV10ToV11: Migration = {\n migrateSchema: async (_, tx) => {\n await tx`DROP INDEX IF EXISTS ${tx(schema)}.desires_expires_at`;\n await tx`ALTER TABLE ${tx(schema)}.desires DROP COLUMN \"expiresAt\"`;\n await tx`DROP INDEX IF EXISTS ${tx(schema)}.client_patch_version`;\n await tx`ALTER TABLE ${tx(schema)}.clients DROP COLUMN \"patchVersion\"`;\n await tx`ALTER TABLE ${tx(schema)}.clients DROP COLUMN \"deleted\"`;\n },\n };\n\n const migratedV11ToV12: Migration = {\n migrateSchema: async (_, tx) => {\n await tx`ALTER TABLE ${tx(schema)}.queries ALTER COLUMN \"queryArgs\" TYPE JSON USING \"queryArgs\"::JSON`;\n },\n };\n\n const migratedV12ToV13: Migration = {\n migrateSchema: async (_, tx) => {\n await tx`ALTER TABLE ${tx(schema)}.instances ADD COLUMN \"ttlClock\" DOUBLE PRECISION NOT NULL DEFAULT 0`;\n },\n };\n\n const migratedV13ToV14: Migration = {\n migrateSchema: async (_, sql) => {\n await sql`\n CREATE INDEX instances_last_active ON ${sql(schema)}.instances (\"lastActive\");\n `;\n\n // Update / add foreign key constraints to cascade deletes.\n for (const [table, reference] of [\n ['clients', 'instances'],\n ['queries', 'instances'],\n ['rows', 'rowsVersion'],\n ] as [string, string][]) {\n const constraint = sql(`fk_${table}_client_group`);\n await sql`\n ALTER TABLE ${sql(schema)}.${sql(table)} DROP CONSTRAINT IF EXISTS ${constraint}`;\n await sql`\n ALTER TABLE ${sql(schema)}.${sql(table)} ADD CONSTRAINT ${constraint}\n FOREIGN KEY(\"clientGroupID\")\n REFERENCES ${sql(schema)}.${sql(reference)} (\"clientGroupID\")\n ON DELETE CASCADE;\n `;\n }\n },\n };\n\n const migratedV14ToV15: Migration = {\n migrateSchema: async (_, sql) => {\n // Add new columns for storing inactivatedAt and ttl in milliseconds.\n // This avoids postgres.js type conversion issues with TIMESTAMPTZ and INTERVAL.\n await sql`ALTER TABLE ${sql(schema)}.desires \n ADD COLUMN \"inactivatedAtMs\" DOUBLE PRECISION`;\n await sql`ALTER TABLE ${sql(schema)}.desires \n ADD COLUMN \"ttlMs\" DOUBLE PRECISION`;\n },\n // Migrate existing data: convert TIMESTAMPTZ to milliseconds for inactivatedAt\n // and INTERVAL to milliseconds for ttl\n // Note: EXTRACT(EPOCH FROM NULL) returns NULL, so NULL values are preserved\n migrateData: async (lc, sql) => {\n lc.info?.(\n 'Migrating desires.inactivatedAt to inactivatedAtMs and ttl to ttlMs',\n );\n await sql`\n UPDATE ${sql(schema)}.desires\n SET \"inactivatedAtMs\" = EXTRACT(EPOCH FROM \"inactivatedAt\") * 1000,\n \"ttlMs\" = EXTRACT(EPOCH FROM \"ttl\") * 1000\n `;\n },\n };\n\n const migratedV15ToV16: Migration = {\n migrateSchema: async (_, sql) => {\n await sql`ALTER TABLE ${sql(schema)}.instances ADD COLUMN \"profileID\" TEXT`;\n await sql`ALTER TABLE ${sql(schema)}.instances ADD COLUMN \"deleted\" BOOL DEFAULT FALSE`;\n\n // Recreate the instances_last_active index to exclude tombstones\n await sql`\n DROP INDEX IF EXISTS ${sql(schema)}.instances_last_active`;\n await sql`\n CREATE INDEX instances_last_active ON ${sql(schema)}.instances (\"lastActive\")\n WHERE NOT \"deleted\"`;\n await sql`\n CREATE INDEX tombstones_last_active ON ${sql(schema)}.instances (\"lastActive\")\n WHERE \"deleted\"`;\n await sql`\n CREATE INDEX profile_ids_last_active ON ${sql(schema)}.instances (\"lastActive\", \"profileID\")\n WHERE \"profileID\" IS NOT NULL`;\n },\n\n // Backfill profileIDs to the `cg${clientGroupID}`, as is done for\n // client groups from old zero-clients that don't send a profileID.\n migrateData: async (lc, sql) => {\n lc.info?.('Backfilling instance.profileIDs');\n await sql`\n UPDATE ${sql(schema)}.instances\n SET \"profileID\" = 'cg' || \"clientGroupID\"\n WHERE \"profileID\" IS NULL\n `;\n },\n };\n\n const migratedV16ToV17: Migration = {\n migrateSchema: async (_, sql) => {\n await sql`ALTER TABLE ${sql(schema)}.queries ADD COLUMN \"rowSetSignature\" TEXT`;\n },\n };\n\n const migratedV17ToV18: Migration = {\n migrateSchema: async (_, sql) => {\n await sql`ALTER TABLE ${sql(schema)}.instances ADD COLUMN \"pinnedUser\" JSONB`;\n },\n };\n\n const schemaVersionMigrationMap: IncrementalMigrationMap = {\n 2: migrateV1toV2,\n 3: migrateV2ToV3,\n 4: migrateV3ToV4,\n // v5 enables asynchronous row-record flushing, and thus relies on\n // the logic that updates and checks the rowsVersion table in v3.\n 5: {minSafeVersion: 3},\n 6: migrateV5ToV6,\n 7: migrateV6ToV7,\n 8: migrateV7ToV8,\n 9: migrateV8ToV9,\n // v10 adds queryName and queryArgs to the queries table to support\n // custom queries. clientAST is now optional to support migrating\n // off client queries.\n 10: migrateV9ToV10,\n // V11 removes the deprecated queries.\"expiresAt\", clients.\"patchVersion\",\n // clients.\"deleted\" columns.\n 11: migrateV10ToV11,\n 12: migratedV11ToV12,\n // V13 adds instances.\"ttlClock\"\n 13: migratedV12ToV13,\n // V14 adds an index on instances.\"lastActive\" and a FK constraint\n // from rows.\"clientGroupID\" to rowsVersion.\"clientGroupID\" for\n // garbage collection\n 14: migratedV13ToV14,\n // V15 adds desires.\"inactivatedAtTTLClock\" to store TTLClock values\n // directly as DOUBLE PRECISION, avoiding postgres.js TIMESTAMPTZ\n // type conversion issues\n 15: migratedV14ToV15,\n // V16 adds instances.\"profileID\" and a corresponding index for estimating\n // active user counts more accurately for apps that use memstore.\n 16: migratedV15ToV16,\n // V17 adds queries.\"rowSetSignature\" — XOR'd hash of row IDs attached to\n // each query, used to detect drift on re-hydration of queries containing\n // the Cap operator.\n 17: migratedV16ToV17,\n // V18 adds instances.\"pinnedUser\", the user of the client group's first\n // validated connection, so that the group stays pinned to that user\n // across view-syncer restarts. NULL for existing groups until their next\n // validated connection.\n 18: migratedV17ToV18,\n };\n\n await runSchemaMigrations(\n log,\n 'view-syncer',\n cvrSchema(shard),\n db,\n setupMigration,\n schemaVersionMigrationMap,\n );\n}\n"],"mappings":";;;;AAWA,eAAsB,qBACpB,KACA,IACA,OACe;CACf,MAAM,SAAS,UAAU,KAAK;CA8P9B,MAAM,oBACJ,KACA,eACA,UAAU,KAAK,GACf,IACA;EAhQA,gBAAgB,IAAI,OAAO,eAAe,IAAI,IAAI,KAAK;EACvD,gBAAgB;CA+PhB,GACA;EAhDA,GAAG,EA5MH,eAAe,OAAO,GAAG,OAAO;GAC9B,MAAM,EAAE,eAAe,GAAG,MAAM,EAAE;EACpC,EA0MG;EACH,GAAG;GAvMH,eAAe,OAAO,GAAG,OAAO;IAC9B,MAAM,GAAG,OAAO,uBAAuB,KAAK,CAAC;GAC/C;;GAGA,aAAa,OAAO,IAAI,OAAO;IAC7B,MAAM,UAAiC,CAAC;IACxC,WAAW,MAAM,YAAY,EAE5B;+CACwC,GAAG,MAAM,EAAE,YAAY,OAC9D,GACF,GACE,KAAK,MAAM,WAAW,UACpB,QAAQ,KACN,EAAE,eAAe,GAAG,MAAM,EAAE,iBAAiB,GAAG,OAAO,EAAE;;+BAEtC,GAAG,OAAO,IAAI,QAAQ,CAC3C;IAGJ,GAAG,OAAO,gCAAgC,QAAQ,OAAO,MAAM;IAC/D,MAAM,QAAQ,IAAI,OAAO;GAC3B;EAgLG;EACH,GAAG,EA7KH,eAAe,OAAO,GAAG,OAAO;GAC9B,MAAM,EAAE,eAAe,GAAG,MAAM,EAAE;GAClC,MAAM,EAAE,eAAe,GAAG,MAAM,EAAE;EACpC,EA0KG;EAGH,GAAG,EAAC,gBAAgB,EAAC;EACrB,GAAG,EA1KH,eAAe,OAAO,GAAG,OAAO;GAC9B,MAAM,EAAE;oBACM,GAAG,MAAM,EAAE;;GAEzB,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CI;EAKJ,IAAI,EA7CJ,eAAe,OAAO,GAAG,QAAQ;GAC/B,MAAM,GAAG,eAAe,IAAI,MAAM,EAAE;EACtC,EA2CI;CASJ,CACF;AACF"}
1
+ {"version":3,"file":"init.js","names":[],"sources":["../../../../../../../zero-cache/src/services/view-syncer/schema/init.ts"],"sourcesContent":["import type {LogContext} from '@rocicorp/logger';\nimport type {PendingQuery, Row} from 'postgres';\nimport {\n runSchemaMigrations,\n type IncrementalMigrationMap,\n type Migration,\n} from '../../../db/migration.ts';\nimport type {PostgresDB} from '../../../types/pg.ts';\nimport {cvrSchema, type ShardID} from '../../../types/shards.ts';\nimport {createRowsVersionTable, setupCVRTables} from './cvr.ts';\n\nexport async function initViewSyncerSchema(\n log: LogContext,\n db: PostgresDB,\n shard: ShardID,\n): Promise<void> {\n const schema = cvrSchema(shard);\n\n const setupMigration: Migration = {\n migrateSchema: (lc, tx) => setupCVRTables(lc, tx, shard),\n minSafeVersion: 1,\n };\n\n const migrateV1toV2: Migration = {\n migrateSchema: async (_, tx) => {\n await tx`ALTER TABLE ${tx(schema)}.instances ADD \"replicaVersion\" TEXT`;\n },\n };\n\n const migrateV2ToV3: Migration = {\n migrateSchema: async (_, tx) => {\n await tx.unsafe(createRowsVersionTable(shard));\n },\n\n /** Populates the cvr.rowsVersion table with versions from cvr.instances. */\n migrateData: async (lc, tx) => {\n const pending: PendingQuery<Row[]>[] = [];\n for await (const versions of tx<\n {clientGroupID: string; version: string}[]\n >`\n SELECT \"clientGroupID\", \"version\" FROM ${tx(schema)}.instances`.cursor(\n 5000,\n )) {\n for (const version of versions) {\n pending.push(\n tx`INSERT INTO ${tx(schema)}.\"rowsVersion\" ${tx(version)} \n ON CONFLICT (\"clientGroupID\")\n DO UPDATE SET ${tx(version)}`.execute(),\n );\n }\n }\n lc.info?.(`initializing rowsVersion for ${pending.length} cvrs`);\n await Promise.all(pending);\n },\n };\n\n const migrateV3ToV4: Migration = {\n migrateSchema: async (_, tx) => {\n await tx`ALTER TABLE ${tx(schema)}.instances ADD \"owner\" TEXT`;\n await tx`ALTER TABLE ${tx(schema)}.instances ADD \"grantedAt\" TIMESTAMPTZ`;\n },\n };\n\n const migrateV5ToV6: Migration = {\n migrateSchema: async (_, tx) => {\n await tx`\n ALTER TABLE ${tx(schema)}.\"rows\"\n DROP CONSTRAINT fk_rows_client_group`;\n await tx`\n ALTER TABLE ${tx(schema)}.\"rowsVersion\"\n DROP CONSTRAINT fk_rows_version_client_group`;\n },\n };\n\n const migrateV6ToV7: Migration = {\n migrateSchema: async (_, tx) => {\n await tx`ALTER TABLE ${tx(schema)}.desires ADD \"expiresAt\" TIMESTAMPTZ`;\n await tx`ALTER TABLE ${tx(\n schema,\n )}.desires ADD \"inactivatedAt\" TIMESTAMPTZ`;\n await tx`ALTER TABLE ${tx(schema)}.desires ADD \"ttl\" INTERVAL`;\n\n await tx`CREATE INDEX desires_expires_at ON ${tx(\n schema,\n )}.desires (\"expiresAt\")`;\n await tx`CREATE INDEX desires_inactivated_at ON ${tx(\n schema,\n )}.desires (\"inactivatedAt\")`;\n },\n };\n\n const migrateV7ToV8: Migration = {\n migrateSchema: async (_, tx) => {\n await tx`ALTER TABLE ${tx(\n schema,\n )}.\"desires\" DROP CONSTRAINT fk_desires_client`;\n },\n };\n\n const migrateV8ToV9: Migration = {\n migrateSchema: async (_, tx) => {\n await tx`ALTER TABLE ${tx(schema)}.instances ADD \"clientSchema\" JSONB`;\n },\n };\n\n const migrateV9ToV10: Migration = {\n migrateSchema: async (_, tx) => {\n await tx`ALTER TABLE ${tx(schema)}.queries ADD \"queryName\" TEXT`;\n await tx`ALTER TABLE ${tx(schema)}.queries ADD \"queryArgs\" JSONB`;\n await tx`ALTER TABLE ${tx(schema)}.queries ALTER COLUMN \"clientAST\" DROP NOT NULL`;\n },\n };\n\n const migrateV10ToV11: Migration = {\n migrateSchema: async (_, tx) => {\n await tx`DROP INDEX IF EXISTS ${tx(schema)}.desires_expires_at`;\n await tx`ALTER TABLE ${tx(schema)}.desires DROP COLUMN \"expiresAt\"`;\n await tx`DROP INDEX IF EXISTS ${tx(schema)}.client_patch_version`;\n await tx`ALTER TABLE ${tx(schema)}.clients DROP COLUMN \"patchVersion\"`;\n await tx`ALTER TABLE ${tx(schema)}.clients DROP COLUMN \"deleted\"`;\n },\n };\n\n const migratedV11ToV12: Migration = {\n migrateSchema: async (_, tx) => {\n await tx`ALTER TABLE ${tx(schema)}.queries ALTER COLUMN \"queryArgs\" TYPE JSON USING \"queryArgs\"::JSON`;\n },\n };\n\n const migratedV12ToV13: Migration = {\n migrateSchema: async (_, tx) => {\n await tx`ALTER TABLE ${tx(schema)}.instances ADD COLUMN \"ttlClock\" DOUBLE PRECISION NOT NULL DEFAULT 0`;\n },\n };\n\n const migratedV13ToV14: Migration = {\n migrateSchema: async (_, sql) => {\n await sql`\n CREATE INDEX instances_last_active ON ${sql(schema)}.instances (\"lastActive\");\n `;\n\n // Update / add foreign key constraints to cascade deletes.\n for (const [table, reference] of [\n ['clients', 'instances'],\n ['queries', 'instances'],\n ['rows', 'rowsVersion'],\n ] as [string, string][]) {\n const constraint = sql(`fk_${table}_client_group`);\n await sql`\n ALTER TABLE ${sql(schema)}.${sql(table)} DROP CONSTRAINT IF EXISTS ${constraint}`;\n await sql`\n ALTER TABLE ${sql(schema)}.${sql(table)} ADD CONSTRAINT ${constraint}\n FOREIGN KEY(\"clientGroupID\")\n REFERENCES ${sql(schema)}.${sql(reference)} (\"clientGroupID\")\n ON DELETE CASCADE;\n `;\n }\n },\n };\n\n const migratedV14ToV15: Migration = {\n migrateSchema: async (_, sql) => {\n // Add new columns for storing inactivatedAt and ttl in milliseconds.\n // This avoids postgres.js type conversion issues with TIMESTAMPTZ and INTERVAL.\n await sql`ALTER TABLE ${sql(schema)}.desires \n ADD COLUMN \"inactivatedAtMs\" DOUBLE PRECISION`;\n await sql`ALTER TABLE ${sql(schema)}.desires \n ADD COLUMN \"ttlMs\" DOUBLE PRECISION`;\n },\n // Migrate existing data: convert TIMESTAMPTZ to milliseconds for inactivatedAt\n // and INTERVAL to milliseconds for ttl\n // Note: EXTRACT(EPOCH FROM NULL) returns NULL, so NULL values are preserved\n migrateData: async (lc, sql) => {\n lc.info?.(\n 'Migrating desires.inactivatedAt to inactivatedAtMs and ttl to ttlMs',\n );\n await sql`\n UPDATE ${sql(schema)}.desires\n SET \"inactivatedAtMs\" = EXTRACT(EPOCH FROM \"inactivatedAt\") * 1000,\n \"ttlMs\" = EXTRACT(EPOCH FROM \"ttl\") * 1000\n `;\n },\n };\n\n const migratedV15ToV16: Migration = {\n migrateSchema: async (_, sql) => {\n await sql`ALTER TABLE ${sql(schema)}.instances ADD COLUMN \"profileID\" TEXT`;\n await sql`ALTER TABLE ${sql(schema)}.instances ADD COLUMN \"deleted\" BOOL DEFAULT FALSE`;\n\n // Recreate the instances_last_active index to exclude tombstones\n await sql`\n DROP INDEX IF EXISTS ${sql(schema)}.instances_last_active`;\n await sql`\n CREATE INDEX instances_last_active ON ${sql(schema)}.instances (\"lastActive\")\n WHERE NOT \"deleted\"`;\n await sql`\n CREATE INDEX tombstones_last_active ON ${sql(schema)}.instances (\"lastActive\")\n WHERE \"deleted\"`;\n await sql`\n CREATE INDEX profile_ids_last_active ON ${sql(schema)}.instances (\"lastActive\", \"profileID\")\n WHERE \"profileID\" IS NOT NULL`;\n },\n\n // Backfill profileIDs to the `cg${clientGroupID}`, as is done for\n // client groups from old zero-clients that don't send a profileID.\n migrateData: async (lc, sql) => {\n lc.info?.('Backfilling instance.profileIDs');\n await sql`\n UPDATE ${sql(schema)}.instances\n SET \"profileID\" = 'cg' || \"clientGroupID\"\n WHERE \"profileID\" IS NULL\n `;\n },\n };\n\n const migratedV16ToV17: Migration = {\n migrateSchema: async (_, sql) => {\n await sql`ALTER TABLE ${sql(schema)}.queries ADD COLUMN \"rowSetSignature\" TEXT`;\n },\n };\n\n const migratedV17ToV18: Migration = {\n migrateSchema: async (_, sql) => {\n await sql`ALTER TABLE ${sql(schema)}.instances ADD COLUMN \"pinnedUser\" JSONB`;\n },\n };\n\n const migratedV18ToV19: Migration = {\n migrateSchema: async (_, sql) => {\n await sql`ALTER TABLE ${sql(schema)}.instances ALTER COLUMN \"ttlClock\" SET DEFAULT 0`;\n },\n };\n\n const schemaVersionMigrationMap: IncrementalMigrationMap = {\n 2: migrateV1toV2,\n 3: migrateV2ToV3,\n 4: migrateV3ToV4,\n // v5 enables asynchronous row-record flushing, and thus relies on\n // the logic that updates and checks the rowsVersion table in v3.\n 5: {minSafeVersion: 3},\n 6: migrateV5ToV6,\n 7: migrateV6ToV7,\n 8: migrateV7ToV8,\n 9: migrateV8ToV9,\n // v10 adds queryName and queryArgs to the queries table to support\n // custom queries. clientAST is now optional to support migrating\n // off client queries.\n 10: migrateV9ToV10,\n // V11 removes the deprecated queries.\"expiresAt\", clients.\"patchVersion\",\n // clients.\"deleted\" columns.\n 11: migrateV10ToV11,\n 12: migratedV11ToV12,\n // V13 adds instances.\"ttlClock\"\n 13: migratedV12ToV13,\n // V14 adds an index on instances.\"lastActive\" and a FK constraint\n // from rows.\"clientGroupID\" to rowsVersion.\"clientGroupID\" for\n // garbage collection\n 14: migratedV13ToV14,\n // V15 adds desires.\"inactivatedAtTTLClock\" to store TTLClock values\n // directly as DOUBLE PRECISION, avoiding postgres.js TIMESTAMPTZ\n // type conversion issues\n 15: migratedV14ToV15,\n // V16 adds instances.\"profileID\" and a corresponding index for estimating\n // active user counts more accurately for apps that use memstore.\n 16: migratedV15ToV16,\n // V17 adds queries.\"rowSetSignature\" — XOR'd hash of row IDs attached to\n // each query, used to detect drift on re-hydration of queries containing\n // the Cap operator.\n 17: migratedV16ToV17,\n // V18 adds instances.\"pinnedUser\", the user of the client group's first\n // validated connection, so that the group stays pinned to that user\n // across view-syncer restarts. NULL for existing groups until their next\n // validated connection.\n 18: migratedV17ToV18,\n // V19 sets the default of instances.\"ttlClock\" to 0. A CVR set up by\n // zero-cache 0.22 to 0.24 created the column without a default, unlike\n // one upgraded through V13 or set up later.\n 19: migratedV18ToV19,\n };\n\n await runSchemaMigrations(\n log,\n 'view-syncer',\n cvrSchema(shard),\n db,\n setupMigration,\n schemaVersionMigrationMap,\n );\n}\n"],"mappings":";;;;AAWA,eAAsB,qBACpB,KACA,IACA,OACe;CACf,MAAM,SAAS,UAAU,KAAK;CAwQ9B,MAAM,oBACJ,KACA,eACA,UAAU,KAAK,GACf,IACA;EA1QA,gBAAgB,IAAI,OAAO,eAAe,IAAI,IAAI,KAAK;EACvD,gBAAgB;CAyQhB,GACA;EApDA,GAAG,EAlNH,eAAe,OAAO,GAAG,OAAO;GAC9B,MAAM,EAAE,eAAe,GAAG,MAAM,EAAE;EACpC,EAgNG;EACH,GAAG;GA7MH,eAAe,OAAO,GAAG,OAAO;IAC9B,MAAM,GAAG,OAAO,uBAAuB,KAAK,CAAC;GAC/C;;GAGA,aAAa,OAAO,IAAI,OAAO;IAC7B,MAAM,UAAiC,CAAC;IACxC,WAAW,MAAM,YAAY,EAE5B;+CACwC,GAAG,MAAM,EAAE,YAAY,OAC9D,GACF,GACE,KAAK,MAAM,WAAW,UACpB,QAAQ,KACN,EAAE,eAAe,GAAG,MAAM,EAAE,iBAAiB,GAAG,OAAO,EAAE;;+BAEtC,GAAG,OAAO,IAAI,QAAQ,CAC3C;IAGJ,GAAG,OAAO,gCAAgC,QAAQ,OAAO,MAAM;IAC/D,MAAM,QAAQ,IAAI,OAAO;GAC3B;EAsLG;EACH,GAAG,EAnLH,eAAe,OAAO,GAAG,OAAO;GAC9B,MAAM,EAAE,eAAe,GAAG,MAAM,EAAE;GAClC,MAAM,EAAE,eAAe,GAAG,MAAM,EAAE;EACpC,EAgLG;EAGH,GAAG,EAAC,gBAAgB,EAAC;EACrB,GAAG,EAhLH,eAAe,OAAO,GAAG,OAAO;GAC9B,MAAM,EAAE;oBACM,GAAG,MAAM,EAAE;;GAEzB,MAAM,EAAE;oBACM,GAAG,MAAM,EAAE;;EAE3B,EAyKG;EACH,GAAG,EAtKH,eAAe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