@hot-updater/server 1.2.0-rc.6 → 1.2.0-rc.61

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.
Files changed (53) hide show
  1. package/dist/adapters/drizzle.cjs +8 -4
  2. package/dist/adapters/drizzle.d.cts +3 -2
  3. package/dist/adapters/drizzle.d.mts +3 -2
  4. package/dist/adapters/drizzle.mjs +8 -4
  5. package/dist/adapters/drizzleExecutor.cjs +4 -2
  6. package/dist/adapters/drizzleExecutor.mjs +4 -2
  7. package/dist/adapters/kysely.cjs +3 -2
  8. package/dist/adapters/kysely.mjs +3 -2
  9. package/dist/adapters/mongodb.cjs +1 -1
  10. package/dist/adapters/mongodb.mjs +1 -1
  11. package/dist/adapters/mongodbAdapter.cjs +15 -3
  12. package/dist/adapters/mongodbAdapter.mjs +15 -3
  13. package/dist/adapters/prisma.cjs +9 -13
  14. package/dist/adapters/prisma.mjs +10 -14
  15. package/dist/adapters/prismaExecutor.cjs +25 -20
  16. package/dist/adapters/prismaExecutor.mjs +25 -20
  17. package/dist/core/api.cjs +2 -0
  18. package/dist/core/api.d.cts +48 -1
  19. package/dist/core/api.d.mts +48 -1
  20. package/dist/core/api.mjs +2 -0
  21. package/dist/core/iosDevices.cjs +306 -0
  22. package/dist/core/iosDevices.mjs +303 -0
  23. package/dist/core/labels.cjs +325 -0
  24. package/dist/core/labels.mjs +318 -0
  25. package/dist/core/nativeBuildDestinations.cjs +13 -0
  26. package/dist/core/nativeBuildDestinations.mjs +13 -0
  27. package/dist/core/nativeBuilds.cjs +291 -22
  28. package/dist/core/nativeBuilds.mjs +291 -23
  29. package/dist/core/operations.cjs +45 -24
  30. package/dist/core/operations.mjs +48 -27
  31. package/dist/core/reads.cjs +69 -5
  32. package/dist/core/reads.mjs +70 -6
  33. package/dist/core/releases.cjs +138 -38
  34. package/dist/core/releases.mjs +138 -41
  35. package/dist/core/writes.cjs +14 -2
  36. package/dist/core/writes.mjs +14 -2
  37. package/dist/createHotUpdaterCore.d.cts +2 -4
  38. package/dist/createHotUpdaterCore.d.mts +2 -4
  39. package/dist/db/engineDrizzleSchema.cjs +21 -5
  40. package/dist/db/engineDrizzleSchema.mjs +21 -6
  41. package/dist/db/enginePrismaSchema.cjs +6 -14
  42. package/dist/db/enginePrismaSchema.mjs +7 -15
  43. package/dist/db/releaseCatalog.cjs +13 -4
  44. package/dist/db/releaseCatalog.mjs +12 -5
  45. package/dist/handler.cjs +2 -1
  46. package/dist/handler.mjs +2 -1
  47. package/dist/handlerAdminRoutes.cjs +288 -16
  48. package/dist/handlerAdminRoutes.mjs +289 -17
  49. package/dist/handlerReleaseCatalogRoutes.cjs +43 -27
  50. package/dist/handlerReleaseCatalogRoutes.mjs +43 -27
  51. package/dist/package.cjs +1 -1
  52. package/dist/package.mjs +1 -1
  53. package/package.json +7 -14
