@rocicorp/zero 0.25.0-canary.6 → 0.25.0-canary.8

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 (1367) hide show
  1. package/out/analyze-query/src/bin-analyze.js +258 -236
  2. package/out/analyze-query/src/bin-analyze.js.map +1 -1
  3. package/out/analyze-query/src/bin-transform.js +31 -23
  4. package/out/analyze-query/src/bin-transform.js.map +1 -1
  5. package/out/analyze-query/src/explain-queries.js +13 -16
  6. package/out/analyze-query/src/explain-queries.js.map +1 -1
  7. package/out/analyze-query/src/run-ast.d.ts +3 -2
  8. package/out/analyze-query/src/run-ast.d.ts.map +1 -1
  9. package/out/analyze-query/src/run-ast.js +79 -73
  10. package/out/analyze-query/src/run-ast.js.map +1 -1
  11. package/out/ast-to-zql/src/ast-to-zql.js +146 -180
  12. package/out/ast-to-zql/src/ast-to-zql.js.map +1 -1
  13. package/out/ast-to-zql/src/bin.js +51 -54
  14. package/out/ast-to-zql/src/bin.js.map +1 -1
  15. package/out/ast-to-zql/src/format.js +15 -14
  16. package/out/ast-to-zql/src/format.js.map +1 -1
  17. package/out/datadog/src/datadog-log-sink.js +223 -0
  18. package/out/datadog/src/datadog-log-sink.js.map +1 -0
  19. package/out/otel/src/enabled.js +15 -15
  20. package/out/otel/src/enabled.js.map +1 -1
  21. package/out/otel/src/log-options.js +36 -31
  22. package/out/otel/src/log-options.js.map +1 -1
  23. package/out/otel/src/maybe-time.js +14 -11
  24. package/out/otel/src/maybe-time.js.map +1 -1
  25. package/out/otel/src/span.js +30 -27
  26. package/out/otel/src/span.js.map +1 -1
  27. package/out/otel/src/test-log-config.js +10 -7
  28. package/out/otel/src/test-log-config.js.map +1 -1
  29. package/out/otel/src/version.js +5 -2
  30. package/out/otel/src/version.js.map +1 -1
  31. package/out/replicache/src/async-iterable-to-array.js +11 -0
  32. package/out/replicache/src/async-iterable-to-array.js.map +1 -0
  33. package/out/replicache/src/bg-interval.js +38 -0
  34. package/out/replicache/src/bg-interval.js.map +1 -0
  35. package/out/replicache/src/btree/diff.js +8 -0
  36. package/out/replicache/src/btree/diff.js.map +1 -0
  37. package/out/replicache/src/btree/node.js +400 -0
  38. package/out/replicache/src/btree/node.js.map +1 -0
  39. package/out/replicache/src/btree/read.d.ts +3 -2
  40. package/out/replicache/src/btree/read.d.ts.map +1 -1
  41. package/out/replicache/src/btree/read.js +266 -0
  42. package/out/replicache/src/btree/read.js.map +1 -0
  43. package/out/replicache/src/btree/splice.js +83 -0
  44. package/out/replicache/src/btree/splice.js.map +1 -0
  45. package/out/replicache/src/btree/write.d.ts +1 -1
  46. package/out/replicache/src/btree/write.d.ts.map +1 -1
  47. package/out/replicache/src/btree/write.js +163 -0
  48. package/out/replicache/src/btree/write.js.map +1 -0
  49. package/out/replicache/src/call-default-fetch.js +34 -0
  50. package/out/replicache/src/call-default-fetch.js.map +1 -0
  51. package/out/replicache/src/connection-loop-delegates.js +34 -0
  52. package/out/replicache/src/connection-loop-delegates.js.map +1 -0
  53. package/out/replicache/src/connection-loop.js +251 -0
  54. package/out/replicache/src/connection-loop.js.map +1 -0
  55. package/out/replicache/src/cookies.js +40 -0
  56. package/out/replicache/src/cookies.js.map +1 -0
  57. package/out/replicache/src/dag/chunk.js +59 -0
  58. package/out/replicache/src/dag/chunk.js.map +1 -0
  59. package/out/replicache/src/dag/gc.js +117 -0
  60. package/out/replicache/src/dag/gc.js.map +1 -0
  61. package/out/replicache/src/dag/key.js +20 -0
  62. package/out/replicache/src/dag/key.js.map +1 -0
  63. package/out/replicache/src/dag/lazy-store.d.ts +2 -1
  64. package/out/replicache/src/dag/lazy-store.d.ts.map +1 -1
  65. package/out/replicache/src/dag/lazy-store.js +515 -0
  66. package/out/replicache/src/dag/lazy-store.js.map +1 -0
  67. package/out/replicache/src/dag/store-impl.js +183 -0
  68. package/out/replicache/src/dag/store-impl.js.map +1 -0
  69. package/out/replicache/src/dag/store.js +27 -0
  70. package/out/replicache/src/dag/store.js.map +1 -0
  71. package/out/replicache/src/dag/visitor.js +22 -0
  72. package/out/replicache/src/dag/visitor.js.map +1 -0
  73. package/out/replicache/src/db/commit.js +358 -0
  74. package/out/replicache/src/db/commit.js.map +1 -0
  75. package/out/replicache/src/db/index-operation-enum.js +7 -0
  76. package/out/replicache/src/db/index-operation-enum.js.map +1 -0
  77. package/out/replicache/src/db/index.js +134 -0
  78. package/out/replicache/src/db/index.js.map +1 -0
  79. package/out/replicache/src/db/meta-type-enum.js +7 -0
  80. package/out/replicache/src/db/meta-type-enum.js.map +1 -0
  81. package/out/replicache/src/db/read.d.ts +3 -2
  82. package/out/replicache/src/db/read.d.ts.map +1 -1
  83. package/out/replicache/src/db/read.js +72 -0
  84. package/out/replicache/src/db/read.js.map +1 -0
  85. package/out/replicache/src/db/rebase.d.ts +2 -2
  86. package/out/replicache/src/db/rebase.d.ts.map +1 -1
  87. package/out/replicache/src/db/rebase.js +85 -0
  88. package/out/replicache/src/db/rebase.js.map +1 -0
  89. package/out/replicache/src/db/write.d.ts +2 -1
  90. package/out/replicache/src/db/write.d.ts.map +1 -1
  91. package/out/replicache/src/db/write.js +296 -0
  92. package/out/replicache/src/db/write.js.map +1 -0
  93. package/out/replicache/src/deleted-clients.js +104 -0
  94. package/out/replicache/src/deleted-clients.js.map +1 -0
  95. package/out/replicache/src/error-responses.js +34 -0
  96. package/out/replicache/src/error-responses.js.map +1 -0
  97. package/out/replicache/src/format-version-enum.js +11 -0
  98. package/out/replicache/src/format-version-enum.js.map +1 -0
  99. package/out/{chunk-EZM3XBAB.js → replicache/src/frozen-json.js} +8 -75
  100. package/out/replicache/src/frozen-json.js.map +1 -0
  101. package/out/replicache/src/get-default-puller.js +61 -0
  102. package/out/replicache/src/get-default-puller.js.map +1 -0
  103. package/out/replicache/src/get-default-pusher.js +39 -0
  104. package/out/replicache/src/get-default-pusher.js.map +1 -0
  105. package/out/replicache/src/get-kv-store-provider.js +23 -0
  106. package/out/replicache/src/get-kv-store-provider.js.map +1 -0
  107. package/out/replicache/src/hash.js +38 -0
  108. package/out/replicache/src/hash.js.map +1 -0
  109. package/out/replicache/src/http-request-info.js +10 -0
  110. package/out/replicache/src/http-request-info.js.map +1 -0
  111. package/out/replicache/src/http-status-unauthorized.js +5 -0
  112. package/out/replicache/src/http-status-unauthorized.js.map +1 -0
  113. package/out/replicache/src/index-defs.js +32 -0
  114. package/out/replicache/src/index-defs.js.map +1 -0
  115. package/out/replicache/src/invoke-kind-enum.js +7 -0
  116. package/out/replicache/src/invoke-kind-enum.js.map +1 -0
  117. package/out/{chunk-HCZQVP5R.js → replicache/src/kv/expo-sqlite/store.js} +8 -16
  118. package/out/replicache/src/kv/expo-sqlite/store.js.map +1 -0
  119. package/out/replicache/src/kv/idb-store-with-mem-fallback.js +80 -0
  120. package/out/replicache/src/kv/idb-store-with-mem-fallback.js.map +1 -0
  121. package/out/replicache/src/kv/idb-store.js +183 -0
  122. package/out/replicache/src/kv/idb-store.js.map +1 -0
  123. package/out/replicache/src/kv/mem-store.js +51 -0
  124. package/out/replicache/src/kv/mem-store.js.map +1 -0
  125. package/out/{op-sqlite.js → replicache/src/kv/op-sqlite/store.js} +7 -18
  126. package/out/replicache/src/kv/op-sqlite/store.js.map +1 -0
  127. package/out/replicache/src/kv/op-sqlite/types.js +6 -0
  128. package/out/replicache/src/kv/op-sqlite/types.js.map +1 -0
  129. package/out/replicache/src/kv/read-impl.js +27 -0
  130. package/out/replicache/src/kv/read-impl.js.map +1 -0
  131. package/out/{chunk-WPAQ4EPM.js → replicache/src/kv/sqlite-store.js} +15 -19
  132. package/out/replicache/src/kv/sqlite-store.js.map +1 -0
  133. package/out/{chunk-ASRS2LFV.js → replicache/src/kv/throw-if-closed.js} +4 -6
  134. package/out/replicache/src/kv/throw-if-closed.js.map +1 -0
  135. package/out/replicache/src/kv/write-impl-base.js +57 -0
  136. package/out/replicache/src/kv/write-impl-base.js.map +1 -0
  137. package/out/replicache/src/kv/write-impl.js +30 -0
  138. package/out/replicache/src/kv/write-impl.js.map +1 -0
  139. package/out/replicache/src/lazy.js +13 -0
  140. package/out/replicache/src/lazy.js.map +1 -0
  141. package/out/replicache/src/log-options.js +9 -0
  142. package/out/replicache/src/log-options.js.map +1 -0
  143. package/out/replicache/src/make-idb-name.js +13 -0
  144. package/out/replicache/src/make-idb-name.js.map +1 -0
  145. package/out/replicache/src/new-client-channel.js +51 -0
  146. package/out/replicache/src/new-client-channel.js.map +1 -0
  147. package/out/replicache/src/on-persist-channel.js +36 -0
  148. package/out/replicache/src/on-persist-channel.js.map +1 -0
  149. package/out/replicache/src/patch-operation.js +42 -0
  150. package/out/replicache/src/patch-operation.js.map +1 -0
  151. package/out/replicache/src/pending-mutations.js +16 -0
  152. package/out/replicache/src/pending-mutations.js.map +1 -0
  153. package/out/replicache/src/persist/client-gc.js +58 -0
  154. package/out/replicache/src/persist/client-gc.js.map +1 -0
  155. package/out/replicache/src/persist/client-group-gc.js +43 -0
  156. package/out/replicache/src/persist/client-group-gc.js.map +1 -0
  157. package/out/replicache/src/persist/client-groups.js +184 -0
  158. package/out/replicache/src/persist/client-groups.js.map +1 -0
  159. package/out/replicache/src/persist/clients.d.ts +3 -2
  160. package/out/replicache/src/persist/clients.d.ts.map +1 -1
  161. package/out/replicache/src/persist/clients.js +353 -0
  162. package/out/replicache/src/persist/clients.js.map +1 -0
  163. package/out/replicache/src/persist/collect-idb-databases.js +188 -0
  164. package/out/replicache/src/persist/collect-idb-databases.js.map +1 -0
  165. package/out/replicache/src/persist/gather-mem-only-visitor.js +27 -0
  166. package/out/replicache/src/persist/gather-mem-only-visitor.js.map +1 -0
  167. package/out/replicache/src/persist/gather-not-cached-visitor.js +37 -0
  168. package/out/replicache/src/persist/gather-not-cached-visitor.js.map +1 -0
  169. package/out/replicache/src/persist/heartbeat.js +48 -0
  170. package/out/replicache/src/persist/heartbeat.js.map +1 -0
  171. package/out/replicache/src/persist/idb-databases-store-db-name.js +14 -0
  172. package/out/replicache/src/persist/idb-databases-store-db-name.js.map +1 -0
  173. package/out/replicache/src/persist/idb-databases-store.js +92 -0
  174. package/out/replicache/src/persist/idb-databases-store.js.map +1 -0
  175. package/out/replicache/src/persist/make-client-id.js +12 -0
  176. package/out/replicache/src/persist/make-client-id.js.map +1 -0
  177. package/out/replicache/src/persist/persist.d.ts +2 -2
  178. package/out/replicache/src/persist/persist.d.ts.map +1 -1
  179. package/out/replicache/src/persist/persist.js +183 -0
  180. package/out/replicache/src/persist/persist.js.map +1 -0
  181. package/out/replicache/src/persist/refresh.d.ts +4 -3
  182. package/out/replicache/src/persist/refresh.d.ts.map +1 -1
  183. package/out/replicache/src/persist/refresh.js +198 -0
  184. package/out/replicache/src/persist/refresh.js.map +1 -0
  185. package/out/replicache/src/process-scheduler.js +96 -0
  186. package/out/replicache/src/process-scheduler.js.map +1 -0
  187. package/out/replicache/src/pusher.js +33 -0
  188. package/out/replicache/src/pusher.js.map +1 -0
  189. package/out/replicache/src/replicache-impl.d.ts +1 -1
  190. package/out/replicache/src/replicache-impl.d.ts.map +1 -1
  191. package/out/replicache/src/replicache-impl.js +1200 -0
  192. package/out/replicache/src/replicache-impl.js.map +1 -0
  193. package/out/replicache/src/report-error.js +6 -0
  194. package/out/replicache/src/report-error.js.map +1 -0
  195. package/out/replicache/src/request-idle.js +13 -0
  196. package/out/replicache/src/request-idle.js.map +1 -0
  197. package/out/replicache/src/scan-iterator.js +146 -0
  198. package/out/replicache/src/scan-iterator.js.map +1 -0
  199. package/out/replicache/src/scan-options.js +45 -0
  200. package/out/replicache/src/scan-options.js.map +1 -0
  201. package/out/replicache/src/set-interval-with-signal.js +12 -0
  202. package/out/replicache/src/set-interval-with-signal.js.map +1 -0
  203. package/out/replicache/src/subscriptions.js +355 -0
  204. package/out/replicache/src/subscriptions.js.map +1 -0
  205. package/out/replicache/src/sync/diff.d.ts +3 -2
  206. package/out/replicache/src/sync/diff.d.ts.map +1 -1
  207. package/out/replicache/src/sync/diff.js +72 -0
  208. package/out/replicache/src/sync/diff.js.map +1 -0
  209. package/out/replicache/src/sync/handle-pull-response-result-type-enum.js +9 -0
  210. package/out/replicache/src/sync/handle-pull-response-result-type-enum.js.map +1 -0
  211. package/out/replicache/src/sync/ids.js +9 -0
  212. package/out/replicache/src/sync/ids.js.map +1 -0
  213. package/out/replicache/src/sync/patch.js +49 -0
  214. package/out/replicache/src/sync/patch.js.map +1 -0
  215. package/out/replicache/src/sync/pull-error.js +16 -0
  216. package/out/replicache/src/sync/pull-error.js.map +1 -0
  217. package/out/replicache/src/sync/pull.d.ts +3 -2
  218. package/out/replicache/src/sync/pull.d.ts.map +1 -1
  219. package/out/replicache/src/sync/pull.js +301 -0
  220. package/out/replicache/src/sync/pull.js.map +1 -0
  221. package/out/replicache/src/sync/push.js +88 -0
  222. package/out/replicache/src/sync/push.js.map +1 -0
  223. package/out/replicache/src/sync/request-id.js +20 -0
  224. package/out/replicache/src/sync/request-id.js.map +1 -0
  225. package/out/replicache/src/sync/sync-head-name.js +5 -0
  226. package/out/replicache/src/sync/sync-head-name.js.map +1 -0
  227. package/out/replicache/src/to-error.js +10 -0
  228. package/out/replicache/src/to-error.js.map +1 -0
  229. package/out/replicache/src/transaction-closed-error.js +19 -0
  230. package/out/replicache/src/transaction-closed-error.js.map +1 -0
  231. package/out/replicache/src/transactions.js +152 -0
  232. package/out/replicache/src/transactions.js.map +1 -0
  233. package/out/replicache/src/version.js +5 -0
  234. package/out/replicache/src/version.js.map +1 -0
  235. package/out/replicache/src/with-transactions.js +28 -0
  236. package/out/replicache/src/with-transactions.js.map +1 -0
  237. package/out/shared/src/abort-error.js +6 -3
  238. package/out/shared/src/abort-error.js.map +1 -1
  239. package/out/shared/src/arrays.js +45 -43
  240. package/out/shared/src/arrays.js.map +1 -1
  241. package/out/shared/src/asserts.js +64 -68
  242. package/out/shared/src/asserts.js.map +1 -1
  243. package/out/shared/src/bigint-json.js +38 -42
  244. package/out/shared/src/bigint-json.js.map +1 -1
  245. package/out/shared/src/binary-search.js +18 -29
  246. package/out/shared/src/binary-search.js.map +1 -1
  247. package/out/shared/src/broadcast-channel.js +24 -0
  248. package/out/shared/src/broadcast-channel.js.map +1 -0
  249. package/out/shared/src/browser-env.js +25 -0
  250. package/out/shared/src/browser-env.js.map +1 -0
  251. package/out/shared/src/btree-set.js +464 -507
  252. package/out/shared/src/btree-set.js.map +1 -1
  253. package/out/shared/src/cache.js +34 -38
  254. package/out/shared/src/cache.js.map +1 -1
  255. package/out/shared/src/centroid.js +24 -24
  256. package/out/shared/src/centroid.js.map +1 -1
  257. package/out/shared/src/config.js +6 -3
  258. package/out/shared/src/config.js.map +1 -1
  259. package/out/shared/src/custom-key-map.js +58 -64
  260. package/out/shared/src/custom-key-map.js.map +1 -1
  261. package/out/shared/src/custom-key-set.js +51 -57
  262. package/out/shared/src/custom-key-set.js.map +1 -1
  263. package/out/shared/src/deep-clone.js +46 -0
  264. package/out/shared/src/deep-clone.js.map +1 -0
  265. package/out/shared/src/document-visible.js +74 -0
  266. package/out/shared/src/document-visible.js.map +1 -0
  267. package/out/shared/src/dotenv.js +5 -7
  268. package/out/shared/src/dotenv.js.map +1 -1
  269. package/out/shared/src/error.js +57 -56
  270. package/out/shared/src/error.js.map +1 -1
  271. package/out/shared/src/has-own.js +5 -3
  272. package/out/shared/src/has-own.js.map +1 -1
  273. package/out/shared/src/hash.js +15 -14
  274. package/out/shared/src/hash.js.map +1 -1
  275. package/out/shared/src/iterables.js +71 -73
  276. package/out/shared/src/iterables.js.map +1 -1
  277. package/out/shared/src/json-schema.js +30 -33
  278. package/out/shared/src/json-schema.js.map +1 -1
  279. package/out/shared/src/json.js +128 -143
  280. package/out/shared/src/json.js.map +1 -1
  281. package/out/shared/src/logging-test-utils.js +12 -19
  282. package/out/shared/src/logging-test-utils.js.map +1 -1
  283. package/out/shared/src/logging.js +83 -83
  284. package/out/shared/src/logging.js.map +1 -1
  285. package/out/shared/src/must.js +9 -7
  286. package/out/shared/src/must.js.map +1 -1
  287. package/out/shared/src/navigator.js +5 -0
  288. package/out/shared/src/navigator.js.map +1 -0
  289. package/out/shared/src/objects.js +21 -22
  290. package/out/shared/src/objects.js.map +1 -1
  291. package/out/shared/src/options.d.ts +2 -0
  292. package/out/shared/src/options.d.ts.map +1 -1
  293. package/out/shared/src/options.js +289 -318
  294. package/out/shared/src/options.js.map +1 -1
  295. package/out/shared/src/parse-big-int.js +12 -10
  296. package/out/shared/src/parse-big-int.js.map +1 -1
  297. package/out/shared/src/promise-race.js +20 -0
  298. package/out/shared/src/promise-race.js.map +1 -0
  299. package/out/shared/src/queue.js +119 -122
  300. package/out/shared/src/queue.js.map +1 -1
  301. package/out/shared/src/rand.js +8 -10
  302. package/out/shared/src/rand.js.map +1 -1
  303. package/out/shared/src/random-uint64.js +9 -0
  304. package/out/shared/src/random-uint64.js.map +1 -0
  305. package/out/shared/src/random-values.js +13 -0
  306. package/out/shared/src/random-values.js.map +1 -0
  307. package/out/shared/src/resolved-promises.js +12 -9
  308. package/out/shared/src/resolved-promises.js.map +1 -1
  309. package/out/shared/src/sentinels.js +13 -6
  310. package/out/shared/src/sentinels.js.map +1 -1
  311. package/out/shared/src/set-utils.js +63 -62
  312. package/out/shared/src/set-utils.js.map +1 -1
  313. package/out/shared/src/size-of-value.js +58 -0
  314. package/out/shared/src/size-of-value.js.map +1 -0
  315. package/out/shared/src/sleep.js +45 -53
  316. package/out/shared/src/sleep.js.map +1 -1
  317. package/out/shared/src/string-compare.js +12 -9
  318. package/out/shared/src/string-compare.js.map +1 -1
  319. package/out/shared/src/subscribable.js +34 -0
  320. package/out/shared/src/subscribable.js.map +1 -0
  321. package/out/shared/src/tdigest-schema.js +7 -7
  322. package/out/shared/src/tdigest-schema.js.map +1 -1
  323. package/out/shared/src/tdigest.js +247 -271
  324. package/out/shared/src/tdigest.js.map +1 -1
  325. package/out/shared/src/valita.js +195 -207
  326. package/out/shared/src/valita.js.map +1 -1
  327. package/out/z2s/src/compiler.d.ts.map +1 -1
  328. package/out/z2s/src/compiler.js +437 -310
  329. package/out/z2s/src/compiler.js.map +1 -1
  330. package/out/z2s/src/sql.js +186 -218
  331. package/out/z2s/src/sql.js.map +1 -1
  332. package/out/zero/package.json.js +9 -0
  333. package/out/zero/package.json.js.map +1 -0
  334. package/out/zero/src/adapters/drizzle.js +5 -2
  335. package/out/zero/src/adapters/drizzle.js.map +1 -1
  336. package/out/zero/src/adapters/pg.js +7 -2
  337. package/out/zero/src/adapters/pg.js.map +1 -1
  338. package/out/zero/src/adapters/postgresjs.js +7 -2
  339. package/out/zero/src/adapters/postgresjs.js.map +1 -1
  340. package/out/zero/src/analyze-query.js +1 -1
  341. package/out/zero/src/analyze-query.js.map +1 -1
  342. package/out/zero/src/ast-to-zql.js +1 -1
  343. package/out/zero/src/ast-to-zql.js.map +1 -1
  344. package/out/zero/src/build-schema.js +3 -5
  345. package/out/zero/src/build-schema.js.map +1 -1
  346. package/out/zero/src/change-protocol/v0.js +5 -3
  347. package/out/zero/src/change-protocol/v0.js.map +1 -1
  348. package/out/zero/src/cli.js +2 -2
  349. package/out/zero/src/cli.js.map +1 -1
  350. package/out/zero/src/deploy-permissions.js +1 -1
  351. package/out/zero/src/deploy-permissions.js.map +1 -1
  352. package/out/zero/src/expo-sqlite.js +5 -0
  353. package/out/zero/src/expo-sqlite.js.map +1 -0
  354. package/out/zero/src/op-sqlite.js +5 -0
  355. package/out/zero/src/op-sqlite.js.map +1 -0
  356. package/out/zero/src/pg.js +31 -3
  357. package/out/zero/src/pg.js.map +1 -1
  358. package/out/zero/src/react-native.js +13 -0
  359. package/out/zero/src/react-native.js.map +1 -0
  360. package/out/zero/src/react.js +17 -0
  361. package/out/zero/src/react.js.map +1 -0
  362. package/out/zero/src/server.js +27 -3
  363. package/out/zero/src/server.js.map +1 -1
  364. package/out/zero/src/solid.js +15 -0
  365. package/out/zero/src/solid.js.map +1 -0
  366. package/out/zero/src/sqlite.js +7 -0
  367. package/out/zero/src/sqlite.js.map +1 -0
  368. package/out/zero/src/transform-query.js +1 -1
  369. package/out/zero/src/transform-query.js.map +1 -1
  370. package/out/zero/src/zero-cache-dev.js +135 -124
  371. package/out/zero/src/zero-cache-dev.js.map +1 -1
  372. package/out/zero/src/zero-out.js +6 -6
  373. package/out/zero/src/zero-out.js.map +1 -1
  374. package/out/zero/src/zero.js +55 -0
  375. package/out/zero/src/zero.js.map +1 -0
  376. package/out/zero/src/zqlite.js +11 -3
  377. package/out/zero/src/zqlite.js.map +1 -1
  378. package/out/zero-cache/src/auth/jwt.js +33 -38
  379. package/out/zero-cache/src/auth/jwt.js.map +1 -1
  380. package/out/zero-cache/src/auth/load-permissions.js +61 -45
  381. package/out/zero-cache/src/auth/load-permissions.js.map +1 -1
  382. package/out/zero-cache/src/auth/read-authorizer.js +79 -91
  383. package/out/zero-cache/src/auth/read-authorizer.js.map +1 -1
  384. package/out/zero-cache/src/auth/write-authorizer.d.ts +2 -2
  385. package/out/zero-cache/src/auth/write-authorizer.d.ts.map +1 -1
  386. package/out/zero-cache/src/auth/write-authorizer.js +394 -349
  387. package/out/zero-cache/src/auth/write-authorizer.js.map +1 -1
  388. package/out/zero-cache/src/config/network.js +42 -45
  389. package/out/zero-cache/src/config/network.js.map +1 -1
  390. package/out/zero-cache/src/config/normalize.js +86 -83
  391. package/out/zero-cache/src/config/normalize.js.map +1 -1
  392. package/out/zero-cache/src/config/zero-config.js +676 -682
  393. package/out/zero-cache/src/config/zero-config.js.map +1 -1
  394. package/out/zero-cache/src/custom/fetch.d.ts.map +1 -1
  395. package/out/zero-cache/src/custom/fetch.js +166 -162
  396. package/out/zero-cache/src/custom/fetch.js.map +1 -1
  397. package/out/zero-cache/src/custom-queries/transform-query.d.ts +7 -0
  398. package/out/zero-cache/src/custom-queries/transform-query.d.ts.map +1 -1
  399. package/out/zero-cache/src/custom-queries/transform-query.js +101 -106
  400. package/out/zero-cache/src/custom-queries/transform-query.js.map +1 -1
  401. package/out/zero-cache/src/db/create.js +32 -36
  402. package/out/zero-cache/src/db/create.js.map +1 -1
  403. package/out/zero-cache/src/db/delete-lite-db.js +9 -6
  404. package/out/zero-cache/src/db/delete-lite-db.js.map +1 -1
  405. package/out/zero-cache/src/db/lite-tables.d.ts.map +1 -1
  406. package/out/zero-cache/src/db/lite-tables.js +150 -174
  407. package/out/zero-cache/src/db/lite-tables.js.map +1 -1
  408. package/out/zero-cache/src/db/migration-lite.js +170 -165
  409. package/out/zero-cache/src/db/migration-lite.js.map +1 -1
  410. package/out/zero-cache/src/db/migration.js +157 -137
  411. package/out/zero-cache/src/db/migration.js.map +1 -1
  412. package/out/zero-cache/src/db/mode-enum.d.ts +2 -0
  413. package/out/zero-cache/src/db/mode-enum.d.ts.map +1 -1
  414. package/out/zero-cache/src/db/mode-enum.js +9 -3
  415. package/out/zero-cache/src/db/mode-enum.js.map +1 -1
  416. package/out/zero-cache/src/db/pg-copy.js +51 -90
  417. package/out/zero-cache/src/db/pg-copy.js.map +1 -1
  418. package/out/zero-cache/src/db/pg-to-lite.js +114 -109
  419. package/out/zero-cache/src/db/pg-to-lite.js.map +1 -1
  420. package/out/zero-cache/src/db/pg-type-parser.js +27 -39
  421. package/out/zero-cache/src/db/pg-type-parser.js.map +1 -1
  422. package/out/zero-cache/src/db/postgres-replica-identity-enum.js +11 -6
  423. package/out/zero-cache/src/db/postgres-replica-identity-enum.js.map +1 -1
  424. package/out/zero-cache/src/db/postgres-type-class-enum.js +17 -9
  425. package/out/zero-cache/src/db/postgres-type-class-enum.js.map +1 -1
  426. package/out/zero-cache/src/db/specs.d.ts +0 -6
  427. package/out/zero-cache/src/db/specs.d.ts.map +1 -1
  428. package/out/zero-cache/src/db/specs.js +66 -40
  429. package/out/zero-cache/src/db/specs.js.map +1 -1
  430. package/out/zero-cache/src/db/statements.d.ts +1 -1
  431. package/out/zero-cache/src/db/statements.d.ts.map +1 -1
  432. package/out/zero-cache/src/db/statements.js +59 -52
  433. package/out/zero-cache/src/db/statements.js.map +1 -1
  434. package/out/zero-cache/src/db/transaction-pool.d.ts +1 -1
  435. package/out/zero-cache/src/db/transaction-pool.d.ts.map +1 -1
  436. package/out/zero-cache/src/db/transaction-pool.js +375 -501
  437. package/out/zero-cache/src/db/transaction-pool.js.map +1 -1
  438. package/out/zero-cache/src/db/warmup.js +25 -12
  439. package/out/zero-cache/src/db/warmup.js.map +1 -1
  440. package/out/zero-cache/src/observability/events.js +71 -82
  441. package/out/zero-cache/src/observability/events.js.map +1 -1
  442. package/out/zero-cache/src/observability/metrics.js +54 -32
  443. package/out/zero-cache/src/observability/metrics.js.map +1 -1
  444. package/out/zero-cache/src/scripts/decommission.js +47 -43
  445. package/out/zero-cache/src/scripts/decommission.js.map +1 -1
  446. package/out/zero-cache/src/scripts/deploy-permissions.js +128 -118
  447. package/out/zero-cache/src/scripts/deploy-permissions.js.map +1 -1
  448. package/out/zero-cache/src/scripts/permissions.js +107 -99
  449. package/out/zero-cache/src/scripts/permissions.js.map +1 -1
  450. package/out/zero-cache/src/server/anonymous-otel-start.js +410 -366
  451. package/out/zero-cache/src/server/anonymous-otel-start.js.map +1 -1
  452. package/out/zero-cache/src/server/change-streamer.js +104 -60
  453. package/out/zero-cache/src/server/change-streamer.js.map +1 -1
  454. package/out/zero-cache/src/server/inspector-delegate.js +112 -109
  455. package/out/zero-cache/src/server/inspector-delegate.js.map +1 -1
  456. package/out/zero-cache/src/server/logging.d.ts +1 -1
  457. package/out/zero-cache/src/server/logging.d.ts.map +1 -1
  458. package/out/zero-cache/src/server/logging.js +26 -19
  459. package/out/zero-cache/src/server/logging.js.map +1 -1
  460. package/out/zero-cache/src/server/main.d.ts.map +1 -1
  461. package/out/zero-cache/src/server/main.js +137 -120
  462. package/out/zero-cache/src/server/main.js.map +1 -1
  463. package/out/zero-cache/src/server/mutator.js +19 -0
  464. package/out/zero-cache/src/server/mutator.js.map +1 -0
  465. package/out/zero-cache/src/server/otel-diag-logger.d.ts +1 -1
  466. package/out/zero-cache/src/server/otel-diag-logger.d.ts.map +1 -1
  467. package/out/zero-cache/src/server/otel-diag-logger.js +67 -70
  468. package/out/zero-cache/src/server/otel-diag-logger.js.map +1 -1
  469. package/out/zero-cache/src/server/otel-log-sink.js +40 -41
  470. package/out/zero-cache/src/server/otel-log-sink.js.map +1 -1
  471. package/out/zero-cache/src/server/otel-start.d.ts +1 -1
  472. package/out/zero-cache/src/server/otel-start.d.ts.map +1 -1
  473. package/out/zero-cache/src/server/otel-start.js +57 -68
  474. package/out/zero-cache/src/server/otel-start.js.map +1 -1
  475. package/out/zero-cache/src/server/reaper.js +34 -26
  476. package/out/zero-cache/src/server/reaper.js.map +1 -1
  477. package/out/zero-cache/src/server/replicator.js +53 -31
  478. package/out/zero-cache/src/server/replicator.js.map +1 -1
  479. package/out/zero-cache/src/server/runner/main.js +6 -4
  480. package/out/zero-cache/src/server/runner/main.js.map +1 -1
  481. package/out/zero-cache/src/server/runner/run-worker.d.ts.map +1 -1
  482. package/out/zero-cache/src/server/runner/run-worker.js +46 -50
  483. package/out/zero-cache/src/server/runner/run-worker.js.map +1 -1
  484. package/out/zero-cache/src/server/runner/runtime.js +33 -32
  485. package/out/zero-cache/src/server/runner/runtime.js.map +1 -1
  486. package/out/zero-cache/src/server/runner/zero-dispatcher.d.ts.map +1 -1
  487. package/out/zero-cache/src/server/runner/zero-dispatcher.js +28 -22
  488. package/out/zero-cache/src/server/runner/zero-dispatcher.js.map +1 -1
  489. package/out/zero-cache/src/server/syncer.d.ts.map +1 -1
  490. package/out/zero-cache/src/server/syncer.js +112 -63
  491. package/out/zero-cache/src/server/syncer.js.map +1 -1
  492. package/out/zero-cache/src/server/worker-dispatcher.d.ts +1 -1
  493. package/out/zero-cache/src/server/worker-dispatcher.d.ts.map +1 -1
  494. package/out/zero-cache/src/server/worker-dispatcher.js +112 -106
  495. package/out/zero-cache/src/server/worker-dispatcher.js.map +1 -1
  496. package/out/zero-cache/src/server/worker-urls.d.ts +7 -0
  497. package/out/zero-cache/src/server/worker-urls.d.ts.map +1 -0
  498. package/out/zero-cache/src/server/worker-urls.js +21 -0
  499. package/out/zero-cache/src/server/worker-urls.js.map +1 -0
  500. package/out/zero-cache/src/services/analyze.d.ts +3 -4
  501. package/out/zero-cache/src/services/analyze.d.ts.map +1 -1
  502. package/out/zero-cache/src/services/analyze.js +96 -122
  503. package/out/zero-cache/src/services/analyze.js.map +1 -1
  504. package/out/zero-cache/src/services/change-source/column-metadata.js +152 -155
  505. package/out/zero-cache/src/services/change-source/column-metadata.js.map +1 -1
  506. package/out/zero-cache/src/services/change-source/custom/change-source.d.ts +1 -1
  507. package/out/zero-cache/src/services/change-source/custom/change-source.d.ts.map +1 -1
  508. package/out/zero-cache/src/services/change-source/custom/change-source.js +197 -171
  509. package/out/zero-cache/src/services/change-source/custom/change-source.js.map +1 -1
  510. package/out/zero-cache/src/services/change-source/custom/sync-schema.js +11 -3
  511. package/out/zero-cache/src/services/change-source/custom/sync-schema.js.map +1 -1
  512. package/out/zero-cache/src/services/change-source/pg/change-source.d.ts +1 -1
  513. package/out/zero-cache/src/services/change-source/pg/change-source.d.ts.map +1 -1
  514. package/out/zero-cache/src/services/change-source/pg/change-source.js +601 -622
  515. package/out/zero-cache/src/services/change-source/pg/change-source.js.map +1 -1
  516. package/out/zero-cache/src/services/change-source/pg/decommission.js +24 -23
  517. package/out/zero-cache/src/services/change-source/pg/decommission.js.map +1 -1
  518. package/out/zero-cache/src/services/change-source/pg/initial-sync.d.ts +1 -1
  519. package/out/zero-cache/src/services/change-source/pg/initial-sync.d.ts.map +1 -1
  520. package/out/zero-cache/src/services/change-source/pg/initial-sync.js +327 -284
  521. package/out/zero-cache/src/services/change-source/pg/initial-sync.js.map +1 -1
  522. package/out/zero-cache/src/services/change-source/pg/logical-replication/binary-reader.js +61 -69
  523. package/out/zero-cache/src/services/change-source/pg/logical-replication/binary-reader.js.map +1 -1
  524. package/out/zero-cache/src/services/change-source/pg/logical-replication/pgoutput-parser.js +247 -257
  525. package/out/zero-cache/src/services/change-source/pg/logical-replication/pgoutput-parser.js.map +1 -1
  526. package/out/zero-cache/src/services/change-source/pg/logical-replication/stream.js +127 -119
  527. package/out/zero-cache/src/services/change-source/pg/logical-replication/stream.js.map +1 -1
  528. package/out/zero-cache/src/services/change-source/pg/lsn.js +20 -19
  529. package/out/zero-cache/src/services/change-source/pg/lsn.js.map +1 -1
  530. package/out/zero-cache/src/services/change-source/pg/schema/ddl.js +96 -119
  531. package/out/zero-cache/src/services/change-source/pg/schema/ddl.js.map +1 -1
  532. package/out/zero-cache/src/services/change-source/pg/schema/init.js +138 -117
  533. package/out/zero-cache/src/services/change-source/pg/schema/init.js.map +1 -1
  534. package/out/zero-cache/src/services/change-source/pg/schema/published.js +67 -74
  535. package/out/zero-cache/src/services/change-source/pg/schema/published.js.map +1 -1
  536. package/out/zero-cache/src/services/change-source/pg/schema/shard.js +199 -188
  537. package/out/zero-cache/src/services/change-source/pg/schema/shard.js.map +1 -1
  538. package/out/zero-cache/src/services/change-source/pg/schema/validation.js +53 -38
  539. package/out/zero-cache/src/services/change-source/pg/schema/validation.js.map +1 -1
  540. package/out/zero-cache/src/services/change-source/pg/sync-schema.js +11 -3
  541. package/out/zero-cache/src/services/change-source/pg/sync-schema.js.map +1 -1
  542. package/out/zero-cache/src/services/change-source/protocol/current/control.js +9 -19
  543. package/out/zero-cache/src/services/change-source/protocol/current/control.js.map +1 -1
  544. package/out/zero-cache/src/services/change-source/protocol/current/data.js +143 -116
  545. package/out/zero-cache/src/services/change-source/protocol/current/data.js.map +1 -1
  546. package/out/zero-cache/src/services/change-source/protocol/current/downstream.js +29 -19
  547. package/out/zero-cache/src/services/change-source/protocol/current/downstream.js.map +1 -1
  548. package/out/zero-cache/src/services/change-source/protocol/current/path.js +5 -20
  549. package/out/zero-cache/src/services/change-source/protocol/current/path.js.map +1 -1
  550. package/out/zero-cache/src/services/change-source/protocol/current/status.js +12 -13
  551. package/out/zero-cache/src/services/change-source/protocol/current/status.js.map +1 -1
  552. package/out/zero-cache/src/services/change-source/protocol/current/upstream.d.ts +1 -1
  553. package/out/zero-cache/src/services/change-source/protocol/current/upstream.d.ts.map +1 -1
  554. package/out/zero-cache/src/services/change-source/protocol/current/upstream.js +5 -4
  555. package/out/zero-cache/src/services/change-source/protocol/current/upstream.js.map +1 -1
  556. package/out/zero-cache/src/services/change-source/protocol/current.js +35 -7
  557. package/out/zero-cache/src/services/change-source/protocol/current.js.map +1 -1
  558. package/out/zero-cache/src/services/change-source/replica-schema.js +64 -47
  559. package/out/zero-cache/src/services/change-source/replica-schema.js.map +1 -1
  560. package/out/zero-cache/src/services/change-streamer/backup-monitor.d.ts +1 -1
  561. package/out/zero-cache/src/services/change-streamer/backup-monitor.d.ts.map +1 -1
  562. package/out/zero-cache/src/services/change-streamer/backup-monitor.js +139 -157
  563. package/out/zero-cache/src/services/change-streamer/backup-monitor.js.map +1 -1
  564. package/out/zero-cache/src/services/change-streamer/change-streamer-http.d.ts +2 -2
  565. package/out/zero-cache/src/services/change-streamer/change-streamer-http.d.ts.map +1 -1
  566. package/out/zero-cache/src/services/change-streamer/change-streamer-http.js +178 -158
  567. package/out/zero-cache/src/services/change-streamer/change-streamer-http.js.map +1 -1
  568. package/out/zero-cache/src/services/change-streamer/change-streamer-service.d.ts +1 -1
  569. package/out/zero-cache/src/services/change-streamer/change-streamer-service.d.ts.map +1 -1
  570. package/out/zero-cache/src/services/change-streamer/change-streamer-service.js +235 -349
  571. package/out/zero-cache/src/services/change-streamer/change-streamer-service.js.map +1 -1
  572. package/out/zero-cache/src/services/change-streamer/change-streamer.d.ts +5 -1
  573. package/out/zero-cache/src/services/change-streamer/change-streamer.d.ts.map +1 -1
  574. package/out/zero-cache/src/services/change-streamer/change-streamer.js +24 -22
  575. package/out/zero-cache/src/services/change-streamer/change-streamer.js.map +1 -1
  576. package/out/zero-cache/src/services/change-streamer/error-type-enum.js +9 -4
  577. package/out/zero-cache/src/services/change-streamer/error-type-enum.js.map +1 -1
  578. package/out/zero-cache/src/services/change-streamer/forwarder.d.ts +1 -1
  579. package/out/zero-cache/src/services/change-streamer/forwarder.d.ts.map +1 -1
  580. package/out/zero-cache/src/services/change-streamer/forwarder.js +53 -57
  581. package/out/zero-cache/src/services/change-streamer/forwarder.js.map +1 -1
  582. package/out/zero-cache/src/services/change-streamer/replica-monitor.js +40 -44
  583. package/out/zero-cache/src/services/change-streamer/replica-monitor.js.map +1 -1
  584. package/out/zero-cache/src/services/change-streamer/schema/init.js +82 -68
  585. package/out/zero-cache/src/services/change-streamer/schema/init.js.map +1 -1
  586. package/out/zero-cache/src/services/change-streamer/schema/tables.d.ts +2 -2
  587. package/out/zero-cache/src/services/change-streamer/schema/tables.d.ts.map +1 -1
  588. package/out/zero-cache/src/services/change-streamer/schema/tables.js +93 -78
  589. package/out/zero-cache/src/services/change-streamer/schema/tables.js.map +1 -1
  590. package/out/zero-cache/src/services/change-streamer/snapshot.d.ts +58 -0
  591. package/out/zero-cache/src/services/change-streamer/snapshot.d.ts.map +1 -1
  592. package/out/zero-cache/src/services/change-streamer/snapshot.js +28 -18
  593. package/out/zero-cache/src/services/change-streamer/snapshot.js.map +1 -1
  594. package/out/zero-cache/src/services/change-streamer/storer.d.ts +3 -2
  595. package/out/zero-cache/src/services/change-streamer/storer.d.ts.map +1 -1
  596. package/out/zero-cache/src/services/change-streamer/storer.js +309 -367
  597. package/out/zero-cache/src/services/change-streamer/storer.js.map +1 -1
  598. package/out/zero-cache/src/services/change-streamer/subscriber.d.ts +2 -1
  599. package/out/zero-cache/src/services/change-streamer/subscriber.d.ts.map +1 -1
  600. package/out/zero-cache/src/services/change-streamer/subscriber.js +83 -90
  601. package/out/zero-cache/src/services/change-streamer/subscriber.js.map +1 -1
  602. package/out/zero-cache/src/services/heapz.js +21 -25
  603. package/out/zero-cache/src/services/heapz.js.map +1 -1
  604. package/out/zero-cache/src/services/http-service.d.ts +1 -1
  605. package/out/zero-cache/src/services/http-service.d.ts.map +1 -1
  606. package/out/zero-cache/src/services/http-service.js +56 -59
  607. package/out/zero-cache/src/services/http-service.js.map +1 -1
  608. package/out/zero-cache/src/services/life-cycle.d.ts +1 -1
  609. package/out/zero-cache/src/services/life-cycle.d.ts.map +1 -1
  610. package/out/zero-cache/src/services/life-cycle.js +216 -255
  611. package/out/zero-cache/src/services/life-cycle.js.map +1 -1
  612. package/out/zero-cache/src/services/limiter/sliding-window-limiter.js +76 -130
  613. package/out/zero-cache/src/services/limiter/sliding-window-limiter.js.map +1 -1
  614. package/out/zero-cache/src/services/litestream/commands.d.ts +1 -1
  615. package/out/zero-cache/src/services/litestream/commands.d.ts.map +1 -1
  616. package/out/zero-cache/src/services/litestream/commands.js +201 -154
  617. package/out/zero-cache/src/services/litestream/commands.js.map +1 -1
  618. package/out/zero-cache/src/services/mutagen/error.js +11 -6
  619. package/out/zero-cache/src/services/mutagen/error.js.map +1 -1
  620. package/out/zero-cache/src/services/mutagen/mutagen.js +270 -267
  621. package/out/zero-cache/src/services/mutagen/mutagen.js.map +1 -1
  622. package/out/zero-cache/src/services/mutagen/pusher.js +351 -344
  623. package/out/zero-cache/src/services/mutagen/pusher.js.map +1 -1
  624. package/out/zero-cache/src/services/replicator/change-processor.js +483 -530
  625. package/out/zero-cache/src/services/replicator/change-processor.js.map +1 -1
  626. package/out/zero-cache/src/services/replicator/incremental-sync.d.ts +1 -1
  627. package/out/zero-cache/src/services/replicator/incremental-sync.d.ts.map +1 -1
  628. package/out/zero-cache/src/services/replicator/incremental-sync.js +97 -97
  629. package/out/zero-cache/src/services/replicator/incremental-sync.js.map +1 -1
  630. package/out/zero-cache/src/services/replicator/notifier.js +28 -52
  631. package/out/zero-cache/src/services/replicator/notifier.js.map +1 -1
  632. package/out/zero-cache/src/services/replicator/replication-status.js +100 -83
  633. package/out/zero-cache/src/services/replicator/replication-status.js.map +1 -1
  634. package/out/zero-cache/src/services/replicator/replicator.d.ts +1 -1
  635. package/out/zero-cache/src/services/replicator/replicator.d.ts.map +1 -1
  636. package/out/zero-cache/src/services/replicator/replicator.js +33 -26
  637. package/out/zero-cache/src/services/replicator/replicator.js.map +1 -1
  638. package/out/zero-cache/src/services/replicator/schema/change-log.d.ts +1 -1
  639. package/out/zero-cache/src/services/replicator/schema/change-log.d.ts.map +1 -1
  640. package/out/zero-cache/src/services/replicator/schema/change-log.js +74 -86
  641. package/out/zero-cache/src/services/replicator/schema/change-log.js.map +1 -1
  642. package/out/zero-cache/src/services/replicator/schema/constants.js +5 -7
  643. package/out/zero-cache/src/services/replicator/schema/constants.js.map +1 -1
  644. package/out/zero-cache/src/services/replicator/schema/replication-state.d.ts +2 -2
  645. package/out/zero-cache/src/services/replicator/schema/replication-state.d.ts.map +1 -1
  646. package/out/zero-cache/src/services/replicator/schema/replication-state.js +70 -74
  647. package/out/zero-cache/src/services/replicator/schema/replication-state.js.map +1 -1
  648. package/out/zero-cache/src/services/run-ast.d.ts +5 -3
  649. package/out/zero-cache/src/services/run-ast.d.ts.map +1 -1
  650. package/out/zero-cache/src/services/run-ast.js +80 -79
  651. package/out/zero-cache/src/services/run-ast.js.map +1 -1
  652. package/out/zero-cache/src/services/runner.d.ts +1 -1
  653. package/out/zero-cache/src/services/runner.d.ts.map +1 -1
  654. package/out/zero-cache/src/services/runner.js +40 -40
  655. package/out/zero-cache/src/services/runner.js.map +1 -1
  656. package/out/zero-cache/src/services/running-state.d.ts +1 -1
  657. package/out/zero-cache/src/services/running-state.d.ts.map +1 -1
  658. package/out/zero-cache/src/services/running-state.js +122 -119
  659. package/out/zero-cache/src/services/running-state.js.map +1 -1
  660. package/out/zero-cache/src/services/statz.js +184 -162
  661. package/out/zero-cache/src/services/statz.js.map +1 -1
  662. package/out/zero-cache/src/services/view-syncer/active-users-gauge.js +40 -39
  663. package/out/zero-cache/src/services/view-syncer/active-users-gauge.js.map +1 -1
  664. package/out/zero-cache/src/services/view-syncer/client-handler.js +307 -298
  665. package/out/zero-cache/src/services/view-syncer/client-handler.js.map +1 -1
  666. package/out/zero-cache/src/services/view-syncer/client-schema.d.ts.map +1 -1
  667. package/out/zero-cache/src/services/view-syncer/client-schema.js +80 -82
  668. package/out/zero-cache/src/services/view-syncer/client-schema.js.map +1 -1
  669. package/out/zero-cache/src/services/view-syncer/cvr-purger.d.ts.map +1 -1
  670. package/out/zero-cache/src/services/view-syncer/cvr-purger.js +84 -94
  671. package/out/zero-cache/src/services/view-syncer/cvr-purger.js.map +1 -1
  672. package/out/zero-cache/src/services/view-syncer/cvr-store.d.ts +2 -4
  673. package/out/zero-cache/src/services/view-syncer/cvr-store.d.ts.map +1 -1
  674. package/out/zero-cache/src/services/view-syncer/cvr-store.js +628 -612
  675. package/out/zero-cache/src/services/view-syncer/cvr-store.js.map +1 -1
  676. package/out/zero-cache/src/services/view-syncer/cvr.d.ts +1 -1
  677. package/out/zero-cache/src/services/view-syncer/cvr.d.ts.map +1 -1
  678. package/out/zero-cache/src/services/view-syncer/cvr.js +631 -694
  679. package/out/zero-cache/src/services/view-syncer/cvr.js.map +1 -1
  680. package/out/zero-cache/src/services/view-syncer/drain-coordinator.js +38 -60
  681. package/out/zero-cache/src/services/view-syncer/drain-coordinator.js.map +1 -1
  682. package/out/zero-cache/src/services/view-syncer/inspect-handler.d.ts +2 -1
  683. package/out/zero-cache/src/services/view-syncer/inspect-handler.d.ts.map +1 -1
  684. package/out/zero-cache/src/services/view-syncer/inspect-handler.js +168 -158
  685. package/out/zero-cache/src/services/view-syncer/inspect-handler.js.map +1 -1
  686. package/out/zero-cache/src/services/view-syncer/pipeline-driver.d.ts +14 -13
  687. package/out/zero-cache/src/services/view-syncer/pipeline-driver.d.ts.map +1 -1
  688. package/out/zero-cache/src/services/view-syncer/pipeline-driver.js +529 -467
  689. package/out/zero-cache/src/services/view-syncer/pipeline-driver.js.map +1 -1
  690. package/out/zero-cache/src/services/view-syncer/row-record-cache.d.ts +1 -1
  691. package/out/zero-cache/src/services/view-syncer/row-record-cache.d.ts.map +1 -1
  692. package/out/zero-cache/src/services/view-syncer/row-record-cache.js +229 -277
  693. package/out/zero-cache/src/services/view-syncer/row-record-cache.js.map +1 -1
  694. package/out/zero-cache/src/services/view-syncer/schema/cvr.js +53 -120
  695. package/out/zero-cache/src/services/view-syncer/schema/cvr.js.map +1 -1
  696. package/out/zero-cache/src/services/view-syncer/schema/init.js +171 -150
  697. package/out/zero-cache/src/services/view-syncer/schema/init.js.map +1 -1
  698. package/out/zero-cache/src/services/view-syncer/schema/types.js +265 -257
  699. package/out/zero-cache/src/services/view-syncer/schema/types.js.map +1 -1
  700. package/out/zero-cache/src/services/view-syncer/snapshotter.d.ts +3 -3
  701. package/out/zero-cache/src/services/view-syncer/snapshotter.d.ts.map +1 -1
  702. package/out/zero-cache/src/services/view-syncer/snapshotter.js +295 -338
  703. package/out/zero-cache/src/services/view-syncer/snapshotter.js.map +1 -1
  704. package/out/zero-cache/src/services/view-syncer/ttl-clock.js +13 -7
  705. package/out/zero-cache/src/services/view-syncer/ttl-clock.js.map +1 -1
  706. package/out/zero-cache/src/services/view-syncer/view-syncer.d.ts +3 -3
  707. package/out/zero-cache/src/services/view-syncer/view-syncer.d.ts.map +1 -1
  708. package/out/zero-cache/src/services/view-syncer/view-syncer.js +1485 -1307
  709. package/out/zero-cache/src/services/view-syncer/view-syncer.js.map +1 -1
  710. package/out/zero-cache/src/types/error-with-level.d.ts.map +1 -1
  711. package/out/zero-cache/src/types/error-with-level.js +29 -25
  712. package/out/zero-cache/src/types/error-with-level.js.map +1 -1
  713. package/out/zero-cache/src/types/http.js +27 -14
  714. package/out/zero-cache/src/types/http.js.map +1 -1
  715. package/out/zero-cache/src/types/lexi-version.js +46 -31
  716. package/out/zero-cache/src/types/lexi-version.js.map +1 -1
  717. package/out/zero-cache/src/types/lite.js +118 -125
  718. package/out/zero-cache/src/types/lite.js.map +1 -1
  719. package/out/zero-cache/src/types/names.js +6 -3
  720. package/out/zero-cache/src/types/names.js.map +1 -1
  721. package/out/zero-cache/src/types/pg-data-type.js +74 -68
  722. package/out/zero-cache/src/types/pg-data-type.js.map +1 -1
  723. package/out/zero-cache/src/types/pg-types.js +17 -72
  724. package/out/zero-cache/src/types/pg-types.js.map +1 -1
  725. package/out/zero-cache/src/types/pg.d.ts +1 -1
  726. package/out/zero-cache/src/types/pg.d.ts.map +1 -1
  727. package/out/zero-cache/src/types/pg.js +213 -233
  728. package/out/zero-cache/src/types/pg.js.map +1 -1
  729. package/out/zero-cache/src/types/processes.d.ts +2 -2
  730. package/out/zero-cache/src/types/processes.d.ts.map +1 -1
  731. package/out/zero-cache/src/types/processes.js +95 -143
  732. package/out/zero-cache/src/types/processes.js.map +1 -1
  733. package/out/zero-cache/src/types/profiler.js +29 -30
  734. package/out/zero-cache/src/types/profiler.js.map +1 -1
  735. package/out/zero-cache/src/types/row-key.js +30 -68
  736. package/out/zero-cache/src/types/row-key.js.map +1 -1
  737. package/out/zero-cache/src/types/schema-versions.js +25 -19
  738. package/out/zero-cache/src/types/schema-versions.js.map +1 -1
  739. package/out/zero-cache/src/types/shards.js +50 -36
  740. package/out/zero-cache/src/types/shards.js.map +1 -1
  741. package/out/zero-cache/src/types/sql.js +9 -13
  742. package/out/zero-cache/src/types/sql.js.map +1 -1
  743. package/out/zero-cache/src/types/streams.js +245 -254
  744. package/out/zero-cache/src/types/streams.js.map +1 -1
  745. package/out/zero-cache/src/types/strings.js +14 -11
  746. package/out/zero-cache/src/types/strings.js.map +1 -1
  747. package/out/zero-cache/src/types/subscription.js +200 -259
  748. package/out/zero-cache/src/types/subscription.js.map +1 -1
  749. package/out/zero-cache/src/types/url-params.js +35 -30
  750. package/out/zero-cache/src/types/url-params.js.map +1 -1
  751. package/out/zero-cache/src/types/websocket-handoff.d.ts +5 -4
  752. package/out/zero-cache/src/types/websocket-handoff.d.ts.map +1 -1
  753. package/out/zero-cache/src/types/websocket-handoff.js +68 -76
  754. package/out/zero-cache/src/types/websocket-handoff.js.map +1 -1
  755. package/out/zero-cache/src/types/ws.js +56 -59
  756. package/out/zero-cache/src/types/ws.js.map +1 -1
  757. package/out/zero-cache/src/workers/connect-params.js +44 -40
  758. package/out/zero-cache/src/workers/connect-params.js.map +1 -1
  759. package/out/zero-cache/src/workers/connection.d.ts.map +1 -1
  760. package/out/zero-cache/src/workers/connection.js +277 -243
  761. package/out/zero-cache/src/workers/connection.js.map +1 -1
  762. package/out/zero-cache/src/workers/mutator.js +24 -0
  763. package/out/zero-cache/src/workers/mutator.js.map +1 -0
  764. package/out/zero-cache/src/workers/replicator.d.ts +1 -1
  765. package/out/zero-cache/src/workers/replicator.d.ts.map +1 -1
  766. package/out/zero-cache/src/workers/replicator.js +103 -106
  767. package/out/zero-cache/src/workers/replicator.js.map +1 -1
  768. package/out/zero-cache/src/workers/syncer-ws-message-handler.js +179 -147
  769. package/out/zero-cache/src/workers/syncer-ws-message-handler.js.map +1 -1
  770. package/out/zero-cache/src/workers/syncer.d.ts +3 -3
  771. package/out/zero-cache/src/workers/syncer.d.ts.map +1 -1
  772. package/out/zero-cache/src/workers/syncer.js +192 -169
  773. package/out/zero-cache/src/workers/syncer.js.map +1 -1
  774. package/out/zero-client/src/client/active-clients-manager.js +199 -0
  775. package/out/zero-client/src/client/active-clients-manager.js.map +1 -0
  776. package/out/zero-client/src/client/bindings.d.ts +8 -7
  777. package/out/zero-client/src/client/bindings.d.ts.map +1 -1
  778. package/out/zero-client/src/client/bindings.js +33 -0
  779. package/out/zero-client/src/client/bindings.js.map +1 -0
  780. package/out/zero-client/src/client/client-error-kind-enum.js +29 -0
  781. package/out/zero-client/src/client/client-error-kind-enum.js.map +1 -0
  782. package/out/zero-client/src/client/connection-manager.d.ts +12 -31
  783. package/out/zero-client/src/client/connection-manager.d.ts.map +1 -1
  784. package/out/zero-client/src/client/connection-manager.js +310 -0
  785. package/out/zero-client/src/client/connection-manager.js.map +1 -0
  786. package/out/zero-client/src/client/connection-status-enum.js +15 -0
  787. package/out/zero-client/src/client/connection-status-enum.js.map +1 -0
  788. package/out/zero-client/src/client/connection.d.ts +47 -4
  789. package/out/zero-client/src/client/connection.d.ts.map +1 -1
  790. package/out/zero-client/src/client/connection.js +103 -0
  791. package/out/zero-client/src/client/connection.js.map +1 -0
  792. package/out/zero-client/src/client/context.d.ts +4 -7
  793. package/out/zero-client/src/client/context.d.ts.map +1 -1
  794. package/out/zero-client/src/client/context.js +104 -0
  795. package/out/zero-client/src/client/context.js.map +1 -0
  796. package/out/zero-client/src/client/crud.js +225 -0
  797. package/out/zero-client/src/client/crud.js.map +1 -0
  798. package/out/zero-client/src/client/custom.d.ts +12 -15
  799. package/out/zero-client/src/client/custom.d.ts.map +1 -1
  800. package/out/zero-client/src/client/custom.js +123 -0
  801. package/out/zero-client/src/client/custom.js.map +1 -0
  802. package/out/zero-client/src/client/delete-clients-manager.d.ts +2 -2
  803. package/out/zero-client/src/client/delete-clients-manager.d.ts.map +1 -1
  804. package/out/zero-client/src/client/delete-clients-manager.js +71 -0
  805. package/out/zero-client/src/client/delete-clients-manager.js.map +1 -0
  806. package/out/zero-client/src/client/enable-analytics.js +18 -0
  807. package/out/zero-client/src/client/enable-analytics.js.map +1 -0
  808. package/out/zero-client/src/client/error.d.ts +2 -1
  809. package/out/zero-client/src/client/error.d.ts.map +1 -1
  810. package/out/zero-client/src/client/error.js +148 -0
  811. package/out/zero-client/src/client/error.js.map +1 -0
  812. package/out/zero-client/src/client/http-string.js +11 -0
  813. package/out/zero-client/src/client/http-string.js.map +1 -0
  814. package/out/zero-client/src/client/inspector/client-group.js +27 -0
  815. package/out/zero-client/src/client/inspector/client-group.js.map +1 -0
  816. package/out/zero-client/src/client/inspector/client.js +28 -0
  817. package/out/zero-client/src/client/inspector/client.js.map +1 -0
  818. package/out/zero-client/src/client/inspector/html-dialog-prompt.js +77 -0
  819. package/out/zero-client/src/client/inspector/html-dialog-prompt.js.map +1 -0
  820. package/out/zero-client/src/client/inspector/inspector.d.ts +1 -1
  821. package/out/zero-client/src/client/inspector/inspector.d.ts.map +1 -1
  822. package/out/zero-client/src/client/inspector/inspector.js +47 -0
  823. package/out/zero-client/src/client/inspector/inspector.js.map +1 -0
  824. package/out/zero-client/src/client/inspector/lazy-inspector.d.ts +1 -1
  825. package/out/zero-client/src/client/inspector/lazy-inspector.d.ts.map +1 -1
  826. package/out/zero-client/src/client/inspector/lazy-inspector.js +243 -0
  827. package/out/zero-client/src/client/inspector/lazy-inspector.js.map +1 -0
  828. package/out/zero-client/src/client/inspector/query.d.ts.map +1 -1
  829. package/out/zero-client/src/client/inspector/query.js +82 -0
  830. package/out/zero-client/src/client/inspector/query.js.map +1 -0
  831. package/out/zero-client/src/client/ivm-branch.d.ts +4 -4
  832. package/out/zero-client/src/client/ivm-branch.d.ts.map +1 -1
  833. package/out/zero-client/src/client/ivm-branch.js +149 -0
  834. package/out/zero-client/src/client/ivm-branch.js.map +1 -0
  835. package/out/zero-client/src/client/keys.js +45 -0
  836. package/out/zero-client/src/client/keys.js.map +1 -0
  837. package/out/zero-client/src/client/log-options.js +60 -0
  838. package/out/zero-client/src/client/log-options.js.map +1 -0
  839. package/out/zero-client/src/client/metric-name-enum.js +15 -0
  840. package/out/zero-client/src/client/metric-name-enum.js.map +1 -0
  841. package/out/zero-client/src/client/metrics.d.ts +2 -2
  842. package/out/zero-client/src/client/metrics.d.ts.map +1 -1
  843. package/out/zero-client/src/client/metrics.js +249 -0
  844. package/out/zero-client/src/client/metrics.js.map +1 -0
  845. package/out/zero-client/src/client/mutation-tracker.d.ts +2 -2
  846. package/out/zero-client/src/client/mutation-tracker.d.ts.map +1 -1
  847. package/out/zero-client/src/client/mutation-tracker.js +363 -0
  848. package/out/zero-client/src/client/mutation-tracker.js.map +1 -0
  849. package/out/zero-client/src/client/mutator-proxy.d.ts +1 -2
  850. package/out/zero-client/src/client/mutator-proxy.d.ts.map +1 -1
  851. package/out/zero-client/src/client/mutator-proxy.js +132 -0
  852. package/out/zero-client/src/client/mutator-proxy.js.map +1 -0
  853. package/out/zero-client/src/client/options.d.ts +36 -19
  854. package/out/zero-client/src/client/options.d.ts.map +1 -1
  855. package/out/zero-client/src/client/options.js +11 -0
  856. package/out/zero-client/src/client/options.js.map +1 -0
  857. package/out/zero-client/src/client/query-manager.d.ts +5 -5
  858. package/out/zero-client/src/client/query-manager.d.ts.map +1 -1
  859. package/out/zero-client/src/client/query-manager.js +377 -0
  860. package/out/zero-client/src/client/query-manager.js.map +1 -0
  861. package/out/zero-client/src/client/reload-error-handler.d.ts +4 -4
  862. package/out/zero-client/src/client/reload-error-handler.d.ts.map +1 -1
  863. package/out/zero-client/src/client/reload-error-handler.js +114 -0
  864. package/out/zero-client/src/client/reload-error-handler.js.map +1 -0
  865. package/out/zero-client/src/client/server-option.js +64 -0
  866. package/out/zero-client/src/client/server-option.js.map +1 -0
  867. package/out/zero-client/src/client/update-needed-reason-type-enum.js +9 -0
  868. package/out/zero-client/src/client/update-needed-reason-type-enum.js.map +1 -0
  869. package/out/zero-client/src/client/version.js +5 -0
  870. package/out/zero-client/src/client/version.js.map +1 -0
  871. package/out/zero-client/src/client/zero-poke-handler.d.ts +2 -2
  872. package/out/zero-client/src/client/zero-poke-handler.d.ts.map +1 -1
  873. package/out/zero-client/src/client/zero-poke-handler.js +303 -0
  874. package/out/zero-client/src/client/zero-poke-handler.js.map +1 -0
  875. package/out/zero-client/src/client/zero-rep.d.ts +2 -2
  876. package/out/zero-client/src/client/zero-rep.d.ts.map +1 -1
  877. package/out/zero-client/src/client/zero-rep.js +72 -0
  878. package/out/zero-client/src/client/zero-rep.js.map +1 -0
  879. package/out/zero-client/src/client/zero.d.ts +28 -11
  880. package/out/zero-client/src/client/zero.d.ts.map +1 -1
  881. package/out/zero-client/src/client/zero.js +1825 -0
  882. package/out/zero-client/src/client/zero.js.map +1 -0
  883. package/out/zero-client/src/mod.d.ts +4 -12
  884. package/out/zero-client/src/mod.d.ts.map +1 -1
  885. package/out/zero-client/src/util/nanoid.js +21 -0
  886. package/out/zero-client/src/util/nanoid.js.map +1 -0
  887. package/out/zero-client/src/util/socket.js +7 -0
  888. package/out/zero-client/src/util/socket.js.map +1 -0
  889. package/out/zero-protocol/src/analyze-query-result.js +32 -24
  890. package/out/zero-protocol/src/analyze-query-result.js.map +1 -1
  891. package/out/zero-protocol/src/application-error.js +35 -37
  892. package/out/zero-protocol/src/application-error.js.map +1 -1
  893. package/out/zero-protocol/src/ast.d.ts +1 -1
  894. package/out/zero-protocol/src/ast.js +296 -277
  895. package/out/zero-protocol/src/ast.js.map +1 -1
  896. package/out/zero-protocol/src/change-desired-queries.d.ts +2 -2
  897. package/out/zero-protocol/src/change-desired-queries.js +11 -7
  898. package/out/zero-protocol/src/change-desired-queries.js.map +1 -1
  899. package/out/zero-protocol/src/client-schema.d.ts +2 -2
  900. package/out/zero-protocol/src/client-schema.d.ts.map +1 -1
  901. package/out/zero-protocol/src/client-schema.js +40 -26
  902. package/out/zero-protocol/src/client-schema.js.map +1 -1
  903. package/out/zero-protocol/src/close-connection.js +11 -18
  904. package/out/zero-protocol/src/close-connection.js.map +1 -1
  905. package/out/zero-protocol/src/connect.d.ts +4 -4
  906. package/out/zero-protocol/src/connect.js +46 -51
  907. package/out/zero-protocol/src/connect.js.map +1 -1
  908. package/out/zero-protocol/src/custom-queries.d.ts +4 -4
  909. package/out/zero-protocol/src/custom-queries.js +61 -39
  910. package/out/zero-protocol/src/custom-queries.js.map +1 -1
  911. package/out/zero-protocol/src/data.js +9 -4
  912. package/out/zero-protocol/src/data.js.map +1 -1
  913. package/out/zero-protocol/src/delete-clients.js +16 -9
  914. package/out/zero-protocol/src/delete-clients.js.map +1 -1
  915. package/out/zero-protocol/src/down.d.ts +6 -6
  916. package/out/zero-protocol/src/down.js +20 -4
  917. package/out/zero-protocol/src/down.js.map +1 -1
  918. package/out/zero-protocol/src/error-kind-enum.js +41 -23
  919. package/out/zero-protocol/src/error-kind-enum.js.map +1 -1
  920. package/out/zero-protocol/src/error-origin-enum.js +9 -4
  921. package/out/zero-protocol/src/error-origin-enum.js.map +1 -1
  922. package/out/zero-protocol/src/error-reason-enum.js +17 -8
  923. package/out/zero-protocol/src/error-reason-enum.js.map +1 -1
  924. package/out/zero-protocol/src/error.d.ts +17 -17
  925. package/out/zero-protocol/src/error.js +151 -89
  926. package/out/zero-protocol/src/error.js.map +1 -1
  927. package/out/zero-protocol/src/inspect-down.d.ts +18 -18
  928. package/out/zero-protocol/src/inspect-down.js +72 -54
  929. package/out/zero-protocol/src/inspect-down.js.map +1 -1
  930. package/out/zero-protocol/src/inspect-up.d.ts +6 -6
  931. package/out/zero-protocol/src/inspect-up.js +38 -26
  932. package/out/zero-protocol/src/inspect-up.js.map +1 -1
  933. package/out/zero-protocol/src/mutation-id.js +9 -5
  934. package/out/zero-protocol/src/mutation-id.js.map +1 -1
  935. package/out/zero-protocol/src/mutation-type-enum.js +7 -3
  936. package/out/zero-protocol/src/mutation-type-enum.js.map +1 -1
  937. package/out/zero-protocol/src/mutations-patch.js +16 -17
  938. package/out/zero-protocol/src/mutations-patch.js.map +1 -1
  939. package/out/zero-protocol/src/ping.js +9 -4
  940. package/out/zero-protocol/src/ping.js.map +1 -1
  941. package/out/zero-protocol/src/poke.js +55 -72
  942. package/out/zero-protocol/src/poke.js.map +1 -1
  943. package/out/zero-protocol/src/pong.js +9 -4
  944. package/out/zero-protocol/src/pong.js.map +1 -1
  945. package/out/zero-protocol/src/primary-key.js +19 -5
  946. package/out/zero-protocol/src/primary-key.js.map +1 -1
  947. package/out/zero-protocol/src/protocol-version.d.ts +2 -2
  948. package/out/zero-protocol/src/protocol-version.d.ts.map +1 -1
  949. package/out/zero-protocol/src/protocol-version.js +7 -59
  950. package/out/zero-protocol/src/protocol-version.js.map +1 -1
  951. package/out/zero-protocol/src/pull.js +26 -19
  952. package/out/zero-protocol/src/pull.js.map +1 -1
  953. package/out/zero-protocol/src/push.d.ts +4 -4
  954. package/out/zero-protocol/src/push.js +179 -176
  955. package/out/zero-protocol/src/push.js.map +1 -1
  956. package/out/zero-protocol/src/queries-patch.d.ts +3 -3
  957. package/out/zero-protocol/src/queries-patch.js +29 -22
  958. package/out/zero-protocol/src/queries-patch.js.map +1 -1
  959. package/out/zero-protocol/src/query-hash.js +18 -14
  960. package/out/zero-protocol/src/query-hash.js.map +1 -1
  961. package/out/zero-protocol/src/row-patch.js +29 -20
  962. package/out/zero-protocol/src/row-patch.js.map +1 -1
  963. package/out/zero-protocol/src/up.d.ts +5 -5
  964. package/out/zero-protocol/src/up.js +18 -4
  965. package/out/zero-protocol/src/up.js.map +1 -1
  966. package/out/zero-protocol/src/version.js +9 -4
  967. package/out/zero-protocol/src/version.js.map +1 -1
  968. package/out/{inspector-GP3CBZRU.js → zero-react/src/components/inspector.js} +4 -9
  969. package/out/zero-react/src/components/inspector.js.map +1 -0
  970. package/out/{chunk-VZOYWIRW.js → zero-react/src/components/mark-icon.js} +3 -5
  971. package/out/zero-react/src/components/mark-icon.js.map +1 -0
  972. package/out/zero-react/src/components/zero-inspector.js +44 -0
  973. package/out/zero-react/src/components/zero-inspector.js.map +1 -0
  974. package/out/zero-react/src/mod.d.ts +1 -3
  975. package/out/zero-react/src/mod.d.ts.map +1 -1
  976. package/out/zero-react/src/use-query.d.ts +4 -4
  977. package/out/zero-react/src/use-query.d.ts.map +1 -1
  978. package/out/{react.js → zero-react/src/use-query.js} +25 -217
  979. package/out/zero-react/src/use-query.js.map +1 -0
  980. package/out/zero-react/src/use-zero-connection-state.d.ts +1 -1
  981. package/out/zero-react/src/use-zero-connection-state.d.ts.map +1 -1
  982. package/out/zero-react/src/use-zero-connection-state.js +14 -0
  983. package/out/zero-react/src/use-zero-connection-state.js.map +1 -0
  984. package/out/zero-react/src/use-zero-online.js +14 -0
  985. package/out/zero-react/src/use-zero-online.js.map +1 -0
  986. package/out/zero-react/src/zero-provider.d.ts +7 -6
  987. package/out/zero-react/src/zero-provider.d.ts.map +1 -1
  988. package/out/zero-react/src/zero-provider.js +59 -0
  989. package/out/zero-react/src/zero-provider.js.map +1 -0
  990. package/out/zero-schema/src/builder/relationship-builder.js +27 -0
  991. package/out/zero-schema/src/builder/relationship-builder.js.map +1 -0
  992. package/out/zero-schema/src/builder/schema-builder.js +88 -0
  993. package/out/zero-schema/src/builder/schema-builder.js.map +1 -0
  994. package/out/zero-schema/src/builder/table-builder.js +129 -0
  995. package/out/zero-schema/src/builder/table-builder.js.map +1 -0
  996. package/out/zero-schema/src/compiled-permissions.js +23 -19
  997. package/out/zero-schema/src/compiled-permissions.js.map +1 -1
  998. package/out/zero-schema/src/name-mapper.js +43 -38
  999. package/out/zero-schema/src/name-mapper.js.map +1 -1
  1000. package/out/zero-schema/src/permissions.d.ts.map +1 -1
  1001. package/out/zero-schema/src/permissions.js +199 -0
  1002. package/out/zero-schema/src/permissions.js.map +1 -0
  1003. package/out/zero-schema/src/schema-config.js +35 -51
  1004. package/out/zero-schema/src/schema-config.js.map +1 -1
  1005. package/out/zero-server/src/adapters/drizzle.d.ts +1 -1
  1006. package/out/zero-server/src/adapters/drizzle.d.ts.map +1 -1
  1007. package/out/zero-server/src/adapters/drizzle.js +83 -100
  1008. package/out/zero-server/src/adapters/drizzle.js.map +1 -1
  1009. package/out/zero-server/src/adapters/pg.d.ts +4 -3
  1010. package/out/zero-server/src/adapters/pg.d.ts.map +1 -1
  1011. package/out/zero-server/src/adapters/pg.js +53 -77
  1012. package/out/zero-server/src/adapters/pg.js.map +1 -1
  1013. package/out/zero-server/src/adapters/postgresjs.d.ts +2 -2
  1014. package/out/zero-server/src/adapters/postgresjs.d.ts.map +1 -1
  1015. package/out/zero-server/src/adapters/postgresjs.js +39 -57
  1016. package/out/zero-server/src/adapters/postgresjs.js.map +1 -1
  1017. package/out/zero-server/src/custom.d.ts +6 -6
  1018. package/out/zero-server/src/custom.d.ts.map +1 -1
  1019. package/out/zero-server/src/custom.js +185 -117
  1020. package/out/zero-server/src/custom.js.map +1 -1
  1021. package/out/zero-server/src/logging.js +7 -4
  1022. package/out/zero-server/src/logging.js.map +1 -1
  1023. package/out/zero-server/src/mod.d.ts +2 -0
  1024. package/out/zero-server/src/mod.d.ts.map +1 -1
  1025. package/out/zero-server/src/pg-query-executor.js +17 -14
  1026. package/out/zero-server/src/pg-query-executor.js.map +1 -1
  1027. package/out/zero-server/src/process-mutations.js +293 -274
  1028. package/out/zero-server/src/process-mutations.js.map +1 -1
  1029. package/out/zero-server/src/push-processor.js +55 -31
  1030. package/out/zero-server/src/push-processor.js.map +1 -1
  1031. package/out/zero-server/src/queries/process-queries.d.ts +63 -2
  1032. package/out/zero-server/src/queries/process-queries.d.ts.map +1 -1
  1033. package/out/zero-server/src/queries/process-queries.js +101 -95
  1034. package/out/zero-server/src/queries/process-queries.js.map +1 -1
  1035. package/out/zero-server/src/query-registry.d.ts +10 -0
  1036. package/out/zero-server/src/query-registry.d.ts.map +1 -0
  1037. package/out/zero-server/src/query-registry.js +35 -0
  1038. package/out/zero-server/src/query-registry.js.map +1 -0
  1039. package/out/zero-server/src/schema.js +136 -124
  1040. package/out/zero-server/src/schema.js.map +1 -1
  1041. package/out/zero-server/src/zql-database.d.ts +4 -4
  1042. package/out/zero-server/src/zql-database.d.ts.map +1 -1
  1043. package/out/zero-server/src/zql-database.js +66 -47
  1044. package/out/zero-server/src/zql-database.js.map +1 -1
  1045. package/out/zero-solid/src/mod.d.ts +1 -2
  1046. package/out/zero-solid/src/mod.d.ts.map +1 -1
  1047. package/out/zero-solid/src/solid-view.d.ts +1 -1
  1048. package/out/zero-solid/src/solid-view.d.ts.map +1 -1
  1049. package/out/{solid.js → zero-solid/src/solid-view.js} +42 -196
  1050. package/out/zero-solid/src/solid-view.js.map +1 -0
  1051. package/out/zero-solid/src/use-query.d.ts +1 -1
  1052. package/out/zero-solid/src/use-query.d.ts.map +1 -1
  1053. package/out/zero-solid/src/use-query.js +70 -0
  1054. package/out/zero-solid/src/use-query.js.map +1 -0
  1055. package/out/zero-solid/src/use-zero-connection-state.d.ts +1 -1
  1056. package/out/zero-solid/src/use-zero-connection-state.d.ts.map +1 -1
  1057. package/out/zero-solid/src/use-zero-connection-state.js +15 -0
  1058. package/out/zero-solid/src/use-zero-connection-state.js.map +1 -0
  1059. package/out/zero-solid/src/use-zero-online.js +13 -0
  1060. package/out/zero-solid/src/use-zero-online.js.map +1 -0
  1061. package/out/zero-solid/src/use-zero.d.ts +1 -1
  1062. package/out/zero-solid/src/use-zero.d.ts.map +1 -1
  1063. package/out/zero-solid/src/use-zero.js +74 -0
  1064. package/out/zero-solid/src/use-zero.js.map +1 -0
  1065. package/out/zero-types/src/format.js +7 -4
  1066. package/out/zero-types/src/format.js.map +1 -1
  1067. package/out/zero-types/src/name-mapper.js +43 -40
  1068. package/out/zero-types/src/name-mapper.js.map +1 -1
  1069. package/out/zql/src/builder/builder.d.ts +2 -1
  1070. package/out/zql/src/builder/builder.d.ts.map +1 -1
  1071. package/out/zql/src/builder/builder.js +486 -428
  1072. package/out/zql/src/builder/builder.js.map +1 -1
  1073. package/out/zql/src/builder/debug-delegate.js +68 -64
  1074. package/out/zql/src/builder/debug-delegate.js.map +1 -1
  1075. package/out/zql/src/builder/filter.js +132 -138
  1076. package/out/zql/src/builder/filter.js.map +1 -1
  1077. package/out/zql/src/builder/like.js +44 -51
  1078. package/out/zql/src/builder/like.js.map +1 -1
  1079. package/out/zql/src/error.d.ts +5 -0
  1080. package/out/zql/src/error.d.ts.map +1 -1
  1081. package/out/zql/src/error.js +18 -6
  1082. package/out/zql/src/error.js.map +1 -1
  1083. package/out/zql/src/ivm/array-view.js +86 -92
  1084. package/out/zql/src/ivm/array-view.js.map +1 -1
  1085. package/out/zql/src/ivm/constraint.js +74 -127
  1086. package/out/zql/src/ivm/constraint.js.map +1 -1
  1087. package/out/zql/src/ivm/data.js +59 -85
  1088. package/out/zql/src/ivm/data.js.map +1 -1
  1089. package/out/zql/src/ivm/exists.js +236 -243
  1090. package/out/zql/src/ivm/exists.js.map +1 -1
  1091. package/out/zql/src/ivm/fan-in.js +50 -51
  1092. package/out/zql/src/ivm/fan-in.js.map +1 -1
  1093. package/out/zql/src/ivm/fan-out.js +48 -50
  1094. package/out/zql/src/ivm/fan-out.js.map +1 -1
  1095. package/out/zql/src/ivm/filter-operators.js +87 -87
  1096. package/out/zql/src/ivm/filter-operators.js.map +1 -1
  1097. package/out/zql/src/ivm/filter-push.js +26 -23
  1098. package/out/zql/src/ivm/filter-push.js.map +1 -1
  1099. package/out/zql/src/ivm/filter.js +30 -32
  1100. package/out/zql/src/ivm/filter.js.map +1 -1
  1101. package/out/zql/src/ivm/flipped-join.js +343 -326
  1102. package/out/zql/src/ivm/flipped-join.js.map +1 -1
  1103. package/out/zql/src/ivm/join-utils.js +85 -79
  1104. package/out/zql/src/ivm/join-utils.js.map +1 -1
  1105. package/out/zql/src/ivm/join.js +287 -207
  1106. package/out/zql/src/ivm/join.js.map +1 -1
  1107. package/out/zql/src/ivm/maybe-split-and-push-edit-change.js +26 -24
  1108. package/out/zql/src/ivm/maybe-split-and-push-edit-change.js.map +1 -1
  1109. package/out/zql/src/ivm/memory-source.d.ts +2 -2
  1110. package/out/zql/src/ivm/memory-source.d.ts.map +1 -1
  1111. package/out/zql/src/ivm/memory-source.js +471 -489
  1112. package/out/zql/src/ivm/memory-source.js.map +1 -1
  1113. package/out/zql/src/ivm/memory-storage.js +32 -31
  1114. package/out/zql/src/ivm/memory-storage.js.map +1 -1
  1115. package/out/zql/src/ivm/operator.js +8 -9
  1116. package/out/zql/src/ivm/operator.js.map +1 -1
  1117. package/out/zql/src/ivm/push-accumulated.js +236 -305
  1118. package/out/zql/src/ivm/push-accumulated.js.map +1 -1
  1119. package/out/zql/src/ivm/skip.js +92 -106
  1120. package/out/zql/src/ivm/skip.js.map +1 -1
  1121. package/out/zql/src/ivm/source.d.ts +3 -1
  1122. package/out/zql/src/ivm/source.d.ts.map +1 -1
  1123. package/out/zql/src/ivm/stream.js +20 -16
  1124. package/out/zql/src/ivm/stream.js.map +1 -1
  1125. package/out/zql/src/ivm/take.js +502 -456
  1126. package/out/zql/src/ivm/take.js.map +1 -1
  1127. package/out/zql/src/ivm/union-fan-in.js +156 -134
  1128. package/out/zql/src/ivm/union-fan-in.js.map +1 -1
  1129. package/out/zql/src/ivm/union-fan-out.js +46 -45
  1130. package/out/zql/src/ivm/union-fan-out.js.map +1 -1
  1131. package/out/zql/src/ivm/view-apply-change.js +246 -216
  1132. package/out/zql/src/ivm/view-apply-change.js.map +1 -1
  1133. package/out/zql/src/ivm/view.d.ts +2 -2
  1134. package/out/zql/src/ivm/view.d.ts.map +1 -1
  1135. package/out/zql/src/mutate/custom.d.ts +11 -11
  1136. package/out/zql/src/mutate/custom.d.ts.map +1 -1
  1137. package/out/zql/src/mutate/custom.js +15 -7
  1138. package/out/zql/src/mutate/custom.js.map +1 -1
  1139. package/out/zql/src/planner/planner-builder.js +238 -172
  1140. package/out/zql/src/planner/planner-builder.js.map +1 -1
  1141. package/out/zql/src/planner/planner-connection.d.ts +7 -0
  1142. package/out/zql/src/planner/planner-connection.d.ts.map +1 -1
  1143. package/out/zql/src/planner/planner-connection.js +202 -250
  1144. package/out/zql/src/planner/planner-connection.js.map +1 -1
  1145. package/out/zql/src/planner/planner-constraint.js +8 -11
  1146. package/out/zql/src/planner/planner-constraint.js.map +1 -1
  1147. package/out/zql/src/planner/planner-debug.d.ts +2 -1
  1148. package/out/zql/src/planner/planner-debug.d.ts.map +1 -1
  1149. package/out/zql/src/planner/planner-fan-in.d.ts.map +1 -1
  1150. package/out/zql/src/planner/planner-fan-in.js +154 -159
  1151. package/out/zql/src/planner/planner-fan-in.js.map +1 -1
  1152. package/out/zql/src/planner/planner-fan-out.js +71 -60
  1153. package/out/zql/src/planner/planner-fan-out.js.map +1 -1
  1154. package/out/zql/src/planner/planner-graph.d.ts +7 -8
  1155. package/out/zql/src/planner/planner-graph.d.ts.map +1 -1
  1156. package/out/zql/src/planner/planner-graph.js +315 -357
  1157. package/out/zql/src/planner/planner-graph.js.map +1 -1
  1158. package/out/zql/src/planner/planner-join.d.ts +6 -2
  1159. package/out/zql/src/planner/planner-join.d.ts.map +1 -1
  1160. package/out/zql/src/planner/planner-join.js +234 -326
  1161. package/out/zql/src/planner/planner-join.js.map +1 -1
  1162. package/out/zql/src/planner/planner-node.d.ts +2 -1
  1163. package/out/zql/src/planner/planner-node.d.ts.map +1 -1
  1164. package/out/zql/src/planner/planner-source.js +23 -12
  1165. package/out/zql/src/planner/planner-source.js.map +1 -1
  1166. package/out/zql/src/planner/planner-terminus.js +28 -27
  1167. package/out/zql/src/planner/planner-terminus.js.map +1 -1
  1168. package/out/zql/src/query/complete-ordering.d.ts +5 -0
  1169. package/out/zql/src/query/complete-ordering.d.ts.map +1 -0
  1170. package/out/zql/src/query/complete-ordering.js +71 -0
  1171. package/out/zql/src/query/complete-ordering.js.map +1 -0
  1172. package/out/zql/src/query/define-query.d.ts +47 -23
  1173. package/out/zql/src/query/define-query.d.ts.map +1 -1
  1174. package/out/zql/src/query/define-query.js +45 -51
  1175. package/out/zql/src/query/define-query.js.map +1 -1
  1176. package/out/zql/src/query/error.js +12 -8
  1177. package/out/zql/src/query/error.js.map +1 -1
  1178. package/out/zql/src/query/escape-like.js +7 -0
  1179. package/out/zql/src/query/escape-like.js.map +1 -0
  1180. package/out/zql/src/query/expression.js +153 -151
  1181. package/out/zql/src/query/expression.js.map +1 -1
  1182. package/out/zql/src/query/measure-push-operator.js +42 -35
  1183. package/out/zql/src/query/measure-push-operator.js.map +1 -1
  1184. package/out/zql/src/query/metrics-delegate.js +9 -5
  1185. package/out/zql/src/query/metrics-delegate.js.map +1 -1
  1186. package/out/zql/src/query/named.d.ts +9 -5
  1187. package/out/zql/src/query/named.d.ts.map +1 -1
  1188. package/out/zql/src/query/named.js +70 -85
  1189. package/out/zql/src/query/named.js.map +1 -1
  1190. package/out/zql/src/query/query-definitions.d.ts +32 -0
  1191. package/out/zql/src/query/query-definitions.d.ts.map +1 -0
  1192. package/out/zql/src/query/query-delegate-base.d.ts +6 -14
  1193. package/out/zql/src/query/query-delegate-base.d.ts.map +1 -1
  1194. package/out/zql/src/query/query-delegate-base.js +118 -134
  1195. package/out/zql/src/query/query-delegate-base.js.map +1 -1
  1196. package/out/zql/src/query/query-delegate.d.ts +6 -8
  1197. package/out/zql/src/query/query-delegate.d.ts.map +1 -1
  1198. package/out/zql/src/query/query-impl.d.ts +17 -18
  1199. package/out/zql/src/query/query-impl.d.ts.map +1 -1
  1200. package/out/zql/src/query/query-impl.js +511 -433
  1201. package/out/zql/src/query/query-impl.js.map +1 -1
  1202. package/out/zql/src/query/query-internals.d.ts +11 -13
  1203. package/out/zql/src/query/query-internals.d.ts.map +1 -1
  1204. package/out/zql/src/query/query-internals.js +13 -19
  1205. package/out/zql/src/query/query-internals.js.map +1 -1
  1206. package/out/zql/src/query/query.d.ts +15 -16
  1207. package/out/zql/src/query/query.d.ts.map +1 -1
  1208. package/out/zql/src/query/static-query.d.ts +3 -3
  1209. package/out/zql/src/query/static-query.d.ts.map +1 -1
  1210. package/out/zql/src/query/static-query.js +41 -18
  1211. package/out/zql/src/query/static-query.js.map +1 -1
  1212. package/out/zql/src/query/ttl.js +69 -62
  1213. package/out/zql/src/query/ttl.js.map +1 -1
  1214. package/out/zql/src/query/validate-input.d.ts +15 -0
  1215. package/out/zql/src/query/validate-input.d.ts.map +1 -0
  1216. package/out/zql/src/query/validate-input.js +25 -0
  1217. package/out/zql/src/query/validate-input.js.map +1 -0
  1218. package/out/zqlite/src/database-storage.d.ts +1 -1
  1219. package/out/zqlite/src/database-storage.d.ts.map +1 -1
  1220. package/out/zqlite/src/database-storage.js +99 -102
  1221. package/out/zqlite/src/database-storage.js.map +1 -1
  1222. package/out/zqlite/src/db.js +241 -194
  1223. package/out/zqlite/src/db.js.map +1 -1
  1224. package/out/zqlite/src/explain-queries.js +13 -16
  1225. package/out/zqlite/src/explain-queries.js.map +1 -1
  1226. package/out/zqlite/src/internal/sql.js +15 -10
  1227. package/out/zqlite/src/internal/sql.js.map +1 -1
  1228. package/out/zqlite/src/internal/statement-cache.js +86 -110
  1229. package/out/zqlite/src/internal/statement-cache.js.map +1 -1
  1230. package/out/zqlite/src/query-builder.js +172 -143
  1231. package/out/zqlite/src/query-builder.js.map +1 -1
  1232. package/out/zqlite/src/query-delegate.d.ts +2 -2
  1233. package/out/zqlite/src/query-delegate.d.ts.map +1 -1
  1234. package/out/zqlite/src/query-delegate.js +53 -43
  1235. package/out/zqlite/src/query-delegate.js.map +1 -1
  1236. package/out/zqlite/src/sqlite-cost-model.d.ts.map +1 -1
  1237. package/out/zqlite/src/sqlite-cost-model.js +96 -120
  1238. package/out/zqlite/src/sqlite-cost-model.js.map +1 -1
  1239. package/out/zqlite/src/sqlite-stat-fanout.d.ts +121 -0
  1240. package/out/zqlite/src/sqlite-stat-fanout.d.ts.map +1 -0
  1241. package/out/zqlite/src/sqlite-stat-fanout.js +301 -0
  1242. package/out/zqlite/src/sqlite-stat-fanout.js.map +1 -0
  1243. package/out/zqlite/src/table-source.d.ts +9 -4
  1244. package/out/zqlite/src/table-source.d.ts.map +1 -1
  1245. package/out/zqlite/src/table-source.js +424 -327
  1246. package/out/zqlite/src/table-source.js.map +1 -1
  1247. package/package.json +23 -26
  1248. package/out/chunk-424PT5DM.js +0 -23
  1249. package/out/chunk-424PT5DM.js.map +0 -7
  1250. package/out/chunk-AFADJQ2O.js +0 -1
  1251. package/out/chunk-AFADJQ2O.js.map +0 -7
  1252. package/out/chunk-ASRS2LFV.js.map +0 -7
  1253. package/out/chunk-EZM3XBAB.js.map +0 -7
  1254. package/out/chunk-HCZQVP5R.js.map +0 -7
  1255. package/out/chunk-PFM5IJC4.js +0 -495
  1256. package/out/chunk-PFM5IJC4.js.map +0 -7
  1257. package/out/chunk-TAUDS4QP.js +0 -4129
  1258. package/out/chunk-TAUDS4QP.js.map +0 -7
  1259. package/out/chunk-VZOYWIRW.js.map +0 -7
  1260. package/out/chunk-WPAQ4EPM.js.map +0 -7
  1261. package/out/chunk-WWNKZSEE.js +0 -18857
  1262. package/out/chunk-WWNKZSEE.js.map +0 -7
  1263. package/out/expo-sqlite.js +0 -11
  1264. package/out/expo-sqlite.js.map +0 -7
  1265. package/out/inspector-GP3CBZRU.js.map +0 -7
  1266. package/out/lazy-inspector-XLKVABX2.js +0 -575
  1267. package/out/lazy-inspector-XLKVABX2.js.map +0 -7
  1268. package/out/op-sqlite.js.map +0 -7
  1269. package/out/react-native.js +0 -25
  1270. package/out/react-native.js.map +0 -7
  1271. package/out/react.js.map +0 -7
  1272. package/out/shared/src/enum.js +0 -2
  1273. package/out/shared/src/enum.js.map +0 -1
  1274. package/out/shared/src/expand.js +0 -2
  1275. package/out/shared/src/expand.js.map +0 -1
  1276. package/out/shared/src/immutable.js +0 -2
  1277. package/out/shared/src/immutable.js.map +0 -1
  1278. package/out/shared/src/types.js +0 -2
  1279. package/out/shared/src/types.js.map +0 -1
  1280. package/out/shared/src/writable.js +0 -2
  1281. package/out/shared/src/writable.js.map +0 -1
  1282. package/out/solid.js.map +0 -7
  1283. package/out/sqlite.js +0 -15
  1284. package/out/sqlite.js.map +0 -7
  1285. package/out/zero/package.json +0 -195
  1286. package/out/zero/src/server/change-streamer.js +0 -2
  1287. package/out/zero/src/server/change-streamer.js.map +0 -1
  1288. package/out/zero/src/server/main.js +0 -2
  1289. package/out/zero/src/server/main.js.map +0 -1
  1290. package/out/zero/src/server/reaper.js +0 -2
  1291. package/out/zero/src/server/reaper.js.map +0 -1
  1292. package/out/zero/src/server/replicator.js +0 -2
  1293. package/out/zero/src/server/replicator.js.map +0 -1
  1294. package/out/zero/src/server/runner/main.js +0 -2
  1295. package/out/zero/src/server/runner/main.js.map +0 -1
  1296. package/out/zero/src/server/syncer.js +0 -2
  1297. package/out/zero/src/server/syncer.js.map +0 -1
  1298. package/out/zero-cache/src/services/change-source/pg/logical-replication/pgoutput.types.js +0 -4
  1299. package/out/zero-cache/src/services/change-source/pg/logical-replication/pgoutput.types.js.map +0 -1
  1300. package/out/zero-cache/src/services/change-source/protocol/mod.js +0 -5
  1301. package/out/zero-cache/src/services/change-source/protocol/mod.js.map +0 -1
  1302. package/out/zero-cache/src/services/service.js +0 -2
  1303. package/out/zero-cache/src/services/service.js.map +0 -1
  1304. package/out/zero-cache/src/services/view-syncer/key-columns.d.ts +0 -32
  1305. package/out/zero-cache/src/services/view-syncer/key-columns.d.ts.map +0 -1
  1306. package/out/zero-cache/src/services/view-syncer/key-columns.js +0 -75
  1307. package/out/zero-cache/src/services/view-syncer/key-columns.js.map +0 -1
  1308. package/out/zero-cache/src/types/satisfies.js +0 -2
  1309. package/out/zero-cache/src/types/satisfies.js.map +0 -1
  1310. package/out/zero-client/src/client/zero-log-context.d.ts +0 -7
  1311. package/out/zero-client/src/client/zero-log-context.d.ts.map +0 -1
  1312. package/out/zero-events/src/index.js +0 -2
  1313. package/out/zero-events/src/index.js.map +0 -1
  1314. package/out/zero-events/src/json.js +0 -2
  1315. package/out/zero-events/src/json.js.map +0 -1
  1316. package/out/zero-events/src/status.js +0 -3
  1317. package/out/zero-events/src/status.js.map +0 -1
  1318. package/out/zero-pg/src/mod.js +0 -6
  1319. package/out/zero-pg/src/mod.js.map +0 -1
  1320. package/out/zero-protocol/src/error-kind.js +0 -3
  1321. package/out/zero-protocol/src/error-kind.js.map +0 -1
  1322. package/out/zero-protocol/src/error-origin.js +0 -3
  1323. package/out/zero-protocol/src/error-origin.js.map +0 -1
  1324. package/out/zero-protocol/src/error-reason.js +0 -3
  1325. package/out/zero-protocol/src/error-reason.js.map +0 -1
  1326. package/out/zero-schema/src/table-schema.js +0 -7
  1327. package/out/zero-schema/src/table-schema.js.map +0 -1
  1328. package/out/zero-server/src/mod.js +0 -8
  1329. package/out/zero-server/src/mod.js.map +0 -1
  1330. package/out/zero-types/src/schema-value.js +0 -2
  1331. package/out/zero-types/src/schema-value.js.map +0 -1
  1332. package/out/zero-types/src/schema.js +0 -2
  1333. package/out/zero-types/src/schema.js.map +0 -1
  1334. package/out/zero-types/src/server-schema.js +0 -2
  1335. package/out/zero-types/src/server-schema.js.map +0 -1
  1336. package/out/zero.js +0 -95
  1337. package/out/zero.js.map +0 -7
  1338. package/out/zql/src/ivm/change.js +0 -2
  1339. package/out/zql/src/ivm/change.js.map +0 -1
  1340. package/out/zql/src/ivm/default-format.js +0 -2
  1341. package/out/zql/src/ivm/default-format.js.map +0 -1
  1342. package/out/zql/src/ivm/schema.js +0 -2
  1343. package/out/zql/src/ivm/schema.js.map +0 -1
  1344. package/out/zql/src/ivm/source.js +0 -2
  1345. package/out/zql/src/ivm/source.js.map +0 -1
  1346. package/out/zql/src/ivm/view.js +0 -2
  1347. package/out/zql/src/ivm/view.js.map +0 -1
  1348. package/out/zql/src/planner/planner-debug.js +0 -176
  1349. package/out/zql/src/planner/planner-debug.js.map +0 -1
  1350. package/out/zql/src/planner/planner-node.js +0 -2
  1351. package/out/zql/src/planner/planner-node.js.map +0 -1
  1352. package/out/zql/src/query/chained-query.d.ts +0 -35
  1353. package/out/zql/src/query/chained-query.d.ts.map +0 -1
  1354. package/out/zql/src/query/chained-query.js +0 -66
  1355. package/out/zql/src/query/chained-query.js.map +0 -1
  1356. package/out/zql/src/query/query-delegate.js +0 -2
  1357. package/out/zql/src/query/query-delegate.js.map +0 -1
  1358. package/out/zql/src/query/query.js +0 -8
  1359. package/out/zql/src/query/query.js.map +0 -1
  1360. package/out/zql/src/query/root-named-query.d.ts +0 -33
  1361. package/out/zql/src/query/root-named-query.d.ts.map +0 -1
  1362. package/out/zql/src/query/root-named-query.js +0 -95
  1363. package/out/zql/src/query/root-named-query.js.map +0 -1
  1364. package/out/zql/src/query/typed-view.js +0 -2
  1365. package/out/zql/src/query/typed-view.js.map +0 -1
  1366. package/out/zqlite/src/mod.js +0 -5
  1367. package/out/zqlite/src/mod.js.map +0 -1
