@rocicorp/zero 1.4.0-canary.1 → 1.4.0-canary.2

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 (115) hide show
  1. package/out/analyze-query/src/bin-analyze.js +1 -1
  2. package/out/analyze-query/src/bin-analyze.js.map +1 -1
  3. package/out/analyze-query/src/bin-transform.js +1 -1
  4. package/out/analyze-query/src/bin-transform.js.map +1 -1
  5. package/out/replicache/src/btree/node.d.ts +1 -1
  6. package/out/replicache/src/btree/node.d.ts.map +1 -1
  7. package/out/replicache/src/btree/node.js +34 -21
  8. package/out/replicache/src/btree/node.js.map +1 -1
  9. package/out/replicache/src/btree/write.js +1 -2
  10. package/out/replicache/src/btree/write.js.map +1 -1
  11. package/out/shared/src/btree-set.d.ts +6 -0
  12. package/out/shared/src/btree-set.d.ts.map +1 -1
  13. package/out/shared/src/btree-set.js +34 -0
  14. package/out/shared/src/btree-set.js.map +1 -1
  15. package/out/zero/package.js +1 -1
  16. package/out/zero/package.js.map +1 -1
  17. package/out/zero-cache/src/config/zero-config.d.ts +18 -0
  18. package/out/zero-cache/src/config/zero-config.d.ts.map +1 -1
  19. package/out/zero-cache/src/config/zero-config.js +35 -3
  20. package/out/zero-cache/src/config/zero-config.js.map +1 -1
  21. package/out/zero-cache/src/scripts/decommission.d.ts.map +1 -1
  22. package/out/zero-cache/src/scripts/decommission.js +3 -3
  23. package/out/zero-cache/src/scripts/decommission.js.map +1 -1
  24. package/out/zero-cache/src/scripts/deploy-permissions.js +1 -1
  25. package/out/zero-cache/src/scripts/deploy-permissions.js.map +1 -1
  26. package/out/zero-cache/src/server/change-streamer.d.ts.map +1 -1
  27. package/out/zero-cache/src/server/change-streamer.js +2 -5
  28. package/out/zero-cache/src/server/change-streamer.js.map +1 -1
  29. package/out/zero-cache/src/server/main.d.ts.map +1 -1
  30. package/out/zero-cache/src/server/main.js +6 -1
  31. package/out/zero-cache/src/server/main.js.map +1 -1
  32. package/out/zero-cache/src/server/reaper.d.ts.map +1 -1
  33. package/out/zero-cache/src/server/reaper.js +1 -4
  34. package/out/zero-cache/src/server/reaper.js.map +1 -1
  35. package/out/zero-cache/src/server/shadow-syncer.js +35 -0
  36. package/out/zero-cache/src/server/shadow-syncer.js.map +1 -0
  37. package/out/zero-cache/src/server/syncer.d.ts.map +1 -1
  38. package/out/zero-cache/src/server/syncer.js +2 -8
  39. package/out/zero-cache/src/server/syncer.js.map +1 -1
  40. package/out/zero-cache/src/server/worker-urls.d.ts +1 -0
  41. package/out/zero-cache/src/server/worker-urls.d.ts.map +1 -1
  42. package/out/zero-cache/src/server/worker-urls.js +2 -1
  43. package/out/zero-cache/src/server/worker-urls.js.map +1 -1
  44. package/out/zero-cache/src/services/change-source/pg/backfill-stream.d.ts +8 -1
  45. package/out/zero-cache/src/services/change-source/pg/backfill-stream.d.ts.map +1 -1
  46. package/out/zero-cache/src/services/change-source/pg/backfill-stream.js +31 -18
  47. package/out/zero-cache/src/services/change-source/pg/backfill-stream.js.map +1 -1
  48. package/out/zero-cache/src/services/change-source/pg/change-source.d.ts.map +1 -1
  49. package/out/zero-cache/src/services/change-source/pg/change-source.js +44 -46
  50. package/out/zero-cache/src/services/change-source/pg/change-source.js.map +1 -1
  51. package/out/zero-cache/src/services/change-source/pg/initial-sync.d.ts +6 -1
  52. package/out/zero-cache/src/services/change-source/pg/initial-sync.d.ts.map +1 -1
  53. package/out/zero-cache/src/services/change-source/pg/initial-sync.js +62 -22
  54. package/out/zero-cache/src/services/change-source/pg/initial-sync.js.map +1 -1
  55. package/out/zero-cache/src/services/change-streamer/change-streamer-http.d.ts.map +1 -1
  56. package/out/zero-cache/src/services/change-streamer/change-streamer-http.js +2 -3
  57. package/out/zero-cache/src/services/change-streamer/change-streamer-http.js.map +1 -1
  58. package/out/zero-cache/src/services/change-streamer/schema/tables.js +1 -1
  59. package/out/zero-cache/src/services/shadow-sync/shadow-sync-service.js +49 -0
  60. package/out/zero-cache/src/services/shadow-sync/shadow-sync-service.js.map +1 -0
  61. package/out/zero-cache/src/services/statz.js +3 -3
  62. package/out/zero-cache/src/services/statz.js.map +1 -1
  63. package/out/zero-cache/src/services/view-syncer/cvr-store.d.ts +1 -0
  64. package/out/zero-cache/src/services/view-syncer/cvr-store.d.ts.map +1 -1
  65. package/out/zero-cache/src/services/view-syncer/cvr-store.js +34 -11
  66. package/out/zero-cache/src/services/view-syncer/cvr-store.js.map +1 -1
  67. package/out/zero-cache/src/services/view-syncer/cvr.d.ts +16 -1
  68. package/out/zero-cache/src/services/view-syncer/cvr.d.ts.map +1 -1
  69. package/out/zero-cache/src/services/view-syncer/cvr.js +19 -1
  70. package/out/zero-cache/src/services/view-syncer/cvr.js.map +1 -1
  71. package/out/zero-cache/src/services/view-syncer/inspect-handler.js +1 -1
  72. package/out/zero-cache/src/services/view-syncer/inspect-handler.js.map +1 -1
  73. package/out/zero-cache/src/services/view-syncer/pipeline-driver.d.ts +6 -0
  74. package/out/zero-cache/src/services/view-syncer/pipeline-driver.d.ts.map +1 -1
  75. package/out/zero-cache/src/services/view-syncer/pipeline-driver.js +45 -2
  76. package/out/zero-cache/src/services/view-syncer/pipeline-driver.js.map +1 -1
  77. package/out/zero-cache/src/services/view-syncer/row-set-signature.d.ts +17 -0
  78. package/out/zero-cache/src/services/view-syncer/row-set-signature.d.ts.map +1 -0
  79. package/out/zero-cache/src/services/view-syncer/row-set-signature.js +29 -0
  80. package/out/zero-cache/src/services/view-syncer/row-set-signature.js.map +1 -0
  81. package/out/zero-cache/src/services/view-syncer/schema/cvr.d.ts +1 -0
  82. package/out/zero-cache/src/services/view-syncer/schema/cvr.d.ts.map +1 -1
  83. package/out/zero-cache/src/services/view-syncer/schema/cvr.js +1 -0
  84. package/out/zero-cache/src/services/view-syncer/schema/cvr.js.map +1 -1
  85. package/out/zero-cache/src/services/view-syncer/schema/init.d.ts.map +1 -1
  86. package/out/zero-cache/src/services/view-syncer/schema/init.js +5 -1
  87. package/out/zero-cache/src/services/view-syncer/schema/init.js.map +1 -1
  88. package/out/zero-cache/src/services/view-syncer/schema/types.d.ts +105 -0
  89. package/out/zero-cache/src/services/view-syncer/schema/types.d.ts.map +1 -1
  90. package/out/zero-cache/src/services/view-syncer/schema/types.js +8 -4
  91. package/out/zero-cache/src/services/view-syncer/schema/types.js.map +1 -1
  92. package/out/zero-cache/src/services/view-syncer/view-syncer.d.ts.map +1 -1
  93. package/out/zero-cache/src/services/view-syncer/view-syncer.js +2 -2
  94. package/out/zero-cache/src/services/view-syncer/view-syncer.js.map +1 -1
  95. package/out/zero-cache/src/types/pg.d.ts +1 -1
  96. package/out/zero-cache/src/types/pg.d.ts.map +1 -1
  97. package/out/zero-cache/src/types/pg.js +8 -2
  98. package/out/zero-cache/src/types/pg.js.map +1 -1
  99. package/out/zero-cache/src/types/timeout.d.ts +11 -0
  100. package/out/zero-cache/src/types/timeout.d.ts.map +1 -0
  101. package/out/zero-cache/src/types/timeout.js +26 -0
  102. package/out/zero-cache/src/types/timeout.js.map +1 -0
  103. package/out/zero-cache/src/workers/connection.js +3 -3
  104. package/out/zero-cache/src/workers/connection.js.map +1 -1
  105. package/out/zero-client/src/client/version.js +1 -1
  106. package/out/zero-server/src/adapters/postgresjs.d.ts.map +1 -1
  107. package/out/zero-server/src/adapters/postgresjs.js +1 -1
  108. package/out/zero-server/src/adapters/postgresjs.js.map +1 -1
  109. package/out/zql/src/ivm/memory-source.d.ts.map +1 -1
  110. package/out/zql/src/ivm/memory-source.js +3 -3
  111. package/out/zql/src/ivm/memory-source.js.map +1 -1
  112. package/out/zql/src/query/query-internals.d.ts.map +1 -1
  113. package/out/zql/src/query/query-internals.js +1 -1
  114. package/out/zql/src/query/query-internals.js.map +1 -1
  115. package/package.json +1 -1
