@hot-updater/server 1.2.0-rc.50 → 1.2.0-rc.51

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.
@@ -1,10 +1,12 @@
1
1
  const require_reads = require("./reads.cjs");
2
+ const require_labels = require("./labels.cjs");
2
3
  const require_writes = require("./writes.cjs");
3
4
  const require_nativeBuilds = require("./nativeBuilds.cjs");
4
5
  const require_releases = require("./releases.cjs");
5
6
  let _hot_updater_plugin_core = require("@hot-updater/plugin-core");
6
7
  let _hot_updater_protocol = require("@hot-updater/protocol");
7
8
  //#region src/core/operations.ts
9
+ const CATALOG_PAGE = 100;
8
10
  /** Carries a preflight's result out of the transaction it stops, so nothing is written. */
9
11
  var Preflight = class extends Error {
10
12
  result;
@@ -236,7 +238,7 @@ const createCoreOperations = (db, { now = Date.now } = {}) => {
236
238
  if (targetChannel.length === 0) throw new _hot_updater_plugin_core.ReleaseManagementError("TARGET_RELEASE_INVALID", "Promotion requires a target channel.");
237
239
  const channel = await ensureChannel(targetChannel);
238
240
  const updatedAtMs = now();
239
- return db.transaction(async (tx) => {
241
+ return require_labels.writeWithLabels(db, async (tx, labels) => {
240
242
  const { release: source, scope: sourceScope } = await loadTarget(tx, input);
241
243
  checkSource(source);
242
244
  const targetScope = scopeOf(channel, source.platform, source.fingerprint_hash);
@@ -264,12 +266,13 @@ const createCoreOperations = (db, { now = Date.now } = {}) => {
264
266
  },
265
267
  updatedAtMs
266
268
  }) : null;
269
+ const { label: _label, ...copied } = source;
267
270
  const target = await require_releases.changeRelease(tx, {
268
271
  scope: targetScope,
269
272
  change: {
270
273
  operation: "insert",
271
274
  row: {
272
- ...source,
275
+ ...copied,
273
276
  id: (0, _hot_updater_plugin_core.createUUIDv7After)(floor ?? null, updatedAtMs),
274
277
  revision: 1,
275
278
  scope_key: targetScope.scopeKey,
@@ -284,7 +287,7 @@ const createCoreOperations = (db, { now = Date.now } = {}) => {
284
287
  }
285
288
  },
286
289
  updatedAtMs
287
- });
290
+ }, labels);
288
291
  return {
289
292
  source: moved === null ? null : mutationResult(moved),
290
293
  target: mutationResult(target)
@@ -302,6 +305,38 @@ const createCoreOperations = (db, { now = Date.now } = {}) => {
302
305
  });
303
306
  },
304
307
  preflightReleaseCatalogRebuild: (scopeKey) => require_releases.preflightRebuild(db, scopeKey, now()),
308
+ fillReleaseLabels: async ({ dryRun = false, catalogs = true } = {}) => {
309
+ let releases = 0;
310
+ const pairs = await require_labels.pendingLabelPairs(db);
311
+ if (dryRun && pairs[0] !== void 0) await require_labels.probeLabelSchema(db, pairs[0]);
312
+ for (const pair of pairs) releases += await require_labels.fillLabels(db, pair, { dryRun });
313
+ let rebuilt = 0;
314
+ if (catalogs) {
315
+ let cursor;
316
+ do {
317
+ const page = await db.findMany("release_catalogs", {
318
+ index: "all",
319
+ where: {},
320
+ limit: CATALOG_PAGE,
321
+ ...cursor === void 0 ? {} : { cursor }
322
+ });
323
+ for (const row of page.rows) {
324
+ if (row.is_tombstone) continue;
325
+ const preflight = await require_releases.preflightRebuild(db, row.scope_key, now()).catch(() => null);
326
+ if (preflight === null || !preflight.labelsOnly) continue;
327
+ rebuilt += 1;
328
+ if (dryRun) continue;
329
+ const updatedAtMs = now();
330
+ await db.transaction((tx) => require_releases.rebuildScope(tx, require_releases.catalogRowScope(require_reads.toCatalogRow(row)), updatedAtMs));
331
+ }
332
+ cursor = page.next;
333
+ } while (cursor !== void 0);
334
+ }
335
+ return {
336
+ releases,
337
+ catalogs: rebuilt
338
+ };
339
+ },
305
340
  ensureChannel,
306
341
  deleteChannel: (id) => require_writes.deleteChannel(db, id),
307
342
  updateBundle: (id, update) => db.transaction(async (tx) => {
@@ -1,10 +1,12 @@
1
1
  import { toBundleRow, toCatalogRow, toReleaseRow } from "./reads.mjs";
2
+ import { fillLabels, pendingLabelPairs, probeLabelSchema, writeWithLabels } from "./labels.mjs";
2
3
  import { deleteBundle, deleteChannel, insertChannel, replaceBundlePatches, updateBundle } from "./writes.mjs";
3
4
  import { isBuiltInBundle, refuseSandboxPatchBase } from "./nativeBuilds.mjs";
4
5
  import { catalogRowScope, changeRelease, changeReleases, preflightRebuild, readCatalog, rebuildScope } from "./releases.mjs";
5
6
  import { DatabaseBundleNotFoundError, DatabaseConstraintError, DatabaseRowReferencedError, ReleaseCatalogMutationError, ReleaseManagementError, bundleToPatchRows, bundleToRow, createUUIDv7After, isUUIDv7, rowToBundle } from "@hot-updater/plugin-core";
6
7
  import { createReleaseCatalogScopeKey, decodeChannelKey, encodeChannelKey } from "@hot-updater/protocol";
7
8
  //#region src/core/operations.ts
9
+ const CATALOG_PAGE = 100;
8
10
  /** Carries a preflight's result out of the transaction it stops, so nothing is written. */
9
11
  var Preflight = class extends Error {
10
12
  result;
@@ -236,7 +238,7 @@ const createCoreOperations = (db, { now = Date.now } = {}) => {
236
238
  if (targetChannel.length === 0) throw new ReleaseManagementError("TARGET_RELEASE_INVALID", "Promotion requires a target channel.");
237
239
  const channel = await ensureChannel(targetChannel);
238
240
  const updatedAtMs = now();
239
- return db.transaction(async (tx) => {
241
+ return writeWithLabels(db, async (tx, labels) => {
240
242
  const { release: source, scope: sourceScope } = await loadTarget(tx, input);
241
243
  checkSource(source);
242
244
  const targetScope = scopeOf(channel, source.platform, source.fingerprint_hash);
@@ -264,12 +266,13 @@ const createCoreOperations = (db, { now = Date.now } = {}) => {
264
266
  },
265
267
  updatedAtMs
266
268
  }) : null;
269
+ const { label: _label, ...copied } = source;
267
270
  const target = await changeRelease(tx, {
268
271
  scope: targetScope,
269
272
  change: {
270
273
  operation: "insert",
271
274
  row: {
272
- ...source,
275
+ ...copied,
273
276
  id: createUUIDv7After(floor ?? null, updatedAtMs),
274
277
  revision: 1,
275
278
  scope_key: targetScope.scopeKey,
@@ -284,7 +287,7 @@ const createCoreOperations = (db, { now = Date.now } = {}) => {
284
287
  }
285
288
  },
286
289
  updatedAtMs
287
- });
290
+ }, labels);
288
291
  return {
289
292
  source: moved === null ? null : mutationResult(moved),
290
293
  target: mutationResult(target)
@@ -302,6 +305,38 @@ const createCoreOperations = (db, { now = Date.now } = {}) => {
302
305
  });
303
306
  },
304
307
  preflightReleaseCatalogRebuild: (scopeKey) => preflightRebuild(db, scopeKey, now()),
308
+ fillReleaseLabels: async ({ dryRun = false, catalogs = true } = {}) => {
309
+ let releases = 0;
310
+ const pairs = await pendingLabelPairs(db);
311
+ if (dryRun && pairs[0] !== void 0) await probeLabelSchema(db, pairs[0]);
312
+ for (const pair of pairs) releases += await fillLabels(db, pair, { dryRun });
313
+ let rebuilt = 0;
314
+ if (catalogs) {
315
+ let cursor;
316
+ do {
317
+ const page = await db.findMany("release_catalogs", {
318
+ index: "all",
319
+ where: {},
320
+ limit: CATALOG_PAGE,
321
+ ...cursor === void 0 ? {} : { cursor }
322
+ });
323
+ for (const row of page.rows) {
324
+ if (row.is_tombstone) continue;
325
+ const preflight = await preflightRebuild(db, row.scope_key, now()).catch(() => null);
326
+ if (preflight === null || !preflight.labelsOnly) continue;
327
+ rebuilt += 1;
328
+ if (dryRun) continue;
329
+ const updatedAtMs = now();
330
+ await db.transaction((tx) => rebuildScope(tx, catalogRowScope(toCatalogRow(row)), updatedAtMs));
331
+ }
332
+ cursor = page.next;
333
+ } while (cursor !== void 0);
334
+ }
335
+ return {
336
+ releases,
337
+ catalogs: rebuilt
338
+ };
339
+ },
305
340
  ensureChannel,
306
341
  deleteChannel: (id) => deleteChannel(db, id),
307
342
  updateBundle: (id, update) => db.transaction(async (tx) => {
@@ -25,7 +25,7 @@ const toPatchRow = pick([
25
25
  "byte_size",
26
26
  "order_index"
27
27
  ]);
28
- const toReleaseRow = pick([
28
+ const pickReleaseRow = pick([
29
29
  "id",
30
30
  "revision",
31
31
  "scope_key",
@@ -46,6 +46,13 @@ const toReleaseRow = pick([
46
46
  "created_at_ms",
47
47
  "updated_at_ms"
48
48
  ]);
49
+ /** A release row; `label` null where the store holds none, as before the column. */
50
+ const toReleaseRow = (row) => {
51
+ return {
52
+ ...pickReleaseRow(row),
53
+ label: typeof row.label === "number" ? row.label : null
54
+ };
55
+ };
49
56
  const toCatalogRow = pick([
50
57
  "scope_key",
51
58
  "catalog_id",
@@ -204,6 +211,23 @@ const createCoreReads = (db, storage) => {
204
211
  const row = await db.findOne("releases", { id });
205
212
  return row === null ? null : toReleaseRow(row);
206
213
  },
214
+ /**
215
+ * The release a label names: its unique index, then the row itself,
216
+ * since a key-value store keeps an index copy a server of an earlier
217
+ * release may have left behind when it changed or deleted the row.
218
+ */
219
+ async getReleaseByLabel({ channel, platform, label }) {
220
+ const found = await db.findOne("releases", {
221
+ channel_id: `channel:${(0, _hot_updater_protocol.encodeChannelKey)(channel)}`,
222
+ platform,
223
+ label
224
+ });
225
+ if (found === null) return null;
226
+ const row = await db.findOne("releases", { id: found.id });
227
+ if (row === null) return null;
228
+ const release = toReleaseRow(row);
229
+ return release.label === label && release.platform === platform ? release : null;
230
+ },
207
231
  /** One page of releases through the index its filter names. */
208
232
  async listReleases(input) {
209
233
  const { filter } = input;
@@ -2,7 +2,7 @@ import { projectReleaseCatalogRow, releaseCatalogScopeKeyOf } from "../db/releas
2
2
  import { resolveManifestArtifactFiles, resolveManifestArtifacts, resolveManifestArtifactsV2 } from "../db/updateArtifacts.mjs";
3
3
  import { baseBundleIdsOf } from "./baseCandidates.mjs";
4
4
  import { parseBaseCandidateKey, rowToBundle } from "@hot-updater/plugin-core";
5
- import { ARTIFACT_FILES_PROTOCOL_VERSION, ARTIFACT_PROTOCOL_VERSION, NIL_UUID } from "@hot-updater/protocol";
5
+ import { ARTIFACT_FILES_PROTOCOL_VERSION, ARTIFACT_PROTOCOL_VERSION, NIL_UUID, encodeChannelKey } from "@hot-updater/protocol";
6
6
  //#region src/core/reads.ts
7
7
  const PAGE = 500;
8
8
  const pick = (fields) => (row) => Object.fromEntries(fields.map((field) => [field, row[field]]));
@@ -25,7 +25,7 @@ const toPatchRow = pick([
25
25
  "byte_size",
26
26
  "order_index"
27
27
  ]);
28
- const toReleaseRow = pick([
28
+ const pickReleaseRow = pick([
29
29
  "id",
30
30
  "revision",
31
31
  "scope_key",
@@ -46,6 +46,13 @@ const toReleaseRow = pick([
46
46
  "created_at_ms",
47
47
  "updated_at_ms"
48
48
  ]);
49
+ /** A release row; `label` null where the store holds none, as before the column. */
50
+ const toReleaseRow = (row) => {
51
+ return {
52
+ ...pickReleaseRow(row),
53
+ label: typeof row.label === "number" ? row.label : null
54
+ };
55
+ };
49
56
  const toCatalogRow = pick([
50
57
  "scope_key",
51
58
  "catalog_id",
@@ -204,6 +211,23 @@ const createCoreReads = (db, storage) => {
204
211
  const row = await db.findOne("releases", { id });
205
212
  return row === null ? null : toReleaseRow(row);
206
213
  },
214
+ /**
215
+ * The release a label names: its unique index, then the row itself,
216
+ * since a key-value store keeps an index copy a server of an earlier
217
+ * release may have left behind when it changed or deleted the row.
218
+ */
219
+ async getReleaseByLabel({ channel, platform, label }) {
220
+ const found = await db.findOne("releases", {
221
+ channel_id: `channel:${encodeChannelKey(channel)}`,
222
+ platform,
223
+ label
224
+ });
225
+ if (found === null) return null;
226
+ const row = await db.findOne("releases", { id: found.id });
227
+ if (row === null) return null;
228
+ const release = toReleaseRow(row);
229
+ return release.label === label && release.platform === platform ? release : null;
230
+ },
207
231
  /** One page of releases through the index its filter names. */
208
232
  async listReleases(input) {
209
233
  const { filter } = input;
@@ -1,4 +1,5 @@
1
1
  const require_reads = require("./reads.cjs");
2
+ const require_labels = require("./labels.cjs");
2
3
  const require_writes = require("./writes.cjs");
3
4
  let _hot_updater_plugin_core = require("@hot-updater/plugin-core");
4
5
  let _hot_updater_protocol = require("@hot-updater/protocol");
@@ -43,15 +44,15 @@ const enabledIn = (scopeKey, cursor) => ({
43
44
  });
44
45
  /** A scope's enabled releases, all of them, under the catalog's guard. */
45
46
  const enabledReleases = (tx, scopeKey) => drainReleases((cursor) => tx.findMany("releases", enabledIn(scopeKey, cursor)));
46
- /** The scope's newest release id: `byScope` descending, limit 1. */
47
- const latestReleaseId = async (tx, scopeKey) => {
47
+ /** The scope's newest release: `byScope` descending, limit 1. */
48
+ const latestRelease = async (tx, scopeKey) => {
48
49
  const { rows } = await tx.findMany("releases", {
49
50
  index: "byScope",
50
51
  where: { scope_key: scopeKey },
51
52
  order: "desc",
52
53
  limit: 1
53
54
  });
54
- return rows[0]?.id ?? null;
55
+ return rows[0] === void 0 ? null : require_reads.toReleaseRow(rows[0]);
55
56
  };
56
57
  /** The scope's next catalog generation, compiled as `compilation`. */
57
58
  const nextCatalog = (scope, stored, compilation, updatedAtMs) => {
@@ -113,11 +114,16 @@ const readCatalog = async (tx, scopeKey) => {
113
114
  const assertHistory = (stored, hasReleases) => {
114
115
  if (stored.catalog === null && hasReleases) fail("CATALOG_IDENTITY_MISSING", "Catalog history is missing. Restore its catalog row from backup before rebuilding or deploying.");
115
116
  };
116
- /** One release change and its scope's next catalog, inside `tx`. */
117
- const changeRelease = async (tx, { scope, change, bundle, updatedAtMs }) => {
117
+ /**
118
+ * One release change and its scope's next catalog, inside `tx`. An insert
119
+ * takes its channel and platform's next label from `labels`, after labeling
120
+ * the releases a server of an earlier release wrote in the scope since its
121
+ * last labeled one.
122
+ */
123
+ const changeRelease = async (tx, { scope, change, bundle, updatedAtMs }, labels) => {
118
124
  checkScope(scope);
119
125
  const stored = await readCatalog(tx, scope.scopeKey);
120
- const enabled = await enabledReleases(tx, scope.scopeKey);
126
+ let enabled = await enabledReleases(tx, scope.scopeKey);
121
127
  if (bundle !== void 0) {
122
128
  require_writes.insertBundle(tx, bundle.row);
123
129
  for (const patch of bundle.patches) tx.create("bundle_patches", patch);
@@ -125,14 +131,22 @@ const changeRelease = async (tx, { scope, change, bundle, updatedAtMs }) => {
125
131
  let before = null;
126
132
  let release;
127
133
  if (change.operation === "insert") {
128
- const latest = await latestReleaseId(tx, scope.scopeKey);
134
+ if (labels === void 0) throw new Error("A release insert takes its label from an allocator.");
135
+ const newest = await latestRelease(tx, scope.scopeKey);
136
+ const latest = newest?.id ?? null;
129
137
  assertHistory(stored, latest !== null);
130
138
  const floor = [latest, bundle && (0, _hot_updater_plugin_core.isUUIDv7)(bundle.row.id) ? bundle.row.id : null].filter((id) => id !== null).sort().at(-1);
131
139
  const id = change.row.id ?? (0, _hot_updater_plugin_core.createUUIDv7After)(floor ?? null);
132
140
  if (latest !== null && id <= latest) fail("NON_MONOTONIC_RELEASE_ID", `Release "${id}" must sort after "${latest}"`);
141
+ const given = await require_labels.catchUpLabels(tx, labels, newest);
142
+ if (given.size > 0) enabled = enabled.map((row) => given.has(row.id) ? {
143
+ ...row,
144
+ label: given.get(row.id)
145
+ } : row);
133
146
  release = {
134
147
  ...change.row,
135
- id
148
+ id,
149
+ label: await labels.next(scope.channelId, scope.platform)
136
150
  };
137
151
  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("INVALID_SCOPE", "Inserted Release does not match its catalog scope");
138
152
  tx.create("releases", release);
@@ -145,8 +159,9 @@ const changeRelease = async (tx, { scope, change, bundle, updatedAtMs }) => {
145
159
  await tx.delete("releases", row);
146
160
  release = null;
147
161
  } else {
162
+ const { label: _label, ...update } = change.update;
148
163
  const set = {
149
- ...change.update,
164
+ ...update,
150
165
  revision: before.revision + 1
151
166
  };
152
167
  tx.update("releases", row, set);
@@ -174,14 +189,27 @@ const changeRelease = async (tx, { scope, change, bundle, updatedAtMs }) => {
174
189
  */
175
190
  const changeReleases = (db, inputs) => {
176
191
  if (new Set(inputs.map(({ scope }) => scope.scopeKey)).size !== inputs.length) fail("INVALID_SCOPE", "A batch cannot change one catalog scope twice");
177
- return db.transaction(async (tx) => {
192
+ return require_labels.writeWithLabels(db, async (tx, labels) => {
178
193
  const results = [];
179
- for (const input of inputs) results.push(await changeRelease(tx, input));
194
+ for (const input of inputs) results.push(await changeRelease(tx, input, labels));
180
195
  return results;
181
196
  });
182
197
  };
183
198
  /** Whether `current` is what the scope's enabled releases compile to. */
184
199
  const isCurrent = (scope, current, compilation) => current.strategy === scope.strategy && current.channel_id === scope.channelId && current.channel_key === (0, _hot_updater_protocol.encodeChannelKey)(scope.channelName) && current.platform === scope.platform && current.fingerprint_hash === scope.fingerprintHash && current.catalog_hash === compilation.catalogHash;
200
+ /** A compiled payload with its descriptors' labels left out. */
201
+ const withoutLabels = (payload) => {
202
+ const parsed = JSON.parse(payload);
203
+ return JSON.stringify({
204
+ ...parsed,
205
+ releaseDescriptors: (parsed.releaseDescriptors ?? []).map(({ label: _label, ...descriptor }) => descriptor)
206
+ });
207
+ };
208
+ /**
209
+ * Whether `projected` differs from `current` only by release labels, as a
210
+ * catalog compiled before its releases had them does.
211
+ */
212
+ 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);
185
213
  /** The scope a catalog row names. */
186
214
  const catalogRowScope = (row) => ({
187
215
  channelId: row.channel_id,
@@ -207,18 +235,20 @@ const preflightRebuild = async (db, scopeKey, updatedAtMs) => {
207
235
  const enabled = await drainReleases((cursor) => db.findMany("releases", enabledIn(scopeKey, cursor)));
208
236
  const compilation = await compileScope(scope, enabled);
209
237
  const changed = !isCurrent(scope, current, compilation);
238
+ const projectedCatalog = changed ? nextCatalog(scope, { catalog: current }, compilation, updatedAtMs) : current;
210
239
  return {
211
240
  changed,
241
+ labelsOnly: changed && differsInLabelsOnly(current, projectedCatalog),
212
242
  currentCatalog: current,
213
243
  diagnostics: compilation.diagnostics,
214
- projectedCatalog: changed ? nextCatalog(scope, { catalog: current }, compilation, updatedAtMs) : current
244
+ projectedCatalog
215
245
  };
216
246
  };
217
247
  /** Recompiles a scope's catalog from its enabled releases inside `tx`; an unchanged catalog is not rewritten. */
218
248
  const rebuildScope = async (tx, scope, updatedAtMs) => {
219
249
  checkScope(scope);
220
250
  const stored = await readCatalog(tx, scope.scopeKey);
221
- assertHistory(stored, await latestReleaseId(tx, scope.scopeKey) !== null);
251
+ assertHistory(stored, await latestRelease(tx, scope.scopeKey) !== null);
222
252
  const enabled = await enabledReleases(tx, scope.scopeKey);
223
253
  const compilation = await compileScope(scope, enabled);
224
254
  const current = stored.catalog;
@@ -240,6 +270,7 @@ const rebuildScope = async (tx, scope, updatedAtMs) => {
240
270
  exports.catalogRowScope = catalogRowScope;
241
271
  exports.changeRelease = changeRelease;
242
272
  exports.changeReleases = changeReleases;
273
+ exports.differsInLabelsOnly = differsInLabelsOnly;
243
274
  exports.preflightRebuild = preflightRebuild;
244
275
  exports.readCatalog = readCatalog;
245
276
  exports.rebuildScope = rebuildScope;
@@ -1,4 +1,5 @@
1
1
  import { toCatalogRow, toReleaseRow } from "./reads.mjs";
2
+ import { catchUpLabels, writeWithLabels } from "./labels.mjs";
2
3
  import { insertBundle } from "./writes.mjs";
3
4
  import { ReleaseCatalogCompilationError, ReleaseCatalogMutationError, compileReleaseCatalog, createUUIDv7, createUUIDv7After, isUUIDv7, releaseRowToRelease } from "@hot-updater/plugin-core";
4
5
  import { MAX_COMPILED_CATALOG_BYTES, createReleaseCatalogScopeKey, decodeChannelKey, encodeChannelKey } from "@hot-updater/protocol";
@@ -43,15 +44,15 @@ const enabledIn = (scopeKey, cursor) => ({
43
44
  });
44
45
  /** A scope's enabled releases, all of them, under the catalog's guard. */
45
46
  const enabledReleases = (tx, scopeKey) => drainReleases((cursor) => tx.findMany("releases", enabledIn(scopeKey, cursor)));
46
- /** The scope's newest release id: `byScope` descending, limit 1. */
47
- const latestReleaseId = async (tx, scopeKey) => {
47
+ /** The scope's newest release: `byScope` descending, limit 1. */
48
+ const latestRelease = async (tx, scopeKey) => {
48
49
  const { rows } = await tx.findMany("releases", {
49
50
  index: "byScope",
50
51
  where: { scope_key: scopeKey },
51
52
  order: "desc",
52
53
  limit: 1
53
54
  });
54
- return rows[0]?.id ?? null;
55
+ return rows[0] === void 0 ? null : toReleaseRow(rows[0]);
55
56
  };
56
57
  /** The scope's next catalog generation, compiled as `compilation`. */
57
58
  const nextCatalog = (scope, stored, compilation, updatedAtMs) => {
@@ -113,11 +114,16 @@ const readCatalog = async (tx, scopeKey) => {
113
114
  const assertHistory = (stored, hasReleases) => {
114
115
  if (stored.catalog === null && hasReleases) fail("CATALOG_IDENTITY_MISSING", "Catalog history is missing. Restore its catalog row from backup before rebuilding or deploying.");
115
116
  };
116
- /** One release change and its scope's next catalog, inside `tx`. */
117
- const changeRelease = async (tx, { scope, change, bundle, updatedAtMs }) => {
117
+ /**
118
+ * One release change and its scope's next catalog, inside `tx`. An insert
119
+ * takes its channel and platform's next label from `labels`, after labeling
120
+ * the releases a server of an earlier release wrote in the scope since its
121
+ * last labeled one.
122
+ */
123
+ const changeRelease = async (tx, { scope, change, bundle, updatedAtMs }, labels) => {
118
124
  checkScope(scope);
119
125
  const stored = await readCatalog(tx, scope.scopeKey);
120
- const enabled = await enabledReleases(tx, scope.scopeKey);
126
+ let enabled = await enabledReleases(tx, scope.scopeKey);
121
127
  if (bundle !== void 0) {
122
128
  insertBundle(tx, bundle.row);
123
129
  for (const patch of bundle.patches) tx.create("bundle_patches", patch);
@@ -125,14 +131,22 @@ const changeRelease = async (tx, { scope, change, bundle, updatedAtMs }) => {
125
131
  let before = null;
126
132
  let release;
127
133
  if (change.operation === "insert") {
128
- const latest = await latestReleaseId(tx, scope.scopeKey);
134
+ if (labels === void 0) throw new Error("A release insert takes its label from an allocator.");
135
+ const newest = await latestRelease(tx, scope.scopeKey);
136
+ const latest = newest?.id ?? null;
129
137
  assertHistory(stored, latest !== null);
130
138
  const floor = [latest, bundle && isUUIDv7(bundle.row.id) ? bundle.row.id : null].filter((id) => id !== null).sort().at(-1);
131
139
  const id = change.row.id ?? createUUIDv7After(floor ?? null);
132
140
  if (latest !== null && id <= latest) fail("NON_MONOTONIC_RELEASE_ID", `Release "${id}" must sort after "${latest}"`);
141
+ const given = await catchUpLabels(tx, labels, newest);
142
+ if (given.size > 0) enabled = enabled.map((row) => given.has(row.id) ? {
143
+ ...row,
144
+ label: given.get(row.id)
145
+ } : row);
133
146
  release = {
134
147
  ...change.row,
135
- id
148
+ id,
149
+ label: await labels.next(scope.channelId, scope.platform)
136
150
  };
137
151
  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("INVALID_SCOPE", "Inserted Release does not match its catalog scope");
138
152
  tx.create("releases", release);
@@ -145,8 +159,9 @@ const changeRelease = async (tx, { scope, change, bundle, updatedAtMs }) => {
145
159
  await tx.delete("releases", row);
146
160
  release = null;
147
161
  } else {
162
+ const { label: _label, ...update } = change.update;
148
163
  const set = {
149
- ...change.update,
164
+ ...update,
150
165
  revision: before.revision + 1
151
166
  };
152
167
  tx.update("releases", row, set);
@@ -174,14 +189,27 @@ const changeRelease = async (tx, { scope, change, bundle, updatedAtMs }) => {
174
189
  */
175
190
  const changeReleases = (db, inputs) => {
176
191
  if (new Set(inputs.map(({ scope }) => scope.scopeKey)).size !== inputs.length) fail("INVALID_SCOPE", "A batch cannot change one catalog scope twice");
177
- return db.transaction(async (tx) => {
192
+ return writeWithLabels(db, async (tx, labels) => {
178
193
  const results = [];
179
- for (const input of inputs) results.push(await changeRelease(tx, input));
194
+ for (const input of inputs) results.push(await changeRelease(tx, input, labels));
180
195
  return results;
181
196
  });
182
197
  };
183
198
  /** Whether `current` is what the scope's enabled releases compile to. */
184
199
  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;
200
+ /** A compiled payload with its descriptors' labels left out. */
201
+ const withoutLabels = (payload) => {
202
+ const parsed = JSON.parse(payload);
203
+ return JSON.stringify({
204
+ ...parsed,
205
+ releaseDescriptors: (parsed.releaseDescriptors ?? []).map(({ label: _label, ...descriptor }) => descriptor)
206
+ });
207
+ };
208
+ /**
209
+ * Whether `projected` differs from `current` only by release labels, as a
210
+ * catalog compiled before its releases had them does.
211
+ */
212
+ 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);
185
213
  /** The scope a catalog row names. */
186
214
  const catalogRowScope = (row) => ({
187
215
  channelId: row.channel_id,
@@ -207,18 +235,20 @@ const preflightRebuild = async (db, scopeKey, updatedAtMs) => {
207
235
  const enabled = await drainReleases((cursor) => db.findMany("releases", enabledIn(scopeKey, cursor)));
208
236
  const compilation = await compileScope(scope, enabled);
209
237
  const changed = !isCurrent(scope, current, compilation);
238
+ const projectedCatalog = changed ? nextCatalog(scope, { catalog: current }, compilation, updatedAtMs) : current;
210
239
  return {
211
240
  changed,
241
+ labelsOnly: changed && differsInLabelsOnly(current, projectedCatalog),
212
242
  currentCatalog: current,
213
243
  diagnostics: compilation.diagnostics,
214
- projectedCatalog: changed ? nextCatalog(scope, { catalog: current }, compilation, updatedAtMs) : current
244
+ projectedCatalog
215
245
  };
216
246
  };
217
247
  /** Recompiles a scope's catalog from its enabled releases inside `tx`; an unchanged catalog is not rewritten. */
218
248
  const rebuildScope = async (tx, scope, updatedAtMs) => {
219
249
  checkScope(scope);
220
250
  const stored = await readCatalog(tx, scope.scopeKey);
221
- assertHistory(stored, await latestReleaseId(tx, scope.scopeKey) !== null);
251
+ assertHistory(stored, await latestRelease(tx, scope.scopeKey) !== null);
222
252
  const enabled = await enabledReleases(tx, scope.scopeKey);
223
253
  const compilation = await compileScope(scope, enabled);
224
254
  const current = stored.catalog;
@@ -237,4 +267,4 @@ const rebuildScope = async (tx, scope, updatedAtMs) => {
237
267
  };
238
268
  };
239
269
  //#endregion
240
- export { catalogRowScope, changeRelease, changeReleases, preflightRebuild, readCatalog, rebuildScope };
270
+ export { catalogRowScope, changeRelease, changeReleases, differsInLabelsOnly, preflightRebuild, readCatalog, rebuildScope };
@@ -1,4 +1,5 @@
1
1
  const require_reads = require("./reads.cjs");
2
+ const require_labels = require("./labels.cjs");
2
3
  let _hot_updater_plugin_core = require("@hot-updater/plugin-core");
3
4
  //#region src/core/writes.ts
4
5
  const PAGE = 500;
@@ -80,7 +81,11 @@ const insertChannel = async (db, row) => {
80
81
  throw error;
81
82
  }
82
83
  };
83
- /** Deletes a channel no release or native build uses: 1 read, 1 query, 1 write. */
84
+ /**
85
+ * Deletes a channel no release or native build uses, with its label
86
+ * counters, so one created again with its name starts at 1: 3 reads,
87
+ * 1 query, 1 write.
88
+ */
84
89
  const deleteChannel = (db, id) => db.transaction(async (tx) => {
85
90
  const row = await tx.findOne("channels", { id });
86
91
  if (row === null) return {
@@ -100,6 +105,10 @@ const deleteChannel = (db, id) => db.transaction(async (tx) => {
100
105
  deleted: false,
101
106
  reason: "not_empty"
102
107
  };
108
+ for (const platform of require_labels.LABEL_PLATFORMS) {
109
+ const counter = await tx.findOne("label_sequences", { id: require_labels.labelSequenceId(id, platform) });
110
+ if (counter !== null) await tx.delete("label_sequences", counter);
111
+ }
103
112
  await tx.delete("channels", row);
104
113
  return { deleted: true };
105
114
  });
@@ -1,4 +1,5 @@
1
1
  import { toChannelRow } from "./reads.mjs";
2
+ import { LABEL_PLATFORMS, labelSequenceId } from "./labels.mjs";
2
3
  import { DatabaseConstraintError } from "@hot-updater/plugin-core";
3
4
  //#region src/core/writes.ts
4
5
  const PAGE = 500;
@@ -80,7 +81,11 @@ const insertChannel = async (db, row) => {
80
81
  throw error;
81
82
  }
82
83
  };
83
- /** Deletes a channel no release or native build uses: 1 read, 1 query, 1 write. */
84
+ /**
85
+ * Deletes a channel no release or native build uses, with its label
86
+ * counters, so one created again with its name starts at 1: 3 reads,
87
+ * 1 query, 1 write.
88
+ */
84
89
  const deleteChannel = (db, id) => db.transaction(async (tx) => {
85
90
  const row = await tx.findOne("channels", { id });
86
91
  if (row === null) return {
@@ -100,6 +105,10 @@ const deleteChannel = (db, id) => db.transaction(async (tx) => {
100
105
  deleted: false,
101
106
  reason: "not_empty"
102
107
  };
108
+ for (const platform of LABEL_PLATFORMS) {
109
+ const counter = await tx.findOne("label_sequences", { id: labelSequenceId(id, platform) });
110
+ if (counter !== null) await tx.delete("label_sequences", counter);
111
+ }
103
112
  await tx.delete("channels", row);
104
113
  return { deleted: true };
105
114
  });
@@ -320,6 +320,30 @@ const createAdminRouteHandlers = () => ({
320
320
  return row === null ? notFound() : json({ data: row });
321
321
  }),
322
322
  rebuildReleaseCatalog: onCore(async (core, _request, params) => json({ data: await core.rebuildReleaseCatalog(scopeKeyOf(params)) })),
323
+ /**
324
+ * The release a label names, or `null`: never 404, which tells a client
325
+ * the server has no such route.
326
+ */
327
+ getReleaseByLabel: onCore(async (core, request) => {
328
+ const url = new URL(request.url);
329
+ const channel = url.searchParams.get("channel");
330
+ const platform = platformOf(url);
331
+ const label = Number(url.searchParams.get("label"));
332
+ if (channel === null || channel.length === 0 || platform === void 0 || !Number.isSafeInteger(label) || label < 1) throw new require_handlerErrors.HandlerBadRequestError("A release label lookup takes channel, platform, and a label of 1 or more.");
333
+ return json({ data: await core.getReleaseByLabel({
334
+ channel,
335
+ platform,
336
+ label
337
+ }) });
338
+ }),
339
+ fillReleaseLabels: onCore(async (core, request) => {
340
+ const body = await request.json().catch(() => ({}));
341
+ const input = body !== null && typeof body === "object" ? body : {};
342
+ return json({ data: await core.fillReleaseLabels({
343
+ dryRun: input.dryRun === true,
344
+ catalogs: input.catalogs !== false
345
+ }) });
346
+ }),
323
347
  updateBundle: onCore(async (core, request, params) => {
324
348
  const bundleId = require_handlerParameters.requireRouteParam(params, "id");
325
349
  const update = bundleUpdateOf(await request.json(), bundleId);
@@ -547,6 +571,16 @@ const ADMIN_ROUTES = [
547
571
  path: "/release-scopes",
548
572
  handler: "listReleaseScopeKeys"
549
573
  },
574
+ {
575
+ method: "GET",
576
+ path: "/release-labels",
577
+ handler: "getReleaseByLabel"
578
+ },
579
+ {
580
+ method: "POST",
581
+ path: "/release-labels/fill",
582
+ handler: "fillReleaseLabels"
583
+ },
550
584
  {
551
585
  method: "POST",
552
586
  path: "/release-catalogs/:scopeKey/rebuild",