@@ -1,1394 +1,1572 @@
1
- import { trace } from '@opentelemetry/api';
2
- import { Lock } from '@rocicorp/lock';
3
- import { resolver } from '@rocicorp/resolver';
4
- import { manualSpan, startAsyncSpan, startSpan, } from "../../../../otel/src/span.js";
1
+ import { trace } from "@opentelemetry/api";
2
+ import { Lock } from "@rocicorp/lock";
3
+ import { resolver } from "@rocicorp/resolver";
4
+ import { startSpan, startAsyncSpan, manualSpan } from "../../../../otel/src/span.js";
5
5
  import { version } from "../../../../otel/src/version.js";
6
6
  import { assert, unreachable } from "../../../../shared/src/asserts.js";
7
7
  import { stringify } from "../../../../shared/src/bigint-json.js";
8
8
  import { CustomKeyMap } from "../../../../shared/src/custom-key-map.js";
9
- import { wrapIterable } from "../../../../shared/src/iterables.js";
10
9
  import { must } from "../../../../shared/src/must.js";
11
10
  import { randInt } from "../../../../shared/src/rand.js";
12
- import { ErrorKind } from "../../../../zero-protocol/src/error-kind.js";
13
- import { ErrorOrigin } from "../../../../zero-protocol/src/error-origin.js";
14
- import { ProtocolError, } from "../../../../zero-protocol/src/error.js";
11
+ import { Rehome, ClientNotFound, TransformFailed, Unauthorized, InvalidConnectionRequestBaseCookie } from "../../../../zero-protocol/src/error-kind-enum.js";
12
+ import { ZeroCache } from "../../../../zero-protocol/src/error-origin-enum.js";
13
+ import { ProtocolError } from "../../../../zero-protocol/src/error.js";
15
14
  import { clampTTL, MAX_TTL_MS } from "../../../../zql/src/query/ttl.js";