@@ -1 +1 @@
1
- {"version":3,"file":"btree-set.js","names":["#root","#delete","#maxKey","#nodeQueue","#nodeIndex","#leaf","#i"],"sources":["../../../../shared/src/btree-set.ts"],"sourcesContent":["import {assert} from './asserts.ts';\n\nconst MAX_NODE_SIZE = 32;\n\ntype Comparator<K> = (a: K, b: K) => number;\n\nexport class BTreeSet<K> {\n #root: BNode<K> = emptyLeaf as BNode<K>;\n size: number = 0;\n\n readonly comparator: Comparator<K>;\n\n constructor(comparator: Comparator<K>, entries?: IterableIterator<K>) {\n this.comparator = comparator;\n if (entries) {\n for (const key of entries) {\n this.add(key);\n }\n }\n }\n\n /** Releases the tree so that its size is 0. */\n clear() {\n this.#root = emptyLeaf as BNode<K>;\n this.size = 0;\n }\n\n clone() {\n this.#root.isShared = true;\n const ret = new BTreeSet<K>(this.comparator);\n ret.#root = this.#root;\n ret.size = this.size;\n return ret;\n }\n\n get(key: K): K | undefined {\n return this.#root.get(key, this);\n }\n\n add(key: K): this {\n if (this.#root.isShared) this.#root = this.#root.clone();\n const result = this.#root.set(key, this);\n if (result === null) return this;\n // Root node has split, so create a new root node.\n this.#root = new BNodeInternal<K>([this.#root, result]);\n return this;\n }\n\n /**\n * Returns true if the key exists in the B+ tree, false if not.\n * Use get() for best performance; use has() if you need to\n * distinguish between \"undefined value\" and \"key not present\".\n * @param key Key to detect\n * @description Computational complexity: O(log size)\n */\n has(key: K): boolean {\n return this.#root.has(key, this);\n }\n\n /**\n * Removes a single key-value pair from the B+ tree.\n * @param key Key to find\n * @returns true if a pair was found and removed, false otherwise.\n * @description Computational complexity: O(log size)\n */\n delete(key: K): boolean {\n return this.#delete(key);\n }\n\n #delete(key: K): boolean {\n let root = this.#root;\n if (root.isShared) {\n this.#root = root = root.clone();\n }\n try {\n return root.delete(key, this);\n } finally {\n let isShared;\n while (root.keys.length <= 1 && root.isInternal()) {\n isShared ||= root.isShared;\n this.#root = root =\n root.keys.length === 0 ? emptyLeaf : root.children[0];\n }\n // If any ancestor of the new root was shared, the new root must also be shared\n if (isShared) {\n root.isShared = true;\n }\n }\n }\n\n keys(): IterableIterator<K> {\n return valuesFrom(this.#root, this.comparator, undefined, true);\n }\n\n values(): IterableIterator<K> {\n return valuesFrom(this.#root, this.comparator, undefined, true);\n }\n\n valuesFrom(lowestKey?: K, inclusive: boolean = true): IterableIterator<K> {\n return valuesFrom(this.#root, this.comparator, lowestKey, inclusive);\n }\n\n valuesReversed(): IterableIterator<K> {\n return valuesFromReversed(\n this.#maxKey(),\n this.#root,\n this.comparator,\n undefined,\n true,\n );\n }\n\n valuesFromReversed(\n highestKey?: K,\n inclusive: boolean = true,\n ): IterableIterator<K> {\n return valuesFromReversed(\n this.#maxKey(),\n this.#root,\n this.comparator,\n highestKey,\n inclusive,\n );\n }\n\n /** Gets the highest key in the tree. Complexity: O(1) */\n #maxKey(): K | undefined {\n return this.#root.maxKey();\n }\n\n [Symbol.iterator](): IterableIterator<K> {\n return this.keys();\n }\n}\n\nclass BTreeForwardIterator<K> implements IterableIterator<K> {\n readonly #nodeQueue: BNode<K>[][];\n readonly #nodeIndex: number[];\n #leaf: BNode<K>;\n #i: number;\n\n constructor(\n nodeQueue: BNode<K>[][],\n nodeIndex: number[],\n leaf: BNode<K>,\n startI: number,\n ) {\n this.#nodeQueue = nodeQueue;\n this.#nodeIndex = nodeIndex;\n this.#leaf = leaf;\n this.#i = startI;\n }\n\n next(): IteratorResult<K> {\n for (;;) {\n if (++this.#i < this.#leaf.keys.length) {\n return {done: false, value: this.#leaf.keys[this.#i]};\n }\n\n let level = -1;\n for (;;) {\n if (++level >= this.#nodeQueue.length) {\n return {done: true, value: undefined as unknown as K};\n }\n if (++this.#nodeIndex[level] < this.#nodeQueue[level].length) {\n break;\n }\n }\n for (; level > 0; level--) {\n this.#nodeQueue[level - 1] = (\n this.#nodeQueue[level][this.#nodeIndex[level]] as BNodeInternal<K>\n ).children;\n this.#nodeIndex[level - 1] = 0;\n }\n this.#leaf = this.#nodeQueue[0][this.#nodeIndex[0]];\n this.#i = -1;\n }\n }\n\n [Symbol.iterator]() {\n return this;\n }\n}\n\nclass BTreeReverseIterator<K> implements IterableIterator<K> {\n readonly #nodeQueue: BNode<K>[][];\n readonly #nodeIndex: number[];\n #leaf: BNode<K>;\n #i: number;\n\n constructor(\n nodeQueue: BNode<K>[][],\n nodeIndex: number[],\n leaf: BNode<K>,\n startI: number,\n ) {\n this.#nodeQueue = nodeQueue;\n this.#nodeIndex = nodeIndex;\n this.#leaf = leaf;\n this.#i = startI;\n }\n\n next(): IteratorResult<K> {\n for (;;) {\n if (--this.#i >= 0) {\n return {done: false, value: this.#leaf.keys[this.#i]};\n }\n\n let level;\n // Advance to the next leaf node\n for (level = -1; ; ) {\n if (++level >= this.#nodeQueue.length) {\n return {done: true, value: undefined as unknown as K};\n }\n if (--this.#nodeIndex[level] >= 0) {\n break;\n }\n }\n for (; level > 0; level--) {\n this.#nodeQueue[level - 1] = (\n this.#nodeQueue[level][this.#nodeIndex[level]] as BNodeInternal<K>\n ).children;\n this.#nodeIndex[level - 1] = this.#nodeQueue[level - 1].length - 1;\n }\n this.#leaf = this.#nodeQueue[0][this.#nodeIndex[0]];\n this.#i = this.#leaf.keys.length;\n }\n }\n\n [Symbol.iterator]() {\n return this;\n }\n}\n\nfunction valuesFrom<K>(\n root: BNode<K>,\n comparator: Comparator<K>,\n lowestKey: K | undefined,\n inclusive: boolean,\n): IterableIterator<K> {\n const info = findPath(lowestKey, root, comparator);\n if (info === undefined) {\n return iterator<K>(() => ({done: true, value: undefined}));\n }\n\n let [nodeQueue, nodeIndex, leaf] = info;\n let i =\n lowestKey === undefined\n ? -1\n : indexOf(lowestKey, leaf.keys, 0, comparator) - 1;\n\n if (\n !inclusive &&\n lowestKey !== undefined &&\n // +1 because we did -1 above.\n i + 1 < leaf.keys.length &&\n comparator(leaf.keys[i + 1], lowestKey) === 0\n ) {\n i++;\n }\n\n return new BTreeForwardIterator(nodeQueue, nodeIndex, leaf, i);\n}\n\nfunction valuesFromReversed<K>(\n maxKey: K | undefined,\n root: BNode<K>,\n comparator: Comparator<K>,\n highestKey: K | undefined,\n inclusive: boolean,\n): IterableIterator<K> {\n if (highestKey === undefined) {\n highestKey = maxKey;\n if (highestKey === undefined) {\n return iterator<K>(() => ({done: true, value: undefined}));\n } // collection is empty\n }\n let [nodeQueue, nodeIndex, leaf] =\n findPath(highestKey, root, comparator) ||\n findPath(maxKey, root, comparator)!;\n assert(\n !nodeQueue[0] || leaf === nodeQueue[0][nodeIndex[0]],\n 'BTreeSet: leaf node mismatch in iteration',\n );\n let i = indexOf(highestKey, leaf.keys, 0, comparator);\n if (\n inclusive &&\n i < leaf.keys.length &&\n comparator(leaf.keys[i], highestKey) <= 0\n ) {\n i++;\n }\n\n return new BTreeReverseIterator(nodeQueue, nodeIndex, leaf, i);\n}\n\nfunction findPath<K>(\n key: K | undefined,\n root: BNode<K>,\n comparator: Comparator<K>,\n): [nodeQueue: BNode<K>[][], nodeIndex: number[], leaf: BNode<K>] | undefined {\n let nextNode = root;\n const nodeQueue: BNode<K>[][] = [];\n const nodeIndex: number[] = [];\n\n if (nextNode.isInternal()) {\n for (let d = 0; nextNode.isInternal(); d++) {\n nodeQueue[d] = nextNode.children;\n nodeIndex[d] =\n key === undefined ? 0 : indexOf(key, nextNode.keys, 0, comparator);\n if (nodeIndex[d] >= nodeQueue[d].length) return; // first key > maxKey()\n nextNode = nodeQueue[d][nodeIndex[d]];\n }\n nodeQueue.reverse();\n nodeIndex.reverse();\n }\n return [nodeQueue, nodeIndex, nextNode];\n}\n\nfunction iterator<T>(next: () => IteratorResult<T>): IterableIterator<T> {\n return {\n next,\n [Symbol.iterator]() {\n return this;\n },\n };\n}\n\n/** Leaf node / base class. **************************************************/\nclass BNode<K> {\n // If this is an internal node, _keys[i] is the highest key in children[i].\n keys: K[];\n // True if this node might be within multiple `BTree`s (or have multiple parents).\n // If so, it must be cloned before being mutated to avoid changing an unrelated tree.\n // This is transitive: if it's true, children are also shared even if `isShared!=true`\n // in those children. (Certain operations will propagate isShared=true to children.)\n isShared: true | undefined;\n\n constructor(keys: K[]) {\n this.keys = keys;\n this.isShared = undefined;\n }\n\n isInternal(): this is BNodeInternal<K> {\n return false;\n }\n\n maxKey() {\n // oxlint-disable-next-line typescript/no-non-null-assertion\n return this.keys.at(-1)!;\n }\n\n minKey(): K | undefined {\n return this.keys[0];\n }\n\n clone(): BNode<K> {\n return new BNode<K>(this.keys.slice(0));\n }\n\n get(key: K, tree: BTreeSet<K>): K | undefined {\n const i = indexOf(key, this.keys, -1, tree.comparator);\n return i < 0 ? undefined : this.keys[i];\n }\n\n has(key: K, tree: BTreeSet<K>): boolean {\n const i = indexOf(key, this.keys, -1, tree.comparator);\n return i >= 0 && i < this.keys.length;\n }\n\n set(key: K, tree: BTreeSet<K>): null | BNode<K> {\n let i = indexOf(key, this.keys, -1, tree.comparator);\n if (i < 0) {\n // key does not exist yet\n i = ~i;\n tree.size++;\n\n if (this.keys.length < MAX_NODE_SIZE) {\n this.keys.splice(i, 0, key);\n return null;\n }\n // This leaf node is full and must split\n const newRightSibling = this.splitOffRightSide();\n // oxlint-disable-next-line @typescript-eslint/no-this-alias\n let target: BNode<K> = this;\n if (i > this.keys.length) {\n i -= this.keys.length;\n target = newRightSibling;\n }\n // target.#insertInLeaf(i, key);\n target.keys.splice(i, 0, key);\n\n return newRightSibling;\n }\n\n // usually this is a no-op, but some users may wish to edit the key\n this.keys[i] = key;\n return null;\n }\n\n takeFromRight(rhs: BNode<K>) {\n this.keys.push(rhs.keys.shift()!);\n }\n\n takeFromLeft(lhs: BNode<K>) {\n this.keys.unshift(lhs.keys.pop()!);\n }\n\n splitOffRightSide(): BNode<K> {\n const half = this.keys.length >> 1;\n const keys = this.keys.splice(half);\n return new BNode<K>(keys);\n }\n\n delete(key: K, tree: BTreeSet<K>): boolean {\n const cmp = tree.comparator;\n const iLow = indexOf(key, this.keys, -1, cmp);\n const iHigh = iLow + 1;\n\n if (iLow < 0) {\n return false;\n }\n\n const {keys} = this;\n for (let i = iLow; i < iHigh; i++) {\n const key = keys[i];\n\n if (key !== keys[i] || this.isShared === true) {\n throw new Error('BTree illegally changed or cloned in delete');\n }\n\n this.keys.splice(i, 1);\n tree.size--;\n return true;\n }\n\n return false;\n }\n\n mergeSibling(rhs: BNode<K>, _: number) {\n this.keys.push(...rhs.keys);\n }\n}\n\n/** Internal node (non-leaf node) ********************************************/\nclass BNodeInternal<K> extends BNode<K> {\n // Note: conventionally B+ trees have one fewer key than the number of\n // children, but I find it easier to keep the array lengths equal: each\n // keys[i] caches the value of children[i].maxKey().\n children: BNode<K>[];\n\n /**\n * This does not mark `children` as shared, so it is the responsibility of the caller\n * to ensure children are either marked shared, or aren't included in another tree.\n */\n constructor(children: BNode<K>[], keys?: K[]) {\n if (!keys) {\n keys = [];\n for (let i = 0; i < children.length; i++) {\n keys[i] = children[i].maxKey();\n }\n }\n super(keys);\n this.children = children;\n }\n\n isInternal(): this is BNodeInternal<K> {\n return true;\n }\n\n clone(): BNode<K> {\n const children = this.children.slice(0);\n for (let i = 0; i < children.length; i++) {\n children[i].isShared = true;\n }\n return new BNodeInternal<K>(children, this.keys.slice(0));\n }\n\n minKey() {\n return this.children[0].minKey();\n }\n\n get(key: K, tree: BTreeSet<K>): K | undefined {\n const i = indexOf(key, this.keys, 0, tree.comparator);\n const {children} = this;\n return i < children.length ? children[i].get(key, tree) : undefined;\n }\n\n has(key: K, tree: BTreeSet<K>): boolean {\n const i = indexOf(key, this.keys, 0, tree.comparator);\n const {children} = this;\n return i < children.length ? children[i].has(key, tree) : false;\n }\n\n set(key: K, tree: BTreeSet<K>): null | BNode<K> {\n const c = this.children;\n const cmp = tree.comparator;\n let i = Math.min(indexOf(key, this.keys, 0, cmp), c.length - 1);\n let child = c[i];\n\n if (child.isShared) {\n c[i] = child = child.clone();\n }\n if (child.keys.length >= MAX_NODE_SIZE) {\n // child is full; inserting anything else will cause a split.\n // Shifting an item to the left or right sibling may avoid a split.\n // We can do a shift if the adjacent node is not full and if the\n // current key can still be placed in the same node after the shift.\n let other: BNode<K>;\n if (\n i > 0 &&\n (other = c[i - 1]).keys.length < MAX_NODE_SIZE &&\n cmp(child.keys[0], key) < 0\n ) {\n if (other.isShared) {\n c[i - 1] = other = other.clone();\n }\n other.takeFromRight(child);\n this.keys[i - 1] = other.maxKey();\n } else if (\n (other = c[i + 1]) !== undefined &&\n other.keys.length < MAX_NODE_SIZE &&\n cmp(child.maxKey(), key) < 0\n ) {\n if (other.isShared) c[i + 1] = other = other.clone();\n other.takeFromLeft(child);\n this.keys[i] = c[i].maxKey();\n }\n }\n\n const result = child.set(key, tree);\n this.keys[i] = child.maxKey();\n if (result === null) return null;\n\n // The child has split and `result` is a new right child... does it fit?\n if (this.keys.length < MAX_NODE_SIZE) {\n // yes\n this.insert(i + 1, result);\n return null;\n }\n // no, we must split also\n const newRightSibling = this.splitOffRightSide();\n // oxlint-disable-next-line @typescript-eslint/no-this-alias\n let target: BNodeInternal<K> = this;\n if (cmp(result.maxKey(), this.maxKey()) > 0) {\n target = newRightSibling;\n i -= this.keys.length;\n }\n target.insert(i + 1, result);\n return newRightSibling;\n }\n\n /**\n * Inserts `child` at index `i`.\n * This does not mark `child` as shared, so it is the responsibility of the caller\n * to ensure that either child is marked shared, or it is not included in another tree.\n */\n insert(i: number, child: BNode<K>) {\n this.children.splice(i, 0, child);\n this.keys.splice(i, 0, child.maxKey());\n }\n\n /**\n * Split this node.\n * Modifies this to remove the second half of the items, returning a separate node containing them.\n */\n splitOffRightSide() {\n const half = this.children.length >> 1;\n return new BNodeInternal<K>(\n this.children.splice(half),\n this.keys.splice(half),\n );\n }\n\n takeFromRight(rhs: BNode<K>) {\n this.keys.push(rhs.keys.shift()!);\n this.children.push((rhs as BNodeInternal<K>).children.shift()!);\n }\n\n takeFromLeft(lhs: BNode<K>) {\n this.keys.unshift(lhs.keys.pop()!);\n this.children.unshift((lhs as BNodeInternal<K>).children.pop()!);\n }\n\n delete(key: K, tree: BTreeSet<K>): boolean {\n const cmp = tree.comparator;\n const {keys} = this;\n const {children} = this;\n let iLow = indexOf(key, this.keys, 0, cmp);\n let i = iLow;\n const iHigh = Math.min(iLow, keys.length - 1);\n if (i <= iHigh) {\n try {\n if (children[i].isShared) {\n children[i] = children[i].clone();\n }\n const result = children[i].delete(key, tree);\n // Note: if children[i] is empty then keys[i]=undefined.\n // This is an invalid state, but it is fixed below.\n keys[i] = children[i].maxKey();\n return result;\n } finally {\n // Deletions may have occurred, so look for opportunities to merge nodes.\n const half = MAX_NODE_SIZE >> 1;\n if (iLow > 0) iLow--;\n for (i = iHigh; i >= iLow; i--) {\n if (children[i].keys.length <= half) {\n if (children[i].keys.length !== 0) {\n this.tryMerge(i, MAX_NODE_SIZE);\n } else {\n // child is empty! delete it!\n keys.splice(i, 1);\n children.splice(i, 1);\n }\n }\n }\n }\n }\n return false;\n }\n\n /** Merges child i with child i+1 if their combined size is not too large */\n tryMerge(i: number, maxSize: number): boolean {\n const {children} = this;\n if (i >= 0 && i + 1 < children.length) {\n if (children[i].keys.length + children[i + 1].keys.length <= maxSize) {\n if (\n children[i].isShared\n ) // cloned already UNLESS i is outside scan range\n {\n children[i] = children[i].clone();\n }\n children[i].mergeSibling(children[i + 1], maxSize);\n children.splice(i + 1, 1);\n this.keys.splice(i + 1, 1);\n this.keys[i] = children[i].maxKey();\n return true;\n }\n }\n return false;\n }\n\n /**\n * Move children from `rhs` into this.\n * `rhs` must be part of this tree, and be removed from it after this call\n * (otherwise isShared for its children could be incorrect).\n */\n mergeSibling(rhs: BNode<K>, maxNodeSize: number) {\n // assert !this.isShared;\n const oldLength = this.keys.length;\n this.keys.push(...rhs.keys);\n const rhsChildren = (rhs as unknown as BNodeInternal<K>).children;\n this.children.push(...rhsChildren);\n\n if (rhs.isShared && !this.isShared) {\n // All children of a shared node are implicitly shared, and since their new\n // parent is not shared, they must now be explicitly marked as shared.\n for (let i = 0; i < rhsChildren.length; i++) {\n rhsChildren[i].isShared = true;\n }\n }\n\n // If our children are themselves almost empty due to a mass-delete,\n // they may need to be merged too (but only the oldLength-1 and its\n // right sibling should need this).\n this.tryMerge(oldLength - 1, maxNodeSize);\n }\n}\n\n// If key not found, returns i^failXor where i is the insertion index.\n// Callers that don't care whether there was a match will set failXor=0.\nfunction indexOf<K>(\n key: K,\n keys: K[],\n failXor: number,\n comparator: Comparator<K>,\n): number {\n let lo = 0;\n let hi = keys.length;\n let mid = hi >> 1;\n while (lo < hi) {\n const c = comparator(keys[mid], key);\n if (c < 0) {\n lo = mid + 1;\n } else if (c > 0) {\n // key < keys[mid]\n hi = mid;\n } else if (c === 0) {\n return mid;\n } else {\n // c is NaN or otherwise invalid\n if (key === key) {\n // at least the search key is not NaN\n return keys.length;\n }\n throw new Error('NaN was used as a key');\n }\n mid = (lo + hi) >> 1;\n }\n return mid ^ failXor;\n}\n\n// oxlint-disable-next-line @typescript-eslint/no-explicit-any\nconst emptyLeaf = new BNode<any>([]);\nemptyLeaf.isShared = true;\n"],"mappings":";;AAEA,IAAM,gBAAgB;AAItB,IAAa,WAAb,MAAa,SAAY;CACvB,QAAkB;CAClB,OAAe;CAEf;CAEA,YAAY,YAA2B,SAA+B;AACpE,OAAK,aAAa;AAClB,MAAI,QACF,MAAK,MAAM,OAAO,QAChB,MAAK,IAAI,IAAI;;;CAMnB,QAAQ;AACN,QAAA,OAAa;AACb,OAAK,OAAO;;CAGd,QAAQ;AACN,QAAA,KAAW,WAAW;EACtB,MAAM,MAAM,IAAI,SAAY,KAAK,WAAW;AAC5C,OAAA,OAAY,MAAA;AACZ,MAAI,OAAO,KAAK;AAChB,SAAO;;CAGT,IAAI,KAAuB;AACzB,SAAO,MAAA,KAAW,IAAI,KAAK,KAAK;;CAGlC,IAAI,KAAc;AAChB,MAAI,MAAA,KAAW,SAAU,OAAA,OAAa,MAAA,KAAW,OAAO;EACxD,MAAM,SAAS,MAAA,KAAW,IAAI,KAAK,KAAK;AACxC,MAAI,WAAW,KAAM,QAAO;AAE5B,QAAA,OAAa,IAAI,cAAiB,CAAC,MAAA,MAAY,OAAO,CAAC;AACvD,SAAO;;;;;;;;;CAUT,IAAI,KAAiB;AACnB,SAAO,MAAA,KAAW,IAAI,KAAK,KAAK;;;;;;;;CASlC,OAAO,KAAiB;AACtB,SAAO,MA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L,OAAI,QAAQ,IAEV,QAAO,KAAK;AAEd,SAAM,IAAI,MAAM,wBAAwB;;AAE1C,QAAO,KAAK,MAAO;;AAErB,QAAO,MAAM;;AAIf,IAAM,YAAY,IAAI,MAAW,EAAE,CAAC;AACpC,UAAU,WAAW"}
1
+ {"version":3,"file":"btree-set.js","names":["#root","#delete","#maxKey","#nodeQueue","#nodeIndex","#leaf","#i"],"sources":["../../../../shared/src/btree-set.ts"],"sourcesContent":["import {assert} from './asserts.ts';\n\nconst MAX_NODE_SIZE = 32;\n\ntype Comparator<K> = (a: K, b: K) => number;\n\nexport class BTreeSet<K> {\n #root: BNode<K> = emptyLeaf as BNode<K>;\n size: number = 0;\n\n readonly comparator: Comparator<K>;\n\n constructor(comparator: Comparator<K>, entries?: IterableIterator<K>) {\n this.comparator = comparator;\n if (entries) {\n for (const key of entries) {\n this.add(key);\n }\n }\n }\n\n /** Releases the tree so that its size is 0. */\n clear() {\n this.#root = emptyLeaf as BNode<K>;\n this.size = 0;\n }\n\n clone() {\n this.#root.isShared = true;\n const ret = new BTreeSet<K>(this.comparator);\n ret.#root = this.#root;\n ret.size = this.size;\n return ret;\n }\n\n get(key: K): K | undefined {\n return this.#root.get(key, this);\n }\n\n add(key: K): this {\n if (this.#root.isShared) this.#root = this.#root.clone();\n const result = this.#root.set(key, this);\n if (result === null) return this;\n // Root node has split, so create a new root node.\n this.#root = new BNodeInternal<K>([this.#root, result]);\n return this;\n }\n\n /**\n * Returns true if the key exists in the B+ tree, false if not.\n * Use get() for best performance; use has() if you need to\n * distinguish between \"undefined value\" and \"key not present\".\n * @param key Key to detect\n * @description Computational complexity: O(log size)\n */\n has(key: K): boolean {\n return this.#root.has(key, this);\n }\n\n /**\n * Removes a single key-value pair from the B+ tree.\n * @param key Key to find\n * @returns true if a pair was found and removed, false otherwise.\n * @description Computational complexity: O(log size)\n */\n delete(key: K): boolean {\n return this.#delete(key);\n }\n\n #delete(key: K): boolean {\n let root = this.#root;\n if (root.isShared) {\n this.#root = root = root.clone();\n }\n try {\n return root.delete(key, this);\n } finally {\n let isShared;\n while (root.keys.length <= 1 && root.isInternal()) {\n isShared ||= root.isShared;\n this.#root = root =\n root.keys.length === 0 ? emptyLeaf : root.children[0];\n }\n // If any ancestor of the new root was shared, the new root must also be shared\n if (isShared) {\n root.isShared = true;\n }\n }\n }\n\n keys(): IterableIterator<K> {\n return valuesFrom(this.#root, this.comparator, undefined, true);\n }\n\n values(): IterableIterator<K> {\n return valuesFrom(this.#root, this.comparator, undefined, true);\n }\n\n valuesFrom(lowestKey?: K, inclusive: boolean = true): IterableIterator<K> {\n return valuesFrom(this.#root, this.comparator, lowestKey, inclusive);\n }\n\n valuesReversed(): IterableIterator<K> {\n return valuesFromReversed(\n this.#maxKey(),\n this.#root,\n this.comparator,\n undefined,\n true,\n );\n }\n\n valuesFromReversed(\n highestKey?: K,\n inclusive: boolean = true,\n ): IterableIterator<K> {\n return valuesFromReversed(\n this.#maxKey(),\n this.#root,\n this.comparator,\n highestKey,\n inclusive,\n );\n }\n\n /** Gets the highest key in the tree. Complexity: O(1) */\n #maxKey(): K | undefined {\n return this.#root.maxKey();\n }\n\n [Symbol.iterator](): IterableIterator<K> {\n return this.keys();\n }\n\n /**\n * Builds a BTreeSet from a pre-sorted iterable in O(N) by constructing\n * the tree bottom-up. The caller must ensure entries are sorted by\n * `comparator`; violating this produces an invalid tree.\n */\n static fromSorted<K>(\n comparator: Comparator<K>,\n sortedEntries: Iterable<K>,\n ): BTreeSet<K> {\n const tree = new BTreeSet<K>(comparator);\n\n // Stream through entries, flushing a leaf node each time we fill MAX_NODE_SIZE keys.\n const leaves: BNode<K>[] = [];\n let currentKeys: K[] = [];\n let size = 0;\n\n for (const key of sortedEntries) {\n currentKeys.push(key);\n if (currentKeys.length === MAX_NODE_SIZE) {\n leaves.push(new BNode<K>(currentKeys));\n currentKeys = [];\n }\n size++;\n }\n\n if (currentKeys.length > 0) {\n leaves.push(new BNode<K>(currentKeys));\n }\n\n if (leaves.length === 0) return tree;\n\n tree.size = size;\n\n if (leaves.length === 1) {\n tree.#root = leaves[0];\n return tree;\n }\n\n // Build internal nodes bottom-up until a single root remains.\n let currentLevel: BNode<K>[] = leaves;\n while (currentLevel.length > 1) {\n const nextLevel: BNodeInternal<K>[] = [];\n for (let i = 0; i < currentLevel.length; i += MAX_NODE_SIZE) {\n nextLevel.push(\n new BNodeInternal<K>(currentLevel.slice(i, i + MAX_NODE_SIZE)),\n );\n }\n currentLevel = nextLevel;\n }\n\n tree.#root = currentLevel[0];\n return tree;\n }\n}\n\nclass BTreeForwardIterator<K> implements IterableIterator<K> {\n readonly #nodeQueue: BNode<K>[][];\n readonly #nodeIndex: number[];\n #leaf: BNode<K>;\n #i: number;\n\n constructor(\n nodeQueue: BNode<K>[][],\n nodeIndex: number[],\n leaf: BNode<K>,\n startI: number,\n ) {\n this.#nodeQueue = nodeQueue;\n this.#nodeIndex = nodeIndex;\n this.#leaf = leaf;\n this.#i = startI;\n }\n\n next(): IteratorResult<K> {\n for (;;) {\n if (++this.#i < this.#leaf.keys.length) {\n return {done: false, value: this.#leaf.keys[this.#i]};\n }\n\n let level = -1;\n for (;;) {\n if (++level >= this.#nodeQueue.length) {\n return {done: true, value: undefined as unknown as K};\n }\n if (++this.#nodeIndex[level] < this.#nodeQueue[level].length) {\n break;\n }\n }\n for (; level > 0; level--) {\n this.#nodeQueue[level - 1] = (\n this.#nodeQueue[level][this.#nodeIndex[level]] as BNodeInternal<K>\n ).children;\n this.#nodeIndex[level - 1] = 0;\n }\n this.#leaf = this.#nodeQueue[0][this.#nodeIndex[0]];\n this.#i = -1;\n }\n }\n\n [Symbol.iterator]() {\n return this;\n }\n}\n\nclass BTreeReverseIterator<K> implements IterableIterator<K> {\n readonly #nodeQueue: BNode<K>[][];\n readonly #nodeIndex: number[];\n #leaf: BNode<K>;\n #i: number;\n\n constructor(\n nodeQueue: BNode<K>[][],\n nodeIndex: number[],\n leaf: BNode<K>,\n startI: number,\n ) {\n this.#nodeQueue = nodeQueue;\n this.#nodeIndex = nodeIndex;\n this.#leaf = leaf;\n this.#i = startI;\n }\n\n next(): IteratorResult<K> {\n for (;;) {\n if (--this.#i >= 0) {\n return {done: false, value: this.#leaf.keys[this.#i]};\n }\n\n let level;\n // Advance to the next leaf node\n for (level = -1; ; ) {\n if (++level >= this.#nodeQueue.length) {\n return {done: true, value: undefined as unknown as K};\n }\n if (--this.#nodeIndex[level] >= 0) {\n break;\n }\n }\n for (; level > 0; level--) {\n this.#nodeQueue[level - 1] = (\n this.#nodeQueue[level][this.#nodeIndex[level]] as BNodeInternal<K>\n ).children;\n this.#nodeIndex[level - 1] = this.#nodeQueue[level - 1].length - 1;\n }\n this.#leaf = this.#nodeQueue[0][this.#nodeIndex[0]];\n this.#i = this.#leaf.keys.length;\n }\n }\n\n [Symbol.iterator]() {\n return this;\n }\n}\n\nfunction valuesFrom<K>(\n root: BNode<K>,\n comparator: Comparator<K>,\n lowestKey: K | undefined,\n inclusive: boolean,\n): IterableIterator<K> {\n const info = findPath(lowestKey, root, comparator);\n if (info === undefined) {\n return iterator<K>(() => ({done: true, value: undefined}));\n }\n\n let [nodeQueue, nodeIndex, leaf] = info;\n let i =\n lowestKey === undefined\n ? -1\n : indexOf(lowestKey, leaf.keys, 0, comparator) - 1;\n\n if (\n !inclusive &&\n lowestKey !== undefined &&\n // +1 because we did -1 above.\n i + 1 < leaf.keys.length &&\n comparator(leaf.keys[i + 1], lowestKey) === 0\n ) {\n i++;\n }\n\n return new BTreeForwardIterator(nodeQueue, nodeIndex, leaf, i);\n}\n\nfunction valuesFromReversed<K>(\n maxKey: K | undefined,\n root: BNode<K>,\n comparator: Comparator<K>,\n highestKey: K | undefined,\n inclusive: boolean,\n): IterableIterator<K> {\n if (highestKey === undefined) {\n highestKey = maxKey;\n if (highestKey === undefined) {\n return iterator<K>(() => ({done: true, value: undefined}));\n } // collection is empty\n }\n let [nodeQueue, nodeIndex, leaf] =\n findPath(highestKey, root, comparator) ||\n findPath(maxKey, root, comparator)!;\n assert(\n !nodeQueue[0] || leaf === nodeQueue[0][nodeIndex[0]],\n 'BTreeSet: leaf node mismatch in iteration',\n );\n let i = indexOf(highestKey, leaf.keys, 0, comparator);\n if (\n inclusive &&\n i < leaf.keys.length &&\n comparator(leaf.keys[i], highestKey) <= 0\n ) {\n i++;\n }\n\n return new BTreeReverseIterator(nodeQueue, nodeIndex, leaf, i);\n}\n\nfunction findPath<K>(\n key: K | undefined,\n root: BNode<K>,\n comparator: Comparator<K>,\n): [nodeQueue: BNode<K>[][], nodeIndex: number[], leaf: BNode<K>] | undefined {\n let nextNode = root;\n const nodeQueue: BNode<K>[][] = [];\n const nodeIndex: number[] = [];\n\n if (nextNode.isInternal()) {\n for (let d = 0; nextNode.isInternal(); d++) {\n nodeQueue[d] = nextNode.children;\n nodeIndex[d] =\n key === undefined ? 0 : indexOf(key, nextNode.keys, 0, comparator);\n if (nodeIndex[d] >= nodeQueue[d].length) return; // first key > maxKey()\n nextNode = nodeQueue[d][nodeIndex[d]];\n }\n nodeQueue.reverse();\n nodeIndex.reverse();\n }\n return [nodeQueue, nodeIndex, nextNode];\n}\n\nfunction iterator<T>(next: () => IteratorResult<T>): IterableIterator<T> {\n return {\n next,\n [Symbol.iterator]() {\n return this;\n },\n };\n}\n\n/** Leaf node / base class. **************************************************/\nclass BNode<K> {\n // If this is an internal node, _keys[i] is the highest key in children[i].\n keys: K[];\n // True if this node might be within multiple `BTree`s (or have multiple parents).\n // If so, it must be cloned before being mutated to avoid changing an unrelated tree.\n // This is transitive: if it's true, children are also shared even if `isShared!=true`\n // in those children. (Certain operations will propagate isShared=true to children.)\n isShared: true | undefined;\n\n constructor(keys: K[]) {\n this.keys = keys;\n this.isShared = undefined;\n }\n\n isInternal(): this is BNodeInternal<K> {\n return false;\n }\n\n maxKey() {\n // oxlint-disable-next-line typescript/no-non-null-assertion\n return this.keys.at(-1)!;\n }\n\n minKey(): K | undefined {\n return this.keys[0];\n }\n\n clone(): BNode<K> {\n return new BNode<K>(this.keys.slice(0));\n }\n\n get(key: K, tree: BTreeSet<K>): K | undefined {\n const i = indexOf(key, this.keys, -1, tree.comparator);\n return i < 0 ? undefined : this.keys[i];\n }\n\n has(key: K, tree: BTreeSet<K>): boolean {\n const i = indexOf(key, this.keys, -1, tree.comparator);\n return i >= 0 && i < this.keys.length;\n }\n\n set(key: K, tree: BTreeSet<K>): null | BNode<K> {\n let i = indexOf(key, this.keys, -1, tree.comparator);\n if (i < 0) {\n // key does not exist yet\n i = ~i;\n tree.size++;\n\n if (this.keys.length < MAX_NODE_SIZE) {\n this.keys.splice(i, 0, key);\n return null;\n }\n // This leaf node is full and must split\n const newRightSibling = this.splitOffRightSide();\n // oxlint-disable-next-line @typescript-eslint/no-this-alias\n let target: BNode<K> = this;\n if (i > this.keys.length) {\n i -= this.keys.length;\n target = newRightSibling;\n }\n // target.#insertInLeaf(i, key);\n target.keys.splice(i, 0, key);\n\n return newRightSibling;\n }\n\n // usually this is a no-op, but some users may wish to edit the key\n this.keys[i] = key;\n return null;\n }\n\n takeFromRight(rhs: BNode<K>) {\n this.keys.push(rhs.keys.shift()!);\n }\n\n takeFromLeft(lhs: BNode<K>) {\n this.keys.unshift(lhs.keys.pop()!);\n }\n\n splitOffRightSide(): BNode<K> {\n const half = this.keys.length >> 1;\n const keys = this.keys.splice(half);\n return new BNode<K>(keys);\n }\n\n delete(key: K, tree: BTreeSet<K>): boolean {\n const cmp = tree.comparator;\n const iLow = indexOf(key, this.keys, -1, cmp);\n const iHigh = iLow + 1;\n\n if (iLow < 0) {\n return false;\n }\n\n const {keys} = this;\n for (let i = iLow; i < iHigh; i++) {\n const key = keys[i];\n\n if (key !== keys[i] || this.isShared === true) {\n throw new Error('BTree illegally changed or cloned in delete');\n }\n\n this.keys.splice(i, 1);\n tree.size--;\n return true;\n }\n\n return false;\n }\n\n mergeSibling(rhs: BNode<K>, _: number) {\n this.keys.push(...rhs.keys);\n }\n}\n\n/** Internal node (non-leaf node) ********************************************/\nclass BNodeInternal<K> extends BNode<K> {\n // Note: conventionally B+ trees have one fewer key than the number of\n // children, but I find it easier to keep the array lengths equal: each\n // keys[i] caches the value of children[i].maxKey().\n children: BNode<K>[];\n\n /**\n * This does not mark `children` as shared, so it is the responsibility of the caller\n * to ensure children are either marked shared, or aren't included in another tree.\n */\n constructor(children: BNode<K>[], keys?: K[]) {\n if (!keys) {\n keys = [];\n for (let i = 0; i < children.length; i++) {\n keys[i] = children[i].maxKey();\n }\n }\n super(keys);\n this.children = children;\n }\n\n isInternal(): this is BNodeInternal<K> {\n return true;\n }\n\n clone(): BNode<K> {\n const children = this.children.slice(0);\n for (let i = 0; i < children.length; i++) {\n children[i].isShared = true;\n }\n return new BNodeInternal<K>(children, this.keys.slice(0));\n }\n\n minKey() {\n return this.children[0].minKey();\n }\n\n get(key: K, tree: BTreeSet<K>): K | undefined {\n const i = indexOf(key, this.keys, 0, tree.comparator);\n const {children} = this;\n return i < children.length ? children[i].get(key, tree) : undefined;\n }\n\n has(key: K, tree: BTreeSet<K>): boolean {\n const i = indexOf(key, this.keys, 0, tree.comparator);\n const {children} = this;\n return i < children.length ? children[i].has(key, tree) : false;\n }\n\n set(key: K, tree: BTreeSet<K>): null | BNode<K> {\n const c = this.children;\n const cmp = tree.comparator;\n let i = Math.min(indexOf(key, this.keys, 0, cmp), c.length - 1);\n let child = c[i];\n\n if (child.isShared) {\n c[i] = child = child.clone();\n }\n if (child.keys.length >= MAX_NODE_SIZE) {\n // child is full; inserting anything else will cause a split.\n // Shifting an item to the left or right sibling may avoid a split.\n // We can do a shift if the adjacent node is not full and if the\n // current key can still be placed in the same node after the shift.\n let other: BNode<K>;\n if (\n i > 0 &&\n (other = c[i - 1]).keys.length < MAX_NODE_SIZE &&\n cmp(child.keys[0], key) < 0\n ) {\n if (other.isShared) {\n c[i - 1] = other = other.clone();\n }\n other.takeFromRight(child);\n this.keys[i - 1] = other.maxKey();\n } else if (\n (other = c[i + 1]) !== undefined &&\n other.keys.length < MAX_NODE_SIZE &&\n cmp(child.maxKey(), key) < 0\n ) {\n if (other.isShared) c[i + 1] = other = other.clone();\n other.takeFromLeft(child);\n this.keys[i] = c[i].maxKey();\n }\n }\n\n const result = child.set(key, tree);\n this.keys[i] = child.maxKey();\n if (result === null) return null;\n\n // The child has split and `result` is a new right child... does it fit?\n if (this.keys.length < MAX_NODE_SIZE) {\n // yes\n this.insert(i + 1, result);\n return null;\n }\n // no, we must split also\n const newRightSibling = this.splitOffRightSide();\n // oxlint-disable-next-line @typescript-eslint/no-this-alias\n let target: BNodeInternal<K> = this;\n if (cmp(result.maxKey(), this.maxKey()) > 0) {\n target = newRightSibling;\n i -= this.keys.length;\n }\n target.insert(i + 1, result);\n return newRightSibling;\n }\n\n /**\n * Inserts `child` at index `i`.\n * This does not mark `child` as shared, so it is the responsibility of the caller\n * to ensure that either child is marked shared, or it is not included in another tree.\n */\n insert(i: number, child: BNode<K>) {\n this.children.splice(i, 0, child);\n this.keys.splice(i, 0, child.maxKey());\n }\n\n /**\n * Split this node.\n * Modifies this to remove the second half of the items, returning a separate node containing them.\n */\n splitOffRightSide() {\n const half = this.children.length >> 1;\n return new BNodeInternal<K>(\n this.children.splice(half),\n this.keys.splice(half),\n );\n }\n\n takeFromRight(rhs: BNode<K>) {\n this.keys.push(rhs.keys.shift()!);\n this.children.push((rhs as BNodeInternal<K>).children.shift()!);\n }\n\n takeFromLeft(lhs: BNode<K>) {\n this.keys.unshift(lhs.keys.pop()!);\n this.children.unshift((lhs as BNodeInternal<K>).children.pop()!);\n }\n\n delete(key: K, tree: BTreeSet<K>): boolean {\n const cmp = tree.comparator;\n const {keys} = this;\n const {children} = this;\n let iLow = indexOf(key, this.keys, 0, cmp);\n let i = iLow;\n const iHigh = Math.min(iLow, keys.length - 1);\n if (i <= iHigh) {\n try {\n if (children[i].isShared) {\n children[i] = children[i].clone();\n }\n const result = children[i].delete(key, tree);\n // Note: if children[i] is empty then keys[i]=undefined.\n // This is an invalid state, but it is fixed below.\n keys[i] = children[i].maxKey();\n return result;\n } finally {\n // Deletions may have occurred, so look for opportunities to merge nodes.\n const half = MAX_NODE_SIZE >> 1;\n if (iLow > 0) iLow--;\n for (i = iHigh; i >= iLow; i--) {\n if (children[i].keys.length <= half) {\n if (children[i].keys.length !== 0) {\n this.tryMerge(i, MAX_NODE_SIZE);\n } else {\n // child is empty! delete it!\n keys.splice(i, 1);\n children.splice(i, 1);\n }\n }\n }\n }\n }\n return false;\n }\n\n /** Merges child i with child i+1 if their combined size is not too large */\n tryMerge(i: number, maxSize: number): boolean {\n const {children} = this;\n if (i >= 0 && i + 1 < children.length) {\n if (children[i].keys.length + children[i + 1].keys.length <= maxSize) {\n if (\n children[i].isShared\n ) // cloned already UNLESS i is outside scan range\n {\n children[i] = children[i].clone();\n }\n children[i].mergeSibling(children[i + 1], maxSize);\n children.splice(i + 1, 1);\n this.keys.splice(i + 1, 1);\n this.keys[i] = children[i].maxKey();\n return true;\n }\n }\n return false;\n }\n\n /**\n * Move children from `rhs` into this.\n * `rhs` must be part of this tree, and be removed from it after this call\n * (otherwise isShared for its children could be incorrect).\n */\n mergeSibling(rhs: BNode<K>, maxNodeSize: number) {\n // assert !this.isShared;\n const oldLength = this.keys.length;\n this.keys.push(...rhs.keys);\n const rhsChildren = (rhs as unknown as BNodeInternal<K>).children;\n this.children.push(...rhsChildren);\n\n if (rhs.isShared && !this.isShared) {\n // All children of a shared node are implicitly shared, and since their new\n // parent is not shared, they must now be explicitly marked as shared.\n for (let i = 0; i < rhsChildren.length; i++) {\n rhsChildren[i].isShared = true;\n }\n }\n\n // If our children are themselves almost empty due to a mass-delete,\n // they may need to be merged too (but only the oldLength-1 and its\n // right sibling should need this).\n this.tryMerge(oldLength - 1, maxNodeSize);\n }\n}\n\n// If key not found, returns i^failXor where i is the insertion index.\n// Callers that don't care whether there was a match will set failXor=0.\nfunction indexOf<K>(\n key: K,\n keys: K[],\n failXor: number,\n comparator: Comparator<K>,\n): number {\n let lo = 0;\n let hi = keys.length;\n let mid = hi >> 1;\n while (lo < hi) {\n const c = comparator(keys[mid], key);\n if (c < 0) {\n lo = mid + 1;\n } else if (c > 0) {\n // key < keys[mid]\n hi = mid;\n } else if (c === 0) {\n return mid;\n } else {\n // c is NaN or otherwise invalid\n if (key === key) {\n // at least the search key is not NaN\n return keys.length;\n }\n throw new Error('NaN was used as a key');\n }\n mid = (lo + hi) >> 1;\n }\n return mid ^ failXor;\n}\n\n// oxlint-disable-next-line @typescript-eslint/no-explicit-any\nconst emptyLeaf = new BNode<any>([]);\nemptyLeaf.isShared = true;\n"],"mappings":";;AAEA,IAAM,gBAAgB;AAItB,IAAa,WAAb,MAAa,SAAY;CACvB,QAAkB;CAClB,OAAe;CAEf;CAEA,YAAY,YAA2B,SAA+B;AACpE,OAAK,aAAa;AAClB,MAAI,QACF,MAAK,MAAM,OAAO,QAChB,MAAK,IAAI,IAAI;;;CAMnB,QAAQ;AACN,QAAA,OAAa;AACb,OAAK,OAAO;;CAGd,QAAQ;AACN,QAAA,KAAW,WAAW;EACtB,MAAM,MAAM,IAAI,SAAY,KAAK,WAAW;AAC5C,OAAA,OAAY,MAAA;AACZ,MAAI,OAAO,KAAK;AAChB,SAAO;;CAGT,IAAI,KAAuB;AACzB,SAAO,MAAA,KAAW,IAAI,KAAK,KAAK;;CAGlC,IAAI,KAAc;AAChB,MAAI,MAAA,KAAW,SAAU,OAAA,OAAa,MAAA,KAAW,OAAO;EACxD,MAAM,SAAS,MAAA,KAAW,IAAI,KAAK,KAAK;AACxC,MAAI,WAAW,KAAM,QAAO;AAE5B,QAAA,OAAa,IAAI,cAAiB,CAAC,MAAA,MAAY,OAAO,CAAC;AACvD,SAAO;;;;;;;;;CAUT,IAAI,KAAiB;AACnB,SAAO,MAAA,KAAW,IAAI,KAAK,KAAK;;;;;;;;CASlC,OAAO,KAAiB;AACtB,SAAO,MAAA,OAAa,IAAI;;CAG1B,QAAQ,KAAiB;EACvB,IAAI,OAAO,MAAA;AACX,MAAI,KAAK,SACP,OAAA,O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AAG,EAAE;AAC1B,SAAK,KAAK,KAAK,SAAS,GAAG,QAAQ;AACnC,WAAO;;;AAGX,SAAO;;;;;;;CAQT,aAAa,KAAe,aAAqB;EAE/C,MAAM,YAAY,KAAK,KAAK;AAC5B,OAAK,KAAK,KAAK,GAAG,IAAI,KAAK;EAC3B,MAAM,cAAe,IAAoC;AACzD,OAAK,SAAS,KAAK,GAAG,YAAY;AAElC,MAAI,IAAI,YAAY,CAAC,KAAK,SAGxB,MAAK,IAAI,IAAI,GAAG,IAAI,YAAY,QAAQ,IACtC,aAAY,GAAG,WAAW;AAO9B,OAAK,SAAS,YAAY,GAAG,YAAY;;;AAM7C,SAAS,QACP,KACA,MACA,SACA,YACQ;CACR,IAAI,KAAK;CACT,IAAI,KAAK,KAAK;CACd,IAAI,MAAM,MAAM;AAChB,QAAO,KAAK,IAAI;EACd,MAAM,IAAI,WAAW,KAAK,MAAM,IAAI;AACpC,MAAI,IAAI,EACN,MAAK,MAAM;WACF,IAAI,EAEb,MAAK;WACI,MAAM,EACf,QAAO;OACF;AAEL,OAAI,QAAQ,IAEV,QAAO,KAAK;AAEd,SAAM,IAAI,MAAM,wBAAwB;;AAE1C,QAAO,KAAK,MAAO;;AAErB,QAAO,MAAM;;AAIf,IAAM,YAAY,IAAI,MAAW,EAAE,CAAC;AACpC,UAAU,WAAW"}
@@ -1,6 +1,6 @@
1
1
  var package_default = {
2
2
  name: "@rocicorp/zero",
3
- version: "1.4.0-canary.1",
3
+ version: "1.4.0-canary.2",
4
4
  description: "Zero is a web framework for serverless web development.",
5
5
  homepage: "https://zero.rocicorp.dev",
6
6
  bugs: { "url": "https://bugs.rocicorp.dev" },
@@ -1 +1 @@
1
- {"version":3,"file":"package.js","names":[],"sources":["../../package.json"],"sourcesContent":["{\n \"name\": \"@rocicorp/zero\",\n \"version\": \"1.4.0-canary.1\",\n \"description\": \"Zero is a web framework for serverless web development.\",\n \"homepage\": \"https://zero.rocicorp.dev\",\n \"bugs\": {\n \"url\": \"https://bugs.rocicorp.dev\"\n },\n \"license\": \"Apache-2.0\",\n \"author\": \"Rocicorp, Inc.\",\n \"repository\": {\n \"type\": \"git\",\n \"url\": \"git+https://github.com/rocicorp/mono.git\",\n \"directory\": \"packages/zero\"\n },\n \"bin\": {\n \"analyze-query\": \"./out/zero/src/analyze-query.js\",\n \"ast-to-zql\": \"./out/zero/src/ast-to-zql.js\",\n \"transform-query\": \"./out/zero/src/transform-query.js\",\n \"zero-build-schema\": \"./out/zero/src/build-schema.js\",\n \"zero-cache\": \"./out/zero/src/cli.js\",\n \"zero-cache-dev\": \"./out/zero/src/zero-cache-dev.js\",\n \"zero-deploy-permissions\": \"./out/zero/src/deploy-permissions.js\",\n \"zero-out\": \"./out/zero/src/zero-out.js\"\n },\n \"files\": [\n \"out\",\n \"!*.tsbuildinfo\"\n ],\n \"type\": \"module\",\n \"main\": \"out/zero/src/zero.js\",\n \"module\": \"out/zero/src/zero.js\",\n \"types\": \"out/zero/src/zero.d.ts\",\n \"exports\": {\n \".\": {\n \"types\": \"./out/zero/src/zero.d.ts\",\n \"default\": \"./out/zero/src/zero.js\"\n },\n \"./analyze\": {\n \"types\": \"./out/zero/src/analyze.d.ts\",\n \"default\": \"./out/zero/src/analyze.js\"\n },\n \"./bindings\": {\n \"types\": \"./out/zero/src/bindings.d.ts\",\n \"default\": \"./out/zero/src/bindings.js\"\n },\n \"./change-protocol/v0\": {\n \"types\": \"./out/zero/src/change-protocol/v0.d.ts\",\n \"default\": \"./out/zero/src/change-protocol/v0.js\"\n },\n \"./expo-sqlite\": {\n \"types\": \"./out/zero/src/expo-sqlite.d.ts\",\n \"default\": \"./out/zero/src/expo-sqlite.js\"\n },\n \"./op-sqlite\": {\n \"types\": \"./out/zero/src/op-sqlite.d.ts\",\n \"default\": \"./out/zero/src/op-sqlite.js\"\n },\n \"./pg\": {\n \"types\": \"./out/zero/src/pg.d.ts\",\n \"default\": \"./out/zero/src/pg.js\"\n },\n \"./react\": {\n \"types\": \"./out/zero/src/react.d.ts\",\n \"default\": \"./out/zero/src/react.js\"\n },\n \"./react-native\": {\n \"types\": \"./out/zero/src/react-native.d.ts\",\n \"default\": \"./out/zero/src/react-native.js\"\n },\n \"./server\": {\n \"types\": \"./out/zero/src/server.d.ts\",\n \"default\": \"./out/zero/src/server.js\"\n },\n \"./server/adapters/drizzle\": {\n \"types\": \"./out/zero/src/adapters/drizzle.d.ts\",\n \"default\": \"./out/zero/src/adapters/drizzle.js\"\n },\n \"./server/adapters/prisma\": {\n \"types\": \"./out/zero/src/adapters/prisma.d.ts\",\n \"default\": \"./out/zero/src/adapters/prisma.js\"\n },\n \"./server/adapters/pg\": {\n \"types\": \"./out/zero/src/adapters/pg.d.ts\",\n \"default\": \"./out/zero/src/adapters/pg.js\"\n },\n \"./server/adapters/postgresjs\": {\n \"types\": \"./out/zero/src/adapters/postgresjs.d.ts\",\n \"default\": \"./out/zero/src/adapters/postgresjs.js\"\n },\n \"./solid\": {\n \"types\": \"./out/zero/src/solid.d.ts\",\n \"default\": \"./out/zero/src/solid.js\"\n },\n \"./sqlite\": {\n \"types\": \"./out/zero/src/sqlite.d.ts\",\n \"default\": \"./out/zero/src/sqlite.js\"\n },\n \"./zqlite\": {\n \"types\": \"./out/zero/src/zqlite.d.ts\",\n \"default\": \"./out/zero/src/zqlite.js\"\n }\n },\n \"scripts\": {\n \"build\": \"node --experimental-strip-types --no-warnings tool/build.ts\",\n \"build:watch\": \"node --experimental-strip-types --no-warnings tool/build.ts --watch\",\n \"check-types\": \"tsc -p tsconfig.client.json && tsc -p tsconfig.server.json\",\n \"check-types:client:watch\": \"tsc -p tsconfig.client.json --watch\",\n \"check-types:server:watch\": \"tsc -p tsconfig.server.json --watch\",\n \"format\": \"oxfmt .\",\n \"check-format\": \"oxfmt --check .\",\n \"lint\": \"oxlint --type-aware src/\",\n \"docs\": \"node --experimental-strip-types --no-warnings tool/generate-docs.ts\",\n \"docs:server\": \"node --watch --experimental-strip-types --no-warnings tool/generate-docs.ts --server\",\n \"fmt\": \"oxfmt .\",\n \"check-fmt\": \"oxfmt --check .\"\n },\n \"dependencies\": {\n \"@badrap/valita\": \"0.3.11\",\n \"@databases/escape-identifier\": \"^1.0.3\",\n \"@databases/sql\": \"^3.3.0\",\n \"@dotenvx/dotenvx\": \"^1.39.0\",\n \"@drdgvhbh/postgres-error-codes\": \"^0.0.6\",\n \"@fastify/cors\": \"^10.0.0\",\n \"@fastify/websocket\": \"^11.0.0\",\n \"@google-cloud/precise-date\": \"^4.0.0\",\n \"@opentelemetry/api\": \"^1.9.0\",\n \"@opentelemetry/api-logs\": \"^0.203.0\",\n \"@opentelemetry/auto-instrumentations-node\": \"^0.62.0\",\n \"@opentelemetry/exporter-metrics-otlp-http\": \"^0.203.0\",\n \"@opentelemetry/resources\": \"^2.0.1\",\n \"@opentelemetry/sdk-metrics\": \"^2.0.1\",\n \"@opentelemetry/sdk-node\": \"^0.203.0\",\n \"@opentelemetry/sdk-trace-node\": \"^2.0.1\",\n \"@postgresql-typed/oids\": \"^0.2.0\",\n \"@rocicorp/lock\": \"^1.0.4\",\n \"@rocicorp/logger\": \"^5.4.0\",\n \"@rocicorp/resolver\": \"^1.0.2\",\n \"@rocicorp/zero-sqlite3\": \"^1.0.17\",\n \"@standard-schema/spec\": \"^1.0.0\",\n \"@types/basic-auth\": \"^1.1.8\",\n \"@types/ws\": \"^8.5.12\",\n \"basic-auth\": \"^2.0.1\",\n \"chalk-template\": \"^1.1.0\",\n \"chokidar\": \"^4.0.1\",\n \"cloudevents\": \"^10.0.0\",\n \"command-line-args\": \"^6.0.1\",\n \"command-line-usage\": \"^7.0.3\",\n \"compare-utf8\": \"^0.2.0\",\n \"defu\": \"^6.1.4\",\n \"eventemitter3\": \"^5.0.1\",\n \"fastify\": \"^5.0.0\",\n \"is-in-subnet\": \"^4.0.1\",\n \"jose\": \"^5.9.3\",\n \"js-xxhash\": \"^4.0.0\",\n \"json-custom-numbers\": \"^3.1.1\",\n \"kasi\": \"^1.1.0\",\n \"nanoid\": \"^5.1.2\",\n \"oxfmt\": \"^0.45.0\",\n \"parse-prometheus-text-format\": \"^1.1.1\",\n \"pg-format\": \"npm:pg-format-fix@^1.0.5\",\n \"postgres\": \"3.4.7\",\n \"semver\": \"^7.5.4\",\n \"tsx\": \"^4.21.0\",\n \"url-pattern\": \"^1.0.3\",\n \"urlpattern-polyfill\": \"^10.1.0\",\n \"ws\": \"^8.18.1\"\n },\n \"devDependencies\": {\n \"@op-engineering/op-sqlite\": \">=15\",\n \"@vitest/runner\": \"4.1.3\",\n \"analyze-query\": \"0.0.0\",\n \"ast-to-zql\": \"0.0.0\",\n \"expo-sqlite\": \">=15\",\n \"replicache\": \"15.2.1\",\n \"shared\": \"0.0.0\",\n \"syncpack\": \"^14.3.0\",\n \"typedoc\": \"^0.28.17\",\n \"typedoc-plugin-markdown\": \"^4.10.0\",\n \"typescript\": \"~6.0.2\",\n \"vite\": \"8.0.3\",\n \"vitest\": \"4.1.3\",\n \"zero-cache\": \"0.0.0\",\n \"zero-client\": \"0.0.0\",\n \"zero-pg\": \"0.0.0\",\n \"zero-protocol\": \"0.0.0\",\n \"zero-react\": \"0.0.0\",\n \"zero-server\": \"0.0.0\",\n \"zero-solid\": \"0.0.0\",\n \"zqlite\": \"0.0.0\"\n },\n \"peerDependencies\": {\n \"@op-engineering/op-sqlite\": \">=15\",\n \"expo-sqlite\": \">=15\"\n },\n \"peerDependenciesMeta\": {\n \"expo-sqlite\": {\n \"optional\": true\n },\n \"@op-engineering/op-sqlite\": {\n \"optional\": true\n }\n },\n \"engines\": {\n \"node\": \">=22\"\n }\n}"],"mappings":""}
1
+ {"version":3,"file":"package.js","names":[],"sources":["../../package.json"],"sourcesContent":["{\n \"name\": \"@rocicorp/zero\",\n \"version\": \"1.4.0-canary.2\",\n \"description\": \"Zero is a web framework for serverless web development.\",\n \"homepage\": \"https://zero.rocicorp.dev\",\n \"bugs\": {\n \"url\": \"https://bugs.rocicorp.dev\"\n },\n \"license\": \"Apache-2.0\",\n \"author\": \"Rocicorp, Inc.\",\n \"repository\": {\n \"type\": \"git\",\n \"url\": \"git+https://github.com/rocicorp/mono.git\",\n \"directory\": \"packages/zero\"\n },\n \"bin\": {\n \"analyze-query\": \"./out/zero/src/analyze-query.js\",\n \"ast-to-zql\": \"./out/zero/src/ast-to-zql.js\",\n \"transform-query\": \"./out/zero/src/transform-query.js\",\n \"zero-build-schema\": \"./out/zero/src/build-schema.js\",\n \"zero-cache\": \"./out/zero/src/cli.js\",\n \"zero-cache-dev\": \"./out/zero/src/zero-cache-dev.js\",\n \"zero-deploy-permissions\": \"./out/zero/src/deploy-permissions.js\",\n \"zero-out\": \"./out/zero/src/zero-out.js\"\n },\n \"files\": [\n \"out\",\n \"!*.tsbuildinfo\"\n ],\n \"type\": \"module\",\n \"main\": \"out/zero/src/zero.js\",\n \"module\": \"out/zero/src/zero.js\",\n \"types\": \"out/zero/src/zero.d.ts\",\n \"exports\": {\n \".\": {\n \"types\": \"./out/zero/src/zero.d.ts\",\n \"default\": \"./out/zero/src/zero.js\"\n },\n \"./analyze\": {\n \"types\": \"./out/zero/src/analyze.d.ts\",\n \"default\": \"./out/zero/src/analyze.js\"\n },\n \"./bindings\": {\n \"types\": \"./out/zero/src/bindings.d.ts\",\n \"default\": \"./out/zero/src/bindings.js\"\n },\n \"./change-protocol/v0\": {\n \"types\": \"./out/zero/src/change-protocol/v0.d.ts\",\n \"default\": \"./out/zero/src/change-protocol/v0.js\"\n },\n \"./expo-sqlite\": {\n \"types\": \"./out/zero/src/expo-sqlite.d.ts\",\n \"default\": \"./out/zero/src/expo-sqlite.js\"\n },\n \"./op-sqlite\": {\n \"types\": \"./out/zero/src/op-sqlite.d.ts\",\n \"default\": \"./out/zero/src/op-sqlite.js\"\n },\n \"./pg\": {\n \"types\": \"./out/zero/src/pg.d.ts\",\n \"default\": \"./out/zero/src/pg.js\"\n },\n \"./react\": {\n \"types\": \"./out/zero/src/react.d.ts\",\n \"default\": \"./out/zero/src/react.js\"\n },\n \"./react-native\": {\n \"types\": \"./out/zero/src/react-native.d.ts\",\n \"default\": \"./out/zero/src/react-native.js\"\n },\n \"./server\": {\n \"types\": \"./out/zero/src/server.d.ts\",\n \"default\": \"./out/zero/src/server.js\"\n },\n \"./server/adapters/drizzle\": {\n \"types\": \"./out/zero/src/adapters/drizzle.d.ts\",\n \"default\": \"./out/zero/src/adapters/drizzle.js\"\n },\n \"./server/adapters/prisma\": {\n \"types\": \"./out/zero/src/adapters/prisma.d.ts\",\n \"default\": \"./out/zero/src/adapters/prisma.js\"\n },\n \"./server/adapters/pg\": {\n \"types\": \"./out/zero/src/adapters/pg.d.ts\",\n \"default\": \"./out/zero/src/adapters/pg.js\"\n },\n \"./server/adapters/postgresjs\": {\n \"types\": \"./out/zero/src/adapters/postgresjs.d.ts\",\n \"default\": \"./out/zero/src/adapters/postgresjs.js\"\n },\n \"./solid\": {\n \"types\": \"./out/zero/src/solid.d.ts\",\n \"default\": \"./out/zero/src/solid.js\"\n },\n \"./sqlite\": {\n \"types\": \"./out/zero/src/sqlite.d.ts\",\n \"default\": \"./out/zero/src/sqlite.js\"\n },\n \"./zqlite\": {\n \"types\": \"./out/zero/src/zqlite.d.ts\",\n \"default\": \"./out/zero/src/zqlite.js\"\n }\n },\n \"scripts\": {\n \"build\": \"node --experimental-strip-types --no-warnings tool/build.ts\",\n \"build:watch\": \"node --experimental-strip-types --no-warnings tool/build.ts --watch\",\n \"check-types\": \"tsc -p tsconfig.client.json && tsc -p tsconfig.server.json\",\n \"check-types:client:watch\": \"tsc -p tsconfig.client.json --watch\",\n \"check-types:server:watch\": \"tsc -p tsconfig.server.json --watch\",\n \"format\": \"oxfmt .\",\n \"check-format\": \"oxfmt --check .\",\n \"lint\": \"oxlint --type-aware src/\",\n \"docs\": \"node --experimental-strip-types --no-warnings tool/generate-docs.ts\",\n \"docs:server\": \"node --watch --experimental-strip-types --no-warnings tool/generate-docs.ts --server\",\n \"fmt\": \"oxfmt .\",\n \"check-fmt\": \"oxfmt --check .\"\n },\n \"dependencies\": {\n \"@badrap/valita\": \"0.3.11\",\n \"@databases/escape-identifier\": \"^1.0.3\",\n \"@databases/sql\": \"^3.3.0\",\n \"@dotenvx/dotenvx\": \"^1.39.0\",\n \"@drdgvhbh/postgres-error-codes\": \"^0.0.6\",\n \"@fastify/cors\": \"^10.0.0\",\n \"@fastify/websocket\": \"^11.0.0\",\n \"@google-cloud/precise-date\": \"^4.0.0\",\n \"@opentelemetry/api\": \"^1.9.0\",\n \"@opentelemetry/api-logs\": \"^0.203.0\",\n \"@opentelemetry/auto-instrumentations-node\": \"^0.62.0\",\n \"@opentelemetry/exporter-metrics-otlp-http\": \"^0.203.0\",\n \"@opentelemetry/resources\": \"^2.0.1\",\n \"@opentelemetry/sdk-metrics\": \"^2.0.1\",\n \"@opentelemetry/sdk-node\": \"^0.203.0\",\n \"@opentelemetry/sdk-trace-node\": \"^2.0.1\",\n \"@postgresql-typed/oids\": \"^0.2.0\",\n \"@rocicorp/lock\": \"^1.0.4\",\n \"@rocicorp/logger\": \"^5.4.0\",\n \"@rocicorp/resolver\": \"^1.0.2\",\n \"@rocicorp/zero-sqlite3\": \"^1.0.17\",\n \"@standard-schema/spec\": \"^1.0.0\",\n \"@types/basic-auth\": \"^1.1.8\",\n \"@types/ws\": \"^8.5.12\",\n \"basic-auth\": \"^2.0.1\",\n \"chalk-template\": \"^1.1.0\",\n \"chokidar\": \"^4.0.1\",\n \"cloudevents\": \"^10.0.0\",\n \"command-line-args\": \"^6.0.1\",\n \"command-line-usage\": \"^7.0.3\",\n \"compare-utf8\": \"^0.2.0\",\n \"defu\": \"^6.1.4\",\n \"eventemitter3\": \"^5.0.1\",\n \"fastify\": \"^5.0.0\",\n \"is-in-subnet\": \"^4.0.1\",\n \"jose\": \"^5.9.3\",\n \"js-xxhash\": \"^4.0.0\",\n \"json-custom-numbers\": \"^3.1.1\",\n \"kasi\": \"^1.1.0\",\n \"nanoid\": \"^5.1.2\",\n \"oxfmt\": \"^0.45.0\",\n \"parse-prometheus-text-format\": \"^1.1.1\",\n \"pg-format\": \"npm:pg-format-fix@^1.0.5\",\n \"postgres\": \"3.4.7\",\n \"semver\": \"^7.5.4\",\n \"tsx\": \"^4.21.0\",\n \"url-pattern\": \"^1.0.3\",\n \"urlpattern-polyfill\": \"^10.1.0\",\n \"ws\": \"^8.18.1\"\n },\n \"devDependencies\": {\n \"@op-engineering/op-sqlite\": \">=15\",\n \"@vitest/runner\": \"4.1.3\",\n \"analyze-query\": \"0.0.0\",\n \"ast-to-zql\": \"0.0.0\",\n \"expo-sqlite\": \">=15\",\n \"replicache\": \"15.2.1\",\n \"shared\": \"0.0.0\",\n \"syncpack\": \"^14.3.0\",\n \"typedoc\": \"^0.28.17\",\n \"typedoc-plugin-markdown\": \"^4.10.0\",\n \"typescript\": \"~6.0.2\",\n \"vite\": \"8.0.3\",\n \"vitest\": \"4.1.3\",\n \"zero-cache\": \"0.0.0\",\n \"zero-client\": \"0.0.0\",\n \"zero-pg\": \"0.0.0\",\n \"zero-protocol\": \"0.0.0\",\n \"zero-react\": \"0.0.0\",\n \"zero-server\": \"0.0.0\",\n \"zero-solid\": \"0.0.0\",\n \"zqlite\": \"0.0.0\"\n },\n \"peerDependencies\": {\n \"@op-engineering/op-sqlite\": \">=15\",\n \"expo-sqlite\": \">=15\"\n },\n \"peerDependenciesMeta\": {\n \"expo-sqlite\": {\n \"optional\": true\n },\n \"@op-engineering/op-sqlite\": {\n \"optional\": true\n }\n },\n \"engines\": {\n \"node\": \">=22\"\n }\n}"],"mappings":""}
@@ -519,6 +519,24 @@ export declare const zeroOptions: {
519
519
  desc: string[];
520
520
  };
521
521
  };
