@hot-updater/plugin-core 1.1.15 → 1.1.16

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.
@@ -31,6 +31,12 @@ const WINDOW_MS = {
31
31
  /** Log rows a compaction reads from each log table for one group. */
32
32
  const LOG_PAGE = 200;
33
33
  /**
34
+ * How old a log row this process can't apply must be before its reads step
35
+ * past it: older than any transaction still committing, between servers
36
+ * whose clocks agree this closely.
37
+ */
38
+ const SKIP_AFTER_MS = 3e5;
39
+ /**
34
40
  * Groups one compaction applies: after a commit, so the request that runs
35
41
  * it waits for one group; before a read; and on flush.
36
42
  */
@@ -163,24 +169,44 @@ const rewrite = (change, key, current) => {
163
169
  previous: current
164
170
  };
165
171
  };
172
+ /** A shard row's place in what `readCurrent` read. */
173
+ const rowId = (model, key) => JSON.stringify([model.table.name, key]);
174
+ /** The shard key each change writes. */
175
+ const keysOf = (changes, shard) => changes.map(({ model, key }) => [...key.slice(0, -1), shard(model)]);
166
176
  /**
167
- * The write for each change on its shard: a blind increment that creates
168
- * the row for counters, and a guarded rewrite for gauges and sketches, whose
169
- * rows are read in one batch per table.
177
+ * The current rows of the changes that rewrite theirs (gauges and sketches),
178
+ * each once, in one batch per table.
170
179
  */