16
- import { transformAndHashQuery, } from "../../auth/read-authorizer.js";
17
- import { CustomQueryTransformer } from "../../custom-queries/transform-query.js";
18
- import { getOrCreateCounter, getOrCreateHistogram, getOrCreateUpDownCounter, } from "../../observability/metrics.js";
19
- import { InspectorDelegate } from "../../server/inspector-delegate.js";
20
- import { getLogLevel, ProtocolErrorWithLevel, } from "../../types/error-with-level.js";
15
+ import { transformAndHashQuery } from "../../auth/read-authorizer.js";
16
+ import { getOrCreateUpDownCounter, getOrCreateCounter, getOrCreateHistogram } from "../../observability/metrics.js";
17
+ import { ProtocolErrorWithLevel, getLogLevel } from "../../types/error-with-level.js";
21
18
  import { rowIDString } from "../../types/row-key.js";
22
19
  import { Subscription } from "../../types/subscription.js";
23
- import { ZERO_VERSION_COLUMN_NAME } from "../replicator/schema/replication-state.js";
24
- import { ClientHandler, startPoke, } from "./client-handler.js";
20
+ import "../replicator/schema/replication-state.js";
21
+ import { startPoke, ClientHandler } from "./client-handler.js";
25
22
  import { CVRStore } from "./cvr-store.js";
