@hot-updater/aws 1.2.0-rc.49 → 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.
@@ -7278,6 +7278,33 @@ const buildOriginRequestPolicyConfig = (clientHeaders) => ({
7278
7278
  CookiesConfig: { CookieBehavior: "none" },
7279
7279
  QueryStringsConfig: { QueryStringBehavior: "all" }
7280
7280
  });
7281
+ /**
7282
+ * Server errors CloudFront never caches: by default it keeps a 5xx for ten
7283
+ * seconds, so one 503 of a retryable read would reach every device behind
7284
+ * that edge. No response page replaces the server's own answer.
7285
+ */
7286
+ const HOT_UPDATER_UNCACHED_ERROR_CODES = [
7287
+ 500,
7288
+ 502,
7289
+ 503,
7290
+ 504
7291
+ ];
7292
+ /**
7293
+ * The API reference lists `ResponsePagePath` and `ResponseCode` as optional,
7294
+ * but CloudFront rejects an error response without both elements
7295
+ * (IllegalUpdate: "The specified list of custom error responses does not
7296
+ * exist or is not valid"). Empty elements mean no page replaces the origin's
7297
+ * answer.
7298
+ */
7299
+ const withResponseElements = (response) => ({
7300
+ ...response,
7301
+ ResponsePagePath: response.ResponsePagePath ?? "",
7302
+ ResponseCode: response.ResponseCode ?? ""
7303
+ });
7304
+ const uncachedErrorResponses = () => HOT_UPDATER_UNCACHED_ERROR_CODES.map((ErrorCode) => withResponseElements({
7305
+ ErrorCode,
7306
+ ErrorCachingMinTTL: 0
7307
+ }));
7281
7308
  const READ_ONLY_METHODS = {
7282
7309
  Quantity: 2,
7283
7310
  Items: ["HEAD", "GET"],
@@ -7337,7 +7364,11 @@ const sanitizeDistributionConfig = (distributionConfig) => ({
7337
7364
  CacheBehaviors: distributionConfig.CacheBehaviors ? {
7338
7365
  Quantity: distributionConfig.CacheBehaviors.Quantity,
7339
7366
  Items: (distributionConfig.CacheBehaviors.Items ?? []).map((behavior) => sanitizeCacheBehavior(behavior))
7340
- } : distributionConfig.CacheBehaviors
7367
+ } : distributionConfig.CacheBehaviors,
7368
+ CustomErrorResponses: distributionConfig.CustomErrorResponses ? {
7369
+ Quantity: distributionConfig.CustomErrorResponses.Quantity,
7370
+ Items: distributionConfig.CustomErrorResponses.Items?.map(withResponseElements)
7371
+ } : distributionConfig.CustomErrorResponses
7341
7372
  });
7342
7373
  const buildOriginRequestLambdaAssociations = (functionArn) => ({
7343
7374
  Quantity: 1,
@@ -7454,6 +7485,10 @@ const buildDistributionConfigOverrides = (options) => ({
7454
7485
  sharedCachePolicyId: options.sharedCachePolicyId
7455
7486
  }))
7456
7487
  ]
7488
+ },
7489
+ CustomErrorResponses: {
7490
+ Quantity: HOT_UPDATER_UNCACHED_ERROR_CODES.length,
7491
+ Items: uncachedErrorResponses()
7457
7492
  }
7458
7493
  });
7459
7494
  const applyDistributionConfigOverrides = (distributionConfig, overrides) => {
@@ -7469,6 +7504,8 @@ const applyDistributionConfigOverrides = (distributionConfig, overrides) => {
7469
7504
  } : behavior);
7470
7505
  const origins = mergeOrigins(distributionConfig.Origins?.Items ?? [], overrides.Origins.Items ?? []);
7471
7506
  const cacheBehaviors = mergeCacheBehaviors(distributionConfig.CacheBehaviors?.Items ?? [], cacheBehaviorOverrides);
7507
+ const managedCodes = new Set((overrides.CustomErrorResponses.Items ?? []).map(({ ErrorCode }) => ErrorCode));
7508
+ const errorResponses = [...(distributionConfig.CustomErrorResponses?.Items ?? []).filter(({ ErrorCode }) => !managedCodes.has(ErrorCode)), ...overrides.CustomErrorResponses.Items ?? []];
7472
7509
  return sanitizeDistributionConfig({
7473
7510
  ...distributionConfig,
7474
7511
  Origins: {
@@ -7479,6 +7516,10 @@ const applyDistributionConfigOverrides = (distributionConfig, overrides) => {
7479
7516
  CacheBehaviors: {
7480
7517
  Quantity: cacheBehaviors.length,
7481
7518
  Items: cacheBehaviors
7519
+ },
7520
+ CustomErrorResponses: {
7521
+ Quantity: errorResponses.length,
7522
+ Items: errorResponses
7482
7523
  }
7483
7524
  });
7484
7525
  };
@@ -7273,6 +7273,33 @@ const buildOriginRequestPolicyConfig = (clientHeaders) => ({
7273
7273
  CookiesConfig: { CookieBehavior: "none" },
7274
7274
  QueryStringsConfig: { QueryStringBehavior: "all" }
7275
7275
  });
7276
+ /**
7277
+ * Server errors CloudFront never caches: by default it keeps a 5xx for ten
7278
+ * seconds, so one 503 of a retryable read would reach every device behind
7279
+ * that edge. No response page replaces the server's own answer.
7280
+ */
7281
+ const HOT_UPDATER_UNCACHED_ERROR_CODES = [
7282
+ 500,
7283
+ 502,
7284
+ 503,
7285
+ 504
7286
+ ];
7287
+ /**
7288
+ * The API reference lists `ResponsePagePath` and `ResponseCode` as optional,
7289
+ * but CloudFront rejects an error response without both elements
7290
+ * (IllegalUpdate: "The specified list of custom error responses does not
7291
+ * exist or is not valid"). Empty elements mean no page replaces the origin's
7292
+ * answer.
7293
+ */
7294
+ const withResponseElements = (response) => ({
7295
+ ...response,
7296
+ ResponsePagePath: response.ResponsePagePath ?? "",
7297
+ ResponseCode: response.ResponseCode ?? ""
7298
+ });
7299
+ const uncachedErrorResponses = () => HOT_UPDATER_UNCACHED_ERROR_CODES.map((ErrorCode) => withResponseElements({
7300
+ ErrorCode,
7301
+ ErrorCachingMinTTL: 0
7302
+ }));
7276
7303
  const READ_ONLY_METHODS = {
7277
7304
  Quantity: 2,
7278
7305
  Items: ["HEAD", "GET"],
@@ -7332,7 +7359,11 @@ const sanitizeDistributionConfig = (distributionConfig) => ({
7332
7359
  CacheBehaviors: distributionConfig.CacheBehaviors ? {
7333
7360
  Quantity: distributionConfig.CacheBehaviors.Quantity,
7334
7361
  Items: (distributionConfig.CacheBehaviors.Items ?? []).map((behavior) => sanitizeCacheBehavior(behavior))
7335
- } : distributionConfig.CacheBehaviors
7362
+ } : distributionConfig.CacheBehaviors,
7363
+ CustomErrorResponses: distributionConfig.CustomErrorResponses ? {
7364
+ Quantity: distributionConfig.CustomErrorResponses.Quantity,
7365
+ Items: distributionConfig.CustomErrorResponses.Items?.map(withResponseElements)
7366
+ } : distributionConfig.CustomErrorResponses
7336
7367
  });
7337
7368
  const buildOriginRequestLambdaAssociations = (functionArn) => ({
7338
7369
  Quantity: 1,
@@ -7449,6 +7480,10 @@ const buildDistributionConfigOverrides = (options) => ({
7449
7480
  sharedCachePolicyId: options.sharedCachePolicyId
7450
7481
  }))
7451
7482
  ]
7483
+ },
7484
+ CustomErrorResponses: {
7485
+ Quantity: HOT_UPDATER_UNCACHED_ERROR_CODES.length,
7486
+ Items: uncachedErrorResponses()
7452
7487
  }
7453
7488
  });
7454
7489
  const applyDistributionConfigOverrides = (distributionConfig, overrides) => {
@@ -7464,6 +7499,8 @@ const applyDistributionConfigOverrides = (distributionConfig, overrides) => {
7464
7499
  } : behavior);
7465
7500
  const origins = mergeOrigins(distributionConfig.Origins?.Items ?? [], overrides.Origins.Items ?? []);
7466
7501
  const cacheBehaviors = mergeCacheBehaviors(distributionConfig.CacheBehaviors?.Items ?? [], cacheBehaviorOverrides);
