@rocicorp/zero 1.10.0-canary.23 → 1.10.0-canary.24
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/out/analyze-query/src/bin-analyze.js +8 -7
- package/out/analyze-query/src/bin-analyze.js.map +1 -1
- package/out/replicache/src/btree/node.d.ts.map +1 -1
- package/out/replicache/src/btree/node.js +3 -6
- package/out/replicache/src/btree/node.js.map +1 -1
- package/out/replicache/src/dag/gc.d.ts.map +1 -1
- package/out/replicache/src/dag/gc.js +6 -10
- package/out/replicache/src/dag/gc.js.map +1 -1
- package/out/replicache/src/kv/sqlite-store.d.ts.map +1 -1
- package/out/replicache/src/kv/sqlite-store.js +24 -2
- package/out/replicache/src/kv/sqlite-store.js.map +1 -1
- package/out/replicache/src/persist/persist.js +1 -1
- package/out/shared/src/arrays.d.ts +5 -0
- package/out/shared/src/arrays.d.ts.map +1 -1
- package/out/shared/src/arrays.js +8 -10
- package/out/shared/src/arrays.js.map +1 -1
- package/out/shared/src/map.d.ts +19 -2
- package/out/shared/src/map.d.ts.map +1 -1
- package/out/shared/src/map.js +18 -4
- package/out/shared/src/map.js.map +1 -1
- package/out/z2s/src/compiler.js +1 -1
- package/out/z2s/src/sql.d.ts.map +1 -1
- package/out/z2s/src/sql.js +2 -2
- package/out/z2s/src/sql.js.map +1 -1
- package/out/zero/package.js +1 -1
- package/out/zero/package.js.map +1 -1
- package/out/zero-cache/src/auth/write-authorizer.d.ts.map +1 -1
- package/out/zero-cache/src/auth/write-authorizer.js +1 -0
- package/out/zero-cache/src/auth/write-authorizer.js.map +1 -1
- package/out/zero-cache/src/config/zero-config.d.ts +15 -0
- package/out/zero-cache/src/config/zero-config.d.ts.map +1 -1
- package/out/zero-cache/src/config/zero-config.js +35 -0
- package/out/zero-cache/src/config/zero-config.js.map +1 -1
- package/out/zero-cache/src/db/lite-tables.d.ts.map +1 -1
- package/out/zero-cache/src/db/lite-tables.js +3 -4
- package/out/zero-cache/src/db/lite-tables.js.map +1 -1
- package/out/zero-cache/src/observability/metrics.d.ts.map +1 -1
- package/out/zero-cache/src/observability/metrics.js +2 -7
- package/out/zero-cache/src/observability/metrics.js.map +1 -1
- package/out/zero-cache/src/server/inspector-delegate.d.ts.map +1 -1
- package/out/zero-cache/src/server/inspector-delegate.js +2 -8
- package/out/zero-cache/src/server/inspector-delegate.js.map +1 -1
- package/out/zero-cache/src/server/syncer.d.ts.map +1 -1
- package/out/zero-cache/src/server/syncer.js +3 -1
- package/out/zero-cache/src/server/syncer.js.map +1 -1
- package/out/zero-cache/src/services/analyze.d.ts.map +1 -1
- package/out/zero-cache/src/services/analyze.js +8 -7
- package/out/zero-cache/src/services/analyze.js.map +1 -1
- package/out/zero-cache/src/services/mutagen/pusher.d.ts +32 -32
- package/out/zero-cache/src/services/mutagen/pusher.d.ts.map +1 -1
- package/out/zero-cache/src/services/mutagen/pusher.js +3 -5
- package/out/zero-cache/src/services/mutagen/pusher.js.map +1 -1
- package/out/zero-cache/src/services/view-syncer/pipeline-driver.d.ts.map +1 -1
- package/out/zero-cache/src/services/view-syncer/pipeline-driver.js +15 -9
- package/out/zero-cache/src/services/view-syncer/pipeline-driver.js.map +1 -1
- package/out/zero-cache/src/services/view-syncer/query-covering.d.ts.map +1 -1
- package/out/zero-cache/src/services/view-syncer/query-covering.js +2 -6
- package/out/zero-cache/src/services/view-syncer/query-covering.js.map +1 -1
- package/out/zero-cache/src/services/view-syncer/snapshot-row-cache.d.ts +95 -0
- package/out/zero-cache/src/services/view-syncer/snapshot-row-cache.d.ts.map +1 -0
- package/out/zero-cache/src/services/view-syncer/snapshot-row-cache.js +155 -0
- package/out/zero-cache/src/services/view-syncer/snapshot-row-cache.js.map +1 -0
- package/out/zero-cache/src/services/view-syncer/snapshotter.d.ts +38 -3
- package/out/zero-cache/src/services/view-syncer/snapshotter.d.ts.map +1 -1
- package/out/zero-cache/src/services/view-syncer/snapshotter.js +110 -27
- package/out/zero-cache/src/services/view-syncer/snapshotter.js.map +1 -1
- package/out/zero-cache/src/services/view-syncer/view-syncer.d.ts.map +1 -1
- package/out/zero-cache/src/services/view-syncer/view-syncer.js +4 -13
- package/out/zero-cache/src/services/view-syncer/view-syncer.js.map +1 -1
- package/out/zero-cache/src/types/row-key.d.ts.map +1 -1
- package/out/zero-cache/src/types/row-key.js +5 -5
- package/out/zero-cache/src/types/row-key.js.map +1 -1
- package/out/zero-client/src/client/query-manager.d.ts.map +1 -1
- package/out/zero-client/src/client/query-manager.js +2 -5
- package/out/zero-client/src/client/query-manager.js.map +1 -1
- package/out/zero-client/src/client/version.js +1 -1
- package/out/zero-protocol/src/analyze-query-result.d.ts +5 -5
- package/out/zero-protocol/src/analyze-query-result.d.ts.map +1 -1
- package/out/zero-protocol/src/analyze-query-result.js +1 -1
- package/out/zero-protocol/src/analyze-query-result.js.map +1 -1
- package/out/zero-protocol/src/ast.d.ts.map +1 -1
- package/out/zero-protocol/src/ast.js +13 -14
- package/out/zero-protocol/src/ast.js.map +1 -1
- package/out/zero-protocol/src/down.d.ts +2 -2
- package/out/zero-protocol/src/inspect-down.d.ts +6 -6
- package/out/zero-protocol/src/protocol-version.d.ts.map +1 -1
- package/out/zero-protocol/src/protocol-version.js.map +1 -1
- package/out/zero-protocol/src/query-hash.d.ts.map +1 -1
- package/out/zero-protocol/src/query-hash.js +2 -5
- package/out/zero-protocol/src/query-hash.js.map +1 -1
- package/out/zql/src/builder/builder.d.ts +19 -0
- package/out/zql/src/builder/builder.d.ts.map +1 -1
- package/out/zql/src/builder/builder.js +28 -11
- package/out/zql/src/builder/builder.js.map +1 -1
- package/out/zql/src/builder/correlated-predicate-pushdown.d.ts +43 -0
- package/out/zql/src/builder/correlated-predicate-pushdown.d.ts.map +1 -0
- package/out/zql/src/builder/correlated-predicate-pushdown.js +161 -0
- package/out/zql/src/builder/correlated-predicate-pushdown.js.map +1 -0
- package/out/zql/src/ivm/connection-index.d.ts +68 -0
- package/out/zql/src/ivm/connection-index.d.ts.map +1 -0
- package/out/zql/src/ivm/connection-index.js +149 -0
- package/out/zql/src/ivm/connection-index.js.map +1 -0
- package/out/zql/src/ivm/exists.js +1 -1
- package/out/zql/src/ivm/filter-operators.d.ts +3 -2
- package/out/zql/src/ivm/filter-operators.d.ts.map +1 -1
- package/out/zql/src/ivm/filter-operators.js +19 -4
- package/out/zql/src/ivm/filter-operators.js.map +1 -1
- package/out/zql/src/ivm/memory-source.d.ts.map +1 -1
- package/out/zql/src/ivm/memory-source.js +17 -4
- package/out/zql/src/ivm/memory-source.js.map +1 -1
- package/out/zql/src/ivm/operator.d.ts +40 -0
- package/out/zql/src/ivm/operator.d.ts.map +1 -1
- package/out/zql/src/ivm/operator.js.map +1 -1
- package/out/zql/src/planner/planner-builder.d.ts +12 -3
- package/out/zql/src/planner/planner-builder.d.ts.map +1 -1
- package/out/zql/src/planner/planner-builder.js +40 -20
- package/out/zql/src/planner/planner-builder.js.map +1 -1
- package/out/zql/src/planner/planner-connection.d.ts +28 -2
- package/out/zql/src/planner/planner-connection.d.ts.map +1 -1
- package/out/zql/src/planner/planner-connection.js +108 -8
- package/out/zql/src/planner/planner-connection.js.map +1 -1
- package/out/zql/src/planner/planner-debug.d.ts +1 -1
- package/out/zql/src/planner/planner-debug.d.ts.map +1 -1
- package/out/zql/src/planner/planner-debug.js +3 -8
- package/out/zql/src/planner/planner-debug.js.map +1 -1
- package/out/zql/src/planner/planner-fan-out.d.ts +1 -0
- package/out/zql/src/planner/planner-fan-out.d.ts.map +1 -1
- package/out/zql/src/planner/planner-fan-out.js +3 -0
- package/out/zql/src/planner/planner-fan-out.js.map +1 -1
- package/out/zql/src/planner/planner-filter.d.ts +59 -0
- package/out/zql/src/planner/planner-filter.d.ts.map +1 -0
- package/out/zql/src/planner/planner-filter.js +116 -0
- package/out/zql/src/planner/planner-filter.js.map +1 -0
- package/out/zql/src/planner/planner-graph.d.ts +2 -0
- package/out/zql/src/planner/planner-graph.d.ts.map +1 -1
- package/out/zql/src/planner/planner-graph.js +2 -0
- package/out/zql/src/planner/planner-graph.js.map +1 -1
- package/out/zql/src/planner/planner-join.d.ts +2 -0
- package/out/zql/src/planner/planner-join.d.ts.map +1 -1
- package/out/zql/src/planner/planner-join.js +7 -0
- package/out/zql/src/planner/planner-join.js.map +1 -1
- package/out/zql/src/planner/planner-node.d.ts +2 -1
- package/out/zql/src/planner/planner-node.d.ts.map +1 -1
- package/out/zql/src/planner/planner-node.js.map +1 -1
- package/out/zql/src/planner/planner-source.d.ts +2 -2
- package/out/zql/src/planner/planner-source.d.ts.map +1 -1
- package/out/zql/src/planner/planner-source.js +2 -2
- package/out/zql/src/planner/planner-source.js.map +1 -1
- package/out/zql/src/query/query-impl.d.ts.map +1 -1
- package/out/zql/src/query/query-impl.js +6 -23
- package/out/zql/src/query/query-impl.js.map +1 -1
- package/out/zql/src/query/query-transitions.d.ts.map +1 -1
- package/out/zql/src/query/query-transitions.js +2 -5
- package/out/zql/src/query/query-transitions.js.map +1 -1
- package/out/zql/src/query/runnable-query-impl.d.ts.map +1 -1
- package/out/zql/src/query/runnable-query-impl.js +2 -10
- package/out/zql/src/query/runnable-query-impl.js.map +1 -1
- package/out/zqlite/src/query-builder.d.ts +1 -1
- package/out/zqlite/src/query-builder.d.ts.map +1 -1
- package/out/zqlite/src/query-builder.js +2 -1
- package/out/zqlite/src/query-builder.js.map +1 -1
- package/out/zqlite/src/query-delegate.d.ts.map +1 -1
- package/out/zqlite/src/query-delegate.js +5 -6
- package/out/zqlite/src/query-delegate.js.map +1 -1
- package/out/zqlite/src/sqlite-cost-model.d.ts.map +1 -1
- package/out/zqlite/src/sqlite-cost-model.js +2 -30
- package/out/zqlite/src/sqlite-cost-model.js.map +1 -1
- package/out/zqlite/src/sqlite-stat-fanout.d.ts.map +1 -1
- package/out/zqlite/src/sqlite-stat-fanout.js +3 -5
- package/out/zqlite/src/sqlite-stat-fanout.js.map +1 -1
- package/out/zqlite/src/table-source.d.ts +14 -2
- package/out/zqlite/src/table-source.d.ts.map +1 -1
- package/out/zqlite/src/table-source.js +25 -12
- package/out/zqlite/src/table-source.js.map +1 -1
- package/package.json +1 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"row-key.d.ts","sourceRoot":"","sources":["../../../../../zero-cache/src/types/row-key.ts"],"names":[],"mappings":"AACA,OAAO,EAAY,KAAK,SAAS,EAAC,MAAM,oCAAoC,CAAC;
|
|
1
|
+
{"version":3,"file":"row-key.d.ts","sourceRoot":"","sources":["../../../../../zero-cache/src/types/row-key.ts"],"names":[],"mappings":"AACA,OAAO,EAAY,KAAK,SAAS,EAAC,MAAM,oCAAoC,CAAC;AAI7E,MAAM,MAAM,UAAU,GAAG;IAAC,QAAQ,CAAC,OAAO,EAAE,MAAM,CAAA;CAAC,CAAC;AACpD,MAAM,MAAM,UAAU,GAAG,QAAQ,CAAC,MAAM,CAAC,MAAM,EAAE,UAAU,CAAC,CAAC,CAAC;AAC9D,MAAM,MAAM,MAAM,GAAG,QAAQ,CAAC,MAAM,CAAC,MAAM,EAAE,SAAS,CAAC,CAAC,CAAC;AAEzD,MAAM,MAAM,KAAK,GAAG,QAAQ,CAAC;IAAC,MAAM,EAAE,MAAM,CAAC;IAAC,KAAK,EAAE,MAAM,CAAC;IAAC,MAAM,EAAE,MAAM,CAAA;CAAC,CAAC,CAAC;AAI9E,MAAM,MAAM,OAAO,GAAG,UAAU,CAAC;AACjC,MAAM,MAAM,QAAQ,GAAG,MAAM,CAAC;AAE9B;;;;;;GAMG;AACH,wBAAgB,kBAAkB,CAAC,CAAC,EAClC,MAAM,EAAE,QAAQ,CAAC,MAAM,CAAC,MAAM,EAAE,CAAC,CAAC,CAAC,GAClC,QAAQ,CAAC,MAAM,CAAC,MAAM,EAAE,CAAC,CAAC,CAAC,CAkB7B;AAED;;;GAGG;AACH,wBAAgB,YAAY,CAAC,GAAG,EAAE,MAAM,GAAG,MAAM,CAEhD;AAQD;;;;GAIG;AACH,wBAAgB,WAAW,CAAC,EAAE,EAAE,KAAK,GAAG,MAAM,CAE7C;AAQD;;;;;;;;;;;GAWG;AACH,wBAAgB,SAAS,CAAC,EAAE,EAAE,KAAK,GAAG,MAAM,CAE3C"}
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { assert } from "../../../shared/src/asserts.js";
|
|
2
|
+
import { getOrInsertComputed } from "../../../shared/src/map.js";
|
|
2
3
|
import "../../../shared/src/hash.js";
|
|
3
4
|
import { stringify } from "../../../shared/src/bigint-json.js";
|
|
4
5
|
//#region ../zero-cache/src/types/row-key.ts
|
|
@@ -34,15 +35,14 @@ var rowIDStrings = /* @__PURE__ */ new WeakMap();
|
|
|
34
35
|
* length.
|
|
35
36
|
*/
|
|
36
37
|
function rowIDString(id) {
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
38
|
+
return getOrInsertComputed(rowIDStrings, id, rowIDStringUncached);
|
|
39
|
+
}
|
|
40
|
+
function rowIDStringUncached(id) {
|
|
41
|
+
return stringify([
|
|
40
42
|
id.schema,
|
|
41
43
|
id.table,
|
|
42
44
|
...tuples(id.rowKey)
|
|
43
45
|
]);
|
|
44
|
-
rowIDStrings.set(id, val);
|
|
45
|
-
return val;
|
|
46
46
|
}
|
|
47
47
|
//#endregion
|
|
48
48
|
export { normalizedKeyOrder, rowIDString };
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"row-key.js","names":[],"sources":["../../../../../zero-cache/src/types/row-key.ts"],"sourcesContent":["import {assert} from '../../../shared/src/asserts.ts';\nimport {stringify, type JSONValue} from '../../../shared/src/bigint-json.ts';\nimport {h128} from '../../../shared/src/hash.ts';\n\nexport type ColumnType = {readonly typeOid: number};\nexport type RowKeyType = Readonly<Record<string, ColumnType>>;\nexport type RowKey = Readonly<Record<string, JSONValue>>;\n\nexport type RowID = Readonly<{schema: string; table: string; rowKey: RowKey}>;\n\n// Aliased for documentation purposes when dealing with full rows vs row keys.\n// The actual structure of the objects is the same.\nexport type RowType = RowKeyType;\nexport type RowValue = RowKey;\n\n/**\n * Returns the `RowKey` such that key iteration produces a sorted sequence. If the\n * keys are already sorted, the input is returned as is.\n *\n * Note that the value type is parameterized as `V` so that this method can be used\n * for both (pg) RowKeys and LiteRowKeys.\n */\nexport function normalizedKeyOrder<V>(\n rowKey: Readonly<Record<string, V>>,\n): Readonly<Record<string, V>> {\n let last = '';\n let empty = true;\n for (const col in rowKey) {\n empty = false;\n if (last > col) {\n const entries = Object.entries(rowKey).sort(([a], [b]) =>\n a < b ? -1 : a > b ? 1 : 0,\n );\n assert(entries.length > 0, 'empty row key');\n return Object.fromEntries(entries);\n }\n last = col;\n }\n assert(!empty, 'empty row key');\n // This case iterates over columns and avoids object allocations, which is\n // expected to be the common case (e.g. single column key).\n return rowKey;\n}\n\n/**\n * Returns a normalized string suitable for representing a row key in a form\n * that can be used as a Map key.\n */\nexport function rowKeyString(key: RowKey): string {\n return stringify(tuples(key));\n}\n\nfunction tuples(key: RowKey) {\n return Object.entries(normalizedKeyOrder(key)).flat();\n}\n\nconst rowIDStrings = new WeakMap<RowID, string>();\n\n/**\n * A normalized string representation of a {@link RowID} suitable to use\n * as a Map key. Use {@link rowIDHash} if you need string keys of bounded\n * length.\n */\nexport function rowIDString(id: RowID): string {\n
|
|
1
|
+
{"version":3,"file":"row-key.js","names":[],"sources":["../../../../../zero-cache/src/types/row-key.ts"],"sourcesContent":["import {assert} from '../../../shared/src/asserts.ts';\nimport {stringify, type JSONValue} from '../../../shared/src/bigint-json.ts';\nimport {h128} from '../../../shared/src/hash.ts';\nimport {getOrInsertComputed} from '../../../shared/src/map.ts';\n\nexport type ColumnType = {readonly typeOid: number};\nexport type RowKeyType = Readonly<Record<string, ColumnType>>;\nexport type RowKey = Readonly<Record<string, JSONValue>>;\n\nexport type RowID = Readonly<{schema: string; table: string; rowKey: RowKey}>;\n\n// Aliased for documentation purposes when dealing with full rows vs row keys.\n// The actual structure of the objects is the same.\nexport type RowType = RowKeyType;\nexport type RowValue = RowKey;\n\n/**\n * Returns the `RowKey` such that key iteration produces a sorted sequence. If the\n * keys are already sorted, the input is returned as is.\n *\n * Note that the value type is parameterized as `V` so that this method can be used\n * for both (pg) RowKeys and LiteRowKeys.\n */\nexport function normalizedKeyOrder<V>(\n rowKey: Readonly<Record<string, V>>,\n): Readonly<Record<string, V>> {\n let last = '';\n let empty = true;\n for (const col in rowKey) {\n empty = false;\n if (last > col) {\n const entries = Object.entries(rowKey).sort(([a], [b]) =>\n a < b ? -1 : a > b ? 1 : 0,\n );\n assert(entries.length > 0, 'empty row key');\n return Object.fromEntries(entries);\n }\n last = col;\n }\n assert(!empty, 'empty row key');\n // This case iterates over columns and avoids object allocations, which is\n // expected to be the common case (e.g. single column key).\n return rowKey;\n}\n\n/**\n * Returns a normalized string suitable for representing a row key in a form\n * that can be used as a Map key.\n */\nexport function rowKeyString(key: RowKey): string {\n return stringify(tuples(key));\n}\n\nfunction tuples(key: RowKey) {\n return Object.entries(normalizedKeyOrder(key)).flat();\n}\n\nconst rowIDStrings = new WeakMap<RowID, string>();\n\n/**\n * A normalized string representation of a {@link RowID} suitable to use\n * as a Map key. Use {@link rowIDHash} if you need string keys of bounded\n * length.\n */\nexport function rowIDString(id: RowID): string {\n return getOrInsertComputed(rowIDStrings, id, rowIDStringUncached);\n}\n\nfunction rowIDStringUncached(id: RowID): string {\n return stringify([id.schema, id.table, ...tuples(id.rowKey)]);\n}\n\nconst rowIDHashes = new WeakMap<RowID, string>();\n\n/**\n * A RowIDHash is a 128-bit column-order-agnostic hash of the schema, table name, and\n * column name / value tuples of a row key. It serves as a compact identifier for\n * a row in the database that:\n *\n * * is guaranteed to fit within the constraints of the CVR store (Durable Object\n * storage keys cannot exceed 2KiB)\n * * can be used to compactly encode (and lookup) the rows of query results for CVR\n * bookkeeping.\n *\n * The hash is encoded in `base36`, with the maximum 128-bit value being 25 characters long.\n */\nexport function rowIDHash(id: RowID): string {\n return getOrInsertComputed(rowIDHashes, id, rowIDHashUncached);\n}\n\nfunction rowIDHashUncached(id: RowID): string {\n return h128(rowIDString(id)).toString(36);\n}\n"],"mappings":";;;;;;;;;;;;AAuBA,SAAgB,mBACd,QAC6B;CAC7B,IAAI,OAAO;CACX,IAAI,QAAQ;CACZ,KAAK,MAAM,OAAO,QAAQ;EACxB,QAAQ;EACR,IAAI,OAAO,KAAK;GACd,MAAM,UAAU,OAAO,QAAQ,MAAM,EAAE,MAAM,CAAC,IAAI,CAAC,OACjD,IAAI,IAAI,KAAK,IAAI,IAAI,IAAI,CAC3B;GACA,OAAO,QAAQ,SAAS,GAAG,eAAe;GAC1C,OAAO,OAAO,YAAY,OAAO;EACnC;EACA,OAAO;CACT;CACA,OAAO,CAAC,OAAO,eAAe;CAG9B,OAAO;AACT;AAUA,SAAS,OAAO,KAAa;CAC3B,OAAO,OAAO,QAAQ,mBAAmB,GAAG,CAAC,EAAE,KAAK;AACtD;AAEA,IAAM,+BAAe,IAAI,QAAuB;;;;;;AAOhD,SAAgB,YAAY,IAAmB;CAC7C,OAAO,oBAAoB,cAAc,IAAI,mBAAmB;AAClE;AAEA,SAAS,oBAAoB,IAAmB;CAC9C,OAAO,UAAU;EAAC,GAAG;EAAQ,GAAG;EAAO,GAAG,OAAO,GAAG,MAAM;CAAC,CAAC;AAC9D"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"query-manager.d.ts","sourceRoot":"","sources":["../../../../../zero-client/src/client/query-manager.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAC,UAAU,EAAC,MAAM,kBAAkB,CAAC;AACjD,OAAO,KAAK,EAAC,cAAc,EAAC,MAAM,4CAA4C,CAAC;AAC/E,OAAO,KAAK,EAAC,QAAQ,EAAC,MAAM,qCAAqC,CAAC;
|
|
1
|
+
{"version":3,"file":"query-manager.d.ts","sourceRoot":"","sources":["../../../../../zero-client/src/client/query-manager.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAC,UAAU,EAAC,MAAM,kBAAkB,CAAC;AACjD,OAAO,KAAK,EAAC,cAAc,EAA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AAI,EAAE,IAAI,EAAC,EAAE,aAAa,EAC3B,GAAG,EAAE,GAAG,EACR,WAAW,CAAC,EAAE,WAAW,GACxB,MAAM,IAAI;IAMb,kBAAkB;IAClB,SAAS,CAAC,GAAG,EAAE,GAAG,EAAE,GAAG,EAAE,GAAG,EAAE,WAAW,CAAC,EAAE,WAAW,GAAG,MAAM,IAAI;IAsFpE,YAAY,CAAC,EAAC,IAAI,EAAE,IAAI,EAAC,EAAE,aAAa,EAAE,GAAG,EAAE,GAAG;IAMlD,kBAAkB;IAClB,YAAY,CAAC,GAAG,EAAE,GAAG,EAAE,GAAG,EAAE,GAAG;IAsC/B,UAAU;IAwCV;;OAEG;IACH,IAAI,OAAO,IAAI,YAAY,CAE1B;IAED,SAAS,CAAC,CAAC,SAAS,MAAM,eAAe,EACvC,MAAM,EAAE,CAAC,EACT,KAAK,EAAE,MAAM,EACb,GAAG,IAAI,EAAE,eAAe,CAAC,CAAC,CAAC,GAC1B,IAAI;IA2DP,eAAe,CAAC,OAAO,EAAE,MAAM,GAAG,oBAAoB,GAAG,SAAS;IAIlE;;OAEG;IACH,uBAAuB,IAAI,QAAQ,CAAC,MAAM,CAAC;CAG5C"}
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { assert, unreachable } from "../../../shared/src/asserts.js";
|
|
2
|
+
import { getOrInsertComputed } from "../../../shared/src/map.js";
|
|
2
3
|
import { must } from "../../../shared/src/must.js";
|
|
3
4
|
import { mapAST, normalizeAST } from "../../../zero-protocol/src/ast.js";
|
|
4
5
|
import { clientToServer, serverToClient } from "../../../zero-schema/src/name-mapper.js";
|
|
@@ -350,11 +351,7 @@ var QueryManager = class {
|
|
|
350
351
|
if (this.#slowMaterializeThreshold !== void 0 && value > this.#slowMaterializeThreshold) this.#lc.warn?.("Slow query materialization (including server/network)", queryID, ast, value);
|
|
351
352
|
else this.#lc.debug?.("Materialized query (including server/network)", queryID, ast, value);
|
|
352
353
|
}
|
|
353
|
-
|
|
354
|
-
if (!existing) {
|
|
355
|
-
existing = newPerQueryMetrics();
|
|
356
|
-
this.#queryMetrics.set(queryID, existing);
|
|
357
|
-
}
|
|
354
|
+
const existing = getOrInsertComputed(this.#queryMetrics, queryID, newPerQueryMetrics);
|
|
358
355
|
switch (metric) {
|
|
359
356
|
case "query-update-client":
|
|
360
357
|
existing["query-update-client"].add(value);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"query-manager.js","names":["#clientID","#clientToServer","#serverToClient","#send","#onFatalError","#queries","#recentQueriesMaxSize","#recentQueries","#gotQueries","#cachedQueries","#mutationTracker","#pendingQueryChanges","#queryChangeThrottleMs","#lc","#metrics","#queryMetrics","#slowMaterializeThreshold","#pendingRemovals","#awaitingPersistedGotDiff","#fireGotCallbacks","#gotQueriesAuthoritative","#queryEvictedCallback","#closedError","#add","#queueQueryChange","#updateEntry","#remove","#scheduleBatch","#batchTimer"],"sources":["../../../../../zero-client/src/client/query-manager.ts"],"sourcesContent":["import type {LogContext} from '@rocicorp/logger';\nimport type {ReplicacheImpl} from '../../../replicache/src/replicache-impl.ts';\nimport type {ClientID} from '../../../replicache/src/sync/ids.ts';\nimport {assert, unreachable} from '../../../shared/src/asserts.ts';\nimport type {ReadonlyJSONValue} from '../../../shared/src/json.ts';\nimport {must} from '../../../shared/src/must.ts';\nimport {difference} from '../../../shared/src/set-utils.ts';\nimport {TDigest} from '../../../shared/src/tdigest.ts';\nimport {\n mapAST,\n normalizeAST,\n type AST,\n} from '../../../zero-protocol/src/ast.ts';\nimport type {ChangeDesiredQueriesMessage} from '../../../zero-protocol/src/change-desired-queries.ts';\nimport type {ErroredQuery} from '../../../zero-protocol/src/custom-queries.ts';\nimport {ErrorKind} from '../../../zero-protocol/src/error-kind.ts';\nimport {ErrorOrigin} from '../../../zero-protocol/src/error-origin.ts';\nimport {ErrorReason} from '../../../zero-protocol/src/error-reason.ts';\nimport {ProtocolError} from '../../../zero-protocol/src/error.ts';\nimport type {UpQueriesPatchOp} from '../../../zero-protocol/src/queries-patch.ts';\nimport {\n hashOfAST,\n hashOfNameAndArgs,\n} from '../../../zero-protocol/src/query-hash.ts';\nimport {\n clientToServer,\n serverToClient,\n type NameMapper,\n} from '../../../zero-schema/src/name-mapper.ts';\nimport type {TableSchema} from '../../../zero-schema/src/table-schema.ts';\nimport type {ClientMetricMap} from '../../../zql/src/query/metrics-delegate.ts';\nimport type {CustomQueryID} from '../../../zql/src/query/named.ts';\nimport type {GotCallback} from '../../../zql/src/query/query-delegate.ts';\nimport {clampTTL, compareTTL, type TTL} from '../../../zql/src/query/ttl.ts';\nimport type {ClientErrorKind} from './client-error-kind.ts';\nimport type {ClientError} from './error.ts';\nimport {type ZeroError} from './error.ts';\nimport type {InspectorDelegate} from './inspector/inspector.ts';\nimport type {QueryClientMetrics} from './inspector/lazy-inspector.ts';\nimport {desiredQueriesPrefixForClient, GOT_QUERIES_KEY_PREFIX} from './keys.ts';\nimport type {MutationTracker} from './mutation-tracker.ts';\nimport type {ReadTransaction} from './replicache-types.ts';\n\ntype QueryHash = string;\n\ntype Entry = {\n // We keep track of the AST so we can use it in the inspector.\n normalized: AST;\n name: string | undefined;\n args: readonly ReadonlyJSONValue[] | undefined;\n count: number;\n gotCallbacks: GotCallback[];\n ttl: TTL;\n};\n\n// A thrown value, boxed so that `throw undefined` is still distinguishable\n// from \"nothing thrown\".\ntype ThrownBy = {readonly error: unknown};\n\ntype ClientMetric = {\n [K in keyof ClientMetricMap]: TDigest;\n};\n\ntype PerQueryClientMetric = {\n 'query-materialization-client': number | undefined;\n 'query-materialization-end-to-end': number | undefined;\n 'query-update-client': TDigest;\n};\n\n/**\n * Tracks what queries the client is currently subscribed to on the server.\n * Sends `changeDesiredQueries` message to server when this changes.\n * Deduplicates requests so that we only listen to a given unique query once.\n */\nexport class QueryManager implements InspectorDelegate {\n readonly #clientID: ClientID;\n readonly #clientToServer: NameMapper;\n readonly #serverToClient: NameMapper;\n readonly #send: (change: ChangeDesiredQueriesMessage) => void;\n readonly #onFatalError: (error: ZeroError) => void;\n readonly #queries: Map<QueryHash, Entry> = new Map();\n readonly #recentQueriesMaxSize: number;\n readonly #recentQueries: Set<string> = new Set();\n readonly #gotQueries: Set<string> = new Set();\n // Whether `#gotQueries` can be trusted. The persisted set loaded from\n // IndexedDB may be stale (a query 'got' in a previous session can be evicted\n // server-side); see `markGotQueriesAuthoritative`.\n #gotQueriesAuthoritative = false;\n // The got keys whose result the store holds from a previous connection: the\n // set persisted by a previous session, and on disconnect everything the\n // connection just torn down had confirmed. Until the got set is\n // authoritative, a registration reports these as 'cached'. Keys added by a\n // live diff are not in it; see the watch below.\n readonly #cachedQueries: Set<string> = new Set();\n // Whether the got-queries watch has yet to deliver its first diff, the\n // persisted set. Cleared before that diff is processed, so a throwing\n // callback cannot leave it set.\n #awaitingPersistedGotDiff = true;\n readonly #mutationTracker: MutationTracker;\n readonly #pendingQueryChanges: UpQueriesPatchOp[] = [];\n readonly #queryChangeThrottleMs: number;\n #pendingRemovals: Array<() => void> = [];\n #batchTimer: ReturnType<typeof setTimeout> | undefined;\n readonly #lc: LogContext;\n readonly #metrics: ClientMetric = newMetrics();\n readonly #queryMetrics: Map<string, PerQueryClientMetric> = new Map();\n readonly #slowMaterializeThreshold: number;\n #closedError: ZeroError | undefined;\n #queryEvictedCallback:\n | ((hash: string, ast: AST, metrics: QueryClientMetrics) => void)\n | undefined;\n\n constructor(\n lc: LogContext,\n mutationTracker: MutationTracker,\n clientID: ClientID,\n tables: Record<string, TableSchema>,\n send: (change: ChangeDesiredQueriesMessage) => void,\n experimentalWatch: ReplicacheImpl['experimentalWatch'],\n recentQueriesMaxSize: number,\n queryChangeThrottleMs: number,\n slowMaterializeThreshold: number,\n onFatalError: (error: ZeroError) => void,\n ) {\n this.#lc = lc.withContext('QueryManager');\n this.#clientID = clientID;\n this.#clientToServer = clientToServer(tables);\n this.#serverToClient = serverToClient(tables);\n this.#recentQueriesMaxSize = recentQueriesMaxSize;\n this.#send = send;\n this.#mutationTracker = mutationTracker;\n this.#queryChangeThrottleMs = queryChangeThrottleMs;\n this.#slowMaterializeThreshold = slowMaterializeThreshold;\n this.#onFatalError = onFatalError;\n this.#mutationTracker.onAllMutationsApplied(() => {\n if (this.#pendingRemovals.length === 0) {\n return;\n }\n const pendingRemovals = this.#pendingRemovals;\n this.#pendingRemovals = [];\n for (const removal of pendingRemovals) {\n removal();\n }\n });\n\n // The first diff is the got set persisted by a previous session, the only\n // state the watch may report as 'cached'. Every later diff is live: this\n // tab's own poke, whose keys are confirmations on this connection and are\n // reported as got once the poke has been applied (see\n // `markGotQueriesAuthoritative`), or another tab's state arriving via\n // replicache refresh. A live diff can therefore only revoke a cached\n // claim (a deleted key), never grant one.\n experimentalWatch(\n diff => {\n const persisted = this.#awaitingPersistedGotDiff;\n this.#awaitingPersistedGotDiff = false;\n // A throwing callback must not leave the rest of the diff unapplied,\n // or later keys would never enter the got set. The first error is\n // rethrown once the sets are consistent.\n let thrown: ThrownBy | undefined;\n const fire = (queryHash: string, got: boolean | 'cached') => {\n const e = this.#fireGotCallbacks(queryHash, got);\n thrown ??= e;\n };\n for (const diffOp of diff) {\n const queryHash = diffOp.key.substring(GOT_QUERIES_KEY_PREFIX.length);\n switch (diffOp.op) {\n case 'add':\n this.#gotQueries.add(queryHash);\n if (this.#gotQueriesAuthoritative) {\n fire(queryHash, true);\n } else if (persisted) {\n this.#cachedQueries.add(queryHash);\n fire(queryHash, 'cached');\n }\n break;\n case 'del':\n this.#gotQueries.delete(queryHash);\n this.#cachedQueries.delete(queryHash);\n fire(queryHash, false);\n break;\n }\n }\n if (thrown) {\n throw thrown.error;\n }\n },\n {\n prefix: GOT_QUERIES_KEY_PREFIX,\n initialValuesInFirstDiff: true,\n },\n );\n }\n\n getAST(queryID: string): AST | undefined {\n const ast = this.#queries.get(queryID)?.normalized;\n return ast && mapAST(ast, this.#serverToClient);\n }\n\n setQueryEvictedCallback(\n cb: (hash: string, ast: AST, metrics: QueryClientMetrics) => void,\n ): void {\n this.#queryEvictedCallback = cb;\n }\n\n mapClientASTToServer(ast: AST): AST {\n return mapAST(ast, this.#clientToServer);\n }\n\n /**\n * Notifies every subscriber of the query. A throwing subscriber does not\n * keep the others from being notified; the first error is returned so the\n * caller can rethrow it once its own bookkeeping is consistent.\n */\n #fireGotCallbacks(\n queryHash: string,\n got: boolean | 'cached',\n ): ThrownBy | undefined {\n const entry = this.#queries.get(queryHash);\n if (!entry) {\n return undefined;\n }\n let thrown: ThrownBy | undefined;\n // A subscriber may unregister during dispatch (a run() waiter destroys its\n // view on the notification it was waiting for), so iterate a snapshot.\n for (const gotCallback of [...entry.gotCallbacks]) {\n try {\n gotCallback(got);\n } catch (error) {\n thrown ??= {error};\n }\n }\n return thrown;\n }\n\n /**\n * Trust `#gotQueries`. Called once the first poke after a (re)connect has\n * been applied. Because `gotQueriesPatch` is a diff, the server won't re-send\n * `put`s for queries it thinks the client already has, so we re-derive and\n * fire `got` for every subscribed query already in the set. Only fires\n * `true`, so this never reverts a query from 'complete'. Idempotent.\n */\n markGotQueriesAuthoritative(): void {\n if (this.#gotQueriesAuthoritative) {\n return;\n }\n this.#gotQueriesAuthoritative = true;\n // Whatever the previous connection held, this one has now confirmed or\n // deleted. Should the watch's first diff have been skipped (a failed\n // initial run), the next diff is live too.\n this.#cachedQueries.clear();\n this.#awaitingPersistedGotDiff = false;\n let thrown: ThrownBy | undefined;\n for (const queryHash of this.#queries.keys()) {\n if (this.#gotQueries.has(queryHash)) {\n const e = this.#fireGotCallbacks(queryHash, true);\n thrown ??= e;\n }\n }\n if (thrown) {\n throw thrown.error;\n }\n }\n\n /** Called on disconnect. The next connect must re-confirm `#gotQueries`. */\n clearGotQueriesAuthoritative(): void {\n if (!this.#gotQueriesAuthoritative) {\n // The connection never confirmed the got set, so the persisted\n // classification still stands. Keys a live diff added in the meantime\n // were not confirmed by this connection and stay unclaimed.\n return;\n }\n this.#gotQueriesAuthoritative = false;\n // Everything got at this point was confirmed by the connection just torn\n // down, which for a new registration is the cached claim.\n for (const queryHash of this.#gotQueries) {\n this.#cachedQueries.add(queryHash);\n }\n }\n\n /**\n * Get the queries that need to be registered with the server.\n *\n * An optional `lastPatch` can be provided. This is the last patch that was\n * sent to the server and may not yet have been acked. If `lastPatch` is provided,\n * this method will return a patch that does not include any events sent in `lastPatch`.\n *\n * This diffing of last patch and current patch is needed since we send\n * a set of queries to the server when we first connect inside of the `sec-protocol` as\n * the `initConnectionMessage`.\n *\n * While we're waiting for the `connected` response to come back from the server,\n * the client may have registered more queries. We need to diff the `initConnectionMessage`\n * queries with the current set of queries to understand what those were.\n */\n async getQueriesPatch(\n tx: ReadTransaction,\n lastPatch?: Map<string, UpQueriesPatchOp>,\n ): Promise<Map<string, UpQueriesPatchOp>> {\n const existingQueryHashes = new Set<string>();\n const prefix = desiredQueriesPrefixForClient(this.#clientID);\n for await (const key of tx.scan({prefix}).keys()) {\n existingQueryHashes.add(key.substring(prefix.length, key.length));\n }\n const patch: Map<string, UpQueriesPatchOp> = new Map();\n for (const hash of existingQueryHashes) {\n if (!this.#queries.has(hash)) {\n patch.set(hash, {op: 'del', hash});\n }\n }\n\n for (const [hash, {normalized, ttl, name, args}] of this.#queries) {\n if (!existingQueryHashes.has(hash)) {\n patch.set(hash, {\n op: 'put',\n hash,\n ast: name === undefined ? normalized : undefined,\n name,\n args,\n // We get TTL out of the DagStore so it is possible that the TTL was written\n // with a too high TTL.\n ttl: clampTTL(ttl), // no lc here since no need to log here\n });\n }\n }\n\n if (lastPatch) {\n // if there are any `puts` in `lastPatch` that are not in `patch` then we need to\n // send a `del` event in `patch`.\n for (const [hash, {op}] of lastPatch) {\n if (op === 'put' && !patch.has(hash)) {\n patch.set(hash, {op: 'del', hash});\n }\n }\n // Remove everything from `patch` that was already sent in `lastPatch`.\n for (const [hash, {op}] of patch) {\n const lastPatchOp = lastPatch.get(hash);\n if (lastPatchOp && lastPatchOp.op === op) {\n patch.delete(hash);\n }\n }\n }\n\n return patch;\n }\n\n handleTransformErrors(errors: ErroredQuery[]) {\n for (const error of errors) {\n const queryId = error.id;\n const entry = this.#queries.get(queryId);\n\n // if we don't have the query registered, continue\n if (!entry) {\n continue;\n }\n\n if (error.error === 'app' || error.error === 'parse') {\n entry.gotCallbacks.forEach(callback => callback(false, error));\n }\n // this code path is not possible technically since errors were never implemented in the legacy query transform error\n // but is included for backwards compatibility and we have a test case for it\n else {\n this.#onFatalError(\n new ProtocolError({\n kind: ErrorKind.TransformFailed,\n origin: ErrorOrigin.ZeroCache,\n reason: ErrorReason.Internal,\n message: `Unknown error transforming queries: ${JSON.stringify(error)}`,\n queryIDs: [],\n }),\n );\n // unreachable(error); TODO(0xcadams): this should eventually be unreachable\n }\n }\n }\n\n handleClosed(\n reason: ClientError<{kind: ClientErrorKind.ClientClosed; message: string}>,\n ) {\n if (this.#closedError) {\n return;\n }\n this.#closedError = reason;\n for (const [queryId, entry] of this.#queries) {\n const erroredQuery: ErroredQuery = {\n error: 'app',\n id: queryId,\n name: entry.name ?? 'legacy',\n message: reason.message,\n details: {kind: reason.kind},\n };\n for (const gotCallback of entry.gotCallbacks) {\n gotCallback(false, erroredQuery);\n }\n }\n }\n\n addCustom(\n ast: AST,\n {name, args}: CustomQueryID,\n ttl: TTL,\n gotCallback?: GotCallback,\n ): () => void {\n const normalized = normalizeAST(ast);\n const queryId = hashOfNameAndArgs(name, args);\n return this.#add(queryId, normalized, name, args, ttl, gotCallback);\n }\n\n /** @deprecated */\n addLegacy(ast: AST, ttl: TTL, gotCallback?: GotCallback): () => void {\n const normalized = normalizeAST(ast);\n const astHash = hashOfAST(normalized);\n return this.#add(\n astHash,\n normalized,\n undefined, // name is undefined for legacy queries\n undefined, // args are undefined for legacy queries\n ttl,\n gotCallback,\n );\n }\n\n #add(\n queryId: string,\n normalized: AST,\n name: string | undefined,\n args: readonly ReadonlyJSONValue[] | undefined,\n ttl: TTL,\n gotCallback?: GotCallback,\n ) {\n assert(\n (name === undefined) === (args === undefined),\n 'If name is defined, args must be defined',\n );\n ttl = clampTTL(ttl, this.#lc);\n let entry = this.#queries.get(queryId);\n this.#recentQueries.delete(queryId);\n if (!entry) {\n normalized = mapAST(normalized, this.#clientToServer);\n\n entry = {\n normalized,\n name,\n args,\n count: 1,\n gotCallbacks: gotCallback ? [gotCallback] : [],\n ttl,\n };\n this.#queries.set(queryId, entry);\n this.#queueQueryChange({\n op: 'put',\n hash: queryId,\n ast: name === undefined ? normalized : undefined,\n name,\n args,\n ttl,\n });\n } else {\n ++entry.count;\n this.#updateEntry(entry, queryId, ttl);\n\n if (gotCallback) {\n entry.gotCallbacks.push(gotCallback);\n }\n }\n\n if (gotCallback) {\n gotCallback(\n this.#gotQueriesAuthoritative\n ? this.#gotQueries.has(queryId)\n : this.#cachedQueries.has(queryId) && 'cached',\n );\n }\n\n let removed = false;\n const cleanupCb = () => {\n if (removed) {\n return;\n }\n removed = true;\n\n // We cannot remove queries while mutations are pending\n // as that could take data out of scope that is needed in a rebase\n if (this.#mutationTracker.size > 0) {\n this.#pendingRemovals.push(() =>\n this.#remove(entry, queryId, gotCallback),\n );\n return;\n }\n\n this.#remove(entry, queryId, gotCallback);\n };\n return cleanupCb;\n }\n\n updateCustom({name, args}: CustomQueryID, ttl: TTL) {\n const queryID = hashOfNameAndArgs(name, args);\n const entry = must(this.#queries.get(queryID));\n this.#updateEntry(entry, queryID, ttl);\n }\n\n /** @deprecated */\n updateLegacy(ast: AST, ttl: TTL) {\n const normalized = normalizeAST(ast);\n const queryID = hashOfAST(normalized);\n const entry = must(this.#queries.get(queryID));\n this.#updateEntry(entry, queryID, ttl);\n }\n\n #updateEntry(entry: Entry, queryID: string, ttl: TTL): void {\n // If the query already exists and the new ttl is larger than the old one\n // we send a changeDesiredQueries message to the server to update the ttl.\n ttl = clampTTL(ttl, this.#lc);\n if (compareTTL(ttl, entry.ttl) > 0) {\n entry.ttl = ttl;\n this.#queueQueryChange({\n op: 'put',\n hash: queryID,\n ast: entry.name === undefined ? entry.normalized : undefined,\n name: entry.name,\n args: entry.args,\n ttl,\n });\n }\n }\n\n #queueQueryChange(op: UpQueriesPatchOp) {\n this.#pendingQueryChanges.push(op);\n this.#scheduleBatch();\n }\n\n #scheduleBatch() {\n if (this.#batchTimer === undefined) {\n this.#batchTimer = setTimeout(\n () => this.flushBatch(),\n this.#queryChangeThrottleMs,\n );\n }\n }\n\n flushBatch() {\n if (this.#batchTimer !== undefined) {\n clearTimeout(this.#batchTimer);\n this.#batchTimer = undefined;\n }\n if (this.#pendingQueryChanges.length > 0) {\n this.#send([\n 'changeDesiredQueries',\n {\n desiredQueriesPatch: [...this.#pendingQueryChanges],\n },\n ]);\n this.#pendingQueryChanges.length = 0;\n }\n }\n\n #remove(entry: Entry, astHash: string, gotCallback: GotCallback | undefined) {\n if (gotCallback) {\n const index = entry.gotCallbacks.indexOf(gotCallback);\n entry.gotCallbacks.splice(index, 1);\n }\n --entry.count;\n if (entry.count === 0) {\n this.#recentQueries.add(astHash);\n if (this.#recentQueries.size > this.#recentQueriesMaxSize) {\n const lruQueryID = this.#recentQueries.values().next().value;\n assert(lruQueryID, 'Expected LRU query ID to exist');\n const evictedAST = this.getAST(lruQueryID);\n const evictedMetrics =\n this.#queryMetrics.get(lruQueryID) ?? newPerQueryMetrics();\n this.#queries.delete(lruQueryID);\n this.#recentQueries.delete(lruQueryID);\n this.#queryMetrics.delete(lruQueryID);\n this.#queueQueryChange({op: 'del', hash: lruQueryID});\n assert(evictedAST, 'Expected evicted AST to exist');\n this.#queryEvictedCallback?.(lruQueryID, evictedAST, evictedMetrics);\n }\n }\n }\n\n /**\n * Gets the aggregated metrics for all queries managed by this QueryManager.\n */\n get metrics(): ClientMetric {\n return this.#metrics;\n }\n\n addMetric<K extends keyof ClientMetricMap>(\n metric: K,\n value: number,\n ...args: ClientMetricMap[K]\n ): void {\n // Only query metrics are tracked at this point.\n // If this check fails then we need to add a runtime check.\n metric satisfies `query-${string}`;\n\n // We track all materializations of queries as well as per\n // query materializations.\n this.#metrics[metric].add(value);\n\n const queryID = args[0];\n\n // Handle slow query logging for end-to-end materialization\n if (metric === 'query-materialization-end-to-end') {\n const ast = args[1];\n\n if (\n this.#slowMaterializeThreshold !== undefined &&\n value > this.#slowMaterializeThreshold\n ) {\n this.#lc.warn?.(\n 'Slow query materialization (including server/network)',\n queryID,\n ast,\n value,\n );\n } else {\n this.#lc.debug?.(\n 'Materialized query (including server/network)',\n queryID,\n ast,\n value,\n );\n }\n }\n\n // The query manager manages metrics that are per query.\n let existing = this.#queryMetrics.get(queryID);\n if (!existing) {\n existing = newPerQueryMetrics();\n this.#queryMetrics.set(queryID, existing);\n }\n switch (metric) {\n case 'query-update-client':\n existing['query-update-client'].add(value);\n break;\n case 'query-materialization-client':\n case 'query-materialization-end-to-end':\n // Recorded once per query (last value wins).\n existing[\n metric as\n | 'query-materialization-client'\n | 'query-materialization-end-to-end'\n ] = value;\n break;\n default:\n unreachable(metric);\n }\n }\n\n getQueryMetrics(queryID: string): PerQueryClientMetric | undefined {\n return this.#queryMetrics.get(queryID);\n }\n\n /**\n * For testing only: returns all query hashes currently registered.\n */\n getAllNonGotQueryHashes(): Iterable<string> {\n return difference(this.#queries, this.#gotQueries);\n }\n}\n\nfunction newMetrics(): ClientMetric {\n return {\n 'query-materialization-client': new TDigest(),\n 'query-materialization-end-to-end': new TDigest(),\n 'query-update-client': new TDigest(),\n };\n}\n\nfunction newPerQueryMetrics(): PerQueryClientMetric {\n return {\n 'query-materialization-client': undefined,\n 'query-materialization-end-to-end': undefined,\n 'query-update-client': new TDigest(),\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;AA0EA,IAAa,eAAb,MAAuD;CACrD;CACA;CACA;CACA;CACA;CACA,2BAA2C,IAAI,IAAI;CACnD;CACA,iCAAuC,IAAI,IAAI;CAC/C,8BAAoC,IAAI,IAAI;CAI5C,2BAA2B;CAM3B,iCAAuC,IAAI,IAAI;CAI/C,4BAA4B;CAC5B;CACA,uBAAoD,CAAC;CACrD;CACA,mBAAsC,CAAC;CACvC;CACA;C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,SAAS,QAAQ;EAC1C;EACA,QAAQ,QAAR;GACE,KAAK;IACH,SAAS,uBAAuB,IAAI,KAAK;IACzC;GACF,KAAK;GACL,KAAK;IAEH,SACE,UAGE;IACJ;GACF,SACE,YAAY,MAAM;EACtB;CACF;CAEA,gBAAgB,SAAmD;EACjE,OAAO,KAAKA,cAAc,IAAI,OAAO;CACvC;;;;CAKA,0BAA4C;EAC1C,OAAO,WAAW,KAAKV,UAAU,KAAKG,WAAW;CACnD;AACF;AAEA,SAAS,aAA2B;CAClC,OAAO;EACL,gCAAgC,IAAI,QAAQ;EAC5C,oCAAoC,IAAI,QAAQ;EAChD,uBAAuB,IAAI,QAAQ;CACrC;AACF;AAEA,SAAS,qBAA2C;CAClD,OAAO;EACL,gCAAgC,KAAA;EAChC,oCAAoC,KAAA;EACpC,uBAAuB,IAAI,QAAQ;CACrC;AACF"}
|
|
1
|
+
{"version":3,"file":"query-manager.js","names":["#clientID","#clientToServer","#serverToClient","#send","#onFatalError","#queries","#recentQueriesMaxSize","#recentQueries","#gotQueries","#cachedQueries","#mutationTracker","#pendingQueryChanges","#queryChangeThrottleMs","#lc","#metrics","#queryMetrics","#slowMaterializeThreshold","#pendingRemovals","#awaitingPersistedGotDiff","#fireGotCallbacks","#gotQueriesAuthoritative","#queryEvictedCallback","#closedError","#add","#queueQueryChange","#updateEntry","#remove","#scheduleBatch","#batchTimer"],"sources":["../../../../../zero-client/src/client/query-manager.ts"],"sourcesContent":["import type {LogContext} from '@rocicorp/logger';\nimport type {ReplicacheImpl} from '../../../replicache/src/replicache-impl.ts';\nimport type {ClientID} from '../../../replicache/src/sync/ids.ts';\nimport {assert, unreachable} from '../../../shared/src/asserts.ts';\nimport type {ReadonlyJSONValue} from '../../../shared/src/json.ts';\nimport {getOrInsertComputed} from '../../../shared/src/map.ts';\nimport {must} from '../../../shared/src/must.ts';\nimport {difference} from '../../../shared/src/set-utils.ts';\nimport {TDigest} from '../../../shared/src/tdigest.ts';\nimport {\n mapAST,\n normalizeAST,\n type AST,\n} from '../../../zero-protocol/src/ast.ts';\nimport type {ChangeDesiredQueriesMessage} from '../../../zero-protocol/src/change-desired-queries.ts';\nimport type {ErroredQuery} from '../../../zero-protocol/src/custom-queries.ts';\nimport {ErrorKind} from '../../../zero-protocol/src/error-kind.ts';\nimport {ErrorOrigin} from '../../../zero-protocol/src/error-origin.ts';\nimport {ErrorReason} from '../../../zero-protocol/src/error-reason.ts';\nimport {ProtocolError} from '../../../zero-protocol/src/error.ts';\nimport type {UpQueriesPatchOp} from '../../../zero-protocol/src/queries-patch.ts';\nimport {\n hashOfAST,\n hashOfNameAndArgs,\n} from '../../../zero-protocol/src/query-hash.ts';\nimport {\n clientToServer,\n serverToClient,\n type NameMapper,\n} from '../../../zero-schema/src/name-mapper.ts';\nimport type {TableSchema} from '../../../zero-schema/src/table-schema.ts';\nimport type {ClientMetricMap} from '../../../zql/src/query/metrics-delegate.ts';\nimport type {CustomQueryID} from '../../../zql/src/query/named.ts';\nimport type {GotCallback} from '../../../zql/src/query/query-delegate.ts';\nimport {clampTTL, compareTTL, type TTL} from '../../../zql/src/query/ttl.ts';\nimport type {ClientErrorKind} from './client-error-kind.ts';\nimport type {ClientError} from './error.ts';\nimport {type ZeroError} from './error.ts';\nimport type {InspectorDelegate} from './inspector/inspector.ts';\nimport type {QueryClientMetrics} from './inspector/lazy-inspector.ts';\nimport {desiredQueriesPrefixForClient, GOT_QUERIES_KEY_PREFIX} from './keys.ts';\nimport type {MutationTracker} from './mutation-tracker.ts';\nimport type {ReadTransaction} from './replicache-types.ts';\n\ntype QueryHash = string;\n\ntype Entry = {\n // We keep track of the AST so we can use it in the inspector.\n normalized: AST;\n name: string | undefined;\n args: readonly ReadonlyJSONValue[] | undefined;\n count: number;\n gotCallbacks: GotCallback[];\n ttl: TTL;\n};\n\n// A thrown value, boxed so that `throw undefined` is still distinguishable\n// from \"nothing thrown\".\ntype ThrownBy = {readonly error: unknown};\n\ntype ClientMetric = {\n [K in keyof ClientMetricMap]: TDigest;\n};\n\ntype PerQueryClientMetric = {\n 'query-materialization-client': number | undefined;\n 'query-materialization-end-to-end': number | undefined;\n 'query-update-client': TDigest;\n};\n\n/**\n * Tracks what queries the client is currently subscribed to on the server.\n * Sends `changeDesiredQueries` message to server when this changes.\n * Deduplicates requests so that we only listen to a given unique query once.\n */\nexport class QueryManager implements InspectorDelegate {\n readonly #clientID: ClientID;\n readonly #clientToServer: NameMapper;\n readonly #serverToClient: NameMapper;\n readonly #send: (change: ChangeDesiredQueriesMessage) => void;\n readonly #onFatalError: (error: ZeroError) => void;\n readonly #queries: Map<QueryHash, Entry> = new Map();\n readonly #recentQueriesMaxSize: number;\n readonly #recentQueries: Set<string> = new Set();\n readonly #gotQueries: Set<string> = new Set();\n // Whether `#gotQueries` can be trusted. The persisted set loaded from\n // IndexedDB may be stale (a query 'got' in a previous session can be evicted\n // server-side); see `markGotQueriesAuthoritative`.\n #gotQueriesAuthoritative = false;\n // The got keys whose result the store holds from a previous connection: the\n // set persisted by a previous session, and on disconnect everything the\n // connection just torn down had confirmed. Until the got set is\n // authoritative, a registration reports these as 'cached'. Keys added by a\n // live diff are not in it; see the watch below.\n readonly #cachedQueries: Set<string> = new Set();\n // Whether the got-queries watch has yet to deliver its first diff, the\n // persisted set. Cleared before that diff is processed, so a throwing\n // callback cannot leave it set.\n #awaitingPersistedGotDiff = true;\n readonly #mutationTracker: MutationTracker;\n readonly #pendingQueryChanges: UpQueriesPatchOp[] = [];\n readonly #queryChangeThrottleMs: number;\n #pendingRemovals: Array<() => void> = [];\n #batchTimer: ReturnType<typeof setTimeout> | undefined;\n readonly #lc: LogContext;\n readonly #metrics: ClientMetric = newMetrics();\n readonly #queryMetrics: Map<string, PerQueryClientMetric> = new Map();\n readonly #slowMaterializeThreshold: number;\n #closedError: ZeroError | undefined;\n #queryEvictedCallback:\n | ((hash: string, ast: AST, metrics: QueryClientMetrics) => void)\n | undefined;\n\n constructor(\n lc: LogContext,\n mutationTracker: MutationTracker,\n clientID: ClientID,\n tables: Record<string, TableSchema>,\n send: (change: ChangeDesiredQueriesMessage) => void,\n experimentalWatch: ReplicacheImpl['experimentalWatch'],\n recentQueriesMaxSize: number,\n queryChangeThrottleMs: number,\n slowMaterializeThreshold: number,\n onFatalError: (error: ZeroError) => void,\n ) {\n this.#lc = lc.withContext('QueryManager');\n this.#clientID = clientID;\n this.#clientToServer = clientToServer(tables);\n this.#serverToClient = serverToClient(tables);\n this.#recentQueriesMaxSize = recentQueriesMaxSize;\n this.#send = send;\n this.#mutationTracker = mutationTracker;\n this.#queryChangeThrottleMs = queryChangeThrottleMs;\n this.#slowMaterializeThreshold = slowMaterializeThreshold;\n this.#onFatalError = onFatalError;\n this.#mutationTracker.onAllMutationsApplied(() => {\n if (this.#pendingRemovals.length === 0) {\n return;\n }\n const pendingRemovals = this.#pendingRemovals;\n this.#pendingRemovals = [];\n for (const removal of pendingRemovals) {\n removal();\n }\n });\n\n // The first diff is the got set persisted by a previous session, the only\n // state the watch may report as 'cached'. Every later diff is live: this\n // tab's own poke, whose keys are confirmations on this connection and are\n // reported as got once the poke has been applied (see\n // `markGotQueriesAuthoritative`), or another tab's state arriving via\n // replicache refresh. A live diff can therefore only revoke a cached\n // claim (a deleted key), never grant one.\n experimentalWatch(\n diff => {\n const persisted = this.#awaitingPersistedGotDiff;\n this.#awaitingPersistedGotDiff = false;\n // A throwing callback must not leave the rest of the diff unapplied,\n // or later keys would never enter the got set. The first error is\n // rethrown once the sets are consistent.\n let thrown: ThrownBy | undefined;\n const fire = (queryHash: string, got: boolean | 'cached') => {\n const e = this.#fireGotCallbacks(queryHash, got);\n thrown ??= e;\n };\n for (const diffOp of diff) {\n const queryHash = diffOp.key.substring(GOT_QUERIES_KEY_PREFIX.length);\n switch (diffOp.op) {\n case 'add':\n this.#gotQueries.add(queryHash);\n if (this.#gotQueriesAuthoritative) {\n fire(queryHash, true);\n } else if (persisted) {\n this.#cachedQueries.add(queryHash);\n fire(queryHash, 'cached');\n }\n break;\n case 'del':\n this.#gotQueries.delete(queryHash);\n this.#cachedQueries.delete(queryHash);\n fire(queryHash, false);\n break;\n }\n }\n if (thrown) {\n throw thrown.error;\n }\n },\n {\n prefix: GOT_QUERIES_KEY_PREFIX,\n initialValuesInFirstDiff: true,\n },\n );\n }\n\n getAST(queryID: string): AST | undefined {\n const ast = this.#queries.get(queryID)?.normalized;\n return ast && mapAST(ast, this.#serverToClient);\n }\n\n setQueryEvictedCallback(\n cb: (hash: string, ast: AST, metrics: QueryClientMetrics) => void,\n ): void {\n this.#queryEvictedCallback = cb;\n }\n\n mapClientASTToServer(ast: AST): AST {\n return mapAST(ast, this.#clientToServer);\n }\n\n /**\n * Notifies every subscriber of the query. A throwing subscriber does not\n * keep the others from being notified; the first error is returned so the\n * caller can rethrow it once its own bookkeeping is consistent.\n */\n #fireGotCallbacks(\n queryHash: string,\n got: boolean | 'cached',\n ): ThrownBy | undefined {\n const entry = this.#queries.get(queryHash);\n if (!entry) {\n return undefined;\n }\n let thrown: ThrownBy | undefined;\n // A subscriber may unregister during dispatch (a run() waiter destroys its\n // view on the notification it was waiting for), so iterate a snapshot.\n for (const gotCallback of [...entry.gotCallbacks]) {\n try {\n gotCallback(got);\n } catch (error) {\n thrown ??= {error};\n }\n }\n return thrown;\n }\n\n /**\n * Trust `#gotQueries`. Called once the first poke after a (re)connect has\n * been applied. Because `gotQueriesPatch` is a diff, the server won't re-send\n * `put`s for queries it thinks the client already has, so we re-derive and\n * fire `got` for every subscribed query already in the set. Only fires\n * `true`, so this never reverts a query from 'complete'. Idempotent.\n */\n markGotQueriesAuthoritative(): void {\n if (this.#gotQueriesAuthoritative) {\n return;\n }\n this.#gotQueriesAuthoritative = true;\n // Whatever the previous connection held, this one has now confirmed or\n // deleted. Should the watch's first diff have been skipped (a failed\n // initial run), the next diff is live too.\n this.#cachedQueries.clear();\n this.#awaitingPersistedGotDiff = false;\n let thrown: ThrownBy | undefined;\n for (const queryHash of this.#queries.keys()) {\n if (this.#gotQueries.has(queryHash)) {\n const e = this.#fireGotCallbacks(queryHash, true);\n thrown ??= e;\n }\n }\n if (thrown) {\n throw thrown.error;\n }\n }\n\n /** Called on disconnect. The next connect must re-confirm `#gotQueries`. */\n clearGotQueriesAuthoritative(): void {\n if (!this.#gotQueriesAuthoritative) {\n // The connection never confirmed the got set, so the persisted\n // classification still stands. Keys a live diff added in the meantime\n // were not confirmed by this connection and stay unclaimed.\n return;\n }\n this.#gotQueriesAuthoritative = false;\n // Everything got at this point was confirmed by the connection just torn\n // down, which for a new registration is the cached claim.\n for (const queryHash of this.#gotQueries) {\n this.#cachedQueries.add(queryHash);\n }\n }\n\n /**\n * Get the queries that need to be registered with the server.\n *\n * An optional `lastPatch` can be provided. This is the last patch that was\n * sent to the server and may not yet have been acked. If `lastPatch` is provided,\n * this method will return a patch that does not include any events sent in `lastPatch`.\n *\n * This diffing of last patch and current patch is needed since we send\n * a set of queries to the server when we first connect inside of the `sec-protocol` as\n * the `initConnectionMessage`.\n *\n * While we're waiting for the `connected` response to come back from the server,\n * the client may have registered more queries. We need to diff the `initConnectionMessage`\n * queries with the current set of queries to understand what those were.\n */\n async getQueriesPatch(\n tx: ReadTransaction,\n lastPatch?: Map<string, UpQueriesPatchOp>,\n ): Promise<Map<string, UpQueriesPatchOp>> {\n const existingQueryHashes = new Set<string>();\n const prefix = desiredQueriesPrefixForClient(this.#clientID);\n for await (const key of tx.scan({prefix}).keys()) {\n existingQueryHashes.add(key.substring(prefix.length, key.length));\n }\n const patch: Map<string, UpQueriesPatchOp> = new Map();\n for (const hash of existingQueryHashes) {\n if (!this.#queries.has(hash)) {\n patch.set(hash, {op: 'del', hash});\n }\n }\n\n for (const [hash, {normalized, ttl, name, args}] of this.#queries) {\n if (!existingQueryHashes.has(hash)) {\n patch.set(hash, {\n op: 'put',\n hash,\n ast: name === undefined ? normalized : undefined,\n name,\n args,\n // We get TTL out of the DagStore so it is possible that the TTL was written\n // with a too high TTL.\n ttl: clampTTL(ttl), // no lc here since no need to log here\n });\n }\n }\n\n if (lastPatch) {\n // if there are any `puts` in `lastPatch` that are not in `patch` then we need to\n // send a `del` event in `patch`.\n for (const [hash, {op}] of lastPatch) {\n if (op === 'put' && !patch.has(hash)) {\n patch.set(hash, {op: 'del', hash});\n }\n }\n // Remove everything from `patch` that was already sent in `lastPatch`.\n for (const [hash, {op}] of patch) {\n const lastPatchOp = lastPatch.get(hash);\n if (lastPatchOp && lastPatchOp.op === op) {\n patch.delete(hash);\n }\n }\n }\n\n return patch;\n }\n\n handleTransformErrors(errors: ErroredQuery[]) {\n for (const error of errors) {\n const queryId = error.id;\n const entry = this.#queries.get(queryId);\n\n // if we don't have the query registered, continue\n if (!entry) {\n continue;\n }\n\n if (error.error === 'app' || error.error === 'parse') {\n entry.gotCallbacks.forEach(callback => callback(false, error));\n }\n // this code path is not possible technically since errors were never implemented in the legacy query transform error\n // but is included for backwards compatibility and we have a test case for it\n else {\n this.#onFatalError(\n new ProtocolError({\n kind: ErrorKind.TransformFailed,\n origin: ErrorOrigin.ZeroCache,\n reason: ErrorReason.Internal,\n message: `Unknown error transforming queries: ${JSON.stringify(error)}`,\n queryIDs: [],\n }),\n );\n // unreachable(error); TODO(0xcadams): this should eventually be unreachable\n }\n }\n }\n\n handleClosed(\n reason: ClientError<{kind: ClientErrorKind.ClientClosed; message: string}>,\n ) {\n if (this.#closedError) {\n return;\n }\n this.#closedError = reason;\n for (const [queryId, entry] of this.#queries) {\n const erroredQuery: ErroredQuery = {\n error: 'app',\n id: queryId,\n name: entry.name ?? 'legacy',\n message: reason.message,\n details: {kind: reason.kind},\n };\n for (const gotCallback of entry.gotCallbacks) {\n gotCallback(false, erroredQuery);\n }\n }\n }\n\n addCustom(\n ast: AST,\n {name, args}: CustomQueryID,\n ttl: TTL,\n gotCallback?: GotCallback,\n ): () => void {\n const normalized = normalizeAST(ast);\n const queryId = hashOfNameAndArgs(name, args);\n return this.#add(queryId, normalized, name, args, ttl, gotCallback);\n }\n\n /** @deprecated */\n addLegacy(ast: AST, ttl: TTL, gotCallback?: GotCallback): () => void {\n const normalized = normalizeAST(ast);\n const astHash = hashOfAST(normalized);\n return this.#add(\n astHash,\n normalized,\n undefined, // name is undefined for legacy queries\n undefined, // args are undefined for legacy queries\n ttl,\n gotCallback,\n );\n }\n\n #add(\n queryId: string,\n normalized: AST,\n name: string | undefined,\n args: readonly ReadonlyJSONValue[] | undefined,\n ttl: TTL,\n gotCallback?: GotCallback,\n ) {\n assert(\n (name === undefined) === (args === undefined),\n 'If name is defined, args must be defined',\n );\n ttl = clampTTL(ttl, this.#lc);\n let entry = this.#queries.get(queryId);\n this.#recentQueries.delete(queryId);\n if (!entry) {\n normalized = mapAST(normalized, this.#clientToServer);\n\n entry = {\n normalized,\n name,\n args,\n count: 1,\n gotCallbacks: gotCallback ? [gotCallback] : [],\n ttl,\n };\n this.#queries.set(queryId, entry);\n this.#queueQueryChange({\n op: 'put',\n hash: queryId,\n ast: name === undefined ? normalized : undefined,\n name,\n args,\n ttl,\n });\n } else {\n ++entry.count;\n this.#updateEntry(entry, queryId, ttl);\n\n if (gotCallback) {\n entry.gotCallbacks.push(gotCallback);\n }\n }\n\n if (gotCallback) {\n gotCallback(\n this.#gotQueriesAuthoritative\n ? this.#gotQueries.has(queryId)\n : this.#cachedQueries.has(queryId) && 'cached',\n );\n }\n\n let removed = false;\n const cleanupCb = () => {\n if (removed) {\n return;\n }\n removed = true;\n\n // We cannot remove queries while mutations are pending\n // as that could take data out of scope that is needed in a rebase\n if (this.#mutationTracker.size > 0) {\n this.#pendingRemovals.push(() =>\n this.#remove(entry, queryId, gotCallback),\n );\n return;\n }\n\n this.#remove(entry, queryId, gotCallback);\n };\n return cleanupCb;\n }\n\n updateCustom({name, args}: CustomQueryID, ttl: TTL) {\n const queryID = hashOfNameAndArgs(name, args);\n const entry = must(this.#queries.get(queryID));\n this.#updateEntry(entry, queryID, ttl);\n }\n\n /** @deprecated */\n updateLegacy(ast: AST, ttl: TTL) {\n const normalized = normalizeAST(ast);\n const queryID = hashOfAST(normalized);\n const entry = must(this.#queries.get(queryID));\n this.#updateEntry(entry, queryID, ttl);\n }\n\n #updateEntry(entry: Entry, queryID: string, ttl: TTL): void {\n // If the query already exists and the new ttl is larger than the old one\n // we send a changeDesiredQueries message to the server to update the ttl.\n ttl = clampTTL(ttl, this.#lc);\n if (compareTTL(ttl, entry.ttl) > 0) {\n entry.ttl = ttl;\n this.#queueQueryChange({\n op: 'put',\n hash: queryID,\n ast: entry.name === undefined ? entry.normalized : undefined,\n name: entry.name,\n args: entry.args,\n ttl,\n });\n }\n }\n\n #queueQueryChange(op: UpQueriesPatchOp) {\n this.#pendingQueryChanges.push(op);\n this.#scheduleBatch();\n }\n\n #scheduleBatch() {\n if (this.#batchTimer === undefined) {\n this.#batchTimer = setTimeout(\n () => this.flushBatch(),\n this.#queryChangeThrottleMs,\n );\n }\n }\n\n flushBatch() {\n if (this.#batchTimer !== undefined) {\n clearTimeout(this.#batchTimer);\n this.#batchTimer = undefined;\n }\n if (this.#pendingQueryChanges.length > 0) {\n this.#send([\n 'changeDesiredQueries',\n {\n desiredQueriesPatch: [...this.#pendingQueryChanges],\n },\n ]);\n this.#pendingQueryChanges.length = 0;\n }\n }\n\n #remove(entry: Entry, astHash: string, gotCallback: GotCallback | undefined) {\n if (gotCallback) {\n const index = entry.gotCallbacks.indexOf(gotCallback);\n entry.gotCallbacks.splice(index, 1);\n }\n --entry.count;\n if (entry.count === 0) {\n this.#recentQueries.add(astHash);\n if (this.#recentQueries.size > this.#recentQueriesMaxSize) {\n const lruQueryID = this.#recentQueries.values().next().value;\n assert(lruQueryID, 'Expected LRU query ID to exist');\n const evictedAST = this.getAST(lruQueryID);\n const evictedMetrics =\n this.#queryMetrics.get(lruQueryID) ?? newPerQueryMetrics();\n this.#queries.delete(lruQueryID);\n this.#recentQueries.delete(lruQueryID);\n this.#queryMetrics.delete(lruQueryID);\n this.#queueQueryChange({op: 'del', hash: lruQueryID});\n assert(evictedAST, 'Expected evicted AST to exist');\n this.#queryEvictedCallback?.(lruQueryID, evictedAST, evictedMetrics);\n }\n }\n }\n\n /**\n * Gets the aggregated metrics for all queries managed by this QueryManager.\n */\n get metrics(): ClientMetric {\n return this.#metrics;\n }\n\n addMetric<K extends keyof ClientMetricMap>(\n metric: K,\n value: number,\n ...args: ClientMetricMap[K]\n ): void {\n // Only query metrics are tracked at this point.\n // If this check fails then we need to add a runtime check.\n metric satisfies `query-${string}`;\n\n // We track all materializations of queries as well as per\n // query materializations.\n this.#metrics[metric].add(value);\n\n const queryID = args[0];\n\n // Handle slow query logging for end-to-end materialization\n if (metric === 'query-materialization-end-to-end') {\n const ast = args[1];\n\n if (\n this.#slowMaterializeThreshold !== undefined &&\n value > this.#slowMaterializeThreshold\n ) {\n this.#lc.warn?.(\n 'Slow query materialization (including server/network)',\n queryID,\n ast,\n value,\n );\n } else {\n this.#lc.debug?.(\n 'Materialized query (including server/network)',\n queryID,\n ast,\n value,\n );\n }\n }\n\n // The query manager manages metrics that are per query.\n const existing = getOrInsertComputed(\n this.#queryMetrics,\n queryID,\n newPerQueryMetrics,\n );\n switch (metric) {\n case 'query-update-client':\n existing['query-update-client'].add(value);\n break;\n case 'query-materialization-client':\n case 'query-materialization-end-to-end':\n // Recorded once per query (last value wins).\n existing[\n metric as\n | 'query-materialization-client'\n | 'query-materialization-end-to-end'\n ] = value;\n break;\n default:\n unreachable(metric);\n }\n }\n\n getQueryMetrics(queryID: string): PerQueryClientMetric | undefined {\n return this.#queryMetrics.get(queryID);\n }\n\n /**\n * For testing only: returns all query hashes currently registered.\n */\n getAllNonGotQueryHashes(): Iterable<string> {\n return difference(this.#queries, this.#gotQueries);\n }\n}\n\nfunction newMetrics(): ClientMetric {\n return {\n 'query-materialization-client': new TDigest(),\n 'query-materialization-end-to-end': new TDigest(),\n 'query-update-client': new TDigest(),\n };\n}\n\nfunction newPerQueryMetrics(): PerQueryClientMetric {\n return {\n 'query-materialization-client': undefined,\n 'query-materialization-end-to-end': undefined,\n 'query-update-client':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B,IAAI,WAAW,oCAAoC;GACjD,MAAM,MAAM,KAAK;GAEjB,IACE,KAAKE,8BAA8B,KAAA,KACnC,QAAQ,KAAKA,2BAEb,KAAKH,IAAI,OACP,yDACA,SACA,KACA,KACF;QAEA,KAAKA,IAAI,QACP,iDACA,SACA,KACA,KACF;EAEJ;EAGA,MAAM,WAAW,oBACf,KAAKE,eACL,SACA,kBACF;EACA,QAAQ,QAAR;GACE,KAAK;IACH,SAAS,uBAAuB,IAAI,KAAK;IACzC;GACF,KAAK;GACL,KAAK;IAEH,SACE,UAGE;IACJ;GACF,SACE,YAAY,MAAM;EACtB;CACF;CAEA,gBAAgB,SAAmD;EACjE,OAAO,KAAKA,cAAc,IAAI,OAAO;CACvC;;;;CAKA,0BAA4C;EAC1C,OAAO,WAAW,KAAKV,UAAU,KAAKG,WAAW;CACnD;AACF;AAEA,SAAS,aAA2B;CAClC,OAAO;EACL,gCAAgC,IAAI,QAAQ;EAC5C,oCAAoC,IAAI,QAAQ;EAChD,uBAAuB,IAAI,QAAQ;CACrC;AACF;AAEA,SAAS,qBAA2C;CAClD,OAAO;EACL,gCAAgC,KAAA;EAChC,oCAAoC,KAAA;EACpC,uBAAuB,IAAI,QAAQ;CACrC;AACF"}
|
|
@@ -37,7 +37,7 @@ declare const bestPlanSelectedEventJSONSchema: v.ObjectType<{
|
|
|
37
37
|
declare const nodeConstraintEventJSONSchema: v.ObjectType<{
|
|
38
38
|
type: v.Type<"node-constraint">;
|
|
39
39
|
attemptNumber: v.Optional<number>;
|
|
40
|
-
nodeType: v.UnionType<[v.Type<"connection">, v.Type<"join">, v.Type<"fan-out">, v.Type<"fan-in">, v.Type<"terminus">]>;
|
|
40
|
+
nodeType: v.UnionType<[v.Type<"connection">, v.Type<"join">, v.Type<"fan-out">, v.Type<"fan-in">, v.Type<"filter">, v.Type<"terminus">]>;
|
|
41
41
|
node: v.Type<string>;
|
|
42
42
|
branchPattern: v.ArrayType<v.Type<number>>;
|
|
43
43
|
constraint: v.Optional<Record<string, unknown> | null>;
|
|
@@ -118,7 +118,7 @@ declare const planDebugEventJSONSchema: v.UnionType<[v.ObjectType<{
|
|
|
118
118
|
}, undefined>, v.ObjectType<{
|
|
119
119
|
type: v.Type<"node-cost">;
|
|
120
120
|
attemptNumber: v.Optional<number>;
|
|
121
|
-
nodeType: v.UnionType<[v.Type<"connection">, v.Type<"join">, v.Type<"fan-out">, v.Type<"fan-in">, v.Type<"terminus">]>;
|
|
121
|
+
nodeType: v.UnionType<[v.Type<"connection">, v.Type<"join">, v.Type<"fan-out">, v.Type<"fan-in">, v.Type<"filter">, v.Type<"terminus">]>;
|
|
122
122
|
node: v.Type<string>;
|
|
123
123
|
branchPattern: v.ArrayType<v.Type<number>>;
|
|
124
124
|
downstreamChildSelectivity: v.Type<number>;
|
|
@@ -136,7 +136,7 @@ declare const planDebugEventJSONSchema: v.UnionType<[v.ObjectType<{
|
|
|
136
136
|
}, undefined>, v.ObjectType<{
|
|
137
137
|
type: v.Type<"node-constraint">;
|
|
138
138
|
attemptNumber: v.Optional<number>;
|
|
139
|
-
nodeType: v.UnionType<[v.Type<"connection">, v.Type<"join">, v.Type<"fan-out">, v.Type<"fan-in">, v.Type<"terminus">]>;
|
|
139
|
+
nodeType: v.UnionType<[v.Type<"connection">, v.Type<"join">, v.Type<"fan-out">, v.Type<"fan-in">, v.Type<"filter">, v.Type<"terminus">]>;
|
|
140
140
|
node: v.Type<string>;
|
|
141
141
|
branchPattern: v.ArrayType<v.Type<number>>;
|
|
142
142
|
constraint: v.Optional<Record<string, unknown> | null>;
|
|
@@ -240,7 +240,7 @@ export declare const analyzeQueryResultSchema: v.ObjectType<{
|
|
|
240
240
|
ordering?: readonly (readonly [string, "desc" | "asc"])[] | undefined;
|
|
241
241
|
joinType?: "semi" | "flipped" | "unflippable" | undefined;
|
|
242
242
|
type: "node-cost";
|
|
243
|
-
nodeType: "join" | "connection" | "fan-out" | "fan-in" | "terminus";
|
|
243
|
+
nodeType: "join" | "filter" | "connection" | "fan-out" | "fan-in" | "terminus";
|
|
244
244
|
node: string;
|
|
245
245
|
branchPattern: number[];
|
|
246
246
|
downstreamChildSelectivity: number;
|
|
@@ -256,7 +256,7 @@ export declare const analyzeQueryResultSchema: v.ObjectType<{
|
|
|
256
256
|
attemptNumber?: number | undefined;
|
|
257
257
|
constraint?: Record<string, unknown> | null | undefined;
|
|
258
258
|
type: "node-constraint";
|
|
259
|
-
nodeType: "join" | "connection" | "fan-out" | "fan-in" | "terminus";
|
|
259
|
+
nodeType: "join" | "filter" | "connection" | "fan-out" | "fan-in" | "terminus";
|
|
260
260
|
node: string;
|
|
261
261
|
branchPattern: number[];
|
|
262
262
|
from: string;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"analyze-query-result.d.ts","sourceRoot":"","sources":["../../../../zero-protocol/src/analyze-query-result.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,CAAC,MAAM,4BAA4B,CAAC;AAKhD,eAAO,MAAM,sBAAsB,gCAAuB,CAAC;AAC3D,MAAM,MAAM,gBAAgB,GAAG,CAAC,CAAC,KAAK,CAAC,OAAO,sBAAsB,CAAC,CAAC;AAEtE,eAAO,MAAM,uBAAuB,gDAAmC,CAAC;AACxE,MAAM,MAAM,iBAAiB,GAAG,CAAC,CAAC,KAAK,CAAC,OAAO,uBAAuB,CAAC,CAAC;AAExE,eAAO,MAAM,iBAAiB,sHAA+B,CAAC;AAC9D,MAAM,MAAM,WAAW,GAAG,CAAC,CAAC,KAAK,CAAC,OAAO,iBAAiB,CAAC,CAAC;AAE5D,eAAO,MAAM,kBAAkB,sIAA8B,CAAC;AAC9D,MAAM,MAAM,YAAY,GAAG,CAAC,CAAC,KAAK,CAAC,OAAO,kBAAkB,CAAC,CAAC;AAe9D,QAAA,MAAM,2BAA2B;;;;aAI/B,CAAC;AAiBH,QAAA,MAAM,iCAAiC;;;;;;aAMrC,CAAC;AAiCH,QAAA,MAAM,yBAAyB;;;;aAI7B,CAAC;AAEH,QAAA,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6BAA6B,GAC9B,CAAC;AAEF,eAAO,MAAM,wBAAwB;;;;;IAKnC,8CAA8C;;;;IAI9C,2CAA2C;;IAE3C,+BAA+B;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;aAQ/B,CAAC;AAEH,MAAM,MAAM,kBAAkB,GAAG,CAAC,CAAC,KAAK,CAAC,OAAO,wBAAwB,CAAC,CAAC"}
|
|
@@ -74,7 +74,7 @@ var bestPlanSelectedEventJSONSchema = valita_exports.object({
|
|
|
74
74
|
type: joinTypeSchema
|
|
75
75
|
}))
|
|
76
76
|
});
|
|
77
|
-
var nodeTypeSchema = valita_exports.union(valita_exports.literal("connection"), valita_exports.literal("join"), valita_exports.literal("fan-out"), valita_exports.literal("fan-in"), valita_exports.literal("terminus"));
|
|
77
|
+
var nodeTypeSchema = valita_exports.union(valita_exports.literal("connection"), valita_exports.literal("join"), valita_exports.literal("fan-out"), valita_exports.literal("fan-in"), valita_exports.literal("filter"), valita_exports.literal("terminus"));
|
|
78
78
|
var nodeCostEventJSONSchema = valita_exports.object({
|
|
79
79
|
type: valita_exports.literal("node-cost"),
|
|
80
80
|
attemptNumber: valita_exports.number().optional(),
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"analyze-query-result.js","names":[],"sources":["../../../../zero-protocol/src/analyze-query-result.ts"],"sourcesContent":["import * as v from '../../shared/src/valita.ts';\n\nimport {conditionSchema, orderingSchema} from './ast.ts';\nimport {rowSchema} from './data.ts';\n\nexport const rowCountsByQuerySchema = v.record(v.number());\nexport type RowCountsByQuery = v.Infer<typeof rowCountsByQuerySchema>;\n\nexport const rowCountsBySourceSchema = v.record(rowCountsByQuerySchema);\nexport type RowCountsBySource = v.Infer<typeof rowCountsBySourceSchema>;\n\nexport const rowsByQuerySchema = v.record(v.array(rowSchema));\nexport type RowsByQuery = v.Infer<typeof rowsByQuerySchema>;\n\nexport const rowsBySourceSchema = v.record(rowsByQuerySchema);\nexport type RowsBySource = v.Infer<typeof rowsBySourceSchema>;\n\n// Planner debug event schemas\n\nconst costEstimateJSONSchema = v.object({\n startupCost: v.number(),\n scanEst: v.number(),\n cost: v.number(),\n returnedRows: v.number(),\n selectivity: v.number(),\n limit: v.number().optional(),\n});\n\nconst plannerConstraintSchema = v.record(v.union(v.unknown(), v.null()));\n\nconst attemptStartEventJSONSchema = v.object({\n type: v.literal('attempt-start'),\n attemptNumber: v.number(),\n totalAttempts: v.number(),\n});\n\nconst connectionCostsEventJSONSchema = v.object({\n type: v.literal('connection-costs'),\n attemptNumber: v.number(),\n costs: v.array(\n v.object({\n connection: v.string(),\n cost: v.number(),\n costEstimate: costEstimateJSONSchema,\n pinned: v.boolean(),\n constraints: v.record(v.union(plannerConstraintSchema, v.null())),\n constraintCosts: v.record(costEstimateJSONSchema),\n }),\n ),\n});\n\nconst connectionSelectedEventJSONSchema = v.object({\n type: v.literal('connection-selected'),\n attemptNumber: v.number(),\n connection: v.string(),\n cost: v.number(),\n isRoot: v.boolean(),\n});\n\nconst constraintsPropagatedEventJSONSchema = v.object({\n type: v.literal('constraints-propagated'),\n attemptNumber: v.number(),\n connectionConstraints: v.array(\n v.object({\n connection: v.string(),\n constraints: v.record(v.union(plannerConstraintSchema, v.null())),\n constraintCosts: v.record(costEstimateJSONSchema),\n }),\n ),\n});\n\nconst joinTypeSchema = v.union(\n v.literal('semi'),\n v.literal('flipped'),\n v.literal('unflippable'),\n);\n\nconst planCompleteEventJSONSchema = v.object({\n type: v.literal('plan-complete'),\n attemptNumber: v.number(),\n totalCost: v.number(),\n flipPattern: v.number(),\n joinStates: v.array(\n v.object({\n join: v.string(),\n type: joinTypeSchema,\n }),\n ),\n});\n\nconst planFailedEventJSONSchema = v.object({\n type: v.literal('plan-failed'),\n attemptNumber: v.number(),\n reason: v.string(),\n});\n\nconst bestPlanSelectedEventJSONSchema = v.object({\n type: v.literal('best-plan-selected'),\n bestAttemptNumber: v.number(),\n totalCost: v.number(),\n flipPattern: v.number(),\n joinStates: v.array(\n v.object({\n join: v.string(),\n type: joinTypeSchema,\n }),\n ),\n});\n\nconst nodeTypeSchema = v.union(\n v.literal('connection'),\n v.literal('join'),\n v.literal('fan-out'),\n v.literal('fan-in'),\n v.literal('terminus'),\n);\n\nconst nodeCostEventJSONSchema = v.object({\n type: v.literal('node-cost'),\n attemptNumber: v.number().optional(),\n nodeType: nodeTypeSchema,\n node: v.string(),\n branchPattern: v.array(v.number()),\n downstreamChildSelectivity: v.number(),\n costEstimate: costEstimateJSONSchema,\n filters: conditionSchema.optional(),\n ordering: orderingSchema.optional(),\n joinType: joinTypeSchema.optional(),\n});\n\nconst nodeConstraintEventJSONSchema = v.object({\n type: v.literal('node-constraint'),\n attemptNumber: v.number().optional(),\n nodeType: nodeTypeSchema,\n node: v.string(),\n branchPattern: v.array(v.number()),\n constraint: v.union(plannerConstraintSchema, v.null()).optional(),\n from: v.string(),\n});\n\nconst planDebugEventJSONSchema = v.union(\n attemptStartEventJSONSchema,\n connectionCostsEventJSONSchema,\n connectionSelectedEventJSONSchema,\n constraintsPropagatedEventJSONSchema,\n planCompleteEventJSONSchema,\n planFailedEventJSONSchema,\n bestPlanSelectedEventJSONSchema,\n nodeCostEventJSONSchema,\n nodeConstraintEventJSONSchema,\n);\n\nexport type PlanDebugEventJSON = v.Infer<typeof planDebugEventJSONSchema>;\n\nexport {\n attemptStartEventJSONSchema,\n connectionSelectedEventJSONSchema,\n planFailedEventJSONSchema,\n bestPlanSelectedEventJSONSchema,\n nodeConstraintEventJSONSchema,\n};\n\nexport const analyzeQueryResultSchema = v.object({\n warnings: v.array(v.string()),\n syncedRows: v.record(v.array(rowSchema)).optional(),\n syncedRowCount: v.number(),\n start: v.number(),\n /** @deprecated Use start + elapsed instead */\n end: v.number(),\n elapsed: v.number().optional(),\n afterPermissions: v.string().optional(),\n /** @deprecated Use readRowCountsByQuery */\n vendedRowCounts: rowCountsBySourceSchema.optional(),\n /** @deprecated Use readRows */\n vendedRows: rowsBySourceSchema.optional(),\n sqlitePlans: v.record(v.array(v.string())).optional(),\n readRows: rowsBySourceSchema.optional(),\n readRowCountsByQuery: rowCountsBySourceSchema.optional(),\n readRowCount: v.number().optional(),\n dbScansByQuery: rowCountsBySourceSchema.optional(),\n joinPlans: v.array(planDebugEventJSONSchema).optional(),\n});\n\nexport type AnalyzeQueryResult = v.Infer<typeof analyzeQueryResultSchema>;\n"],"mappings":";;;;AAKA,IAAa,yBAAyB,eAAE,OAAO,eAAE,OAAO,CAAC;AAGzD,IAAa,0BAA0B,eAAE,OAAO,sBAAsB;AAGtE,IAAa,oBAAoB,eAAE,OAAO,eAAE,MAAM,SAAS,CAAC;AAG5D,IAAa,qBAAqB,eAAE,OAAO,iBAAiB;AAK5D,IAAM,yBAAyB,eAAE,OAAO;CACtC,aAAa,eAAE,OAAO;CACtB,SAAS,eAAE,OAAO;CAClB,MAAM,eAAE,OAAO;CACf,cAAc,eAAE,OAAO;CACvB,aAAa,eAAE,OAAO;CACtB,OAAO,eAAE,OAAO,EAAE,SAAS;AAC7B,CAAC;AAED,IAAM,0BAA0B,eAAE,OAAO,eAAE,MAAM,eAAE,QAAQ,GAAG,eAAE,KAAK,CAAC,CAAC;AAEvE,IAAM,8BAA8B,eAAE,OAAO;CAC3C,MAAM,eAAE,QAAQ,eAAe;CAC/B,eAAe,eAAE,OAAO;CACxB,eAAe,eAAE,OAAO;AAC1B,CAAC;AAED,IAAM,iCAAiC,eAAE,OAAO;CAC9C,MAAM,eAAE,QAAQ,kBAAkB;CAClC,eAAe,eAAE,OAAO;CACxB,OAAO,eAAE,MACP,eAAE,OAAO;EACP,YAAY,eAAE,OAAO;EACrB,MAAM,eAAE,OAAO;EACf,cAAc;EACd,QAAQ,eAAE,QAAQ;EAClB,aAAa,eAAE,OAAO,eAAE,MAAM,yBAAyB,eAAE,KAAK,CAAC,CAAC;EAChE,iBAAiB,eAAE,OAA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AS;CACtC,sBAAsB,wBAAwB,SAAS;CACvD,cAAc,eAAE,OAAO,EAAE,SAAS;CAClC,gBAAgB,wBAAwB,SAAS;CACjD,WAAW,eAAE,MAAM,wBAAwB,EAAE,SAAS;AACxD,CAAC"}
|
|
1
|
+
{"version":3,"file":"analyze-query-result.js","names":[],"sources":["../../../../zero-protocol/src/analyze-query-result.ts"],"sourcesContent":["import * as v from '../../shared/src/valita.ts';\n\nimport {conditionSchema, orderingSchema} from './ast.ts';\nimport {rowSchema} from './data.ts';\n\nexport const rowCountsByQuerySchema = v.record(v.number());\nexport type RowCountsByQuery = v.Infer<typeof rowCountsByQuerySchema>;\n\nexport const rowCountsBySourceSchema = v.record(rowCountsByQuerySchema);\nexport type RowCountsBySource = v.Infer<typeof rowCountsBySourceSchema>;\n\nexport const rowsByQuerySchema = v.record(v.array(rowSchema));\nexport type RowsByQuery = v.Infer<typeof rowsByQuerySchema>;\n\nexport const rowsBySourceSchema = v.record(rowsByQuerySchema);\nexport type RowsBySource = v.Infer<typeof rowsBySourceSchema>;\n\n// Planner debug event schemas\n\nconst costEstimateJSONSchema = v.object({\n startupCost: v.number(),\n scanEst: v.number(),\n cost: v.number(),\n returnedRows: v.number(),\n selectivity: v.number(),\n limit: v.number().optional(),\n});\n\nconst plannerConstraintSchema = v.record(v.union(v.unknown(), v.null()));\n\nconst attemptStartEventJSONSchema = v.object({\n type: v.literal('attempt-start'),\n attemptNumber: v.number(),\n totalAttempts: v.number(),\n});\n\nconst connectionCostsEventJSONSchema = v.object({\n type: v.literal('connection-costs'),\n attemptNumber: v.number(),\n costs: v.array(\n v.object({\n connection: v.string(),\n cost: v.number(),\n costEstimate: costEstimateJSONSchema,\n pinned: v.boolean(),\n constraints: v.record(v.union(plannerConstraintSchema, v.null())),\n constraintCosts: v.record(costEstimateJSONSchema),\n }),\n ),\n});\n\nconst connectionSelectedEventJSONSchema = v.object({\n type: v.literal('connection-selected'),\n attemptNumber: v.number(),\n connection: v.string(),\n cost: v.number(),\n isRoot: v.boolean(),\n});\n\nconst constraintsPropagatedEventJSONSchema = v.object({\n type: v.literal('constraints-propagated'),\n attemptNumber: v.number(),\n connectionConstraints: v.array(\n v.object({\n connection: v.string(),\n constraints: v.record(v.union(plannerConstraintSchema, v.null())),\n constraintCosts: v.record(costEstimateJSONSchema),\n }),\n ),\n});\n\nconst joinTypeSchema = v.union(\n v.literal('semi'),\n v.literal('flipped'),\n v.literal('unflippable'),\n);\n\nconst planCompleteEventJSONSchema = v.object({\n type: v.literal('plan-complete'),\n attemptNumber: v.number(),\n totalCost: v.number(),\n flipPattern: v.number(),\n joinStates: v.array(\n v.object({\n join: v.string(),\n type: joinTypeSchema,\n }),\n ),\n});\n\nconst planFailedEventJSONSchema = v.object({\n type: v.literal('plan-failed'),\n attemptNumber: v.number(),\n reason: v.string(),\n});\n\nconst bestPlanSelectedEventJSONSchema = v.object({\n type: v.literal('best-plan-selected'),\n bestAttemptNumber: v.number(),\n totalCost: v.number(),\n flipPattern: v.number(),\n joinStates: v.array(\n v.object({\n join: v.string(),\n type: joinTypeSchema,\n }),\n ),\n});\n\nconst nodeTypeSchema = v.union(\n v.literal('connection'),\n v.literal('join'),\n v.literal('fan-out'),\n v.literal('fan-in'),\n v.literal('filter'),\n v.literal('terminus'),\n);\n\nconst nodeCostEventJSONSchema = v.object({\n type: v.literal('node-cost'),\n attemptNumber: v.number().optional(),\n nodeType: nodeTypeSchema,\n node: v.string(),\n branchPattern: v.array(v.number()),\n downstreamChildSelectivity: v.number(),\n costEstimate: costEstimateJSONSchema,\n filters: conditionSchema.optional(),\n ordering: orderingSchema.optional(),\n joinType: joinTypeSchema.optional(),\n});\n\nconst nodeConstraintEventJSONSchema = v.object({\n type: v.literal('node-constraint'),\n attemptNumber: v.number().optional(),\n nodeType: nodeTypeSchema,\n node: v.string(),\n branchPattern: v.array(v.number()),\n constraint: v.union(plannerConstraintSchema, v.null()).optional(),\n from: v.string(),\n});\n\nconst planDebugEventJSONSchema = v.union(\n attemptStartEventJSONSchema,\n connectionCostsEventJSONSchema,\n connectionSelectedEventJSONSchema,\n constraintsPropagatedEventJSONSchema,\n planCompleteEventJSONSchema,\n planFailedEventJSONSchema,\n bestPlanSelectedEventJSONSchema,\n nodeCostEventJSONSchema,\n nodeConstraintEventJSONSchema,\n);\n\nexport type PlanDebugEventJSON = v.Infer<typeof planDebugEventJSONSchema>;\n\nexport {\n attemptStartEventJSONSchema,\n connectionSelectedEventJSONSchema,\n planFailedEventJSONSchema,\n bestPlanSelectedEventJSONSchema,\n nodeConstraintEventJSONSchema,\n};\n\nexport const analyzeQueryResultSchema = v.object({\n warnings: v.array(v.string()),\n syncedRows: v.record(v.array(rowSchema)).optional(),\n syncedRowCount: v.number(),\n start: v.number(),\n /** @deprecated Use start + elapsed instead */\n end: v.number(),\n elapsed: v.number().optional(),\n afterPermissions: v.string().optional(),\n /** @deprecated Use readRowCountsByQuery */\n vendedRowCounts: rowCountsBySourceSchema.optional(),\n /** @deprecated Use readRows */\n vendedRows: rowsBySourceSchema.optional(),\n sqlitePlans: v.record(v.array(v.string())).optional(),\n readRows: rowsBySourceSchema.optional(),\n readRowCountsByQuery: rowCountsBySourceSchema.optional(),\n readRowCount: v.number().optional(),\n dbScansByQuery: rowCountsBySourceSchema.optional(),\n joinPlans: v.array(planDebugEventJSONSchema).optional(),\n});\n\nexport type AnalyzeQueryResult = v.Infer<typeof analyzeQueryResultSchema>;\n"],"mappings":";;;;AAKA,IAAa,yBAAyB,eAAE,OAAO,eAAE,OAAO,CAAC;AAGzD,IAAa,0BAA0B,eAAE,OAAO,sBAAsB;AAGtE,IAAa,oBAAoB,eAAE,OAAO,eAAE,MAAM,SAAS,CAAC;AAG5D,IAAa,qBAAqB,eAAE,OAAO,iBAAiB;AAK5D,IAAM,yBAAyB,eAAE,OAAO;CACtC,aAAa,eAAE,OAAO;CACtB,SAAS,eAAE,OAAO;CAClB,MAAM,eAAE,OAAO;CACf,cAAc,eAAE,OAAO;CACvB,aAAa,eAAE,OA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,eAAE,KAAK,CAAC,EAAE,SAAS;CAChE,MAAM,eAAE,OAAO;AACjB,CAAC;AAED,IAAM,2BAA2B,eAAE,MACjC,6BACA,gCACA,mCACA,sCACA,6BACA,2BACA,iCACA,yBACA,6BACF;AAYA,IAAa,2BAA2B,eAAE,OAAO;CAC/C,UAAU,eAAE,MAAM,eAAE,OAAO,CAAC;CAC5B,YAAY,eAAE,OAAO,eAAE,MAAM,SAAS,CAAC,EAAE,SAAS;CAClD,gBAAgB,eAAE,OAAO;CACzB,OAAO,eAAE,OAAO;;CAEhB,KAAK,eAAE,OAAO;CACd,SAAS,eAAE,OAAO,EAAE,SAAS;CAC7B,kBAAkB,eAAE,OAAO,EAAE,SAAS;;CAEtC,iBAAiB,wBAAwB,SAAS;;CAElD,YAAY,mBAAmB,SAAS;CACxC,aAAa,eAAE,OAAO,eAAE,MAAM,eAAE,OAAO,CAAC,CAAC,EAAE,SAAS;CACpD,UAAU,mBAAmB,SAAS;CACtC,sBAAsB,wBAAwB,SAAS;CACvD,cAAc,eAAE,OAAO,EAAE,SAAS;CAClC,gBAAgB,wBAAwB,SAAS;CACjD,WAAW,eAAE,MAAM,wBAAwB,EAAE,SAAS;AACxD,CAAC"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"ast.d.ts","sourceRoot":"","sources":["../../../../zero-protocol/src/ast.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;
|
|
1
|
+
{"version":3,"file":"ast.d.ts","sourceRoot":"","sources":["../../../../zero-protocol/src/ast.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AAMH,OAAO,KAAK,CAAC,MAAM,4BAA4B,CAAC;AAChD,OAAO,KAAK,EAAC,UAAU,EAAC,MAAM,qCAAqC,CAAC;AACpE,OAAO,EAAY,KAAK,GAAG,EAAC,MAAM,WAAW,CAAC;AAE9C,eAAO,MAAM,WAAW,WAAW,CAAC;AAEpC,eAAO,MAAM,cAAc,gBAAa,CAAC;AACzC,eAAO,MAAM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B,GAC1B,QAAQ,CAAC,kBAAkB,CAAC,CAW9B;AAaD;;;;;;;;;;;GAWG;AACH,wBAAgB,kBAAkB,CAAC,IAAI,EAAE,SAAS,GAAG,SAAS,CAiD7D;AAED;;;;GAIG;AACH,wBAAgB,MAAM,CAAC,GAAG,EAAE,GAAG,EAAE,MAAM,EAAE,UAAU,iBAKlD;AAED,wBAAgB,YAAY,CAC1B,IAAI,EAAE,SAAS,EACf,KAAK,EAAE,MAAM,EACb,MAAM,EAAE,UAAU,aAMnB"}
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { assert } from "../../shared/src/asserts.js";
|
|
2
2
|
import { literalUnion, readonly, readonlyArray, readonlyObject, valita_exports } from "../../shared/src/valita.js";
|
|
3
|
+
import { getOrInsertComputed } from "../../shared/src/map.js";
|
|
3
4
|
import { must } from "../../shared/src/must.js";
|
|
4
5
|
import { rowSchema } from "./data.js";
|
|
5
6
|
import { compareUTF8 } from "compare-utf8";
|
|
@@ -167,20 +168,18 @@ function asNormalized(ast) {
|
|
|
167
168
|
}
|
|
168
169
|
var normalizeCache = /* @__PURE__ */ new WeakMap();
|
|
169
170
|
function normalizeAST(ast) {
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
})
|
|
181
|
-
|
|
182
|
-
}
|
|
183
|
-
return normalized;
|
|
171
|
+
return getOrInsertComputed(normalizeCache, ast, normalizeASTUncached);
|
|
172
|
+
}
|
|
173
|
+
function normalizeASTUncached(ast) {
|
|
174
|
+
const { where, related } = ast;
|
|
175
|
+
return normalizedAST({
|
|
176
|
+
...ast,
|
|
177
|
+
where: where && normalizeSubqueries(where),
|
|
178
|
+
related: related?.map((r) => normalizedRelated({
|
|
179
|
+
...r,
|
|
180
|
+
subquery: normalizeAST(r.subquery)
|
|
181
|
+
}))
|
|
182
|
+
});
|
|
184
183
|
}
|
|
185
184
|
/**
|
|
186
185
|
* Normalizes the ASTs of the correlated subqueries of `cond`. The condition
|