@hot-updater/plugin-core 1.2.0-rc.5 → 1.2.0-rc.50
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/dist/coreApi.d.cts +246 -10
- package/dist/coreApi.d.mts +246 -10
- package/dist/database/adapter.d.cts +12 -0
- package/dist/database/adapter.d.mts +12 -0
- package/dist/engine/core/schema.cjs +200 -5
- package/dist/engine/core/schema.d.cts +127 -1
- package/dist/engine/core/schema.d.mts +127 -1
- package/dist/engine/core/schema.mjs +200 -6
- package/dist/engine/createEngine.cjs +1 -2
- package/dist/engine/createEngine.d.cts +1 -6
- package/dist/engine/createEngine.d.mts +1 -6
- package/dist/engine/createEngine.mjs +1 -2
- package/dist/engine/database/aggregateBatching.cjs +87 -129
- package/dist/engine/database/aggregateBatching.mjs +87 -129
- package/dist/engine/database/database.cjs +1 -4
- package/dist/engine/database/database.mjs +1 -4
- package/dist/engine/database/engineTransaction.cjs +21 -1
- package/dist/engine/database/engineTransaction.d.cts +5 -1
- package/dist/engine/database/engineTransaction.d.mts +5 -1
- package/dist/engine/database/engineTransaction.mjs +21 -1
- package/dist/engine/database/kv/kvAdapter.cjs +80 -4
- package/dist/engine/database/kv/kvAdapter.mjs +80 -4
- package/dist/engine/database/resolveSchema.cjs +6 -3
- package/dist/engine/database/resolveSchema.mjs +6 -3
- package/dist/engine/database/sql/sqlAdapter.cjs +9 -4
- package/dist/engine/database/sql/sqlAdapter.mjs +9 -4
- package/dist/engine/database/sql/sqlSchema.cjs +24 -6
- package/dist/engine/database/sql/sqlSchema.d.cts +1 -1
- package/dist/engine/database/sql/sqlSchema.d.mts +1 -1
- package/dist/engine/database/sql/sqlSchema.mjs +24 -6
- package/dist/engine/db/coreDatabase.cjs +10 -5
- package/dist/engine/db/coreDatabase.d.cts +2 -1
- package/dist/engine/db/coreDatabase.d.mts +2 -1
- package/dist/engine/db/coreDatabase.mjs +10 -5
- package/dist/engine/db/engineMigrator.cjs +21 -16
- package/dist/engine/db/engineMigrator.mjs +22 -17
- package/dist/engine/db/engineSqlMigrator.cjs +53 -20
- package/dist/engine/db/engineSqlMigrator.d.cts +2 -0
- package/dist/engine/db/engineSqlMigrator.d.mts +2 -0
- package/dist/engine/db/engineSqlMigrator.mjs +55 -22
- package/dist/engine/db/schemaSettings.cjs +36 -5
- package/dist/engine/db/schemaSettings.d.cts +5 -2
- package/dist/engine/db/schemaSettings.d.mts +5 -2
- package/dist/engine/db/schemaSettings.mjs +36 -6
- package/dist/engine/db/settingsMigrator.cjs +92 -14
- package/dist/engine/db/settingsMigrator.d.cts +18 -8
- package/dist/engine/db/settingsMigrator.d.mts +18 -8
- package/dist/engine/db/settingsMigrator.mjs +89 -15
- package/dist/engine/db/sqlSchemaState.cjs +108 -0
- package/dist/engine/db/sqlSchemaState.mjs +104 -0
- package/dist/engine/db/types.d.cts +6 -0
- package/dist/engine/db/types.d.mts +6 -0
- package/dist/index.cjs +2 -8
- package/dist/index.d.cts +5 -6
- package/dist/index.d.mts +5 -6
- package/dist/index.mjs +3 -4
- package/dist/serverPlugin/coreReads.d.cts +10 -1
- package/dist/serverPlugin/coreReads.d.mts +10 -1
- package/dist/serverPlugin/definitions.d.cts +4 -0
- package/dist/serverPlugin/definitions.d.mts +4 -0
- package/dist/serverPlugin/schema.d.cts +4 -0
- package/dist/serverPlugin/schema.d.mts +4 -0
- package/dist/types/databaseConfig.d.cts +10 -20
- package/dist/types/databaseConfig.d.mts +10 -20
- package/dist/types/databaseRows.d.cts +70 -2
- package/dist/types/databaseRows.d.mts +70 -2
- package/dist/types/index.cjs +3 -0
- package/dist/types/index.d.cts +114 -56
- package/dist/types/index.d.mts +114 -56
- package/dist/types/index.mjs +3 -1
- package/dist/types/models.d.cts +9 -1
- package/dist/types/models.d.mts +9 -1
- package/dist/types/public.d.cts +3 -3
- package/dist/types/public.d.mts +3 -3
- package/package.json +3 -9
- package/dist/remoteBundleSigning.cjs +0 -357
- package/dist/remoteBundleSigning.d.cts +0 -38
- package/dist/remoteBundleSigning.d.mts +0 -38
- package/dist/remoteBundleSigning.mjs +0 -352
|
@@ -19,18 +19,17 @@ const LEASE_TABLE = "aggregate_lease";
|
|
|
19
19
|
const LEASE = { id: "compaction" };
|
|
20
20
|
/** How long a compaction holds the lease before another process may take it. */
|
|
21
21
|
const LEASE_MS = 3e4;
|
|
22
|
-
/**
|
|
23
|
-
|
|
24
|
-
* first; memory mode flushes every 15, since its window is what a crash
|
|
25
|
-
* loses.
|
|
26
|
-
*/
|
|
27
|
-
const WINDOW_MS = {
|
|
28
|
-
log: 6e4,
|
|
29
|
-
memory: 15e3
|
|
30
|
-
};
|
|
22
|
+
/** A commit compacts once this has passed since the last compaction. */
|
|
23
|
+
const WINDOW_MS = 6e4;
|
|
31
24
|
/** Log rows a compaction reads from each log table for one group. */
|
|
32
25
|
const LOG_PAGE = 200;
|
|
33
26
|
/**
|
|
27
|
+
* How old a log row this process can't apply must be before its reads step
|
|
28
|
+
* past it: older than any transaction still committing, between servers
|
|
29
|
+
* whose clocks agree this closely.
|
|
30
|
+
*/
|
|
31
|
+
const SKIP_AFTER_MS = 3e5;
|
|
32
|
+
/**
|
|
34
33
|
* Groups one compaction applies: after a commit, so the request that runs
|
|
35
34
|
* it waits for one group; before a read; and on flush.
|
|
36
35
|
*/
|
|
@@ -41,8 +40,6 @@ const GROUPS = {
|
|
|
41
40
|
};
|
|
42
41
|
/** Tries per write after a conflict or a transient error. */
|
|
43
42
|
const ATTEMPTS = 5;
|
|
44
|
-
/** Aggregate rows a memory buffer holds before a commit waits for a flush. */
|
|
45
|
-
const MAX_BUFFERED = 1e4;
|
|
46
43
|
const log = defineTable({
|
|
47
44
|
id: {
|
|
48
45
|
type: "string",
|
|
@@ -92,7 +89,7 @@ const valuesOf = ({ deltas, sketches }) => ({
|
|
|
92
89
|
/**
|
|
93
90
|
* Merges `values` into the change for `key`'s identity as `tx.aggregate`
|
|
94
91
|
* does: deltas add up and sketches merge. One constant `shardBy` keys each
|
|
95
|
-
* identity to one entry;
|
|
92
|
+
* identity to one entry; `compile` writes it to shard 0.
|
|
96
93
|
*/
|
|
97
94
|
const merge = (into, model, key, values) => recordAggregate(into, model, Object.fromEntries(shapeOf(model).key.map((field, at) => [field, key[at]])), values, "");
|
|
98
95
|
const mergeAll = (into, changes) => {
|
|
@@ -126,7 +123,7 @@ const increment = ({ model, deltas }, key) => Object.values(deltas).some((delta)
|
|
|
126
123
|
/**
|
|
127
124
|
* The guarded write that merges `change` into `current`: insert, patch, or
|
|
128
125
|
* delete at zero. Unlike a transaction's, a gauge may go below zero here: a
|
|
129
|
-
*
|
|
126
|
+
* group can hold a loss without the gain before it, and reads sum every shard.
|
|
130
127
|
*/
|
|
131
128
|
const rewrite = (change, key, current) => {
|
|
132
129
|
const { model } = change;
|
|
@@ -163,23 +160,41 @@ const rewrite = (change, key, current) => {
|
|
|
163
160
|
previous: current
|
|
164
161
|
};
|
|
165
162
|
};
|
|
163
|
+
/** A shard row's place in what `readCurrent` read. */
|
|
164
|
+
const rowId = (model, key) => JSON.stringify([model.table.name, key]);
|
|
165
|
+
/** The shard key each change writes: shard 0, since one compaction runs at a time. */
|
|
166
|
+
const keysOf = (changes) => changes.map(({ key }) => [...key.slice(0, -1), 0]);
|
|
166
167
|
/**
|
|
167
|
-
* The
|
|
168
|
-
*
|
|
169
|
-
* rows are read in one batch per table.
|
|
168
|
+
* The current rows of the changes that rewrite theirs (gauges and sketches),
|
|
169
|
+
* each once, in one batch per table.
|
|
170
170
|
*/
|
|
171
|
-
const
|
|
172
|
-
const keys = changes
|
|
171
|
+
const readCurrent = async (adapter, changes) => {
|
|
172
|
+
const keys = keysOf(changes);
|
|
173
173
|
const reads = /* @__PURE__ */ new Map();
|
|
174
174
|
changes.forEach((change, at) => {
|
|
175
|
-
if (rewrites(change))
|
|
175
|
+
if (!rewrites(change)) return;
|
|
176
|
+
const wanted = reads.get(change.model) ?? /* @__PURE__ */ new Map();
|
|
177
|
+
wanted.set(rowId(change.model, keys[at]), keys[at]);
|
|
178
|
+
reads.set(change.model, wanted);
|
|
176
179
|
});
|
|
177
180
|
const current = /* @__PURE__ */ new Map();
|
|
178
|
-
await Promise.all([...reads].map(async ([model,
|
|
179
|
-
const
|
|
180
|
-
|
|
181
|
+
await Promise.all([...reads].map(async ([model, wanted]) => {
|
|
182
|
+
const keys = [...wanted.values()];
|
|
183
|
+
const rows = await adapter.get(model.table, keys);
|
|
184
|
+
keys.forEach((key, at) => {
|
|
185
|
+
current.set(rowId(model, key), rows[at] ?? null);
|
|
186
|
+
});
|
|
181
187
|
}));
|
|
182
|
-
return
|
|
188
|
+
return current;
|
|
189
|
+
};
|
|
190
|
+
/**
|
|
191
|
+
* The write for each change: a blind increment that creates the row for
|
|
192
|
+
* counters, and a guarded rewrite for gauges and sketches, over the rows
|
|
193
|
+
* `current` read.
|
|
194
|
+
*/
|
|
195
|
+
const build = (changes, current) => {
|
|
196
|
+
const keys = keysOf(changes);
|
|
197
|
+
return changes.map((change, at) => rewrites(change) ? rewrite(change, keys[at], current.get(rowId(change.model, keys[at])) ?? null) : increment(change, keys[at]));
|
|
183
198
|
};
|
|
184
199
|
const isOp = (op) => op !== void 0;
|
|
185
200
|
const sleep = (attempt) => new Promise((resolve) => setTimeout(resolve, Math.min(250, 5 * 2 ** attempt) * Math.random()));
|
|
@@ -223,14 +238,13 @@ const encode = async (changes) => {
|
|
|
223
238
|
return zipped !== void 0 && zipped.length < json.length ? `z${zipped}` : json;
|
|
224
239
|
};
|
|
225
240
|
/**
|
|
226
|
-
* Batches changes to aggregates declared `batched`. A transaction
|
|
227
|
-
* them
|
|
228
|
-
*
|
|
229
|
-
*
|
|
230
|
-
*
|
|
231
|
-
* applies exactly once. One lease row keeps compactions one at a time.
|
|
241
|
+
* Batches changes to aggregates declared `batched`. A transaction writes
|
|
242
|
+
* them as one log row in its own atomic write, in place of their rows; a
|
|
243
|
+
* compaction later merges log rows into the aggregates and deletes them,
|
|
244
|
+
* atomically again, so each applies exactly once. One lease row keeps
|
|
245
|
+
* compactions one at a time.
|
|
232
246
|
*/
|
|
233
|
-
const createAggregateBatches = ({ engine, adapter, schema, batching: {
|
|
247
|
+
const createAggregateBatches = ({ engine, adapter, schema, batching: { windowMs = WINDOW_MS }, now }) => {
|
|
234
248
|
if (!schema.models.has(LEASE_TABLE)) throw new DatabaseTransactionError("An engine that batches aggregates needs aggregateBatchingModule in its schema.");
|
|
235
249
|
const holder = crypto.randomUUID().replaceAll("-", "");
|
|
236
250
|
const table = (name) => schema.models.get(name).table;
|
|
@@ -258,72 +272,20 @@ const createAggregateBatches = ({ engine, adapter, schema, batching: { mode = "l
|
|
|
258
272
|
}
|
|
259
273
|
return changes;
|
|
260
274
|
};
|
|
261
|
-
/**
|
|
262
|
-
* Writes changes in atomic chunks within `fits`, and returns the ones it
|
|
263
|
-
* could not apply. A write whose outcome is unknown is dropped, never
|
|
264
|
-
* resent, so no change applies twice.
|
|
265
|
-
*/
|
|
266
|
-
const apply = async (changes, shard) => {
|
|
267
|
-
let rest = changes;
|
|
268
|
-
let ops = [];
|
|
269
|
-
let read = true;
|
|
270
|
-
for (let failures = 0; rest.length > 0 && failures < ATTEMPTS;) try {
|
|
271
|
-
if (read) ops = await compile(adapter, rest, shard);
|
|
272
|
-
let size = rest.length;
|
|
273
|
-
const chunk = () => ops.slice(0, size).filter(isOp);
|
|
274
|
-
while (size > 1 && !adapter.fits(chunk())) size = Math.ceil(size / 2);
|
|
275
|
-
let result = { ok: true };
|
|
276
|
-
if (chunk().length > 0) result = await adapter.write(chunk()).catch((error) => {
|
|
277
|
-
warn("flush")(error);
|
|
278
|
-
return { ok: true };
|
|
279
|
-
});
|
|
280
|
-
read = !result.ok && !("retry" in result);
|
|
281
|
-
if (result.ok) {
|
|
282
|
-
rest = rest.slice(size);
|
|
283
|
-
ops = ops.slice(size);
|
|
284
|
-
failures = 0;
|
|
285
|
-
} else {
|
|
286
|
-
failures += 1;
|
|
287
|
-
if (!read) await sleep(failures);
|
|
288
|
-
}
|
|
289
|
-
} catch (error) {
|
|
290
|
-
warn("flush")(error);
|
|
291
|
-
return rest;
|
|
292
|
-
}
|
|
293
|
-
return rest;
|
|
294
|
-
};
|
|
295
|
-
let buffer = /* @__PURE__ */ new Map();
|
|
296
|
-
let timer;
|
|
297
|
-
let flushing;
|
|
298
|
-
const shards = /* @__PURE__ */ new Map();
|
|
299
|
-
/** Each process writes its own shard, so flushes of two processes rarely meet. */
|
|
300
|
-
const processShard = (model) => {
|
|
301
|
-
if (!shards.has(model)) shards.set(model, Math.floor(Math.random() * shapeOf(model).shards));
|
|
302
|
-
return shards.get(model);
|
|
303
|
-
};
|
|
304
|
-
const schedule = () => {
|
|
305
|
-
if (timer !== void 0 || buffer.size === 0) return;
|
|
306
|
-
timer = setTimeout(() => {
|
|
307
|
-
timer = void 0;
|
|
308
|
-
flushBuffer();
|
|
309
|
-
}, windowMs);
|
|
310
|
-
timer.unref?.();
|
|
311
|
-
};
|
|
312
|
-
/** Never rejects: what it cannot apply goes back into the buffer. */
|
|
313
|
-
const flushBuffer = () => flushing ??= (async () => {
|
|
314
|
-
clearTimeout(timer);
|
|
315
|
-
timer = void 0;
|
|
316
|
-
const pending = [...buffer.values()];
|
|
317
|
-
buffer = /* @__PURE__ */ new Map();
|
|
318
|
-
mergeAll(buffer, await apply(pending, processShard));
|
|
319
|
-
})().catch(warn("flush")).finally(() => {
|
|
320
|
-
flushing = void 0;
|
|
321
|
-
schedule();
|
|
322
|
-
});
|
|
323
275
|
let nextDue = 0;
|
|
324
276
|
let compacting;
|
|
325
277
|
/** Log rows this process read, by `[log table's index, id]`, for the deletes after a group. */
|
|
326
278
|
const known = /* @__PURE__ */ new Map();
|
|
279
|
+
/**
|
|
280
|
+
* Each log table's last row of a run at its head that this process can't
|
|
281
|
+
* apply (it names an aggregate or metric this schema lacks), whose reads
|
|
282
|
+
* start past it. The rows wait for a process that can apply them, and a
|
|
283
|
+
* restart reads them again.
|
|
284
|
+
*/
|
|
285
|
+
const skipped = LOG_TABLES.map(() => void 0);
|
|
286
|
+
const past = (shard) => skipped[shard] === void 0 ? {} : { range: { gt: skipped[shard] } };
|
|
287
|
+
/** When a log row's transaction stamped its ID. */
|
|
288
|
+
const stampOf = (id) => Number.parseInt(id.slice(0, 9), 36);
|
|
327
289
|
const idOf = (shard, id) => JSON.stringify([shard, id]);
|
|
328
290
|
/** The lease row as stored once `set` is written over it. */
|
|
329
291
|
const leaseOp = (held, set) => {
|
|
@@ -439,14 +401,22 @@ const createAggregateBatches = ({ engine, adapter, schema, batching: { mode = "l
|
|
|
439
401
|
logs: (await Promise.all(LOG_TABLES.map(async (name, shard) => {
|
|
440
402
|
const page = await engine.reads.findMany(name, {
|
|
441
403
|
index: "oldest",
|
|
442
|
-
limit: LOG_PAGE
|
|
404
|
+
limit: LOG_PAGE,
|
|
405
|
+
...past(shard)
|
|
443
406
|
});
|
|
444
407
|
more ||= page.next !== void 0;
|
|
445
|
-
|
|
408
|
+
const decoded = await Promise.all(page.rows.map(async (row) => ({
|
|
446
409
|
shard,
|
|
447
410
|
row,
|
|
448
411
|
changes: await decode(String(row.changes))
|
|
449
|
-
})))
|
|
412
|
+
})));
|
|
413
|
+
const settled = now() - SKIP_AFTER_MS;
|
|
414
|
+
for (const { row, changes } of decoded) {
|
|
415
|
+
const id = String(row.id);
|
|
416
|
+
if (changes !== void 0 || stampOf(id) >= settled) break;
|
|
417
|
+
skipped[shard] = id;
|
|
418
|
+
}
|
|
419
|
+
return decoded.flatMap(({ changes, ...entry }) => changes === void 0 ? [] : [{
|
|
450
420
|
...entry,
|
|
451
421
|
changes
|
|
452
422
|
}]);
|
|
@@ -454,7 +424,6 @@ const createAggregateBatches = ({ engine, adapter, schema, batching: { mode = "l
|
|
|
454
424
|
more
|
|
455
425
|
};
|
|
456
426
|
};
|
|
457
|
-
const rowsFor = async (changes) => (await compile(adapter, changes, () => 0)).filter(isOp);
|
|
458
427
|
/**
|
|
459
428
|
* Applies the oldest pending log rows whose merged changes fit in one
|
|
460
429
|
* atomic write with the lease, which lists them as applied; the rows are
|
|
@@ -463,12 +432,14 @@ const createAggregateBatches = ({ engine, adapter, schema, batching: { mode = "l
|
|
|
463
432
|
* log rows it applied whole, or undefined when a conflict stopped it.
|
|
464
433
|
*/
|
|
465
434
|
const applyGroup = async (held, logs) => {
|
|
435
|
+
const current = await readCurrent(adapter, logs.flatMap((entry) => [...entry.changes.values()]));
|
|
436
|
+
const rowsFor = (changes) => build(changes, current).filter(isOp);
|
|
466
437
|
for (let count = logs.length; count > 0; count = Math.floor(count / 2)) {
|
|
467
438
|
const batch = logs.slice(0, count);
|
|
468
439
|
const changes = mergeAll(/* @__PURE__ */ new Map(), batch.flatMap((entry) => [...entry.changes.values()]));
|
|
469
440
|
const applied = batch.map(({ shard, row }) => [shard, row.id]);
|
|
470
441
|
const lease = leaseOp(held, { applied: JSON.stringify(applied) });
|
|
471
|
-
const ops = [...
|
|
442
|
+
const ops = [...rowsFor([...changes.values()]), lease.op];
|
|
472
443
|
if (!adapter.fits(ops)) continue;
|
|
473
444
|
for (const { shard, row } of batch) known.set(idOf(shard, row.id), row);
|
|
474
445
|
return await commit(ops) ? {
|
|
@@ -490,7 +461,7 @@ const createAggregateBatches = ({ engine, adapter, schema, batching: { mode = "l
|
|
|
490
461
|
};
|
|
491
462
|
const lease = leaseOp(held, {});
|
|
492
463
|
const ops = [
|
|
493
|
-
...
|
|
464
|
+
...rowsFor(entries.slice(0, take)),
|
|
494
465
|
kept,
|
|
495
466
|
lease.op
|
|
496
467
|
];
|
|
@@ -511,11 +482,12 @@ const createAggregateBatches = ({ engine, adapter, schema, batching: { mode = "l
|
|
|
511
482
|
if (held === void 0) return;
|
|
512
483
|
let pending = true;
|
|
513
484
|
let clear = false;
|
|
485
|
+
let carried;
|
|
514
486
|
try {
|
|
515
487
|
for (let group = 0;; group += 1) {
|
|
516
488
|
clear = await deleteApplied(held);
|
|
517
489
|
if (!clear || !pending || group === groups) break;
|
|
518
|
-
const { logs, more } = await readLogs();
|
|
490
|
+
const { logs, more } = carried ?? await readLogs();
|
|
519
491
|
if (logs.length === 0) {
|
|
520
492
|
pending = false;
|
|
521
493
|
break;
|
|
@@ -523,6 +495,11 @@ const createAggregateBatches = ({ engine, adapter, schema, batching: { mode = "l
|
|
|
523
495
|
const applied = await applyGroup(held, logs);
|
|
524
496
|
if (applied === void 0) break;
|
|
525
497
|
[held, clear] = [applied.held, false];
|
|
498
|
+
const rest = applied.count === 0 ? [] : logs.slice(applied.count);
|
|
499
|
+
carried = rest.length > 0 ? {
|
|
500
|
+
logs: rest,
|
|
501
|
+
more
|
|
502
|
+
} : void 0;
|
|
526
503
|
pending = more || applied.count < logs.length;
|
|
527
504
|
}
|
|
528
505
|
} finally {
|
|
@@ -542,26 +519,13 @@ const createAggregateBatches = ({ engine, adapter, schema, batching: { mode = "l
|
|
|
542
519
|
});
|
|
543
520
|
let checking;
|
|
544
521
|
/** Whether any log row waits; reads at once share one check. */
|
|
545
|
-
const hasPending = () => checking ??= Promise.all(LOG_TABLES.map((name) => engine.reads.findMany(name, {
|
|
522
|
+
const hasPending = () => checking ??= Promise.all(LOG_TABLES.map((name, shard) => engine.reads.findMany(name, {
|
|
546
523
|
index: "oldest",
|
|
547
|
-
limit: 1
|
|
524
|
+
limit: 1,
|
|
525
|
+
...past(shard)
|
|
548
526
|
}))).then((pages) => pages.some((page) => page.rows.length > 0)).finally(() => {
|
|
549
527
|
checking = void 0;
|
|
550
528
|
});
|
|
551
|
-
/** Takes a committed transaction's changes; never rejects, since the transaction already committed. */
|
|
552
|
-
const committed = async (changes) => {
|
|
553
|
-
if (mode === "log") {
|
|
554
|
-
if (now() >= nextDue) await compact(false, GROUPS.commit);
|
|
555
|
-
return;
|
|
556
|
-
}
|
|
557
|
-
mergeAll(buffer, changes.values());
|
|
558
|
-
schedule();
|
|
559
|
-
if (buffer.size >= MAX_BUFFERED) await flushBuffer();
|
|
560
|
-
};
|
|
561
|
-
const flush = async () => {
|
|
562
|
-
await flushBuffer();
|
|
563
|
-
if (mode === "log" && await hasPending()) await compact(true, GROUPS.flush);
|
|
564
|
-
};
|
|
565
529
|
return {
|
|
566
530
|
async transaction(fn) {
|
|
567
531
|
let changes = /* @__PURE__ */ new Map();
|
|
@@ -587,7 +551,7 @@ const createAggregateBatches = ({ engine, adapter, schema, batching: { mode = "l
|
|
|
587
551
|
aggregate
|
|
588
552
|
});
|
|
589
553
|
if (failure) throw failure.error;
|
|
590
|
-
if (
|
|
554
|
+
if (attempt.size > 0) {
|
|
591
555
|
const id = `${now().toString(36).padStart(9, "0")}${holder.slice(0, 8)}${crypto.randomUUID().slice(0, 8)}`;
|
|
592
556
|
const shard = Math.floor(Math.random() * LOG_TABLES.length);
|
|
593
557
|
const merged = mergeAll(/* @__PURE__ */ new Map(), attempt.values());
|
|
@@ -601,24 +565,18 @@ const createAggregateBatches = ({ engine, adapter, schema, batching: { mode = "l
|
|
|
601
565
|
open = false;
|
|
602
566
|
}
|
|
603
567
|
});
|
|
604
|
-
if (changes.size > 0) await
|
|
568
|
+
if (changes.size > 0 && now() >= nextDue) await compact(false, GROUPS.commit);
|
|
605
569
|
return result;
|
|
606
570
|
},
|
|
607
571
|
async beforeRead(name) {
|
|
608
572
|
if (!isBatched(schema.models.get(name))) return;
|
|
609
|
-
if (
|
|
610
|
-
|
|
611
|
-
|
|
612
|
-
|
|
613
|
-
return false;
|
|
614
|
-
})) await compact(true, GROUPS.read);
|
|
615
|
-
}
|
|
573
|
+
if (await hasPending().catch((error) => {
|
|
574
|
+
warn("read")(error);
|
|
575
|
+
return false;
|
|
576
|
+
})) await compact(true, GROUPS.read);
|
|
616
577
|
},
|
|
617
|
-
flush
|
|
618
|
-
|
|
619
|
-
clearTimeout(timer);
|
|
620
|
-
timer = void 0;
|
|
621
|
-
await flush();
|
|
578
|
+
async flush() {
|
|
579
|
+
if (await hasPending()) await compact(true, GROUPS.flush);
|
|
622
580
|
}
|
|
623
581
|
};
|
|
624
582
|
};
|
|
@@ -35,13 +35,10 @@ const createDatabaseEngine = ({ batching, now = Date.now, meter, ...options }) =
|
|
|
35
35
|
};
|
|
36
36
|
return {
|
|
37
37
|
...engine,
|
|
38
|
-
/** Applies batched aggregate changes still
|
|
38
|
+
/** Applies the batched aggregate changes still in the log. */
|
|
39
39
|
flush: async () => {
|
|
40
40
|
await batches?.flush();
|
|
41
41
|
},
|
|
42
|
-
dispose: async () => {
|
|
43
|
-
await batches?.dispose();
|
|
44
|
-
},
|
|
45
42
|
database(module) {
|
|
46
43
|
const name = (model) => module.namespace ? `${module.namespace}_${model}` : model;
|
|
47
44
|
return {
|
|
@@ -35,13 +35,10 @@ const createDatabaseEngine = ({ batching, now = Date.now, meter, ...options }) =
|
|
|
35
35
|
};
|
|
36
36
|
return {
|
|
37
37
|
...engine,
|
|
38
|
-
/** Applies batched aggregate changes still
|
|
38
|
+
/** Applies the batched aggregate changes still in the log. */
|
|
39
39
|
flush: async () => {
|
|
40
40
|
await batches?.flush();
|
|
41
41
|
},
|
|
42
|
-
dispose: async () => {
|
|
43
|
-
await batches?.dispose();
|
|
44
|
-
},
|
|
45
42
|
database(module) {
|
|
46
43
|
const name = (model) => module.namespace ? `${module.namespace}_${model}` : model;
|
|
47
44
|
return {
|
|
@@ -6,6 +6,12 @@ const require_engineAggregates = require("./engineAggregates.cjs");
|
|
|
6
6
|
/** A row this attempt read changed while it ran; the attempt reruns. */
|
|
7
7
|
var StaleReadError = class extends Error {};
|
|
8
8
|
const idOf = (table, key) => JSON.stringify([table, key]);
|
|
9
|
+
/** The aggregate rows a write changes, at the versions it read them. */
|
|
10
|
+
const versionsOf = (ops) => JSON.stringify(ops.map((op) => op.type === "insert" ? [op.table.name, require_adapter.rowKey(op.table, op.row)] : [
|
|
11
|
+
op.table.name,
|
|
12
|
+
op.key,
|
|
13
|
+
"guard" in op ? op.guard?.v : void 0
|
|
14
|
+
]));
|
|
9
15
|
const versionOf = (row) => Number(row["_v"]);
|
|
10
16
|
const isKeyed = (value) => value !== null && value !== void 0;
|
|
11
17
|
const misuse = (table, message) => new require_errors.DatabaseTransactionError(`${table}: ${message}`);
|
|
@@ -350,7 +356,9 @@ const createTransactions = ({ adapter, schema, reads, retry = {} }) => {
|
|
|
350
356
|
assertOutsideTransaction();
|
|
351
357
|
let run;
|
|
352
358
|
let negative;
|
|
353
|
-
|
|
359
|
+
let failures = 0;
|
|
360
|
+
let lost;
|
|
361
|
+
for (let round = 0;; round += 1) {
|
|
354
362
|
const delay = round && Math.min(maxDelayMs, baseDelayMs * 2 ** (round - 1));
|
|
355
363
|
if (delay > 0) await new Promise((resolve) => setTimeout(resolve, delay / 2 + Math.random() * (delay / 2)));
|
|
356
364
|
run ??= await attempt(fn).catch((error) => {
|
|
@@ -359,6 +367,8 @@ const createTransactions = ({ adapter, schema, reads, retry = {} }) => {
|
|
|
359
367
|
});
|
|
360
368
|
if (run === void 0) {
|
|
361
369
|
onRetry?.("rerun", round + 1);
|
|
370
|
+
lost = void 0;
|
|
371
|
+
if ((failures += 1) >= attempts) break;
|
|
362
372
|
continue;
|
|
363
373
|
}
|
|
364
374
|
let aggregates;
|
|
@@ -369,8 +379,14 @@ const createTransactions = ({ adapter, schema, reads, retry = {} }) => {
|
|
|
369
379
|
negative = error;
|
|
370
380
|
onRetry?.("rerun", round + 1);
|
|
371
381
|
run = void 0;
|
|
382
|
+
lost = void 0;
|
|
383
|
+
if ((failures += 1) >= attempts) break;
|
|
372
384
|
continue;
|
|
373
385
|
}
|
|
386
|
+
const versions = versionsOf(aggregates);
|
|
387
|
+
if (lost !== void 0 && versions !== lost) failures -= 1;
|
|
388
|
+
lost = void 0;
|
|
389
|
+
if (failures >= attempts) break;
|
|
374
390
|
const ops = [...run.ops, ...aggregates];
|
|
375
391
|
if (ops.length <= 1 && ops.every(({ type }) => type === "check")) return run.result;
|
|
376
392
|
if (!adapter.fits(ops)) throw new require_errors.DatabaseConstraintError("too_large", ops[0].table.name);
|
|
@@ -384,12 +400,16 @@ const createTransactions = ({ adapter, schema, reads, retry = {} }) => {
|
|
|
384
400
|
const failed = "failedOp" in outcome ? outcome.failedOp : void 0;
|
|
385
401
|
if (failed === void 0 || failed >= run.ops.length) {
|
|
386
402
|
onRetry?.("resend", round + 1);
|
|
403
|
+
failures += 1;
|
|
404
|
+
if (failed !== void 0) lost = versions;
|
|
405
|
+
else if (failures >= attempts) break;
|
|
387
406
|
continue;
|
|
388
407
|
}
|
|
389
408
|
const reason = await classify(ops[failed], run.read);
|
|
390
409
|
if (reason) throw new require_errors.DatabaseConstraintError(reason, ops[failed].table.name);
|
|
391
410
|
onRetry?.("rerun", round + 1);
|
|
392
411
|
run = void 0;
|
|
412
|
+
if ((failures += 1) >= attempts) break;
|
|
393
413
|
}
|
|
394
414
|
throw negative ?? new require_errors.DatabaseConflictError(`The transaction conflicted ${attempts} times.`);
|
|
395
415
|
} };
|
|
@@ -5,7 +5,11 @@
|
|
|
5
5
|
* observe each rerun.
|
|
6
6
|
*/
|
|
7
7
|
interface RetryOptions {
|
|
8
|
-
/**
|
|
8
|
+
/**
|
|
9
|
+
* How many failed rounds a transaction takes before it fails; 8 by default.
|
|
10
|
+
* A resend that lost its aggregate rows to another writer's commit does not
|
|
11
|
+
* count: it reads them again until it applies.
|
|
12
|
+
*/
|
|
9
13
|
readonly attempts?: number;
|
|
10
14
|
/** The wait before the second attempt, doubling after each; 5 ms by default. */
|
|
11
15
|
readonly baseDelayMs?: number;
|
|
@@ -5,7 +5,11 @@
|
|
|
5
5
|
* observe each rerun.
|
|
6
6
|
*/
|
|
7
7
|
interface RetryOptions {
|
|
8
|
-
/**
|
|
8
|
+
/**
|
|
9
|
+
* How many failed rounds a transaction takes before it fails; 8 by default.
|
|
10
|
+
* A resend that lost its aggregate rows to another writer's commit does not
|
|
11
|
+
* count: it reads them again until it applies.
|
|
12
|
+
*/
|
|
9
13
|
readonly attempts?: number;
|
|
10
14
|
/** The wait before the second attempt, doubling after each; 5 ms by default. */
|
|
11
15
|
readonly baseDelayMs?: number;
|
|
@@ -6,6 +6,12 @@ import { NegativeGaugeError, compileAggregates, recordAggregate } from "./engine
|
|
|
6
6
|
/** A row this attempt read changed while it ran; the attempt reruns. */
|
|
7
7
|
var StaleReadError = class extends Error {};
|
|
8
8
|
const idOf = (table, key) => JSON.stringify([table, key]);
|
|
9
|
+
/** The aggregate rows a write changes, at the versions it read them. */
|
|
10
|
+
const versionsOf = (ops) => JSON.stringify(ops.map((op) => op.type === "insert" ? [op.table.name, rowKey(op.table, op.row)] : [
|
|
11
|
+
op.table.name,
|
|
12
|
+
op.key,
|
|
13
|
+
"guard" in op ? op.guard?.v : void 0
|
|
14
|
+
]));
|
|
9
15
|
const versionOf = (row) => Number(row["_v"]);
|
|
10
16
|
const isKeyed = (value) => value !== null && value !== void 0;
|
|
11
17
|
const misuse = (table, message) => new DatabaseTransactionError(`${table}: ${message}`);
|
|
@@ -350,7 +356,9 @@ const createTransactions = ({ adapter, schema, reads, retry = {} }) => {
|
|
|
350
356
|
assertOutsideTransaction();
|
|
351
357
|
let run;
|
|
352
358
|
let negative;
|
|
353
|
-
|
|
359
|
+
let failures = 0;
|
|
360
|
+
let lost;
|
|
361
|
+
for (let round = 0;; round += 1) {
|
|
354
362
|
const delay = round && Math.min(maxDelayMs, baseDelayMs * 2 ** (round - 1));
|
|
355
363
|
if (delay > 0) await new Promise((resolve) => setTimeout(resolve, delay / 2 + Math.random() * (delay / 2)));
|
|
356
364
|
run ??= await attempt(fn).catch((error) => {
|
|
@@ -359,6 +367,8 @@ const createTransactions = ({ adapter, schema, reads, retry = {} }) => {
|
|
|
359
367
|
});
|
|
360
368
|
if (run === void 0) {
|
|
361
369
|
onRetry?.("rerun", round + 1);
|
|
370
|
+
lost = void 0;
|
|
371
|
+
if ((failures += 1) >= attempts) break;
|
|
362
372
|
continue;
|
|
363
373
|
}
|
|
364
374
|
let aggregates;
|
|
@@ -369,8 +379,14 @@ const createTransactions = ({ adapter, schema, reads, retry = {} }) => {
|
|
|
369
379
|
negative = error;
|
|
370
380
|
onRetry?.("rerun", round + 1);
|
|
371
381
|
run = void 0;
|
|
382
|
+
lost = void 0;
|
|
383
|
+
if ((failures += 1) >= attempts) break;
|
|
372
384
|
continue;
|
|
373
385
|
}
|
|
386
|
+
const versions = versionsOf(aggregates);
|
|
387
|
+
if (lost !== void 0 && versions !== lost) failures -= 1;
|
|
388
|
+
lost = void 0;
|
|
389
|
+
if (failures >= attempts) break;
|
|
374
390
|
const ops = [...run.ops, ...aggregates];
|
|
375
391
|
if (ops.length <= 1 && ops.every(({ type }) => type === "check")) return run.result;
|
|
376
392
|
if (!adapter.fits(ops)) throw new DatabaseConstraintError("too_large", ops[0].table.name);
|
|
@@ -384,12 +400,16 @@ const createTransactions = ({ adapter, schema, reads, retry = {} }) => {
|
|
|
384
400
|
const failed = "failedOp" in outcome ? outcome.failedOp : void 0;
|
|
385
401
|
if (failed === void 0 || failed >= run.ops.length) {
|
|
386
402
|
onRetry?.("resend", round + 1);
|
|
403
|
+
failures += 1;
|
|
404
|
+
if (failed !== void 0) lost = versions;
|
|
405
|
+
else if (failures >= attempts) break;
|
|
387
406
|
continue;
|
|
388
407
|
}
|
|
389
408
|
const reason = await classify(ops[failed], run.read);
|
|
390
409
|
if (reason) throw new DatabaseConstraintError(reason, ops[failed].table.name);
|
|
391
410
|
onRetry?.("rerun", round + 1);
|
|
392
411
|
run = void 0;
|
|
412
|
+
if ((failures += 1) >= attempts) break;
|
|
393
413
|
}
|
|
394
414
|
throw negative ?? new DatabaseConflictError(`The transaction conflicted ${attempts} times.`);
|
|
395
415
|
} };
|
|
@@ -67,10 +67,10 @@ const createKvAdapter = ({ store, tablePrefix = "" }) => {
|
|
|
67
67
|
const at = row && require_adapter.expiresAt(table, row);
|
|
68
68
|
return at === void 0 ? {} : { expiresAt: at };
|
|
69
69
|
};
|
|
70
|
-
/** Every index and unique item a row has, by address. */
|
|
71
|
-
const itemsOf = (layout, row) => {
|
|
70
|
+
/** Every index and unique item a row has, by address: in `indexes`, if given. */
|
|
71
|
+
const itemsOf = (layout, row, indexes = layout.indexed) => {
|
|
72
72
|
const items = /* @__PURE__ */ new Map();
|
|
73
|
-
for (const index of row === null ? [] :
|
|
73
|
+
for (const index of row === null ? [] : indexes) for (const eq of require_values.indexEntries(layout.table, index, row)) {
|
|
74
74
|
const pk = partition(layout, index, eq);
|
|
75
75
|
const sk = index.unique ? ONLY : encodeKvKey(require_values.indexOrderTuple(layout.table, index, row)) || ONLY;
|
|
76
76
|
items.set(JSON.stringify([pk, sk]), {
|
|
@@ -225,6 +225,79 @@ const createKvAdapter = ({ store, tablePrefix = "" }) => {
|
|
|
225
225
|
lte: lt.endsWith(SEPARATOR) ? lt.slice(0, -1) : lt
|
|
226
226
|
};
|
|
227
227
|
};
|
|
228
|
+
/** One row's check and its item puts in `index`, copies of the row as it is. */
|
|
229
|
+
const fillOps = (layout, index, row) => [{
|
|
230
|
+
type: "check",
|
|
231
|
+
key: rowItem(layout, require_adapter.rowKey(layout.table, row)),
|
|
232
|
+
condition: { v: Number(row["_v"]) }
|
|
233
|
+
}, ...[...itemsOf(layout, row, [index]).values()].map(({ key }) => ({
|
|
234
|
+
type: "put",
|
|
235
|
+
key,
|
|
236
|
+
value: copyOf(layout, row),
|
|
237
|
+
...stamp(layout.table, row)
|
|
238
|
+
}))];
|
|
239
|
+
/**
|
|
240
|
+
* Writes one row's items in `index`, checking the row's `_v` in the same
|
|
241
|
+
* write: a row that changed is read again, and a deleted one needs none.
|
|
242
|
+
*/
|
|
243
|
+
const fillRow = async (layout, index, first) => {
|
|
244
|
+
const key = rowItem(layout, require_adapter.rowKey(layout.table, first));
|
|
245
|
+
let row = first;
|
|
246
|
+
for (let attempt = 0; row !== null; attempt += 1) {
|
|
247
|
+
if (attempt === 8) throw new Error(`${layout.table.name}.${index.name}: a row kept changing while its index items were written; run the migration again.`);
|
|
248
|
+
if ((await store.write(fillOps(layout, index, row))).ok) return;
|
|
249
|
+
[row] = await store.get([key]);
|
|
250
|
+
}
|
|
251
|
+
};
|
|
252
|
+
/**
|
|
253
|
+
* Finds the rows that lack an item in `index` and, unless `dryRun`, writes
|
|
254
|
+
* them, as many rows per atomic write as the store takes. It reads every
|
|
255
|
+
* row and its items, page by page.
|
|
256
|
+
*/
|
|
257
|
+
const fillIndex = async (table, name, { dryRun = false } = {}) => {
|
|
258
|
+
const layout = layoutOf(table);
|
|
259
|
+
const index = layout.indexed.find((candidate) => candidate.name === name);
|
|
260
|
+
if (index === void 0) return 0;
|
|
261
|
+
if (index.unique) throw new require_verifyAdapter.DatabaseAdapterContractError(`${table.name}.${name} is unique: its items can't be written for rows stored before it, since two of them may hold one value.`);
|
|
262
|
+
const { items: most, bytes } = store.limits;
|
|
263
|
+
let lacking = 0;
|
|
264
|
+
for (let after;;) {
|
|
265
|
+
const page = await store.query({
|
|
266
|
+
pk: layout.rows,
|
|
267
|
+
order: "asc",
|
|
268
|
+
limit: 100,
|
|
269
|
+
after
|
|
270
|
+
});
|
|
271
|
+
const rows = page.items.map(({ value }) => value);
|
|
272
|
+
const keys = rows.map((row) => [...itemsOf(layout, row, [index]).values()].map(({ key }) => key));
|
|
273
|
+
const wanted = keys.flat();
|
|
274
|
+
const found = wanted.length === 0 ? [] : await store.get(wanted);
|
|
275
|
+
let at = 0;
|
|
276
|
+
const missing = rows.filter((_, position) => {
|
|
277
|
+
return found.slice(at, at += keys[position].length).some((item) => item === null);
|
|
278
|
+
});
|
|
279
|
+
lacking += missing.length;
|
|
280
|
+
if (!dryRun) {
|
|
281
|
+
let chunk = [];
|
|
282
|
+
let ops = [];
|
|
283
|
+
const flush = async () => {
|
|
284
|
+
if (ops.length > 0 && !(await store.write(ops)).ok) for (const row of chunk) await fillRow(layout, index, row);
|
|
285
|
+
chunk = [];
|
|
286
|
+
ops = [];
|
|
287
|
+
};
|
|
288
|
+
for (const row of missing) {
|
|
289
|
+
const next = fillOps(layout, index, row);
|
|
290
|
+
const size = (list) => list.reduce((sum, op) => sum + encoder.encode(op.key.pk + op.key.sk + JSON.stringify(op.type === "put" ? op.value : null)).length, 0);
|
|
291
|
+
if (chunk.length > 0 && (ops.length + next.length > most || size(ops) + size(next) > bytes)) await flush();
|
|
292
|
+
chunk.push(row);
|
|
293
|
+
ops.push(...next);
|
|
294
|
+
}
|
|
295
|
+
await flush();
|
|
296
|
+
}
|
|
297
|
+
if (!page.more || page.items.length === 0) return lacking;
|
|
298
|
+
after = page.items.at(-1).sk;
|
|
299
|
+
}
|
|
300
|
+
};
|
|
228
301
|
return {
|
|
229
302
|
id: store.id,
|
|
230
303
|
fits(ops) {
|
|
@@ -284,7 +357,10 @@ const createKvAdapter = ({ store, tablePrefix = "" }) => {
|
|
|
284
357
|
const layout = layoutOf(table);
|
|
285
358
|
return store.deleteConsumed(rows.flatMap((row) => [rowItem(layout, require_adapter.rowKey(table, row)), ...[...itemsOf(layout, row).values()].map(({ key }) => key)]));
|
|
286
359
|
} },
|
|
287
|
-
migrations: {
|
|
360
|
+
migrations: {
|
|
361
|
+
apply: async () => store.migrations?.apply(),
|
|
362
|
+
fillIndex
|
|
363
|
+
},
|
|
288
364
|
...store.dispose === void 0 ? {} : { dispose: () => store.dispose() }
|
|
289
365
|
};
|
|
290
366
|
};
|