26
- import { CVRConfigDrivenUpdater, CVRQueryDrivenUpdater, CVRUpdater, nextEvictionTime, } from "./cvr.js";
23
+ import { CVRConfigDrivenUpdater, nextEvictionTime, CVRQueryDrivenUpdater } from "./cvr.js";
27
24
  import { handleInspect } from "./inspect-handler.js";
28
- import { PipelineDriver } from "./pipeline-driver.js";
29
- import { cmpVersions, EMPTY_CVR_VERSION, versionFromString, versionString, versionToCookie, } from "./schema/types.js";
25
+ import "../../../../shared/src/config.js";
26
+ import "compare-utf8";
27
+ import "../../../../zero-protocol/src/ast.js";
28
+ import "../../../../zero-protocol/src/data.js";
29
+ import "@rocicorp/zero-sqlite3";
30
+ import "../../../../zqlite/src/internal/sql.js";
31
+ import "../../../../shared/src/btree-set.js";
32
+ import "../../../../shared/src/valita.js";
33
+ import "../../../../zero-schema/src/compiled-permissions.js";
34
+ import "../../../../zero-protocol/src/primary-key.js";
35
+ import { ZERO_VERSION_COLUMN_NAME } from "../replicator/schema/constants.js";
36
+ import "../../types/pg-data-type.js";
37
+ import "../../db/specs.js";
30
38
  import { ResetPipelinesSignal } from "./snapshotter.js";
31
- import { ttlClockAsNumber, ttlClockFromNumber, } from "./ttl-clock.js";
32
- const tracer = trace.getTracer('view-syncer', version);
33
- const PROTOCOL_VERSION_ATTR = 'protocol.version';
34
- const DEFAULT_KEEPALIVE_MS = 5_000;
39
+ import { versionString, cmpVersions, EMPTY_CVR_VERSION, versionToCookie, versionFromString } from "./schema/types.js";
40
+ import { ttlClockFromNumber, ttlClockAsNumber } from "./ttl-clock.js";
41
+ const tracer = trace.getTracer("view-syncer", version);
42
+ const PROTOCOL_VERSION_ATTR = "protocol.version";
43
+ const DEFAULT_KEEPALIVE_MS = 5e3;
35
44
  function randomID() {
36
- return randInt(1, Number.MAX_SAFE_INTEGER).toString(36);
45
+ return randInt(1, Number.MAX_SAFE_INTEGER).toString(36);
37
46
  }
38
- /**
39
- * We update the ttlClock in flush that writes to the CVR but
40
- * some flushes do not write to the CVR and in those cases we
41
- * use a timer to update the ttlClock every minute.
42
- */
43
- export const TTL_CLOCK_INTERVAL = 60_000;
44
- /**
45
- * This is some extra time we delay the TTL timer to allow for some
46
- * slack in the timing of the timer. This is to allow multiple evictions
47
- * to happen in a short period of time without having to wait for the
48
- * next tick of the timer.
49
- */
50
- export const TTL_TIMER_HYSTERESIS = 50; // ms
51
- export class ViewSyncerService {
52
- id;
53
- #shard;
54
- #lc;
55
- #pipelines;
56
- #stateChanges;
57
- #drainCoordinator;
58
- #keepaliveMs;
59
- #slowHydrateThreshold;
60
- #queryConfig;
61
- userQueryURL;
62
- // The ViewSyncerService is only started in response to a connection,
63
- // so #lastConnectTime is always initialized to now(). This is necessary
64
- // to handle race conditions in which, e.g. the replica is ready and the
65
- // CVR is accessed before the first connection sends a request.
66
- //
67
- // Note: It is fine to update this variable outside of the lock.
68
- #lastConnectTime = Date.now();
69
- /**
70
- * The TTL clock is used to determine the time at which queries are considered
71
- * expired.
72
- */
73
- #ttlClock;
74
- /**
75
- * The base time for the TTL clock. This is used to compute the current TTL
76
- * clock value. The first time a connection is made, this is set to the
77
- * current time. On subsequent connections, the TTL clock is computed as the
78
- * difference between the current time and this base time.
79
- *
80
- * Every time we write the ttlClock this is update to the current time. That
81
- * way we can compute how much time has passed since the last time we set the
82
- * ttlClock. When we set the ttlClock we just increment it by the amount of
83
- * time that has passed since the last time we set it.
84
- */
85
- #ttlClockBase = Date.now();
86
- /**
87
- * We update the ttlClock every minute to ensure that it is not too much
88
- * out of sync with the current time.
89
- */
90
- #ttlClockInterval = 0;
91
- // Note: It is okay to add/remove clients without acquiring the lock.
92
- #clients = new Map();
93
- // Serialize on this lock for:
94
- // (1) storage or database-dependent operations
95
- // (2) updating member variables.
96
- #lock = new Lock();
97
- #cvrStore;
98
- #stopped = resolver();
99
- #initialized = resolver();
100
- #cvr;
101
- #pipelinesSynced = false;
102
- // DEPRECATED: remove `authData` in favor of forwarding
103
- // auth and cookie headers directly
104
- #authData;
105
- // Not sure why lint can't see that this is used?
106
- // oxlint-disable-next-line no-unused-private-class-members
107
- #httpCookie;
108
- #expiredQueriesTimer = 0;
109
- #setTimeout;
110
- #customQueryTransformer;
111
- #activeClients = getOrCreateUpDownCounter('sync', 'active-clients', 'Number of active sync clients');
112
- #hydrations = getOrCreateCounter('sync', 'hydration', 'Number of query hydrations');
113
- #hydrationTime = getOrCreateHistogram('sync', 'hydration-time', {
114
- description: 'Time to hydrate a query.',
115
- unit: 's',
116
- });
117
- #transactionAdvanceTime = getOrCreateHistogram('sync', 'advance-time', {
118
- description: 'Time to advance all queries for a given client group after applying a new transaction to the replica.',
119
- unit: 's',
120
- });
121
- #inspectorDelegate;
122
- #config;
123
- constructor(config, lc, shard, taskID, clientGroupID, cvrDb, upstreamDb, pipelineDriver, versionChanges, drainCoordinator, slowHydrateThreshold, inspectorDelegate, customQueryTransformer, keepaliveMs = DEFAULT_KEEPALIVE_MS, setTimeoutFn = setTimeout.bind(globalThis)) {
124
- const { getQueries: pullConfig } = config;
125
- this.#config = config;
126
- this.id = clientGroupID;
127
- this.#shard = shard;
128
- this.#queryConfig = pullConfig;
129
- this.#lc = lc;
130
- this.#pipelines = pipelineDriver;
131
- this.#stateChanges = versionChanges;
132
- this.#drainCoordinator = drainCoordinator;
133
- this.#keepaliveMs = keepaliveMs;
134
- this.#slowHydrateThreshold = slowHydrateThreshold;
135
- this.#inspectorDelegate = inspectorDelegate;
136
- this.#customQueryTransformer = customQueryTransformer;
137
- this.#cvrStore = new CVRStore(lc, cvrDb, upstreamDb, shard, taskID, clientGroupID,
138
- // On failure, cancel the #stateChanges subscription. The run()
139
- // loop will then await #cvrStore.flushed() which rejects if necessary.
140
- () => this.#stateChanges.cancel());
141
- this.#setTimeout = setTimeoutFn;
142
- // Wait for the first connection to init.
143
- this.keepalive();
47
+ const TTL_CLOCK_INTERVAL = 6e4;
48
+ const TTL_TIMER_HYSTERESIS = 50;
49
+ class ViewSyncerService {
50
+ id;
51
+ #shard;
52
+ #lc;
53
+ #pipelines;
54
+ #stateChanges;
55
+ #drainCoordinator;
56
+ #keepaliveMs;
57
+ #slowHydrateThreshold;
58
+ #queryConfig;
59
+ userQueryURL;
60
+ // The ViewSyncerService is only started in response to a connection,
61
+ // so #lastConnectTime is always initialized to now(). This is necessary
62
+ // to handle race conditions in which, e.g. the replica is ready and the
63
+ // CVR is accessed before the first connection sends a request.
64
+ //
65
+ // Note: It is fine to update this variable outside of the lock.
66
+ #lastConnectTime = Date.now();
67
+ /**
68
+ * The TTL clock is used to determine the time at which queries are considered
69
+ * expired.
70
+ */
71
+ #ttlClock;
72
+ /**
73
+ * The base time for the TTL clock. This is used to compute the current TTL
74
+ * clock value. The first time a connection is made, this is set to the
75
+ * current time. On subsequent connections, the TTL clock is computed as the
76
+ * difference between the current time and this base time.
77
+ *
78
+ * Every time we write the ttlClock this is update to the current time. That
79
+ * way we can compute how much time has passed since the last time we set the
80
+ * ttlClock. When we set the ttlClock we just increment it by the amount of
81
+ * time that has passed since the last time we set it.
82
+ */
83
+ #ttlClockBase = Date.now();
84
+ /**
85
+ * We update the ttlClock every minute to ensure that it is not too much
86
+ * out of sync with the current time.
87
+ */
88
+ #ttlClockInterval = 0;
89
+ // Note: It is okay to add/remove clients without acquiring the lock.
90
+ #clients = /* @__PURE__ */ new Map();
91
+ // Serialize on this lock for:
92
+ // (1) storage or database-dependent operations
93
+ // (2) updating member variables.
94
+ #lock = new Lock();
95
+ #cvrStore;
96
+ #stopped = resolver();
97
+ #initialized = resolver();
98
+ #cvr;
99
+ #pipelinesSynced = false;
100
+ // DEPRECATED: remove `authData` in favor of forwarding
101
+ // auth and cookie headers directly
102
+ #authData;
103
+ // Not sure why lint can't see that this is used?
104
+ // oxlint-disable-next-line no-unused-private-class-members
105
+ #httpCookie;
106
+ #expiredQueriesTimer = 0;
107
+ #setTimeout;
108
+ #customQueryTransformer;
109
+ // Track query replacements for thrashing detection
110
+ #queryReplacements = /* @__PURE__ */ new Map();
111
+ #activeClients = getOrCreateUpDownCounter(
112
+ "sync",
113
+ "active-clients",
114
+ "Number of active sync clients"
115
+ );
116
+ #hydrations = getOrCreateCounter(
117
+ "sync",
118
+ "hydration",
119
+ "Number of query hydrations"
120
+ );
121
+ #hydrationTime = getOrCreateHistogram("sync", "hydration-time", {
122
+ description: "Time to hydrate a query.",
123
+ unit: "s"
124
+ });
125
+ #transactionAdvanceTime = getOrCreateHistogram(
126
+ "sync",
127
+ "advance-time",
128
+ {
129
+ description: "Time to advance all queries for a given client group after applying a new transaction to the replica.",
130
+ unit: "s"
144
131
  }
