@hot-updater/server 1.2.0-rc.5 → 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.
Files changed (51) 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 +317 -0
  24. package/dist/core/labels.mjs +310 -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 +121 -38
  34. package/dist/core/releases.mjs +121 -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/handlerAdminRoutes.cjs +288 -16
  46. package/dist/handlerAdminRoutes.mjs +289 -17
  47. package/dist/handlerReleaseCatalogRoutes.cjs +43 -27
  48. package/dist/handlerReleaseCatalogRoutes.mjs +43 -27
  49. package/dist/package.cjs +1 -1
  50. package/dist/package.mjs +1 -1
  51. 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);
@@ -94,11 +114,16 @@ const readCatalog = async (tx, scopeKey) => {
94
114
  const assertHistory = (stored, hasReleases) => {
95
115
  if (stored.catalog === null && hasReleases) fail("CATALOG_IDENTITY_MISSING", "Catalog history is missing. Restore its catalog row from backup before rebuilding or deploying.");
96
116
  };
97
- /** One release change and its scope's next catalog, inside `tx`. */
98
- 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) => {
99
124
  checkScope(scope);
100
125
  const stored = await readCatalog(tx, scope.scopeKey);
101
- const enabled = await enabledReleases(tx, scope.scopeKey);
126
+ let enabled = await enabledReleases(tx, scope.scopeKey);
102
127
  if (bundle !== void 0) {
103
128
  require_writes.insertBundle(tx, bundle.row);
104
129
  for (const patch of bundle.patches) tx.create("bundle_patches", patch);
@@ -106,14 +131,22 @@ const changeRelease = async (tx, { scope, change, bundle, updatedAtMs }) => {
106
131
  let before = null;
107
132
  let release;
108
133
  if (change.operation === "insert") {
109
- 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;
110
137
  assertHistory(stored, latest !== null);
111
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);
112
139
  const id = change.row.id ?? (0, _hot_updater_plugin_core.createUUIDv7After)(floor ?? null);
113
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);
114
146
  release = {
115
147
  ...change.row,
116
- id
148
+ id,
149
+ label: await labels.next(scope.channelId, scope.platform)
117
150
  };
118
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");
119
152
  tx.create("releases", release);
@@ -126,8 +159,9 @@ const changeRelease = async (tx, { scope, change, bundle, updatedAtMs }) => {
126
159
  await tx.delete("releases", row);
127
160
  release = null;
128
161
  } else {
162
+ const { label: _label, ...update } = change.update;
129
163
  const set = {
130
- ...change.update,
164
+ ...update,
131
165
  revision: before.revision + 1
132
166
  };
133
167
  tx.update("releases", row, set);
@@ -155,24 +189,70 @@ const changeRelease = async (tx, { scope, change, bundle, updatedAtMs }) => {
155
189
  */
156
190
  const changeReleases = (db, inputs) => {
157
191
  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) => {
192
+ return require_labels.writeWithLabels(db, async (tx, labels) => {
159
193
  const results = [];
160
- for (const input of inputs) results.push(await changeRelease(tx, input));
194
+ for (const input of inputs) results.push(await changeRelease(tx, input, labels));
161
195
  return results;
162
196
  });
163
197
  };
198
+ /** Whether `current` is what the scope's enabled releases compile to. */
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);
213
+ /** The scope a catalog row names. */
214
+ const catalogRowScope = (row) => ({
215
+ channelId: row.channel_id,
216
+ channelName: (0, _hot_updater_protocol.decodeChannelKey)(row.channel_key),
217
+ fingerprintHash: row.fingerprint_hash,
218
+ platform: row.platform,
219
+ scopeKey: row.scope_key,
220
+ strategy: row.strategy
221
+ });
222
+ /**
223
+ * What a rebuild of the scope's catalog would write, without writing: one
224
+ * read of the catalog row and one of the scope's enabled releases. It needs
225
+ * no transaction, whose guards would read the catalog again for each read
226
+ * beneath it, nor the scope's newest release, which matters only to a scope
227
+ * without a catalog row; that one is not found.
228
+ */
229
+ const preflightRebuild = async (db, scopeKey, updatedAtMs) => {
230
+ const row = await db.findOne("release_catalogs", { scope_key: scopeKey });
231
+ if (row === null) throw new Error(`Release catalog "${scopeKey}" was not found.`);
232
+ const current = require_reads.toCatalogRow(row);
233
+ const scope = catalogRowScope(current);
234
+ checkScope(scope);
235
+ const enabled = await drainReleases((cursor) => db.findMany("releases", enabledIn(scopeKey, cursor)));
236
+ const compilation = await compileScope(scope, enabled);
237
+ const changed = !isCurrent(scope, current, compilation);
238
+ const projectedCatalog = changed ? nextCatalog(scope, { catalog: current }, compilation, updatedAtMs) : current;
239
+ return {
240
+ changed,
241
+ labelsOnly: changed && differsInLabelsOnly(current, projectedCatalog),
242
+ currentCatalog: current,
243
+ diagnostics: compilation.diagnostics,
244
+ projectedCatalog
245
+ };
246
+ };
164
247
  /** Recompiles a scope's catalog from its enabled releases inside `tx`; an unchanged catalog is not rewritten. */
165
248
  const rebuildScope = async (tx, scope, updatedAtMs) => {
166
249
  checkScope(scope);
167
250
  const stored = await readCatalog(tx, scope.scopeKey);
168
- assertHistory(stored, await latestReleaseId(tx, scope.scopeKey) !== null);
251
+ assertHistory(stored, await latestRelease(tx, scope.scopeKey) !== null);
169
252
  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
- });
253
+ const compilation = await compileScope(scope, enabled);
174
254
  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 {
255
+ if (current !== null && isCurrent(scope, current, compilation)) return {
176
256
  catalog: current,
177
257
  current,
178
258
  changed: false,
@@ -187,7 +267,10 @@ const rebuildScope = async (tx, scope, updatedAtMs) => {
187
267
  };
188
268
  };
189
269
  //#endregion
270
+ exports.catalogRowScope = catalogRowScope;
190
271
  exports.changeRelease = changeRelease;
191
272
  exports.changeReleases = changeReleases;
273
+ exports.differsInLabelsOnly = differsInLabelsOnly;
274
+ exports.preflightRebuild = preflightRebuild;
192
275
  exports.readCatalog = readCatalog;
193
276
  exports.rebuildScope = rebuildScope;