@rocicorp/zero 1.12.0 → 1.13.0-canary.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/out/shared/src/bigint-json.d.ts +6 -0
- package/out/shared/src/bigint-json.d.ts.map +1 -1
- package/out/shared/src/bigint-json.js +14 -1
- package/out/shared/src/bigint-json.js.map +1 -1
- package/out/shared/src/objects.d.ts +7 -0
- package/out/shared/src/objects.d.ts.map +1 -1
- package/out/shared/src/objects.js +10 -1
- package/out/shared/src/objects.js.map +1 -1
- package/out/shared/src/resolver.d.ts.map +1 -1
- package/out/shared/src/resolver.js +12 -1
- package/out/shared/src/resolver.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.js +4 -3
- package/out/zero-cache/src/auth/write-authorizer.js.map +1 -1
- package/out/zero-cache/src/config/normalize.d.ts.map +1 -1
- package/out/zero-cache/src/config/normalize.js +3 -23
- package/out/zero-cache/src/config/normalize.js.map +1 -1
- package/out/zero-cache/src/config/zero-config.d.ts +1 -27
- package/out/zero-cache/src/config/zero-config.d.ts.map +1 -1
- package/out/zero-cache/src/config/zero-config.js +19 -47
- package/out/zero-cache/src/config/zero-config.js.map +1 -1
- package/out/zero-cache/src/custom/fetch.js +17 -2
- package/out/zero-cache/src/custom/fetch.js.map +1 -1
- package/out/zero-cache/src/db/create.js +45 -1
- package/out/zero-cache/src/db/create.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 +4 -3
- package/out/zero-cache/src/db/lite-tables.js.map +1 -1
- package/out/zero-cache/src/db/pg-copy-binary.js +61 -25
- package/out/zero-cache/src/db/pg-copy-binary.js.map +1 -1
- package/out/zero-cache/src/db/pg-to-lite.d.ts +17 -0
- package/out/zero-cache/src/db/pg-to-lite.d.ts.map +1 -1
- package/out/zero-cache/src/db/pg-to-lite.js +84 -1
- package/out/zero-cache/src/db/pg-to-lite.js.map +1 -1
- package/out/zero-cache/src/server/change-streamer.js +21 -30
- package/out/zero-cache/src/server/change-streamer.js.map +1 -1
- package/out/zero-cache/src/server/main.js +0 -1
- package/out/zero-cache/src/server/main.js.map +1 -1
- package/out/zero-cache/src/server/replicator.js +1 -1
- package/out/zero-cache/src/server/replicator.js.map +1 -1
- package/out/zero-cache/src/services/change-source/pg/backfill-stream.js +6 -5
- package/out/zero-cache/src/services/change-source/pg/backfill-stream.js.map +1 -1
- package/out/zero-cache/src/services/change-source/pg/change-source.js +49 -11
- package/out/zero-cache/src/services/change-source/pg/change-source.js.map +1 -1
- package/out/zero-cache/src/services/change-source/pg/initial-sync.js +64 -21
- package/out/zero-cache/src/services/change-source/pg/initial-sync.js.map +1 -1
- package/out/zero-cache/src/services/change-source/pg/replication-slots.js +11 -6
- package/out/zero-cache/src/services/change-source/pg/replication-slots.js.map +1 -1
- package/out/zero-cache/src/services/change-source/pg/schema/ddl.d.ts +13 -1
- package/out/zero-cache/src/services/change-source/pg/schema/ddl.d.ts.map +1 -1
- package/out/zero-cache/src/services/change-source/pg/schema/ddl.js +16 -3
- package/out/zero-cache/src/services/change-source/pg/schema/ddl.js.map +1 -1
- package/out/zero-cache/src/services/change-source/pg/schema/init.js +59 -3
- package/out/zero-cache/src/services/change-source/pg/schema/init.js.map +1 -1
- package/out/zero-cache/src/services/change-source/pg/schema/published.d.ts +1 -0
- package/out/zero-cache/src/services/change-source/pg/schema/published.d.ts.map +1 -1
- package/out/zero-cache/src/services/change-source/pg/schema/published.js +56 -12
- package/out/zero-cache/src/services/change-source/pg/schema/published.js.map +1 -1
- package/out/zero-cache/src/services/change-source/pg/schema/shard.d.ts +1 -0
- package/out/zero-cache/src/services/change-source/pg/schema/shard.d.ts.map +1 -1
- package/out/zero-cache/src/services/change-source/pg/schema/shard.js +35 -12
- package/out/zero-cache/src/services/change-source/pg/schema/shard.js.map +1 -1
- package/out/zero-cache/src/services/change-source/pg/schema/validation.d.ts +6 -1
- package/out/zero-cache/src/services/change-source/pg/schema/validation.d.ts.map +1 -1
- package/out/zero-cache/src/services/change-source/pg/schema/validation.js +25 -1
- package/out/zero-cache/src/services/change-source/pg/schema/validation.js.map +1 -1
- package/out/zero-cache/src/services/change-source/protocol/backfill-progress.js +6 -5
- package/out/zero-cache/src/services/change-source/protocol/backfill-progress.js.map +1 -1
- package/out/zero-cache/src/services/change-streamer/backfill-state.js +7 -6
- package/out/zero-cache/src/services/change-streamer/backfill-state.js.map +1 -1
- package/out/zero-cache/src/services/change-streamer/change-log-codec.js +2 -2
- package/out/zero-cache/src/services/change-streamer/change-log-codec.js.map +1 -1
- package/out/zero-cache/src/services/change-streamer/change-log-initializer.js +16 -199
- package/out/zero-cache/src/services/change-streamer/change-log-initializer.js.map +1 -1
- package/out/zero-cache/src/services/change-streamer/change-streamer-service.js +76 -127
- package/out/zero-cache/src/services/change-streamer/change-streamer-service.js.map +1 -1
- package/out/zero-cache/src/services/change-streamer/snapshot-reservations.js +1 -1
- package/out/zero-cache/src/services/change-streamer/snapshot-reservations.js.map +1 -1
- package/out/zero-cache/src/services/change-streamer/sqlite-change-log-catchup.js.map +1 -1
- package/out/zero-cache/src/services/change-streamer/sqlite-change-log-purge-scheduler.js +1 -1
- package/out/zero-cache/src/services/change-streamer/sqlite-change-log-read-router.js +15 -49
- package/out/zero-cache/src/services/change-streamer/sqlite-change-log-read-router.js.map +1 -1
- package/out/zero-cache/src/services/change-streamer/sqlite-change-log-reader.js +8 -2
- package/out/zero-cache/src/services/change-streamer/sqlite-change-log-reader.js.map +1 -1
- package/out/zero-cache/src/services/change-streamer/sqlite-change-log-writer.js +20 -36
- package/out/zero-cache/src/services/change-streamer/sqlite-change-log-writer.js.map +1 -1
- package/out/zero-cache/src/services/change-streamer/storer.js +32 -20
- package/out/zero-cache/src/services/change-streamer/storer.js.map +1 -1
- package/out/zero-cache/src/services/mutagen/mutagen.js +4 -2
- package/out/zero-cache/src/services/mutagen/mutagen.js.map +1 -1
- package/out/zero-cache/src/services/replicator/change-log-cookies.d.ts +0 -16
- package/out/zero-cache/src/services/replicator/change-log-cookies.d.ts.map +1 -1
- package/out/zero-cache/src/services/replicator/change-log-cookies.js +3 -95
- package/out/zero-cache/src/services/replicator/change-log-cookies.js.map +1 -1
- package/out/zero-cache/src/services/replicator/change-log-db.js +2 -2
- package/out/zero-cache/src/services/replicator/change-log-db.js.map +1 -1
- package/out/zero-cache/src/services/replicator/change-log-stream-writer.js +1 -30
- package/out/zero-cache/src/services/replicator/change-log-stream-writer.js.map +1 -1
- package/out/zero-cache/src/services/replicator/change-processor.js +82 -9
- package/out/zero-cache/src/services/replicator/change-processor.js.map +1 -1
- package/out/zero-cache/src/services/replicator/incremental-sync.js +7 -1
- package/out/zero-cache/src/services/replicator/incremental-sync.js.map +1 -1
- package/out/zero-cache/src/services/replicator/reporter/report-schema.d.ts +1 -0
- package/out/zero-cache/src/services/replicator/reporter/report-schema.d.ts.map +1 -1
- package/out/zero-cache/src/services/replicator/reporter/report-schema.js +4 -1
- package/out/zero-cache/src/services/replicator/reporter/report-schema.js.map +1 -1
- package/out/zero-cache/src/services/replicator/schema/change-log.d.ts.map +1 -1
- package/out/zero-cache/src/services/replicator/schema/change-log.js +2 -1
- package/out/zero-cache/src/services/replicator/schema/change-log.js.map +1 -1
- package/out/zero-cache/src/services/replicator/sqlite-change-log-observability.js +6 -102
- package/out/zero-cache/src/services/replicator/sqlite-change-log-observability.js.map +1 -1
- package/out/zero-cache/src/services/statz.d.ts.map +1 -1
- package/out/zero-cache/src/services/statz.js +1 -1
- package/out/zero-cache/src/services/statz.js.map +1 -1
- package/out/zero-cache/src/services/view-syncer/schema/init.js +3 -0
- package/out/zero-cache/src/services/view-syncer/schema/init.js.map +1 -1
- package/out/zero-cache/src/services/view-syncer/snapshot-row-cache.js +47 -3
- package/out/zero-cache/src/services/view-syncer/snapshot-row-cache.js.map +1 -1
- package/out/zero-cache/src/services/view-syncer/view-syncer.js +51 -6
- package/out/zero-cache/src/services/view-syncer/view-syncer.js.map +1 -1
- package/out/zero-cache/src/types/lite.d.ts +7 -0
- package/out/zero-cache/src/types/lite.d.ts.map +1 -1
- package/out/zero-cache/src/types/lite.js +12 -2
- package/out/zero-cache/src/types/lite.js.map +1 -1
- package/out/zero-cache/src/types/pg-types.d.ts +2 -1
- package/out/zero-cache/src/types/pg-types.d.ts.map +1 -1
- package/out/zero-cache/src/types/pg-types.js +2 -1
- package/out/zero-cache/src/types/pg-types.js.map +1 -1
- package/out/zero-cache/src/types/pg.d.ts +20 -0
- package/out/zero-cache/src/types/pg.d.ts.map +1 -1
- package/out/zero-cache/src/types/pg.js +64 -27
- package/out/zero-cache/src/types/pg.js.map +1 -1
- package/out/zero-cache/src/types/streams.d.ts +2 -0
- package/out/zero-cache/src/types/streams.d.ts.map +1 -1
- package/out/zero-cache/src/types/streams.js +2 -1
- package/out/zero-cache/src/types/streams.js.map +1 -1
- package/out/zero-cache/src/workers/replicator.js +7 -6
- package/out/zero-cache/src/workers/replicator.js.map +1 -1
- package/out/zero-cache/src/workers/syncer.js +18 -1
- package/out/zero-cache/src/workers/syncer.js.map +1 -1
- package/out/zero-client/src/client/version.js +1 -1
- package/out/zqlite/src/db.js +4 -1
- package/out/zqlite/src/db.js.map +1 -1
- package/package.json +1 -1
- package/out/zero-cache/src/services/change-streamer/change-log-compare-digest.js +0 -67
- package/out/zero-cache/src/services/change-streamer/change-log-compare-digest.js.map +0 -1
- package/out/zero-cache/src/services/change-streamer/change-log-transaction-hash.js +0 -39
- package/out/zero-cache/src/services/change-streamer/change-log-transaction-hash.js.map +0 -1
- package/out/zero-cache/src/services/change-streamer/shard-sampling.js +0 -19
- package/out/zero-cache/src/services/change-streamer/shard-sampling.js.map +0 -1
- package/out/zero-cache/src/services/change-streamer/sqlite-change-log-comparator.js +0 -417
- package/out/zero-cache/src/services/change-streamer/sqlite-change-log-comparator.js.map +0 -1
|
@@ -16,6 +16,36 @@ import { RingBuffer } from "../../../../shared/src/ring-buffer.js";
|
|
|
16
16
|
*/
|
|
17
17
|
var DEFAULT_MAX_SNAPSHOT_ROW_CACHE_ENTRIES = 5e4;
|
|
18
18
|
/**
|
|
19
|
+
* The maximum approximate size of the rows retained by a
|
|
20
|
+
* {@link SnapshotRowCache}, in string characters and blob bytes.
|
|
21
|
+
*
|
|
22
|
+
* The entry count alone does not bound memory: each update of a row adds
|
|
23
|
+
* entries for the new version of the row, so a large row (e.g. one with a
|
|
24
|
+
* large JSON column) that is updated many times a second fills the heap long
|
|
25
|
+
* before the entry limit is reached.
|
|
26
|
+
*/
|
|
27
|
+
var MAX_SNAPSHOT_ROW_CACHE_BYTES = 67108864;
|
|
28
|
+
/**
|
|
29
|
+
* Approximates the memory retained by a cached value, which is a raw SQLite
|
|
30
|
+
* row or an array of them. Only strings and blobs are measured exactly, as
|
|
31
|
+
* they are the values that can be large.
|
|
32
|
+
*/
|
|
33
|
+
function approximateSize(value) {
|
|
34
|
+
if (typeof value === "string") return value.length;
|
|
35
|
+
if (value instanceof Uint8Array) return value.byteLength;
|
|
36
|
+
if (Array.isArray(value)) {
|
|
37
|
+
let size = 0;
|
|
38
|
+
for (const row of value) size += approximateSize(row);
|
|
39
|
+
return size;
|
|
40
|
+
}
|
|
41
|
+
if (typeof value === "object" && value !== null) {
|
|
42
|
+
let size = 0;
|
|
43
|
+
for (const col in value) size += approximateSize(value[col]);
|
|
44
|
+
return size;
|
|
45
|
+
}
|
|
46
|
+
return 8;
|
|
47
|
+
}
|
|
48
|
+
/**
|
|
19
49
|
* Serializes a lookup key value (i.e. a SQLite-bound parameter). Numbers and
|
|
20
50
|
* bigints serialize identically, as row keys parsed from the change log are
|
|
21
51
|
* JSON numbers whereas the values read from SQLite are bigints; both address
|
|
@@ -75,7 +105,9 @@ var MISS = { result: "miss" };
|
|
|
75
105
|
*
|
|
76
106
|
* ### Eviction
|
|
77
107
|
*
|
|
78
|
-
* The cache is bounded by entry count and
|
|
108
|
+
* The cache is bounded by entry count and by the approximate size of its
|
|
109
|
+
* rows (see {@link MAX_SNAPSHOT_ROW_CACHE_BYTES}), and evicts in insertion
|
|
110
|
+
* (FIFO) order
|
|
79
111
|
* rather than by recency. Diffs are traversed in change log order by every
|
|
80
112
|
* client group, so the entries that will not be needed again are those that
|
|
81
113
|
* were inserted the earliest (all groups have moved past them), while the
|
|
@@ -92,12 +124,16 @@ var SnapshotRowCache = class {
|
|
|
92
124
|
#maxEntries;
|
|
93
125
|
#entries = /* @__PURE__ */ new Map();
|
|
94
126
|
#keys = new RingBuffer();
|
|
127
|
+
#sizes = new RingBuffer();
|
|
128
|
+
#maxBytes;
|
|
129
|
+
#bytes = 0;
|
|
95
130
|
#sqlIDs = /* @__PURE__ */ new Map();
|
|
96
131
|
#reads = getOrCreateCounter("sync", "ivm.snapshot-row-reads", "Row reads performed while computing snapshot diffs for IVM, labeled by whether the read was served by the worker-wide snapshot row cache.");
|
|
97
132
|
#hits = 0;
|
|
98
133
|
#misses = 0;
|
|
99
|
-
constructor(maxEntries = DEFAULT_MAX_SNAPSHOT_ROW_CACHE_ENTRIES) {
|
|
134
|
+
constructor(maxEntries = DEFAULT_MAX_SNAPSHOT_ROW_CACHE_ENTRIES, maxBytes = MAX_SNAPSHOT_ROW_CACHE_BYTES) {
|
|
100
135
|
this.#maxEntries = Math.max(0, maxEntries);
|
|
136
|
+
this.#maxBytes = maxBytes;
|
|
101
137
|
}
|
|
102
138
|
get size() {
|
|
103
139
|
return this.#entries.size;
|
|
@@ -136,13 +172,21 @@ var SnapshotRowCache = class {
|
|
|
136
172
|
if (value !== void 0 && this.#maxEntries > 0) {
|
|
137
173
|
this.#entries.set(key, value);
|
|
138
174
|
this.#keys.push(key);
|
|
139
|
-
|
|
175
|
+
const size = approximateSize(value);
|
|
176
|
+
this.#sizes.push(size);
|
|
177
|
+
this.#bytes += size;
|
|
178
|
+
while (this.#keys.size > this.#maxEntries || this.#bytes > this.#maxBytes) {
|
|
179
|
+
this.#entries.delete(must(this.#keys.shift()));
|
|
180
|
+
this.#bytes -= must(this.#sizes.shift());
|
|
181
|
+
}
|
|
140
182
|
}
|
|
141
183
|
return value;
|
|
142
184
|
}
|
|
143
185
|
clear() {
|
|
144
186
|
this.#entries.clear();
|
|
145
187
|
this.#keys.clear();
|
|
188
|
+
this.#sizes.clear();
|
|
189
|
+
this.#bytes = 0;
|
|
146
190
|
this.#sqlIDs.clear();
|
|
147
191
|
}
|
|
148
192
|
#key(tag, sql, mode, args) {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"snapshot-row-cache.js","names":[],"sources":["../../../../../../zero-cache/src/services/view-syncer/snapshot-row-cache.ts"],"sourcesContent":["import {stringify} from '../../../../shared/src/bigint-json.ts';\nimport {getOrInsert} from '../../../../shared/src/map.ts';\nimport {must} from '../../../../shared/src/must.ts';\nimport {RingBuffer} from '../../../../shared/src/ring-buffer.ts';\nimport {getOrCreateCounter} from '../../observability/metrics.ts';\n\n/**\n * The default maximum number of entries retained by a {@link SnapshotRowCache}.\n *\n * Each entry is a raw SQLite row (or the list of rows conflicting with\n * a row on its unique keys) read while computing a snapshot diff. A\n * replicated transaction of N rows produces up to 2N entries (the new value\n * and the previous value(s) of each row), so the cache should be large enough\n * to hold the largest transactions that are commonly replicated in order for\n * all of the client groups on a worker to share the reads.\n */\nexport const DEFAULT_MAX_SNAPSHOT_ROW_CACHE_ENTRIES = 50_000;\n\n/**\n * Serializes a lookup key value (i.e. a SQLite-bound parameter). Numbers and\n * bigints serialize identically, as row keys parsed from the change log are\n * JSON numbers whereas the values read from SQLite are bigints; both address\n * the same row. Strings are prefixed to distinguish them from numbers.\n */\nfunction serialize(v: unknown): string {\n switch (typeof v) {\n case 'string':\n return 's' + v;\n case 'number':\n case 'bigint':\n return String(v);\n case 'boolean':\n return v ? 'true' : 'false';\n case 'object':\n return v === null ? 'null' : 'o' + stringify(v);\n default:\n return 'u' + String(v);\n }\n}\n\n/**\n * How a statement's results are read: a single row (`Statement.get()`) or\n * all rows (`Statement.all()`).\n */\nexport type ReadMode = 'get' | 'all';\n\n/**\n * The maximum number of distinct SQL statements interned by a\n * {@link SnapshotRowCache} before it is cleared. There is one per table and\n * lookup shape, so this is only reached after many schema changes.\n */\nexport const MAX_INTERNED_STATEMENTS = 10_000;\n\nconst HIT = {result: 'hit'} as const;\nconst MISS = {result: 'miss'} as const;\n\n/**\n * A worker-wide, bounded cache of the rows that a `Snapshotter` reads from\n * replica snapshots when computing the diff between two versions of the\n * replica.\n *\n * Every client group (i.e. view-syncer) on a sync worker computes its own\n * diff from the shared `_zero.changeLog2`, and each change in the diff costs\n * two SQLite reads: the new value of the row (from the `curr` snapshot) and\n * the previous value(s) that it replaces (from the `prev` snapshot). The\n * reads for a given change are identical for every client group that\n * traverses it, so a replicated transaction of N rows costs N × 2 × (client\n * groups) reads per worker, most of which are redundant. This cache lets the\n * client groups on a worker share those reads.\n *\n * ### Keys\n *\n * Entries are keyed by the exact SQL statement and arguments of the read\n * (which encodes the table, the selected columns and the lookup keys), plus\n * a `tag` supplied by the caller that pins the result to a version of the\n * replica:\n *\n * - The new value of a row is the row as of the `stateVersion` recorded in\n * its change log entry (its `_0_version` is asserted to equal that\n * version), and is tagged with that `stateVersion`. It is thus shareable\n * by all client groups regardless of the snapshots they are advancing\n * between.\n * - Previous values are read from the `prev` snapshot at its version, and\n * are tagged with that version (and, when the result can depend on the\n * changes applied to the snapshot before the read, the `curr` version\n * as well). See `Diff` in `snapshotter.ts` for the details.\n *\n * Because every key includes the version(s) that the result depends on,\n * entries never go stale and are never invalidated; they are only evicted.\n *\n * ### Eviction\n *\n * The cache is bounded by entry count and evicts in insertion (FIFO) order\n * rather than by recency. Diffs are traversed in change log order by every\n * client group, so the entries that will not be needed again are those that\n * were inserted the earliest (all groups have moved past them), while the\n * most recently inserted entries are the ones that the trailing groups have\n * yet to reach. Refreshing an entry on a hit would evict exactly the wrong\n * entries when a trailing group catches up.\n *\n * ### Sharing\n *\n * Cached values are shared by reference across client groups and must\n * therefore never be mutated by callers.\n */\nexport class SnapshotRowCache {\n readonly #maxEntries: number;\n readonly #entries = new Map<string, unknown>();\n // The keys of #entries in insertion order, so that the oldest can be\n // evicted in O(1). (Finding the oldest key with a fresh Map iterator\n // instead costs O(evictions) per insert, as V8 leaves deleted entries in\n // the table until it is compacted and every new iterator walks over them.)\n readonly #keys = new RingBuffer<string>();\n // Interns the SQL text of each distinct read so that entry keys\n // do not repeat the (long) column list of every statement.\n readonly #sqlIDs = new Map<string, number>();\n readonly #reads = getOrCreateCounter(\n 'sync',\n 'ivm.snapshot-row-reads',\n 'Row reads performed while computing snapshot diffs for IVM, labeled by whether the read was served by the worker-wide snapshot row cache.',\n );\n #hits = 0;\n #misses = 0;\n\n constructor(maxEntries = DEFAULT_MAX_SNAPSHOT_ROW_CACHE_ENTRIES) {\n this.#maxEntries = Math.max(0, maxEntries);\n }\n\n get size(): number {\n return this.#entries.size;\n }\n\n get maxEntries(): number {\n return this.#maxEntries;\n }\n\n stats(): {hits: number; misses: number; size: number} {\n return {hits: this.#hits, misses: this.#misses, size: this.#entries.size};\n }\n\n /**\n * Returns the cached result of the read identified by `tag`, `sql`, `mode`\n * and `args`, or performs the read via `read()`, caching and returning its\n * result. `undefined` results (i.e. a missing row) are not cached.\n *\n * `mode` is part of the key because the same statement can be read both\n * ways: for a table whose only unique key is its primary key, `getRow()`\n * and `getRows()` produce identical SQL, args and tags, but the former\n * caches a row and the latter an array of rows.\n */\n getOrRead<T>(\n tag: string,\n sql: string,\n mode: ReadMode,\n args: unknown[],\n read: () => T,\n ): T {\n const key = this.#key(tag, sql, mode, args);\n const cached = this.#entries.get(key);\n if (cached !== undefined) {\n this.#hits++;\n this.#reads.add(1, HIT);\n return cached as T;\n }\n this.#misses++;\n this.#reads.add(1, MISS);\n const value = read();\n if (value !== undefined && this.#maxEntries > 0) {\n // `key` is not in #entries (this is a miss), so it is always added.\n this.#entries.set(key, value);\n this.#keys.push(key);\n if (this.#keys.size > this.#maxEntries) {\n this.#entries.delete(must(this.#keys.shift()));\n }\n }\n return value;\n }\n\n clear(): void {\n this.#entries.clear();\n this.#keys.clear();\n this.#sqlIDs.clear();\n }\n\n #key(tag: string, sql: string, mode: ReadMode, args: unknown[]): string {\n if (\n this.#sqlIDs.size >= MAX_INTERNED_STATEMENTS &&\n !this.#sqlIDs.has(sql)\n ) {\n // Statements are only added (e.g. when schema changes produce new\n // column lists), so bound them by starting over. The entries refer to\n // statements by ID and are cleared with them.\n this.clear();\n }\n const sqlID = getOrInsert(this.#sqlIDs, sql, this.#sqlIDs.size);\n let key = `${tag}\\0${mode}${sqlID}`;\n // Include each value's length so separators inside string values cannot\n // make different argument arrays produce the same key.\n for (const arg of args) {\n const serialized = serialize(arg);\n key += `\\0${serialized.length}:${serialized}`;\n }\n return key;\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;AAgBA,IAAa,yCAAyC;;;;;;;AAQtD,SAAS,UAAU,GAAoB;CACrC,QAAQ,OAAO,GAAf;EACE,KAAK,UACH,OAAO,MAAM;EACf,KAAK;EACL,KAAK,UACH,OAAO,OAAO,CAAC;EACjB,KAAK,WACH,OAAO,IAAI,SAAS;EACtB,KAAK,UACH,OAAO,MAAM,OAAO,SAAS,MAAM,UAAU,CAAC;EAChD,SACE,OAAO,MAAM,OAAO,CAAC;CACzB;AACF;;;;;;AAaA,IAAa,0BAA0B;AAEvC,IAAM,MAAM,EAAC,QAAQ,MAAK;AAC1B,IAAM,OAAO,EAAC,QAAQ,OAAM;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAmD5B,IAAa,mBAAb,MAA8B;CAC5B;CACA,2BAAoB,IAAI,IAAqB;CAK7C,QAAiB,IAAI,WAAmB;CAGxC,0BAAmB,IAAI,IAAoB;CAC3C,SAAkB,mBAChB,QACA,0BACA,2IACF;CACA,QAAQ;CACR,UAAU;CAEV,YAAY,aAAa,wCAAwC;EAC/D,KAAK,cAAc,KAAK,IAAI,GAAG,UAAU;CAC3C;CAEA,I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shot-row-cache.ts"],"sourcesContent":["import {stringify} from '../../../../shared/src/bigint-json.ts';\nimport {getOrInsert} from '../../../../shared/src/map.ts';\nimport {must} from '../../../../shared/src/must.ts';\nimport {RingBuffer} from '../../../../shared/src/ring-buffer.ts';\nimport {getOrCreateCounter} from '../../observability/metrics.ts';\n\n/**\n * The default maximum number of entries retained by a {@link SnapshotRowCache}.\n *\n * Each entry is a raw SQLite row (or the list of rows conflicting with\n * a row on its unique keys) read while computing a snapshot diff. A\n * replicated transaction of N rows produces up to 2N entries (the new value\n * and the previous value(s) of each row), so the cache should be large enough\n * to hold the largest transactions that are commonly replicated in order for\n * all of the client groups on a worker to share the reads.\n */\nexport const DEFAULT_MAX_SNAPSHOT_ROW_CACHE_ENTRIES = 50_000;\n\n/**\n * The maximum approximate size of the rows retained by a\n * {@link SnapshotRowCache}, in string characters and blob bytes.\n *\n * The entry count alone does not bound memory: each update of a row adds\n * entries for the new version of the row, so a large row (e.g. one with a\n * large JSON column) that is updated many times a second fills the heap long\n * before the entry limit is reached.\n */\nconst MAX_SNAPSHOT_ROW_CACHE_BYTES = 64 * 1024 * 1024;\n\n/**\n * Approximates the memory retained by a cached value, which is a raw SQLite\n * row or an array of them. Only strings and blobs are measured exactly, as\n * they are the values that can be large.\n */\nfunction approximateSize(value: unknown): number {\n if (typeof value === 'string') {\n return value.length;\n }\n if (value instanceof Uint8Array) {\n return value.byteLength;\n }\n if (Array.isArray(value)) {\n let size = 0;\n for (const row of value) {\n size += approximateSize(row);\n }\n return size;\n }\n if (typeof value === 'object' && value !== null) {\n let size = 0;\n for (const col in value) {\n size += approximateSize((value as Record<string, unknown>)[col]);\n }\n return size;\n }\n return 8;\n}\n\n/**\n * Serializes a lookup key value (i.e. a SQLite-bound parameter). Numbers and\n * bigints serialize identically, as row keys parsed from the change log are\n * JSON numbers whereas the values read from SQLite are bigints; both address\n * the same row. Strings are prefixed to distinguish them from numbers.\n */\nfunction serialize(v: unknown): string {\n switch (typeof v) {\n case 'string':\n return 's' + v;\n case 'number':\n case 'bigint':\n return String(v);\n case 'boolean':\n return v ? 'true' : 'false';\n case 'object':\n return v === null ? 'null' : 'o' + stringify(v);\n default:\n return 'u' + String(v);\n }\n}\n\n/**\n * How a statement's results are read: a single row (`Statement.get()`) or\n * all rows (`Statement.all()`).\n */\nexport type ReadMode = 'get' | 'all';\n\n/**\n * The maximum number of distinct SQL statements interned by a\n * {@link SnapshotRowCache} before it is cleared. There is one per table and\n * lookup shape, so this is only reached after many schema changes.\n */\nexport const MAX_INTERNED_STATEMENTS = 10_000;\n\nconst HIT = {result: 'hit'} as const;\nconst MISS = {result: 'miss'} as const;\n\n/**\n * A worker-wide, bounded cache of the rows that a `Snapshotter` reads from\n * replica snapshots when computing the diff between two versions of the\n * replica.\n *\n * Every client group (i.e. view-syncer) on a sync worker computes its own\n * diff from the shared `_zero.changeLog2`, and each change in the diff costs\n * two SQLite reads: the new value of the row (from the `curr` snapshot) and\n * the previous value(s) that it replaces (from the `prev` snapshot). The\n * reads for a given change are identical for every client group that\n * traverses it, so a replicated transaction of N rows costs N × 2 × (client\n * groups) reads per worker, most of which are redundant. This cache lets the\n * client groups on a worker share those reads.\n *\n * ### Keys\n *\n * Entries are keyed by the exact SQL statement and arguments of the read\n * (which encodes the table, the selected columns and the lookup keys), plus\n * a `tag` supplied by the caller that pins the result to a version of the\n * replica:\n *\n * - The new value of a row is the row as of the `stateVersion` recorded in\n * its change log entry (its `_0_version` is asserted to equal that\n * version), and is tagged with that `stateVersion`. It is thus shareable\n * by all client groups regardless of the snapshots they are advancing\n * between.\n * - Previous values are read from the `prev` snapshot at its version, and\n * are tagged with that version (and, when the result can depend on the\n * changes applied to the snapshot before the read, the `curr` version\n * as well). See `Diff` in `snapshotter.ts` for the details.\n *\n * Because every key includes the version(s) that the result depends on,\n * entries never go stale and are never invalidated; they are only evicted.\n *\n * ### Eviction\n *\n * The cache is bounded by entry count and by the approximate size of its\n * rows (see {@link MAX_SNAPSHOT_ROW_CACHE_BYTES}), and evicts in insertion\n * (FIFO) order\n * rather than by recency. Diffs are traversed in change log order by every\n * client group, so the entries that will not be needed again are those that\n * were inserted the earliest (all groups have moved past them), while the\n * most recently inserted entries are the ones that the trailing groups have\n * yet to reach. Refreshing an entry on a hit would evict exactly the wrong\n * entries when a trailing group catches up.\n *\n * ### Sharing\n *\n * Cached values are shared by reference across client groups and must\n * therefore never be mutated by callers.\n */\nexport class SnapshotRowCache {\n readonly #maxEntries: number;\n readonly #entries = new Map<string, unknown>();\n // The keys of #entries in insertion order, so that the oldest can be\n // evicted in O(1). (Finding the oldest key with a fresh Map iterator\n // instead costs O(evictions) per insert, as V8 leaves deleted entries in\n // the table until it is compacted and every new iterator walks over them.)\n readonly #keys = new RingBuffer<string>();\n // The approximate size of each entry, in the same order as #keys.\n readonly #sizes = new RingBuffer<number>();\n readonly #maxBytes: number;\n #bytes = 0;\n // Interns the SQL text of each distinct read so that entry keys\n // do not repeat the (long) column list of every statement.\n readonly #sqlIDs = new Map<string, number>();\n readonly #reads = getOrCreateCounter(\n 'sync',\n 'ivm.snapshot-row-reads',\n 'Row reads performed while computing snapshot diffs for IVM, labeled by whether the read was served by the worker-wide snapshot row cache.',\n );\n #hits = 0;\n #misses = 0;\n\n constructor(\n maxEntries = DEFAULT_MAX_SNAPSHOT_ROW_CACHE_ENTRIES,\n maxBytes = MAX_SNAPSHOT_ROW_CACHE_BYTES,\n ) {\n this.#maxEntries = Math.max(0, maxEntries);\n this.#maxBytes = maxBytes;\n }\n\n get size(): number {\n return this.#entries.size;\n }\n\n get maxEntries(): number {\n return this.#maxEntries;\n }\n\n stats(): {hits: number; misses: number; size: number} {\n return {hits: this.#hits, misses: this.#misses, size: this.#entries.size};\n }\n\n /**\n * Returns the cached result of the read identified by `tag`, `sql`, `mode`\n * and `args`, or performs the read via `read()`, caching and returning its\n * result. `undefined` results (i.e. a missing row) are not cached.\n *\n * `mode` is part of the key because the same statement can be read both\n * ways: for a table whose only unique key is its primary key, `getRow()`\n * and `getRows()` produce identical SQL, args and tags, but the former\n * caches a row and the latter an array of rows.\n */\n getOrRead<T>(\n tag: string,\n sql: string,\n mode: ReadMode,\n args: unknown[],\n read: () => T,\n ): T {\n const key = this.#key(tag, sql, mode, args);\n const cached = this.#entries.get(key);\n if (cached !== undefined) {\n this.#hits++;\n this.#reads.add(1, HIT);\n return cached as T;\n }\n this.#misses++;\n this.#reads.add(1, MISS);\n const value = read();\n if (value !== undefined && this.#maxEntries > 0) {\n // `key` is not in #entries (this is a miss), so it is always added.\n this.#entries.set(key, value);\n this.#keys.push(key);\n const size = approximateSize(value);\n this.#sizes.push(size);\n this.#bytes += size;\n // A value larger than #maxBytes is evicted here, i.e. it is not cached.\n while (\n this.#keys.size > this.#maxEntries ||\n this.#bytes > this.#maxBytes\n ) {\n this.#entries.delete(must(this.#keys.shift()));\n this.#bytes -= must(this.#sizes.shift());\n }\n }\n return value;\n }\n\n clear(): void {\n this.#entries.clear();\n this.#keys.clear();\n this.#sizes.clear();\n this.#bytes = 0;\n this.#sqlIDs.clear();\n }\n\n #key(tag: string, sql: string, mode: ReadMode, args: unknown[]): string {\n if (\n this.#sqlIDs.size >= MAX_INTERNED_STATEMENTS &&\n !this.#sqlIDs.has(sql)\n ) {\n // Statements are only added (e.g. when schema changes produce new\n // column lists), so bound them by starting over. The entries refer to\n // statements by ID and are cleared with them.\n this.clear();\n }\n const sqlID = getOrInsert(this.#sqlIDs, sql, this.#sqlIDs.size);\n let key = `${tag}\\0${mode}${sqlID}`;\n // Include each value's length so separators inside string values cannot\n // make different argument arrays produce the same key.\n for (const arg of args) {\n const serialized = serialize(arg);\n key += `\\0${serialized.length}:${serialized}`;\n }\n return key;\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;AAgBA,IAAa,yCAAyC;;;;;;;;;;AAWtD,IAAM,+BAA+B;;;;;;AAOrC,SAAS,gBAAgB,OAAwB;CAC/C,IAAI,OAAO,UAAU,UACnB,OAAO,MAAM;CAEf,IAAI,iBAAiB,YACnB,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
|
|
136
136
|
#shuttingDown = false;
|
|
137
137
|
#initialized = resolver();
|
|
138
|
+
#hasInitialized = false;
|
|
138
139
|
#cvr;
|
|
139
140
|
/**
|
|
140
141
|
* Indicates whether the query pipelines have completed initial catch-up and
|
|
@@ -356,6 +357,11 @@ var ViewSyncerService = class {
|
|
|
356
357
|
};
|
|
357
358
|
}
|
|
358
359
|
try {
|
|
360
|
+
if (reloaded && this.#hasInitialized && this.#cvr.clientSchema === null) {
|
|
361
|
+
const e = clientSchemaMissingError(this.#cvr);
|
|
362
|
+
this.#stateChanges.fail(e);
|
|
363
|
+
throw e;
|
|
364
|
+
}
|
|
359
365
|
if (reloaded && this.#cvr.pinnedUser !== null) try {
|
|
360
366
|
this.connContextManager.restorePinnedUser(this.#cvr.pinnedUser);
|
|
361
367
|
} catch (e) {
|
|
@@ -402,7 +408,7 @@ var ViewSyncerService = class {
|
|
|
402
408
|
this.#pipelineResets.add(1, { reason: "cvr-reloaded" });
|
|
403
409
|
this.#pipelinesHydrated = false;
|
|
404
410
|
this.connContextManager.setSharedRetransformReady(false);
|
|
405
|
-
this.#pipelines.reset(
|
|
411
|
+
this.#pipelines.reset(requireClientSchema(cvr));
|
|
406
412
|
return true;
|
|
407
413
|
}
|
|
408
414
|
readyState() {
|
|
@@ -434,7 +440,7 @@ var ViewSyncerService = class {
|
|
|
434
440
|
this.#e2eServingLagTracker.onVersionReady(replicaState);
|
|
435
441
|
this.#batchTimeMs = void 0;
|
|
436
442
|
await this.#runInLockWithCVR(async (lc, cvr) => {
|
|
437
|
-
const clientSchema =
|
|
443
|
+
const clientSchema = requireClientSchema(cvr);
|
|
438
444
|
if (!this.#pipelines.initialized()) this.#pipelines.init(clientSchema);
|
|
439
445
|
if (cvr.replicaVersion !== null && cvr.version.stateVersion !== "00" && this.#pipelines.replicaVersion < cvr.replicaVersion) {
|
|
440
446
|
const message = `Cannot sync from older replica: CVR=${cvr.replicaVersion}, DB=${this.#pipelines.replicaVersion}`;
|
|
@@ -511,7 +517,7 @@ var ViewSyncerService = class {
|
|
|
511
517
|
if (!(e instanceof ResetPipelinesSignal)) throw e;
|
|
512
518
|
lc.info?.(`resetting pipelines: ${e.message}${e.breakdown ? ` (${e.breakdown})` : ""}`);
|
|
513
519
|
this.#pipelineResets.add(1, { reason: e.reason });
|
|
514
|
-
this.#pipelines.reset(
|
|
520
|
+
this.#pipelines.reset(requireClientSchema(cvr));
|
|
515
521
|
version = this.#pipelines.currentVersion();
|
|
516
522
|
}
|
|
517
523
|
const cvrVer = versionString(cvr.version);
|
|
@@ -582,6 +588,22 @@ var ViewSyncerService = class {
|
|
|
582
588
|
get servingLagEligible() {
|
|
583
589
|
return this.#clients.size > 0 && this.connContextManager.getBackgroundConnectionContext() !== void 0;
|
|
584
590
|
}
|
|
591
|
+
#apiServerRequestsInFlight = 0;
|
|
592
|
+
get awaitingAPIServer() {
|
|
593
|
+
return this.#apiServerRequestsInFlight > 0;
|
|
594
|
+
}
|
|
595
|
+
/**
|
|
596
|
+
* Runs a request to the API server, during which {@link awaitingAPIServer}
|
|
597
|
+
* says that the client group is waiting for it.
|
|
598
|
+
*/
|
|
599
|
+
async #awaitAPIServer(request) {
|
|
600
|
+
this.#apiServerRequestsInFlight++;
|
|
601
|
+
try {
|
|
602
|
+
return await request();
|
|
603
|
+
} finally {
|
|
604
|
+
this.#apiServerRequestsInFlight--;
|
|
605
|
+
}
|
|
606
|
+
}
|
|
585
607
|
/**
|
|
586
608
|
* Records that this client group is caught up through `stateVersion`, i.e.
|
|
587
609
|
* everything the replica had at that version has been poked to clients.
|
|
@@ -753,6 +775,7 @@ var ViewSyncerService = class {
|
|
|
753
775
|
if (!validatedConnCtx) return;
|
|
754
776
|
newClient.markValidated();
|
|
755
777
|
await this.#handleConfigUpdate(lc, clientID, msg, cvr, "all", validatedConnCtx.profileID ?? `cg${this.id}`, validatedConnCtx);
|
|
778
|
+
this.#hasInitialized = true;
|
|
756
779
|
this.#initialized.resolve("initialized");
|
|
757
780
|
}, newClient)).catch((e) => newClient.fail(e));
|
|
758
781
|
return downstream;
|
|
@@ -1026,7 +1049,7 @@ var ViewSyncerService = class {
|
|
|
1026
1049
|
if (customQueries.size > 0 && !this.#customQueryTransformer) lc.warn?.("Custom/named queries were requested but no `ZERO_QUERY_URL` is configured for Zero Cache.");
|
|
1027
1050
|
const customQueryTransformer = this.#customQueryTransformer;
|
|
1028
1051
|
if (customQueryTransformer && customQueries.size > 0) {
|
|
1029
|
-
const transformedCustomQueries = await hydrationBudget.excluding(() => this.#runPriorityOp(lc, "#hydrateUnchangedQueries transforming custom queries", () => customQueryTransformer.transform(connCtx, customQueries.values())));
|
|
1052
|
+
const transformedCustomQueries = await hydrationBudget.excluding(() => this.#runPriorityOp(lc, "#hydrateUnchangedQueries transforming custom queries", () => this.#awaitAPIServer(() => customQueryTransformer.transform(connCtx, customQueries.values()))));
|
|
1030
1053
|
if (transformedCustomQueries.kind === "success" && !transformedCustomQueries.cached) this.connContextManager.validateConnection(connCtx, connCtx.revision, transformedCustomQueries.validation);
|
|
1031
1054
|
if (Array.isArray(transformedCustomQueries.result)) for (const q of transformedCustomQueries.result) if ("error" in q) customErrorCount++;
|
|
1032
1055
|
else if (q.transformationHash !== customQueries.get(q.id)?.transformationHash) customHashMismatchCount++;
|
|
@@ -1236,7 +1259,7 @@ var ViewSyncerService = class {
|
|
|
1236
1259
|
const transformStart = performance.now();
|
|
1237
1260
|
let transformedCustomQueries;
|
|
1238
1261
|
try {
|
|
1239
|
-
transformedCustomQueries = await hydrationBudget.excluding(() => this.#runPriorityOp(lc, "#syncQueryPipelineSet transforming custom queries", () => customQueryTransformer.transform(connCtx, queries)));
|
|
1262
|
+
transformedCustomQueries = await hydrationBudget.excluding(() => this.#runPriorityOp(lc, "#syncQueryPipelineSet transforming custom queries", () => this.#awaitAPIServer(() => customQueryTransformer.transform(connCtx, queries))));
|
|
1240
1263
|
if (transformedCustomQueries.kind === "failed") throw new ProtocolErrorWithLevel(transformedCustomQueries.result, "warn");
|
|
1241
1264
|
else {
|
|
1242
1265
|
if (!transformedCustomQueries.cached) this.connContextManager.validateConnection(connCtx, connCtx.revision, transformedCustomQueries.validation);
|
|
@@ -2119,7 +2142,8 @@ var ViewSyncerService = class {
|
|
|
2119
2142
|
try {
|
|
2120
2143
|
let validation = void 0;
|
|
2121
2144
|
if (this.#customQueryTransformer) {
|
|
2122
|
-
const
|
|
2145
|
+
const transformer = this.#customQueryTransformer;
|
|
2146
|
+
const response = await this.#awaitAPIServer(() => transformer.validate(connCtx));
|
|
2123
2147
|
if (response.kind === "TransformFailed") throw new ProtocolErrorWithLevel(response, "warn");
|
|
2124
2148
|
validation = response.validation;
|
|
2125
2149
|
} else validation = { kind: "client-fallback" };
|
|
@@ -2223,6 +2247,27 @@ function checkClientAndCVRVersions(client, cvr) {
|
|
|
2223
2247
|
origin: ZeroCache
|
|
2224
2248
|
});
|
|
2225
2249
|
}
|
|
2250
|
+
/**
|
|
2251
|
+
* Returns the client schema of a CVR that is used after the view-syncer has
|
|
2252
|
+
* been initialized.
|
|
2253
|
+
*
|
|
2254
|
+
* `initConnection` only signals initialization once the schema is in the CVR,
|
|
2255
|
+
* so a CVR without one was reloaded (after an error cleared the cached
|
|
2256
|
+
* snapshot) from a store that no longer has what this view-syncer wrote, e.g.
|
|
2257
|
+
* because the CVR's row was removed or the CVR db was restored to an earlier
|
|
2258
|
+
* state. The clients' state cannot be reconciled with such a CVR, so they are
|
|
2259
|
+
* told to start over, as they are when the CVR has been purged.
|
|
2260
|
+
*
|
|
2261
|
+
* `#runInLockWithCVR` rejects such a CVR when it reloads it, so this is not
|
|
2262
|
+
* expected to throw.
|
|
2263
|
+
*/
|
|
2264
|
+
function requireClientSchema(cvr) {
|
|
2265
|
+
if (cvr.clientSchema === null) throw clientSchemaMissingError(cvr);
|
|
2266
|
+
return cvr.clientSchema;
|
|
2267
|
+
}
|
|
2268
|
+
function clientSchemaMissingError(cvr) {
|
|
2269
|
+
return new ClientNotFoundError(`CVR@${versionString(cvr.version)} has no client schema after initialization`);
|
|
2270
|
+
}
|
|
2226
2271
|
function isTransformFailedError(error) {
|
|
2227
2272
|
return error.errorBody.kind === "TransformFailed" && !isAuthErrorBody(error.errorBody);
|
|
2228
2273
|
}
|