145
- #getHeaderOptions(forwardCookie) {
146
- return {
147
- apiKey: this.#queryConfig.apiKey,
148
- token: this.#authData?.raw,
149
- cookie: forwardCookie ? this.#httpCookie : undefined,
150
- };
132
+ );
133
+ #queryTransformations = getOrCreateCounter(
134
+ "sync",
135
+ "query.transformations",
136
+ "Number of query transformations performed"
137
+ );
138
+ #queryTransformationTime = getOrCreateHistogram(
139
+ "sync",
140
+ "query.transformation-time",
141
+ {
142
+ description: "Time to transform custom queries via API server",
143
+ unit: "s"
151
144
  }
152
- #runInLockWithCVR(fn) {
153
- const rid = randomID();
154
- this.#lc.debug?.('about to acquire lock for cvr ', rid);
155
- return this.#lock.withLock(async () => {
156
- this.#lc.debug?.('acquired lock in #runInLockWithCVR ', rid);
157
- const lc = this.#lc.withContext('lock', rid);
158
- if (!this.#stateChanges.active) {
159
- // view-syncer has been shutdown. this can be a backlog of tasks
160
- // queued on the lock, or it can be a race condition in which a
161
- // client connects before the ViewSyncer has been deleted from the
162
- // ServiceRunner.
163
- this.#lc.debug?.('state changes are inactive');
164
- clearTimeout(this.#expiredQueriesTimer);
165
- throw new ProtocolErrorWithLevel({
166
- kind: ErrorKind.Rehome,
167
- message: 'Reconnect required',
168
- origin: ErrorOrigin.ZeroCache,
169
- }, 'warn');
170
- }
171
- // If all clients have disconnected, cancel all pending work.
172
- if (await this.#checkForShutdownConditionsInLock()) {
173
- this.#lc.info?.(`closing clientGroupID=${this.id}`);
174
- this.#stateChanges.cancel(); // Note: #stateChanges.active becomes false.
175
- return;
176
- }
177
- if (!this.#cvr) {
178
- this.#lc.debug?.('loading CVR');
179
- this.#cvr = await this.#cvrStore.load(lc, this.#lastConnectTime);
180
- this.#ttlClock = this.#cvr.ttlClock;
181
- this.#ttlClockBase = Date.now();
182
- }
183
- else {
184
- // Make sure the CVR ttlClock is up to date.
185
- const now = Date.now();
186
- this.#cvr = {
187
- ...this.#cvr,
188
- ttlClock: this.#getTTLClock(now),
189
- };
190
- }
191
- try {
192
- await fn(lc, this.#cvr);
193
- }
194
- catch (e) {
195
- // Clear cached state if an error is encountered.
196
- this.#cvr = undefined;
197
- throw e;
145
+ );
146
+ #queryTransformationHashChanges = getOrCreateCounter(
147
+ "sync",
148
+ "query.transformation-hash-changes",
149
+ "Number of times query transformation hash changed"
150
+ );
151
+ #queryTransformationNoOps = getOrCreateCounter(
152
+ "sync",
153
+ "query.transformation-no-ops",
154
+ "Number of times query transformation resulted in no-op (hash unchanged)"
155
+ );
156
+ #inspectorDelegate;
157
+ #config;
158
+ constructor(config, lc, shard, taskID, clientGroupID, cvrDb, upstreamDb, pipelineDriver, versionChanges, drainCoordinator, slowHydrateThreshold, inspectorDelegate, customQueryTransformer, keepaliveMs = DEFAULT_KEEPALIVE_MS, setTimeoutFn = setTimeout.bind(globalThis)) {
159
+ const { getQueries: pullConfig } = config;
160
+ this.#config = config;
161
+ this.id = clientGroupID;
162
+ this.#shard = shard;
163
+ this.#queryConfig = pullConfig;
164
+ this.#lc = lc;
165
+ this.#pipelines = pipelineDriver;
166
+ this.#stateChanges = versionChanges;
167
+ this.#drainCoordinator = drainCoordinator;
168
+ this.#keepaliveMs = keepaliveMs;
169
+ this.#slowHydrateThreshold = slowHydrateThreshold;
170
+ this.#inspectorDelegate = inspectorDelegate;
171
+ this.#customQueryTransformer = customQueryTransformer;
172
+ this.#cvrStore = new CVRStore(
173
+ lc,
174
+ cvrDb,
175
+ upstreamDb,
176
+ shard,
177
+ taskID,
178
+ clientGroupID,
179
+ // On failure, cancel the #stateChanges subscription. The run()
180
+ // loop will then await #cvrStore.flushed() which rejects if necessary.
181
+ () => this.#stateChanges.cancel()
182
+ );
183
+ this.#setTimeout = setTimeoutFn;
184
+ this.keepalive();
185
+ }
186
+ #getHeaderOptions(forwardCookie) {
187
+ return {
188
+ apiKey: this.#queryConfig.apiKey,
189
+ token: this.#authData?.raw,
190
+ cookie: forwardCookie ? this.#httpCookie : void 0
191
+ };
192
+ }
193
+ #runInLockWithCVR(fn) {
194
+ const rid = randomID();
195
+ this.#lc.debug?.("about to acquire lock for cvr ", rid);
196
+ return this.#lock.withLock(async () => {
197
+ this.#lc.debug?.("acquired lock in #runInLockWithCVR ", rid);
198
+ const lc = this.#lc.withContext("lock", rid);
199
+ if (!this.#stateChanges.active) {
200
+ this.#lc.debug?.("state changes are inactive");
201
+ clearTimeout(this.#expiredQueriesTimer);
202
+ throw new ProtocolErrorWithLevel({
203
+ kind: Rehome,
204
+ message: "Reconnect required",
205
+ origin: ZeroCache
206
+ });
207
+ }
208
+ if (await this.#checkForShutdownConditionsInLock()) {
209
+ this.#lc.info?.(`closing clientGroupID=${this.id}`);
210
+ this.#stateChanges.cancel();
211
+ return;
212
+ }
213
+ if (!this.#cvr) {
214
+ this.#lc.debug?.("loading CVR");
215
+ this.#cvr = await this.#cvrStore.load(lc, this.#lastConnectTime);
216
+ this.#ttlClock = this.#cvr.ttlClock;
217
+ this.#ttlClockBase = Date.now();
218
+ } else {
219
+ const now = Date.now();
220
+ this.#cvr = {
221
+ ...this.#cvr,
222
+ ttlClock: this.#getTTLClock(now)
223
+ };
224
+ }
225
+ try {
226
+ await fn(lc, this.#cvr);
227
+ } catch (e) {
228
+ this.#cvr = void 0;
229
+ throw e;
230
+ }
231
+ });
232
+ }
233
+ readyState() {
234
+ return Promise.race([
235
+ this.#initialized.promise,
236
+ this.#drainCoordinator.draining
237
+ ]);
238
+ }
239
+ async run() {
240
+ try {
241
+ if (await this.readyState() === "draining") {
242
+ this.#lc.debug?.(`draining view-syncer ${this.id} before running`);
243
+ void this.stop();
244
+ }
245
+ for await (const { state } of this.#stateChanges) {
246
+ if (this.#drainCoordinator.shouldDrain()) {
247
+ this.#lc.debug?.(`draining view-syncer ${this.id} (elective)`);
248
+ break;
249
+ }
250
+ assert(state === "version-ready", "state should be version-ready");
251
+ await this.#runInLockWithCVR(async (lc, cvr) => {
252
+ if (!this.#pipelines.initialized()) {
253
+ this.#pipelines.init(must(cvr.clientSchema));
254
+ }
255
+ if (cvr.replicaVersion !== null && cvr.version.stateVersion !== "00" && this.#pipelines.replicaVersion < cvr.replicaVersion) {
256
+ const message = `Cannot sync from older replica: CVR=${cvr.replicaVersion}, DB=${this.#pipelines.replicaVersion}`;
257
+ lc.info?.(`resetting CVR: ${message}`);
258
+ throw new ProtocolErrorWithLevel({
259
+ kind: ClientNotFound,
260
+ message,
261
+ origin: ZeroCache
262
+ });
263
+ }
264
+ if (this.#pipelinesSynced) {
265
+ const result = await this.#advancePipelines(lc, cvr);
266
+ if (result === "success") {
267
+ return;
198
268
  }
269
+ lc.info?.(`resetting pipelines: ${result.message}`);
270
+ this.#pipelines.reset(must(cvr.clientSchema));
271
+ }
272
+ const version2 = this.#pipelines.advanceWithoutDiff();
273
+ const cvrVer = versionString(cvr.version);
274
+ if (version2 < cvr.version.stateVersion) {
275
+ lc.debug?.(`replica@${version2} is behind cvr@${cvrVer}`);
276
+ return;
277
+ }
278
+ lc.info?.(`init pipelines@${version2} (cvr@${cvrVer})`);
279
+ await this.#hydrateUnchangedQueries(lc, cvr);
280
+ await this.#syncQueryPipelineSet(lc, cvr);
281
+ this.#pipelinesSynced = true;
199
282
  });
283
+ }
284
+ if (this.#drainCoordinator.shouldDrain()) {
285
+ this.#drainCoordinator.drainNextIn(this.#totalHydrationTimeMs());
286
+ }
287
+ this.#cleanup();
288
+ } catch (e) {
289
+ this.#lc[getLogLevel(e)]?.(`stopping view-syncer: ${String(e)}`, e);
290
+ this.#cleanup(e);
291
+ } finally {
292
+ await this.#cvrStore.flushed(this.#lc).catch((e) => this.#lc[getLogLevel(e)]?.(e));
293
+ this.#lc.info?.("view-syncer stopped");
294
+ this.#stopped.resolve();
200
295
  }
201
- readyState() {
202
- return Promise.race([
203
- this.#initialized.promise,
204
- this.#drainCoordinator.draining,
205
- ]);
296
+ }
297
+ // must be called from within #lock
298
+ #removeExpiredQueries = async (lc, cvr) => {
299
+ if (hasExpiredQueries(cvr)) {
300
+ lc = lc.withContext("method", "#removeExpiredQueries");
301
+ lc.debug?.("Queries have expired");
302
+ await this.#syncQueryPipelineSet(lc, cvr);
303
+ this.#pipelinesSynced = true;
206
304
  }
207
- async run() {
208
- try {
209
- // Wait for initialization if we need to process queries.
210
- // This ensures authData is available before transforming custom queries.
211
- if ((await this.readyState()) === 'draining') {
212
- this.#lc.debug?.(`draining view-syncer ${this.id} before running`);
213
- void this.stop();
214
- }
215
- for await (const { state } of this.#stateChanges) {
216
- if (this.#drainCoordinator.shouldDrain()) {
217
- this.#lc.debug?.(`draining view-syncer ${this.id} (elective)`);
218
- break;
219
- }
220
- assert(state === 'version-ready', 'state should be version-ready'); // This is the only state change used.
221
- await this.#runInLockWithCVR(async (lc, cvr) => {
222
- if (!this.#pipelines.initialized()) {
223
- // On the first version-ready signal, connect to the replica.
224
- this.#pipelines.init(cvr.clientSchema);
225
- }
226
- if (cvr.replicaVersion !== null &&
227
- cvr.version.stateVersion !== '00' &&
228
- this.#pipelines.replicaVersion < cvr.replicaVersion) {
229
- const message = `Cannot sync from older replica: CVR=${cvr.replicaVersion}, DB=${this.#pipelines.replicaVersion}`;
230
- lc.info?.(`resetting CVR: ${message}`);
231
- throw new ProtocolError({
232
- kind: ErrorKind.ClientNotFound,
233
- message,
234
- origin: ErrorOrigin.ZeroCache,
235
- });
236
- }
237
- if (this.#pipelinesSynced) {
238
- const result = await this.#advancePipelines(lc, cvr);
239
- if (result === 'success') {
240
- return;
241
- }
242
- lc.info?.(`resetting pipelines: ${result.message}`);
243
- this.#pipelines.reset(cvr.clientSchema);
244
- }
245
- // Advance the snapshot to the current version.
246
- const version = this.#pipelines.advanceWithoutDiff();
247
- const cvrVer = versionString(cvr.version);
248
- if (version < cvr.version.stateVersion) {
249
- lc.debug?.(`replica@${version} is behind cvr@${cvrVer}`);
250
- return; // Wait for the next advancement.
251
- }
252
- // stateVersion is at or beyond CVR version for the first time.
253
- lc.info?.(`init pipelines@${version} (cvr@${cvrVer})`);
254
- await this.#hydrateUnchangedQueries(lc, cvr);
255
- await this.#syncQueryPipelineSet(lc, cvr);
256
- this.#pipelinesSynced = true;
257
- });
258
- }
259
- // If this view-syncer exited due to an elective or forced drain,
260
- // set the next drain timeout.
261
- if (this.#drainCoordinator.shouldDrain()) {
262
- this.#drainCoordinator.drainNextIn(this.#totalHydrationTimeMs());
263
- }
264
- this.#cleanup();
265
- }
266
- catch (e) {
267
- this.#lc[getLogLevel(e)]?.(`stopping view-syncer: ${String(e)}`, e);
268
- this.#cleanup(e);
269
- }
270
- finally {
271
- // Always wait for the cvrStore to flush, regardless of how the service
272
- // was stopped.
273
- await this.#cvrStore
274
- .flushed(this.#lc)
275
- .catch(e => this.#lc[getLogLevel(e)]?.(e));
276
- this.#lc.info?.('view-syncer stopped');
277
- this.#stopped.resolve();
278
- }
279
- }
280
- // must be called from within #lock
281
- #removeExpiredQueries = async (lc, cvr) => {
282
- if (hasExpiredQueries(cvr)) {
283
- lc = lc.withContext('method', '#removeExpiredQueries');
284
- lc.debug?.('Queries have expired');
285
- // #syncQueryPipelineSet() will remove the expired queries.
286
- await this.#syncQueryPipelineSet(lc, cvr);
287
- this.#pipelinesSynced = true;
288
- }
289
- // Even if we have expired queries, we still need to schedule next eviction
290
- // since there might be inactivated queries that need to be expired queries
291
- // in the future.
292
- this.#scheduleExpireEviction(lc, cvr);
293
- };
294
- #totalHydrationTimeMs() {
295
- return this.#pipelines.totalHydrationTimeMs();
305
+ this.#scheduleExpireEviction(lc, cvr);
306
+ };
307
+ #totalHydrationTimeMs() {
308
+ return this.#pipelines.totalHydrationTimeMs();
309
+ }
310
+ #keepAliveUntil = 0;
311
+ /**
312
+ * Guarantees that the ViewSyncer will remain running for at least
313
+ * its configured `keepaliveMs`. This is called when establishing a
314
+ * new connection to ensure that its associated ViewSyncer isn't
315
+ * shutdown before it receives the connection.
316
+ *
317
+ * @return `true` if the ViewSyncer will stay alive, `false` if the
318
+ * ViewSyncer is shutting down.
319
+ */
320
+ keepalive() {
321
+ if (!this.#stateChanges.active) {
322
+ return false;
296
323
  }
297
- #keepAliveUntil = 0;
298
- /**
299
- * Guarantees that the ViewSyncer will remain running for at least
300
- * its configured `keepaliveMs`. This is called when establishing a
301
- * new connection to ensure that its associated ViewSyncer isn't
302
- * shutdown before it receives the connection.
303
- *
304
- * @return `true` if the ViewSyncer will stay alive, `false` if the
305
- * ViewSyncer is shutting down.
306
- */
307
- keepalive() {
308
- if (!this.#stateChanges.active) {
309
- return false;
310
- }
311
- this.#keepAliveUntil = Date.now() + this.#keepaliveMs;
312
- return true;
324
+ this.#keepAliveUntil = Date.now() + this.#keepaliveMs;
325
+ return true;
326
+ }
327
+ // oxlint-disable-next-line no-unused-private-class-members -- False positive, used in #scheduleShutdown
328
+ #shutdownTimer = null;
329
+ #scheduleShutdown(delayMs = 0) {
330
+ this.#shutdownTimer ??= this.#setTimeout(() => {
331
+ this.#shutdownTimer = null;
332
+ void this.#runInLockWithCVR(() => {
333
+ }).catch(
334
+ (e) => (
335
+ // If an error occurs (e.g. ownership change), propagate the error
336
+ // to the main run() loop via the #stateChanges Subscription.
337
+ this.#stateChanges.fail(e)
338
+ )
339
+ );
340
+ }, delayMs);
341
+ }
342
+ async #checkForShutdownConditionsInLock() {
343
+ if (this.#clients.size > 0) {
344
+ return false;
313
345
  }
314
- // oxlint-disable-next-line no-unused-private-class-members -- False positive, used in #scheduleShutdown
315
- #shutdownTimer = null;
316
- #scheduleShutdown(delayMs = 0) {
317
- this.#shutdownTimer ??= this.#setTimeout(() => {
318
- this.#shutdownTimer = null;
319
- // All lock tasks check for shutdown so that queued work is immediately
320
- // canceled when clients disconnect. Queue an empty task to ensure that
321
- // this check happens.
322
- void this.#runInLockWithCVR(() => { }).catch(e =>
323
- // If an error occurs (e.g. ownership change), propagate the error
324
- // to the main run() loop via the #stateChanges Subscription.
325
- this.#stateChanges.fail(e));
326
- }, delayMs);
346
+ await this.#cvrStore.flushed(this.#lc);
347
+ if (Date.now() <= this.#keepAliveUntil) {
348
+ this.#scheduleShutdown(this.#keepaliveMs);
349
+ return false;
327
350
  }
328
- async #checkForShutdownConditionsInLock() {
329
- if (this.#clients.size > 0) {
330
- return false; // common case.
331
- }
332
- // Keep the view-syncer alive if there are pending rows being flushed.
333
- // It's better to do this before shutting down since it may take a
334
- // while, during which new connections may come in.
335
- await this.#cvrStore.flushed(this.#lc);
336
- if (Date.now() <= this.#keepAliveUntil) {
337
- this.#scheduleShutdown(this.#keepaliveMs); // check again later
338
- return false;
351
+ return this.#clients.size === 0;
352
+ }
353
+ #deleteClientDueToDisconnect(clientID, client) {
354
+ const c = this.#clients.get(clientID);
355
+ if (c === client) {
356
+ this.#clients.delete(clientID);
357
+ if (this.#clients.size === 0) {
358
+ if (this.#ttlClock !== void 0) {
359
+ this.#updateTTLClockInCVRWithoutLock(this.#lc);
339
360
  }
340
- // If no clients have connected while waiting for the row flush, shutdown.
341
- return this.#clients.size === 0;
361
+ this.#stopExpireTimer();
362
+ this.#scheduleShutdown();
363
+ }
342
364
  }
343
- #deleteClientDueToDisconnect(clientID, client) {
344
- // Note: It is okay to delete / cleanup clients without acquiring the lock.
345
- // In fact, it is important to do so in order to guarantee that idle cleanup
346
- // is performed in a timely manner, regardless of the amount of work
347
- // queued on the lock.
348
- const c = this.#clients.get(clientID);
349
- if (c === client) {
350
- this.#clients.delete(clientID);
351
- if (this.#clients.size === 0) {
352
- // It is possible to delete a client before we read the ttl clock from
353
- // the CVR.
354
- if (this.#ttlClock !== undefined) {
355
- this.#updateTTLClockInCVRWithoutLock(this.#lc);
356
- }
357
- this.#stopExpireTimer();
358
- this.#scheduleShutdown();
365
+ }
366
+ #stopExpireTimer() {
367
+ this.#lc.debug?.("Stopping expired queries timer");
368
+ clearTimeout(this.#expiredQueriesTimer);
369
+ this.#expiredQueriesTimer = 0;
370
+ }
371
+ initConnection(ctx, initConnectionMessage) {
372
+ this.#lc.debug?.("viewSyncer.initConnection");
373
+ return startSpan(tracer, "vs.initConnection", () => {
374
+ const {
375
+ clientID,
376
+ wsID,
377
+ baseCookie,
378
+ schemaVersion,
379
+ tokenData,
380
+ httpCookie,
381
+ protocolVersion
382
+ } = ctx;
383
+ this.#authData = pickToken(this.#lc, this.#authData, tokenData);
384
+ this.#initialized.resolve("initialized");
385
+ this.#lc.debug?.(
386
+ `Picked auth token: ${JSON.stringify(this.#authData?.decoded)}`
387
+ );
388
+ this.#httpCookie = httpCookie;
389
+ const [, { userQueryURL }] = initConnectionMessage;
390
+ if (this.userQueryURL === void 0) {
391
+ this.userQueryURL = userQueryURL;
392
+ } else {
393
+ if (this.userQueryURL !== userQueryURL) {
394
+ this.#lc.error?.(
395
+ "Client provided different query parameters than client group",
396
+ {
397
+ clientID,
398
+ clientURL: userQueryURL,
399
+ clientGroupURL: this.userQueryURL
359
400
  }
401
+ );
360
402
  }
403
+ }
404
+ const lc = this.#lc.withContext("clientID", clientID).withContext("wsID", wsID);
405
+ const downstream = Subscription.create({
406
+ cleanup: (_, err) => {
407
+ err ? lc[getLogLevel(err)]?.(`client closed with error`, err) : lc.info?.("client closed");
408
+ this.#deleteClientDueToDisconnect(clientID, newClient);
409
+ this.#activeClients.add(-1, {
410
+ [PROTOCOL_VERSION_ATTR]: protocolVersion
411
+ });
412
+ }
413
+ });
414
+ this.#activeClients.add(1, {
415
+ [PROTOCOL_VERSION_ATTR]: protocolVersion
416
+ });
417
+ if (this.#clients.size === 0) {
418
+ const now = Date.now();
419
+ this.#ttlClockBase = now;
420
+ }
421
+ const newClient = new ClientHandler(
422
+ lc,
423
+ this.id,
424
+ clientID,
425
+ wsID,
426
+ this.#shard,
427
+ baseCookie,
428
+ schemaVersion,
429
+ downstream
430
+ );
431
+ this.#clients.get(clientID)?.close(`replaced by wsID: ${wsID}`);
432
+ this.#clients.set(clientID, newClient);
433
+ void this.#runInLockForClient(
434
+ ctx,
435
+ initConnectionMessage,
436
+ this.#handleConfigUpdate,
437
+ newClient
438
+ ).catch((e) => newClient.fail(e));
439
+ return downstream;
440
+ });
441
+ }
442
+ async changeDesiredQueries(ctx, msg) {
443
+ await this.#runInLockForClient(ctx, msg, this.#handleConfigUpdate);
444
+ }
445
+ async deleteClients(ctx, msg) {
446
+ try {
447
+ await this.#runInLockForClient(
448
+ ctx,
449
+ [msg[0], { deleted: msg[1] }],
450
+ this.#handleConfigUpdate
451
+ );
452
+ } catch (e) {
453
+ this.#lc.error?.("deleteClients failed", e);
361
454
  }