@@ -1,10 +1,12 @@
1
- import { toBundleRow, toReleaseRow } from "./reads.mjs";
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
- import { isBuiltInBundle } from "./nativeBuilds.mjs";
4
- import { changeRelease, changeReleases, readCatalog, rebuildScope } from "./releases.mjs";
4
+ import { isBuiltInBundle, refuseSandboxPatchBase } from "./nativeBuilds.mjs";
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;
@@ -93,14 +95,7 @@ const mutationResult = ({ catalog, release }) => ({
93
95
  const catalogScope = async (tx, scopeKey) => {
94
96
  const row = await tx.findOne("release_catalogs", { scope_key: scopeKey });
95
97
  if (row === null) throw new Error(`Release catalog "${scopeKey}" was not found.`);
96
- return {
97
- channelId: row.channel_id,
98
- channelName: decodeChannelKey(row.channel_key),
99
- fingerprintHash: row.fingerprint_hash,
100
- platform: row.platform,
101
- scopeKey: row.scope_key,
102
- strategy: row.strategy
103
- };
98
+ return catalogRowScope(toCatalogRow(row));
104
99
  };
105
100
  /**
106
101
  * Core's typed writes: each runs in one engine transaction rooted at the
@@ -129,7 +124,11 @@ const createCoreOperations = (db, { now = Date.now } = {}) => {
129
124
  for (const { release } of deployments) if (!channels.has(release.channel)) channels.set(release.channel, await ensureChannel(release.channel));
130
125
  const platforms = /* @__PURE__ */ new Map();
131
126
  for (const deployment of deployments) {
132
- if (!("bundleId" in deployment) || platforms.has(deployment.bundleId)) continue;
127
+ if (!("bundleId" in deployment)) {
128
+ for (const { baseBundleId } of deployment.bundle.patches ?? []) await refuseSandboxPatchBase(db, baseBundleId);
129
+ continue;
130
+ }
131
+ if (platforms.has(deployment.bundleId)) continue;
133
132
  const row = await db.findOne("bundles", { id: deployment.bundleId });
134
133
  if (row === null) throw new DatabaseBundleNotFoundError(deployment.bundleId);
135
134
  if (await isBuiltInBundle(db, deployment.bundleId)) throw new ReleaseManagementError("TARGET_RELEASE_INVALID", `Bundle "${deployment.bundleId}" is a native build's built-in bundle, which no release publishes.`);
@@ -239,7 +238,7 @@ const createCoreOperations = (db, { now = Date.now } = {}) => {
239
238
  if (targetChannel.length === 0) throw new ReleaseManagementError("TARGET_RELEASE_INVALID", "Promotion requires a target channel.");
240
239
  const channel = await ensureChannel(targetChannel);
241
240
  const updatedAtMs = now();
242
- return db.transaction(async (tx) => {
241
+ return writeWithLabels(db, async (tx, labels) => {
243
242
  const { release: source, scope: sourceScope } = await loadTarget(tx, input);
244
243
  checkSource(source);
245
244
  const targetScope = scopeOf(channel, source.platform, source.fingerprint_hash);
@@ -267,12 +266,13 @@ const createCoreOperations = (db, { now = Date.now } = {}) => {
267
266
  },
268
267
  updatedAtMs
269
268
  }) : null;
269
+ const { label: _label, ...copied } = source;
270
270
  const target = await changeRelease(tx, {
271
271
  scope: targetScope,
272
272
  change: {
273
273
  operation: "insert",
274
274
  row: {
275
- ...source,
275
+ ...copied,
276
276
  id: createUUIDv7After(floor ?? null, updatedAtMs),
277
277
  revision: 1,
278
278
  scope_key: targetScope.scopeKey,
@@ -287,7 +287,7 @@ const createCoreOperations = (db, { now = Date.now } = {}) => {
287
287
  }
288
288
  },
289
289
  updatedAtMs
290
- });
290
+ }, labels);
291
291
  return {
292
292
  source: moved === null ? null : mutationResult(moved),
293
293
  target: mutationResult(target)
@@ -304,17 +304,38 @@ const createCoreOperations = (db, { now = Date.now } = {}) => {
304
304
  };
305
305
  });
306
306
  },
307
- preflightReleaseCatalogRebuild: (scopeKey) => {
308
- const updatedAtMs = now();
309
- return dryRun(db, async (tx) => {
310
- const rebuilt = await rebuildScope(tx, await catalogScope(tx, scopeKey), updatedAtMs);
311
- return {
312
- changed: rebuilt.changed,
313
- currentCatalog: rebuilt.current,
314
- diagnostics: rebuilt.diagnostics,
315
- projectedCatalog: rebuilt.catalog
316
- };
317
- });
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
+ };
318
339
  },
319
340
  ensureChannel,
320
341
  deleteChannel: (id) => deleteChannel(db, id),
@@ -333,7 +354,7 @@ const createCoreOperations = (db, { now = Date.now } = {}) => {
333
354
  if (patches !== void 0) await replaceBundlePatches(tx, current, bundleToPatchRows({
334
355
  ...next,
335
356
  patches
336
- }));
357
+ }), (row) => refuseSandboxPatchBase(tx, row.base_bundle_id));
337
358
  }),