171
- const compile = async (adapter, changes, shard) => {
172
- const keys = changes.map(({ model, key }) => [...key.slice(0, -1), shard(model)]);
180
+ const readCurrent = async (adapter, changes, shard) => {
181
+ const keys = keysOf(changes, shard);
173
182
  const reads = /* @__PURE__ */ new Map();
174
183
  changes.forEach((change, at) => {
175
- if (rewrites(change)) reads.set(change.model, [...reads.get(change.model) ?? [], at]);
184
+ if (!rewrites(change)) return;
185
+ const wanted = reads.get(change.model) ?? /* @__PURE__ */ new Map();
186
+ wanted.set(rowId(change.model, keys[at]), keys[at]);
187
+ reads.set(change.model, wanted);
176
188
  });
177
189
  const current = /* @__PURE__ */ new Map();
178
- await Promise.all([...reads].map(async ([model, positions]) => {
179
- const rows = await adapter.get(model.table, positions.map((at) => keys[at]));
180
- positions.forEach((at, index) => current.set(at, rows[index] ?? null));
190
+ await Promise.all([...reads].map(async ([model, wanted]) => {
191
+ const keys = [...wanted.values()];
192
+ const rows = await adapter.get(model.table, keys);
193
+ keys.forEach((key, at) => {
194
+ current.set(rowId(model, key), rows[at] ?? null);
195
+ });
181
196
  }));
182
- return changes.map((change, at) => current.has(at) ? rewrite(change, keys[at], current.get(at)) : increment(change, keys[at]));
197
+ return current;
183
198
  };
199
+ /**
200
+ * The write for each change on its shard: a blind increment that creates
201
+ * the row for counters, and a guarded rewrite for gauges and sketches, over
202
+ * the rows `current` read.
203
+ */
204
+ const build = (changes, shard, current) => {
205
+ const keys = keysOf(changes, shard);
206
+ return changes.map((change, at) => rewrites(change) ? rewrite(change, keys[at], current.get(rowId(change.model, keys[at])) ?? null) : increment(change, keys[at]));
207
+ };
208
+ /** `build` over rows read for these changes. */
209
+ const compile = async (adapter, changes, shard) => build(changes, shard, await readCurrent(adapter, changes, shard));
184
210
  const isOp = (op) => op !== void 0;
185
211
  const sleep = (attempt) => new Promise((resolve) => setTimeout(resolve, Math.min(250, 5 * 2 ** attempt) * Math.random()));
186
212
  /** Runs of one character, where shorter: a sparse sketch packs into a few. */
@@ -324,6 +350,16 @@ const createAggregateBatches = ({ engine, adapter, schema, batching: { mode = "l
324
350
  let compacting;
325
351
  /** Log rows this process read, by `[log table's index, id]`, for the deletes after a group. */
326
352
  const known = /* @__PURE__ */ new Map();
353
+ /**
354
+ * Each log table's last row of a run at its head that this process can't
355
+ * apply (it names an aggregate or metric this schema lacks), whose reads
356
+ * start past it. The rows wait for a process that can apply them, and a
357
+ * restart reads them again.
358
+ */
359
+ const skipped = LOG_TABLES.map(() => void 0);
360
+ const past = (shard) => skipped[shard] === void 0 ? {} : { range: { gt: skipped[shard] } };
361
+ /** When a log row's transaction stamped its ID. */
362
+ const stampOf = (id) => Number.parseInt(id.slice(0, 9), 36);
327
363
  const idOf = (shard, id) => JSON.stringify([shard, id]);
328
364
  /** The lease row as stored once `set` is written over it. */
329
365
  const leaseOp = (held, set) => {
@@ -439,14 +475,22 @@ const createAggregateBatches = ({ engine, adapter, schema, batching: { mode = "l
439
475
  logs: (await Promise.all(LOG_TABLES.map(async (name, shard) => {
440
476
  const page = await engine.reads.findMany(name, {
441
477
  index: "oldest",
442
- limit: LOG_PAGE
478
+ limit: LOG_PAGE,
479
+ ...past(shard)
443
480
  });
444
481
  more ||= page.next !== void 0;
445
- return (await Promise.all(page.rows.map(async (row) => ({
482
+ const decoded = await Promise.all(page.rows.map(async (row) => ({
446
483
  shard,
447
484
  row,
448
485
  changes: await decode(String(row.changes))
449
- })))).flatMap(({ changes, ...entry }) => changes === void 0 ? [] : [{
486
+ })));
487
+ const settled = now() - SKIP_AFTER_MS;
488
+ for (const { row, changes } of decoded) {
489
+ const id = String(row.id);
490
+ if (changes !== void 0 || stampOf(id) >= settled) break;
491
+ skipped[shard] = id;
492
+ }
493
+ return decoded.flatMap(({ changes, ...entry }) => changes === void 0 ? [] : [{
450
494
  ...entry,
451
495
  changes
452
496
  }]);
@@ -454,7 +498,6 @@ const createAggregateBatches = ({ engine, adapter, schema, batching: { mode = "l
454
498
  more
455
499
  };
456
500
  };
457
- const rowsFor = async (changes) => (await compile(adapter, changes, () => 0)).filter(isOp);
458
501
  /**
459
502
  * Applies the oldest pending log rows whose merged changes fit in one
460
503
  * atomic write with the lease, which lists them as applied; the rows are
@@ -463,12 +506,14 @@ const createAggregateBatches = ({ engine, adapter, schema, batching: { mode = "l
463
506
  * log rows it applied whole, or undefined when a conflict stopped it.
464
507
  */
465
508
  const applyGroup = async (held, logs) => {
509
+ const current = await readCurrent(adapter, logs.flatMap((entry) => [...entry.changes.values()]), () => 0);
510
+ const rowsFor = (changes) => build(changes, () => 0, current).filter(isOp);
466
511
  for (let count = logs.length; count > 0; count = Math.floor(count / 2)) {
467
512
  const batch = logs.slice(0, count);
468
513
  const changes = mergeAll(/* @__PURE__ */ new Map(), batch.flatMap((entry) => [...entry.changes.values()]));
469
514
  const applied = batch.map(({ shard, row }) => [shard, row.id]);
470
515
  const lease = leaseOp(held, { applied: JSON.stringify(applied) });
471
- const ops = [...await rowsFor([...changes.values()]), lease.op];
516
+ const ops = [...rowsFor([...changes.values()]), lease.op];
472
517
  if (!adapter.fits(ops)) continue;
473
518
  for (const { shard, row } of batch) known.set(idOf(shard, row.id), row);
474
519
  return await commit(ops) ? {
@@ -490,7 +535,7 @@ const createAggregateBatches = ({ engine, adapter, schema, batching: { mode = "l
490
535
  };
491
536
  const lease = leaseOp(held, {});
492
537
  const ops = [
493
- ...await rowsFor(entries.slice(0, take)),
538
+ ...rowsFor(entries.slice(0, take)),
494
539
  kept,
495
540
  lease.op
496
541
  ];
@@ -511,11 +556,12 @@ const createAggregateBatches = ({ engine, adapter, schema, batching: { mode = "l
511
556
  if (held === void 0) return;
512
557
  let pending = true;
513
558
  let clear = false;
559
+ let carried;
514
560
  try {
515
561
  for (let group = 0;; group += 1) {
516
562
  clear = await deleteApplied(held);
517
563
  if (!clear || !pending || group === groups) break;
518
- const { logs, more } = await readLogs();
564
+ const { logs, more } = carried ?? await readLogs();
519
565
  if (logs.length === 0) {
520
566
  pending = false;
521
567
  break;
@@ -523,6 +569,11 @@ const createAggregateBatches = ({ engine, adapter, schema, batching: { mode = "l
523
569
  const applied = await applyGroup(held, logs);
524
570
  if (applied === void 0) break;
525
571
  [held, clear] = [applied.held, false];
572
+ const rest = applied.count === 0 ? [] : logs.slice(applied.count);
573
+ carried = rest.length > 0 ? {
574
+ logs: rest,
575
+ more
576
+ } : void 0;
526
577
  pending = more || applied.count < logs.length;
527
578
  }
528
579
  } finally {
@@ -542,9 +593,10 @@ const createAggregateBatches = ({ engine, adapter, schema, batching: { mode = "l
542
593
  });
543
594
  let checking;
544
595
  /** 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, {
596
+ const hasPending = () => checking ??= Promise.all(LOG_TABLES.map((name, shard) => engine.reads.findMany(name, {
546
597
  index: "oldest",
547
- limit: 1
598
+ limit: 1,
599
+ ...past(shard)
548
600
  }))).then((pages) => pages.some((page) => page.rows.length > 0)).finally(() => {
549
601
  checking = void 0;
550
602
  });
@@ -31,6 +31,12 @@ const WINDOW_MS = {
31
31
  /** Log rows a compaction reads from each log table for one group. */
32
32
  const LOG_PAGE = 200;
33
33
  /**
34
+ * How old a log row this process can't apply must be before its reads step
35
+ * past it: older than any transaction still committing, between servers
36
+ * whose clocks agree this closely.
37
+ */
38
+ const SKIP_AFTER_MS = 3e5;
39
+ /**
34
40
  * Groups one compaction applies: after a commit, so the request that runs
35
41
  * it waits for one group; before a read; and on flush.
36
42
  */
@@ -163,24 +169,44 @@ const rewrite = (change, key, current) => {
163
169
  previous: current
164
170
  };
165
171
  };
172
+ /** A shard row's place in what `readCurrent` read. */
173
+ const rowId = (model, key) => JSON.stringify([model.table.name, key]);
174
+ /** The shard key each change writes. */
175
+ const keysOf = (changes, shard) => changes.map(({ model, key }) => [...key.slice(0, -1), shard(model)]);
166
176
  /**
167
- * The write for each change on its shard: a blind increment that creates
168
- * the row for counters, and a guarded rewrite for gauges and sketches, whose
169
- * rows are read in one batch per table.
177
+ * The current rows of the changes that rewrite theirs (gauges and sketches),
178
+ * each once, in one batch per table.
170
179
  */
171
- const compile = async (adapter, changes, shard) => {
172
- const keys = changes.map(({ model, key }) => [...key.slice(0, -1), shard(model)]);
180
+ const readCurrent = async (adapter, changes, shard) => {
181
+ const keys = keysOf(changes, shard);
173
182
  const reads = /* @__PURE__ */ new Map();
174
183
  changes.forEach((change, at) => {
175
- if (rewrites(change)) reads.set(change.model, [...reads.get(change.model) ?? [], at]);
184
+ if (!rewrites(change)) return;
185
+ const wanted = reads.get(change.model) ?? /* @__PURE__ */ new Map();
186
+ wanted.set(rowId(change.model, keys[at]), keys[at]);
187
+ reads.set(change.model, wanted);
176
188
  });
177
189
  const current = /* @__PURE__ */ new Map();
178
- await Promise.all([...reads].map(async ([model, positions]) => {
179
- const rows = await adapter.get(model.table, positions.map((at) => keys[at]));
180
- positions.forEach((at, index) => current.set(at, rows[index] ?? null));
190
+ await Promise.all([...reads].map(async ([model, wanted]) => {
191
+ const keys = [...wanted.values()];
192
+ const rows = await adapter.get(model.table, keys);
193
+ keys.forEach((key, at) => {
194
+ current.set(rowId(model, key), rows[at] ?? null);
195
+ });
181
196
  }));
182
- return changes.map((change, at) => current.has(at) ? rewrite(change, keys[at], current.get(at)) : increment(change, keys[at]));
197
+ return current;
183
198
  };
199
+ /**
200
+ * The write for each change on its shard: a blind increment that creates
201
+ * the row for counters, and a guarded rewrite for gauges and sketches, over
202
+ * the rows `current` read.
203
+ */
204
+ const build = (changes, shard, current) => {
205
+ const keys = keysOf(changes, shard);
206
+ return changes.map((change, at) => rewrites(change) ? rewrite(change, keys[at], current.get(rowId(change.model, keys[at])) ?? null) : increment(change, keys[at]));
207
+ };
208
+ /** `build` over rows read for these changes. */
209
+ const compile = async (adapter, changes, shard) => build(changes, shard, await readCurrent(adapter, changes, shard));
184
210
  const isOp = (op) => op !== void 0;
185
211
  const sleep = (attempt) => new Promise((resolve) => setTimeout(resolve, Math.min(250, 5 * 2 ** attempt) * Math.random()));
186
212
  /** Runs of one character, where shorter: a sparse sketch packs into a few. */
@@ -324,6 +350,16 @@ const createAggregateBatches = ({ engine, adapter, schema, batching: { mode = "l
324
350
  let compacting;
325
351
  /** Log rows this process read, by `[log table's index, id]`, for the deletes after a group. */
326
352
  const known = /* @__PURE__ */ new Map();
353
+ /**
354
+ * Each log table's last row of a run at its head that this process can't
355
+ * apply (it names an aggregate or metric this schema lacks), whose reads
356
+ * start past it. The rows wait for a process that can apply them, and a
357
+ * restart reads them again.
358
+ */
359
+ const skipped = LOG_TABLES.map(() => void 0);
360
+ const past = (shard) => skipped[shard] === void 0 ? {} : { range: { gt: skipped[shard] } };
361
+ /** When a log row's transaction stamped its ID. */
362
+ const stampOf = (id) => Number.parseInt(id.slice(0, 9), 36);
327
363
  const idOf = (shard, id) => JSON.stringify([shard, id]);
328
364
  /** The lease row as stored once `set` is written over it. */
329
365
  const leaseOp = (held, set) => {
@@ -439,14 +475,22 @@ const createAggregateBatches = ({ engine, adapter, schema, batching: { mode = "l
439
475
  logs: (await Promise.all(LOG_TABLES.map(async (name, shard) => {
440
476
  const page = await engine.reads.findMany(name, {
441
477
  index: "oldest",
442
- limit: LOG_PAGE
478
+ limit: LOG_PAGE,
479
+ ...past(shard)
443
480
  });
444
481
  more ||= page.next !== void 0;
445
- return (await Promise.all(page.rows.map(async (row) => ({
482
+ const decoded = await Promise.all(page.rows.map(async (row) => ({
446
483
  shard,
447
484
  row,
448
485
  changes: await decode(String(row.changes))
449
- })))).flatMap(({ changes, ...entry }) => changes === void 0 ? [] : [{
486
+ })));
487
+ const settled = now() - SKIP_AFTER_MS;
488
+ for (const { row, changes } of decoded) {
489
+ const id = String(row.id);
490
+ if (changes !== void 0 || stampOf(id) >= settled) break;
491
+ skipped[shard] = id;
492
+ }
493
+ return decoded.flatMap(({ changes, ...entry }) => changes === void 0 ? [] : [{
450
494
  ...entry,
451
495
  changes
452
496
  }]);
@@ -454,7 +498,6 @@ const createAggregateBatches = ({ engine, adapter, schema, batching: { mode = "l
454
498
  more
455
499
  };
456
500
  };
457
- const rowsFor = async (changes) => (await compile(adapter, changes, () => 0)).filter(isOp);
458
501
  /**
459
502
  * Applies the oldest pending log rows whose merged changes fit in one
460
503
  * atomic write with the lease, which lists them as applied; the rows are
@@ -463,12 +506,14 @@ const createAggregateBatches = ({ engine, adapter, schema, batching: { mode = "l
463
506
  * log rows it applied whole, or undefined when a conflict stopped it.
464
507
  */
465
508
  const applyGroup = async (held, logs) => {
509
+ const current = await readCurrent(adapter, logs.flatMap((entry) => [...entry.changes.values()]), () => 0);
510
+ const rowsFor = (changes) => build(changes, () => 0, current).filter(isOp);
466
511
  for (let count = logs.length; count > 0; count = Math.floor(count / 2)) {
467
512
  const batch = logs.slice(0, count);
468
513
  const changes = mergeAll(/* @__PURE__ */ new Map(), batch.flatMap((entry) => [...entry.changes.values()]));
469
514
  const applied = batch.map(({ shard, row }) => [shard, row.id]);
470
515
  const lease = leaseOp(held, { applied: JSON.stringify(applied) });
471
- const ops = [...await rowsFor([...changes.values()]), lease.op];
516
+ const ops = [...rowsFor([...changes.values()]), lease.op];
472
517
  if (!adapter.fits(ops)) continue;
473
518
  for (const { shard, row } of batch) known.set(idOf(shard, row.id), row);
474
519
  return await commit(ops) ? {
@@ -490,7 +535,7 @@ const createAggregateBatches = ({ engine, adapter, schema, batching: { mode = "l
490
535
  };
491
536
  const lease = leaseOp(held, {});
492
537
  const ops = [
493
- ...await rowsFor(entries.slice(0, take)),
538
+ ...rowsFor(entries.slice(0, take)),
494
539
  kept,
495
540
  lease.op
496
541
  ];
@@ -511,11 +556,12 @@ const createAggregateBatches = ({ engine, adapter, schema, batching: { mode = "l
511
556
  if (held === void 0) return;
512
557
  let pending = true;
513
558
  let clear = false;
559
+ let carried;
514
560
  try {
515
561
  for (let group = 0;; group += 1) {
516
562
  clear = await deleteApplied(held);
517
563
  if (!clear || !pending || group === groups) break;
518
- const { logs, more } = await readLogs();
564
+ const { logs, more } = carried ?? await readLogs();
519
565
  if (logs.length === 0) {
520
566
  pending = false;
521
567
  break;
@@ -523,6 +569,11 @@ const createAggregateBatches = ({ engine, adapter, schema, batching: { mode = "l
523
569
  const applied = await applyGroup(held, logs);
524
570
  if (applied === void 0) break;
525
571
  [held, clear] = [applied.held, false];
572
+ const rest = applied.count === 0 ? [] : logs.slice(applied.count);
573
+ carried = rest.length > 0 ? {
574
+ logs: rest,
575
+ more
576
+ } : void 0;
526
577
  pending = more || applied.count < logs.length;
527
578
  }
528
579
  } finally {
@@ -542,9 +593,10 @@ const createAggregateBatches = ({ engine, adapter, schema, batching: { mode = "l
542
593
  });
543
594
  let checking;
544
595
  /** 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, {
596
+ const hasPending = () => checking ??= Promise.all(LOG_TABLES.map((name, shard) => engine.reads.findMany(name, {
546
597
  index: "oldest",
547
- limit: 1
598
+ limit: 1,
599
+ ...past(shard)
548
600
  }))).then((pages) => pages.some((page) => page.rows.length > 0)).finally(() => {
549
601
  checking = void 0;
550
602
  });
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@hot-updater/plugin-core",
3
- "version": "1.1.15",
3
+ "version": "1.1.16",
4
4
  "type": "module",
5
5
  "description": "React Native OTA solution for self-hosted",
6
6
  "sideEffects": false,
@@ -45,7 +45,7 @@
45
45
  "es-toolkit": "^1.32.0",
46
46
  "mime": "^4.0.4",
47
47
  "verkit": "0.4.0",
48
- "@hot-updater/protocol": "1.1.15"
48
+ "@hot-updater/protocol": "1.1.16"
49
49
  },
50
50
  "devDependencies": {
51
51
  "@electric-sql/pglite": "0.4.1",