362
- #stopExpireTimer() {
363
- this.#lc.debug?.('Stopping expired queries timer');
364
- clearTimeout(this.#expiredQueriesTimer);
365
- this.#expiredQueriesTimer = 0;
455
+ }
456
+ #getTTLClock(now) {
457
+ const delta = now - this.#ttlClockBase;
458
+ assert(this.#ttlClock !== void 0, "ttlClock should be defined");
459
+ const ttlClock = ttlClockFromNumber(
460
+ ttlClockAsNumber(this.#ttlClock) + delta
461
+ );
462
+ assert(
463
+ ttlClockAsNumber(ttlClock) <= now,
464
+ "ttlClock should be less than or equal to now"
465
+ );
466
+ this.#ttlClock = ttlClock;
467
+ this.#ttlClockBase = now;
468
+ return ttlClock;
469
+ }
470
+ async #flushUpdater(lc, updater) {
471
+ const now = Date.now();
472
+ const ttlClock = this.#getTTLClock(now);
473
+ const { cvr, flushed } = await updater.flush(
474
+ lc,
475
+ this.#lastConnectTime,
476
+ now,
477
+ ttlClock
478
+ );
479
+ if (flushed) {
480
+ this.#startTTLClockInterval(lc);
366
481
  }
367
- initConnection(ctx, initConnectionMessage) {
368
- this.#lc.debug?.('viewSyncer.initConnection');
369
- return startSpan(tracer, 'vs.initConnection', () => {
370
- const { clientID, wsID, baseCookie, schemaVersion, tokenData, httpCookie, protocolVersion, } = ctx;
371
- this.#authData = pickToken(this.#lc, this.#authData, tokenData);
372
- this.#initialized.resolve('initialized'); // Signal that initialization is complete.
373
- this.#lc.debug?.(`Picked auth token: ${JSON.stringify(this.#authData?.decoded)}`);
374
- this.#httpCookie = httpCookie;
375
- // Handle custom query URL
376
- const [, { userQueryURL }] = initConnectionMessage;
377
- if (this.userQueryURL === undefined) {
378
- // First client in the group - store its parameters
379
- this.userQueryURL = userQueryURL;
380
- }
381
- else {
382
- // Validate that subsequent clients have compatible parameters
383
- if (this.userQueryURL !== userQueryURL) {
384
- this.#lc.error?.('Client provided different query parameters than client group', {
385
- clientID,
386
- clientURL: userQueryURL,
387
- clientGroupURL: this.userQueryURL,
388
- });
389
- }
390
- }
391
- const lc = this.#lc
392
- .withContext('clientID', clientID)
393
- .withContext('wsID', wsID);
394
- // Setup the downstream connection.
395
- const downstream = Subscription.create({
396
- cleanup: (_, err) => {
397
- err
398
- ? lc[getLogLevel(err)]?.(`client closed with error`, err)
399
- : lc.info?.('client closed');
400
- this.#deleteClientDueToDisconnect(clientID, newClient);
401
- this.#activeClients.add(-1, {
402
- [PROTOCOL_VERSION_ATTR]: protocolVersion,
403
- });
404
- },
405
- });
406
- this.#activeClients.add(1, {
407
- [PROTOCOL_VERSION_ATTR]: protocolVersion,
408
- });
409
- if (this.#clients.size === 0) {
410
- // First connection to this ViewSyncerService.
411
- // initConnection must be synchronous so that the downstream
412
- // subscription is returned immediately.
413
- const now = Date.now();
414
- this.#ttlClockBase = now;
415
- }
416
- const newClient = new ClientHandler(lc, this.id, clientID, wsID, this.#shard, baseCookie, schemaVersion, downstream);
417
- this.#clients.get(clientID)?.close(`replaced by wsID: ${wsID}`);
418
- this.#clients.set(clientID, newClient);
419
- // Note: initConnection() must be synchronous so that `downstream` is
420
- // immediately returned to the caller (connection.ts). This ensures
421
- // that if the connection is subsequently closed, the `downstream`
422
- // subscription can be properly canceled even if #runInLockForClient()
423
- // has not had a chance to run.
424
- void this.#runInLockForClient(ctx, initConnectionMessage, this.#handleConfigUpdate, newClient).catch(e => newClient.fail(e));
425
- return downstream;
426
- });
482
+ return cvr;
483
+ }
484
+ #startTTLClockInterval(lc) {
485
+ this.#stopTTLClockInterval();
486
+ this.#ttlClockInterval = this.#setTimeout(() => {
487
+ this.#updateTTLClockInCVRWithoutLock(lc);
488
+ this.#startTTLClockInterval(lc);
489
+ }, TTL_CLOCK_INTERVAL);
490
+ }
491
+ #stopTTLClockInterval() {
492
+ clearTimeout(this.#ttlClockInterval);
493
+ this.#ttlClockInterval = 0;
494
+ }
495
+ #updateTTLClockInCVRWithoutLock(lc) {
496
+ lc.debug?.("Syncing ttlClock");
497
+ const now = Date.now();
498
+ const ttlClock = this.#getTTLClock(now);
499
+ this.#cvrStore.updateTTLClock(ttlClock, now).catch((e) => {
500
+ lc.error?.("failed to update TTL clock", e);
501
+ });
502
+ }
503
+ async #updateCVRConfig(lc, cvr, clientID, fn) {
504
+ const updater = new CVRConfigDrivenUpdater(
505
+ this.#cvrStore,
506
+ cvr,
507
+ this.#shard
508
+ );
509
+ updater.ensureClient(clientID);
510
+ const patches = fn(updater);
511
+ this.#cvr = await this.#flushUpdater(lc, updater);
512
+ if (cmpVersions(cvr.version, this.#cvr.version) < 0) {
513
+ const newCVR = this.#cvr;
514
+ const pokers = startPoke(this.#getClients(cvr.version), newCVR.version);
515
+ for (const patch of patches) {
516
+ await pokers.addPatch(patch);
517
+ }
518
+ await pokers.end(newCVR.version);
519
+ }
520
+ if (this.#pipelinesSynced) {
521
+ await this.#syncQueryPipelineSet(lc, this.#cvr);
427
522
  }
428
- async changeDesiredQueries(ctx, msg) {
429
- await this.#runInLockForClient(ctx, msg, this.#handleConfigUpdate);
523
+ return this.#cvr;
524
+ }
525
+ /**
526
+ * Runs the given `fn` to process the `msg` from within the `#lock`,
527
+ * optionally adding the `newClient` if supplied.
528
+ */
529
+ #runInLockForClient(ctx, msg, fn, newClient) {
530
+ this.#lc.debug?.("viewSyncer.#runInLockForClient");
531
+ const { clientID, wsID } = ctx;
532
+ const [cmd, body] = msg;
533
+ if (newClient || !this.#clients.has(clientID)) {
534
+ this.#lastConnectTime = Date.now();
430
535
  }
431
- async deleteClients(ctx, msg) {
536
+ return startAsyncSpan(
537
+ tracer,
538
+ `vs.#runInLockForClient(${cmd})`,
539
+ async () => {
540
+ let client;
432
541
  try {
433
- await this.#runInLockForClient(ctx, [msg[0], { deleted: msg[1] }], this.#handleConfigUpdate);
542
+ await this.#runInLockWithCVR((lc, cvr) => {
543
+ lc = lc.withContext("clientID", clientID).withContext("wsID", wsID).withContext("cmd", cmd);
544
+ lc.debug?.("acquired lock for cvr");
545
+ client = this.#clients.get(clientID);
546
+ if (client?.wsID !== wsID) {
547
+ lc.debug?.("mismatched wsID", client?.wsID, wsID);
548
+ return;
549
+ }
550
+ if (newClient) {
551
+ assert(
552
+ newClient === client,
553
+ "newClient must match existing client"
554
+ );
555
+ checkClientAndCVRVersions(client.version(), cvr.version);
556
+ } else if (!this.#clients.has(clientID)) {
557
+ lc.warn?.(`Processing ${cmd} before initConnection was received`);
558
+ }
559
+ lc.debug?.(cmd, body);
560
+ return fn(lc, clientID, body, cvr);
561
+ });
562
+ } catch (e) {
563
+ const lc = this.#lc.withContext("clientID", clientID).withContext("wsID", wsID).withContext("cmd", cmd);
564
+ lc[getLogLevel(e)]?.(`closing connection with error`, e);
565
+ if (client) {
566
+ client.fail(e);
567
+ } else {
568
+ throw e;
569
+ }
570
+ }
571
+ }
572
+ );
573
+ }
574
+ #getClients(atVersion) {
575
+ const clients = [...this.#clients.values()];
576
+ return atVersion ? clients.filter(
577
+ (c) => cmpVersions(c.version() ?? EMPTY_CVR_VERSION, atVersion) === 0
578
+ ) : clients;
579
+ }
580
+ // Must be called from within #lock.
581
+ #handleConfigUpdate = (lc, clientID, {
582
+ clientSchema,
583
+ deleted,
584
+ desiredQueriesPatch,
585
+ activeClients
586
+ }, cvr) => startAsyncSpan(tracer, "vs.#patchQueries", async () => {
587
+ const deletedClientIDs = [];
588
+ const deletedClientGroupIDs = [];
589
+ cvr = await this.#updateCVRConfig(lc, cvr, clientID, (updater) => {
590
+ const { ttlClock } = cvr;
591
+ const patches = [];
592
+ if (clientSchema) {
593
+ updater.setClientSchema(lc, clientSchema);
594
+ }
595
+ lc.debug?.(`applying ${desiredQueriesPatch?.length} query patches`);
596
+ if (desiredQueriesPatch?.length) {
597
+ for (const patch of desiredQueriesPatch) {
598
+ switch (patch.op) {
599
+ case "put":
600
+ patches.push(...updater.putDesiredQueries(clientID, [patch]));
601
+ break;
602
+ case "del":
603
+ patches.push(
604
+ ...updater.markDesiredQueriesAsInactive(
605
+ clientID,
606
+ [patch.hash],
607
+ ttlClock
608
+ )
609
+ );
610
+ break;
611
+ case "clear":
612
+ patches.push(...updater.clearDesiredQueries(clientID));
613
+ break;
614
+ }
434
615
  }
435
- catch (e) {
436
- this.#lc.error?.('deleteClients failed', e);
616
+ }
617
+ const clientIDsToDelete = /* @__PURE__ */ new Set();
618
+ if (activeClients) {
619
+ const allClientIDs = Object.keys(cvr.clients);
620
+ const activeClientsSet = new Set(activeClients);
621
+ for (const id of allClientIDs) {
622
+ if (!activeClientsSet.has(id)) {
623
+ clientIDsToDelete.add(id);
624
+ }
437
625
  }
626
+ }
627
+ if (deleted?.clientIDs?.length) {
628
+ for (const cid of deleted.clientIDs) {
629
+ assert(cid !== clientID, "cannot delete self");
630
+ clientIDsToDelete.add(cid);
631
+ }
632
+ }
633
+ for (const cid of clientIDsToDelete) {
634
+ const patchesDueToClient = updater.deleteClient(cid, ttlClock);
635
+ patches.push(...patchesDueToClient);
636
+ deletedClientIDs.push(cid);
637
+ }
638
+ if (deleted?.clientGroupIDs?.length) {
639
+ lc.debug?.(
640
+ `ignoring ${deleted.clientGroupIDs.length} deprecated client group deletes`
641
+ );
642
+ }
643
+ return patches;
644
+ });
645
+ if (deletedClientIDs.length && deleted?.clientIDs?.length || deletedClientGroupIDs.length) {
646
+ const clients = this.#getClients();
647
+ await Promise.allSettled(
648
+ clients.map(
649
+ (client) => client.sendDeleteClients(
650
+ lc,
651
+ deletedClientIDs,
652
+ deletedClientGroupIDs
653
+ )
654
+ )
655
+ );
438
656
  }
439
- #getTTLClock(now) {
440
- // We will update ttlClock with delta from the ttlClockBase to the current time.
441
- const delta = now - this.#ttlClockBase;
442
- assert(this.#ttlClock !== undefined, 'ttlClock should be defined');
443
- const ttlClock = ttlClockFromNumber(ttlClockAsNumber(this.#ttlClock) + delta);
444
- assert(ttlClockAsNumber(ttlClock) <= now, 'ttlClock should be less than or equal to now');
445
- this.#ttlClock = ttlClock;
446
- this.#ttlClockBase = now;
447
- return ttlClock;
657
+ this.#scheduleExpireEviction(lc, cvr);
658
+ });
659
+ #scheduleExpireEviction(lc, cvr) {
660
+ const { ttlClock } = cvr;
661
+ this.#stopExpireTimer();
662
+ const next = nextEvictionTime(cvr);
663
+ if (next === void 0) {
664
+ lc.debug?.("no inactive queries with ttl");
665
+ return;
448
666
  }
449
- async #flushUpdater(lc, updater) {
450
- const now = Date.now();
451
- const ttlClock = this.#getTTLClock(now);
452
- const { cvr, flushed } = await updater.flush(lc, this.#lastConnectTime, now, ttlClock);
453
- if (flushed) {
454
- // If the CVR was flushed, we restart the ttlClock interval.
455
- this.#startTTLClockInterval(lc);
456
- }
457
- return cvr;
667
+ const delay = Math.max(
668
+ TTL_TIMER_HYSTERESIS,
669
+ Math.min(
670
+ ttlClockAsNumber(next) - ttlClockAsNumber(ttlClock) + TTL_TIMER_HYSTERESIS,
671
+ MAX_TTL_MS
672
+ )
673
+ );
674
+ lc.debug?.("Scheduling eviction timer to run in ", delay, "ms");
675
+ this.#expiredQueriesTimer = this.#setTimeout(() => {
676
+ this.#expiredQueriesTimer = 0;
677
+ this.#runInLockWithCVR(
678
+ (lc2, cvr2) => this.#removeExpiredQueries(lc2, cvr2)
679
+ ).catch(
680
+ (e) => (
681
+ // If an error occurs (e.g. ownership change), propagate the error
682
+ // to the main run() loop via the #stateChanges Subscription.
683
+ this.#stateChanges.fail(e)
684
+ )
685
+ );
686
+ }, delay);
687
+ }
688
+ /**
689
+ * Adds and hydrates pipelines for queries whose results are already
690
+ * recorded in the CVR. Namely:
691
+ *
692
+ * 1. The CVR state version and database version are the same.
693
+ * 2. The transformation hash of the queries equal those in the CVR.
694
+ *
695
+ * Note that by definition, only "got" queries can satisfy condition (2),
696
+ * as desired queries do not have a transformation hash.
697
+ *
698
+ * This is an initialization step that sets up pipeline state without
699
+ * the expensive of loading and diffing CVR row state.
700
+ *
701
+ * This must be called from within the #lock.
702
+ */
703
+ async #hydrateUnchangedQueries(lc, cvr) {
704
+ assert(this.#pipelines.initialized(), "pipelines must be initialized");
705
+ const dbVersion = this.#pipelines.currentVersion();
706
+ const cvrVersion = cvr.version;
707
+ if (cvrVersion.stateVersion !== dbVersion) {
708
+ lc.info?.(
709
+ `CVR (${versionToCookie(cvrVersion)}) is behind db ${dbVersion}`
710
+ );
711
+ return;
458
712
  }
459
- #startTTLClockInterval(lc) {
460
- this.#stopTTLClockInterval();
461
- this.#ttlClockInterval = this.#setTimeout(() => {
462
- this.#updateTTLClockInCVRWithoutLock(lc);
463
- this.#startTTLClockInterval(lc);
464
- }, TTL_CLOCK_INTERVAL);
713
+ const gotQueries = Object.entries(cvr.queries).filter(
714
+ ([_, state]) => state.transformationHash !== void 0
715
+ );
716
+ const customQueries = /* @__PURE__ */ new Map();
717
+ const otherQueries = [];
718
+ for (const [, query] of gotQueries) {
719
+ if (query.type !== "internal" && Object.values(query.clientState).every(
720
+ ({ inactivatedAt }) => inactivatedAt !== void 0
721
+ )) {
722
+ continue;
723
+ }
724
+ if (query.type === "custom") {
725
+ customQueries.set(query.id, query);
726
+ } else {
727
+ otherQueries.push(query);
728
+ }
465
729
  }
466
- #stopTTLClockInterval() {
467
- clearTimeout(this.#ttlClockInterval);
468
- this.#ttlClockInterval = 0;
730
+ const transformedQueries = [];
731
+ if (customQueries.size > 0 && !this.#customQueryTransformer) {
732
+ lc.error?.(
733
+ "Custom/named queries were requested but no `ZERO_GET_QUERIES_URL` is configured for Zero Cache."
734
+ );
469
735
  }
470
- #updateTTLClockInCVRWithoutLock(lc) {
471
- lc.debug?.('Syncing ttlClock');
472
- const now = Date.now();
473
- const ttlClock = this.#getTTLClock(now);
474
- this.#cvrStore.updateTTLClock(ttlClock, now).catch(e => {
475
- lc.error?.('failed to update TTL clock', e);
476
- });
736
+ if (this.#customQueryTransformer && customQueries.size > 0) {
737
+ const transformedCustomQueries = await this.#customQueryTransformer.transform(
738
+ this.#getHeaderOptions(this.#queryConfig.forwardCookies),
739
+ customQueries.values(),
740
+ this.userQueryURL
741
+ );
742
+ this.#processTransformedCustomQueries(
743
+ lc,
744
+ transformedCustomQueries,
745
+ (q) => transformedQueries.push(q),
746
+ customQueries
747
+ );
748
+ }
749
+ for (const q of otherQueries) {
750
+ const transformed = transformAndHashQuery(
751
+ lc,
752
+ q.id,
753
+ q.ast,
754
+ must(this.#pipelines.currentPermissions()).permissions ?? {
755
+ tables: {}
756
+ },
757
+ this.#authData?.decoded,
758
+ q.type === "internal"
759
+ );
760
+ if (transformed.transformationHash === q.transformationHash) {
761
+ transformedQueries.push(transformed);
762
+ }
477
763
  }
478
- async #updateCVRConfig(lc, cvr, clientID, fn) {
479
- const updater = new CVRConfigDrivenUpdater(this.#cvrStore, cvr, this.#shard);
480
- updater.ensureClient(clientID);
481
- const patches = fn(updater);
482
- this.#cvr = await this.#flushUpdater(lc, updater);
483
- if (cmpVersions(cvr.version, this.#cvr.version) < 0) {
484
- // Send pokes to catch up clients that are up to date.
485
- // (Clients that are behind the cvr.version need to be caught up in
486
- // #syncQueryPipelineSet(), as row data may be needed for catchup)
487
- const newCVR = this.#cvr;
488
- const pokers = startPoke(this.#getClients(cvr.version), newCVR.version);
489
- for (const patch of patches) {
490
- await pokers.addPatch(patch);
764
+ for (const {
765
+ id: queryID,
766
+ transformationHash,
767
+ transformedAst
768
+ } of transformedQueries) {
769
+ const timer = new TimeSliceTimer();
770
+ let count = 0;
771
+ await startAsyncSpan(
772
+ tracer,
773
+ "vs.#hydrateUnchangedQueries.addQuery",
774
+ async (span) => {
775
+ span.setAttribute("queryHash", queryID);
776
+ span.setAttribute("transformationHash", transformationHash);
777
+ span.setAttribute("table", transformedAst.table);
778
+ for (const _ of this.#pipelines.addQuery(
779
+ transformationHash,
780
+ queryID,
781
+ transformedAst,
782
+ await timer.start()
783
+ )) {
784
+ if (++count % TIME_SLICE_CHECK_SIZE === 0) {
785
+ if (timer.elapsedLap() > TIME_SLICE_MS) {
786
+ await timer.yieldProcess();
787
+ }
491
788
  }
492
- await pokers.end(newCVR.version);
789
+ }
493
790
  }
494
- if (this.#pipelinesSynced) {
495
- await this.#syncQueryPipelineSet(lc, this.#cvr);
496
- }
497
- return this.#cvr;
791
+ );
792
+ const elapsed = timer.totalElapsed();
793
+ this.#hydrations.add(1);
794
+ this.#hydrationTime.record(elapsed / 1e3);
795
+ this.#addQueryMaterializationServerMetric(transformationHash, elapsed);
796
+ lc.debug?.(`hydrated ${count} rows for ${queryID} (${elapsed} ms)`);
498
797
  }
499
- /**
500
- * Runs the given `fn` to process the `msg` from within the `#lock`,
501
- * optionally adding the `newClient` if supplied.
502
- */
503
- #runInLockForClient(ctx, msg, fn, newClient) {
504
- this.#lc.debug?.('viewSyncer.#runInLockForClient');
505
- const { clientID, wsID } = ctx;
506
- const [cmd, body] = msg;
507
- if (newClient || !this.#clients.has(clientID)) {
508
- this.#lastConnectTime = Date.now();
509
- }
510
- return startAsyncSpan(tracer, `vs.#runInLockForClient(${cmd})`, async () => {
511
- let client;
512
- try {
513
- await this.#runInLockWithCVR((lc, cvr) => {
514
- lc = lc
515
- .withContext('clientID', clientID)
516
- .withContext('wsID', wsID)
517
- .withContext('cmd', cmd);
518
- lc.debug?.('acquired lock for cvr');
519
- client = this.#clients.get(clientID);
520
- if (client?.wsID !== wsID) {
521
- lc.debug?.('mismatched wsID', client?.wsID, wsID);
522
- // Only respond to messages of the currently connected client.
523
- // Connections may have been drained or dropped due to an error.
524
- return;
525
- }
526
- if (newClient) {
527
- assert(newClient === client, 'newClient must match existing client');
528
- checkClientAndCVRVersions(client.version(), cvr.version);
529
- }
530
- else if (!this.#clients.has(clientID)) {
531
- lc.warn?.(`Processing ${cmd} before initConnection was received`);
532
- }
533
- lc.debug?.(cmd, body);
534
- return fn(lc, clientID, body, cvr);
535
- });
536
- }
537
- catch (e) {
538
- const lc = this.#lc
539
- .withContext('clientID', clientID)
540
- .withContext('wsID', wsID)
541
- .withContext('cmd', cmd);
542
- lc[getLogLevel(e)]?.(`closing connection with error`, e);
543
- if (client) {
544
- // Ideally, propagate the exception to the client's downstream subscription ...
545
- client.fail(e);
546
- }
547
- else {
548
- // unless the exception happened before the client could be looked up.
549
- throw e;
550
- }
551
- }
552
- });
798
+ }
799
+ #processTransformedCustomQueries(lc, transformedCustomQueries, cb, customQueryMap) {
800
+ if ("kind" in transformedCustomQueries) {
801
+ this.#sendQueryTransformErrorToClients(
802
+ customQueryMap,
803
+ transformedCustomQueries
804
+ );
805
+ return transformedCustomQueries.queryIDs;
553
806
  }