338
359
  deleteBundles: async (ids) => {
339
360
  try {
@@ -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",
@@ -74,8 +81,16 @@ const drain = async (read) => {
74
81
  return rows;
75
82
  };
76
83
  /** A keyset page's range: the keys strictly after `after`, in `order`. */
77
- const after = (input) => input.after === void 0 ? {} : { range: (input.order ?? "asc") === "asc" ? { gt: input.after } : { lt: input.after } };
78
- /** Core's reads, each through one declared index or key. */
84
+ /** A keyset read's range on its index's order: past `after`, up to `through`. */
85
+ const after = (input) => {
86
+ const asc = (input.order ?? "asc") === "asc";
87
+ const range = {
88
+ ...input.after === void 0 ? {} : asc ? { gt: input.after } : { lt: input.after },
89
+ ...input.through === void 0 ? {} : asc ? { lte: input.through } : { gte: input.through }
90
+ };
91
+ return Object.keys(range).length === 0 ? {} : { range };
92
+ };
93
+ /** Core's reads, each through one declared index or key; plugins get `CoreReads`. */
79
94
  const createCoreReads = (db, storage) => {
80
95
  /** A bundle row's patches, exactly as many as its reference counter holds. */
81
96
  const detail = async (row) => {
@@ -196,6 +211,23 @@ const createCoreReads = (db, storage) => {
196
211
  const row = await db.findOne("releases", { id });
197
212
  return row === null ? null : toReleaseRow(row);
198
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
+ },
199
231
  /** One page of releases through the index its filter names. */
200
232
  async listReleases(input) {
201
233
  const { filter } = input;
@@ -263,8 +295,35 @@ const createCoreReads = (db, storage) => {
263
295
  ...after(input)
264
296
  })).rows.map(toCatalogRow);
265
297
  },
266
- /** Every channel, by name. */
267
- async listChannels() {
298
+ /**
299
+ * Up to `limit` scope keys that have releases, ascending after `after`:
300
+ * one limit-1 seek of the `scopes` index past each scope, so the reads
301
+ * grow with the scopes, not with their releases.
302
+ */
303
+ async listReleaseScopeKeys(input) {
304
+ const scopeKeys = [];
305
+ for (let last = input.after ?? ""; scopeKeys.length < input.limit;) {
306
+ const { rows } = await db.findMany("releases", {
307
+ index: "scopes",
308
+ where: {},
309
+ limit: 1,
310
+ range: { gt: last }
311
+ });
312
+ if (rows[0] === void 0) break;
313
+ last = rows[0].scope_key;
314
+ scopeKeys.push(last);
315
+ }
316
+ return scopeKeys;
317
+ },
318
+ /** Every channel by name; with `input`, one keyset page of them. */
319
+ async listChannels(input) {
320
+ if (input !== void 0) return (await db.findMany("channels", {
321
+ index: "all",
322
+ where: {},
323
+ order: input.order ?? "asc",
324
+ limit: input.limit,
325
+ ...after(input)
326
+ })).rows.map(toChannelRow);
268
327
  return (await drain((page) => db.findMany("channels", {
269
328
  index: "all",
270
329
  where: {},
@@ -272,6 +331,11 @@ const createCoreReads = (db, storage) => {
272
331
  ...page
273
332
  }))).map(toChannelRow);
274
333
  },
334
+ async getChannels(ids) {
335
+ const unique = [...new Set(ids)];
336
+ if (unique.length === 0) return [];
337
+ return (await db.findByKeys("channels", unique.map((id) => ({ id })))).flatMap((row) => row ? [toChannelRow(row)] : []);
338
+ },
275
339
  async findChannelByName(name) {
276
340
  const row = await db.findOne("channels", { name });
277
341
  return row === null ? null : toChannelRow(row);
@@ -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",
@@ -74,8 +81,16 @@ const drain = async (read) => {
74
81
  return rows;
75
82
  };
76
83
  /** A keyset page's range: the keys strictly after `after`, in `order`. */
77
- const after = (input) => input.after === void 0 ? {} : { range: (input.order ?? "asc") === "asc" ? { gt: input.after } : { lt: input.after } };
78
- /** Core's reads, each through one declared index or key. */
84
+ /** A keyset read's range on its index's order: past `after`, up to `through`. */
85
+ const after = (input) => {
86
+ const asc = (input.order ?? "asc") === "asc";
87
+ const range = {
88
+ ...input.after === void 0 ? {} : asc ? { gt: input.after } : { lt: input.after },
89
+ ...input.through === void 0 ? {} : asc ? { lte: input.through } : { gte: input.through }
90
+ };
91
+ return Object.keys(range).length === 0 ? {} : { range };
92
+ };
93
+ /** Core's reads, each through one declared index or key; plugins get `CoreReads`. */
79
94
  const createCoreReads = (db, storage) => {
80
95
  /** A bundle row's patches, exactly as many as its reference counter holds. */
81
96
  const detail = async (row) => {
@@ -196,6 +211,23 @@ const createCoreReads = (db, storage) => {
196
211
  const row = await db.findOne("releases", { id });
197
212
  return row === null ? null : toReleaseRow(row);
198
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
+ },
199
231
  /** One page of releases through the index its filter names. */
200
232
  async listReleases(input) {
201
233
  const { filter } = input;
@@ -263,8 +295,35 @@ const createCoreReads = (db, storage) => {
263
295
  ...after(input)
264
296
  })).rows.map(toCatalogRow);
265
297
  },
266
- /** Every channel, by name. */
267
- async listChannels() {
298
+ /**
299
+ * Up to `limit` scope keys that have releases, ascending after `after`:
300
+ * one limit-1 seek of the `scopes` index past each scope, so the reads
301
+ * grow with the scopes, not with their releases.
302
+ */
303
+ async listReleaseScopeKeys(input) {
304
+ const scopeKeys = [];
305
+ for (let last = input.after ?? ""; scopeKeys.length < input.limit;) {
306
+ const { rows } = await db.findMany("releases", {
307
+ index: "scopes",
308
+ where: {},
309
+ limit: 1,
310
+ range: { gt: last }
311
+ });
312
+ if (rows[0] === void 0) break;
313
+ last = rows[0].scope_key;
314
+ scopeKeys.push(last);
315
+ }
316
+ return scopeKeys;
317
+ },
318
+ /** Every channel by name; with `input`, one keyset page of them. */
319
+ async listChannels(input) {
320
+ if (input !== void 0) return (await db.findMany("channels", {
321
+ index: "all",
322
+ where: {},
323
+ order: input.order ?? "asc",
324
+ limit: input.limit,
325
+ ...after(input)
326
+ })).rows.map(toChannelRow);
268
327
  return (await drain((page) => db.findMany("channels", {
269
328
  index: "all",
270
329
  where: {},
@@ -272,6 +331,11 @@ const createCoreReads = (db, storage) => {
272
331
  ...page
273
332
  }))).map(toChannelRow);
274
333
  },
334
+ async getChannels(ids) {
335
+ const unique = [...new Set(ids)];
336
+ if (unique.length === 0) return [];
337
+ return (await db.findByKeys("channels", unique.map((id) => ({ id })))).flatMap((row) => row ? [toChannelRow(row)] : []);
338
+ },
275
339
  async findChannelByName(name) {
276
340
  const row = await db.findOne("channels", { name });
277
341
  return row === null ? null : toChannelRow(row);
@@ -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");
@@ -21,44 +22,43 @@ const checkScope = (scope) => {
21
22
  });
22
23
  if (scope.strategy === "FINGERPRINT" !== (scope.fingerprintHash !== null) || scope.scopeKey !== expected) fail("INVALID_SCOPE", "Release catalog scope metadata is inconsistent");
23
24
  };
24
- /** A scope's enabled releases, all of them, under the catalog's guard. */
25
- const enabledReleases = async (tx, scopeKey) => {
25
+ /** Every row of a paged read, as release rows. */
26
+ const drainReleases = async (page) => {
26
27
  const rows = [];
27
28
  let cursor;
28
29
  do {
29
- const page = await tx.findMany("releases", {
30
- index: "byScopeEnabled",
31
- where: {
32
- scope_key: scopeKey,
33
- enabled: true
34
- },
35
- limit: PAGE,
36
- ...cursor === void 0 ? {} : { cursor }
37
- });
38
- rows.push(...page.rows.map(require_reads.toReleaseRow));
39
- cursor = page.next;
30
+ const found = await page(cursor);
31
+ rows.push(...found.rows.map((row) => require_reads.toReleaseRow(row)));
32
+ cursor = found.next;
40
33
  } while (cursor !== void 0);
41
34
  return rows;
42
35
  };
43
- /** The scope's newest release id: `byScope` descending, limit 1. */
44
- const latestReleaseId = async (tx, scopeKey) => {
36
+ const enabledIn = (scopeKey, cursor) => ({
37
+ index: "byScopeEnabled",
38
+ where: {
39
+ scope_key: scopeKey,
40
+ enabled: true
41
+ },
42
+ limit: PAGE,
43
+ ...cursor === void 0 ? {} : { cursor }
44
+ });
45
+ /** A scope's enabled releases, all of them, under the catalog's guard. */
46
+ const enabledReleases = (tx, scopeKey) => drainReleases((cursor) => tx.findMany("releases", enabledIn(scopeKey, cursor)));
47
+ /** The scope's newest release: `byScope` descending, limit 1. */
48
+ const latestRelease = async (tx, scopeKey) => {
45
49
  const { rows } = await tx.findMany("releases", {
46
50
  index: "byScope",
47
51
  where: { scope_key: scopeKey },
48
52
  order: "desc",
49
53
  limit: 1
50
54
  });
51
- return rows[0]?.id ?? null;
55
+ return rows[0] === void 0 ? null : require_reads.toReleaseRow(rows[0]);
52
56
  };
53
- /** Compiles `enabled` and writes it as the scope's next catalog generation. */
54
- const writeCatalog = async (tx, scope, stored, enabled, updatedAtMs) => {
55
- const compilation = await (0, _hot_updater_plugin_core.compileReleaseCatalog)({
56
- strategy: scope.strategy,
57
- releases: enabled.map(_hot_updater_plugin_core.releaseRowToRelease)
58
- });
59
- const generation = (stored.generation ?? 0) + 1;
57
+ /** The scope's next catalog generation, compiled as `compilation`. */
58
+ const nextCatalog = (scope, stored, compilation, updatedAtMs) => {
59
+ const generation = (stored.catalog?.generation ?? 0) + 1;
60
60
  if (!Number.isSafeInteger(generation)) fail("CATALOG_GENERATION_EXHAUSTED", `Catalog "${scope.scopeKey}" exhausted its generation counter`);
61
- const catalog = {
61
+ return {
62
62
  scope_key: scope.scopeKey,
63
63
  catalog_id: stored.catalog?.catalog_id ?? (0, _hot_updater_plugin_core.createUUIDv7)(),
64
64
  strategy: scope.strategy,
@@ -73,6 +73,26 @@ const writeCatalog = async (tx, scope, stored, enabled, updatedAtMs) => {
73
73
  is_tombstone: compilation.payload.releaseDescriptors.length === 0,
74
74
  updated_at_ms: updatedAtMs
75
75
  };
76
+ };
77
+ /**
78
+ * Compiles a scope's enabled releases. A catalog over the size limit is
79
+ * refused naming its channel and platform, and what frees room in it.
80
+ */
81
+ const compileScope = async (scope, enabled) => {
82
+ try {
83
+ return await (0, _hot_updater_plugin_core.compileReleaseCatalog)({
84
+ strategy: scope.strategy,
85
+ releases: enabled.map(_hot_updater_plugin_core.releaseRowToRelease)
86
+ });
87
+ } catch (error) {
88
+ if (!(error instanceof _hot_updater_plugin_core.ReleaseCatalogCompilationError) || error.code !== "CATALOG_OVERSIZE") throw error;
89
+ throw new _hot_updater_plugin_core.ReleaseCatalogCompilationError("CATALOG_OVERSIZE", `The ${scope.platform} release catalog of channel "${scope.channelName}" would be over its ${_hot_updater_protocol.MAX_COMPILED_CATALOG_BYTES / 1024} KiB limit.\nDisable or delete old bundles on that channel, then try again.`);
90
+ }
91
+ };
92
+ /** Compiles `enabled` and writes it as the scope's next catalog generation. */
93
+ const writeCatalog = async (tx, scope, stored, enabled, updatedAtMs) => {
94
+ const compilation = await compileScope(scope, enabled);
95
+ const catalog = nextCatalog(scope, stored, compilation, updatedAtMs);
76
96
  const { scope_key: _scopeKey, ...set } = catalog;
77
97
  if (stored.row === null) tx.create("release_catalogs", catalog);
78
98
  else tx.update("release_catalogs", stored.row, set);
@@ -90,15 +110,28 @@ const readCatalog = async (tx, scopeKey) => {
90
110
  catalog: row === null ? null : require_reads.toCatalogRow(row)
91
111
  };
92
112
  };
113
+ /**
114
+ * Refuses to rewrite a catalog a later release compiled: this release's
115
+ * compiler would drop the fields that release added.
116
+ */
117
+ const refuseLaterCatalog = (scope, catalog) => {
118
+ if (catalog !== null && (0, _hot_updater_plugin_core.readCompiledCatalogPayload)(catalog.payload).fromLaterRelease) fail("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.`);
119
+ };
93
120
  /** A scope with releases and no compiled catalog lost its history. */
94
121
  const assertHistory = (stored, hasReleases) => {
95
122
  if (stored.catalog === null && hasReleases) fail("CATALOG_IDENTITY_MISSING", "Catalog history is missing. Restore its catalog row from backup before rebuilding or deploying.");
96
123
  };
97
- /** One release change and its scope's next catalog, inside `tx`. */
98
- const changeRelease = async (tx, { scope, change, bundle, updatedAtMs }) => {
124
+ /**
125
+ * One release change and its scope's next catalog, inside `tx`. An insert
126
+ * takes its channel and platform's next label from `labels`, after labeling
127
+ * the releases a server of an earlier release wrote in the scope since its
128
+ * last labeled one.
129
+ */
130
+ const changeRelease = async (tx, { scope, change, bundle, updatedAtMs }, labels) => {
99
131
  checkScope(scope);
100
132
  const stored = await readCatalog(tx, scope.scopeKey);
101
- const enabled = await enabledReleases(tx, scope.scopeKey);
133
+ refuseLaterCatalog(scope, stored.catalog);
134
+ let enabled = await enabledReleases(tx, scope.scopeKey);
102
135
  if (bundle !== void 0) {
103
136
  require_writes.insertBundle(tx, bundle.row);
104
137
  for (const patch of bundle.patches) tx.create("bundle_patches", patch);
@@ -106,14 +139,22 @@ const changeRelease = async (tx, { scope, change, bundle, updatedAtMs }) => {
106
139
  let before = null;
107
140
  let release;
108
141
  if (change.operation === "insert") {
109
- const latest = await latestReleaseId(tx, scope.scopeKey);
142
+ if (labels === void 0) throw new Error("A release insert takes its label from an allocator.");
143
+ const newest = await latestRelease(tx, scope.scopeKey);
144
+ const latest = newest?.id ?? null;
110
145
  assertHistory(stored, latest !== null);
111
146
  const floor = [latest, bundle && (0, _hot_updater_plugin_core.isUUIDv7)(bundle.row.id) ? bundle.row.id : null].filter((id) => id !== null).sort().at(-1);
112
147
  const id = change.row.id ?? (0, _hot_updater_plugin_core.createUUIDv7After)(floor ?? null);
113
148
  if (latest !== null && id <= latest) fail("NON_MONOTONIC_RELEASE_ID", `Release "${id}" must sort after "${latest}"`);
149
+ const given = await require_labels.catchUpLabels(tx, labels, newest);
150
+ if (given.size > 0) enabled = enabled.map((row) => given.has(row.id) ? {
151
+ ...row,
152
+ label: given.get(row.id)
153
+ } : row);
114
154
  release = {
115
155
  ...change.row,
116
- id
156
+ id,
157
+ label: await labels.next(scope.channelId, scope.platform)
117
158
  };
118
159
  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");
119
160
  tx.create("releases", release);
@@ -126,8 +167,9 @@ const changeRelease = async (tx, { scope, change, bundle, updatedAtMs }) => {
126
167
  await tx.delete("releases", row);
127
168
  release = null;
128
169
  } else {
170
+ const { label: _label, ...update } = change.update;
129
171
  const set = {
130
- ...change.update,
172
+ ...update,
131
173
  revision: before.revision + 1
132
174
  };
133
175
  tx.update("releases", row, set);
@@ -155,29 +197,84 @@ const changeRelease = async (tx, { scope, change, bundle, updatedAtMs }) => {
155
197
  */
156
198
  const changeReleases = (db, inputs) => {
157
199
  if (new Set(inputs.map(({ scope }) => scope.scopeKey)).size !== inputs.length) fail("INVALID_SCOPE", "A batch cannot change one catalog scope twice");
158
- return db.transaction(async (tx) => {
200
+ return require_labels.writeWithLabels(db, async (tx, labels) => {
159
201
  const results = [];
160
- for (const input of inputs) results.push(await changeRelease(tx, input));
202
+ for (const input of inputs) results.push(await changeRelease(tx, input, labels));
161
203
  return results;
162
204
  });
163
205
  };
206
+ /**
207
+ * Whether `current` is what the scope's enabled releases compile to, in the
208
+ * fields this release compiles: a later release's catalog may add others.
209
+ */
210
+ const isCurrent = (scope, current, compilation) => {
211
+ if (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) return false;
212
+ if (current.catalog_hash === compilation.catalogHash) return true;
213
+ const read = (0, _hot_updater_plugin_core.readCompiledCatalogPayload)(current.payload);
214
+ return read.fromLaterRelease && read.canonicalPayload === compilation.canonicalPayload;
215
+ };
216
+ /** A compiled payload with its descriptors' labels left out. */
217
+ const withoutLabels = (payload) => {
218
+ const parsed = JSON.parse(payload);
219
+ return JSON.stringify({
220
+ ...parsed,
221
+ releaseDescriptors: (parsed.releaseDescriptors ?? []).map(({ label: _label, ...descriptor }) => descriptor)
222
+ });
223
+ };
224
+ /**
225
+ * Whether `projected` differs from `current` only by release labels, as a
226
+ * catalog compiled before its releases had them does.
227
+ */
228
+ 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);
229
+ /** The scope a catalog row names. */
230
+ const catalogRowScope = (row) => ({
231
+ channelId: row.channel_id,
232
+ channelName: (0, _hot_updater_protocol.decodeChannelKey)(row.channel_key),
233
+ fingerprintHash: row.fingerprint_hash,
234
+ platform: row.platform,
235
+ scopeKey: row.scope_key,
236
+ strategy: row.strategy
237
+ });
238
+ /**
239
+ * What a rebuild of the scope's catalog would write, without writing: one
240
+ * read of the catalog row and one of the scope's enabled releases. It needs
241
+ * no transaction, whose guards would read the catalog again for each read
242
+ * beneath it, nor the scope's newest release, which matters only to a scope
243
+ * without a catalog row; that one is not found.
244
+ */
245
+ const preflightRebuild = async (db, scopeKey, updatedAtMs) => {
246
+ const row = await db.findOne("release_catalogs", { scope_key: scopeKey });
247
+ if (row === null) throw new Error(`Release catalog "${scopeKey}" was not found.`);
248
+ const current = require_reads.toCatalogRow(row);
249
+ const scope = catalogRowScope(current);
250
+ checkScope(scope);
251
+ const enabled = await drainReleases((cursor) => db.findMany("releases", enabledIn(scopeKey, cursor)));
252
+ const compilation = await compileScope(scope, enabled);
253
+ const changed = !isCurrent(scope, current, compilation);
254
+ const projectedCatalog = changed ? nextCatalog(scope, { catalog: current }, compilation, updatedAtMs) : current;
255
+ return {
256
+ changed,
257
+ labelsOnly: changed && differsInLabelsOnly(current, projectedCatalog),
258
+ currentCatalog: current,
259
+ diagnostics: compilation.diagnostics,
260
+ projectedCatalog
261
+ };
262
+ };
164
263
  /** Recompiles a scope's catalog from its enabled releases inside `tx`; an unchanged catalog is not rewritten. */
165
264
  const rebuildScope = async (tx, scope, updatedAtMs) => {
166
265
  checkScope(scope);
167
266
  const stored = await readCatalog(tx, scope.scopeKey);
168
- assertHistory(stored, await latestReleaseId(tx, scope.scopeKey) !== null);
267
+ assertHistory(stored, await latestRelease(tx, scope.scopeKey) !== null);
169
268
  const enabled = await enabledReleases(tx, scope.scopeKey);
170
- const compilation = await (0, _hot_updater_plugin_core.compileReleaseCatalog)({
171
- strategy: scope.strategy,
172
- releases: enabled.map(_hot_updater_plugin_core.releaseRowToRelease)
173
- });
269
+ const compilation = await compileScope(scope, enabled);
174
270
  const current = stored.catalog;
175
- if (current !== null && 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) return {
271
+ if (current !== null && isCurrent(scope, current, compilation)) return {
176
272
  catalog: current,
177
273
  current,
178
274
  changed: false,
179
275
  diagnostics: compilation.diagnostics
180
276
  };
277
+ refuseLaterCatalog(scope, current);
181
278
  const written = await writeCatalog(tx, scope, stored, enabled, updatedAtMs);
182
279
  return {
183
280
  catalog: written.catalog,
@@ -187,7 +284,10 @@ const rebuildScope = async (tx, scope, updatedAtMs) => {
187
284
  };
188
285
  };
189
286
  //#endregion
287
+ exports.catalogRowScope = catalogRowScope;
190
288
  exports.changeRelease = changeRelease;
191
289
  exports.changeReleases = changeReleases;
290
+ exports.differsInLabelsOnly = differsInLabelsOnly;
291
+ exports.preflightRebuild = preflightRebuild;
192
292
  exports.readCatalog = readCatalog;
193
293
  exports.rebuildScope = rebuildScope;