522
+ shadowSync: {
523
+ enabled: {
524
+ type: v.Type<boolean>;
525
+ desc: string[];
526
+ };
527
+ intervalHours: {
528
+ type: v.Type<number>;
529
+ desc: string[];
530
+ };
531
+ sampleRate: {
532
+ type: v.Type<number>;
533
+ desc: string[];
534
+ };
535
+ maxRowsPerTable: {
536
+ type: v.Type<number>;
537
+ desc: string[];
538
+ };
539
+ };
522
540
  /** @deprecated */
523
541
  targetClientRowCount: {
524
542
  type: v.Type<number>;
@@ -1 +1 @@
1
- {"version":3,"file":"zero-config.d.ts","sourceRoot":"","sources":["../../../../../zero-cache/src/config/zero-config.ts"],"names":[],"mappings":"AAAA;;GAEG;AAGH,OAAO,KAAK,EAAC,UAAU,EAAC,MAAM,kBAAkB,CAAC;AAEjD,OAAO,EAGL,KAAK,MAAM,EACX,KAAK,YAAY,EAClB,MAAM,gCAAgC,CAAC;AACxC,OAAO,KAAK,CAAC,MAAM,+BAA+B,CAAC;AAUnD,OAAO,EAGL,KAAK,oBAAoB,EAC1B,MAAM,gBAAgB,CAAC;AACxB,YAAY,EAAC,SAAS,EAAC,MAAM,kCAAkC,CAAC;AAEhE,eAAO,MAAM,mBAAmB,UAAU,CAAC;AAE3C,eAAO,MAAM,UAAU;;;;;;;;;CA+CtB,CAAC;AAEF,eAAO,MAAM,YAAY;;;;;;;;;;CAwBxB,CAAC;AAEF,QAAA,MAAM,cAAc;;;;;;;;;CAmBnB,CAAC;AAEF,MAAM,MAAM,cAAc,GAAG,MAAM,CAAC,OAAO,cAAc,CAAC,CAAC;AAE3D,QAAA,MAAM,oBAAoB;;;;;;;;;CAczB,CAAC;AAEF,MAAM,MAAM,SAAS,GAAG,MAAM,CAAC,OAAO,oBAAoB,CAAC,CAAC;AAE5D,QAAA,MAAM,WAAW;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CA8DhB,CAAC;AAuGF,MAAM,MAAM,UAAU,GAAG,MAAM,CAAC,OAAO,WAAW,CAAC,CAAC;AAEpD,+DAA+D;AAC/D,MAAM,MAAM,mBAAmB,GAAG,IAAI,CACpC,UAAU,EACV,KAAK,GAAG,SAAS,GAAG,QAAQ,GAAG,QAAQ,GAAG,UAAU,CACrD,CAAC;AAKF,eAAO,MAAM,WAAW;;;;;;;;;;;;;;;;;;;;;;;;IAsDtB,kBAAkB;;;;;;;;;;;;;;;;;;;;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;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;QAuLhB,kBAAkB;;;;;;QASlB,kBAAkB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;IAkZpB,kBAAkB;;;;;;;;;;;;;;;;;;;;;;;;;;;;CAgEnB,CAAC;AAEF,MAAM,MAAM,UAAU,GAAG,MAAM,CAAC,OAAO,WAAW,CAAC,CAAC;AAIpD,wBAAgB,aAAa,CAC3B,IAAI,GAAE,IAAI,CAAC,YAAY,EAAE,eAAe,CAAM,GAC7C,UAAU,CAaZ;AAED;;;GAGG;AACH,wBAAgB,uBAAuB,CACrC,IAAI,GAAE,IAAI,CAAC,YAAY,EAAE,eAAe,CAAM,GAC7C,oBAAoB,CAItB;AAED;;;GAGG;AACH,wBAAgB,gBAAgB,CAC9B,MAAM,EAAE,IAAI,CAAC,UAAU,EAAE,eAAe,CAAC,GAAG,SAAS,GACpD,MAAM,CAER;AAED,wBAAgB,oBAAoB,CAClC,EAAE,EAAE,UAAU,EACd,MAAM,EAAE,IAAI,CAAC,oBAAoB,EAAE,eAAe,CAAC,EACnD,QAAQ,EAAE,MAAM,GAAG,SAAS,WAwC7B;AAYD,wBAAgB,kBAAkB,SAEjC"}
@@ -725,12 +725,44 @@ var zeroOptions = {
725
725
  textCopy: {
726
726
  type: valita_exports.boolean().default(false),
727
727
  desc: [
728
- `Use text-format COPY instead of binary COPY for the initial sync.`,
729
- `This is slower but can work around issues with binary encoding of`,
730
- `certain data types.`
728
+ `Use text-format COPY instead of binary COPY for initial sync and`,
729
+ `backfill streaming. This is slower but can work around issues with`,
730
+ `binary encoding of certain data types.`
731
731
  ]
732
732
  }
733
733
  },
734
+ shadowSync: {
735
+ enabled: {
736
+ type: valita_exports.boolean().default(false),
737
+ desc: [
738
+ `Periodically exercises the initial-sync code path against a sample of`,
739
+ `rows from every published table, writing to a throwaway SQLite database.`,
740
+ `This acts as a canary: if the real initial-sync path ever breaks (schema`,
741
+ `drift, PG version quirks, etc.), the shadow run fails before a customer`,
742
+ `actually needs a full reset.`
743
+ ]
744
+ },
745
+ intervalHours: {
746
+ type: valita_exports.number().default(24),
747
+ desc: [
748
+ `The interval between shadow initial-sync runs, in hours. The first run`,
749
+ `is additionally staggered by a random fraction of this interval so that`,
750
+ `a fleet restart does not cause all tasks to canary simultaneously.`
751
+ ]
752
+ },
753
+ sampleRate: {
754
+ type: valita_exports.number().default(.1),
755
+ desc: [
756
+ `The BERNOULLI sampling rate for each table (0 < rate <= 1). A value of`,
757
+ `1 disables sampling and copies all rows (still subject to`,
758
+ `{bold max-rows-per-table}).`
759
+ ]
760
+ },
761
+ maxRowsPerTable: {
762
+ type: valita_exports.number().default(1e4),
763
+ desc: [`The hard upper bound on rows copied per table per shadow run. Guards`, `against unexpectedly large tables consuming disk / upstream bandwidth.`]
764
+ }
765
+ },
734
766
  targetClientRowCount: {
735
767
  type: valita_exports.number().default(2e4),
736
768
  deprecated: [
@@ -1 +1 @@
1
- {"version":3,"file":"zero-config.js","names":[],"sources":["../../../../../zero-cache/src/config/zero-config.ts"],"sourcesContent":["/**\n * These types represent the _compiled_ config whereas `define-config` types represent the _source_ config.\n */\n\nimport {timingSafeEqual} from 'node:crypto';\nimport type {LogContext} from '@rocicorp/logger';\nimport {logOptions} from '../../../otel/src/log-options.ts';\nimport {\n flagToEnv,\n parseOptions,\n type Config,\n type ParseOptions,\n} from '../../../shared/src/options.ts';\nimport * as v from '../../../shared/src/valita.ts';\n// @circular-dep-ignore - importing package.json for version info only\nimport packageJson from '../../../zero/package.json' with {type: 'json'};\nimport {runtimeDebugFlags} from '../../../zql/src/builder/debug-delegate.ts';\nimport {singleProcessMode} from '../types/processes.ts';\nimport {\n ALLOWED_APP_ID_CHARACTERS,\n INVALID_APP_ID_MESSAGE,\n} from '../types/shards.ts';\nimport {DEFAULT_PREFERRED_PREFIXES} from './network.ts';\nimport {\n assertNormalized,\n isDevelopmentMode,\n type NormalizedZeroConfig,\n} from './normalize.ts';\nexport type {LogConfig} from '../../../otel/src/log-options.ts';\n\nexport const ZERO_ENV_VAR_PREFIX = 'ZERO_';\n\nexport const appOptions = {\n id: {\n type: v\n .string()\n .default('zero')\n .assert(id => ALLOWED_APP_ID_CHARACTERS.test(id), INVALID_APP_ID_MESSAGE),\n desc: [\n 'Unique identifier for the app.',\n '',\n 'Multiple zero-cache apps can run on a single upstream database, each of which',\n 'is isolated from the others, with its own permissions, sharding (future feature),',\n 'and change/cvr databases.',\n '',\n 'The metadata of an app is stored in an upstream schema with the same name,',\n 'e.g. \"zero\", and the metadata for each app shard, e.g. client and mutation',\n 'ids, is stored in the \"\\\\{app-id\\\\}_\\\\{#\\\\}\" schema. (Currently there is only a single',\n '\"0\" shard, but this will change with sharding).',\n '',\n 'The CVR and Change data are managed in schemas named \"\\\\{app-id\\\\}_\\\\{shard-num\\\\}/cvr\"',\n 'and \"\\\\{app-id\\\\}_\\\\{shard-num\\\\}/cdc\", respectively, allowing multiple apps and shards',\n 'to share the same database instance (e.g. a Postgres \"cluster\") for CVR and Change management.',\n '',\n 'Due to constraints on replication slot names, an App ID may only consist of',\n 'lower-case letters, numbers, and the underscore character.',\n '',\n 'Note that this option is used by both {bold zero-cache} and {bold zero-deploy-permissions}.',\n ],\n },\n\n publications: {\n type: v.array(v.string()).optional(() => []),\n desc: [\n `Postgres {bold PUBLICATION}s that define the tables and columns to`,\n `replicate. Publication names may not begin with an underscore,`,\n `as zero reserves that prefix for internal use.`,\n ``,\n `If unspecified, zero-cache will create and use an internal publication that`,\n `publishes all tables in the {bold public} schema, i.e.:`,\n ``,\n `CREATE PUBLICATION _\\\\{app-id\\\\}_public_0 FOR TABLES IN SCHEMA public;`,\n ``,\n `Note that changing the set of publications will result in resyncing the replica,`,\n `which may involve downtime (replication lag) while the new replica is initializing.`,\n `To change the set of publications without disrupting an existing app, a new app`,\n `should be created.`,\n ],\n },\n};\n\nexport const shardOptions = {\n id: {\n type: v\n .string()\n .assert(() => {\n throw new Error(\n `ZERO_SHARD_ID is no longer an option. Please use ZERO_APP_ID instead.`,\n // TODO: Link to release / migration notes?\n );\n })\n .optional(),\n hidden: true,\n },\n\n num: {\n type: v.number().default(0),\n desc: [\n `The shard number (from 0 to NUM_SHARDS) of the App. zero will eventually`,\n `support data sharding as a first-class primitive; until then, deploying`,\n `multiple shard-nums creates functionally identical shards. Until sharding is`,\n `actually meaningful, this flag is hidden but available for testing.`,\n ],\n hidden: true,\n },\n};\n\nconst replicaOptions = {\n file: {\n type: v.string().default('zero.db'),\n desc: [\n `File path to the SQLite replica that zero-cache maintains.`,\n `This can be lost, but if it is, zero-cache will have to re-replicate next`,\n `time it starts up.`,\n ],\n },\n\n vacuumIntervalHours: {\n type: v.number().optional(),\n desc: [\n `Performs a VACUUM at server startup if the specified number of hours has elapsed`,\n `since the last VACUUM (or initial-sync). The VACUUM operation is heavyweight`,\n `and requires double the size of the db in disk space. If unspecified, VACUUM`,\n `operations are not performed.`,\n ],\n },\n};\n\nexport type ReplicaOptions = Config<typeof replicaOptions>;\n\nconst perUserMutationLimit = {\n max: {\n type: v.number().optional(),\n desc: [\n `The maximum mutations per user within the specified {bold windowMs}.`,\n `If unset, no rate limiting is enforced.`,\n ],\n },\n windowMs: {\n type: v.number().default(60_000),\n desc: [\n `The sliding window over which the {bold perUserMutationLimitMax} is enforced.`,\n ],\n },\n};\n\nexport type RateLimit = Config<typeof perUserMutationLimit>;\n\nconst authOptions = {\n jwk: {\n type: v.string().optional(),\n desc: [\n `A public key in JWK format used to verify JWTs. Only one of {bold jwk}, {bold jwksUrl} and {bold secret} may be set.`,\n ],\n deprecated: [\n `Use cookie-based authentication or an auth token instead - see https://zero.rocicorp.dev/docs/auth.`,\n ],\n },\n jwksUrl: {\n type: v.string().optional(),\n desc: [\n `A URL that returns a JWK set used to verify JWTs. Only one of {bold jwk}, {bold jwksUrl} and {bold secret} may be set.`,\n ],\n deprecated: [\n `Use cookie-based authentication or an auth token instead - see https://zero.rocicorp.dev/docs/auth.`,\n ],\n },\n secret: {\n type: v.string().optional(),\n desc: [\n `A symmetric key used to verify JWTs. Only one of {bold jwk}, {bold jwksUrl} and {bold secret} may be set.`,\n ],\n deprecated: [\n `Use cookie-based authentication or an auth token instead - see https://zero.rocicorp.dev/docs/auth.`,\n ],\n },\n issuer: {\n type: v.string().optional(),\n desc: [\n `Expected issuer ({bold iss} claim) for JWT validation.`,\n `If set, tokens with a different or missing issuer will be rejected.`,\n ],\n deprecated: [\n `Use cookie-based authentication or an auth token instead - see https://zero.rocicorp.dev/docs/auth.`,\n ],\n },\n audience: {\n type: v.string().optional(),\n desc: [\n `Expected audience ({bold aud} claim) for JWT validation.`,\n `If set, tokens with a different or missing audience will be rejected.`,\n ],\n deprecated: [\n `Use cookie-based authentication or an auth token instead - see https://zero.rocicorp.dev/docs/auth.`,\n ],\n },\n revalidateIntervalSeconds: {\n type: v.number().optional(),\n desc: [\n `The interval in seconds between periodic /query auth revalidation for validated connections.`,\n `If unset, periodic auth revalidation is disabled.`,\n ],\n },\n retransformIntervalSeconds: {\n type: v.number().optional(),\n desc: [\n `The interval in seconds between periodic shared /query retransform work for a client group.`,\n `If unset, periodic shared retransform is disabled.`,\n ],\n },\n};\n\nconst makeDeprecationMessage = (flag: string) =>\n `Use {bold ${flagToEnv(ZERO_ENV_VAR_PREFIX, flag)}} (or {bold --${flag}}) instead.`;\n\nconst makeMutatorQueryOptions = (\n replacement: 'mutate' | 'query' | undefined,\n suffix: string,\n) => ({\n url: {\n type: v.array(v.string()).optional(), // optional until we remove CRUD mutations\n desc: [\n `The URL of the API server to which zero-cache will ${suffix}.`,\n ``,\n `{bold IMPORTANT:} URLs are matched using {bold URLPattern}, a standard Web API.`,\n ``,\n `{bold Pattern Syntax:}`,\n ` URLPattern uses a simple and intuitive syntax similar to Express routes.`,\n ` Wildcards and named parameters make it easy to match multiple URLs.`,\n ``,\n `{bold Basic Examples:}`,\n ` Exact URL match:`,\n ` \"https://api.example.com/mutate\"`,\n ` `,\n ` Any subdomain using wildcard:`,\n ` \"https://*.example.com/mutate\"`,\n ` `,\n ` Multiple subdomain levels:`,\n ` \"https://*.*.example.com/mutate\"`,\n ` `,\n ` Any path under a domain:`,\n ` \"https://api.example.com/*\"`,\n ` `,\n ` Named path parameters:`,\n ` \"https://api.example.com/:version/mutate\"`,\n ` ↳ Matches \"https://api.example.com/v1/mutate\", \"https://api.example.com/v2/mutate\", etc.`,\n ``,\n `{bold Advanced Patterns:}`,\n ` Optional path segments:`,\n ` \"https://api.example.com/:path?\"`,\n ` `,\n ` Regex in segments (for specific patterns):`,\n ` \"https://api.example.com/:version(v\\\\\\\\d+)/mutate\"`,\n ` ↳ Matches only \"v\" followed by digits`,\n ``,\n `{bold Multiple patterns:}`,\n ` [\"https://api1.example.com/mutate\", \"https://api2.example.com/mutate\"]`,\n ``,\n `{bold Note:} Query parameters and URL fragments (#) are automatically ignored during matching.`,\n ``,\n `For full URLPattern syntax, see: https://developer.mozilla.org/en-US/docs/Web/API/URLPattern`,\n ],\n ...(replacement\n ? {deprecated: [makeDeprecationMessage(`${replacement}-url`)]}\n : {}),\n },\n apiKey: {\n type: v.string().optional(),\n desc: [\n `An optional secret used to authorize zero-cache to call the API server handling writes.`,\n ],\n ...(replacement\n ? {deprecated: [makeDeprecationMessage(`${replacement}-api-key`)]}\n : {}),\n },\n forwardCookies: {\n type: v.boolean().default(false),\n desc: [\n `If true, zero-cache will forward cookies from the request.`,\n `This is useful for passing authentication cookies to the API server.`,\n `If false, cookies are not forwarded.`,\n ],\n ...(replacement\n ? {deprecated: [makeDeprecationMessage(`${replacement}-forward-cookies`)]}\n : {}),\n },\n allowedClientHeaders: {\n type: v.array(v.string()).optional(),\n desc: [\n `A list of header names that clients are allowed to set via custom headers.`,\n `If specified, only headers in this list will be forwarded to the ${suffix === 'push mutations' ? 'push' : 'query'} URL.`,\n `Header names are case-insensitive.`,\n `If not specified, no client-provided headers are forwarded (secure by default).`,\n `Example: ZERO_${replacement ? replacement.toUpperCase() : suffix === 'push mutations' ? 'MUTATE' : 'QUERY'}_ALLOWED_CLIENT_HEADERS=x-request-id,x-correlation-id`,\n ],\n ...(replacement\n ? {\n deprecated: [\n makeDeprecationMessage(`${replacement}-allowed-client-headers`),\n ],\n }\n : {}),\n },\n});\n\nconst mutateOptions = makeMutatorQueryOptions(undefined, 'push mutations');\nconst pushOptions = makeMutatorQueryOptions('mutate', 'push mutations');\nconst queryOptions = makeMutatorQueryOptions(undefined, 'send synced queries');\nconst getQueriesOptions = makeMutatorQueryOptions(\n 'query',\n 'send synced queries',\n);\n\nexport type AuthConfig = Config<typeof authOptions>;\n\n/** @deprecated used only by legacy JWT verification helpers */\nexport type LegacyJWTAuthConfig = Pick<\n AuthConfig,\n 'jwk' | 'jwksUrl' | 'secret' | 'issuer' | 'audience'\n>;\n\n// Note: --help will list flags in the order in which they are defined here,\n// so order the fields such that the important (e.g. required) ones are first.\n// (Exported for testing)\nexport const zeroOptions = {\n upstream: {\n db: {\n type: v.string(),\n desc: [\n `The \"upstream\" authoritative postgres database.`,\n `In the future we will support other types of upstream besides PG.`,\n ],\n },\n\n type: {\n type: v.literalUnion('pg', 'custom').default('pg'),\n desc: [\n `The meaning of the {bold upstream-db} depends on the upstream type:`,\n `* {bold pg}: The connection database string, e.g. \"postgres://...\"`,\n `* {bold custom}: The base URI of the change source \"endpoint, e.g.`,\n ` \"https://my-change-source.dev/changes/v0/stream?apiKey=...\"`,\n ],\n hidden: true, // TODO: Unhide when ready to officially support.\n },\n\n maxConns: {\n type: v.number().default(20),\n desc: [\n `The maximum number of connections to open to the upstream database`,\n `for committing mutations. This is divided evenly amongst sync workers.`,\n `In addition to this number, zero-cache uses one connection for the`,\n `replication stream.`,\n ``,\n `Note that this number must allow for at least one connection per`,\n `sync worker, or zero-cache will fail to start. See {bold num-sync-workers}`,\n ],\n },\n\n maxConnsPerWorker: {\n type: v.number().optional(),\n hidden: true, // Passed from main thread to sync workers\n },\n\n pgReplicationSlotFailover: {\n type: v.boolean().optional(),\n desc: [\n `For upstream Postgres versions 17+, creates replication slots with the`,\n `{bold failover} parameter set to {bold true} to enable slot synchronization`,\n `and failover. Note that additional Postgres-level configuration is necessary`,\n `when enabling this option. For details, see:`,\n ``,\n `https://www.postgresql.org/docs/current/logicaldecoding-explanation.html#LOGICALDECODING-REPLICATION-SLOTS-SYNCHRONIZATION`,\n ``,\n `(Note that this option has no effect for Postgres versions before 17.)`,\n ],\n },\n },\n\n /** @deprecated */\n push: pushOptions,\n mutate: mutateOptions,\n /** @deprecated */\n getQueries: getQueriesOptions,\n query: queryOptions,\n\n enableCrudMutations: {\n type: v.boolean().default(true),\n desc: [\n `Enables support for legacy CRUD mutations. When this is {bold false}, no connections`,\n `are made from view-syncers to the upstream db, and push messages with CRUD mutations`,\n `result in an InvalidPush response.`,\n ],\n },\n\n cvr: {\n db: {\n type: v.string().optional(),\n desc: [\n `The Postgres database used to store CVRs. CVRs (client view records) keep track`,\n `of the data synced to clients in order to determine the diff to send on reconnect.`,\n `If unspecified, the {bold upstream-db} will be used.`,\n ],\n },\n\n maxConns: {\n type: v.number().default(30),\n desc: [\n `The maximum number of connections to open to the CVR database.`,\n `This is divided evenly amongst sync workers.`,\n ``,\n `Note that this number must allow for at least one connection per`,\n `sync worker, or zero-cache will fail to start. See {bold num-sync-workers}`,\n ],\n },\n\n maxConnsPerWorker: {\n type: v.number().optional(),\n hidden: true, // Passed from main thread to sync workers\n },\n\n garbageCollectionInactivityThresholdHours: {\n type: v.number().default(48),\n desc: [\n `The duration after which an inactive CVR is eligible for garbage collection.`,\n `Note that garbage collection is an incremental, periodic process which does not`,\n `necessarily purge all eligible CVRs immediately.`,\n ],\n },\n\n garbageCollectionInitialIntervalSeconds: {\n type: v.number().default(60),\n desc: [\n `The initial interval at which to check and garbage collect inactive CVRs.`,\n `This interval is increased exponentially (up to 16 minutes) when there is`,\n `nothing to purge.`,\n ],\n },\n\n garbageCollectionInitialBatchSize: {\n type: v.number().default(25),\n desc: [\n `The initial number of CVRs to purge per garbage collection interval.`,\n `This number is increased linearly if the rate of new CVRs exceeds the rate of`,\n `purged CVRs, in order to reach a steady state.`,\n ``,\n `Setting this to 0 effectively disables CVR garbage collection.`,\n ],\n },\n },\n\n queryHydrationStats: {\n type: v.boolean().optional(),\n desc: [\n `Track and log the number of rows considered by query hydrations which`,\n `take longer than {bold log-slow-hydrate-threshold} milliseconds.`,\n `This is useful for debugging and performance tuning.`,\n ],\n },\n\n enableQueryPlanner: {\n type: v.boolean().default(true),\n desc: [\n `Enable the query planner for optimizing ZQL queries.`,\n ``,\n `The query planner analyzes and optimizes query execution by determining`,\n `the most efficient join strategies.`,\n ``,\n `You can disable the planner if it is picking bad strategies.`,\n ],\n },\n\n yieldThresholdMs: {\n type: v.number().default(10),\n desc: [\n `The maximum amount of time in milliseconds that a sync worker will`,\n `spend in IVM (processing query hydration and advancement) before yielding`,\n `to the event loop. Lower values increase responsiveness and fairness at`,\n `the cost of reduced throughput.`,\n ],\n },\n\n change: {\n db: {\n type: v.string().optional(),\n desc: [\n `The Postgres database used to store recent replication log entries, in order`,\n `to sync multiple view-syncers without requiring multiple replication slots on`,\n `the upstream database. If unspecified, the {bold upstream-db} will be used.`,\n ],\n },\n\n maxConns: {\n type: v.number().default(5),\n desc: [\n `The maximum number of connections to open to the change database.`,\n `This is used by the {bold change-streamer} for catching up`,\n `{bold zero-cache} replication subscriptions.`,\n ],\n },\n\n statementTimeoutMs: {\n type: v.number().default(20_000),\n desc: [\n `Fail change-log transactions if a statement response from postgres is not received within`,\n `the specified timeout. This differs from a postgres {bold statement_timeout} in that`,\n `it is implemented to handle a pathological case in which Postgres does not return a`,\n `response but otherwise believes the transaction to be idle.`,\n ],\n hidden: true, // make visible if proven to be effective/necessary\n },\n },\n\n replica: replicaOptions,\n\n log: logOptions,\n\n app: appOptions,\n\n shard: shardOptions,\n\n auth: authOptions,\n\n port: {\n type: v.number().default(4848),\n desc: [`The port for sync connections.`],\n },\n\n changeStreamer: {\n uri: {\n type: v.string().optional(),\n desc: [\n `When set, connects to the {bold change-streamer} at the given URI.`,\n `In a multi-node setup, this should be specified in {bold view-syncer} options,`,\n `pointing to the {bold replication-manager} URI, which runs a {bold change-streamer}`,\n `on port 4849.`,\n ],\n },\n\n mode: {\n type: v.literalUnion('dedicated', 'discover').default('dedicated'),\n desc: [\n `As an alternative to {bold ZERO_CHANGE_STREAMER_URI}, the {bold ZERO_CHANGE_STREAMER_MODE}`,\n `can be set to \"{bold discover}\" to instruct the {bold view-syncer} to connect to the `,\n `ip address registered by the {bold replication-manager} upon startup.`,\n ``,\n `This may not work in all networking configurations, e.g. certain private `,\n `networking or port forwarding configurations. Using the {bold ZERO_CHANGE_STREAMER_URI}`,\n `with an explicit routable hostname is recommended instead.`,\n ``,\n `Note: This option is ignored if the {bold ZERO_CHANGE_STREAMER_URI} is set.`,\n ],\n },\n\n port: {\n type: v.number().optional(),\n desc: [\n `The port on which the {bold change-streamer} runs. This is an internal`,\n `protocol between the {bold replication-manager} and {bold view-syncers}, which`,\n `runs in the same process tree in local development or a single-node configuration.`,\n ``,\n `If unspecified, defaults to {bold --port} + 1.`,\n ],\n },\n\n /** @deprecated */\n address: {\n type: v.string().optional(),\n deprecated: [\n `Set the {bold ZERO_CHANGE_STREAMER_URI} on view-syncers instead.`,\n ],\n hidden: true,\n },\n\n /** @deprecated */\n protocol: {\n type: v.literalUnion('ws', 'wss').default('ws'),\n deprecated: [\n `Set the {bold ZERO_CHANGE_STREAMER_URI} on view-syncers instead.`,\n ],\n hidden: true,\n },\n\n discoveryInterfacePreferences: {\n type: v.array(v.string()).default([...DEFAULT_PREFERRED_PREFIXES]),\n desc: [\n `The name prefixes to prefer when introspecting the network interfaces to determine`,\n `the externally reachable IP address for change-streamer discovery. This defaults`,\n `to commonly used names for standard ethernet interfaces in order to prevent selecting`,\n `special interfaces such as those for VPNs.`,\n ],\n // More confusing than it's worth to advertise this. The default list should be\n // adjusted to make things work for all environments; it is controlled as a\n // hidden flag as an emergency to unblock people with outlier network configs.\n hidden: true,\n },\n\n startupDelayMs: {\n type: v.number().default(15000),\n desc: [\n `The delay to wait before the change-streamer takes over the replication stream`,\n `(i.e. the handoff during replication-manager updates), to allow loadbalancers to register`,\n `the task as healthy based on healthcheck parameters. Note that if a change stream request`,\n `is received during this interval, the delay will be canceled and the takeover will happen`,\n `immediately, since the incoming request indicates that the task is registered as a target.`,\n ],\n },\n\n backPressureLimitHeapProportion: {\n type: v.number().default(0.04),\n desc: [\n `The percentage of {bold --max-old-space-size} to use as a buffer for absorbing replication`,\n `stream spikes. When the estimated amount of queued data exceeds this threshold, back pressure`,\n `is applied to the replication stream, delaying downstream sync as a result.`,\n ``,\n `The threshold was determined empirically with load testing. Higher thresholds have resulted`,\n `in OOMs. Note also that the byte-counting logic in the queue is strictly an underestimate of`,\n `actual memory usage (but importantly, proportionally correct), so the queue is actually`,\n `using more than what this proportion suggests.`,\n ``,\n `This parameter is exported as an emergency knob to reduce the size of the buffer in the`,\n `event that the server OOMs from back pressure. Resist the urge to {italic increase} this`,\n `proportion, as it is mainly useful for absorbing periodic spikes and does not meaningfully`,\n `affect steady-state replication throughput; the latter is determined by other factors such`,\n `as object serialization and PG throughput`,\n ``,\n `In other words, the back pressure limit does not constrain replication throughput;`,\n `rather, it protects the system when the upstream throughput exceeds the downstream`,\n `throughput.`,\n ],\n },\n\n flowControlConsensusPaddingSeconds: {\n type: v.number().default(1),\n desc: [\n `During periodic flow control checks (every 64kb), the amount of time to wait after the`,\n `majority of subscribers have acked, after which replication will continue even if`,\n `some subscribers have yet to ack. (Note that this is not a timeout for the {italic entire} send,`,\n `but a timeout that starts {italic after} the majority of receivers have acked.)`,\n ``,\n `This allows a bounded amount of time for backlogged subscribers to catch up on each flush`,\n `without forcing all subscribers to wait for the entire backlog to be processed. It is also`,\n `useful for mitigating the effect of unresponsive subscribers due to severed websocket`,\n `connections (until liveness checks disconnect them).`,\n ``,\n `Set this to a negative number to disable early flow control releases. (Not recommended, but`,\n `available as an emergency measure.)`,\n ],\n },\n },\n\n taskID: {\n type: v.string().optional(),\n desc: [\n `Globally unique identifier for the zero-cache instance.`,\n ``,\n `Setting this to a platform specific task identifier can be useful for debugging.`,\n `If unspecified, zero-cache will attempt to extract the TaskARN if run from within`,\n `an AWS ECS container, and otherwise use a random string.`,\n ],\n },\n\n perUserMutationLimit,\n\n numSyncWorkers: {\n type: v.number().optional(),\n desc: [\n `The number of processes to use for view syncing.`,\n `Leave this unset to use the maximum available parallelism.`,\n `If set to 0, the server runs without sync workers, which is the`,\n `configuration for running the {bold replication-manager}.`,\n ],\n },\n\n autoReset: {\n type: v.boolean().default(true),\n desc: [\n `Automatically wipe and resync the replica when replication is halted.`,\n `This situation can occur for configurations in which the upstream database`,\n `provider prohibits event trigger creation, preventing the zero-cache from`,\n `being able to correctly replicate schema changes. For such configurations,`,\n `an upstream schema change will instead result in halting replication with an`,\n `error indicating that the replica needs to be reset.`,\n ``,\n `When {bold auto-reset} is enabled, zero-cache will respond to such situations`,\n `by shutting down, and when restarted, resetting the replica and all synced `,\n `clients. This is a heavy-weight operation and can result in user-visible`,\n `slowness or downtime if compute resources are scarce.`,\n ],\n },\n\n replicationLag: {\n reportIntervalMs: {\n type: v.number().default(30000),\n desc: [\n `The minimum interval at which replication lag reports are written upstream and`,\n `reported via the {bold zero.replication.total_lag} opentelemetry metric. Because`,\n `replication lag reports are only issued after the previous one was received, the`,\n `actual interval between reports may be longer when there is a backlog in the`,\n `replication stream. A negative or 0 value disables lag reporting.`,\n ``,\n `This monitoring feature is only support on the postgres upstream type.`,\n ],\n },\n },\n\n adminPassword: {\n type: v.string().optional(),\n desc: [\n `A password used to administer zero-cache server, for example to access the`,\n `/statz endpoint.`,\n '',\n 'A password is optional in development mode but {bold required in production} mode.',\n ],\n },\n\n websocketCompression: {\n type: v.boolean().default(false),\n desc: [\n 'Enable WebSocket per-message deflate compression.',\n '',\n 'Compression can reduce bandwidth usage for sync traffic but',\n 'increases CPU usage on both client and server. Disabled by default.',\n '',\n 'See: https://github.com/websockets/ws#websocket-compression',\n ],\n },\n\n websocketCompressionOptions: {\n type: v.string().optional(),\n desc: [\n 'JSON string containing WebSocket compression options.',\n '',\n 'Only used if websocketCompression is enabled.',\n '',\n 'Example: \\\\{\"zlibDeflateOptions\":\\\\{\"level\":3\\\\},\"threshold\":1024\\\\}',\n '',\n 'See https://github.com/websockets/ws/blob/master/doc/ws.md#new-websocketserveroptions-callback for available options.',\n ],\n },\n\n websocketMaxPayloadBytes: {\n type: v.number().default(10 * 1024 * 1024),\n desc: [\n 'Maximum size of incoming WebSocket messages in bytes.',\n '',\n 'Messages exceeding this limit are rejected before parsing.',\n 'Default: 10MB (10 * 1024 * 1024 = 10485760)',\n ],\n },\n\n litestream: {\n executable: {\n type: v.string().optional(),\n desc: [\n `Path to the {bold litestream} executable. This must be built from the`,\n `{bold rocicorp/litestream} fork. Support for the official binary at v0.5.x`,\n `is planned.`,\n ],\n },\n\n executableV5: {\n type: v.string().optional(),\n desc: [\n `The v0.5.x litestream executable which is used for restoring the backup`,\n `backup when {bold ZERO_LITESTREAM_RESTORE_USING_V5} is specified.`,\n `litestream v0.5.8+ can restore from both v0.3.x and v0.5.x backup formats,`,\n `affording forwards compatibility with a future zero-cache`,\n `version that will use litestream v0.5.x to backup the replica.`,\n ],\n },\n\n restoreUsingV5: {\n type: v.boolean().default(false),\n desc: [\n `Restores the backup using the {bold ZERO_LITESTREAM_EXECUTABLE_V5} if specified.`,\n ],\n },\n\n configPath: {\n type: v.string().default('./src/services/litestream/config.yml'),\n desc: [\n `Path to the litestream yaml config file. zero-cache will run this with its`,\n `environment variables, which can be referenced in the file via $\\\\{ENV\\\\}`,\n `substitution, for example:`,\n `* {bold ZERO_REPLICA_FILE} for the db path`,\n `* {bold ZERO_LITESTREAM_BACKUP_LOCATION} for the db replica url`,\n `* {bold ZERO_LITESTREAM_LOG_LEVEL} for the log level`,\n `* {bold ZERO_LOG_FORMAT} for the log type`,\n ],\n },\n\n logLevel: {\n type: v.literalUnion('debug', 'info', 'warn', 'error').default('warn'),\n },\n\n backupURL: {\n type: v.string().optional(),\n desc: [\n `The location of the litestream backup, usually an {bold s3://} URL.`,\n `This is only consulted by the {bold replication-manager}.`,\n `{bold view-syncers} receive this information from the {bold replication-manager}.`,\n ],\n },\n\n endpoint: {\n type: v.string().optional(),\n desc: [\n `The S3-compatible endpoint URL to use for the litestream backup. Only required for non-AWS services.`,\n `The {bold replication-manager} and {bold view-syncers} must have the same endpoint.`,\n ],\n },\n\n port: {\n type: v.number().optional(),\n desc: [\n `Port on which litestream exports metrics, used to determine the replication`,\n `watermark up to which it is safe to purge change log records.`,\n ``,\n `If unspecified, defaults to {bold --port} + 2.`,\n ],\n },\n\n checkpointThresholdMB: {\n type: v.number().default(40),\n desc: [\n `The size of the WAL file at which to perform an SQlite checkpoint to apply`,\n `the writes in the WAL to the main database file. Each checkpoint creates`,\n `a new WAL segment file that will be backed up by litestream. Smaller thresholds`,\n `may improve read performance, at the expense of creating more files to download`,\n `when restoring the replica from the backup.`,\n ],\n },\n\n minCheckpointPageCount: {\n type: v.number().optional(),\n desc: [\n `The WAL page count at which SQLite attempts a PASSIVE checkpoint, which`,\n `transfers pages to the main database file without blocking writers.`,\n `Defaults to {bold checkpointThresholdMB * 250} (since SQLite page size is 4KB).`,\n ],\n },\n\n maxCheckpointPageCount: {\n type: v.number().optional(),\n desc: [\n `The WAL page count at which SQLite performs a RESTART checkpoint, which`,\n `blocks writers until complete. Defaults to {bold minCheckpointPageCount * 10}.`,\n `Set to {bold 0} to disable RESTART checkpoints entirely.`,\n ],\n },\n\n incrementalBackupIntervalMinutes: {\n type: v.number().default(15),\n desc: [\n `The interval between incremental backups of the replica. Shorter intervals`,\n `reduce the amount of change history that needs to be replayed when catching`,\n `up a new view-syncer, at the expense of increasing the number of files needed`,\n `to download for the initial litestream restore.`,\n ],\n },\n\n snapshotBackupIntervalHours: {\n type: v.number().default(12),\n desc: [\n `The interval between snapshot backups of the replica. Snapshot backups`,\n `make a full copy of the database to a new litestream generation. This`,\n `improves restore time at the expense of bandwidth. Applications with a`,\n `large database and low write rate can increase this interval to reduce`,\n `network usage for backups (litestream defaults to 24 hours).`,\n ],\n },\n\n restoreParallelism: {\n type: v.number().default(48),\n desc: [\n `The number of WAL files to download in parallel when performing the`,\n `initial restore of the replica from the backup.`,\n ],\n },\n\n multipartConcurrency: {\n type: v.number().default(48),\n desc: [\n `The number of parts (of size {bold --litestream-multipart-size} bytes)`,\n `to upload or download in parallel when backing up or restoring the snapshot.`,\n ],\n },\n\n multipartSize: {\n type: v.number().default(16 * 1024 * 1024),\n desc: [\n `The size of each part when uploading or downloading the snapshot with`,\n `{bold --multipart-concurrency}. Note that up to {bold concurrency * size}`,\n `bytes of memory are used when backing up or restoring the snapshot.`,\n ],\n },\n },\n\n storageDBTmpDir: {\n type: v.string().optional(),\n desc: [\n `tmp directory for IVM operator storage. Leave unset to use os.tmpdir()`,\n ],\n },\n\n initialSync: {\n tableCopyWorkers: {\n type: v.number().default(5),\n desc: [\n `The number of parallel workers used to copy tables during initial sync.`,\n `Each worker uses a database connection and will buffer up to (approximately)`,\n `10 MB of table data in memory during initial sync. Increasing the number of`,\n `workers may improve initial sync speed; however, note that local disk throughput`,\n `(i.e. IOPS), upstream CPU, and network bandwidth may also be bottlenecks.`,\n ],\n },\n\n profileCopy: {\n type: v.boolean().optional(),\n hidden: true,\n desc: [\n `Takes a cpu profile during the copy phase initial-sync, storing it as a JSON file`,\n `initial-copy.cpuprofile in the tmp directory.`,\n ],\n },\n\n textCopy: {\n type: v.boolean().default(false),\n desc: [\n `Use text-format COPY instead of binary COPY for the initial sync.`,\n `This is slower but can work around issues with binary encoding of`,\n `certain data types.`,\n ],\n },\n },\n\n /** @deprecated */\n targetClientRowCount: {\n type: v.number().default(20_000),\n deprecated: [\n 'This option is no longer used and will be removed in a future version.',\n 'The client-side cache no longer enforces a row limit. Instead, TTL-based expiration',\n 'automatically manages cache size to prevent unbounded growth.',\n ],\n hidden: true,\n },\n\n lazyStartup: {\n type: v.boolean().default(false),\n desc: [\n 'Delay starting the majority of zero-cache until first request.',\n '',\n 'This is mainly intended to avoid connecting to Postgres replication stream',\n 'until the first request is received, which can be useful i.e., for preview instances.',\n '',\n 'Currently only supported in single-node mode.',\n ],\n },\n\n serverVersion: {\n type: v.string().optional(),\n desc: [`The version string outputted to logs when the server starts up.`],\n },\n\n enableTelemetry: {\n type: v.boolean().default(true),\n desc: [\n `Set to false to opt out of telemetry collection.`,\n ``,\n `This helps us improve Zero by collecting anonymous usage data.`,\n `Setting the DO_NOT_TRACK environment variable also disables telemetry.`,\n ],\n },\n\n cloudEvent: {\n sinkEnv: {\n type: v.string().optional(),\n desc: [\n `ENV variable containing a URI to a CloudEvents sink. When set, ZeroEvents`,\n `will be published to the sink as the {bold data} field of CloudEvents.`,\n `The {bold source} field of the CloudEvents will be set to the {bold ZERO_TASK_ID},`,\n `along with any extension attributes specified by the {bold ZERO_CLOUD_EVENT_EXTENSION_OVERRIDES_ENV}.`,\n ``,\n `This configuration is modeled to easily integrate with a knative K_SINK binding,`,\n `(i.e. https://github.com/knative/eventing/blob/main/docs/spec/sources.md#sinkbinding).`,\n `However, any CloudEvents sink can be used.`,\n ],\n },\n\n extensionOverridesEnv: {\n type: v.string().optional(),\n desc: [\n `ENV variable containing a JSON stringified object with an {bold extensions} field`,\n `containing attributes that should be added or overridden on outbound CloudEvents.`,\n ``,\n `This configuration is modeled to easily integrate with a knative K_CE_OVERRIDES binding,`,\n `(i.e. https://github.com/knative/eventing/blob/main/docs/spec/sources.md#sinkbinding).`,\n ],\n },\n },\n};\n\nexport type ZeroConfig = Config<typeof zeroOptions>;\n\nlet loadedConfig: Config<typeof zeroOptions> | undefined;\n\nexport function getZeroConfig(\n opts: Omit<ParseOptions, 'envNamePrefix'> = {},\n): ZeroConfig {\n if (!loadedConfig || singleProcessMode()) {\n loadedConfig = parseOptions(zeroOptions, {\n envNamePrefix: ZERO_ENV_VAR_PREFIX,\n emitDeprecationWarnings: false, // overridden at the top level parse\n ...opts,\n });\n\n if (loadedConfig.queryHydrationStats) {\n runtimeDebugFlags.trackRowCountsVended = true;\n }\n }\n return loadedConfig;\n}\n\n/**\n * Same as {@link getZeroConfig}, with an additional check that the\n * config has already been normalized (i.e. by the top level server/runner).\n */\nexport function getNormalizedZeroConfig(\n opts: Omit<ParseOptions, 'envNamePrefix'> = {},\n): NormalizedZeroConfig {\n const config = getZeroConfig(opts);\n assertNormalized(config);\n return config;\n}\n\n/**\n * Gets the server version from the config if provided. Otherwise it gets it\n * from the Zero package.json.\n */\nexport function getServerVersion(\n config: Pick<ZeroConfig, 'serverVersion'> | undefined,\n): string {\n return config?.serverVersion ?? packageJson.version;\n}\n\nexport function isAdminPasswordValid(\n lc: LogContext,\n config: Pick<NormalizedZeroConfig, 'adminPassword'>,\n password: string | undefined,\n) {\n // If development mode, password is optional\n // We use process.env.NODE_ENV === 'development' as a sign that we're in\n // development mode, rather than a custom env var like ZERO_DEVELOPMENT_MODE,\n // because NODE_ENV is more standard and is already used by many tools.\n // Note that if NODE_ENV is not set, we assume production mode.\n\n if (!password && !config.adminPassword && isDevelopmentMode()) {\n warnOnce(\n lc,\n 'No admin password set; allowing access in development mode only',\n );\n return true;\n }\n\n if (!config.adminPassword) {\n lc.warn?.('No admin password set; denying access');\n return false;\n }\n\n // Use constant-time comparison to prevent timing attacks\n const passwordBuffer = Buffer.from(password ?? '');\n const configBuffer = Buffer.from(config.adminPassword);\n\n // Handle length mismatch in constant time\n if (passwordBuffer.length !== configBuffer.length) {\n // Perform dummy comparison to maintain constant timing\n timingSafeEqual(configBuffer, configBuffer);\n lc.warn?.('Invalid admin password');\n return false;\n }\n\n if (!timingSafeEqual(passwordBuffer, configBuffer)) {\n lc.warn?.('Invalid admin password');\n return false;\n }\n\n lc.debug?.('Admin password accepted');\n return true;\n}\n\nlet hasWarned = false;\n\nfunction warnOnce(lc: LogContext, msg: string) {\n if (!hasWarned) {\n lc.warn?.(msg);\n hasWarned = true;\n }\n}\n\n// For testing purposes - reset the warning state\nexport function resetWarnOnceState() {\n hasWarned = false;\n}\n"],"mappings":";;;;;;;;;;;;;;AA8BA,IAAa,sBAAsB;AAEnC,IAAa,aAAa;CACxB,IAAI;EACF,MAAM,eACH,QAAQ,CACR,QAAQ,OAAO,CACf,QAAO,OAAM,0BAA0B,KAAK,GAAG,EAAE,uBAAuB;EAC3E,MAAM;GACJ;GACA;GACA;GACA;GACA;GACA;GACA;GACA;GACA;GACA;GACA;GACA;GACA;GACA;GACA;GACA;GACA;GACA;GACA;GACD;EACF;CAED,cAAc;EACZ,MAAM,eAAE,MAAM,eAAE,QAAQ,CAAC,CAAC,eAAe,EAAE,CAAC;EAC5C,MAAM;GACJ;GACA;GACA;GACA;GACA;GACA;GACA;GACA;GACA;GACA;GACA;GACA;GACA;GACD;EACF;CACF;AAED,IAAa,eAAe;CAC1B,IAAI;EACF,MAAM,eACH,QAAQ,CACR,aAAa;AACZ,SAAM,IAAI,MACR,wEAED;IACD,CACD,UAAU;EACb,QAAQ;EACT;CAED,KAAK;EACH,MAAM,eAAE,QAAQ,CAAC,QAAQ,EAAE;EAC3B,MAAM;GACJ;GACA;GACA;GACA;GACD;EACD,QAAQ;EACT;CACF;AAED,IAAM,iBAAiB;CACrB,MAAM;EACJ,MAAM,eAAE,QAAQ,CAAC,QAAQ,UAAU;EACnC,MAAM;GACJ;GACA;GACA;GACD;EACF;CAED,qBAAqB;EACnB,MAAM,eAAE,QAAQ,CAAC,UAAU;EAC3B,MAAM;GACJ;GACA;GACA;GACA;GACD;EACF;CACF;AAID,IAAM,uBAAuB;CAC3B,KAAK;EACH,MAAM,eAAE,QAAQ,CAAC,UAAU;EAC3B,M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,OAA4C,EAAE,EAClC;AACZ,KAAI,CAAC,gBAAgB,mBAAmB,EAAE;AACxC,iBAAe,aAAa,aAAa;GACvC,eAAe;GACf,yBAAyB;GACzB,GAAG;GACJ,CAAC;AAEF,MAAI,aAAa,oBACf,mBAAkB,uBAAuB;;AAG7C,QAAO;;;;;;AAOT,SAAgB,wBACd,OAA4C,EAAE,EACxB;CACtB,MAAM,SAAS,cAAc,KAAK;AAClC,kBAAiB,OAAO;AACxB,QAAO;;;;;;AAOT,SAAgB,iBACd,QACQ;AACR,QAAO,QAAQ,iBAAiB,gBAAY;;AAG9C,SAAgB,qBACd,IACA,QACA,UACA;AAOA,KAAI,CAAC,YAAY,CAAC,OAAO,iBAAiB,mBAAmB,EAAE;AAC7D,WACE,IACA,kEACD;AACD,SAAO;;AAGT,KAAI,CAAC,OAAO,eAAe;AACzB,KAAG,OAAO,wCAAwC;AAClD,SAAO;;CAIT,MAAM,iBAAiB,OAAO,KAAK,YAAY,GAAG;CAClD,MAAM,eAAe,OAAO,KAAK,OAAO,cAAc;AAGtD,KAAI,eAAe,WAAW,aAAa,QAAQ;AAEjD,kBAAgB,cAAc,aAAa;AAC3C,KAAG,OAAO,yBAAyB;AACnC,SAAO;;AAGT,KAAI,CAAC,gBAAgB,gBAAgB,aAAa,EAAE;AAClD,KAAG,OAAO,yBAAyB;AACnC,SAAO;;AAGT,IAAG,QAAQ,0BAA0B;AACrC,QAAO;;AAGT,IAAI,YAAY;AAEhB,SAAS,SAAS,IAAgB,KAAa;AAC7C,KAAI,CAAC,WAAW;AACd,KAAG,OAAO,IAAI;AACd,cAAY"}
1
+ {"version":3,"file":"zero-config.js","names":[],"sources":["../../../../../zero-cache/src/config/zero-config.ts"],"sourcesContent":["/**\n * These types represent the _compiled_ config whereas `define-config` types represent the _source_ config.\n */\n\nimport {timingSafeEqual} from 'node:crypto';\nimport type {LogContext} from '@rocicorp/logger';\nimport {logOptions} from '../../../otel/src/log-options.ts';\nimport {\n flagToEnv,\n parseOptions,\n type Config,\n type ParseOptions,\n} from '../../../shared/src/options.ts';\nimport * as v from '../../../shared/src/valita.ts';\n// @circular-dep-ignore - importing package.json for version info only\nimport packageJson from '../../../zero/package.json' with {type: 'json'};\nimport {runtimeDebugFlags} from '../../../zql/src/builder/debug-delegate.ts';\nimport {singleProcessMode} from '../types/processes.ts';\nimport {\n ALLOWED_APP_ID_CHARACTERS,\n INVALID_APP_ID_MESSAGE,\n} from '../types/shards.ts';\nimport {DEFAULT_PREFERRED_PREFIXES} from './network.ts';\nimport {\n assertNormalized,\n isDevelopmentMode,\n type NormalizedZeroConfig,\n} from './normalize.ts';\nexport type {LogConfig} from '../../../otel/src/log-options.ts';\n\nexport const ZERO_ENV_VAR_PREFIX = 'ZERO_';\n\nexport const appOptions = {\n id: {\n type: v\n .string()\n .default('zero')\n .assert(id => ALLOWED_APP_ID_CHARACTERS.test(id), INVALID_APP_ID_MESSAGE),\n desc: [\n 'Unique identifier for the app.',\n '',\n 'Multiple zero-cache apps can run on a single upstream database, each of which',\n 'is isolated from the others, with its own permissions, sharding (future feature),',\n 'and change/cvr databases.',\n '',\n 'The metadata of an app is stored in an upstream schema with the same name,',\n 'e.g. \"zero\", and the metadata for each app shard, e.g. client and mutation',\n 'ids, is stored in the \"\\\\{app-id\\\\}_\\\\{#\\\\}\" schema. (Currently there is only a single',\n '\"0\" shard, but this will change with sharding).',\n '',\n 'The CVR and Change data are managed in schemas named \"\\\\{app-id\\\\}_\\\\{shard-num\\\\}/cvr\"',\n 'and \"\\\\{app-id\\\\}_\\\\{shard-num\\\\}/cdc\", respectively, allowing multiple apps and shards',\n 'to share the same database instance (e.g. a Postgres \"cluster\") for CVR and Change management.',\n '',\n 'Due to constraints on replication slot names, an App ID may only consist of',\n 'lower-case letters, numbers, and the underscore character.',\n '',\n 'Note that this option is used by both {bold zero-cache} and {bold zero-deploy-permissions}.',\n ],\n },\n\n publications: {\n type: v.array(v.string()).optional(() => []),\n desc: [\n `Postgres {bold PUBLICATION}s that define the tables and columns to`,\n `replicate. Publication names may not begin with an underscore,`,\n `as zero reserves that prefix for internal use.`,\n ``,\n `If unspecified, zero-cache will create and use an internal publication that`,\n `publishes all tables in the {bold public} schema, i.e.:`,\n ``,\n `CREATE PUBLICATION _\\\\{app-id\\\\}_public_0 FOR TABLES IN SCHEMA public;`,\n ``,\n `Note that changing the set of publications will result in resyncing the replica,`,\n `which may involve downtime (replication lag) while the new replica is initializing.`,\n `To change the set of publications without disrupting an existing app, a new app`,\n `should be created.`,\n ],\n },\n};\n\nexport const shardOptions = {\n id: {\n type: v\n .string()\n .assert(() => {\n throw new Error(\n `ZERO_SHARD_ID is no longer an option. Please use ZERO_APP_ID instead.`,\n // TODO: Link to release / migration notes?\n );\n })\n .optional(),\n hidden: true,\n },\n\n num: {\n type: v.number().default(0),\n desc: [\n `The shard number (from 0 to NUM_SHARDS) of the App. zero will eventually`,\n `support data sharding as a first-class primitive; until then, deploying`,\n `multiple shard-nums creates functionally identical shards. Until sharding is`,\n `actually meaningful, this flag is hidden but available for testing.`,\n ],\n hidden: true,\n },\n};\n\nconst replicaOptions = {\n file: {\n type: v.string().default('zero.db'),\n desc: [\n `File path to the SQLite replica that zero-cache maintains.`,\n `This can be lost, but if it is, zero-cache will have to re-replicate next`,\n `time it starts up.`,\n ],\n },\n\n vacuumIntervalHours: {\n type: v.number().optional(),\n desc: [\n `Performs a VACUUM at server startup if the specified number of hours has elapsed`,\n `since the last VACUUM (or initial-sync). The VACUUM operation is heavyweight`,\n `and requires double the size of the db in disk space. If unspecified, VACUUM`,\n `operations are not performed.`,\n ],\n },\n};\n\nexport type ReplicaOptions = Config<typeof replicaOptions>;\n\nconst perUserMutationLimit = {\n max: {\n type: v.number().optional(),\n desc: [\n `The maximum mutations per user within the specified {bold windowMs}.`,\n `If unset, no rate limiting is enforced.`,\n ],\n },\n windowMs: {\n type: v.number().default(60_000),\n desc: [\n `The sliding window over which the {bold perUserMutationLimitMax} is enforced.`,\n ],\n },\n};\n\nexport type RateLimit = Config<typeof perUserMutationLimit>;\n\nconst authOptions = {\n jwk: {\n type: v.string().optional(),\n desc: [\n `A public key in JWK format used to verify JWTs. Only one of {bold jwk}, {bold jwksUrl} and {bold secret} may be set.`,\n ],\n deprecated: [\n `Use cookie-based authentication or an auth token instead - see https://zero.rocicorp.dev/docs/auth.`,\n ],\n },\n jwksUrl: {\n type: v.string().optional(),\n desc: [\n `A URL that returns a JWK set used to verify JWTs. Only one of {bold jwk}, {bold jwksUrl} and {bold secret} may be set.`,\n ],\n deprecated: [\n `Use cookie-based authentication or an auth token instead - see https://zero.rocicorp.dev/docs/auth.`,\n ],\n },\n secret: {\n type: v.string().optional(),\n desc: [\n `A symmetric key used to verify JWTs. Only one of {bold jwk}, {bold jwksUrl} and {bold secret} may be set.`,\n ],\n deprecated: [\n `Use cookie-based authentication or an auth token instead - see https://zero.rocicorp.dev/docs/auth.`,\n ],\n },\n issuer: {\n type: v.string().optional(),\n desc: [\n `Expected issuer ({bold iss} claim) for JWT validation.`,\n `If set, tokens with a different or missing issuer will be rejected.`,\n ],\n deprecated: [\n `Use cookie-based authentication or an auth token instead - see https://zero.rocicorp.dev/docs/auth.`,\n ],\n },\n audience: {\n type: v.string().optional(),\n desc: [\n `Expected audience ({bold aud} claim) for JWT validation.`,\n `If set, tokens with a different or missing audience will be rejected.`,\n ],\n deprecated: [\n `Use cookie-based authentication or an auth token instead - see https://zero.rocicorp.dev/docs/auth.`,\n ],\n },\n revalidateIntervalSeconds: {\n type: v.number().optional(),\n desc: [\n `The interval in seconds between periodic /query auth revalidation for validated connections.`,\n `If unset, periodic auth revalidation is disabled.`,\n ],\n },\n retransformIntervalSeconds: {\n type: v.number().optional(),\n desc: [\n `The interval in seconds between periodic shared /query retransform work for a client group.`,\n `If unset, periodic shared retransform is disabled.`,\n ],\n },\n};\n\nconst makeDeprecationMessage = (flag: string) =>\n `Use {bold ${flagToEnv(ZERO_ENV_VAR_PREFIX, flag)}} (or {bold --${flag}}) instead.`;\n\nconst makeMutatorQueryOptions = (\n replacement: 'mutate' | 'query' | undefined,\n suffix: string,\n) => ({\n url: {\n type: v.array(v.string()).optional(), // optional until we remove CRUD mutations\n desc: [\n `The URL of the API server to which zero-cache will ${suffix}.`,\n ``,\n `{bold IMPORTANT:} URLs are matched using {bold URLPattern}, a standard Web API.`,\n ``,\n `{bold Pattern Syntax:}`,\n ` URLPattern uses a simple and intuitive syntax similar to Express routes.`,\n ` Wildcards and named parameters make it easy to match multiple URLs.`,\n ``,\n `{bold Basic Examples:}`,\n ` Exact URL match:`,\n ` \"https://api.example.com/mutate\"`,\n ` `,\n ` Any subdomain using wildcard:`,\n ` \"https://*.example.com/mutate\"`,\n ` `,\n ` Multiple subdomain levels:`,\n ` \"https://*.*.example.com/mutate\"`,\n ` `,\n ` Any path under a domain:`,\n ` \"https://api.example.com/*\"`,\n ` `,\n ` Named path parameters:`,\n ` \"https://api.example.com/:version/mutate\"`,\n ` ↳ Matches \"https://api.example.com/v1/mutate\", \"https://api.example.com/v2/mutate\", etc.`,\n ``,\n `{bold Advanced Patterns:}`,\n ` Optional path segments:`,\n ` \"https://api.example.com/:path?\"`,\n ` `,\n ` Regex in segments (for specific patterns):`,\n ` \"https://api.example.com/:version(v\\\\\\\\d+)/mutate\"`,\n ` ↳ Matches only \"v\" followed by digits`,\n ``,\n `{bold Multiple patterns:}`,\n ` [\"https://api1.example.com/mutate\", \"https://api2.example.com/mutate\"]`,\n ``,\n `{bold Note:} Query parameters and URL fragments (#) are automatically ignored during matching.`,\n ``,\n `For full URLPattern syntax, see: https://developer.mozilla.org/en-US/docs/Web/API/URLPattern`,\n ],\n ...(replacement\n ? {deprecated: [makeDeprecationMessage(`${replacement}-url`)]}\n : {}),\n },\n apiKey: {\n type: v.string().optional(),\n desc: [\n `An optional secret used to authorize zero-cache to call the API server handling writes.`,\n ],\n ...(replacement\n ? {deprecated: [makeDeprecationMessage(`${replacement}-api-key`)]}\n : {}),\n },\n forwardCookies: {\n type: v.boolean().default(false),\n desc: [\n `If true, zero-cache will forward cookies from the request.`,\n `This is useful for passing authentication cookies to the API server.`,\n `If false, cookies are not forwarded.`,\n ],\n ...(replacement\n ? {deprecated: [makeDeprecationMessage(`${replacement}-forward-cookies`)]}\n : {}),\n },\n allowedClientHeaders: {\n type: v.array(v.string()).optional(),\n desc: [\n `A list of header names that clients are allowed to set via custom headers.`,\n `If specified, only headers in this list will be forwarded to the ${suffix === 'push mutations' ? 'push' : 'query'} URL.`,\n `Header names are case-insensitive.`,\n `If not specified, no client-provided headers are forwarded (secure by default).`,\n `Example: ZERO_${replacement ? replacement.toUpperCase() : suffix === 'push mutations' ? 'MUTATE' : 'QUERY'}_ALLOWED_CLIENT_HEADERS=x-request-id,x-correlation-id`,\n ],\n ...(replacement\n ? {\n deprecated: [\n makeDeprecationMessage(`${replacement}-allowed-client-headers`),\n ],\n }\n : {}),\n },\n});\n\nconst mutateOptions = makeMutatorQueryOptions(undefined, 'push mutations');\nconst pushOptions = makeMutatorQueryOptions('mutate', 'push mutations');\nconst queryOptions = makeMutatorQueryOptions(undefined, 'send synced queries');\nconst getQueriesOptions = makeMutatorQueryOptions(\n 'query',\n 'send synced queries',\n);\n\nexport type AuthConfig = Config<typeof authOptions>;\n\n/** @deprecated used only by legacy JWT verification helpers */\nexport type LegacyJWTAuthConfig = Pick<\n AuthConfig,\n 'jwk' | 'jwksUrl' | 'secret' | 'issuer' | 'audience'\n>;\n\n// Note: --help will list flags in the order in which they are defined here,\n// so order the fields such that the important (e.g. required) ones are first.\n// (Exported for testing)\nexport const zeroOptions = {\n upstream: {\n db: {\n type: v.string(),\n desc: [\n `The \"upstream\" authoritative postgres database.`,\n `In the future we will support other types of upstream besides PG.`,\n ],\n },\n\n type: {\n type: v.literalUnion('pg', 'custom').default('pg'),\n desc: [\n `The meaning of the {bold upstream-db} depends on the upstream type:`,\n `* {bold pg}: The connection database string, e.g. \"postgres://...\"`,\n `* {bold custom}: The base URI of the change source \"endpoint, e.g.`,\n ` \"https://my-change-source.dev/changes/v0/stream?apiKey=...\"`,\n ],\n hidden: true, // TODO: Unhide when ready to officially support.\n },\n\n maxConns: {\n type: v.number().default(20),\n desc: [\n `The maximum number of connections to open to the upstream database`,\n `for committing mutations. This is divided evenly amongst sync workers.`,\n `In addition to this number, zero-cache uses one connection for the`,\n `replication stream.`,\n ``,\n `Note that this number must allow for at least one connection per`,\n `sync worker, or zero-cache will fail to start. See {bold num-sync-workers}`,\n ],\n },\n\n maxConnsPerWorker: {\n type: v.number().optional(),\n hidden: true, // Passed from main thread to sync workers\n },\n\n pgReplicationSlotFailover: {\n type: v.boolean().optional(),\n desc: [\n `For upstream Postgres versions 17+, creates replication slots with the`,\n `{bold failover} parameter set to {bold true} to enable slot synchronization`,\n `and failover. Note that additional Postgres-level configuration is necessary`,\n `when enabling this option. For details, see:`,\n ``,\n `https://www.postgresql.org/docs/current/logicaldecoding-explanation.html#LOGICALDECODING-REPLICATION-SLOTS-SYNCHRONIZATION`,\n ``,\n `(Note that this option has no effect for Postgres versions before 17.)`,\n ],\n },\n },\n\n /** @deprecated */\n push: pushOptions,\n mutate: mutateOptions,\n /** @deprecated */\n getQueries: getQueriesOptions,\n query: queryOptions,\n\n enableCrudMutations: {\n type: v.boolean().default(true),\n desc: [\n `Enables support for legacy CRUD mutations. When this is {bold false}, no connections`,\n `are made from view-syncers to the upstream db, and push messages with CRUD mutations`,\n `result in an InvalidPush response.`,\n ],\n },\n\n cvr: {\n db: {\n type: v.string().optional(),\n desc: [\n `The Postgres database used to store CVRs. CVRs (client view records) keep track`,\n `of the data synced to clients in order to determine the diff to send on reconnect.`,\n `If unspecified, the {bold upstream-db} will be used.`,\n ],\n },\n\n maxConns: {\n type: v.number().default(30),\n desc: [\n `The maximum number of connections to open to the CVR database.`,\n `This is divided evenly amongst sync workers.`,\n ``,\n `Note that this number must allow for at least one connection per`,\n `sync worker, or zero-cache will fail to start. See {bold num-sync-workers}`,\n ],\n },\n\n maxConnsPerWorker: {\n type: v.number().optional(),\n hidden: true, // Passed from main thread to sync workers\n },\n\n garbageCollectionInactivityThresholdHours: {\n type: v.number().default(48),\n desc: [\n `The duration after which an inactive CVR is eligible for garbage collection.`,\n `Note that garbage collection is an incremental, periodic process which does not`,\n `necessarily purge all eligible CVRs immediately.`,\n ],\n },\n\n garbageCollectionInitialIntervalSeconds: {\n type: v.number().default(60),\n desc: [\n `The initial interval at which to check and garbage collect inactive CVRs.`,\n `This interval is increased exponentially (up to 16 minutes) when there is`,\n `nothing to purge.`,\n ],\n },\n\n garbageCollectionInitialBatchSize: {\n type: v.number().default(25),\n desc: [\n `The initial number of CVRs to purge per garbage collection interval.`,\n `This number is increased linearly if the rate of new CVRs exceeds the rate of`,\n `purged CVRs, in order to reach a steady state.`,\n ``,\n `Setting this to 0 effectively disables CVR garbage collection.`,\n ],\n },\n },\n\n queryHydrationStats: {\n type: v.boolean().optional(),\n desc: [\n `Track and log the number of rows considered by query hydrations which`,\n `take longer than {bold log-slow-hydrate-threshold} milliseconds.`,\n `This is useful for debugging and performance tuning.`,\n ],\n },\n\n enableQueryPlanner: {\n type: v.boolean().default(true),\n desc: [\n `Enable the query planner for optimizing ZQL queries.`,\n ``,\n `The query planner analyzes and optimizes query execution by determining`,\n `the most efficient join strategies.`,\n ``,\n `You can disable the planner if it is picking bad strategies.`,\n ],\n },\n\n yieldThresholdMs: {\n type: v.number().default(10),\n desc: [\n `The maximum amount of time in milliseconds that a sync worker will`,\n `spend in IVM (processing query hydration and advancement) before yielding`,\n `to the event loop. Lower values increase responsiveness and fairness at`,\n `the cost of reduced throughput.`,\n ],\n },\n\n change: {\n db: {\n type: v.string().optional(),\n desc: [\n `The Postgres database used to store recent replication log entries, in order`,\n `to sync multiple view-syncers without requiring multiple replication slots on`,\n `the upstream database. If unspecified, the {bold upstream-db} will be used.`,\n ],\n },\n\n maxConns: {\n type: v.number().default(5),\n desc: [\n `The maximum number of connections to open to the change database.`,\n `This is used by the {bold change-streamer} for catching up`,\n `{bold zero-cache} replication subscriptions.`,\n ],\n },\n\n statementTimeoutMs: {\n type: v.number().default(20_000),\n desc: [\n `Fail change-log transactions if a statement response from postgres is not received within`,\n `the specified timeout. This differs from a postgres {bold statement_timeout} in that`,\n `it is implemented to handle a pathological case in which Postgres does not return a`,\n `response but otherwise believes the transaction to be idle.`,\n ],\n hidden: true, // make visible if proven to be effective/necessary\n },\n },\n\n replica: replicaOptions,\n\n log: logOptions,\n\n app: appOptions,\n\n shard: shardOptions,\n\n auth: authOptions,\n\n port: {\n type: v.number().default(4848),\n desc: [`The port for sync connections.`],\n },\n\n changeStreamer: {\n uri: {\n type: v.string().optional(),\n desc: [\n `When set, connects to the {bold change-streamer} at the given URI.`,\n `In a multi-node setup, this should be specified in {bold view-syncer} options,`,\n `pointing to the {bold replication-manager} URI, which runs a {bold change-streamer}`,\n `on port 4849.`,\n ],\n },\n\n mode: {\n type: v.literalUnion('dedicated', 'discover').default('dedicated'),\n desc: [\n `As an alternative to {bold ZERO_CHANGE_STREAMER_URI}, the {bold ZERO_CHANGE_STREAMER_MODE}`,\n `can be set to \"{bold discover}\" to instruct the {bold view-syncer} to connect to the `,\n `ip address registered by the {bold replication-manager} upon startup.`,\n ``,\n `This may not work in all networking configurations, e.g. certain private `,\n `networking or port forwarding configurations. Using the {bold ZERO_CHANGE_STREAMER_URI}`,\n `with an explicit routable hostname is recommended instead.`,\n ``,\n `Note: This option is ignored if the {bold ZERO_CHANGE_STREAMER_URI} is set.`,\n ],\n },\n\n port: {\n type: v.number().optional(),\n desc: [\n `The port on which the {bold change-streamer} runs. This is an internal`,\n `protocol between the {bold replication-manager} and {bold view-syncers}, which`,\n `runs in the same process tree in local development or a single-node configuration.`,\n ``,\n `If unspecified, defaults to {bold --port} + 1.`,\n ],\n },\n\n /** @deprecated */\n address: {\n type: v.string().optional(),\n deprecated: [\n `Set the {bold ZERO_CHANGE_STREAMER_URI} on view-syncers instead.`,\n ],\n hidden: true,\n },\n\n /** @deprecated */\n protocol: {\n type: v.literalUnion('ws', 'wss').default('ws'),\n deprecated: [\n `Set the {bold ZERO_CHANGE_STREAMER_URI} on view-syncers instead.`,\n ],\n hidden: true,\n },\n\n discoveryInterfacePreferences: {\n type: v.array(v.string()).default([...DEFAULT_PREFERRED_PREFIXES]),\n desc: [\n `The name prefixes to prefer when introspecting the network interfaces to determine`,\n `the externally reachable IP address for change-streamer discovery. This defaults`,\n `to commonly used names for standard ethernet interfaces in order to prevent selecting`,\n `special interfaces such as those for VPNs.`,\n ],\n // More confusing than it's worth to advertise this. The default list should be\n // adjusted to make things work for all environments; it is controlled as a\n // hidden flag as an emergency to unblock people with outlier network configs.\n hidden: true,\n },\n\n startupDelayMs: {\n type: v.number().default(15000),\n desc: [\n `The delay to wait before the change-streamer takes over the replication stream`,\n `(i.e. the handoff during replication-manager updates), to allow loadbalancers to register`,\n `the task as healthy based on healthcheck parameters. Note that if a change stream request`,\n `is received during this interval, the delay will be canceled and the takeover will happen`,\n `immediately, since the incoming request indicates that the task is registered as a target.`,\n ],\n },\n\n backPressureLimitHeapProportion: {\n type: v.number().default(0.04),\n desc: [\n `The percentage of {bold --max-old-space-size} to use as a buffer for absorbing replication`,\n `stream spikes. When the estimated amount of queued data exceeds this threshold, back pressure`,\n `is applied to the replication stream, delaying downstream sync as a result.`,\n ``,\n `The threshold was determined empirically with load testing. Higher thresholds have resulted`,\n `in OOMs. Note also that the byte-counting logic in the queue is strictly an underestimate of`,\n `actual memory usage (but importantly, proportionally correct), so the queue is actually`,\n `using more than what this proportion suggests.`,\n ``,\n `This parameter is exported as an emergency knob to reduce the size of the buffer in the`,\n `event that the server OOMs from back pressure. Resist the urge to {italic increase} this`,\n `proportion, as it is mainly useful for absorbing periodic spikes and does not meaningfully`,\n `affect steady-state replication throughput; the latter is determined by other factors such`,\n `as object serialization and PG throughput`,\n ``,\n `In other words, the back pressure limit does not constrain replication throughput;`,\n `rather, it protects the system when the upstream throughput exceeds the downstream`,\n `throughput.`,\n ],\n },\n\n flowControlConsensusPaddingSeconds: {\n type: v.number().default(1),\n desc: [\n `During periodic flow control checks (every 64kb), the amount of time to wait after the`,\n `majority of subscribers have acked, after which replication will continue even if`,\n `some subscribers have yet to ack. (Note that this is not a timeout for the {italic entire} send,`,\n `but a timeout that starts {italic after} the majority of receivers have acked.)`,\n ``,\n `This allows a bounded amount of time for backlogged subscribers to catch up on each flush`,\n `without forcing all subscribers to wait for the entire backlog to be processed. It is also`,\n `useful for mitigating the effect of unresponsive subscribers due to severed websocket`,\n `connections (until liveness checks disconnect them).`,\n ``,\n `Set this to a negative number to disable early flow control releases. (Not recommended, but`,\n `available as an emergency measure.)`,\n ],\n },\n },\n\n taskID: {\n type: v.string().optional(),\n desc: [\n `Globally unique identifier for the zero-cache instance.`,\n ``,\n `Setting this to a platform specific task identifier can be useful for debugging.`,\n `If unspecified, zero-cache will attempt to extract the TaskARN if run from within`,\n `an AWS ECS container, and otherwise use a random string.`,\n ],\n },\n\n perUserMutationLimit,\n\n numSyncWorkers: {\n type: v.number().optional(),\n desc: [\n `The number of processes to use for view syncing.`,\n `Leave this unset to use the maximum available parallelism.`,\n `If set to 0, the server runs without sync workers, which is the`,\n `configuration for running the {bold replication-manager}.`,\n ],\n },\n\n autoReset: {\n type: v.boolean().default(true),\n desc: [\n `Automatically wipe and resync the replica when replication is halted.`,\n `This situation can occur for configurations in which the upstream database`,\n `provider prohibits event trigger creation, preventing the zero-cache from`,\n `being able to correctly replicate schema changes. For such configurations,`,\n `an upstream schema change will instead result in halting replication with an`,\n `error indicating that the replica needs to be reset.`,\n ``,\n `When {bold auto-reset} is enabled, zero-cache will respond to such situations`,\n `by shutting down, and when restarted, resetting the replica and all synced `,\n `clients. This is a heavy-weight operation and can result in user-visible`,\n `slowness or downtime if compute resources are scarce.`,\n ],\n },\n\n replicationLag: {\n reportIntervalMs: {\n type: v.number().default(30000),\n desc: [\n `The minimum interval at which replication lag reports are written upstream and`,\n `reported via the {bold zero.replication.total_lag} opentelemetry metric. Because`,\n `replication lag reports are only issued after the previous one was received, the`,\n `actual interval between reports may be longer when there is a backlog in the`,\n `replication stream. A negative or 0 value disables lag reporting.`,\n ``,\n `This monitoring feature is only support on the postgres upstream type.`,\n ],\n },\n },\n\n adminPassword: {\n type: v.string().optional(),\n desc: [\n `A password used to administer zero-cache server, for example to access the`,\n `/statz endpoint.`,\n '',\n 'A password is optional in development mode but {bold required in production} mode.',\n ],\n },\n\n websocketCompression: {\n type: v.boolean().default(false),\n desc: [\n 'Enable WebSocket per-message deflate compression.',\n '',\n 'Compression can reduce bandwidth usage for sync traffic but',\n 'increases CPU usage on both client and server. Disabled by default.',\n '',\n 'See: https://github.com/websockets/ws#websocket-compression',\n ],\n },\n\n websocketCompressionOptions: {\n type: v.string().optional(),\n desc: [\n 'JSON string containing WebSocket compression options.',\n '',\n 'Only used if websocketCompression is enabled.',\n '',\n 'Example: \\\\{\"zlibDeflateOptions\":\\\\{\"level\":3\\\\},\"threshold\":1024\\\\}',\n '',\n 'See https://github.com/websockets/ws/blob/master/doc/ws.md#new-websocketserveroptions-callback for available options.',\n ],\n },\n\n websocketMaxPayloadBytes: {\n type: v.number().default(10 * 1024 * 1024),\n desc: [\n 'Maximum size of incoming WebSocket messages in bytes.',\n '',\n 'Messages exceeding this limit are rejected before parsing.',\n 'Default: 10MB (10 * 1024 * 1024 = 10485760)',\n ],\n },\n\n litestream: {\n executable: {\n type: v.string().optional(),\n desc: [\n `Path to the {bold litestream} executable. This must be built from the`,\n `{bold rocicorp/litestream} fork. Support for the official binary at v0.5.x`,\n `is planned.`,\n ],\n },\n\n executableV5: {\n type: v.string().optional(),\n desc: [\n `The v0.5.x litestream executable which is used for restoring the backup`,\n `backup when {bold ZERO_LITESTREAM_RESTORE_USING_V5} is specified.`,\n `litestream v0.5.8+ can restore from both v0.3.x and v0.5.x backup formats,`,\n `affording forwards compatibility with a future zero-cache`,\n `version that will use litestream v0.5.x to backup the replica.`,\n ],\n },\n\n restoreUsingV5: {\n type: v.boolean().default(false),\n desc: [\n `Restores the backup using the {bold ZERO_LITESTREAM_EXECUTABLE_V5} if specified.`,\n ],\n },\n\n configPath: {\n type: v.string().default('./src/services/litestream/config.yml'),\n desc: [\n `Path to the litestream yaml config file. zero-cache will run this with its`,\n `environment variables, which can be referenced in the file via $\\\\{ENV\\\\}`,\n `substitution, for example:`,\n `* {bold ZERO_REPLICA_FILE} for the db path`,\n `* {bold ZERO_LITESTREAM_BACKUP_LOCATION} for the db replica url`,\n `* {bold ZERO_LITESTREAM_LOG_LEVEL} for the log level`,\n `* {bold ZERO_LOG_FORMAT} for the log type`,\n ],\n },\n\n logLevel: {\n type: v.literalUnion('debug', 'info', 'warn', 'error').default('warn'),\n },\n\n backupURL: {\n type: v.string().optional(),\n desc: [\n `The location of the litestream backup, usually an {bold s3://} URL.`,\n `This is only consulted by the {bold replication-manager}.`,\n `{bold view-syncers} receive this information from the {bold replication-manager}.`,\n ],\n },\n\n endpoint: {\n type: v.string().optional(),\n desc: [\n `The S3-compatible endpoint URL to use for the litestream backup. Only required for non-AWS services.`,\n `The {bold replication-manager} and {bold view-syncers} must have the same endpoint.`,\n ],\n },\n\n port: {\n type: v.number().optional(),\n desc: [\n `Port on which litestream exports metrics, used to determine the replication`,\n `watermark up to which it is safe to purge change log records.`,\n ``,\n `If unspecified, defaults to {bold --port} + 2.`,\n ],\n },\n\n checkpointThresholdMB: {\n type: v.number().default(40),\n desc: [\n `The size of the WAL file at which to perform an SQlite checkpoint to apply`,\n `the writes in the WAL to the main database file. Each checkpoint creates`,\n `a new WAL segment file that will be backed up by litestream. Smaller thresholds`,\n `may improve read performance, at the expense of creating more files to download`,\n `when restoring the replica from the backup.`,\n ],\n },\n\n minCheckpointPageCount: {\n type: v.number().optional(),\n desc: [\n `The WAL page count at which SQLite attempts a PASSIVE checkpoint, which`,\n `transfers pages to the main database file without blocking writers.`,\n `Defaults to {bold checkpointThresholdMB * 250} (since SQLite page size is 4KB).`,\n ],\n },\n\n maxCheckpointPageCount: {\n type: v.number().optional(),\n desc: [\n `The WAL page count at which SQLite performs a RESTART checkpoint, which`,\n `blocks writers until complete. Defaults to {bold minCheckpointPageCount * 10}.`,\n `Set to {bold 0} to disable RESTART checkpoints entirely.`,\n ],\n },\n\n incrementalBackupIntervalMinutes: {\n type: v.number().default(15),\n desc: [\n `The interval between incremental backups of the replica. Shorter intervals`,\n `reduce the amount of change history that needs to be replayed when catching`,\n `up a new view-syncer, at the expense of increasing the number of files needed`,\n `to download for the initial litestream restore.`,\n ],\n },\n\n snapshotBackupIntervalHours: {\n type: v.number().default(12),\n desc: [\n `The interval between snapshot backups of the replica. Snapshot backups`,\n `make a full copy of the database to a new litestream generation. This`,\n `improves restore time at the expense of bandwidth. Applications with a`,\n `large database and low write rate can increase this interval to reduce`,\n `network usage for backups (litestream defaults to 24 hours).`,\n ],\n },\n\n restoreParallelism: {\n type: v.number().default(48),\n desc: [\n `The number of WAL files to download in parallel when performing the`,\n `initial restore of the replica from the backup.`,\n ],\n },\n\n multipartConcurrency: {\n type: v.number().default(48),\n desc: [\n `The number of parts (of size {bold --litestream-multipart-size} bytes)`,\n `to upload or download in parallel when backing up or restoring the snapshot.`,\n ],\n },\n\n multipartSize: {\n type: v.number().default(16 * 1024 * 1024),\n desc: [\n `The size of each part when uploading or downloading the snapshot with`,\n `{bold --multipart-concurrency}. Note that up to {bold concurrency * size}`,\n `bytes of memory are used when backing up or restoring the snapshot.`,\n ],\n },\n },\n\n storageDBTmpDir: {\n type: v.string().optional(),\n desc: [\n `tmp directory for IVM operator storage. Leave unset to use os.tmpdir()`,\n ],\n },\n\n initialSync: {\n tableCopyWorkers: {\n type: v.number().default(5),\n desc: [\n `The number of parallel workers used to copy tables during initial sync.`,\n `Each worker uses a database connection and will buffer up to (approximately)`,\n `10 MB of table data in memory during initial sync. Increasing the number of`,\n `workers may improve initial sync speed; however, note that local disk throughput`,\n `(i.e. IOPS), upstream CPU, and network bandwidth may also be bottlenecks.`,\n ],\n },\n\n profileCopy: {\n type: v.boolean().optional(),\n hidden: true,\n desc: [\n `Takes a cpu profile during the copy phase initial-sync, storing it as a JSON file`,\n `initial-copy.cpuprofile in the tmp directory.`,\n ],\n },\n\n textCopy: {\n type: v.boolean().default(false),\n desc: [\n `Use text-format COPY instead of binary COPY for initial sync and`,\n `backfill streaming. This is slower but can work around issues with`,\n `binary encoding of certain data types.`,\n ],\n },\n },\n\n shadowSync: {\n enabled: {\n type: v.boolean().default(false),\n desc: [\n `Periodically exercises the initial-sync code path against a sample of`,\n `rows from every published table, writing to a throwaway SQLite database.`,\n `This acts as a canary: if the real initial-sync path ever breaks (schema`,\n `drift, PG version quirks, etc.), the shadow run fails before a customer`,\n `actually needs a full reset.`,\n ],\n },\n\n intervalHours: {\n type: v.number().default(24),\n desc: [\n `The interval between shadow initial-sync runs, in hours. The first run`,\n `is additionally staggered by a random fraction of this interval so that`,\n `a fleet restart does not cause all tasks to canary simultaneously.`,\n ],\n },\n\n sampleRate: {\n type: v.number().default(0.1),\n desc: [\n `The BERNOULLI sampling rate for each table (0 < rate <= 1). A value of`,\n `1 disables sampling and copies all rows (still subject to`,\n `{bold max-rows-per-table}).`,\n ],\n },\n\n maxRowsPerTable: {\n type: v.number().default(10000),\n desc: [\n `The hard upper bound on rows copied per table per shadow run. Guards`,\n `against unexpectedly large tables consuming disk / upstream bandwidth.`,\n ],\n },\n },\n\n /** @deprecated */\n targetClientRowCount: {\n type: v.number().default(20_000),\n deprecated: [\n 'This option is no longer used and will be removed in a future version.',\n 'The client-side cache no longer enforces a row limit. Instead, TTL-based expiration',\n 'automatically manages cache size to prevent unbounded growth.',\n ],\n hidden: true,\n },\n\n lazyStartup: {\n type: v.boolean().default(false),\n desc: [\n 'Delay starting the majority of zero-cache until first request.',\n '',\n 'This is mainly intended to avoid connecting to Postgres replication stream',\n 'until the first request is received, which can be useful i.e., for preview instances.',\n '',\n 'Currently only supported in single-node mode.',\n ],\n },\n\n serverVersion: {\n type: v.string().optional(),\n desc: [`The version string outputted to logs when the server starts up.`],\n },\n\n enableTelemetry: {\n type: v.boolean().default(true),\n desc: [\n `Set to false to opt out of telemetry collection.`,\n ``,\n `This helps us improve Zero by collecting anonymous usage data.`,\n `Setting the DO_NOT_TRACK environment variable also disables telemetry.`,\n ],\n },\n\n cloudEvent: {\n sinkEnv: {\n type: v.string().optional(),\n desc: [\n `ENV variable containing a URI to a CloudEvents sink. When set, ZeroEvents`,\n `will be published to the sink as the {bold data} field of CloudEvents.`,\n `The {bold source} field of the CloudEvents will be set to the {bold ZERO_TASK_ID},`,\n `along with any extension attributes specified by the {bold ZERO_CLOUD_EVENT_EXTENSION_OVERRIDES_ENV}.`,\n ``,\n `This configuration is modeled to easily integrate with a knative K_SINK binding,`,\n `(i.e. https://github.com/knative/eventing/blob/main/docs/spec/sources.md#sinkbinding).`,\n `However, any CloudEvents sink can be used.`,\n ],\n },\n\n extensionOverridesEnv: {\n type: v.string().optional(),\n desc: [\n `ENV variable containing a JSON stringified object with an {bold extensions} field`,\n `containing attributes that should be added or overridden on outbound CloudEvents.`,\n ``,\n `This configuration is modeled to easily integrate with a knative K_CE_OVERRIDES binding,`,\n `(i.e. https://github.com/knative/eventing/blob/main/docs/spec/sources.md#sinkbinding).`,\n ],\n },\n },\n};\n\nexport type ZeroConfig = Config<typeof zeroOptions>;\n\nlet loadedConfig: Config<typeof zeroOptions> | undefined;\n\nexport function getZeroConfig(\n opts: Omit<ParseOptions, 'envNamePrefix'> = {},\n): ZeroConfig {\n if (!loadedConfig || singleProcessMode()) {\n loadedConfig = parseOptions(zeroOptions, {\n envNamePrefix: ZERO_ENV_VAR_PREFIX,\n emitDeprecationWarnings: false, // overridden at the top level parse\n ...opts,\n });\n\n if (loadedConfig.queryHydrationStats) {\n runtimeDebugFlags.trackRowCountsVended = true;\n }\n }\n return loadedConfig;\n}\n\n/**\n * Same as {@link getZeroConfig}, with an additional check that the\n * config has already been normalized (i.e. by the top level server/runner).\n */\nexport function getNormalizedZeroConfig(\n opts: Omit<ParseOptions, 'envNamePrefix'> = {},\n): NormalizedZeroConfig {\n const config = getZeroConfig(opts);\n assertNormalized(config);\n return config;\n}\n\n/**\n * Gets the server version from the config if provided. Otherwise it gets it\n * from the Zero package.json.\n */\nexport function getServerVersion(\n config: Pick<ZeroConfig, 'serverVersion'> | undefined,\n): string {\n return config?.serverVersion ?? packageJson.version;\n}\n\nexport function isAdminPasswordValid(\n lc: LogContext,\n config: Pick<NormalizedZeroConfig, 'adminPassword'>,\n password: string | undefined,\n) {\n // If development mode, password is optional\n // We use process.env.NODE_ENV === 'development' as a sign that we're in\n // development mode, rather than a custom env var like ZERO_DEVELOPMENT_MODE,\n // because NODE_ENV is more standard and is already used by many tools.\n // Note that if NODE_ENV is not set, we assume production mode.\n\n if (!password && !config.adminPassword && isDevelopmentMode()) {\n warnOnce(\n lc,\n 'No admin password set; allowing access in development mode only',\n );\n return true;\n }\n\n if (!config.adminPassword) {\n lc.warn?.('No admin password set; denying access');\n return false;\n }\n\n // Use constant-time comparison to prevent timing attacks\n const passwordBuffer = Buffer.from(password ?? '');\n const configBuffer = Buffer.from(config.adminPassword);\n\n // Handle length mismatch in constant time\n if (passwordBuffer.length !== configBuffer.length) {\n // Perform dummy comparison to maintain constant timing\n timingSafeEqual(configBuffer, configBuffer);\n lc.warn?.('Invalid admin password');\n return false;\n }\n\n if (!timingSafeEqual(passwordBuffer, configBuffer)) {\n lc.warn?.('Invalid admin password');\n return false;\n }\n\n lc.debug?.('Admin password accepted');\n return true;\n}\n\nlet hasWarned = false;\n\nfunction warnOnce(lc: LogContext, msg: string) {\n if (!hasWarned) {\n lc.warn?.(msg);\n hasWarned = true;\n }\n}\n\n// For testing purposes - reset the warning state\nexport function resetWarnOnceState() {\n hasWarned = false;\n}\n"],"mappings":";;;;;;;;;;;;;;AA8BA,IAAa,sBAAsB;AAEnC,IAAa,aAAa;CACxB,IAAI;EACF,MAAM,eACH,QAAQ,CACR,QAAQ,OAAO,CACf,QAAO,OAAM,0BAA0B,KAAK,GAAG,EAAE,uBAAuB;EAC3E,MAAM;GACJ;GACA;GAC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mB,EAAE;AACxC,iBAAe,aAAa,aAAa;GACvC,eAAe;GACf,yBAAyB;GACzB,GAAG;GACJ,CAAC;AAEF,MAAI,aAAa,oBACf,mBAAkB,uBAAuB;;AAG7C,QAAO;;;;;;AAOT,SAAgB,wBACd,OAA4C,EAAE,EACxB;CACtB,MAAM,SAAS,cAAc,KAAK;AAClC,kBAAiB,OAAO;AACxB,QAAO;;;;;;AAOT,SAAgB,iBACd,QACQ;AACR,QAAO,QAAQ,iBAAiB,gBAAY;;AAG9C,SAAgB,qBACd,IACA,QACA,UACA;AAOA,KAAI,CAAC,YAAY,CAAC,OAAO,iBAAiB,mBAAmB,EAAE;AAC7D,WACE,IACA,kEACD;AACD,SAAO;;AAGT,KAAI,CAAC,OAAO,eAAe;AACzB,KAAG,OAAO,wCAAwC;AAClD,SAAO;;CAIT,MAAM,iBAAiB,OAAO,KAAK,YAAY,GAAG;CAClD,MAAM,eAAe,OAAO,KAAK,OAAO,cAAc;AAGtD,KAAI,eAAe,WAAW,aAAa,QAAQ;AAEjD,kBAAgB,cAAc,aAAa;AAC3C,KAAG,OAAO,yBAAyB;AACnC,SAAO;;AAGT,KAAI,CAAC,gBAAgB,gBAAgB,aAAa,EAAE;AAClD,KAAG,OAAO,yBAAyB;AACnC,SAAO;;AAGT,IAAG,QAAQ,0BAA0B;AACrC,QAAO;;AAGT,IAAI,YAAY;AAEhB,SAAS,SAAS,IAAgB,KAAa;AAC7C,KAAI,CAAC,WAAW;AACd,KAAG,OAAO,IAAI;AACd,cAAY"}
@@ -1 +1 @@
1
- {"version":3,"file":"decommission.d.ts","sourceRoot":"","sources":["../../../../../zero-cache/src/scripts/decommission.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAC,UAAU,EAAC,MAAM,kBAAkB,CAAC;AAEjD,OAAO,KAAK,EAAC,MAAM,EAAC,MAAM,gCAAgC,CAAC;AAO3D,eAAO,MAAM,mBAAmB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CAuB/B,CAAC;AAEF,MAAM,MAAM,kBAAkB,GAAG,MAAM,CAAC,OAAO,mBAAmB,CAAC,CAAC;AAEpE,wBAAsB,gBAAgB,CACpC,EAAE,EAAE,UAAU,EACd,GAAG,EAAE,kBAAkB,iBA0BxB"}
1
+ {"version":3,"file":"decommission.d.ts","sourceRoot":"","sources":["../../../../../zero-cache/src/scripts/decommission.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAC,UAAU,EAAC,MAAM,kBAAkB,CAAC;AAEjD,OAAO,KAAK,EAAC,MAAM,EAAC,MAAM,gCAAgC,CAAC;AAO3D,eAAO,MAAM,mBAAmB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CAuB/B,CAAC;AAEF,MAAM,MAAM,kBAAkB,GAAG,MAAM,CAAC,OAAO,mBAAmB,CAAC,CAAC;AAEpE,wBAAsB,gBAAgB,CACpC,EAAE,EAAE,UAAU,EACd,GAAG,EAAE,kBAAkB,iBA8BxB"}
@@ -24,17 +24,17 @@ async function decommissionZero(lc, cfg) {
24
24
  const shardID = getShardID(cfg);
25
25
  lc.info?.(`Decommissioning app "${app.id}"`);
26
26
  if (cfg.upstream.type === "pg") {
27
- const upstream = pgClient(lc, cfg.upstream.db);
27
+ const upstream = pgClient(lc, cfg.upstream.db, "decommission-upstream");
28
28
  await decommissionShard(lc, upstream, app.id, shard.num);
29
29
  lc.debug?.(`Cleaning up upstream metadata from ${hostPort(upstream)}`);
30
30
  await upstream.unsafe(`DROP SCHEMA IF EXISTS ${id(app.id)} CASCADE`);
31
31
  await upstream.end();
32
32
  }
33
- const cvr = pgClient(lc, cfg.cvr.db ?? cfg.upstream.db);
33
+ const cvr = pgClient(lc, cfg.cvr.db ?? cfg.upstream.db, "decommission-cvr");
34
34
  lc.debug?.(`Cleaning up cvc data from ${hostPort(cvr)}`);
35
35
  await cvr.unsafe(`DROP SCHEMA IF EXISTS ${id(cvrSchema(shardID))} CASCADE`);
36
36
  await cvr.end();
37
- const cdc = pgClient(lc, cfg.change.db ?? cfg.upstream.db);
37
+ const cdc = pgClient(lc, cfg.change.db ?? cfg.upstream.db, "decommission-cdc");
38
38
  lc.debug?.(`Cleaning up cdc data from ${hostPort(cdc)}`);
39
39
  await cdc.unsafe(`DROP SCHEMA IF EXISTS ${id(cdcSchema(shardID))} CASCADE`);
40
40
  await cdc.end();