554
- #getClients(atVersion) {
555
- const clients = [...this.#clients.values()];
556
- return atVersion
557
- ? clients.filter(c => cmpVersions(c.version() ?? EMPTY_CVR_VERSION, atVersion) === 0)
558
- : clients;
807
+ const appQueryErrors = [];
808
+ for (const q of transformedCustomQueries) {
809
+ if ("error" in q) {
810
+ const errorMessage = `Error transforming custom query ${q.name}: ${q.error}${q.details ? ` ${JSON.stringify(q.details)}` : ""}`;
811
+ lc.error?.(errorMessage, q);
812
+ appQueryErrors.push(q);
813
+ continue;
814
+ }
815
+ cb(q);
559
816
  }
560
- // Must be called from within #lock.
561
- #handleConfigUpdate = (lc, clientID, { clientSchema, deleted, desiredQueriesPatch, activeClients, }, cvr) => startAsyncSpan(tracer, 'vs.#patchQueries', async () => {
562
- const deletedClientIDs = [];
563
- const deletedClientGroupIDs = [];
564
- cvr = await this.#updateCVRConfig(lc, cvr, clientID, updater => {
565
- const { ttlClock } = cvr;
566
- const patches = [];
567
- if (clientSchema) {
568
- updater.setClientSchema(lc, clientSchema);
569
- }
570
- // Apply requested patches.
571
- lc.debug?.(`applying ${desiredQueriesPatch?.length} query patches`);
572
- if (desiredQueriesPatch?.length) {
573
- for (const patch of desiredQueriesPatch) {
574
- switch (patch.op) {
575
- case 'put':
576
- patches.push(...updater.putDesiredQueries(clientID, [patch]));
577
- break;
578
- case 'del':
579
- patches.push(...updater.markDesiredQueriesAsInactive(clientID, [patch.hash], ttlClock));
580
- break;
581
- case 'clear':
582
- patches.push(...updater.clearDesiredQueries(clientID));
583
- break;
584
- }
585
- }
586
- }
587
- const clientIDsToDelete = new Set();
588
- if (activeClients) {
589
- // We find all the clients in this client group that are not active.
590
- const allClientIDs = Object.keys(cvr.clients);
591
- const activeClientsSet = new Set(activeClients);
592
- for (const id of allClientIDs) {
593
- if (!activeClientsSet.has(id)) {
594
- clientIDsToDelete.add(id);
595
- }
596
- }
597
- }
598
- if (deleted?.clientIDs?.length) {
599
- for (const cid of deleted.clientIDs) {
600
- assert(cid !== clientID, 'cannot delete self');
601
- clientIDsToDelete.add(cid);
602
- }
603
- }
604
- for (const cid of clientIDsToDelete) {
605
- const patchesDueToClient = updater.deleteClient(cid, ttlClock);
606
- patches.push(...patchesDueToClient);
607
- deletedClientIDs.push(cid);
608
- }
609
- if (deleted?.clientGroupIDs?.length) {
610
- lc.debug?.(`ignoring ${deleted.clientGroupIDs.length} deprecated client group deletes`);
611
- }
612
- return patches;
613
- });
614
- // Send 'deleteClients' ack to the clients.
615
- if ((deletedClientIDs.length && deleted?.clientIDs?.length) ||
616
- deletedClientGroupIDs.length) {
617
- const clients = this.#getClients();
618
- await Promise.allSettled(clients.map(client => client.sendDeleteClients(lc, deletedClientIDs, deletedClientGroupIDs)));
817
+ this.#sendQueryTransformErrorToClients(customQueryMap, appQueryErrors);
818
+ return appQueryErrors.map((q) => q.id);
819
+ }
820
+ #sendQueryTransformErrorToClients(customQueryMap, errorOrErrors) {
821
+ const getAffectedClientIDs = (queryIDs) => {
822
+ const clientIds = /* @__PURE__ */ new Set();
823
+ for (const queryID of queryIDs) {
824
+ const q = customQueryMap.get(queryID);
825
+ assert(
826
+ q,
827
+ `got an error for query ${queryID} that does not map back to a custom query`
828
+ );
829
+ Object.keys(q.clientState).forEach((id) => clientIds.add(id));
830
+ }
831
+ return clientIds;
832
+ };
833
+ if ("queryIDs" in errorOrErrors) {
834
+ for (const clientId of getAffectedClientIDs(errorOrErrors.queryIDs)) {
835
+ this.#clients.get(clientId)?.sendQueryTransformFailedError(errorOrErrors);
836
+ }
837
+ return;
838
+ }
839
+ const appErrorGroups = /* @__PURE__ */ new Map();
840
+ for (const err of errorOrErrors) {
841
+ for (const clientId of getAffectedClientIDs([err.id])) {
842
+ const group = appErrorGroups.get(clientId) ?? [];
843
+ group.push(err);
844
+ appErrorGroups.set(clientId, group);
845
+ }
846
+ }
847
+ for (const [clientId, errors] of appErrorGroups) {
848
+ this.#clients.get(clientId)?.sendQueryTransformApplicationErrors(errors);
849
+ }
850
+ }
851
+ #addQueryMaterializationServerMetric(transformationHash, elapsed) {
852
+ this.#inspectorDelegate.addMetric(
853
+ "query-materialization-server",
854
+ elapsed,
855
+ transformationHash
856
+ );
857
+ }
858
+ /**
859
+ * Adds and/or removes queries to/from the PipelineDriver to bring it
860
+ * in sync with the set of queries in the CVR (both got and desired).
861
+ * If queries are added, removed, or queried due to a new state version,
862
+ * a new CVR version is created and pokes sent to connected clients.
863
+ *
864
+ * This must be called from within the #lock.
865
+ */
866
+ #syncQueryPipelineSet(lc, cvr) {
867
+ return startAsyncSpan(tracer, "vs.#syncQueryPipelineSet", async () => {
868
+ assert(
869
+ this.#pipelines.initialized(),
870
+ "pipelines must be initialized (syncQueryPipelineSet)"
871
+ );
872
+ const [hydratedQueries, byOriginalHash] = this.#pipelines.addedQueries();
873
+ const hashToIDs = /* @__PURE__ */ new Map();
874
+ if (this.#ttlClock === void 0) {
875
+ this.#ttlClock = cvr.ttlClock;
876
+ }
877
+ const now = Date.now();
878
+ const ttlClock = this.#getTTLClock(now);
879
+ const cvrQueryEntires = Object.entries(cvr.queries);
880
+ const customQueries = /* @__PURE__ */ new Map();
881
+ const otherQueries = [];
882
+ const transformedQueries = [];
883
+ for (const [id, query] of cvrQueryEntires) {
884
+ if (query.type === "custom") {
885
+ assert(id === query.id, "custom query id mismatch");
886
+ customQueries.set(id, query);
887
+ } else {
888
+ otherQueries.push({ id, query });
619
889
  }
620
- this.#scheduleExpireEviction(lc, cvr);
621
- });
622
- #scheduleExpireEviction(lc, cvr) {
623
- const { ttlClock } = cvr;
624
- this.#stopExpireTimer();
625
- // first see if there is any inactive query with a ttl.
626
- const next = nextEvictionTime(cvr);
627
- if (next === undefined) {
628
- lc.debug?.('no inactive queries with ttl');
629
- // no inactive queries with a ttl. Cancel existing timeout if any.
630
- return;
890
+ }
891
+ for (const { id, query: origQuery } of otherQueries) {
892
+ assert(id === origQuery.id, "query id mismatch");
893
+ const transformed = transformAndHashQuery(
894
+ lc,
895
+ origQuery.id,
896
+ origQuery.ast,
897
+ must(this.#pipelines.currentPermissions()).permissions ?? {
898
+ tables: {}
899
+ },
900
+ this.#authData?.decoded,
901
+ origQuery.type === "internal"
902
+ );
903
+ transformedQueries.push({
904
+ id,
905
+ origQuery,
906
+ transformed
907
+ });
908
+ }
909
+ if (customQueries.size > 0 && !this.#customQueryTransformer) {
910
+ lc.error?.(
911
+ "Custom/named queries were requested but no `ZERO_GET_QUERIES_URL` is configured for Zero Cache."
912
+ );
913
+ }
914
+ let erroredQueryIDs;
915
+ if (this.#customQueryTransformer && customQueries.size > 0) {
916
+ const transformStart = performance.now();
917
+ let transformedCustomQueries;
918
+ try {
919
+ transformedCustomQueries = await this.#customQueryTransformer.transform(
920
+ this.#getHeaderOptions(true),
921
+ customQueries.values(),
922
+ this.userQueryURL
923
+ );
924
+ this.#queryTransformations.add(1, { result: "success" });
925
+ } catch (e) {
926
+ this.#queryTransformations.add(1, { result: "error" });
927
+ throw e;
928
+ } finally {
929
+ const transformDuration = (performance.now() - transformStart) / 1e3;
930
+ this.#queryTransformationTime.record(transformDuration);
631
931
  }
632
- // It is common for many queries to be evicted close to the same time, so
633
- // we add a small delay so we can collapse multiple evictions into a
634
- // single timer. However, don't add the delay if we're already at the
635
- // maximum timer limit, as that's not about collapsing.
636
- const delay = Math.max(TTL_TIMER_HYSTERESIS, Math.min(ttlClockAsNumber(next) -
637
- ttlClockAsNumber(ttlClock) +
638
- TTL_TIMER_HYSTERESIS, MAX_TTL_MS));
639
- lc.debug?.('Scheduling eviction timer to run in ', delay, 'ms');
640
- this.#expiredQueriesTimer = this.#setTimeout(() => {
641
- this.#expiredQueriesTimer = 0;
642
- this.#runInLockWithCVR((lc, cvr) => this.#removeExpiredQueries(lc, cvr)).catch(e =>
643
- // If an error occurs (e.g. ownership change), propagate the error
644
- // to the main run() loop via the #stateChanges Subscription.
645
- this.#stateChanges.fail(e));
646
- }, delay);
647
- }
648
- /**
649
- * Adds and hydrates pipelines for queries whose results are already
650
- * recorded in the CVR. Namely:
651
- *
652
- * 1. The CVR state version and database version are the same.
653
- * 2. The transformation hash of the queries equal those in the CVR.
654
- *
655
- * Note that by definition, only "got" queries can satisfy condition (2),
656
- * as desired queries do not have a transformation hash.
657
- *
658
- * This is an initialization step that sets up pipeline state without
659
- * the expensive of loading and diffing CVR row state.
660
- *
661
- * This must be called from within the #lock.
662
- */
663
- async #hydrateUnchangedQueries(lc, cvr) {
664
- assert(this.#pipelines.initialized(), 'pipelines must be initialized');
665
- const dbVersion = this.#pipelines.currentVersion();
666
- const cvrVersion = cvr.version;
667
- if (cvrVersion.stateVersion !== dbVersion) {
668
- lc.info?.(`CVR (${versionToCookie(cvrVersion)}) is behind db ${dbVersion}`);
669
- return; // hydration needs to be run with the CVR updater.
932
+ if (!Array.isArray(transformedCustomQueries) && transformedCustomQueries.kind === TransformFailed) {
933
+ throw new ProtocolErrorWithLevel(
934
+ transformedCustomQueries,
935
+ getLogLevel(transformedCustomQueries.kind)
936
+ );
670
937
  }
671
- const gotQueries = Object.entries(cvr.queries).filter(([_, state]) => state.transformationHash !== undefined);
672
- const customQueries = new Map();
673
- const otherQueries = [];
674
- for (const [, query] of gotQueries) {
675
- if (query.type !== 'internal' &&
676
- Object.values(query.clientState).every(({ inactivatedAt }) => inactivatedAt !== undefined)) {
677
- continue; // No longer desired.
678
- }
679
- if (query.type === 'custom') {
680
- customQueries.set(query.id, query);
681
- }
682
- else {
683
- otherQueries.push(query);
938
+ const successfullyTransformed = /* @__PURE__ */ new Map();
939
+ erroredQueryIDs = this.#processTransformedCustomQueries(
940
+ lc,
941
+ transformedCustomQueries,
942
+ (q) => {
943
+ successfullyTransformed.set(q.id, q);
944
+ transformedQueries.push({
945
+ id: q.id,
946
+ origQuery: must(customQueries.get(q.id)),
947
+ transformed: q
948
+ });
949
+ },
950
+ customQueries
951
+ );
952
+ for (const [queryID, newTransform] of successfullyTransformed) {
953
+ const existingTransforms = byOriginalHash.get(queryID);
954
+ if (existingTransforms && existingTransforms.length > 0) {
955
+ const oldHash = existingTransforms[0].transformationHash;
956
+ const newHash = newTransform.transformationHash;
957
+ if (oldHash !== newHash) {
958
+ lc.info?.(
959
+ `Query ${queryID} transformation changed: ${oldHash} -> ${newHash}`
960
+ );
961
+ this.#checkForThrashing(queryID);
962
+ this.#queryTransformationHashChanges.add(1);
963
+ } else {
964
+ this.#queryTransformationNoOps.add(1);
684
965
  }
966
+ }
685
967
  }
686
- const transformedQueries = [];
687
- if (customQueries.size > 0 && !this.#customQueryTransformer) {
688
- lc.error?.('Custom/named queries were requested but no `ZERO_GET_QUERIES_URL` is configured for Zero Cache.');
968
+ }
969
+ const serverQueries = transformedQueries.map(
970
+ ({ id, origQuery, transformed }) => {
971
+ const ids = hashToIDs.get(transformed.transformationHash);
972
+ if (ids) {
973
+ ids.push(id);
974
+ } else {
975
+ hashToIDs.set(transformed.transformationHash, [id]);
976
+ }
977
+ return {
978
+ id,
979
+ ast: transformed.transformedAst,
980
+ transformationHash: transformed.transformationHash,
981
+ remove: expired(ttlClock, origQuery)
982
+ };
689
983
  }
690
- const [_, byOriginalHash] = this.#pipelines.addedQueries();
691
- if (this.#customQueryTransformer && customQueries.size > 0) {
692
- const filteredCustomQueries = this.#filterCustomQueries(customQueries.values(), byOriginalHash, undefined);
693
- const transformedCustomQueries = await this.#customQueryTransformer.transform(this.#getHeaderOptions(this.#queryConfig.forwardCookies), filteredCustomQueries, this.userQueryURL);
694
- this.#processTransformedCustomQueries(lc, transformedCustomQueries, (q) => transformedQueries.push(q), customQueries);
984
+ );
985
+ const addQueries = serverQueries.filter(
986
+ (q) => !q.remove && !hydratedQueries.has(q.transformationHash)
987
+ );
988
+ const removeQueries = serverQueries.filter((q) => q.remove);
989
+ const desiredQueries = new Set(
990
+ serverQueries.filter((q) => !q.remove).map((q) => q.transformationHash)
991
+ );
992
+ const unhydrateQueries = [...hydratedQueries].filter(
993
+ (transformationHash) => !desiredQueries.has(transformationHash)
994
+ );
995
+ for (const q of addQueries) {
996
+ const orig = cvr.queries[q.id];
997
+ lc.debug?.(
998
+ "ViewSyncer adding query",
999
+ q.ast,
1000
+ "transformed from",
1001
+ orig.type === "custom" ? orig.name : orig.ast
1002
+ );
1003
+ }
1004
+ if (erroredQueryIDs) {
1005
+ for (const queryID of erroredQueryIDs) {
1006
+ removeQueries.push({
1007
+ id: queryID,
1008
+ transformationHash: void 0
1009
+ });
695
1010
  }
696
- for (const q of otherQueries) {
697
- const transformed = transformAndHashQuery(lc, q.id, q.ast, must(this.#pipelines.currentPermissions()).permissions ?? {
698
- tables: {},
699
- }, this.#authData?.decoded, q.type === 'internal');
700
- if (transformed.transformationHash === q.transformationHash) {
701
- // only processing unchanged queries here
702
- transformedQueries.push(transformed);
703
- }
1011
+ }
1012
+ if (addQueries.length > 0 || removeQueries.length > 0 || unhydrateQueries.length > 0) {
1013
+ await this.#addAndRemoveQueries(
1014
+ lc,
1015
+ cvr,
1016
+ addQueries,
1017
+ removeQueries,
1018
+ unhydrateQueries,
1019
+ hashToIDs
1020
+ );
1021
+ } else {
1022
+ await this.#catchupClients(lc, cvr);
1023
+ }
1024
+ });
1025
+ }
1026
+ /**
1027
+ * Check if a query is being replaced too frequently (thrashing).
1028
+ * Logs a warning if the query has been replaced more than 3 times in 60 seconds.
1029
+ */
1030
+ #checkForThrashing(queryID) {
1031
+ const THRASH_WINDOW_MS = 6e4;
1032
+ const THRASH_THRESHOLD = 3;
1033
+ const now = Date.now();
1034
+ let record = this.#queryReplacements.get(queryID);
1035
+ if (!record) {
1036
+ record = { count: 1, windowStart: now };
1037
+ this.#queryReplacements.set(queryID, record);
1038
+ return;
1039
+ }
1040
+ if (now - record.windowStart > THRASH_WINDOW_MS) {
1041
+ this.#queryReplacements.delete(queryID);
1042
+ this.#queryReplacements.set(queryID, { count: 1, windowStart: now });
1043
+ return;
1044
+ }
1045
+ record.count++;
1046
+ if (record.count >= THRASH_THRESHOLD) {
1047
+ this.#lc.warn?.(
1048
+ `Query thrashing detected for query ${queryID}. ${record.count} replacements in 60s. This may indicate clients with different auth contexts connecting to the same client group.`
1049
+ );
1050
+ }
1051
+ }
1052
+ // This must be called from within the #lock.
1053
+ #addAndRemoveQueries(lc, cvr, addQueries, removeQueries, unhydrateQueries, hashToIDs) {
1054
+ return startAsyncSpan(tracer, "vs.#addAndRemoveQueries", async () => {
1055
+ assert(
1056
+ addQueries.length > 0 || removeQueries.length > 0 || unhydrateQueries.length > 0,
1057
+ "Must have queries to add or remove"
1058
+ );
1059
+ const start = performance.now();
1060
+ const stateVersion = this.#pipelines.currentVersion();
1061
+ lc = lc.withContext("stateVersion", stateVersion);
1062
+ lc.info?.(`hydrating ${addQueries.length} queries`);
1063
+ const updater = new CVRQueryDrivenUpdater(
1064
+ this.#cvrStore,
1065
+ cvr,
1066
+ stateVersion,
1067
+ this.#pipelines.replicaVersion
1068
+ );
1069
+ const { newVersion, queryPatches } = updater.trackQueries(
1070
+ lc,
1071
+ addQueries,
1072
+ removeQueries
1073
+ );
1074
+ const clients = this.#getClients();
1075
+ const pokers = startPoke(
1076
+ clients,
1077
+ newVersion,
1078
+ this.#pipelines.currentSchemaVersions()
1079
+ );
1080
+ for (const patch of queryPatches) {
1081
+ await pokers.addPatch(patch);
1082
+ }
1083
+ for (const q of removeQueries) {
1084
+ if (q.transformationHash) {
1085
+ this.#pipelines.removeQuery(q.transformationHash);
704
1086
  }
705
- for (const { id: queryID, transformationHash, transformedAst, } of transformedQueries) {
706
- const timer = new TimeSliceTimer();
707
- let count = 0;
708
- await startAsyncSpan(tracer, 'vs.#hydrateUnchangedQueries.addQuery', async (span) => {
709
- span.setAttribute('queryHash', queryID);
710
- span.setAttribute('transformationHash', transformationHash);
711
- span.setAttribute('table', transformedAst.table);
712
- for (const _ of this.#pipelines.addQuery(transformationHash, queryID, transformedAst, await timer.start())) {
713
- if (++count % TIME_SLICE_CHECK_SIZE === 0) {
714
- if (timer.elapsedLap() > TIME_SLICE_MS) {
715
- await timer.yieldProcess();
716
- }
717
- }
718
- }
719
- });
720
- const elapsed = timer.totalElapsed();
721
- this.#hydrations.add(1);
722
- this.#hydrationTime.record(elapsed / 1000);
723
- this.#addQueryMaterializationServerMetric(transformationHash, elapsed);
724
- lc.debug?.(`hydrated ${count} rows for ${queryID} (${elapsed} ms)`);
1087
+ this.#inspectorDelegate.removeQuery(q.id);
1088
+ this.#queryReplacements.delete(q.id);
1089
+ }
1090
+ for (const hash of unhydrateQueries) {
1091
+ this.#pipelines.removeQuery(hash);
1092
+ const ids = hashToIDs.get(hash);
1093
+ if (ids) {
1094
+ for (const id of ids) {
1095
+ this.#inspectorDelegate.removeQuery(id);
1096
+ this.#queryReplacements.delete(id);
1097
+ }
725
1098
  }
726
- }
727
- #processTransformedCustomQueries(lc, transformedCustomQueries, cb, customQueryMap) {
728
- if ('kind' in transformedCustomQueries) {
729
- this.#sendQueryTransformErrorToClients(customQueryMap, transformedCustomQueries);
730
- return transformedCustomQueries.queryIDs;
1099
+ }
1100
+ let totalProcessTime = 0;
1101
+ const timer = new TimeSliceTimer();
1102
+ const pipelines = this.#pipelines;
1103
+ const hydrations = this.#hydrations;
1104
+ const hydrationTime = this.#hydrationTime;
1105
+ const self = this;
1106
+ await yieldProcess();
1107
+ function* generateRowChanges(slowHydrateThreshold) {
1108
+ for (const q of addQueries) {
1109
+ lc = lc.withContext("hash", q.id).withContext("transformationHash", q.transformationHash);
1110
+ lc.debug?.(`adding pipeline for query`, q.ast);
1111
+ yield* pipelines.addQuery(
1112
+ q.transformationHash,
1113
+ q.id,
1114
+ q.ast,
1115
+ timer.startWithoutYielding()
1116
+ );
1117
+ const elapsed = timer.stop();
1118
+ totalProcessTime += elapsed;
1119
+ self.#addQueryMaterializationServerMetric(
1120
+ q.transformationHash,
1121
+ elapsed
1122
+ );
1123
+ if (elapsed > slowHydrateThreshold) {
1124
+ lc.warn?.("Slow query materialization", elapsed, q.ast);
1125
+ }
1126
+ manualSpan(tracer, "vs.addAndConsumeQuery", elapsed, {
1127
+ hash: q.id,
1128
+ transformationHash: q.transformationHash
1129
+ });
731
1130
  }
732
- const appQueryErrors = [];
733
- for (const q of transformedCustomQueries) {
734
- if ('error' in q) {
735
- lc.error?.(`Error transforming custom query ${q.name}: ${q.error}${q.details ? ` ${JSON.stringify(q.details)}` : ''}`);
736
- appQueryErrors.push(q);
737
- continue;
738
- }
739
- cb(q);
1131
+ hydrations.add(1);
1132
+ hydrationTime.record(totalProcessTime / 1e3);
1133
+ }
1134
+ await this.#processChanges(
1135
+ lc,
1136
+ timer,
1137
+ generateRowChanges(this.#slowHydrateThreshold),
1138
+ updater,
1139
+ pokers,
1140
+ hashToIDs
1141
+ );
1142
+ for (const patch of await updater.deleteUnreferencedRows(lc)) {
1143
+ await pokers.addPatch(patch);
1144
+ }
1145
+ this.#cvr = await this.#flushUpdater(lc, updater);
1146
+ const finalVersion = this.#cvr.version;
1147
+ await this.#catchupClients(
1148
+ lc,
1149
+ cvr,
1150
+ finalVersion,
1151
+ addQueries.map((q) => q.id),
1152
+ pokers
1153
+ );
1154
+ await pokers.end(finalVersion);
1155
+ const wallTime = performance.now() - start;
1156
+ lc.info?.(
1157
+ `finished processing queries (process: ${totalProcessTime} ms, wall: ${wallTime} ms)`
1158
+ );
1159
+ });
1160
+ }
1161
+ /**
1162
+ * @param cvr The CVR to which clients should be caught up to. This does
1163
+ * not necessarily need to be the current CVR.
1164
+ * @param current The expected current CVR version. Before performing
1165
+ * catchup, the snapshot read will verify that the CVR has not been
1166
+ * concurrently modified. Note that this only needs to be done for
1167
+ * catchup because it is the only time data from the CVR DB is
1168
+ * "exported" without being gated by a CVR flush (which provides
1169
+ * concurrency protection in all other cases).
1170
+ *
1171
+ * If unspecified, the version of the `cvr` is used.
1172
+ * @param excludeQueryHashes Exclude patches from rows associated with
1173
+ * the specified queries.
1174
+ * @param usePokers If specified, sends pokes on existing PokeHandlers,
1175
+ * in which case the caller is responsible for sending the `pokeEnd`
1176
+ * messages. If unspecified, the pokes will be started and ended
1177
+ * using the version from the supplied `cvr`.
1178
+ */
1179
+ // Must be called within #lock
1180
+ #catchupClients(lc, cvr, current, excludeQueryHashes = [], usePokers) {
1181
+ return startAsyncSpan(tracer, "vs.#catchupClients", async (span) => {
1182
+ current ??= cvr.version;
1183
+ const clients = this.#getClients();
1184
+ const pokers = usePokers ?? startPoke(
1185
+ clients,
1186
+ cvr.version,
1187
+ this.#pipelines.currentSchemaVersions()
1188
+ );
1189
+ span.setAttribute("numClients", clients.length);
1190
+ const catchupFrom = clients.map((c) => c.version()).reduce((a, b) => cmpVersions(a, b) < 0 ? a : b, cvr.version);
1191
+ const rowPatches = this.#cvrStore.catchupRowPatches(
1192
+ lc,
1193
+ catchupFrom,
1194
+ cvr,
1195
+ current,
1196
+ excludeQueryHashes
1197
+ );
1198
+ const configPatches = this.#cvrStore.catchupConfigPatches(
1199
+ lc,
1200
+ catchupFrom,
1201
+ cvr,
1202
+ current
1203
+ );
1204
+ let rowPatchCount = 0;
1205
+ for await (const rows of rowPatches) {
1206
+ for (const row of rows) {
1207
+ const { schema, table } = row;
1208
+ const rowKey = row.rowKey;
1209
+ const toVersion = versionFromString(row.patchVersion);
1210
+ const id = { schema, table, rowKey };
1211
+ let patch;
1212
+ if (!row.refCounts) {
1213
+ patch = { type: "row", op: "del", id };
1214
+ } else {
1215
+ const row2 = must(
1216
+ this.#pipelines.getRow(table, rowKey),
1217
+ `Missing row ${table}:${stringify(rowKey)}`
1218
+ );
1219
+ const { contents } = contentsAndVersion(row2);
1220
+ patch = { type: "row", op: "put", id, contents };
1221
+ }
1222
+ const patchToVersion = { patch, toVersion };
1223
+ await pokers.addPatch(patchToVersion);
1224
+ rowPatchCount++;
740
1225
  }
741
- this.#sendQueryTransformErrorToClients(customQueryMap, appQueryErrors);
742
- return appQueryErrors.map(q => q.id);
743
- }
744
- #sendQueryTransformErrorToClients(customQueryMap, errorOrErrors) {
745
- const getAffectedClientIDs = (queryIDs) => {
746
- const clientIds = new Set();
747
- for (const queryID of queryIDs) {
748
- const q = customQueryMap.get(queryID);
749
- assert(q, `got an error for query ${queryID} that does not map back to a custom query`);
750
- Object.keys(q.clientState).forEach(id => clientIds.add(id));
751
- }
752
- return clientIds;
753
- };
754
- // send the transform failed error to each affected client
755
- if ('queryIDs' in errorOrErrors) {
756
- for (const clientId of getAffectedClientIDs(errorOrErrors.queryIDs)) {
757
- this.#clients
758
- .get(clientId)
759
- ?.sendQueryTransformFailedError(errorOrErrors);
760
- }
761
- return;
1226
+ }
1227
+ span.setAttribute("rowPatchCount", rowPatchCount);
1228
+ if (rowPatchCount) {
1229
+ lc.debug?.(`sent ${rowPatchCount} row patches`);
1230
+ }
1231
+ for (const patch of await configPatches) {
1232
+ await pokers.addPatch(patch);
1233
+ }
1234
+ if (!usePokers) {
1235
+ await pokers.end(cvr.version);
1236
+ }
1237
+ });
1238
+ }
1239
+ #processChanges(lc, timer, changes, updater, pokers, hashToIDs) {
1240
+ return startAsyncSpan(tracer, "vs.#processChanges", async () => {
1241
+ const start = performance.now();
1242
+ const rows = new CustomKeyMap(rowIDString);
1243
+ let total = 0;
1244
+ const processBatch = () => startAsyncSpan(tracer, "processBatch", async () => {
1245
+ const wallElapsed = performance.now() - start;
1246
+ total += rows.size;
1247
+ lc.debug?.(
1248
+ `processing ${rows.size} (of ${total}) rows (${wallElapsed} ms)`
1249
+ );
1250
+ const patches = await updater.received(lc, rows);
1251
+ for (const patch of patches) {
1252
+ await pokers.addPatch(patch);
762
1253
  }
763
- // Group and send application errors to each affected client
764
- const appErrorGroups = new Map();
765
- for (const err of errorOrErrors) {
766
- // Application errors need to be grouped by client
767
- for (const clientId of getAffectedClientIDs([err.id])) {
768
- const group = appErrorGroups.get(clientId) ?? [];
769
- group.push(err);
770
- appErrorGroups.set(clientId, group);
1254
+ rows.clear();
1255
+ });
1256
+ await startAsyncSpan(tracer, "loopingChanges", async (span) => {
1257
+ for (const change of changes) {
1258
+ const {
1259
+ type,
1260
+ queryHash: transformationHash,
1261
+ table,
1262
+ rowKey,
1263
+ row
1264
+ } = change;
1265
+ const queryIDs = must(
1266
+ hashToIDs.get(transformationHash),
1267
+ "could not find the original hash for the transformation hash"
1268
+ );
1269
+ const rowID = { schema: "", table, rowKey };
1270
+ let parsedRow = rows.get(rowID);
1271
+ if (!parsedRow) {
1272
+ parsedRow = { refCounts: {} };
1273
+ rows.set(rowID, parsedRow);
1274
+ }
1275
+ queryIDs.forEach((hash) => parsedRow.refCounts[hash] ??= 0);
1276
+ const updateVersion = (row2) => {
1277
+ const { version: version2, contents } = contentsAndVersion(row2);
1278
+ parsedRow.version = version2;
1279
+ parsedRow.contents = contents;
1280
+ };
1281
+ switch (type) {
1282
+ case "add":
1283
+ updateVersion(row);
1284
+ queryIDs.forEach((hash) => parsedRow.refCounts[hash]++);
1285
+ break;
1286
+ case "edit":
1287
+ updateVersion(row);
1288
+ break;
1289
+ case "remove":
1290
+ queryIDs.forEach((hash) => parsedRow.refCounts[hash]--);
1291
+ break;
1292
+ default:
1293
+ unreachable(type);
1294
+ }
1295
+ if (rows.size % CURSOR_PAGE_SIZE === 0) {
1296
+ await processBatch();
1297
+ }
1298
+ if (rows.size % TIME_SLICE_CHECK_SIZE === 0) {
1299
+ if (timer.elapsedLap() > TIME_SLICE_MS) {
1300
+ await timer.yieldProcess();
771
1301
  }
1302
+ }
772
1303
  }
773
- for (const [clientId, errors] of appErrorGroups) {
774
- this.#clients.get(clientId)?.sendQueryTransformApplicationErrors(errors);
1304
+ if (rows.size) {
1305
+ await processBatch();
775
1306
  }
776
- }
777
- #addQueryMaterializationServerMetric(transformationHash, elapsed) {
778
- this.#inspectorDelegate.addMetric('query-materialization-server', elapsed, transformationHash);
779
- }
780
- /**
781
- * Adds and/or removes queries to/from the PipelineDriver to bring it
782
- * in sync with the set of queries in the CVR (both got and desired).
783
- * If queries are added, removed, or queried due to a new state version,
784
- * a new CVR version is created and pokes sent to connected clients.
785
- *
786
- * This must be called from within the #lock.
787
- */
788
- #syncQueryPipelineSet(lc, cvr) {
789
- return startAsyncSpan(tracer, 'vs.#syncQueryPipelineSet', async () => {
790
- assert(this.#pipelines.initialized(), 'pipelines must be initialized (syncQueryPipelineSet)');
791
- const [hydratedQueries, byOriginalHash] = this.#pipelines.addedQueries();
792
- // Convert queries to their transformed ast's and hashes
793
- const hashToIDs = new Map();
794
- if (this.#ttlClock === undefined) {
795
- // Get it from the CVR or initialize it to now.
796
- this.#ttlClock = cvr.ttlClock;
797
- }
798
- const now = Date.now();
799
- const ttlClock = this.#getTTLClock(now);
800
- // group cvr queries into:
801
- // 1. custom queries
802
- // 2. everything else
803
- // Handle transformation appropriately
804
- // Then hydrate as `serverQueries`
805
- const cvrQueryEntires = Object.entries(cvr.queries);
806
- const customQueries = new Map();
807
- const otherQueries = [];
808
- const transformedQueries = [];
809
- for (const [id, query] of cvrQueryEntires) {
810
- if (query.type === 'custom') {
811
- // This should always match, no?
812
- assert(id === query.id, 'custom query id mismatch');
813
- customQueries.set(id, query);
814
- }
815
- else {
816
- otherQueries.push({ id, query });
817
- }
818
- }
819
- for (const { id, query: origQuery } of otherQueries) {
820
- // This should always match, no?
821
- assert(id === origQuery.id, 'query id mismatch');
822
- const transformed = transformAndHashQuery(lc, origQuery.id, origQuery.ast, must(this.#pipelines.currentPermissions()).permissions ?? {
823
- tables: {},
824
- }, this.#authData?.decoded, origQuery.type === 'internal');
825
- transformedQueries.push({
826
- id,
827
- origQuery,
828
- transformed,
829
- });
830
- }
831
- if (customQueries.size > 0 && !this.#customQueryTransformer) {
832
- lc.error?.('Custom/named queries were requested but no `ZERO_GET_QUERIES_URL` is configured for Zero Cache.');
833
- }
834
- let erroredQueryIDs;
835
- if (this.#customQueryTransformer && customQueries.size > 0) {
836
- const filteredCustomQueries = this.#filterCustomQueries(customQueries.values(), byOriginalHash, (origQuery, existing) => {
837
- for (const transformed of existing) {
838
- transformedQueries.push({
839
- id: origQuery.id,
840
- origQuery,
841
- transformed: {
842
- id: origQuery.id,
843
- transformationHash: transformed.transformationHash,
844
- transformedAst: transformed.transformedAst,
845
- },
846
- });
847
- }
848
- });
849
- const transformedCustomQueries = await this.#customQueryTransformer.transform(this.#getHeaderOptions(true), filteredCustomQueries, this.userQueryURL);
850
- erroredQueryIDs = this.#processTransformedCustomQueries(lc, transformedCustomQueries, (q) => transformedQueries.push({
851
- id: q.id,
852
- origQuery: must(customQueries.get(q.id)),
853
- transformed: q,
854
- }), customQueries);
855
- }
856
- const serverQueries = transformedQueries.map(({ id, origQuery, transformed }) => {
857
- const ids = hashToIDs.get(transformed.transformationHash);
858
- if (ids) {
859
- ids.push(id);
860
- }
861
- else {
862
- hashToIDs.set(transformed.transformationHash, [id]);
863
- }
864
- return {
865
- id,
866
- ast: transformed.transformedAst,
867
- transformationHash: transformed.transformationHash,
868
- remove: expired(ttlClock, origQuery),
869
- };
870
- });
871
- const addQueries = serverQueries.filter(q => !q.remove && !hydratedQueries.has(q.transformationHash));
872
- const removeQueries = serverQueries.filter(q => q.remove);
873
- const desiredQueries = new Set(serverQueries.filter(q => !q.remove).map(q => q.transformationHash));
874
- const unhydrateQueries = [...hydratedQueries].filter(transformationHash => !desiredQueries.has(transformationHash));
875
- for (const q of addQueries) {
876
- const orig = cvr.queries[q.id];
877
- lc.debug?.('ViewSyncer adding query', q.ast, 'transformed from', orig.type === 'custom' ? orig.name : orig.ast);
878
- }
879
- // These are queries we need to remove from `desired`, not `got`, because they never transformed.
880
- if (erroredQueryIDs) {
881
- for (const queryID of erroredQueryIDs) {
882
- removeQueries.push({
883
- id: queryID,
884
- transformationHash: undefined,
885
- });
886
- }
887
- }
888
- if (addQueries.length > 0 ||
889
- removeQueries.length > 0 ||
890
- unhydrateQueries.length > 0) {
891
- await this.#addAndRemoveQueries(lc, cvr, addQueries, removeQueries, unhydrateQueries, hashToIDs);
892
- }
893
- else {
894
- await this.#catchupClients(lc, cvr);
895
- }
896
- });
897
- }
898
- // Removes queries from `customQueries` that are already
899
- // transformed and in the pipelines. We do not want to re-transform
900
- // a query that has already been transformed. The reason is that
901
- // we do not want a query that is already running to suddenly flip
902
- // to error due to re-calling transform.
903
- #filterCustomQueries(customQueries, byOriginalHash, onExisting) {
904
- return wrapIterable(customQueries).filter(origQuery => {
905
- const existing = byOriginalHash.get(origQuery.id);
906
- if (existing) {
907
- onExisting?.(origQuery, existing);
908
- return false;
909
- }
910
- return true;
911
- });
912
- }
913
- // This must be called from within the #lock.
914
- #addAndRemoveQueries(lc, cvr, addQueries, removeQueries, unhydrateQueries, hashToIDs) {
915
- return startAsyncSpan(tracer, 'vs.#addAndRemoveQueries', async () => {
916
- assert(addQueries.length > 0 ||
917
- removeQueries.length > 0 ||
918
- unhydrateQueries.length > 0, 'Must have queries to add or remove');
919
- const start = performance.now();
920
- const stateVersion = this.#pipelines.currentVersion();
921
- lc = lc.withContext('stateVersion', stateVersion);
922
- lc.info?.(`hydrating ${addQueries.length} queries`);
923
- const updater = new CVRQueryDrivenUpdater(this.#cvrStore, cvr, stateVersion, this.#pipelines.replicaVersion);
924
- // Note: This kicks off background PG queries for CVR data associated with the
925
- // executed and removed queries.
926
- const { newVersion, queryPatches } = updater.trackQueries(lc, addQueries, removeQueries);
927
- const clients = this.#getClients();
928
- const pokers = startPoke(clients, newVersion, this.#pipelines.currentSchemaVersions());
929
- for (const patch of queryPatches) {
930
- await pokers.addPatch(patch);
931
- }
932
- // Removing queries is easy. The pipelines are dropped, and the CVR
933
- // updater handles the updates and pokes.
934
- for (const q of removeQueries) {
935
- if (q.transformationHash) {
936
- this.#pipelines.removeQuery(q.transformationHash);
937
- }
938
- // Remove per-query server metrics when query is deleted
939
- this.#inspectorDelegate.removeQuery(q.id);
940
- }
941
- for (const hash of unhydrateQueries) {
942
- this.#pipelines.removeQuery(hash);
943
- // Remove per-query server metrics for unhydrated queries
944
- const ids = hashToIDs.get(hash);
945
- if (ids) {
946
- for (const id of ids) {
947
- this.#inspectorDelegate.removeQuery(id);
948
- }
949
- }
950
- }
951
- let totalProcessTime = 0;
952
- const timer = new TimeSliceTimer();
953
- const pipelines = this.#pipelines;
954
- const hydrations = this.#hydrations;
955
- const hydrationTime = this.#hydrationTime;
956
- // oxlint-disable-next-line @typescript-eslint/no-this-alias
957
- const self = this;
958
- // yield at the very beginning so that the first time slice
959
- // is properly processed by the time-slice queue.
960
- await yieldProcess();
961
- function* generateRowChanges(slowHydrateThreshold) {
962
- for (const q of addQueries) {
963
- lc = lc
964
- .withContext('hash', q.id)
965
- .withContext('transformationHash', q.transformationHash);
966
- lc.debug?.(`adding pipeline for query`, q.ast);
967
- yield* pipelines.addQuery(q.transformationHash, q.id, q.ast, timer.startWithoutYielding());
968
- const elapsed = timer.stop();
969
- totalProcessTime += elapsed;
970
- self.#addQueryMaterializationServerMetric(q.transformationHash, elapsed);
971
- if (elapsed > slowHydrateThreshold) {
972
- lc.warn?.('Slow query materialization', elapsed, q.ast);
973
- }
974
- manualSpan(tracer, 'vs.addAndConsumeQuery', elapsed, {
975
- hash: q.id,
976
- transformationHash: q.transformationHash,
977
- });
978
- }
979
- hydrations.add(1);
980
- hydrationTime.record(totalProcessTime / 1000);
981
- }
982
- // #processChanges does batched de-duping of rows. Wrap all pipelines in
983
- // a single generator in order to maximize de-duping.
984
- await this.#processChanges(lc, timer, generateRowChanges(this.#slowHydrateThreshold), updater, pokers, hashToIDs);
985
- for (const patch of await updater.deleteUnreferencedRows(lc)) {
986
- await pokers.addPatch(patch);
987
- }
988
- // Commit the changes and update the CVR snapshot.
989
- this.#cvr = await this.#flushUpdater(lc, updater);
990
- const finalVersion = this.#cvr.version;
991
- // Before ending the poke, catch up clients that were behind the old CVR.
992
- await this.#catchupClients(lc, cvr, finalVersion, addQueries.map(q => q.id), pokers);
993
- // Signal clients to commit.
994
- await pokers.end(finalVersion);
995
- const wallTime = performance.now() - start;
996
- lc.info?.(`finished processing queries (process: ${totalProcessTime} ms, wall: ${wallTime} ms)`);
997
- });
998
- }
999
- /**
1000
- * @param cvr The CVR to which clients should be caught up to. This does
1001
- * not necessarily need to be the current CVR.
1002
- * @param current The expected current CVR version. Before performing
1003
- * catchup, the snapshot read will verify that the CVR has not been
1004
- * concurrently modified. Note that this only needs to be done for
1005
- * catchup because it is the only time data from the CVR DB is
1006
- * "exported" without being gated by a CVR flush (which provides
1007
- * concurrency protection in all other cases).
1008
- *
1009
- * If unspecified, the version of the `cvr` is used.
1010
- * @param excludeQueryHashes Exclude patches from rows associated with
1011
- * the specified queries.
1012
- * @param usePokers If specified, sends pokes on existing PokeHandlers,
1013
- * in which case the caller is responsible for sending the `pokeEnd`
1014
- * messages. If unspecified, the pokes will be started and ended
1015
- * using the version from the supplied `cvr`.
1016
- */
1017
- // Must be called within #lock
1018
- #catchupClients(lc, cvr, current, excludeQueryHashes = [], usePokers) {
1019
- return startAsyncSpan(tracer, 'vs.#catchupClients', async (span) => {
1020
- current ??= cvr.version;
1021
- const clients = this.#getClients();
1022
- const pokers = usePokers ??
1023
- startPoke(clients, cvr.version, this.#pipelines.currentSchemaVersions());
1024
- span.setAttribute('numClients', clients.length);
1025
- const catchupFrom = clients
1026
- .map(c => c.version())
1027
- .reduce((a, b) => (cmpVersions(a, b) < 0 ? a : b), cvr.version);
1028
- // This is an AsyncGenerator which won't execute until awaited.
1029
- const rowPatches = this.#cvrStore.catchupRowPatches(lc, catchupFrom, cvr, current, excludeQueryHashes);
1030
- // This is a plain async function that kicks off immediately.
1031
- const configPatches = this.#cvrStore.catchupConfigPatches(lc, catchupFrom, cvr, current);
1032
- // await the rowPatches first so that the AsyncGenerator kicks off.
1033
- let rowPatchCount = 0;
1034
- for await (const rows of rowPatches) {
1035
- for (const row of rows) {
1036
- const { schema, table } = row;
1037
- const rowKey = row.rowKey;
1038
- const toVersion = versionFromString(row.patchVersion);
1039
- const id = { schema, table, rowKey };
1040
- let patch;
1041
- if (!row.refCounts) {
1042
- patch = { type: 'row', op: 'del', id };
1043
- }
1044
- else {
1045
- const row = must(this.#pipelines.getRow(table, rowKey), `Missing row ${table}:${stringify(rowKey)}`);
1046
- const { contents } = contentsAndVersion(row);
1047
- patch = { type: 'row', op: 'put', id, contents };
1048
- }
1049
- const patchToVersion = { patch, toVersion };
1050
- await pokers.addPatch(patchToVersion);
1051
- rowPatchCount++;
1052
- }
1053
- }
1054
- span.setAttribute('rowPatchCount', rowPatchCount);
1055
- if (rowPatchCount) {
1056
- lc.debug?.(`sent ${rowPatchCount} row patches`);
1057
- }
1058
- // Then await the config patches which were fetched in parallel.
1059
- for (const patch of await configPatches) {
1060
- await pokers.addPatch(patch);
1061
- }
1062
- if (!usePokers) {
1063
- await pokers.end(cvr.version);
1064
- }
1065
- });
1066
- }
1067
- #processChanges(lc, timer, changes, updater, pokers, hashToIDs) {
1068
- return startAsyncSpan(tracer, 'vs.#processChanges', async () => {
1069
- const start = performance.now();
1070
- const rows = new CustomKeyMap(rowIDString);
1071
- let total = 0;
1072
- const processBatch = () => startAsyncSpan(tracer, 'processBatch', async () => {
1073
- const wallElapsed = performance.now() - start;
1074
- total += rows.size;
1075
- lc.debug?.(`processing ${rows.size} (of ${total}) rows (${wallElapsed} ms)`);
1076
- const patches = await updater.received(lc, rows);
1077
- for (const patch of patches) {
1078
- await pokers.addPatch(patch);
1079
- }
1080
- rows.clear();
1081
- });
1082
- await startAsyncSpan(tracer, 'loopingChanges', async (span) => {
1083
- for (const change of changes) {
1084
- const { type, queryHash: transformationHash, table, rowKey, row, } = change;
1085
- const queryIDs = must(hashToIDs.get(transformationHash), 'could not find the original hash for the transformation hash');
1086
- const rowID = { schema: '', table, rowKey: rowKey };
1087
- let parsedRow = rows.get(rowID);
1088
- if (!parsedRow) {
1089
- parsedRow = { refCounts: {} };
1090
- rows.set(rowID, parsedRow);
1091
- }
1092
- queryIDs.forEach(hash => (parsedRow.refCounts[hash] ??= 0));
1093
- const updateVersion = (row) => {
1094
- // IVM can output multiple versions of a row as it goes through its
1095
- // intermediate stages. Always update the version and contents;
1096
- // the last version will reflect the final state.
1097
- const { version, contents } = contentsAndVersion(row);
1098
- parsedRow.version = version;
1099
- parsedRow.contents = contents;
1100
- };
1101
- switch (type) {
1102
- case 'add':
1103
- updateVersion(row);
1104
- queryIDs.forEach(hash => parsedRow.refCounts[hash]++);
1105
- break;
1106
- case 'edit':
1107
- updateVersion(row);
1108
- // No update to refCounts.
1109
- break;
1110
- case 'remove':
1111
- queryIDs.forEach(hash => parsedRow.refCounts[hash]--);
1112
- break;
1113
- default:
1114
- unreachable(type);
1115
- }
1116
- if (rows.size % CURSOR_PAGE_SIZE === 0) {
1117
- await processBatch();
1118
- }
1119
- if (rows.size % TIME_SLICE_CHECK_SIZE === 0) {
1120
- if (timer.elapsedLap() > TIME_SLICE_MS) {
1121
- await timer.yieldProcess();
1122
- }
1123
- }
1124
- }
1125
- if (rows.size) {
1126
- await processBatch();
1127
- }
1128
- span.setAttribute('totalRows', total);
1129
- });
1130
- });
1131
- }
1132
- /**
1133
- * Advance to the current snapshot of the replica and apply / send
1134
- * changes.
1135
- *
1136
- * Must be called from within the #lock.
1137
- *
1138
- * Returns false if the advancement failed due to a schema change.
1139
- */
1140
- #advancePipelines(lc, cvr) {
1141
- return startAsyncSpan(tracer, 'vs.#advancePipelines', async () => {
1142
- assert(this.#pipelines.initialized(), 'pipelines must be initialized (advancePipelines');
1143
- const start = performance.now();
1144
- const timer = new TimeSliceTimer();
1145
- const { version, numChanges, changes } = this.#pipelines.advance(timer);
1146
- lc = lc.withContext('newVersion', version);
1147
- // Probably need a new updater type. CVRAdvancementUpdater?
1148
- const updater = new CVRQueryDrivenUpdater(this.#cvrStore, cvr, version, this.#pipelines.replicaVersion);
1149
- // Only poke clients that are at the cvr.version. New clients that
1150
- // are behind need to first be caught up when their initConnection
1151
- // message is processed (and #syncQueryPipelines is called).
1152
- const pokers = startPoke(this.#getClients(cvr.version), updater.updatedVersion(), this.#pipelines.currentSchemaVersions());
1153
- lc.debug?.(`applying ${numChanges} to advance to ${version}`);
1154
- const hashToIDs = createHashToIDs(cvr);
1155
- try {
1156
- await this.#processChanges(lc, await timer.start(), changes, updater, pokers, hashToIDs);
1157
- }
1158
- catch (e) {
1159
- if (e instanceof ResetPipelinesSignal) {
1160
- await pokers.cancel();
1161
- return e;
1162
- }
1163
- throw e;
1164
- }
1165
- // Commit the changes and update the CVR snapshot.
1166
- this.#cvr = await this.#flushUpdater(lc, updater);
1167
- const finalVersion = this.#cvr.version;
1168
- // Signal clients to commit.
1169
- await pokers.end(finalVersion);
1170
- const elapsed = performance.now() - start;
1171
- lc.info?.(`finished processing advancement of ${numChanges} changes (${elapsed} ms)`);
1172
- this.#transactionAdvanceTime.record(elapsed / 1000);
1173
- return 'success';
1174
- });
1175
- }
1176
- inspect(context, msg) {
1177
- return this.#runInLockForClient(context, msg, this.#handleInspect);
1178
- }
1179
- // oxlint-disable-next-line require-await
1180
- #handleInspect = async (lc, clientID, body, cvr) => {
1181
- const client = must(this.#clients.get(clientID));
1182
- return handleInspect(lc, body, cvr, client, this.#inspectorDelegate, this.id, this.#cvrStore, this.#config, this.#getHeaderOptions(this.#queryConfig.forwardCookies ?? false), this.userQueryURL, this.#authData?.raw);
1183
- };
1184
- stop() {
1185
- this.#lc.info?.('stopping view syncer');
1186
- this.#initialized.reject('shut down before initialization completed');
1187
- this.#stateChanges.cancel();
1188
- return this.#stopped.promise;
1189
- }
1190
- #cleanup(err) {
1191
- this.#stopTTLClockInterval();
1192
- this.#stopExpireTimer();
1193
- this.#pipelines.destroy();
1194
- for (const client of this.#clients.values()) {
1195
- if (err) {
1196
- client.fail(err);
1197
- }
1198
- else {
1199
- client.close(`closed clientGroupID=${this.id}`);
1200
- }
1307
+ span.setAttribute("totalRows", total);
1308
+ });
1309
+ });
1310
+ }
1311
+ /**
1312
+ * Advance to the current snapshot of the replica and apply / send
1313
+ * changes.
1314
+ *
1315
+ * Must be called from within the #lock.
1316
+ *
1317
+ * Returns false if the advancement failed due to a schema change.
1318
+ */
1319
+ #advancePipelines(lc, cvr) {
1320
+ return startAsyncSpan(tracer, "vs.#advancePipelines", async () => {
1321
+ assert(
1322
+ this.#pipelines.initialized(),
1323
+ "pipelines must be initialized (advancePipelines"
1324
+ );
1325
+ const start = performance.now();
1326
+ const timer = new TimeSliceTimer();
1327
+ const { version: version2, numChanges, changes } = this.#pipelines.advance(timer);
1328
+ lc = lc.withContext("newVersion", version2);
1329
+ const updater = new CVRQueryDrivenUpdater(
1330
+ this.#cvrStore,
1331
+ cvr,
1332
+ version2,
1333
+ this.#pipelines.replicaVersion
1334
+ );
1335
+ const pokers = startPoke(
1336
+ this.#getClients(cvr.version),
1337
+ updater.updatedVersion(),
1338
+ this.#pipelines.currentSchemaVersions()
1339
+ );
1340
+ lc.debug?.(`applying ${numChanges} to advance to ${version2}`);
1341
+ const hashToIDs = createHashToIDs(cvr);
1342
+ try {
1343
+ await this.#processChanges(
1344
+ lc,
1345
+ await timer.start(),
1346
+ changes,
1347
+ updater,
1348
+ pokers,
1349
+ hashToIDs
1350
+ );
1351
+ } catch (e) {
1352
+ if (e instanceof ResetPipelinesSignal) {
1353
+ await pokers.cancel();
1354
+ return e;
1201
1355
  }
1356
+ throw e;
1357
+ }
1358
+ this.#cvr = await this.#flushUpdater(lc, updater);
1359
+ const finalVersion = this.#cvr.version;
1360
+ await pokers.end(finalVersion);
1361
+ const elapsed = performance.now() - start;
1362
+ lc.info?.(
1363
+ `finished processing advancement of ${numChanges} changes (${elapsed} ms)`
1364
+ );
1365
+ this.#transactionAdvanceTime.record(elapsed / 1e3);
1366
+ return "success";
1367
+ });
1368
+ }
1369
+ inspect(context, msg) {
1370
+ return this.#runInLockForClient(context, msg, this.#handleInspect);
1371
+ }
1372
+ // oxlint-disable-next-line require-await
1373
+ #handleInspect = async (lc, clientID, body, cvr) => {
1374
+ const client = must(this.#clients.get(clientID));
1375
+ return handleInspect(
1376
+ lc,
1377
+ body,
1378
+ cvr,
1379
+ client,
1380
+ this.#inspectorDelegate,
1381
+ this.id,
1382
+ this.#cvrStore,
1383
+ this.#config,
1384
+ this.#getHeaderOptions(this.#queryConfig.forwardCookies ?? false),
1385
+ this.userQueryURL,
1386
+ this.#authData
1387
+ );
1388
+ };
1389
+ stop() {
1390
+ this.#lc.info?.("stopping view syncer");
1391
+ this.#initialized.reject("shut down before initialization completed");
1392
+ this.#stateChanges.cancel();
1393
+ return this.#stopped.promise;
1394
+ }
1395
+ #cleanup(err) {
1396
+ this.#stopTTLClockInterval();
1397
+ this.#stopExpireTimer();
1398
+ this.#pipelines.destroy();
1399
+ for (const client of this.#clients.values()) {
1400
+ if (err) {
1401
+ client.fail(err);
1402
+ } else {
1403
+ client.close(`closed clientGroupID=${this.id}`);
1404
+ }
1202
1405
  }
