@hot-updater/aws 1.2.0-rc.50 → 1.2.0-rc.52

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.
@@ -8775,6 +8775,7 @@ const runInit = async ({ build, envFile, secretsEnv }) => {
8775
8775
  });
8776
8776
  let credential;
8777
8777
  try {
8778
+ await (0, _hot_updater_cli_tools.fillReleaseLabels)(server);
8778
8779
  credential = await (0, _hot_updater_cli_tools.provisionClientCredential)(server, {
8779
8780
  env: providerEnv,
8780
8781
  name: "AWS init"
@@ -1,5 +1,5 @@
1
1
  import { createRequire } from "node:module";
2
- import { ConfigBuilder, InitError, MissingInitInputsError, assembleServer, assertInfrastructureGenerationAtUrl, assertInfrastructureGenerationPayload, assertInitProviderInputs, colors, confirmInitInputPersistence, copyDirToTmp, createHotUpdaterConfigScaffoldFromBuilder, createZip, ensureInstallPackages, getCwd, getHotUpdaterInitInputEnv, getInitProviderEnvVars, getInitProviderTextPromptValues, link, makeEnv, p, printAppSetup, provisionClientCredential, readHotUpdaterInitEnv, resolveInitProviderInput, transformEnv, writeHotUpdaterFiles } from "@hot-updater/cli-tools";
2
+ import { ConfigBuilder, InitError, MissingInitInputsError, assembleServer, assertInfrastructureGenerationAtUrl, assertInfrastructureGenerationPayload, assertInitProviderInputs, colors, confirmInitInputPersistence, copyDirToTmp, createHotUpdaterConfigScaffoldFromBuilder, createZip, ensureInstallPackages, fillReleaseLabels, getCwd, getHotUpdaterInitInputEnv, getInitProviderEnvVars, getInitProviderTextPromptValues, link, makeEnv, p, printAppSetup, provisionClientCredential, readHotUpdaterInitEnv, resolveInitProviderInput, transformEnv, writeHotUpdaterFiles } from "@hot-updater/cli-tools";
3
3
  import { apiKeys, insights, remoteConfig } from "@hot-updater/server/plugins";
4
4
  import { fileURLToPath } from "node:url";
5
5
  import { ChildProcess, execFile, spawn, spawnSync } from "node:child_process";
@@ -8770,6 +8770,7 @@ const runInit = async ({ build, envFile, secretsEnv }) => {
8770
8770
  });
8771
8771
  let credential;
8772
8772
  try {
8773
+ await fillReleaseLabels(server);
8773
8774
  credential = await provisionClientCredential(server, {
8774
8775
  env: providerEnv,
8775
8776
  name: "AWS init"
@@ -628,7 +628,8 @@ const releaseRowToRelease = (row) => ({
628
628
  operation: row.operation,
629
629
  sourceReleaseId: row.source_release_id,
630
630
  createdAtMs: row.created_at_ms,
631
- updatedAtMs: row.updated_at_ms
631
+ updatedAtMs: row.updated_at_ms,
632
+ label: row.label ?? null
632
633
  });
633
634
  const bundleToRow = (bundle) => {
634
635
  const metadata = bundleMetadataToRow(bundle.metadata);
@@ -1137,7 +1138,8 @@ function rangeToIntervals(range) {
1137
1138
  throw new ReleaseCatalogCompilationError("INVALID_TARGET_RANGE", `Invalid target app-version range: ${range}`);
1138
1139
  }
1139
1140
  }
1140
- function releaseDescriptor(release) {
1141
+ /** A release's descriptor; its label only when it has one and `labels`. */
1142
+ function releaseDescriptor(release, labels) {
1141
1143
  return {
1142
1144
  releaseId: release.id,
1143
1145
  kind: release.kind,
@@ -1145,7 +1147,8 @@ function releaseDescriptor(release) {
1145
1147
  rolloutCohortCount: release.rolloutCohortCount,
1146
1148
  targetCohorts: [...new Set(release.targetCohorts)].sort(),
1147
1149
  shouldForceUpdate: release.shouldForceUpdate,
1148
- message: release.message
1150
+ message: release.message,
1151
+ ...labels && typeof release.label === "number" ? { label: release.label } : {}
1149
1152
  };
1150
1153
  }
1151
1154
  function validateReleases(releases, strategy) {
@@ -1353,17 +1356,96 @@ function canonicalStringify(value) {
1353
1356
  const record = value;
1354
1357
  return `{${Object.keys(record).sort().map((key) => `${JSON.stringify(key)}:${canonicalStringify(record[key])}`).join(",")}}`;
1355
1358
  }
1359
+ const BOUND_SHAPE = {
1360
+ inclusive: null,
1361
+ version: null
1362
+ };
1363
+ /**
1364
+ * Every key this release's compiler writes in a catalog payload, where it
1365
+ * writes it: the envelope's, a segment's and its bounds', and a release
1366
+ * descriptor's. A key outside it was written by a later release.
1367
+ */
1368
+ const COMPILED_CATALOG_SHAPE = {
1369
+ fallbackPolicy: null,
1370
+ schemaVersion: null,
1371
+ strategy: null,
1372
+ releaseIndexes: null,
1373
+ rollbackReleaseIndexes: null,
1374
+ segments: {
1375
+ lower: BOUND_SHAPE,
1376
+ upper: BOUND_SHAPE,
1377
+ releaseIndexes: null,
1378
+ rollbackReleaseIndexes: null
1379
+ },
1380
+ releaseDescriptors: {
1381
+ releaseId: null,
1382
+ kind: null,
1383
+ bundleId: null,
1384
+ rolloutCohortCount: null,
1385
+ targetCohorts: null,
1386
+ shouldForceUpdate: null,
1387
+ message: null,
1388
+ label: null
1389
+ }
1390
+ };
1391
+ /**
1392
+ * A stored catalog payload as this release reads it: canonical, with the
1393
+ * keys a later release added left out, and whether it had any, a later
1394
+ * schema version included. Server core compares a catalog by the fields
1395
+ * its compiler writes, and refuses to rewrite one a later release wrote,
1396
+ * which would drop what that release added.
1397
+ */
1398
+ function readCompiledCatalogPayload(payload) {
1399
+ let fromLaterRelease = false;
1400
+ const known = (value, shape) => {
1401
+ if (Array.isArray(value)) return value.map((item) => known(item, shape));
1402
+ if (value === null || typeof value !== "object") return value;
1403
+ const entries = Object.entries(value).filter(([key]) => {
1404
+ if (Object.hasOwn(shape, key)) return true;
1405
+ fromLaterRelease = true;
1406
+ return false;
1407
+ });
1408
+ return Object.fromEntries(entries.map(([key, entry]) => {
1409
+ const inner = shape[key];
1410
+ return [key, inner === null ? entry : known(entry, inner)];
1411
+ }));
1412
+ };
1413
+ let parsed;
1414
+ try {
1415
+ parsed = JSON.parse(payload);
1416
+ } catch {
1417
+ parsed = null;
1418
+ }
1419
+ if (parsed === null || typeof parsed !== "object" || Array.isArray(parsed)) return {
1420
+ canonicalPayload: payload,
1421
+ fromLaterRelease: false
1422
+ };
1423
+ if ("schemaVersion" in parsed && typeof parsed.schemaVersion === "number" && parsed.schemaVersion > 1) fromLaterRelease = true;
1424
+ return {
1425
+ canonicalPayload: canonicalStringify(known(parsed, COMPILED_CATALOG_SHAPE)),
1426
+ fromLaterRelease
1427
+ };
1428
+ }
1356
1429
  async function compileReleaseCatalog(input) {
1357
1430
  const releases = validateReleases(input.releases, input.strategy);
1358
1431
  const targetCohorts = new Set(releases.flatMap((release) => release.targetCohorts));
1359
1432
  if (targetCohorts.size > 512) throw new ReleaseCatalogCompilationError("DISTINCT_TARGET_COHORT_LIMIT", `Scope exceeds 512 distinct target cohorts`);
1360
1433
  const { envelope, retainedReleases } = input.strategy === "APP_VERSION" ? compileAppVersion(releases) : compileFingerprint(releases);
1361
- const payload = {
1362
- ...envelope,
1363
- releaseDescriptors: retainedReleases.map(releaseDescriptor)
1434
+ const compile = (labels) => {
1435
+ const payload = {
1436
+ ...envelope,
1437
+ releaseDescriptors: retainedReleases.map((release) => releaseDescriptor(release, labels))
1438
+ };
1439
+ const canonicalPayload = canonicalStringify(payload);
1440
+ return {
1441
+ payload,
1442
+ canonicalPayload,
1443
+ byteSize: new TextEncoder().encode(canonicalPayload).byteLength
1444
+ };
1364
1445
  };
1365
- const canonicalPayload = canonicalStringify(payload);
1366
- const byteSize = new TextEncoder().encode(canonicalPayload).byteLength;
1446
+ let compiled = compile(true);
1447
+ if (compiled.byteSize > 262144 && retainedReleases.some((release) => typeof release.label === "number")) compiled = compile(false);
1448
+ const { payload, canonicalPayload, byteSize } = compiled;
1367
1449
  if (byteSize > 262144) throw new ReleaseCatalogCompilationError("CATALOG_OVERSIZE", `Compiled Release catalog is ${byteSize} bytes; maximum is ${MAX_COMPILED_CATALOG_BYTES}`);
1368
1450
  return {
1369
1451
  byteSize,
@@ -1931,6 +2013,23 @@ const SETTINGS_TABLE = {
1931
2013
  /** The engine's storage-layout generation; it changes only with a migration. */
1932
2014
  const ENGINE_SCHEMA_KEY = "schema.engine";
1933
2015
  const CORE_SCHEMA_KEY = "schema.core";
2016
+ /** Compares dotted numeric versions, such as "1" and "1.2.0"; NaN when either is not one. */
2017
+ const compareVersions = (left, right) => {
2018
+ const parse = (version) => /^\d+(?:\.\d+)*$/u.test(version) ? version.split(".").map(Number) : [NaN];
2019
+ const [a, b] = [parse(left), parse(right)];
2020
+ if ([...a, ...b].some(Number.isNaN)) return NaN;
2021
+ for (let index = 0; index < Math.max(a.length, b.length); index += 1) {
2022
+ const difference = (a[index] ?? 0) - (b[index] ?? 0);
2023
+ if (difference !== 0) return difference;
2024
+ }
2025
+ return 0;
2026
+ };
2027
+ /**
2028
+ * The `schema.core` a newer release recorded, which `hot-updater db migrate`
2029
+ * never moves back: the fix is to upgrade, not to migrate.
2030
+ */
2031
+ const newerCore = (settings) => settings.find(({ key, expected, found }) => key === CORE_SCHEMA_KEY && found !== null && compareVersions(found, expected) > 0);
2032
+ const newerMessage = (adapterName, { key, expected, found }) => `Hot Updater schema setting "${key}" for ${adapterName} is "${found}"; expected "${expected}". The database was migrated by Hot Updater ${found}: upgrade hot-updater and the @hot-updater packages to ${found} or later.`;
1934
2033
  const stored = ({ key, expected, found }) => `"${key}" is ${found === null ? "missing" : `"${found}"`}; expected "${expected}"`;
1935
2034
  /**
1936
2035
  * How to migrate a database the fence refused: doctor names the command for
@@ -1944,7 +2043,10 @@ const pluginOf = ({ key }) => key.startsWith("schema.") && key !== "schema.engin
1944
2043
  const listed = (items) => items.length < 2 ? items.join("") : `${items.slice(0, -1).join(", ")} and ${items.at(-1)}`;
1945
2044
  const settingsMessage = (adapterName, settings) => `Hot Updater schema settings for ${adapterName} are not migrated: ${settings.map(stored).join(", and ")}. ${MIGRATE_SCHEMA_FIX}`;
1946
2045
  const pluginsMessage = (adapterName, plugins, settings, fix) => `The tables of ${plugins.length === 1 ? "plugin" : "plugins"} ${listed(plugins.map((id) => `"${id}"`))} are not migrated on ${adapterName}: schema ${settings.length === 1 ? "setting" : "settings"} ${settings.map(stored).join(", and ")}. ${fix}`;
1947
- /** The database needs `hot-updater db migrate`, or a new database; the handler answers 503. */
2046
+ /**
2047
+ * The database needs `hot-updater db migrate`, a new database, or a newer
2048
+ * Hot Updater; the handler answers 503.
2049
+ */
1948
2050
  var HotUpdaterSchemaMigrationRequiredError = class extends Error {
1949
2051
  adapterName;
1950
2052
  currentVersion;
@@ -1959,7 +2061,8 @@ var HotUpdaterSchemaMigrationRequiredError = class extends Error {
1959
2061
  constructor(adapterName, currentVersion, setting, options) {
1960
2062
  const settings = options?.settings ?? (setting === void 0 ? [] : [setting]);
1961
2063
  const plugins = settings.flatMap((mismatch) => pluginOf(mismatch) ?? []);
1962
- super(setting === void 0 ? currentVersion === void 0 ? `Hot Updater database schema is not initialized for ${adapterName}. ${MIGRATE_SCHEMA_FIX}` : `Hot Updater v1 cannot migrate schema ${currentVersion} in place. Create a new empty database and run \`hot-updater db migrate\`.` : plugins.length > 0 && plugins.length === settings.length ? pluginsMessage(adapterName, plugins, settings, options?.fix ?? MIGRATE_SCHEMA_FIX) : settings.length > 1 && !(setting.key === "schema.engine" && setting.found === null) ? settingsMessage(adapterName, settings) : settingMessage(adapterName, setting), options?.cause === void 0 ? void 0 : { cause: options.cause });
2064
+ const newer = newerCore(settings);
2065
+ super(newer !== void 0 ? newerMessage(adapterName, newer) : setting === void 0 ? currentVersion === void 0 ? `Hot Updater database schema is not initialized for ${adapterName}. ${MIGRATE_SCHEMA_FIX}` : `Hot Updater v1 cannot migrate schema ${currentVersion} in place. Create a new empty database and run \`hot-updater db migrate\`.` : plugins.length > 0 && plugins.length === settings.length ? pluginsMessage(adapterName, plugins, settings, options?.fix ?? MIGRATE_SCHEMA_FIX) : settings.length > 1 && !(setting.key === "schema.engine" && setting.found === null) ? settingsMessage(adapterName, settings) : settingMessage(adapterName, setting), options?.cause === void 0 ? void 0 : { cause: options.cause });
1963
2066
  this.adapterName = adapterName;
1964
2067
  this.currentVersion = currentVersion;
1965
2068
  this.setting = setting;
@@ -2092,7 +2195,7 @@ const CHANNEL_ID = {
2092
2195
  * every database's migrator creates missing tables and then records the
2093
2196
  * version, and none of them changes an existing table's columns, so changing
2094
2197
  * 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
2198
+ * table is listed in `LATE_INDEXES`, and a column in `LATE_COLUMNS`. The schema fence answers 503 on
2096
2199
  * a database whose row differs, until it runs. Before a version is released,
2097
2200
  * its tables change in place in its own migration, and a database one of its
2098
2201
  * prereleases migrated takes the same change by hand: the fence compares this
@@ -2245,7 +2348,11 @@ const releases = defineTable({
2245
2348
  }
2246
2349
  },
2247
2350
  created_at_ms: { type: "integer" },
2248
- updated_at_ms: { type: "integer" }
2351
+ updated_at_ms: { type: "integer" },
2352
+ label: {
2353
+ type: "integer",
2354
+ required: false
2355
+ }
2249
2356
  }, {
2250
2357
  key: ["id"],
2251
2358
  indexes: {
@@ -2282,6 +2389,15 @@ const releases = defineTable({
2282
2389
  scopes: {
2283
2390
  eq: [],
2284
2391
  sort: ["scope_key"]
2392
+ },
2393
+ byLabel: {
2394
+ eq: [
2395
+ "channel_id",
2396
+ "platform",
2397
+ "label"
2398
+ ],
2399
+ sort: [],
2400
+ unique: true
2285
2401
  }
2286
2402
  }
2287
2403
  });
@@ -2298,6 +2414,43 @@ const LATE_INDEXES = [{
2298
2414
  table: "releases",
2299
2415
  index: "scopes"
2300
2416
  }];
2417
+ /**
2418
+ * Columns added to a table that a released schema created: a migrator whose
2419
+ * store has columns adds each one missing from an existing table, with
2420
+ * `ALTER TABLE … ADD COLUMN`, before it creates the table's indexes, and
2421
+ * `db migrate` on a database whose settings match still looks for them,
2422
+ * since a database a prerelease migrated records the same settings. Each
2423
+ * is optional, so rows written before it, and rows a server of the earlier
2424
+ * release still writes, read as null. `releases.label` arrived in 1.2.0.
2425
+ */
2426
+ const LATE_COLUMNS = [{
2427
+ table: "releases",
2428
+ column: "label"
2429
+ }];
2430
+ /**
2431
+ * One counter per sequence: `releases/<platform>/<channel ID>` holds the
2432
+ * last label that channel and platform's releases took. A deploy or a
2433
+ * promote reads it and writes the next value in the transaction that writes
2434
+ * the release, so two writers never take one label. `is_filled` is true once
2435
+ * every release of the sequence written before labels has one, in ID order;
2436
+ * until then a writer fills them first. Deleting a channel deletes its
2437
+ * counters, so a channel created again with the name starts at 1.
2438
+ */
2439
+ const labelSequences = defineTable({
2440
+ id: {
2441
+ type: "string",
2442
+ maxLength: 1440,
2443
+ ascii: true
2444
+ },
2445
+ last_label: { type: "integer" },
2446
+ is_filled: { type: "boolean" }
2447
+ }, {
2448
+ key: ["id"],
2449
+ indexes: { all: {
2450
+ eq: [],
2451
+ sort: ["id"]
2452
+ } }
2453
+ });
2301
2454
  /** One compiled catalog per scope; the update check reads exactly this row. */
2302
2455
  const releaseCatalogs = defineTable({
2303
2456
  scope_key: {
@@ -2669,7 +2822,8 @@ const coreModule = {
2669
2822
  }),
2670
2823
  native_builds: nativeBuilds,
2671
2824
  ios_devices: iosDevices,
2672
- ios_device_account: iosDeviceAccount
2825
+ ios_device_account: iosDeviceAccount,
2826
+ label_sequences: labelSequences
2673
2827
  }
2674
2828
  };
2675
2829
  //#endregion
@@ -2695,17 +2849,6 @@ const refuseV0Database = (adapterName, stored) => {
2695
2849
  if (typeof version !== "string" || stored.has("schema.engine")) return;
2696
2850
  throw new HotUpdaterSchemaMigrationRequiredError(adapterName, version);
2697
2851
  };
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
2852
  /**
2710
2853
  * The settings whose versions only move forward when a `ToolingTarget` names
2711
2854
  * none. `schema.engine` is a storage layout, not a release: a store refuses
@@ -2797,8 +2940,26 @@ const fillLateIndexes = async (adapter, tables, { dryRun = false } = {}) => {
2797
2940
  return lacking;
2798
2941
  };
2799
2942
  /**
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
2943
+ * The `LATE_COLUMNS` among `tables` that an existing table lacks, as
2944
+ * `<table>.<column>`, added unless `dryRun`: none on a store without
2945
+ * `migrations.addColumns`, or for a table not created yet.
2946
+ */
2947
+ const addLateColumns = async (adapter, tables, { dryRun = false } = {}) => {
2948
+ const addColumns = adapter.migrations?.addColumns;
2949
+ if (addColumns === void 0) return [];
2950
+ const lacking = [];
2951
+ for (const table of tables) {
2952
+ const columns = LATE_COLUMNS.filter(({ table: name }) => name === table.name).map(({ column }) => column);
2953
+ if (columns.length === 0) continue;
2954
+ const added = await addColumns(table, columns, { dryRun });
2955
+ lacking.push(...added.map((column) => `${table.name}.${column}`));
2956
+ }
2957
+ return lacking;
2958
+ };
2959
+ /**
2960
+ * Adds the late columns existing tables lack, creates or updates every
2961
+ * table, writes the late indexes' missing items, then writes the settings
2962
+ * rows last. A database a newer release migrated is
2802
2963
  * refused before anything is written: its settings are read first, and a
2803
2964
  * store without them yet, whose read fails, has none to refuse.
2804
2965
  */
@@ -2806,6 +2967,7 @@ const migrateSchema = async (adapter, adapterName, tables, settings, ordered) =>
2806
2967
  if (adapter.migrations === void 0) throw new Error(`${adapterName} creates its tables with its own tooling; write only the settings rows.`);
2807
2968
  const stored = await storedSettings(adapter, Object.keys(settings)).catch(() => void 0);
2808
2969
  if (stored !== void 0) refuseNewerSchema(adapterName, new Map([...stored].map(([key, row]) => [key, row?.value])), settings, ordered);
2970
+ await addLateColumns(adapter, tables);
2809
2971
  await adapter.migrations.apply([...tables, SETTINGS_TABLE]);
2810
2972
  await fillLateIndexes(adapter, tables);
2811
2973
  await writeSchemaSettings(adapter, adapterName, settings, ordered);
@@ -3842,23 +4004,45 @@ const createEngineMigrator = (options) => {
3842
4004
  refuseNewerSchema(options.adapterName, stored, options.settings, options.ordered);
3843
4005
  const changed = Object.entries(options.settings).filter(([key, value]) => stored.get(key) !== value);
3844
4006
  if (changed.length === 0) {
4007
+ const columns = await addLateColumns(options.adapter, options.schema.tables, { dryRun: true });
3845
4008
  const lacking = await fillLateIndexes(options.adapter, options.schema.tables, { dryRun: true });
3846
- if (lacking.length === 0) return getEmptyMigrationResult();
4009
+ if (columns.length === 0 && lacking.length === 0) return getEmptyMigrationResult();
3847
4010
  return {
3848
- operations: [{
3849
- type: "custom",
3850
- description: `Write the index items rows lack: ${lacking.join(", ")}`
3851
- }],
4011
+ operations: [
4012
+ ...columns.map((column) => ({
4013
+ type: "custom",
4014
+ description: `Add column: ${column}`
4015
+ })),
4016
+ ...columns.length === 0 ? [] : [{
4017
+ type: "custom",
4018
+ description: "Create the tables and indexes the database lacks"
4019
+ }],
4020
+ ...lacking.length === 0 ? [] : [{
4021
+ type: "custom",
4022
+ description: `Write the index items rows lack: ${lacking.join(", ")}`
4023
+ }]
4024
+ ],
3852
4025
  execute: async () => {
4026
+ if (columns.length > 0) {
4027
+ await addLateColumns(options.adapter, options.schema.tables);
4028
+ await options.adapter.migrations.apply([...options.schema.tables, SETTINGS_TABLE]);
4029
+ }
3853
4030
  await fillLateIndexes(options.adapter, options.schema.tables);
3854
4031
  }
3855
4032
  };
3856
4033
  }
3857
4034
  return {
3858
- operations: [{
3859
- type: "custom",
3860
- description: "Create the tables and indexes the database lacks"
3861
- }, ...migrate.updateSettings === false ? [] : [settingsOperation(stored, changed)]],
4035
+ operations: [
4036
+ ...(await addLateColumns(options.adapter, options.schema.tables, { dryRun: true }).catch(() => [])).map((column) => ({
4037
+ type: "custom",
4038
+ description: `Add column: ${column}`
4039
+ })),
4040
+ {
4041
+ type: "custom",
4042
+ description: "Create the tables and indexes the database lacks"
4043
+ },
4044
+ ...migrate.updateSettings === false ? [] : [settingsOperation(stored, changed)]
4045
+ ],
3862
4046
  execute: () => migrateSchema(options.adapter, options.adapterName, options.schema.tables, options.settings, options.ordered)
3863
4047
  };
3864
4048
  };
@@ -5042,7 +5226,7 @@ const createKvAdapter = ({ store, tablePrefix = "" }) => {
5042
5226
  };
5043
5227
  //#endregion
5044
5228
  //#region ../../packages/server/dist/version.mjs
5045
- const HOT_UPDATER_SERVER_VERSION = "1.2.0-rc.50";
5229
+ const HOT_UPDATER_SERVER_VERSION = "1.2.0-rc.52";
5046
5230
  //#endregion
5047
5231
  //#region ../../packages/server/dist/handlerVersionRoutes.mjs
5048
5232
  /**
@@ -5841,7 +6025,7 @@ const baseBundleIdsOf = (row, range, bundleId, limit) => {
5841
6025
  };
5842
6026
  //#endregion
5843
6027
  //#region ../../packages/server/dist/core/reads.mjs
5844
- const PAGE$3 = 500;
6028
+ const PAGE$4 = 500;
5845
6029
  const pick$2 = (fields) => (row) => Object.fromEntries(fields.map((field) => [field, row[field]]));
5846
6030
  const toBundleRow = pick$2([
5847
6031
  "id",
@@ -5862,7 +6046,7 @@ const toPatchRow = pick$2([
5862
6046
  "byte_size",
5863
6047
  "order_index"
5864
6048
  ]);
5865
- const toReleaseRow = pick$2([
6049
+ const pickReleaseRow = pick$2([
5866
6050
  "id",
5867
6051
  "revision",
5868
6052
  "scope_key",
@@ -5883,6 +6067,13 @@ const toReleaseRow = pick$2([
5883
6067
  "created_at_ms",
5884
6068
  "updated_at_ms"
5885
6069
  ]);
6070
+ /** A release row; `label` null where the store holds none, as before the column. */
6071
+ const toReleaseRow = (row) => {
6072
+ return {
6073
+ ...pickReleaseRow(row),
6074
+ label: typeof row.label === "number" ? row.label : null
6075
+ };
6076
+ };
5886
6077
  const toCatalogRow = pick$2([
5887
6078
  "scope_key",
5888
6079
  "catalog_id",
@@ -5931,7 +6122,7 @@ const createCoreReads = (db, storage) => {
5931
6122
  const page = await db.findMany("bundle_patches", {
5932
6123
  index: "byBundle",
5933
6124
  where: { bundle_id: row.id },
5934
- limit: Math.min(count - patches.length, PAGE$3),
6125
+ limit: Math.min(count - patches.length, PAGE$4),
5935
6126
  ...cursor === void 0 ? {} : { cursor }
5936
6127
  });
5937
6128
  patches.push(...page.rows.map(toPatchRow));
@@ -6041,6 +6232,23 @@ const createCoreReads = (db, storage) => {
6041
6232
  const row = await db.findOne("releases", { id });
6042
6233
  return row === null ? null : toReleaseRow(row);
6043
6234
  },
6235
+ /**
6236
+ * The release a label names: its unique index, then the row itself,
6237
+ * since a key-value store keeps an index copy a server of an earlier
6238
+ * release may have left behind when it changed or deleted the row.
6239
+ */
6240
+ async getReleaseByLabel({ channel, platform, label }) {
6241
+ const found = await db.findOne("releases", {
6242
+ channel_id: `channel:${encodeChannelKey(channel)}`,
6243
+ platform,
6244
+ label
6245
+ });
6246
+ if (found === null) return null;
6247
+ const row = await db.findOne("releases", { id: found.id });
6248
+ if (row === null) return null;
6249
+ const release = toReleaseRow(row);
6250
+ return release.label === label && release.platform === platform ? release : null;
6251
+ },
6044
6252
  /** One page of releases through the index its filter names. */
6045
6253
  async listReleases(input) {
6046
6254
  const { filter } = input;
@@ -6140,7 +6348,7 @@ const createCoreReads = (db, storage) => {
6140
6348
  return (await drain$1((page) => db.findMany("channels", {
6141
6349
  index: "all",
6142
6350
  where: {},
6143
- limit: PAGE$3,
6351
+ limit: PAGE$4,
6144
6352
  ...page
6145
6353
  }))).map(toChannelRow);
6146
6354
  },
@@ -6468,6 +6676,313 @@ const NATIVE_BUILD_SUBMISSION_DESTINATIONS = {
6468
6676
  ios: ["testflight"]
6469
6677
  };
6470
6678
  //#endregion
6679
+ //#region ../../packages/server/dist/core/labels.mjs
6680
+ /**
6681
+ * The counter of a channel and platform's release labels: one
6682
+ * `label_sequences` row, which every writer of the pair reads and bumps.
6683
+ */
6684
+ const labelSequenceId = (channelId, platform) => `releases/${platform}/${channelId}`;
6685
+ /** The pairs a channel's counters belong to, which deleting it removes. */
6686
+ const LABEL_PLATFORMS = ["ios", "android"];
6687
+ /**
6688
+ * A channel and platform whose releases written before labels have none
6689
+ * yet, or that has no counter: the write stops before taking a label, the
6690
+ * core labels the pair with `fillLabels`, and the write runs again.
6691
+ */
6692
+ var NeedsLabelFill = class extends Error {
6693
+ channelId;
6694
+ platform;
6695
+ constructor(channelId, platform) {
6696
+ super(`Release labels of ${platform} ${channelId} need a fill first.`);
6697
+ this.channelId = channelId;
6698
+ this.platform = platform;
6699
+ }
6700
+ };
6701
+ const createLabelAllocator = (tx, used, caughtUp) => {
6702
+ const sequences = /* @__PURE__ */ new Map();
6703
+ return {
6704
+ async next(channelId, platform) {
6705
+ const id = labelSequenceId(channelId, platform);
6706
+ let sequence = sequences.get(id);
6707
+ if (sequence === void 0) {
6708
+ const row = await tx.findOne("label_sequences", { id });
6709
+ if (row === null || !row.is_filled) {
6710
+ const channel = row === null ? await tx.findOne("channels", { id: channelId }) : null;
6711
+ if (channel === null || (channel._refs_releases_channel_id ?? 0) > 0) throw new NeedsLabelFill(channelId, platform);
6712
+ }
6713
+ const read = row?.last_label ?? 0;
6714
+ sequence = {
6715
+ row,
6716
+ read,
6717
+ last: read
6718
+ };
6719
+ sequences.set(id, sequence);
6720
+ used.set(id, {
6721
+ channelId,
6722
+ platform,
6723
+ read
6724
+ });
6725
+ }
6726
+ sequence.last += 1;
6727
+ return sequence.last;
6728
+ },
6729
+ caughtUp(channelId, platform) {
6730
+ caughtUp.set(labelSequenceId(channelId, platform), {
6731
+ channelId,
6732
+ platform
6733
+ });
6734
+ },
6735
+ flush() {
6736
+ for (const [id, { row, read, last }] of sequences) if (row === null) tx.create("label_sequences", {
6737
+ id,
6738
+ last_label: last,
6739
+ is_filled: true
6740
+ });
6741
+ else if (last !== read) tx.update("label_sequences", row, { last_label: last });
6742
+ }
6743
+ };
6744
+ };
6745
+ const FILL_BATCH = 25;
6746
+ const PAGE$3 = 500;
6747
+ /**
6748
+ * Labels a channel and platform's releases that have none, in ID order,
6749
+ * which is the order they were created in, and marks its counter filled:
6750
+ * each batch reads the counter and its rows guarded, so a concurrent fill or
6751
+ * write serializes on the counter and skips what another labeled. With
6752
+ * `dryRun`, it only counts them. Answers how many it labeled.
6753
+ */
6754
+ const fillLabels = async (db, { channelId, platform }, { dryRun = false } = {}) => {
6755
+ const id = labelSequenceId(channelId, platform);
6756
+ let labeled = 0;
6757
+ let batchSize = FILL_BATCH;
6758
+ const label = async (ids) => {
6759
+ for (let at = 0; at < ids.length;) {
6760
+ const batch = ids.slice(at, at + batchSize);
6761
+ try {
6762
+ labeled += await db.transaction(async (tx) => {
6763
+ const counter = await tx.findOne("label_sequences", { id });
6764
+ let last = counter?.last_label ?? 0;
6765
+ let count = 0;
6766
+ for (const releaseId of batch) {
6767
+ const row = await tx.findOne("releases", { id: releaseId });
6768
+ if (row === null || typeof row.label === "number") continue;
6769
+ last += 1;
6770
+ count += 1;
6771
+ tx.update("releases", row, { label: last });
6772
+ }
6773
+ if (counter === null) tx.create("label_sequences", {
6774
+ id,
6775
+ last_label: last,
6776
+ is_filled: false
6777
+ });
6778
+ else if (last !== counter.last_label) tx.update("label_sequences", counter, { last_label: last });
6779
+ return count;
6780
+ });
6781
+ at += batch.length;
6782
+ } catch (error) {
6783
+ if (batchSize > 1 && error instanceof DatabaseConstraintError && error.reason === "too_large") {
6784
+ batchSize = Math.max(1, Math.floor(batchSize / 2));
6785
+ continue;
6786
+ }
6787
+ throw error;
6788
+ }
6789
+ }
6790
+ };
6791
+ let cursor;
6792
+ do {
6793
+ const page = await db.findMany("releases", {
6794
+ index: "byChannelPlatform",
6795
+ where: {
6796
+ channel_id: channelId,
6797
+ platform
6798
+ },
6799
+ limit: PAGE$3,
6800
+ ...cursor === void 0 ? {} : { cursor }
6801
+ });
6802
+ const unlabeled = page.rows.filter((row) => typeof row.label !== "number").map((row) => row.id);
6803
+ if (dryRun) labeled += unlabeled.length;
6804
+ else await label(unlabeled);
6805
+ cursor = page.next;
6806
+ } while (cursor !== void 0);
6807
+ if (dryRun) return labeled;
6808
+ await db.transaction(async (tx) => {
6809
+ const counter = await tx.findOne("label_sequences", { id });
6810
+ if (counter === null) tx.create("label_sequences", {
6811
+ id,
6812
+ last_label: 0,
6813
+ is_filled: true
6814
+ });
6815
+ else if (!counter.is_filled) tx.update("label_sequences", counter, { is_filled: true });
6816
+ });
6817
+ return labeled;
6818
+ };
6819
+ /**
6820
+ * Reads what a pair's fill writes, its counter and its label index, without
6821
+ * writing: a database without release labels' schema, such as one a 1.2
6822
+ * prerelease migrated, fails here as the fill would. The schema is the
6823
+ * database's, so one pair tells. Two reads.
6824
+ */
6825
+ const probeLabelSchema = async (db, { channelId, platform }) => {
6826
+ await db.findOne("label_sequences", { id: labelSequenceId(channelId, platform) });
6827
+ await db.findMany("releases", {
6828
+ index: "byLabel",
6829
+ where: {
6830
+ channel_id: channelId,
6831
+ platform,
6832
+ label: 0
6833
+ },
6834
+ limit: 1
6835
+ });
6836
+ };
6837
+ const REPAIRS = 4;
6838
+ const RACES = 32;
6839
+ /**
6840
+ * Runs a release write that takes labels, in one transaction with the
6841
+ * counters it bumps. A pair that still needs its fill is filled, and the
6842
+ * write runs again; so is a pair whose catch-up made the write too large for
6843
+ * the store. A label another row holds, such as an index item a release
6844
+ * deleted by a server of an earlier release left on a key-value store, is
6845
+ * skipped: its counters move past it and the write runs again.
6846
+ */
6847
+ const writeWithLabels = async (db, write) => {
6848
+ const filled = /* @__PURE__ */ new Set();
6849
+ const fill = async (pairs) => {
6850
+ for (const pair of pairs) {
6851
+ filled.add(labelSequenceId(pair.channelId, pair.platform));
6852
+ await fillLabels(db, pair);
6853
+ }
6854
+ };
6855
+ for (let repairs = 0, races = 0;;) {
6856
+ const used = /* @__PURE__ */ new Map();
6857
+ const caughtUp = /* @__PURE__ */ new Map();
6858
+ try {
6859
+ return await db.transaction(async (tx) => {
6860
+ used.clear();
6861
+ caughtUp.clear();
6862
+ const labels = createLabelAllocator(tx, used, caughtUp);
6863
+ const result = await write(tx, labels);
6864
+ labels.flush();
6865
+ return result;
6866
+ });
6867
+ } catch (error) {
6868
+ const needs = error instanceof NeedsLabelFill ? [error] : error instanceof DatabaseConstraintError && error.reason === "too_large" ? [...caughtUp.values()] : [];
6869
+ if (needs.length > 0) {
6870
+ const fresh = needs.some(({ channelId, platform }) => !filled.has(labelSequenceId(channelId, platform)));
6871
+ if (fresh || repairs < REPAIRS) {
6872
+ if (!fresh) repairs += 1;
6873
+ await fill(needs);
6874
+ continue;
6875
+ }
6876
+ }
6877
+ if (error instanceof DatabaseConstraintError && error.reason === "unique" && error.model === "releases" && used.size > 0) {
6878
+ if (await db.transaction(async (tx) => {
6879
+ const moves = [];
6880
+ for (const [id, { channelId, read }] of used) {
6881
+ const counter = await tx.findOne("label_sequences", { id });
6882
+ if (counter !== null) {
6883
+ if (counter.last_label !== read) return false;
6884
+ moves.push(() => tx.update("label_sequences", counter, { last_label: read + 1 }));
6885
+ continue;
6886
+ }
6887
+ const channel = await tx.findOne("channels", { id: channelId });
6888
+ if (channel === null || (channel._refs_releases_channel_id ?? 0) > 0) return false;
6889
+ moves.push(() => tx.create("label_sequences", {
6890
+ id,
6891
+ last_label: read + 1,
6892
+ is_filled: true
6893
+ }));
6894
+ }
6895
+ for (const move of moves) move();
6896
+ return true;
6897
+ }) ? (repairs += 1) <= REPAIRS : (races += 1) <= RACES) continue;
6898
+ }
6899
+ throw error;
6900
+ }
6901
+ }
6902
+ };
6903
+ /**
6904
+ * Labels a scope's releases a server of an earlier release wrote after its
6905
+ * newest labeled one, oldest first, before the write takes its own label:
6906
+ * `latest` is the scope's newest release, so a labeled one costs no read.
6907
+ * Answers the labels it gave, by release ID.
6908
+ */
6909
+ const catchUpLabels = async (tx, labels, latest) => {
6910
+ const given = /* @__PURE__ */ new Map();
6911
+ if (latest === null || typeof latest.label === "number") return given;
6912
+ const unlabeled = [];
6913
+ let cursor;
6914
+ scan: do {
6915
+ const page = await tx.findMany("releases", {
6916
+ index: "byScope",
6917
+ where: { scope_key: latest.scope_key },
6918
+ order: "desc",
6919
+ limit: FILL_BATCH,
6920
+ ...cursor === void 0 ? {} : { cursor }
6921
+ });
6922
+ for (const row of page.rows) {
6923
+ if (typeof row.label === "number") break scan;
6924
+ unlabeled.push(row);
6925
+ }
6926
+ cursor = page.next;
6927
+ } while (cursor !== void 0);
6928
+ labels.caughtUp(latest.channel_id, latest.platform);
6929
+ for (const row of unlabeled.reverse()) {
6930
+ const { id, channel_id, platform } = toReleaseRow(row);
6931
+ const label = await labels.next(channel_id, platform);
6932
+ tx.update("releases", row, { label });
6933
+ given.set(id, label);
6934
+ }
6935
+ return given;
6936
+ };
6937
+ /**
6938
+ * The channels and platforms whose releases need labels: a scope whose
6939
+ * newest release has none, or a pair without a filled counter. Releases a
6940
+ * server of an earlier release wrote in a filled pair come after its
6941
+ * labeled ones in their scope, so the newest release of each scope tells.
6942
+ * Two reads per scope, one per pair.
6943
+ */
6944
+ const pendingLabelPairs = async (db) => {
6945
+ const pairs = /* @__PURE__ */ new Map();
6946
+ for (let last = "";;) {
6947
+ const { rows } = await db.findMany("releases", {
6948
+ index: "scopes",
6949
+ where: {},
6950
+ limit: 1,
6951
+ range: { gt: last }
6952
+ });
6953
+ if (rows[0] === void 0) break;
6954
+ last = rows[0].scope_key;
6955
+ const { rows: newest } = await db.findMany("releases", {
6956
+ index: "byScope",
6957
+ where: { scope_key: last },
6958
+ order: "desc",
6959
+ limit: 1
6960
+ });
6961
+ if (newest[0] === void 0) continue;
6962
+ const { channel_id: channelId, platform, label } = toReleaseRow(newest[0]);
6963
+ const id = labelSequenceId(channelId, platform);
6964
+ const pair = pairs.get(id) ?? {
6965
+ channelId,
6966
+ platform,
6967
+ pending: false
6968
+ };
6969
+ pair.pending ||= label === null;
6970
+ pairs.set(id, pair);
6971
+ }
6972
+ const pending = [];
6973
+ for (const [id, { channelId, platform, pending: unlabeled }] of pairs) {
6974
+ if (!unlabeled) {
6975
+ const counter = await db.findOne("label_sequences", { id });
6976
+ if (counter !== null && counter.is_filled) continue;
6977
+ }
6978
+ pending.push({
6979
+ channelId,
6980
+ platform
6981
+ });
6982
+ }
6983
+ return pending;
6984
+ };
6985
+ //#endregion
6471
6986
  //#region ../../packages/server/dist/core/writes.mjs
6472
6987
  const PAGE$2 = 500;
6473
6988
  /** Moves one bundle into or out of its platform's total and the overall total. */
@@ -6548,7 +7063,11 @@ const insertChannel = async (db, row) => {
6548
7063
  throw error;
6549
7064
  }
6550
7065
  };
6551
- /** Deletes a channel no release or native build uses: 1 read, 1 query, 1 write. */
7066
+ /**
7067
+ * Deletes a channel no release or native build uses, with its label
7068
+ * counters, so one created again with its name starts at 1: 3 reads,
7069
+ * 1 query, 1 write.
7070
+ */
6552
7071
  const deleteChannel = (db, id) => db.transaction(async (tx) => {
6553
7072
  const row = await tx.findOne("channels", { id });
6554
7073
  if (row === null) return {
@@ -6568,6 +7087,10 @@ const deleteChannel = (db, id) => db.transaction(async (tx) => {
6568
7087
  deleted: false,
6569
7088
  reason: "not_empty"
6570
7089
  };
7090
+ for (const platform of LABEL_PLATFORMS) {
7091
+ const counter = await tx.findOne("label_sequences", { id: labelSequenceId(id, platform) });
7092
+ if (counter !== null) await tx.delete("label_sequences", counter);
7093
+ }
6571
7094
  await tx.delete("channels", row);
6572
7095
  return { deleted: true };
6573
7096
  });
@@ -7104,15 +7627,15 @@ const enabledIn = (scopeKey, cursor) => ({
7104
7627
  });
7105
7628
  /** A scope's enabled releases, all of them, under the catalog's guard. */
7106
7629
  const enabledReleases = (tx, scopeKey) => drainReleases((cursor) => tx.findMany("releases", enabledIn(scopeKey, cursor)));
7107
- /** The scope's newest release id: `byScope` descending, limit 1. */
7108
- const latestReleaseId = async (tx, scopeKey) => {
7630
+ /** The scope's newest release: `byScope` descending, limit 1. */
7631
+ const latestRelease = async (tx, scopeKey) => {
7109
7632
  const { rows } = await tx.findMany("releases", {
7110
7633
  index: "byScope",
7111
7634
  where: { scope_key: scopeKey },
7112
7635
  order: "desc",
7113
7636
  limit: 1
7114
7637
  });
7115
- return rows[0]?.id ?? null;
7638
+ return rows[0] === void 0 ? null : toReleaseRow(rows[0]);
7116
7639
  };
7117
7640
  /** The scope's next catalog generation, compiled as `compilation`. */
7118
7641
  const nextCatalog = (scope, stored, compilation, updatedAtMs) => {
@@ -7170,15 +7693,28 @@ const readCatalog = async (tx, scopeKey) => {
7170
7693
  catalog: row === null ? null : toCatalogRow(row)
7171
7694
  };
7172
7695
  };
7696
+ /**
7697
+ * Refuses to rewrite a catalog a later release compiled: this release's
7698
+ * compiler would drop the fields that release added.
7699
+ */
7700
+ const refuseLaterCatalog = (scope, catalog) => {
7701
+ if (catalog !== null && readCompiledCatalogPayload(catalog.payload).fromLaterRelease) fail$1("CATALOG_FROM_LATER_RELEASE", `The ${scope.platform} release catalog of channel "${scope.channelName}" was written by a later Hot Updater.\nUpgrade hot-updater, then try again.`);
7702
+ };
7173
7703
  /** A scope with releases and no compiled catalog lost its history. */
7174
7704
  const assertHistory = (stored, hasReleases) => {
7175
7705
  if (stored.catalog === null && hasReleases) fail$1("CATALOG_IDENTITY_MISSING", "Catalog history is missing. Restore its catalog row from backup before rebuilding or deploying.");
7176
7706
  };
7177
- /** One release change and its scope's next catalog, inside `tx`. */
7178
- const changeRelease = async (tx, { scope, change, bundle, updatedAtMs }) => {
7707
+ /**
7708
+ * One release change and its scope's next catalog, inside `tx`. An insert
7709
+ * takes its channel and platform's next label from `labels`, after labeling
7710
+ * the releases a server of an earlier release wrote in the scope since its
7711
+ * last labeled one.
7712
+ */
7713
+ const changeRelease = async (tx, { scope, change, bundle, updatedAtMs }, labels) => {
7179
7714
  checkScope(scope);
7180
7715
  const stored = await readCatalog(tx, scope.scopeKey);
7181
- const enabled = await enabledReleases(tx, scope.scopeKey);
7716
+ refuseLaterCatalog(scope, stored.catalog);
7717
+ let enabled = await enabledReleases(tx, scope.scopeKey);
7182
7718
  if (bundle !== void 0) {
7183
7719
  insertBundle(tx, bundle.row);
7184
7720
  for (const patch of bundle.patches) tx.create("bundle_patches", patch);
@@ -7186,14 +7722,22 @@ const changeRelease = async (tx, { scope, change, bundle, updatedAtMs }) => {
7186
7722
  let before = null;
7187
7723
  let release;
7188
7724
  if (change.operation === "insert") {
7189
- const latest = await latestReleaseId(tx, scope.scopeKey);
7725
+ if (labels === void 0) throw new Error("A release insert takes its label from an allocator.");
7726
+ const newest = await latestRelease(tx, scope.scopeKey);
7727
+ const latest = newest?.id ?? null;
7190
7728
  assertHistory(stored, latest !== null);
7191
7729
  const floor = [latest, bundle && isUUIDv7(bundle.row.id) ? bundle.row.id : null].filter((id) => id !== null).sort().at(-1);
7192
7730
  const id = change.row.id ?? createUUIDv7After(floor ?? null);
7193
7731
  if (latest !== null && id <= latest) fail$1("NON_MONOTONIC_RELEASE_ID", `Release "${id}" must sort after "${latest}"`);
7732
+ const given = await catchUpLabels(tx, labels, newest);
7733
+ if (given.size > 0) enabled = enabled.map((row) => given.has(row.id) ? {
7734
+ ...row,
7735
+ label: given.get(row.id)
7736
+ } : row);
7194
7737
  release = {
7195
7738
  ...change.row,
7196
- id
7739
+ id,
7740
+ label: await labels.next(scope.channelId, scope.platform)
7197
7741
  };
7198
7742
  if (release.scope_key !== scope.scopeKey || release.channel_id !== scope.channelId || release.platform !== scope.platform || release.strategy !== scope.strategy || release.fingerprint_hash !== scope.fingerprintHash || release.revision !== 1) fail$1("INVALID_SCOPE", "Inserted Release does not match its catalog scope");
7199
7743
  tx.create("releases", release);
@@ -7206,8 +7750,9 @@ const changeRelease = async (tx, { scope, change, bundle, updatedAtMs }) => {
7206
7750
  await tx.delete("releases", row);
7207
7751
  release = null;
7208
7752
  } else {
7753
+ const { label: _label, ...update } = change.update;
7209
7754
  const set = {
7210
- ...change.update,
7755
+ ...update,
7211
7756
  revision: before.revision + 1
7212
7757
  };
7213
7758
  tx.update("releases", row, set);
@@ -7235,14 +7780,35 @@ const changeRelease = async (tx, { scope, change, bundle, updatedAtMs }) => {
7235
7780
  */
7236
7781
  const changeReleases = (db, inputs) => {
7237
7782
  if (new Set(inputs.map(({ scope }) => scope.scopeKey)).size !== inputs.length) fail$1("INVALID_SCOPE", "A batch cannot change one catalog scope twice");
7238
- return db.transaction(async (tx) => {
7783
+ return writeWithLabels(db, async (tx, labels) => {
7239
7784
  const results = [];
7240
- for (const input of inputs) results.push(await changeRelease(tx, input));
7785
+ for (const input of inputs) results.push(await changeRelease(tx, input, labels));
7241
7786
  return results;
7242
7787
  });
7243
7788
  };
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;
7789
+ /**
7790
+ * Whether `current` is what the scope's enabled releases compile to, in the
7791
+ * fields this release compiles: a later release's catalog may add others.
7792
+ */
7793
+ const isCurrent = (scope, current, compilation) => {
7794
+ if (current.strategy !== scope.strategy || current.channel_id !== scope.channelId || current.channel_key !== encodeChannelKey(scope.channelName) || current.platform !== scope.platform || current.fingerprint_hash !== scope.fingerprintHash) return false;
7795
+ if (current.catalog_hash === compilation.catalogHash) return true;
7796
+ const read = readCompiledCatalogPayload(current.payload);
7797
+ return read.fromLaterRelease && read.canonicalPayload === compilation.canonicalPayload;
7798
+ };
7799
+ /** A compiled payload with its descriptors' labels left out. */
7800
+ const withoutLabels = (payload) => {
7801
+ const parsed = JSON.parse(payload);
7802
+ return JSON.stringify({
7803
+ ...parsed,
7804
+ releaseDescriptors: (parsed.releaseDescriptors ?? []).map(({ label: _label, ...descriptor }) => descriptor)
7805
+ });
7806
+ };
7807
+ /**
7808
+ * Whether `projected` differs from `current` only by release labels, as a
7809
+ * catalog compiled before its releases had them does.
7810
+ */
7811
+ const differsInLabelsOnly = (current, projected) => current.payload !== projected.payload && current.strategy === projected.strategy && current.channel_id === projected.channel_id && current.channel_key === projected.channel_key && current.platform === projected.platform && current.fingerprint_hash === projected.fingerprint_hash && withoutLabels(current.payload) === withoutLabels(projected.payload);
7246
7812
  /** The scope a catalog row names. */
7247
7813
  const catalogRowScope = (row) => ({
7248
7814
  channelId: row.channel_id,
@@ -7268,18 +7834,20 @@ const preflightRebuild = async (db, scopeKey, updatedAtMs) => {
7268
7834
  const enabled = await drainReleases((cursor) => db.findMany("releases", enabledIn(scopeKey, cursor)));
7269
7835
  const compilation = await compileScope(scope, enabled);
7270
7836
  const changed = !isCurrent(scope, current, compilation);
7837
+ const projectedCatalog = changed ? nextCatalog(scope, { catalog: current }, compilation, updatedAtMs) : current;
7271
7838
  return {
7272
7839
  changed,
7840
+ labelsOnly: changed && differsInLabelsOnly(current, projectedCatalog),
7273
7841
  currentCatalog: current,
7274
7842
  diagnostics: compilation.diagnostics,
7275
- projectedCatalog: changed ? nextCatalog(scope, { catalog: current }, compilation, updatedAtMs) : current
7843
+ projectedCatalog
7276
7844
  };
7277
7845
  };
7278
7846
  /** Recompiles a scope's catalog from its enabled releases inside `tx`; an unchanged catalog is not rewritten. */
7279
7847
  const rebuildScope = async (tx, scope, updatedAtMs) => {
7280
7848
  checkScope(scope);
7281
7849
  const stored = await readCatalog(tx, scope.scopeKey);
7282
- assertHistory(stored, await latestReleaseId(tx, scope.scopeKey) !== null);
7850
+ assertHistory(stored, await latestRelease(tx, scope.scopeKey) !== null);
7283
7851
  const enabled = await enabledReleases(tx, scope.scopeKey);
7284
7852
  const compilation = await compileScope(scope, enabled);
7285
7853
  const current = stored.catalog;
@@ -7289,6 +7857,7 @@ const rebuildScope = async (tx, scope, updatedAtMs) => {
7289
7857
  changed: false,
7290
7858
  diagnostics: compilation.diagnostics
7291
7859
  };
7860
+ refuseLaterCatalog(scope, current);
7292
7861
  const written = await writeCatalog(tx, scope, stored, enabled, updatedAtMs);
7293
7862
  return {
7294
7863
  catalog: written.catalog,
@@ -7299,6 +7868,7 @@ const rebuildScope = async (tx, scope, updatedAtMs) => {
7299
7868
  };
7300
7869
  //#endregion
7301
7870
  //#region ../../packages/server/dist/core/operations.mjs
7871
+ const CATALOG_PAGE = 100;
7302
7872
  /** Carries a preflight's result out of the transaction it stops, so nothing is written. */
7303
7873
  var Preflight = class extends Error {
7304
7874
  result;
@@ -7530,7 +8100,7 @@ const createCoreOperations = (db, { now = Date.now } = {}) => {
7530
8100
  if (targetChannel.length === 0) throw new ReleaseManagementError("TARGET_RELEASE_INVALID", "Promotion requires a target channel.");
7531
8101
  const channel = await ensureChannel(targetChannel);
7532
8102
  const updatedAtMs = now();
7533
- return db.transaction(async (tx) => {
8103
+ return writeWithLabels(db, async (tx, labels) => {
7534
8104
  const { release: source, scope: sourceScope } = await loadTarget(tx, input);
7535
8105
  checkSource(source);
7536
8106
  const targetScope = scopeOf$1(channel, source.platform, source.fingerprint_hash);
@@ -7558,12 +8128,13 @@ const createCoreOperations = (db, { now = Date.now } = {}) => {
7558
8128
  },
7559
8129
  updatedAtMs
7560
8130
  }) : null;
8131
+ const { label: _label, ...copied } = source;
7561
8132
  const target = await changeRelease(tx, {
7562
8133
  scope: targetScope,
7563
8134
  change: {
7564
8135
  operation: "insert",
7565
8136
  row: {
7566
- ...source,
8137
+ ...copied,
7567
8138
  id: createUUIDv7After(floor ?? null, updatedAtMs),
7568
8139
  revision: 1,
7569
8140
  scope_key: targetScope.scopeKey,
@@ -7578,7 +8149,7 @@ const createCoreOperations = (db, { now = Date.now } = {}) => {
7578
8149
  }
7579
8150
  },
7580
8151
  updatedAtMs
7581
- });
8152
+ }, labels);
7582
8153
  return {
7583
8154
  source: moved === null ? null : mutationResult(moved),
7584
8155
  target: mutationResult(target)
@@ -7596,6 +8167,38 @@ const createCoreOperations = (db, { now = Date.now } = {}) => {
7596
8167
  });
7597
8168
  },
7598
8169
  preflightReleaseCatalogRebuild: (scopeKey) => preflightRebuild(db, scopeKey, now()),
8170
+ fillReleaseLabels: async ({ dryRun = false, catalogs = true } = {}) => {
8171
+ let releases = 0;
8172
+ const pairs = await pendingLabelPairs(db);
8173
+ if (dryRun && pairs[0] !== void 0) await probeLabelSchema(db, pairs[0]);
8174
+ for (const pair of pairs) releases += await fillLabels(db, pair, { dryRun });
8175
+ let rebuilt = 0;
8176
+ if (catalogs) {
8177
+ let cursor;
8178
+ do {
8179
+ const page = await db.findMany("release_catalogs", {
8180
+ index: "all",
8181
+ where: {},
8182
+ limit: CATALOG_PAGE,
8183
+ ...cursor === void 0 ? {} : { cursor }
8184
+ });
8185
+ for (const row of page.rows) {
8186
+ if (row.is_tombstone) continue;
8187
+ const preflight = await preflightRebuild(db, row.scope_key, now()).catch(() => null);
8188
+ if (preflight === null || !preflight.labelsOnly) continue;
8189
+ rebuilt += 1;
8190
+ if (dryRun) continue;
8191
+ const updatedAtMs = now();
8192
+ await db.transaction((tx) => rebuildScope(tx, catalogRowScope(toCatalogRow(row)), updatedAtMs));
8193
+ }
8194
+ cursor = page.next;
8195
+ } while (cursor !== void 0);
8196
+ }
8197
+ return {
8198
+ releases,
8199
+ catalogs: rebuilt
8200
+ };
8201
+ },
7599
8202
  ensureChannel,
7600
8203
  deleteChannel: (id) => deleteChannel(db, id),
7601
8204
  updateBundle: (id, update) => db.transaction(async (tx) => {
@@ -8166,6 +8769,30 @@ const createAdminRouteHandlers = () => ({
8166
8769
  return row === null ? notFound() : json$2({ data: row });
8167
8770
  }),
8168
8771
  rebuildReleaseCatalog: onCore(async (core, _request, params) => json$2({ data: await core.rebuildReleaseCatalog(scopeKeyOf(params)) })),
8772
+ /**
8773
+ * The release a label names, or `null`: never 404, which tells a client
8774
+ * the server has no such route.
8775
+ */
8776
+ getReleaseByLabel: onCore(async (core, request) => {
8777
+ const url = new URL(request.url);
8778
+ const channel = url.searchParams.get("channel");
8779
+ const platform = platformOf(url);
8780
+ const label = Number(url.searchParams.get("label"));
8781
+ if (channel === null || channel.length === 0 || platform === void 0 || !Number.isSafeInteger(label) || label < 1) throw new HandlerBadRequestError("A release label lookup takes channel, platform, and a label of 1 or more.");
8782
+ return json$2({ data: await core.getReleaseByLabel({
8783
+ channel,
8784
+ platform,
8785
+ label
8786
+ }) });
8787
+ }),
8788
+ fillReleaseLabels: onCore(async (core, request) => {
8789
+ const body = await request.json().catch(() => ({}));
8790
+ const input = body !== null && typeof body === "object" ? body : {};
8791
+ return json$2({ data: await core.fillReleaseLabels({
8792
+ dryRun: input.dryRun === true,
8793
+ catalogs: input.catalogs !== false
8794
+ }) });
8795
+ }),
8169
8796
  updateBundle: onCore(async (core, request, params) => {
8170
8797
  const bundleId = requireRouteParam(params, "id");
8171
8798
  const update = bundleUpdateOf(await request.json(), bundleId);
@@ -8393,6 +9020,16 @@ const ADMIN_ROUTES = [
8393
9020
  path: "/release-scopes",
8394
9021
  handler: "listReleaseScopeKeys"
8395
9022
  },
9023
+ {
9024
+ method: "GET",
9025
+ path: "/release-labels",
9026
+ handler: "getReleaseByLabel"
9027
+ },
9028
+ {
9029
+ method: "POST",
9030
+ path: "/release-labels/fill",
9031
+ handler: "fillReleaseLabels"
9032
+ },
8396
9033
  {
8397
9034
  method: "POST",
8398
9035
  path: "/release-catalogs/:scopeKey/rebuild",
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.50",
4
+ "version": "1.2.0-rc.52",
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.50",
49
- "@hot-updater/mock": "1.2.0-rc.50",
50
- "@hot-updater/test-utils": "1.2.0-rc.50"
48
+ "@hot-updater/protocol": "1.2.0-rc.52",
49
+ "@hot-updater/test-utils": "1.2.0-rc.52",
50
+ "@hot-updater/mock": "1.2.0-rc.52"
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/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"
67
+ "@hot-updater/cli-tools": "1.2.0-rc.52",
68
+ "@hot-updater/plugin-core": "1.2.0-rc.52",
69
+ "@hot-updater/server": "1.2.0-rc.52",
70
+ "@hot-updater/storage-s3": "1.2.0-rc.52"
71
71
  },
72
72
  "scripts": {
73
73
  "build": "tsdown",