@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
|
@@ -14,9 +14,13 @@ const CHANNEL_ID = {
|
|
|
14
14
|
* applies it to managed databases an earlier release created. The official
|
|
15
15
|
* plugins' `schemaVersion`s follow the same rule. A bump only adds tables:
|
|
16
16
|
* every database's migrator creates missing tables and then records the
|
|
17
|
-
* version, and none of them changes an existing table, so changing
|
|
18
|
-
* needs a migration step of its own first.
|
|
19
|
-
*
|
|
17
|
+
* version, and none of them changes an existing table's columns, so changing
|
|
18
|
+
* one needs a migration step of its own first. An index added to an existing
|
|
19
|
+
* table is listed in `LATE_INDEXES`. The schema fence answers 503 on
|
|
20
|
+
* a database whose row differs, until it runs. Before a version is released,
|
|
21
|
+
* its tables change in place in its own migration, and a database one of its
|
|
22
|
+
* prereleases migrated takes the same change by hand: the fence compares this
|
|
23
|
+
* row, not columns, so nothing reports it.
|
|
20
24
|
*/
|
|
21
25
|
const HOT_UPDATER_SCHEMA_VERSION = "1.2.0";
|
|
22
26
|
const bundles = defineTable({
|
|
@@ -198,9 +202,26 @@ const releases = defineTable({
|
|
|
198
202
|
all: {
|
|
199
203
|
eq: [],
|
|
200
204
|
sort: ["id"]
|
|
205
|
+
},
|
|
206
|
+
scopes: {
|
|
207
|
+
eq: [],
|
|
208
|
+
sort: ["scope_key"]
|
|
201
209
|
}
|
|
202
210
|
}
|
|
203
211
|
});
|
|
212
|
+
/**
|
|
213
|
+
* Indexes declared on a table that a released schema's servers write: a
|
|
214
|
+
* store that keeps index items of its own (`migrations.fillIndex`) lacks
|
|
215
|
+
* them for rows written before, and for rows such a server still writes
|
|
216
|
+
* after the migration, since its schema fence keeps a check that passed.
|
|
217
|
+
* Each migration writes the missing items, and `db migrate` on a database
|
|
218
|
+
* whose settings match looks for them. `releases.scopes` arrived in 1.2.0;
|
|
219
|
+
* 1.1.x servers write releases without it.
|
|
220
|
+
*/
|
|
221
|
+
const LATE_INDEXES = [{
|
|
222
|
+
table: "releases",
|
|
223
|
+
index: "scopes"
|
|
224
|
+
}];
|
|
204
225
|
/** One compiled catalog per scope; the update check reads exactly this row. */
|
|
205
226
|
const releaseCatalogs = defineTable({
|
|
206
227
|
scope_key: {
|
|
@@ -270,7 +291,10 @@ const channels = defineTable({
|
|
|
270
291
|
/**
|
|
271
292
|
* The native builds `native-build android` and `native-build ios` track, newest first
|
|
272
293
|
* in each scope: a platform, a channel, and the fingerprint or app version
|
|
273
|
-
* the build compiled in.
|
|
294
|
+
* the build compiled in. A sandbox build's scope has no channel: its app ID,
|
|
295
|
+
* URL scheme, artifact kind and distribution in its place, so pull requests
|
|
296
|
+
* reuse it across channels, while `channel_id` still names the channel it
|
|
297
|
+
* embeds. `min_bundle_id` names the build's built-in bundle,
|
|
274
298
|
* a `bundles` row no release publishes. Its references keep no counters, so
|
|
275
299
|
* adding this table changes no existing one; a channel with builds is
|
|
276
300
|
* refused deletion through `byChannel`. `build_key` is the native build key
|
|
@@ -280,6 +304,27 @@ const channels = defineTable({
|
|
|
280
304
|
* or `versionCode`. `submitted_to`, `submitted_at_ms` and
|
|
281
305
|
* `submitted_version` record the store track a build went to, when, and
|
|
282
306
|
* the store's label of the build; they stay null for a build no store took.
|
|
307
|
+
* `is_store_build` is true on the build a person or a job says the store
|
|
308
|
+
* sells, and false on every other: deploys patch from it over the scope's
|
|
309
|
+
* newest build. The engine copies the scope key into `store_build_scope_key`
|
|
310
|
+
* for that build alone, so `byStoreBuild` holds one entry per scope at most,
|
|
311
|
+
* on every store, while any number of a scope's builds hold none.
|
|
312
|
+
* `is_sandbox` is true on a sandbox build, set from its artifact when it
|
|
313
|
+
* registers and never changed, and `sandbox_url_scheme` is the URL scheme its artifact registers,
|
|
314
|
+
* which its preview links open; null on any other build, and on a sandbox
|
|
315
|
+
* build registered before the column, which registered the derived one.
|
|
316
|
+
* `export_method` is how an `.ipa` was exported, read from its profile when
|
|
317
|
+
* it registers and never changed; null on any other artifact, on an `.ipa`
|
|
318
|
+
* whose profile couldn't be read, and on one registered before the column.
|
|
319
|
+
* `native_app_version` is the app version the artifact itself reports, its
|
|
320
|
+
* `CFBundleShortVersionString` or `versionName`, read from the artifact when
|
|
321
|
+
* it registers and never changed, whatever the update strategy; `app_version`
|
|
322
|
+
* stays the version OTAs target, null on a fingerprint build. It is null
|
|
323
|
+
* when the artifact's can't be read, and on a build registered before the
|
|
324
|
+
* column.
|
|
325
|
+
* Boolean columns follow one rule: `is_*` for a fact about the row or
|
|
326
|
+
* `should_*` for an instruction to the client, never null; a unique index over
|
|
327
|
+
* the rows where one is true keys a derived slot, not the boolean.
|
|
283
328
|
*/
|
|
284
329
|
const nativeBuilds = defineTable({
|
|
285
330
|
id: {
|
|
@@ -356,9 +401,34 @@ const nativeBuilds = defineTable({
|
|
|
356
401
|
type: "string",
|
|
357
402
|
maxLength: 255,
|
|
358
403
|
required: false
|
|
404
|
+
},
|
|
405
|
+
is_store_build: { type: "boolean" },
|
|
406
|
+
is_sandbox: { type: "boolean" },
|
|
407
|
+
sandbox_url_scheme: {
|
|
408
|
+
type: "string",
|
|
409
|
+
maxLength: 255,
|
|
410
|
+
ascii: true,
|
|
411
|
+
required: false
|
|
412
|
+
},
|
|
413
|
+
export_method: {
|
|
414
|
+
type: "string",
|
|
415
|
+
maxLength: 16,
|
|
416
|
+
required: false
|
|
417
|
+
},
|
|
418
|
+
native_app_version: {
|
|
419
|
+
type: "string",
|
|
420
|
+
required: false
|
|
359
421
|
}
|
|
360
422
|
}, {
|
|
361
423
|
key: ["id"],
|
|
424
|
+
derived: {
|
|
425
|
+
/** The scope this build is the store build of; null on every other. */
|
|
426
|
+
store_build_scope_key: {
|
|
427
|
+
type: "string",
|
|
428
|
+
maxLength: 2048,
|
|
429
|
+
ascii: true,
|
|
430
|
+
compute: (row) => row.is_store_build ? row.scope_key : null
|
|
431
|
+
} },
|
|
362
432
|
indexes: {
|
|
363
433
|
byScope: {
|
|
364
434
|
eq: ["scope_key"],
|
|
@@ -368,6 +438,15 @@ const nativeBuilds = defineTable({
|
|
|
368
438
|
eq: ["scope_key", "build_key"],
|
|
369
439
|
sort: ["id"]
|
|
370
440
|
},
|
|
441
|
+
byScopeKind: {
|
|
442
|
+
eq: ["scope_key", "artifact_kind"],
|
|
443
|
+
sort: ["id"]
|
|
444
|
+
},
|
|
445
|
+
byStoreBuild: {
|
|
446
|
+
eq: ["store_build_scope_key"],
|
|
447
|
+
sort: [],
|
|
448
|
+
unique: true
|
|
449
|
+
},
|
|
371
450
|
byChannel: {
|
|
372
451
|
eq: ["channel_id"],
|
|
373
452
|
sort: ["id"],
|
|
@@ -379,6 +458,119 @@ const nativeBuilds = defineTable({
|
|
|
379
458
|
}
|
|
380
459
|
}
|
|
381
460
|
});
|
|
461
|
+
/**
|
|
462
|
+
* The iPhones a team asks to install ad hoc builds on. A row decides what the
|
|
463
|
+
* CLI registers with Apple, not what an export includes: Xcode's automatic ad
|
|
464
|
+
* hoc profile lists every device the Apple account has enabled. `status` is
|
|
465
|
+
* `pending` until someone approves it, `approved` until a build or
|
|
466
|
+
* `native-build devices add` registers it with Apple, then `registered`;
|
|
467
|
+
* declining or removing one deletes its row. `udid` is the UDID in lower case.
|
|
468
|
+
* `apple_issuer_id` is the App Store Connect issuer whose key registered it,
|
|
469
|
+
* set once: a build signed by another account never registers these rows.
|
|
470
|
+
* `apple_error` is Apple's refusal of the device, or why it stopped counting
|
|
471
|
+
* it, cleared by the next success. `build_id` is the newest native build whose
|
|
472
|
+
* .ipa the CLI checked lists it; deleting that build never touches the row.
|
|
473
|
+
* It holds personal data: a UDID, a name, and the emails of who asked and who
|
|
474
|
+
* approved, null for the CLI.
|
|
475
|
+
*/
|
|
476
|
+
const iosDevices = defineTable({
|
|
477
|
+
id: {
|
|
478
|
+
type: "string",
|
|
479
|
+
maxLength: 36
|
|
480
|
+
},
|
|
481
|
+
udid: {
|
|
482
|
+
type: "string",
|
|
483
|
+
maxLength: 40,
|
|
484
|
+
ascii: true,
|
|
485
|
+
unique: true
|
|
486
|
+
},
|
|
487
|
+
name: {
|
|
488
|
+
type: "string",
|
|
489
|
+
maxLength: 100
|
|
490
|
+
},
|
|
491
|
+
status: {
|
|
492
|
+
type: "string",
|
|
493
|
+
maxLength: 16
|
|
494
|
+
},
|
|
495
|
+
requested_by: {
|
|
496
|
+
type: "string",
|
|
497
|
+
maxLength: 320,
|
|
498
|
+
required: false
|
|
499
|
+
},
|
|
500
|
+
created_at_ms: { type: "integer" },
|
|
501
|
+
approved_by: {
|
|
502
|
+
type: "string",
|
|
503
|
+
maxLength: 320,
|
|
504
|
+
required: false
|
|
505
|
+
},
|
|
506
|
+
approved_at_ms: {
|
|
507
|
+
type: "integer",
|
|
508
|
+
required: false
|
|
509
|
+
},
|
|
510
|
+
registered_at_ms: {
|
|
511
|
+
type: "integer",
|
|
512
|
+
required: false
|
|
513
|
+
},
|
|
514
|
+
apple_issuer_id: {
|
|
515
|
+
type: "string",
|
|
516
|
+
maxLength: 64,
|
|
517
|
+
ascii: true,
|
|
518
|
+
required: false
|
|
519
|
+
},
|
|
520
|
+
apple_error: {
|
|
521
|
+
type: "string",
|
|
522
|
+
maxLength: 512,
|
|
523
|
+
required: false
|
|
524
|
+
},
|
|
525
|
+
build_id: {
|
|
526
|
+
type: "string",
|
|
527
|
+
maxLength: 36,
|
|
528
|
+
required: false
|
|
529
|
+
}
|
|
530
|
+
}, {
|
|
531
|
+
key: ["id"],
|
|
532
|
+
indexes: {
|
|
533
|
+
byStatus: {
|
|
534
|
+
eq: ["status"],
|
|
535
|
+
sort: ["id"]
|
|
536
|
+
},
|
|
537
|
+
byRegistration: {
|
|
538
|
+
eq: [],
|
|
539
|
+
sort: ["registered_at_ms"]
|
|
540
|
+
},
|
|
541
|
+
all: {
|
|
542
|
+
eq: [],
|
|
543
|
+
sort: ["id"]
|
|
544
|
+
}
|
|
545
|
+
}
|
|
546
|
+
});
|
|
547
|
+
/**
|
|
548
|
+
* The Apple account the iOS device registry belongs to: one row, keyed
|
|
549
|
+
* `registry`, holding the App Store Connect issuer that first registered a
|
|
550
|
+
* device. A build claims it before it sends Apple anything, and its key makes
|
|
551
|
+
* the claim atomic on every store, so two builds of two accounts can't both
|
|
552
|
+
* spend a slot; another account's build then registers nothing. Removing
|
|
553
|
+
* devices never releases it.
|
|
554
|
+
*/
|
|
555
|
+
const iosDeviceAccount = defineTable({
|
|
556
|
+
id: {
|
|
557
|
+
type: "string",
|
|
558
|
+
maxLength: 16,
|
|
559
|
+
ascii: true
|
|
560
|
+
},
|
|
561
|
+
apple_issuer_id: {
|
|
562
|
+
type: "string",
|
|
563
|
+
maxLength: 64,
|
|
564
|
+
ascii: true
|
|
565
|
+
},
|
|
566
|
+
claimed_at_ms: { type: "integer" }
|
|
567
|
+
}, {
|
|
568
|
+
key: ["id"],
|
|
569
|
+
indexes: { all: {
|
|
570
|
+
eq: [],
|
|
571
|
+
sort: ["id"]
|
|
572
|
+
} }
|
|
573
|
+
});
|
|
382
574
|
const coreSchema = {
|
|
383
575
|
bundles,
|
|
384
576
|
bundle_patches: bundlePatches,
|
|
@@ -396,7 +588,9 @@ const coreSchema = {
|
|
|
396
588
|
sort: []
|
|
397
589
|
} }
|
|
398
590
|
}),
|
|
399
|
-
native_builds: nativeBuilds
|
|
591
|
+
native_builds: nativeBuilds,
|
|
592
|
+
ios_devices: iosDevices,
|
|
593
|
+
ios_device_account: iosDeviceAccount
|
|
400
594
|
};
|
|
401
595
|
/** Core's module: always installed, never a plugin. */
|
|
402
596
|
const coreModule = {
|
|
@@ -404,4 +598,4 @@ const coreModule = {
|
|
|
404
598
|
schema: coreSchema
|
|
405
599
|
};
|
|
406
600
|
//#endregion
|
|
407
|
-
export { HOT_UPDATER_SCHEMA_VERSION, coreModule, coreSchema };
|
|
601
|
+
export { HOT_UPDATER_SCHEMA_VERSION, LATE_INDEXES, coreModule, coreSchema };
|
|
@@ -64,8 +64,7 @@ const createEngine = (database, { plugins = [], now = Date.now } = {}) => {
|
|
|
64
64
|
if (module === void 0) throw new require_configError.HotUpdaterConfigError(`Plugin "${plugin.id}" is not one of this engine's plugins.`);
|
|
65
65
|
return engine.database(module);
|
|
66
66
|
},
|
|
67
|
-
flush: () => engine.flush()
|
|
68
|
-
dispose: () => engine.dispose()
|
|
67
|
+
flush: () => engine.flush()
|
|
69
68
|
};
|
|
70
69
|
};
|
|
71
70
|
//#endregion
|
|
@@ -23,13 +23,8 @@ interface Engine {
|
|
|
23
23
|
readonly id: string;
|
|
24
24
|
readonly schema: TSchema;
|
|
25
25
|
}): HotUpdaterDatabase<TSchema>;
|
|
26
|
-
/**
|
|
27
|
-
* Applies aggregate changes the database batches that are still pending:
|
|
28
|
-
* this process's buffer, and the log rows no compaction has merged yet.
|
|
29
|
-
*/
|
|
26
|
+
/** Applies the log rows of batched aggregates that no compaction has merged yet. */
|
|
30
27
|
flush(): Promise<void>;
|
|
31
|
-
/** Stops batching's timer after a last flush. */
|
|
32
|
-
dispose(): Promise<void>;
|
|
33
28
|
}
|
|
34
29
|
/**
|
|
35
30
|
* The storage engine over a database, as a server runs it: core's tables
|
|
@@ -23,13 +23,8 @@ interface Engine {
|
|
|
23
23
|
readonly id: string;
|
|
24
24
|
readonly schema: TSchema;
|
|
25
25
|
}): HotUpdaterDatabase<TSchema>;
|
|
26
|
-
/**
|
|
27
|
-
* Applies aggregate changes the database batches that are still pending:
|
|
28
|
-
* this process's buffer, and the log rows no compaction has merged yet.
|
|
29
|
-
*/
|
|
26
|
+
/** Applies the log rows of batched aggregates that no compaction has merged yet. */
|
|
30
27
|
flush(): Promise<void>;
|
|
31
|
-
/** Stops batching's timer after a last flush. */
|
|
32
|
-
dispose(): Promise<void>;
|
|
33
28
|
}
|
|
34
29
|
/**
|
|
35
30
|
* The storage engine over a database, as a server runs it: core's tables
|
|
@@ -64,8 +64,7 @@ const createEngine = (database, { plugins = [], now = Date.now } = {}) => {
|
|
|
64
64
|
if (module === void 0) throw new HotUpdaterConfigError(`Plugin "${plugin.id}" is not one of this engine's plugins.`);
|
|
65
65
|
return engine.database(module);
|
|
66
66
|
},
|
|
67
|
-
flush: () => engine.flush()
|
|
68
|
-
dispose: () => engine.dispose()
|
|
67
|
+
flush: () => engine.flush()
|
|
69
68
|
};
|
|
70
69
|
};
|
|
71
70
|
//#endregion
|
|
@@ -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 = require_schema.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) => require_engineAggregates.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 require_errors.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
|
};
|