1203
- /**
1204
- * Test helper: Manually mark initialization as complete.
1205
- * This should only be used in tests that don't call initConnection().
1206
- */
1207
- markInitialized() {
1208
- this.#initialized.resolve('initialized');
1209
- }
1406
+ }
1407
+ /**
1408
+ * Test helper: Manually mark initialization as complete.
1409
+ * This should only be used in tests that don't call initConnection().
1410
+ */
1411
+ markInitialized() {
1412
+ this.#initialized.resolve("initialized");
1413
+ }
1210
1414
  }
1211
- // Update CVR after every 10000 rows.
1212
- const CURSOR_PAGE_SIZE = 10000;
1213
- // Check the elapsed time every 100 rows.
1415
+ const CURSOR_PAGE_SIZE = 1e4;
1214
1416
  const TIME_SLICE_CHECK_SIZE = 100;
1215
- // Yield the process after churning for > 500ms.
1216
1417
  const TIME_SLICE_MS = 500;
1217
1418
  function createHashToIDs(cvr) {
1218
- const hashToIDs = new Map();
1219
- for (const { id, transformationHash } of Object.values(cvr.queries)) {
1220
- if (!transformationHash) {
1221
- continue;
1222
- }
1223
- if (hashToIDs.has(transformationHash)) {
1224
- must(hashToIDs.get(transformationHash)).push(id);
1225
- }
1226
- else {
1227
- hashToIDs.set(transformationHash, [id]);
1228
- }
1419
+ const hashToIDs = /* @__PURE__ */ new Map();
1420
+ for (const { id, transformationHash } of Object.values(cvr.queries)) {
1421
+ if (!transformationHash) {
1422
+ continue;
1423
+ }
1424
+ if (hashToIDs.has(transformationHash)) {
1425
+ must(hashToIDs.get(transformationHash)).push(id);
1426
+ } else {
1427
+ hashToIDs.set(transformationHash, [id]);
1229
1428
  }
1230
- return hashToIDs;
1429
+ }
1430
+ return hashToIDs;
1231
1431
  }
1232
- // A global Lock acts as a queue to run a single IVM time slice per iteration
1233
- // of the node event loop, thus bounding I/O delay to the duration of a single
1234
- // time slice.
1235
- //
1236
- // Refresher:
1237
- // https://nodejs.org/en/learn/asynchronous-work/event-loop-timers-and-nexttick#phases-overview
1238
- //
1239
- // Note that recursive use of setImmediate() (i.e. calling setImmediate() from
1240
- // within a setImmediate() callback), results in enqueuing the latter
1241
- // callback in the *next* event loop iteration, as documented in:
1242
- // https://nodejs.org/api/timers.html#setimmediatecallback-args
1243
- //
1244
- // This effectively achieves the desired one-per-event-loop-iteration behavior.
1245
1432
  const timeSliceQueue = new Lock();
1246
1433
  function yieldProcess() {
1247
- return timeSliceQueue.withLock(() => new Promise(setImmediate));
1434
+ return timeSliceQueue.withLock(() => new Promise(setImmediate));
1248
1435
  }
1249
1436
  function contentsAndVersion(row) {
1250
- const { [ZERO_VERSION_COLUMN_NAME]: version, ...contents } = row;
1251
- if (typeof version !== 'string' || version.length === 0) {
1252
- throw new Error(`Invalid _0_version in ${stringify(row)}`);
1253
- }
1254
- return { contents, version };
1437
+ const { [ZERO_VERSION_COLUMN_NAME]: version2, ...contents } = row;
1438
+ if (typeof version2 !== "string" || version2.length === 0) {
1439
+ throw new Error(`Invalid _0_version in ${stringify(row)}`);
1440
+ }
1441
+ return { contents, version: version2 };
1255
1442
  }
1256
- const NEW_CVR_VERSION = { stateVersion: '00' };
1443
+ const NEW_CVR_VERSION = { stateVersion: "00" };
1257
1444
  function checkClientAndCVRVersions(client, cvr) {
1258
- if (cmpVersions(cvr, NEW_CVR_VERSION) === 0 &&
1259
- cmpVersions(client, NEW_CVR_VERSION) > 0) {
1260
- // CVR is empty but client is not.
1261
- throw new ProtocolError({
1262
- kind: ErrorKind.ClientNotFound,
1263
- message: 'Client not found',
1264
- origin: ErrorOrigin.ZeroCache,
1265
- });
1445
+ if (cmpVersions(cvr, NEW_CVR_VERSION) === 0 && cmpVersions(client, NEW_CVR_VERSION) > 0) {
1446
+ throw new ProtocolErrorWithLevel({
1447
+ kind: ClientNotFound,
1448
+ message: "Client not found",
1449
+ origin: ZeroCache
1450
+ });
1451
+ }
1452
+ if (cmpVersions(client, cvr) > 0) {
1453
+ throw new ProtocolError({
1454
+ kind: InvalidConnectionRequestBaseCookie,
1455
+ message: `CVR is at version ${versionString(cvr)}`,
1456
+ origin: ZeroCache
1457
+ });
1458
+ }
1459
+ }
1460
+ function pickToken(lc, previousToken, newToken) {
1461
+ if (previousToken === void 0) {
1462
+ lc.debug?.(`No previous token, using new token`);
1463
+ return newToken;
1464
+ }
1465
+ if (newToken) {
1466
+ if (previousToken.decoded.sub !== newToken.decoded.sub) {
1467
+ throw new ProtocolError({
1468
+ kind: Unauthorized,
1469
+ message: "The user id in the new token does not match the previous token. Client groups are pinned to a single user.",
1470
+ origin: ZeroCache
1471
+ });
1266
1472
  }
1267
- if (cmpVersions(client, cvr) > 0) {
1268
- // Client is ahead of a non-empty CVR.
1269
- throw new ProtocolError({
1270
- kind: ErrorKind.InvalidConnectionRequestBaseCookie,
1271
- message: `CVR is at version ${versionString(cvr)}`,
1272
- origin: ErrorOrigin.ZeroCache,
1273
- });
1473
+ if (previousToken.decoded.iat === void 0) {
1474
+ lc.debug?.(`No issued at time for the existing token, using new token`);
1475
+ return newToken;
1274
1476
  }
1275
- }
1276
- export function pickToken(lc, previousToken, newToken) {
1277
- if (previousToken === undefined) {
1278
- lc.debug?.(`No previous token, using new token`);
1279
- return newToken;
1477
+ if (newToken.decoded.iat === void 0) {
1478
+ throw new ProtocolError({
1479
+ kind: Unauthorized,
1480
+ message: "The new token does not have an issued at time but the prior token does. Tokens for a client group must either all have issued at times or all not have issued at times",
1481
+ origin: ZeroCache
1482
+ });
1280
1483
  }
1281
- if (newToken) {
1282
- if (previousToken.decoded.sub !== newToken.decoded.sub) {
1283
- throw new ProtocolError({
1284
- kind: ErrorKind.Unauthorized,
1285
- message: 'The user id in the new token does not match the previous token. Client groups are pinned to a single user.',
1286
- origin: ErrorOrigin.ZeroCache,
1287
- });
1288
- }
1289
- if (previousToken.decoded.iat === undefined) {
1290
- lc.debug?.(`No issued at time for the existing token, using new token`);
1291
- // No issued at time for the existing token? We take the most recently received token.
1292
- return newToken;
1293
- }
1294
- if (newToken.decoded.iat === undefined) {
1295
- throw new ProtocolError({
1296
- kind: ErrorKind.Unauthorized,
1297
- message: 'The new token does not have an issued at time but the prior token does. Tokens for a client group must either all have issued at times or all not have issued at times',
1298
- origin: ErrorOrigin.ZeroCache,
1299
- });
1300
- }
1301
- // The new token is newer, so we take it.
1302
- if (previousToken.decoded.iat < newToken.decoded.iat) {
1303
- lc.debug?.(`New token is newer, using it`);
1304
- return newToken;
1305
- }
1306
- // if the new token is older or the same, we keep the existing token.
1307
- lc.debug?.(`New token is older or the same, using existing token`);
1308
- return previousToken;
1484
+ if (previousToken.decoded.iat < newToken.decoded.iat) {
1485
+ lc.debug?.(`New token is newer, using it`);
1486
+ return newToken;
1309
1487
  }
1310
- // previousToken !== undefined but newToken is undefined
1311
- throw new ProtocolError({
1312
- kind: ErrorKind.Unauthorized,
1313
- message: 'No token provided. An unauthenticated client cannot connect to an authenticated client group.',
1314
- origin: ErrorOrigin.ZeroCache,
1315
- });
1488
+ lc.debug?.(`New token is older or the same, using existing token`);
1489
+ return previousToken;
1490
+ }
1491
+ throw new ProtocolError({
1492
+ kind: Unauthorized,
1493
+ message: "No token provided. An unauthenticated client cannot connect to an authenticated client group.",
1494
+ origin: ZeroCache
1495
+ });
1316
1496
  }
1317
- /**
1318
- * A query must be expired for all clients in order to be considered
1319
- * expired.
1320
- */
1321
1497
  function expired(ttlClock, q) {
1322
- if (q.type === 'internal') {
1323
- return false;
1498
+ if (q.type === "internal") {
1499
+ return false;
1500
+ }
1501
+ for (const clientState of Object.values(q.clientState)) {
1502
+ const { ttl, inactivatedAt } = clientState;
1503
+ if (inactivatedAt === void 0) {
1504
+ return false;
1324
1505
  }
1325
- for (const clientState of Object.values(q.clientState)) {
1326
- const { ttl, inactivatedAt } = clientState;
1327
- if (inactivatedAt === undefined) {
1328
- return false;
1329
- }
1330
- const clampedTTL = clampTTL(ttl);
1331
- if (ttlClockAsNumber(inactivatedAt) + clampedTTL >
1332
- ttlClockAsNumber(ttlClock)) {
1333
- return false;
1334
- }
1506
+ const clampedTTL = clampTTL(ttl);
1507
+ if (ttlClockAsNumber(inactivatedAt) + clampedTTL > ttlClockAsNumber(ttlClock)) {
1508
+ return false;
1335
1509
  }
1336
- return true;
1510
+ }
1511
+ return true;
1337
1512
  }
1338
1513
  function hasExpiredQueries(cvr) {
1339
- const { ttlClock } = cvr;
1340
- for (const q of Object.values(cvr.queries)) {
1341
- if (expired(ttlClock, q)) {
1342
- return true;
1343
- }
1514
+ const { ttlClock } = cvr;
1515
+ for (const q of Object.values(cvr.queries)) {
1516
+ if (expired(ttlClock, q)) {
1517
+ return true;
1344
1518
  }
1345
- return false;
1519
+ }
1520
+ return false;
1346
1521
  }
1347
- export class TimeSliceTimer {
1348
- #total = 0;
1349
- #start = 0;
1350
- async start() {
1351
- // yield at the very beginning so that the first time slice
1352
- // is properly processed by the time-slice queue.
1353
- await yieldProcess();
1354
- return this.startWithoutYielding();
1355
- }
1356
- startWithoutYielding() {
1357
- this.#total = 0;
1358
- this.#startLap();
1359
- return this;
1360
- }
1361
- async yieldProcess() {
1362
- this.#stopLap();
1363
- await yieldProcess();
1364
- this.#startLap();
1365
- }
1366
- #startLap() {
1367
- assert(this.#start === 0, 'already running');
1368
- this.#start = performance.now();
1369
- }
1370
- elapsedLap() {
1371
- assert(this.#start !== 0, 'not running');
1372
- return performance.now() - this.#start;
1373
- }
1374
- #stopLap() {
1375
- assert(this.#start !== 0, 'not running');
1376
- this.#total += performance.now() - this.#start;
1377
- this.#start = 0;
1378
- }
1379
- /** @returns the total elapsed time */
1380
- stop() {
1381
- this.#stopLap();
1382
- return this.#total;
1383
- }
1384
- /**
1385
- * @returns the elapsed time. This can be called while the Timer is running
1386
- * or after it has been stopped.
1387
- */
1388
- totalElapsed() {
1389
- return this.#start === 0
1390
- ? this.#total
1391
- : this.#total + performance.now() - this.#start;
1392
- }
1522
+ class TimeSliceTimer {
1523
+ #total = 0;
1524
+ #start = 0;
1525
+ async start() {
1526
+ await yieldProcess();
1527
+ return this.startWithoutYielding();
1528
+ }
1529
+ startWithoutYielding() {
1530
+ this.#total = 0;
1531
+ this.#startLap();
1532
+ return this;
1533
+ }
1534
+ async yieldProcess() {
1535
+ this.#stopLap();
1536
+ await yieldProcess();
1537
+ this.#startLap();
1538
+ }
1539
+ #startLap() {
1540
+ assert(this.#start === 0, "already running");
1541
+ this.#start = performance.now();
1542
+ }
1543
+ elapsedLap() {
1544
+ assert(this.#start !== 0, "not running");
1545
+ return performance.now() - this.#start;
1546
+ }
1547
+ #stopLap() {
1548
+ assert(this.#start !== 0, "not running");
1549
+ this.#total += performance.now() - this.#start;
1550
+ this.#start = 0;
1551
+ }
1552
+ /** @returns the total elapsed time */
1553
+ stop() {
1554
+ this.#stopLap();
1555
+ return this.#total;
1556
+ }
1557
+ /**
1558
+ * @returns the elapsed time. This can be called while the Timer is running
1559
+ * or after it has been stopped.
1560
+ */
1561
+ totalElapsed() {
1562
+ return this.#start === 0 ? this.#total : this.#total + performance.now() - this.#start;
1563
+ }
1393
1564
  }
1394
- //# sourceMappingURL=view-syncer.js.map
1565
+ export {
1566
+ TTL_CLOCK_INTERVAL,
1567
+ TTL_TIMER_HYSTERESIS,
1568
+ TimeSliceTimer,
1569
+ ViewSyncerService,
1570
+ pickToken
1571
+ };
1572
+ //# sourceMappingURL=view-syncer.js.map