7502
+ const managedCodes = new Set((overrides.CustomErrorResponses.Items ?? []).map(({ ErrorCode }) => ErrorCode));
7503
+ const errorResponses = [...(distributionConfig.CustomErrorResponses?.Items ?? []).filter(({ ErrorCode }) => !managedCodes.has(ErrorCode)), ...overrides.CustomErrorResponses.Items ?? []];
7467
7504
  return sanitizeDistributionConfig({
7468
7505
  ...distributionConfig,
7469
7506
  Origins: {
@@ -7474,6 +7511,10 @@ const applyDistributionConfigOverrides = (distributionConfig, overrides) => {
7474
7511
  CacheBehaviors: {
7475
7512
  Quantity: cacheBehaviors.length,
7476
7513
  Items: cacheBehaviors
7514
+ },
7515
+ CustomErrorResponses: {
7516
+ Quantity: errorResponses.length,
7517
+ Items: errorResponses
7477
7518
  }
7478
7519
  });
7479
7520
  };
@@ -2075,45 +2075,6 @@ const METER = Symbol.for("@hot-updater/plugin-core/read-meter");
2075
2075
  /** The meter `meterReads` gave `database`, if it did. */
2076
2076
  const readMeterOf = (database) => typeof database === "object" && database !== null ? database[METER] : void 0;
2077
2077
  //#endregion
2078
- //#region ../plugin-core/dist/engine/db/schemaSettings.mjs
2079
- const storedSettings = async (adapter, keys) => {
2080
- const rows = await readSettings(adapter, keys);
2081
- return new Map(keys.map((key, position) => [key, rows[position] ?? null]));
2082
- };
2083
- /** Writes the settings rows after every table exists. */
2084
- const writeSchemaSettings = async (adapter, adapterName, settings) => {
2085
- const stored = await storedSettings(adapter, Object.keys(settings));
2086
- const ops = Object.entries(settings).flatMap(([key, value]) => {
2087
- const row = stored.get(key);
2088
- if (row === null || row === void 0) return [{
2089
- type: "insert",
2090
- table: SETTINGS_TABLE,
2091
- row: {
2092
- key,
2093
- value,
2094
- _v: 0
2095
- }
2096
- }];
2097
- if (row.value === value) return [];
2098
- return [{
2099
- type: "patch",
2100
- table: SETTINGS_TABLE,
2101
- key: [key],
2102
- set: { value },
2103
- guard: { v: Number(row._v) },
2104
- previous: row
2105
- }];
2106
- });
2107
- if (ops.length === 0) return;
2108
- if (!(await adapter.write(ops)).ok) throw new Error(`${adapterName}: the schema settings changed during the migration; run it again.`);
2109
- };
2110
- /** Creates or updates every table, then writes the settings rows last. */
2111
- const migrateSchema = async (adapter, adapterName, tables, settings) => {
2112
- if (adapter.migrations === void 0) throw new Error(`${adapterName} creates its tables with its own tooling; write only the settings rows.`);
2113
- await adapter.migrations.apply([...tables, SETTINGS_TABLE]);
2114
- await writeSchemaSettings(adapter, adapterName, settings);
2115
- };
2116
- //#endregion
2117
2078
  //#region ../plugin-core/dist/engine/core/schema.mjs
2118
2079
  /** A channel's id is `channel:` and its name's channel key, so ids share channel_key's bound. */
2119
2080
  const CHANNEL_ID = {
@@ -2129,8 +2090,9 @@ const CHANNEL_ID = {
2129
2090
  * applies it to managed databases an earlier release created. The official
2130
2091
  * plugins' `schemaVersion`s follow the same rule. A bump only adds tables:
2131
2092
  * every database's migrator creates missing tables and then records the
2132
- * version, and none of them changes an existing table, so changing one
2133
- * needs a migration step of its own first. The schema fence answers 503 on
2093
+ * version, and none of them changes an existing table's columns, so changing
2094
+ * one needs a migration step of its own first. An index added to an existing
2095
+ * table is listed in `LATE_INDEXES`. The schema fence answers 503 on
2134
2096
  * a database whose row differs, until it runs. Before a version is released,
2135
2097
  * its tables change in place in its own migration, and a database one of its
2136
2098
  * prereleases migrated takes the same change by hand: the fence compares this
@@ -2316,9 +2278,26 @@ const releases = defineTable({
2316
2278
  all: {
2317
2279
  eq: [],
2318
2280
  sort: ["id"]
2281
+ },
2282
+ scopes: {
2283
+ eq: [],
2284
+ sort: ["scope_key"]
2319
2285
  }
2320
2286
  }
2321
2287
  });
2288
+ /**
2289
+ * Indexes declared on a table that a released schema's servers write: a
2290
+ * store that keeps index items of its own (`migrations.fillIndex`) lacks
2291
+ * them for rows written before, and for rows such a server still writes
2292
+ * after the migration, since its schema fence keeps a check that passed.
2293
+ * Each migration writes the missing items, and `db migrate` on a database
2294
+ * whose settings match looks for them. `releases.scopes` arrived in 1.2.0;
2295
+ * 1.1.x servers write releases without it.
2296
+ */
2297
+ const LATE_INDEXES = [{
2298
+ table: "releases",
2299
+ index: "scopes"
2300
+ }];
2322
2301
  /** One compiled catalog per scope; the update check reads exactly this row. */
2323
2302
  const releaseCatalogs = defineTable({
2324
2303
  scope_key: {
@@ -2716,6 +2695,121 @@ const refuseV0Database = (adapterName, stored) => {
2716
2695
  if (typeof version !== "string" || stored.has("schema.engine")) return;
2717
2696
  throw new HotUpdaterSchemaMigrationRequiredError(adapterName, version);
2718
2697
  };
2698
+ /** Compares dotted numeric versions, such as "1" and "1.2.0"; NaN when either is not one. */
2699
+ const compareVersions = (left, right) => {
2700
+ const parse = (version) => /^\d+(?:\.\d+)*$/u.test(version) ? version.split(".").map(Number) : [NaN];
2701
+ const [a, b] = [parse(left), parse(right)];
2702
+ if ([...a, ...b].some(Number.isNaN)) return NaN;
2703
+ for (let index = 0; index < Math.max(a.length, b.length); index += 1) {
2704
+ const difference = (a[index] ?? 0) - (b[index] ?? 0);
2705
+ if (difference !== 0) return difference;
2706
+ }
2707
+ return 0;
2708
+ };
2709
+ /**
2710
+ * The settings whose versions only move forward when a `ToolingTarget` names
2711
+ * none. `schema.engine` is a storage layout, not a release: a store refuses
2712
+ * another layout itself, and doctor reports it as not migratable.
2713
+ */
2714
+ const DEFAULT_ORDERED_SETTINGS = ["schema.core"];
2715
+ /**
2716
+ * Refuses a database a newer release migrated, one whose `schema.core` is
2717
+ * newer than this release's: writing this release's settings would move the
2718
+ * schema back, and every server of the newer release would answer 503. Only
2719
+ * `ordered` settings are compared, `schema.core` among them, and the message
2720
+ * lists each that is newer. An official plugin's
2721
+ * newer version alone is no newer release: Insights recorded "1.2.0" in
2722
+ * 1.0.0-rc.23 and rc.24, then went back to "1.0.0" with the same tables.
2723
+ */
2724
+ const refuseNewerSchema = (adapterName, stored, settings, ordered = DEFAULT_ORDERED_SETTINGS) => {
2725
+ const newer = ordered.flatMap((key) => {
2726
+ const found = stored.get(key);
2727
+ const expected = settings[key];
2728
+ return typeof found === "string" && expected !== void 0 && compareVersions(found, expected) > 0 ? [{
2729
+ key,
2730
+ found,
2731
+ expected
2732
+ }] : [];
2733
+ });
2734
+ const core = newer.find(({ key }) => key === "schema.core");
2735
+ if (core === void 0) return;
2736
+ throw new Error(`${adapterName}: the database was migrated by Hot Updater ${core.found} (${newer.map(({ key, found, expected }) => `${key} "${found}", this CLI's "${expected}"`).join("; ")}). Upgrade hot-updater to ${core.found} or later; nothing was written.`);
2737
+ };
2738
+ /** The settings rows a migration changes, each with its stored value. */
2739
+ const settingsOperation = (stored, changed) => ({
2740
+ type: "custom",
2741
+ description: `Record ${changed.map(([key, value]) => {
2742
+ const found = stored.get(key);
2743
+ return typeof found === "string" ? `${key} ${found} → ${value}` : `${key} ${value}`;
2744
+ }).join(", ")}`
2745
+ });
2746
+ //#endregion
2747
+ //#region ../plugin-core/dist/engine/db/schemaSettings.mjs
2748
+ const storedSettings = async (adapter, keys) => {
2749
+ const rows = await readSettings(adapter, keys);
2750
+ return new Map(keys.map((key, position) => [key, rows[position] ?? null]));
2751
+ };
2752
+ /**
2753
+ * Writes the settings rows after every table exists, and refuses a database
2754
+ * whose `ordered` settings a newer release recorded.
2755
+ */
2756
+ const writeSchemaSettings = async (adapter, adapterName, settings, ordered) => {
2757
+ const stored = await storedSettings(adapter, Object.keys(settings));
2758
+ refuseNewerSchema(adapterName, new Map([...stored].map(([key, row]) => [key, row?.value])), settings, ordered);
2759
+ const ops = Object.entries(settings).flatMap(([key, value]) => {
2760
+ const row = stored.get(key);
2761
+ if (row === null || row === void 0) return [{
2762
+ type: "insert",
2763
+ table: SETTINGS_TABLE,
2764
+ row: {
2765
+ key,
2766
+ value,
2767
+ _v: 0
2768
+ }
2769
+ }];
2770
+ if (row.value === value) return [];
2771
+ return [{
2772
+ type: "patch",
2773
+ table: SETTINGS_TABLE,
2774
+ key: [key],
2775
+ set: { value },
2776
+ guard: { v: Number(row._v) },
2777
+ previous: row
2778
+ }];
2779
+ });
2780
+ if (ops.length === 0) return;
2781
+ if (!(await adapter.write(ops)).ok) throw new Error(`${adapterName}: the schema settings changed during the migration; run it again.`);
2782
+ };
2783
+ /**
2784
+ * The `LATE_INDEXES` among `tables` whose items some rows lack, as
2785
+ * `<table>.<index>`, written unless `dryRun`: none on a store without
2786
+ * `migrations.fillIndex`.
2787
+ */
2788
+ const fillLateIndexes = async (adapter, tables, { dryRun = false } = {}) => {
2789
+ const fillIndex = adapter.migrations?.fillIndex;
2790
+ if (fillIndex === void 0) return [];
2791
+ const lacking = [];
2792
+ for (const { table: name, index } of LATE_INDEXES) {
2793
+ const table = tables.find((candidate) => candidate.name === name);
2794
+ if (table === void 0) continue;
2795
+ if (await fillIndex(table, index, { dryRun }) > 0) lacking.push(`${name}.${index}`);
2796
+ }
2797
+ return lacking;
2798
+ };
2799
+ /**
2800
+ * Creates or updates every table, writes the late indexes' missing items,
2801
+ * then writes the settings rows last. A database a newer release migrated is
2802
+ * refused before anything is written: its settings are read first, and a
2803
+ * store without them yet, whose read fails, has none to refuse.
2804
+ */
2805
+ const migrateSchema = async (adapter, adapterName, tables, settings, ordered) => {
2806
+ if (adapter.migrations === void 0) throw new Error(`${adapterName} creates its tables with its own tooling; write only the settings rows.`);
2807
+ const stored = await storedSettings(adapter, Object.keys(settings)).catch(() => void 0);
2808
+ if (stored !== void 0) refuseNewerSchema(adapterName, new Map([...stored].map(([key, row]) => [key, row?.value])), settings, ordered);
2809
+ await adapter.migrations.apply([...tables, SETTINGS_TABLE]);
2810
+ await fillLateIndexes(adapter, tables);
2811
+ await writeSchemaSettings(adapter, adapterName, settings, ordered);
2812
+ };
2719
2813
  //#endregion
2720
2814
  //#region ../plugin-core/dist/engine/database/cursor.mjs
2721
2815
  const encoder$1 = new TextEncoder();
@@ -3738,29 +3832,34 @@ const resolveSchema = (modules) => {
3738
3832
  * `hot-updater db migrate` for a store whose adapter creates its own tables
3739
3833
  * (MongoDB and the key-value stores): the tables and indexes, then the
3740
3834
  * settings rows, applied when a setting is missing or different, and refused
3741
- * on a v0 database.
3835
+ * on a v0 database or one a newer release migrated.
3742
3836
  */
3743
3837
  const createEngineMigrator = (options) => {
3744
3838
  const getVersion = async () => storedSchemaVersion(await options.readSettings());
3745
3839
  const makeResult = async (migrate = {}) => {
3746
3840
  const stored = await options.readSettings();
3747
3841
  refuseV0Database(options.adapterName, stored);
3748
- if (Object.entries(options.settings).every(([key, value]) => stored.get(key) === value)) return getEmptyMigrationResult();
3749
- return {
3750
- operations: [...options.schema.tables.map((table) => ({
3751
- type: "create-table",
3752
- value: {
3753
- ormName: table.name,
3754
- columns: Object.fromEntries(table.columns.map((column) => [column.name, {
3755
- ormName: column.name,
3756
- type: column.type
3757
- }]))
3842
+ refuseNewerSchema(options.adapterName, stored, options.settings, options.ordered);
3843
+ const changed = Object.entries(options.settings).filter(([key, value]) => stored.get(key) !== value);
3844
+ if (changed.length === 0) {
3845
+ const lacking = await fillLateIndexes(options.adapter, options.schema.tables, { dryRun: true });
3846
+ if (lacking.length === 0) return getEmptyMigrationResult();
3847
+ return {
3848
+ operations: [{
3849
+ type: "custom",
3850
+ description: `Write the index items rows lack: ${lacking.join(", ")}`
3851
+ }],
3852
+ execute: async () => {
3853
+ await fillLateIndexes(options.adapter, options.schema.tables);
3758
3854
  }
3759
- })), ...migrate.updateSettings === false ? [] : [{
3855
+ };
3856
+ }
3857
+ return {
3858
+ operations: [{
3760
3859
  type: "custom",
3761
- description: `Write the schema settings: ${Object.keys(options.settings).join(", ")}`
3762
- }]],
3763
- execute: () => migrateSchema(options.adapter, options.adapterName, options.schema.tables, options.settings)
3860
+ description: "Create the tables and indexes the database lacks"
3861
+ }, ...migrate.updateSettings === false ? [] : [settingsOperation(stored, changed)]],
3862
+ execute: () => migrateSchema(options.adapter, options.adapterName, options.schema.tables, options.settings, options.ordered)
3764
3863
  };
3765
3864
  };
3766
3865
  return {
@@ -3791,7 +3890,8 @@ const coreSettings = {
3791
3890
  /** What `hot-updater db` creates for a server without plugins. */
3792
3891
  const coreTarget = {
3793
3892
  schema: coreSchema,
3794
- settings: coreSettings
3893
+ settings: coreSettings,
3894
+ ordered: ["schema.core"]
3795
3895
  };
3796
3896
  resolveSchema([aggregateBatchingModule]).tables;
3797
3897
  /** Each plugin's `schema.<id>` settings row. */
@@ -3811,11 +3911,12 @@ const pluginModule = ({ id, schema, namespace }) => ({
3811
3911
  */
3812
3912
  const createEngineDatabase = ({ name, adapter, onCachedRoutesChange, aggregateBatching, retry, readSettings: readStored }) => {
3813
3913
  const fenced = withSchemaFence(adapter, name, coreSettings);
3814
- const createMigrator = ({ schema, settings } = coreTarget) => createEngineMigrator({
3914
+ const createMigrator = ({ schema, settings, ordered } = coreTarget) => createEngineMigrator({
3815
3915
  adapterName: name,
3816
3916
  adapter,
3817
3917
  schema,
3818
3918
  settings,
3919
+ ordered,
3819
3920
  readSettings: readStored ?? (async () => {
3820
3921
  const rows = await readSettings(adapter, Object.keys(settings)).catch((error) => {
3821
3922
  if (isMissingSchemaError(error)) return [];
@@ -3839,6 +3940,12 @@ const createEngineDatabase = ({ name, adapter, onCachedRoutesChange, aggregateBa
3839
3940
  /** A row this attempt read changed while it ran; the attempt reruns. */
3840
3941
  var StaleReadError = class extends Error {};
3841
3942
  const idOf$1 = (table, key) => JSON.stringify([table, key]);
3943
+ /** The aggregate rows a write changes, at the versions it read them. */
3944
+ const versionsOf = (ops) => JSON.stringify(ops.map((op) => op.type === "insert" ? [op.table.name, rowKey(op.table, op.row)] : [
3945
+ op.table.name,
3946
+ op.key,
3947
+ "guard" in op ? op.guard?.v : void 0
3948
+ ]));
3842
3949
  const versionOf = (row) => Number(row["_v"]);
3843
3950
  const isKeyed = (value) => value !== null && value !== void 0;
3844
3951
  const misuse = (table, message) => new DatabaseTransactionError(`${table}: ${message}`);
@@ -4183,7 +4290,9 @@ const createTransactions = ({ adapter, schema, reads, retry = {} }) => {
4183
4290
  assertOutsideTransaction();
4184
4291
  let run;
4185
4292
  let negative;
4186
- for (let round = 0; round < attempts; round += 1) {
4293
+ let failures = 0;
4294
+ let lost;
4295
+ for (let round = 0;; round += 1) {
4187
4296
  const delay = round && Math.min(maxDelayMs, baseDelayMs * 2 ** (round - 1));
4188
4297
  if (delay > 0) await new Promise((resolve) => setTimeout(resolve, delay / 2 + Math.random() * (delay / 2)));
4189
4298
  run ??= await attempt(fn).catch((error) => {
@@ -4192,6 +4301,8 @@ const createTransactions = ({ adapter, schema, reads, retry = {} }) => {
4192
4301
  });
4193
4302
  if (run === void 0) {
4194
4303
  onRetry?.("rerun", round + 1);
4304
+ lost = void 0;
4305
+ if ((failures += 1) >= attempts) break;
4195
4306
  continue;
4196
4307
  }
4197
4308
  let aggregates;
@@ -4202,8 +4313,14 @@ const createTransactions = ({ adapter, schema, reads, retry = {} }) => {
4202
4313
  negative = error;
4203
4314
  onRetry?.("rerun", round + 1);
4204
4315
  run = void 0;
4316
+ lost = void 0;
4317
+ if ((failures += 1) >= attempts) break;
4205
4318
  continue;
4206
4319
  }
4320
+ const versions = versionsOf(aggregates);
4321
+ if (lost !== void 0 && versions !== lost) failures -= 1;
4322
+ lost = void 0;
4323
+ if (failures >= attempts) break;
4207
4324
  const ops = [...run.ops, ...aggregates];
4208
4325
  if (ops.length <= 1 && ops.every(({ type }) => type === "check")) return run.result;
4209
4326
  if (!adapter.fits(ops)) throw new DatabaseConstraintError("too_large", ops[0].table.name);
@@ -4217,12 +4334,16 @@ const createTransactions = ({ adapter, schema, reads, retry = {} }) => {
4217
4334
  const failed = "failedOp" in outcome ? outcome.failedOp : void 0;
4218
4335
  if (failed === void 0 || failed >= run.ops.length) {
4219
4336
  onRetry?.("resend", round + 1);
4337
+ failures += 1;
4338
+ if (failed !== void 0) lost = versions;
4339
+ else if (failures >= attempts) break;
4220
4340
  continue;
4221
4341
  }
4222
4342
  const reason = await classify(ops[failed], run.read);
4223
4343
  if (reason) throw new DatabaseConstraintError(reason, ops[failed].table.name);
4224
4344
  onRetry?.("rerun", round + 1);
4225
4345
  run = void 0;
4346
+ if ((failures += 1) >= attempts) break;
4226
4347
  }
4227
4348
  throw negative ?? new DatabaseConflictError(`The transaction conflicted ${attempts} times.`);
4228
4349
  } };
@@ -4622,10 +4743,10 @@ const createKvAdapter = ({ store, tablePrefix = "" }) => {
4622
4743
  const at = row && expiresAt(table, row);
4623
4744
  return at === void 0 ? {} : { expiresAt: at };
4624
4745
  };
4625
- /** Every index and unique item a row has, by address. */
4626
- const itemsOf = (layout, row) => {
4746
+ /** Every index and unique item a row has, by address: in `indexes`, if given. */
4747
+ const itemsOf = (layout, row, indexes = layout.indexed) => {
4627
4748
  const items = /* @__PURE__ */ new Map();
4628
- for (const index of row === null ? [] : layout.indexed) for (const eq of indexEntries(layout.table, index, row)) {
4749
+ for (const index of row === null ? [] : indexes) for (const eq of indexEntries(layout.table, index, row)) {
4629
4750
  const pk = partition(layout, index, eq);
4630
4751
  const sk = index.unique ? ONLY : encodeKvKey(indexOrderTuple(layout.table, index, row)) || ONLY;
4631
4752
  items.set(JSON.stringify([pk, sk]), {
@@ -4780,6 +4901,79 @@ const createKvAdapter = ({ store, tablePrefix = "" }) => {
4780
4901
  lte: lt.endsWith(SEPARATOR) ? lt.slice(0, -1) : lt
4781
4902
  };
4782
4903
  };
4904
+ /** One row's check and its item puts in `index`, copies of the row as it is. */
4905
+ const fillOps = (layout, index, row) => [{
4906
+ type: "check",
4907
+ key: rowItem(layout, rowKey(layout.table, row)),
4908
+ condition: { v: Number(row["_v"]) }
4909
+ }, ...[...itemsOf(layout, row, [index]).values()].map(({ key }) => ({
4910
+ type: "put",
4911
+ key,
4912
+ value: copyOf(layout, row),
4913
+ ...stamp(layout.table, row)
4914
+ }))];
4915
+ /**
4916
+ * Writes one row's items in `index`, checking the row's `_v` in the same
4917
+ * write: a row that changed is read again, and a deleted one needs none.
4918
+ */
4919
+ const fillRow = async (layout, index, first) => {
4920
+ const key = rowItem(layout, rowKey(layout.table, first));
4921
+ let row = first;
4922
+ for (let attempt = 0; row !== null; attempt += 1) {
4923
+ 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.`);
4924
+ if ((await store.write(fillOps(layout, index, row))).ok) return;
4925
+ [row] = await store.get([key]);
4926
+ }
4927
+ };
4928
+ /**
4929
+ * Finds the rows that lack an item in `index` and, unless `dryRun`, writes
4930
+ * them, as many rows per atomic write as the store takes. It reads every
4931
+ * row and its items, page by page.
4932
+ */
4933
+ const fillIndex = async (table, name, { dryRun = false } = {}) => {
4934
+ const layout = layoutOf(table);
4935
+ const index = layout.indexed.find((candidate) => candidate.name === name);
4936
+ if (index === void 0) return 0;
4937
+ if (index.unique) throw new 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.`);
4938
+ const { items: most, bytes } = store.limits;
4939
+ let lacking = 0;
4940
+ for (let after;;) {
4941
+ const page = await store.query({
4942
+ pk: layout.rows,
4943
+ order: "asc",
4944
+ limit: 100,
4945
+ after
4946
+ });
4947
+ const rows = page.items.map(({ value }) => value);
4948
+ const keys = rows.map((row) => [...itemsOf(layout, row, [index]).values()].map(({ key }) => key));
4949
+ const wanted = keys.flat();
4950
+ const found = wanted.length === 0 ? [] : await store.get(wanted);
4951
+ let at = 0;
4952
+ const missing = rows.filter((_, position) => {
4953
+ return found.slice(at, at += keys[position].length).some((item) => item === null);
4954
+ });
4955
+ lacking += missing.length;
4956
+ if (!dryRun) {
4957
+ let chunk = [];
4958
+ let ops = [];
4959
+ const flush = async () => {
4960
+ if (ops.length > 0 && !(await store.write(ops)).ok) for (const row of chunk) await fillRow(layout, index, row);
4961
+ chunk = [];
4962
+ ops = [];
4963
+ };
4964
+ for (const row of missing) {
4965
+ const next = fillOps(layout, index, row);
4966
+ 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);
4967
+ if (chunk.length > 0 && (ops.length + next.length > most || size(ops) + size(next) > bytes)) await flush();
4968
+ chunk.push(row);
4969
+ ops.push(...next);
4970
+ }
4971
+ await flush();
4972
+ }
4973
+ if (!page.more || page.items.length === 0) return lacking;
4974
+ after = page.items.at(-1).sk;
4975
+ }
4976
+ };
4783
4977
  return {
4784
4978
  id: store.id,
4785
4979
  fits(ops) {
@@ -4839,13 +5033,16 @@ const createKvAdapter = ({ store, tablePrefix = "" }) => {
4839
5033
  const layout = layoutOf(table);
4840
5034
  return store.deleteConsumed(rows.flatMap((row) => [rowItem(layout, rowKey(table, row)), ...[...itemsOf(layout, row).values()].map(({ key }) => key)]));
4841
5035
  } },
4842
- migrations: { apply: async () => store.migrations?.apply() },
5036
+ migrations: {
5037
+ apply: async () => store.migrations?.apply(),
5038
+ fillIndex
5039
+ },
4843
5040
  ...store.dispose === void 0 ? {} : { dispose: () => store.dispose() }
4844
5041
  };
4845
5042
  };
4846
5043
  //#endregion
4847
5044
  //#region ../../packages/server/dist/version.mjs
4848
- const HOT_UPDATER_SERVER_VERSION = "1.2.0-rc.49";
5045
+ const HOT_UPDATER_SERVER_VERSION = "1.2.0-rc.50";
4849
5046
  //#endregion
4850
5047
  //#region ../../packages/server/dist/handlerVersionRoutes.mjs
4851
5048
  /**
@@ -5005,10 +5202,15 @@ const releaseCatalogScopeKeyOf = (input) => input.strategy === "APP_VERSION" ? c
5005
5202
  platform: input.platform,
5006
5203
  strategy: "FINGERPRINT"
5007
5204
  });
5008
- /** Projects a stored catalog row for one update check; null when the row is not this scope's. */
5009
- const projectReleaseCatalogRow = (row, input, scopeKey = releaseCatalogScopeKeyOf(input)) => {
5010
- if (row === null || row.platform !== input.platform || row.strategy !== input.strategy || row.channel_key !== input.channelKey || row.scope_key !== scopeKey || row.fingerprint_hash !== (input.strategy === "FINGERPRINT" ? input.fingerprintHash : null)) return null;
5011
- const compiled = parseCompiledCatalog(row.payload, input.strategy);
5205
+ const parseReleaseCatalogRow = ({ payload, ...row }) => ({
5206
+ row,
5207
+ compiled: parseCompiledCatalog(payload, row.strategy)
5208
+ });
5209
+ /** Projects a parsed catalog row for one update check; null when the row is not this scope's. */
5210
+ const projectParsedReleaseCatalogRow = (parsed, input, scopeKey = releaseCatalogScopeKeyOf(input)) => {
5211
+ if (parsed === null) return null;
5212
+ const { row, compiled } = parsed;
5213
+ if (row.platform !== input.platform || row.strategy !== input.strategy || row.channel_key !== input.channelKey || row.scope_key !== scopeKey || row.fingerprint_hash !== (input.strategy === "FINGERPRINT" ? input.fingerprintHash : null)) return null;
5012
5214
  const appVersion = input.strategy === "APP_VERSION" ? input.appVersion : void 0;
5013
5215
  return {
5014
5216
  catalogId: row.catalog_id,
@@ -5021,6 +5223,8 @@ const projectReleaseCatalogRow = (row, input, scopeKey = releaseCatalogScopeKeyO
5021
5223
  scopeKey
5022
5224
  };
5023
5225
  };
5226
+ /** Projects a stored catalog row for one update check; null when the row is not this scope's. */
5227
+ const projectReleaseCatalogRow = (row, input, scopeKey = releaseCatalogScopeKeyOf(input)) => projectParsedReleaseCatalogRow(row === null ? null : parseReleaseCatalogRow(row), input, scopeKey);
5024
5228
  //#endregion
5025
5229
  //#region ../../packages/server/dist/db/updateArtifacts.mjs
5026
5230
  const HBC_ASSET_PATH_RE = /\.bundle$/;
@@ -5716,7 +5920,7 @@ const after = (input) => {
5716
5920
  };
5717
5921
  return Object.keys(range).length === 0 ? {} : { range };
5718
5922
  };
5719
- /** Core's reads, each through one declared index or key. */
5923
+ /** Core's reads, each through one declared index or key; plugins get `CoreReads`. */
5720
5924
  const createCoreReads = (db, storage) => {
5721
5925
  /** A bundle row's patches, exactly as many as its reference counter holds. */
5722
5926
  const detail = async (row) => {
@@ -5904,8 +6108,35 @@ const createCoreReads = (db, storage) => {
5904
6108
  ...after(input)
5905
6109
  })).rows.map(toCatalogRow);
5906
6110
  },
5907
- /** Every channel, by name. */
5908
- async listChannels() {
6111
+ /**
6112
+ * Up to `limit` scope keys that have releases, ascending after `after`:
6113
+ * one limit-1 seek of the `scopes` index past each scope, so the reads
6114
+ * grow with the scopes, not with their releases.
6115
+ */
6116
+ async listReleaseScopeKeys(input) {
6117
+ const scopeKeys = [];
6118
+ for (let last = input.after ?? ""; scopeKeys.length < input.limit;) {
6119
+ const { rows } = await db.findMany("releases", {
6120
+ index: "scopes",
6121
+ where: {},
6122
+ limit: 1,
6123
+ range: { gt: last }
6124
+ });
6125
+ if (rows[0] === void 0) break;
6126
+ last = rows[0].scope_key;
6127
+ scopeKeys.push(last);
6128
+ }
6129
+ return scopeKeys;
6130
+ },
6131
+ /** Every channel by name; with `input`, one keyset page of them. */
6132
+ async listChannels(input) {
6133
+ if (input !== void 0) return (await db.findMany("channels", {
6134
+ index: "all",
6135
+ where: {},
6136
+ order: input.order ?? "asc",
6137
+ limit: input.limit,
6138
+ ...after(input)
6139
+ })).rows.map(toChannelRow);
5909
6140
  return (await drain$1((page) => db.findMany("channels", {
5910
6141
  index: "all",
5911
6142
  where: {},
@@ -5913,6 +6144,11 @@ const createCoreReads = (db, storage) => {
5913
6144
  ...page
5914
6145
  }))).map(toChannelRow);
5915
6146
  },
6147
+ async getChannels(ids) {
6148
+ const unique = [...new Set(ids)];
6149
+ if (unique.length === 0) return [];
6150
+ return (await db.findByKeys("channels", unique.map((id) => ({ id })))).flatMap((row) => row ? [toChannelRow(row)] : []);
6151
+ },
5916
6152
  async findChannelByName(name) {
5917
6153
  const row = await db.findOne("channels", { name });
5918
6154
  return row === null ? null : toChannelRow(row);
@@ -6846,25 +7082,28 @@ const checkScope = (scope) => {
6846
7082
  });
6847
7083
  if (scope.strategy === "FINGERPRINT" !== (scope.fingerprintHash !== null) || scope.scopeKey !== expected) fail$1("INVALID_SCOPE", "Release catalog scope metadata is inconsistent");
6848
7084
  };
6849
- /** A scope's enabled releases, all of them, under the catalog's guard. */
6850
- const enabledReleases = async (tx, scopeKey) => {
7085
+ /** Every row of a paged read, as release rows. */
7086
+ const drainReleases = async (page) => {
6851
7087
  const rows = [];
6852
7088
  let cursor;
6853
7089
  do {
6854
- const page = await tx.findMany("releases", {
6855
- index: "byScopeEnabled",
6856
- where: {
6857
- scope_key: scopeKey,
6858
- enabled: true
6859
- },
6860
- limit: PAGE$1,
6861
- ...cursor === void 0 ? {} : { cursor }
6862
- });
6863
- rows.push(...page.rows.map(toReleaseRow));
6864
- cursor = page.next;
7090
+ const found = await page(cursor);
7091
+ rows.push(...found.rows.map((row) => toReleaseRow(row)));
7092
+ cursor = found.next;
6865
7093
  } while (cursor !== void 0);
6866
7094
  return rows;
6867
7095
  };
7096
+ const enabledIn = (scopeKey, cursor) => ({
7097
+ index: "byScopeEnabled",
7098
+ where: {
7099
+ scope_key: scopeKey,
7100
+ enabled: true
7101
+ },
7102
+ limit: PAGE$1,
7103
+ ...cursor === void 0 ? {} : { cursor }
7104
+ });
7105
+ /** A scope's enabled releases, all of them, under the catalog's guard. */
7106
+ const enabledReleases = (tx, scopeKey) => drainReleases((cursor) => tx.findMany("releases", enabledIn(scopeKey, cursor)));
6868
7107
  /** The scope's newest release id: `byScope` descending, limit 1. */
6869
7108
  const latestReleaseId = async (tx, scopeKey) => {
6870
7109
  const { rows } = await tx.findMany("releases", {
@@ -6875,15 +7114,11 @@ const latestReleaseId = async (tx, scopeKey) => {
6875
7114
  });
6876
7115
  return rows[0]?.id ?? null;
6877
7116
  };
6878
- /** Compiles `enabled` and writes it as the scope's next catalog generation. */
6879
- const writeCatalog = async (tx, scope, stored, enabled, updatedAtMs) => {
6880
- const compilation = await compileReleaseCatalog({
6881
- strategy: scope.strategy,
6882
- releases: enabled.map(releaseRowToRelease)
6883
- });
6884
- const generation = (stored.generation ?? 0) + 1;
7117
+ /** The scope's next catalog generation, compiled as `compilation`. */
7118
+ const nextCatalog = (scope, stored, compilation, updatedAtMs) => {
7119
+ const generation = (stored.catalog?.generation ?? 0) + 1;
6885
7120
  if (!Number.isSafeInteger(generation)) fail$1("CATALOG_GENERATION_EXHAUSTED", `Catalog "${scope.scopeKey}" exhausted its generation counter`);
6886
- const catalog = {
7121
+ return {
6887
7122
  scope_key: scope.scopeKey,
6888
7123
  catalog_id: stored.catalog?.catalog_id ?? createUUIDv7(),
6889
7124
  strategy: scope.strategy,
@@ -6898,6 +7133,26 @@ const writeCatalog = async (tx, scope, stored, enabled, updatedAtMs) => {
6898
7133
  is_tombstone: compilation.payload.releaseDescriptors.length === 0,
6899
7134
  updated_at_ms: updatedAtMs
6900
7135
  };
7136
+ };
7137
+ /**
7138
+ * Compiles a scope's enabled releases. A catalog over the size limit is
7139
+ * refused naming its channel and platform, and what frees room in it.
7140
+ */
7141
+ const compileScope = async (scope, enabled) => {
7142
+ try {
7143
+ return await compileReleaseCatalog({
7144
+ strategy: scope.strategy,
7145
+ releases: enabled.map(releaseRowToRelease)
7146
+ });
7147
+ } catch (error) {
7148
+ if (!(error instanceof ReleaseCatalogCompilationError) || error.code !== "CATALOG_OVERSIZE") throw error;
7149
+ throw new ReleaseCatalogCompilationError("CATALOG_OVERSIZE", `The ${scope.platform} release catalog of channel "${scope.channelName}" would be over its ${MAX_COMPILED_CATALOG_BYTES / 1024} KiB limit.\nDisable or delete old bundles on that channel, then try again.`);
7150
+ }
7151
+ };
7152
+ /** Compiles `enabled` and writes it as the scope's next catalog generation. */
7153
+ const writeCatalog = async (tx, scope, stored, enabled, updatedAtMs) => {
7154
+ const compilation = await compileScope(scope, enabled);
7155
+ const catalog = nextCatalog(scope, stored, compilation, updatedAtMs);
6901
7156
  const { scope_key: _scopeKey, ...set } = catalog;
6902
7157
  if (stored.row === null) tx.create("release_catalogs", catalog);
6903
7158
  else tx.update("release_catalogs", stored.row, set);
@@ -6986,18 +7241,49 @@ const changeReleases = (db, inputs) => {
6986
7241
  return results;
6987
7242
  });
6988
7243
  };
7244
+ /** Whether `current` is what the scope's enabled releases compile to. */
7245
+ const isCurrent = (scope, current, compilation) => current.strategy === scope.strategy && current.channel_id === scope.channelId && current.channel_key === encodeChannelKey(scope.channelName) && current.platform === scope.platform && current.fingerprint_hash === scope.fingerprintHash && current.catalog_hash === compilation.catalogHash;
7246
+ /** The scope a catalog row names. */
7247
+ const catalogRowScope = (row) => ({
7248
+ channelId: row.channel_id,
7249
+ channelName: decodeChannelKey(row.channel_key),
7250
+ fingerprintHash: row.fingerprint_hash,
7251
+ platform: row.platform,
7252
+ scopeKey: row.scope_key,
7253
+ strategy: row.strategy
7254
+ });
7255
+ /**
7256
+ * What a rebuild of the scope's catalog would write, without writing: one
7257
+ * read of the catalog row and one of the scope's enabled releases. It needs
7258
+ * no transaction, whose guards would read the catalog again for each read
7259
+ * beneath it, nor the scope's newest release, which matters only to a scope
7260
+ * without a catalog row; that one is not found.
7261
+ */
7262
+ const preflightRebuild = async (db, scopeKey, updatedAtMs) => {
7263
+ const row = await db.findOne("release_catalogs", { scope_key: scopeKey });
7264
+ if (row === null) throw new Error(`Release catalog "${scopeKey}" was not found.`);
7265
+ const current = toCatalogRow(row);
7266
+ const scope = catalogRowScope(current);
7267
+ checkScope(scope);
7268
+ const enabled = await drainReleases((cursor) => db.findMany("releases", enabledIn(scopeKey, cursor)));
7269
+ const compilation = await compileScope(scope, enabled);
7270
+ const changed = !isCurrent(scope, current, compilation);
7271
+ return {
7272
+ changed,
7273
+ currentCatalog: current,
7274
+ diagnostics: compilation.diagnostics,
7275
+ projectedCatalog: changed ? nextCatalog(scope, { catalog: current }, compilation, updatedAtMs) : current
7276
+ };
7277
+ };
6989
7278
  /** Recompiles a scope's catalog from its enabled releases inside `tx`; an unchanged catalog is not rewritten. */
6990
7279
  const rebuildScope = async (tx, scope, updatedAtMs) => {
6991
7280
  checkScope(scope);
6992
7281
  const stored = await readCatalog(tx, scope.scopeKey);
6993
7282
  assertHistory(stored, await latestReleaseId(tx, scope.scopeKey) !== null);
6994
7283
  const enabled = await enabledReleases(tx, scope.scopeKey);
6995
- const compilation = await compileReleaseCatalog({
6996
- strategy: scope.strategy,
6997
- releases: enabled.map(releaseRowToRelease)
6998
- });
7284
+ const compilation = await compileScope(scope, enabled);
6999
7285
  const current = stored.catalog;
7000
- if (current !== null && current.strategy === scope.strategy && current.channel_id === scope.channelId && current.channel_key === encodeChannelKey(scope.channelName) && current.platform === scope.platform && current.fingerprint_hash === scope.fingerprintHash && current.catalog_hash === compilation.catalogHash) return {
7286
+ if (current !== null && isCurrent(scope, current, compilation)) return {
7001
7287
  catalog: current,
7002
7288
  current,
7003
7289
  changed: false,
@@ -7101,14 +7387,7 @@ const mutationResult = ({ catalog, release }) => ({
7101
7387
  const catalogScope = async (tx, scopeKey) => {
7102
7388
  const row = await tx.findOne("release_catalogs", { scope_key: scopeKey });
7103
7389
  if (row === null) throw new Error(`Release catalog "${scopeKey}" was not found.`);
7104
- return {
7105
- channelId: row.channel_id,
7106
- channelName: decodeChannelKey(row.channel_key),
7107
- fingerprintHash: row.fingerprint_hash,
7108
- platform: row.platform,
7109
- scopeKey: row.scope_key,
7110
- strategy: row.strategy
7111
- };
7390
+ return catalogRowScope(toCatalogRow(row));
7112
7391
  };
7113
7392
  /**
7114
7393
  * Core's typed writes: each runs in one engine transaction rooted at the
@@ -7316,18 +7595,7 @@ const createCoreOperations = (db, { now = Date.now } = {}) => {
7316
7595
  };
7317
7596
  });
7318
7597
  },
7319
- preflightReleaseCatalogRebuild: (scopeKey) => {
7320
- const updatedAtMs = now();
7321
- return dryRun(db, async (tx) => {
7322
- const rebuilt = await rebuildScope(tx, await catalogScope(tx, scopeKey), updatedAtMs);
7323
- return {
7324
- changed: rebuilt.changed,
7325
- currentCatalog: rebuilt.current,
7326
- diagnostics: rebuilt.diagnostics,
7327
- projectedCatalog: rebuilt.catalog
7328
- };
7329
- });
7330
- },
7598
+ preflightReleaseCatalogRebuild: (scopeKey) => preflightRebuild(db, scopeKey, now()),
7331
7599
  ensureChannel,
7332
7600
  deleteChannel: (id) => deleteChannel(db, id),
7333
7601
  updateBundle: (id, update) => db.transaction(async (tx) => {
@@ -7600,6 +7868,10 @@ const answer = async (operation) => {
7600
7868
  error: error.message
7601
7869
  }, status);
7602
7870
  }
7871
+ if (error instanceof ReleaseCatalogCompilationError && error.code === "CATALOG_OVERSIZE") return json$2({
7872
+ code: error.code,
7873
+ error: error.message
7874
+ }, 400);
7603
7875
  if (error instanceof DatabaseBundleNotFoundError) return json$2({
7604
7876
  code: "BUNDLE_NOT_FOUND",
7605
7877
  error: error.message
@@ -7619,9 +7891,11 @@ const LIMITS = {
7619
7891
  defaultValue: 50,
7620
7892
  maxValue: 500
7621
7893
  };
7894
+ /** The most IDs one request names: a lookup's, or a write's. */
7895
+ const MAX_IDS = 100;
7622
7896
  /** `order`, `cursor`, and `limit`: one keyset page. */
7623
- const keyset = (url, maxValue = LIMITS.maxValue) => {
7624
- const order = url.searchParams.get("order") ?? "desc";
7897
+ const keyset = (url, maxValue = LIMITS.maxValue, defaultOrder = "desc") => {
7898
+ const order = url.searchParams.get("order") ?? defaultOrder;
7625
7899
  if (order !== "asc" && order !== "desc") throw new HandlerBadRequestError("order must be 'asc' or 'desc'.");
7626
7900
  const limitParam = url.searchParams.get("limit");
7627
7901
  const limit = limitParam === null ? Math.min(LIMITS.defaultValue, maxValue) : Number(limitParam);
@@ -7817,12 +8091,40 @@ const createAdminRouteHandlers = () => ({
7817
8091
  const rows = await core.listReleaseCatalogs(input);
7818
8092
  return page(rows, input, (row) => row.scope_key);
7819
8093
  }),
7820
- /** With `name`, the one channel of that name: 1 read. */
8094
+ /** Up to 100 scope keys that have releases, after `cursor`: one seek each. */
8095
+ listReleaseScopeKeys: onCore(async (core, request) => {
8096
+ const input = keyset(new URL(request.url), 100, "asc");
8097
+ if (input.order !== "asc" || input.through !== void 0) throw new HandlerBadRequestError("Release scopes are listed ascending, by limit and cursor only.");
8098
+ const rows = await core.listReleaseScopeKeys({
8099
+ limit: input.limit,
8100
+ ...input.after === void 0 ? {} : { after: input.after }
8101
+ });
8102
+ return page(rows, input, (scopeKey) => scopeKey);
8103
+ }),
8104
+ /**
8105
+ * With `name`, the one channel of that name: 1 read. With `ids`, the
8106
+ * channels of up to 100 IDs: 1 batch read. With `limit` or `cursor`, one
8107
+ * page by name. With none, every channel, as servers before pages answered.
8108
+ */
7821
8109
  getChannels: onCore(async (core, request) => {
7822
- const name = new URL(request.url).searchParams.get("name");
7823
- if (name === null) return json$2({ data: await core.listChannels() });
7824
- const channel = await core.findChannelByName(name);
7825
- return channel === null ? notFound() : json$2({ data: channel });
8110
+ const url = new URL(request.url);
8111
+ const name = url.searchParams.get("name");
8112
+ if (name !== null) {
8113
+ const channel = await core.findChannelByName(name);
8114
+ return channel === null ? notFound() : json$2({ data: channel });
8115
+ }
8116
+ const ids = url.searchParams.get("ids");
8117
+ if (ids !== null) {
8118
+ const list = ids.split(",").filter((id) => id.length > 0);
8119
+ if (list.length === 0 || list.length > MAX_IDS) throw new HandlerBadRequestError(`Channels by ID take ids=<channel id>,... with 1 to ${MAX_IDS} ids.`);
8120
+ return json$2({ data: await core.getChannels(list) });
8121
+ }
8122
+ if (url.searchParams.has("limit") || url.searchParams.has("cursor")) {
8123
+ const input = keyset(url, LIMITS.maxValue, "asc");
8124
+ const rows = await core.listChannels(input);
8125
+ return page(rows, input, (row) => row.name);
8126
+ }
8127
+ return json$2({ data: await core.listChannels() });
7826
8128
  }),
7827
8129
  /** The channel named in the body, created when missing. */
7828
8130
  createChannel: onCore(async (core, request) => {
@@ -7873,7 +8175,7 @@ const createAdminRouteHandlers = () => ({
7873
8175
  countBundles: onCore(async (core, request) => json$2({ data: await core.countBundles(platformOf(new URL(request.url))) })),
7874
8176
  countBundleChildren: onCore(async (core, request) => {
7875
8177
  const ids = (new URL(request.url).searchParams.get("ids") ?? "").split(",").filter((id) => id.length > 0);
7876
- if (ids.length === 0 || ids.length > 100) throw new HandlerBadRequestError("Bundle child counts take ids=<bundle id>,... with 1 to 100 ids.");
8178
+ if (ids.length === 0 || ids.length > MAX_IDS) throw new HandlerBadRequestError(`Bundle child counts take ids=<bundle id>,... with 1 to ${MAX_IDS} ids.`);
7877
8179
  return json$2({ data: await core.countBundleChildren(ids) });
7878
8180
  }),
7879
8181
  listBundleChildren: onCore(async (core, request, params) => {
@@ -8015,6 +8317,7 @@ const createAdminRouteHandlers = () => ({
8015
8317
  markIosDevicesInBuild: onCore(async (core, request) => {
8016
8318
  const { buildId, ids } = await body(request);
8017
8319
  if (!isText$2(buildId) || !Array.isArray(ids) || !ids.every((id) => isText$2(id))) throw new HandlerBadRequestError("Marking iOS devices in a build needs buildId and ids.");
8320
+ if (ids.length > MAX_IDS) throw new HandlerBadRequestError(`Marking iOS devices in a build takes at most ${MAX_IDS} ids a request.`);
8018
8321
  await core.markIosDevicesInBuild({
8019
8322
  buildId,
8020
8323
  ids
@@ -8085,6 +8388,11 @@ const ADMIN_ROUTES = [
8085
8388
  path: "/release-catalogs",
8086
8389
  handler: "listReleaseCatalogs"
8087
8390
  },
8391
+ {
8392
+ method: "GET",
8393
+ path: "/release-scopes",
8394
+ handler: "listReleaseScopeKeys"
8395
+ },
8088
8396
  {
8089
8397
  method: "POST",
8090
8398
  path: "/release-catalogs/:scopeKey/rebuild",
@@ -8266,9 +8574,9 @@ const CATALOG_CACHE_CONTROL = "public, max-age=0, s-maxage=5";
8266
8574
  * background. `stale-if-error=0` keeps origin errors visible: without it,
8267
8575
  * Cloudflare serves a stale copy on error indefinitely.
8268
8576
  *
8269
- * A device can see a catalog up to 15 seconds after a deploy or a Roll back
8270
- * replaced it: the origin's 5-second catalog memo, then 5 seconds fresh and
8271
- * 5 stale at the CDN. A revoked API key can read a cached catalog up to
8577
+ * A device can see a catalog, or a scope's lack of one, up to 15 seconds
8578
+ * after a deploy or a Roll back replaced it: the origin's 5-second catalog
8579
+ * memo, then 5 seconds fresh and 5 stale at the CDN. A revoked API key can read a cached catalog up to
8272
8580
  * 10 seconds. Devices and caches that don't read the header keep
8273
8581
  * `Cache-Control`.
8274
8582
  */
@@ -8347,38 +8655,53 @@ const catalogResponse = async (catalog, request) => {
8347
8655
  };
8348
8656
  const createReleaseCatalogRouteHandlers = () => {
8349
8657
  const cache = /* @__PURE__ */ new Map();
8658
+ const evict = (insertedHit) => {
8659
+ const now = Date.now();
8660
+ let oldestMiss;
8661
+ let oldest;
8662
+ for (const [key, entry] of cache) if (entry.expiresAt <= now) cache.delete(key);
8663
+ else {
8664
+ if (entry.row === null) oldestMiss ??= key;
8665
+ oldest ??= key;
8666
+ }
8667
+ if (cache.size <= ORIGIN_CACHE_MAX_ENTRIES) return;
8668
+ const victim = oldestMiss ?? (insertedHit ? oldest : void 0);
8669
+ if (victim !== void 0) cache.delete(victim);
8670
+ };
8350
8671
  const inFlight = /* @__PURE__ */ new Map();
8351
- const loadCatalog = async (key, load) => {
8352
- const cached = cache.get(key);
8672
+ const loadRow = async (scopeKey, load) => {
8673
+ const cached = cache.get(scopeKey);
8353
8674
  if (cached !== void 0 && cached.expiresAt > Date.now()) {
8354
- cache.delete(key);
8355
- cache.set(key, cached);
8356
- return cached.catalog;
8675
+ cache.delete(scopeKey);
8676
+ cache.set(scopeKey, cached);
8677
+ return cached.row;
8357
8678
  }
8358
- if (cached !== void 0) cache.delete(key);
8359
- const pending = inFlight.get(key);
8679
+ if (cached !== void 0) cache.delete(scopeKey);
8680
+ const pending = inFlight.get(scopeKey);
8360
8681
  if (pending !== void 0) return pending;
8361
- const next = load().then((catalog) => {
8362
- if (catalog !== null) {
8363
- cache.set(key, {
8364
- catalog,
8365
- expiresAt: Date.now() + ORIGIN_CACHE_TTL_MS
8366
- });
8367
- while (cache.size > ORIGIN_CACHE_MAX_ENTRIES) {
8368
- const oldestKey = cache.keys().next().value;
8369
- if (oldestKey === void 0) break;
8370
- cache.delete(oldestKey);
8371
- }
8372
- }
8373
- return catalog;
8682
+ const next = load().then((row) => {
8683
+ cache.set(scopeKey, {
8684
+ row,
8685
+ expiresAt: Date.now() + ORIGIN_CACHE_TTL_MS
8686
+ });
8687
+ if (cache.size > ORIGIN_CACHE_MAX_ENTRIES) evict(row !== null);
8688
+ return row;
8374
8689
  });
8375
- inFlight.set(key, next);
8690
+ inFlight.set(scopeKey, next);
8376
8691
  try {
8377
8692
  return await next;
8378
8693
  } finally {
8379
- inFlight.delete(key);
8694
+ inFlight.delete(scopeKey);
8380
8695
  }
8381
8696
  };
8697
+ const loadCatalog = async (core, input) => {
8698
+ const scopeKey = releaseCatalogScopeKeyOf(input);
8699
+ const parsed = await loadRow(scopeKey, async () => {
8700
+ const row = await core.getReleaseCatalogRow(scopeKey);
8701
+ return row === null ? null : parseReleaseCatalogRow(row);
8702
+ });
8703
+ return projectParsedReleaseCatalogRow(parsed, input, scopeKey);
8704
+ };
8382
8705
  return {
8383
8706
  appVersionReleaseCatalog: async (params, request, { core }) => {
8384
8707
  const rawAppVersion = requireRouteParam(params, "appVersion");
@@ -8392,7 +8715,7 @@ const createReleaseCatalogRouteHandlers = () => {
8392
8715
  };
8393
8716
  const invalid = invalidScope(input);
8394
8717
  if (invalid) return invalid;
8395
- return catalogResponse(await loadCatalog(`app-version:${JSON.stringify(input)}`, () => core.getReleaseCatalog(input)), request);
8718
+ return catalogResponse(await loadCatalog(core, input), request);
8396
8719
  },
8397
8720
  fingerprintReleaseCatalog: async (params, request, { core }) => {
8398
8721
  const input = {
@@ -8403,7 +8726,7 @@ const createReleaseCatalogRouteHandlers = () => {
8403
8726
  };
8404
8727
  const invalid = invalidScope(input);
8405
8728
  if (invalid) return invalid;
8406
- return catalogResponse(await loadCatalog(`fingerprint:${JSON.stringify(input)}`, () => core.getReleaseCatalog(input)), request);
8729
+ return catalogResponse(await loadCatalog(core, input), request);
8407
8730
  },
8408
8731
  artifactV2: async (params, _request, { core }) => {
8409
8732
  const info = await core.getArtifactInfo(requireRouteParam(params, "targetBundleId"), requireRouteParam(params, "currentBundleId"), 2);
@@ -11686,13 +12009,80 @@ const breakdownOf = (rows) => {
11686
12009
  });
11687
12010
  };
11688
12011
  /**
12012
+ * The breakdown rows a failures read takes from one hour. An hour holds a
12013
+ * row per release, stage, reason, and detail that failed in it, a handful in
12014
+ * practice, and an incident across several releases and error codes still
12015
+ * fits; but a client with the app's API key can report any number of
12016
+ * details.
12017
+ */
12018
+ const FAILURE_ROWS_PER_HOUR = 20;
12019
+ /**
12020
+ * One query's stored rows: an hour's bound and one more row, on every shard,
12021
+ * so an hour past its bound costs at most one query's worth of rows more.
12022
+ */
12023
+ const FAILURE_QUERY_LIMIT = Math.min(PAGE, 168);
12024
+ /**
12025
+ * A channel's breakdown rows over a range, newest first, up to
12026
+ * {@link FAILURE_ROWS_PER_HOUR} an hour: 480 rows for a day, 14,400 for 30
12027
+ * days, however many details clients report. An hour that holds more is read
12028
+ * no further, and the read goes on from the hour before it with a new query;
12029
+ * the hour is listed in `cappedHours`, since its failures count only in part.
12030
+ * Every other hour counts every failure it holds.
12031
+ */
12032
+ const failureRowsByHour = async (db, platform, channel, timeRange) => {
12033
+ const read = (end, cursor) => db.findAggregates("insights_failures", {
12034
+ index: "byScope",
12035
+ where: {
12036
+ platform,
12037
+ channel
12038
+ },
12039
+ range: {
12040
+ gte: timeRange.start,
12041
+ lt: end
12042
+ },
12043
+ order: "desc",
12044
+ limit: FAILURE_QUERY_LIMIT,
12045
+ ...cursor === void 0 ? {} : { cursor }
12046
+ });
12047
+ const rows = [];
12048
+ const cappedHours = [];
12049
+ const perHour = /* @__PURE__ */ new Map();
12050
+ let end = timeRange.end;
12051
+ let cursor;
12052
+ while (end > timeRange.start) {
12053
+ const page = await read(end, cursor);
12054
+ let capped;
12055
+ for (const row of page.rows) {
12056
+ const hour = row.bucket_start_ms;
12057
+ const count = (perHour.get(hour) ?? 0) + 1;
12058
+ if (count > FAILURE_ROWS_PER_HOUR) {
12059
+ capped = hour;
12060
+ break;
12061
+ }
12062
+ perHour.set(hour, count);
12063
+ rows.push(row);
12064
+ }
12065
+ if (capped !== void 0) {
12066
+ cappedHours.unshift(capped);
12067
+ end = capped;
12068
+ cursor = void 0;
12069
+ } else if (page.next === void 0) break;
12070
+ else cursor = page.next;
12071
+ }
12072
+ return {
12073
+ rows,
12074
+ cappedHours
12075
+ };
12076
+ };
12077
+ /**
11689
12078
  * A release's or a channel's update failures. Since a release's first
11690
12079
  * report: its lifetime counters and failed installations. Over a time range
11691
12080
  * of at most 30 days: failures, failed checks, and the breakdown by stage,
11692
12081
  * reason, and detail, all summed from the breakdown's hourly rows; downloads
11693
12082
  * from the counters; failed installations from their sketches. A release reads hourly rows, a
11694
12083
  * channel daily rows past 48 hours like its activity; the breakdown's rows
11695
- * are hourly, so its coverage is the raw period's.
12084
+ * are hourly, so its coverage is the raw period's, and partial when an hour
12085
+ * held more breakdown rows than a read takes from it.
11696
12086
  */
11697
12087
  const getUpdateFailures = async (db, input, now, retention) => {
11698
12088
  const { platform, channel, releaseId, timeRange } = input;
@@ -11754,7 +12144,7 @@ const getUpdateFailures = async (db, input, now, retention) => {
11754
12144
  days,
11755
12145
  kept.hour
11756
12146
  ];
11757
- const [counters, failures, checks, active, rows] = await Promise.all([
12147
+ const [counters, failures, checks, active, { rows, cappedHours }] = await Promise.all([
11758
12148
  counterRows(db, parts, ...window),
11759
12149
  sketchRows(db, failure, ...window),
11760
12150
  days ? sketchRows(db, {
@@ -11762,25 +12152,17 @@ const getUpdateFailures = async (db, input, now, retention) => {
11762
12152
  scopeKind: "check"
11763
12153
  }, ...window) : [],
11764
12154
  days ? sketchRows(db, usageParts(channel, platform), ...window) : [],
11765
- drain((page) => db.findAggregates("insights_failures", {
11766
- index: "byScope",
11767
- where: {
11768
- platform,
11769
- channel
11770
- },
11771
- range: {
11772
- gte: timeRange.start,
11773
- lt: timeRange.end
11774
- },
11775
- limit: PAGE,
11776
- ...page
11777
- }))
12155
+ failureRowsByHour(db, platform, channel, timeRange)
11778
12156
  ]);
11779
12157
  const total = (field) => counters.reduce((sum, row) => sum + row[field], 0);
11780
12158
  const scoped = rows.filter((row) => FAILURE_STAGES.has(row.stage) && (releaseId === void 0 || row.release_id === releaseId));
11781
12159
  const failuresAt = (counted) => scoped.reduce((sum, row) => sum + (counted(row.stage) ? Math.max(0, row.events) : 0), 0);
12160
+ const coverage = coverageOf(timeRange.start, kept.hour);
11782
12161
  return {
11783
- coverage: coverageOf(timeRange.start, kept.hour),
12162
+ coverage: cappedHours.length === 0 ? coverage : {
12163
+ kind: "partial",
12164
+ sinceMs: coverage.sinceMs
12165
+ },
11784
12166
  measuredAtMs: at,
11785
12167
  failedUpdates: failuresAt((stage) => stage !== "check"),
11786
12168
  failedInstallations: failed(failures),
@@ -11792,7 +12174,8 @@ const getUpdateFailures = async (db, input, now, retention) => {
11792
12174
  failedInstallations: failed(checks),
11793
12175
  activeInstallations: countDistinct(mergeDistinct(active.map((row) => row.activity_users)))
11794
12176
  } } : {},
11795
- breakdown: breakdownOf(scoped)
12177
+ breakdown: breakdownOf(scoped),
12178
+ ...cappedHours.length === 0 ? {} : { cappedHours }
11796
12179
  };
11797
12180
  };
11798
12181
  //#endregion
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@hot-updater/aws",
3
3
  "type": "module",
4
- "version": "1.2.0-rc.49",
4
+ "version": "1.2.0-rc.50",
5
5
  "description": "React Native OTA solution for self-hosted",
6
6
  "main": "dist/index.cjs",
7
7
  "module": "dist/index.mjs",
@@ -45,9 +45,9 @@
45
45
  "es-toolkit": "^1.32.0",
46
46
  "execa": "9.5.2",
47
47
  "mime": "^4.0.4",
48
- "@hot-updater/protocol": "1.2.0-rc.49",
49
- "@hot-updater/mock": "1.2.0-rc.49",
50
- "@hot-updater/test-utils": "1.2.0-rc.49"
48
+ "@hot-updater/protocol": "1.2.0-rc.50",
49
+ "@hot-updater/mock": "1.2.0-rc.50",
50
+ "@hot-updater/test-utils": "1.2.0-rc.50"
51
51
  },
52
52
  "dependencies": {
53
53
  "@aws-sdk/client-cloudfront": "3.1066.0",
@@ -64,10 +64,10 @@
64
64
  "@aws-sdk/lib-dynamodb": "3.1066.0",
65
65
  "@aws-sdk/s3-request-presigner": "3.1066.0",
66
66
  "hono": "4.12.34",
67
- "@hot-updater/cli-tools": "1.2.0-rc.49",
68
- "@hot-updater/plugin-core": "1.2.0-rc.49",
69
- "@hot-updater/server": "1.2.0-rc.49",
70
- "@hot-updater/storage-s3": "1.2.0-rc.49"
67
+ "@hot-updater/plugin-core": "1.2.0-rc.50",
68
+ "@hot-updater/server": "1.2.0-rc.50",
69
+ "@hot-updater/storage-s3": "1.2.0-rc.50",
70
+ "@hot-updater/cli-tools": "1.2.0-rc.50"
71
71
  },
72
72
  "scripts": {
73
73
  "build": "tsdown",