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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -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) => {
@@ -109,15 +110,28 @@ const readCatalog = async (tx, scopeKey) => {
109
110
  catalog: row === null ? null : require_reads.toCatalogRow(row)
110
111
  };
111
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
+ };
112
120
  /** A scope with releases and no compiled catalog lost its history. */
113
121
  const assertHistory = (stored, hasReleases) => {
114
122
  if (stored.catalog === null && hasReleases) fail("CATALOG_IDENTITY_MISSING", "Catalog history is missing. Restore its catalog row from backup before rebuilding or deploying.");
115
123
  };
116
- /** One release change and its scope's next catalog, inside `tx`. */
117
- 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) => {
118
131
  checkScope(scope);
119
132
  const stored = await readCatalog(tx, scope.scopeKey);
120
- const enabled = await enabledReleases(tx, scope.scopeKey);
133
+ refuseLaterCatalog(scope, stored.catalog);
134
+ let enabled = await enabledReleases(tx, scope.scopeKey);
121
135
  if (bundle !== void 0) {
122
136
  require_writes.insertBundle(tx, bundle.row);
123
137
  for (const patch of bundle.patches) tx.create("bundle_patches", patch);
@@ -125,14 +139,22 @@ const changeRelease = async (tx, { scope, change, bundle, updatedAtMs }) => {
125
139
  let before = null;
126
140
  let release;
127
141
  if (change.operation === "insert") {
128
- 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;
129
145
  assertHistory(stored, latest !== null);
130
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);
131
147
  const id = change.row.id ?? (0, _hot_updater_plugin_core.createUUIDv7After)(floor ?? null);
132
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);
133
154
  release = {
134
155
  ...change.row,
135
- id
156
+ id,
157
+ label: await labels.next(scope.channelId, scope.platform)
136
158
  };
137
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");
138
160
  tx.create("releases", release);
@@ -145,8 +167,9 @@ const changeRelease = async (tx, { scope, change, bundle, updatedAtMs }) => {
145
167
  await tx.delete("releases", row);
146
168
  release = null;
147
169
  } else {
170
+ const { label: _label, ...update } = change.update;
148
171
  const set = {
149
- ...change.update,
172
+ ...update,
150
173
  revision: before.revision + 1
151
174
  };
152
175
  tx.update("releases", row, set);
@@ -174,14 +197,35 @@ const changeRelease = async (tx, { scope, change, bundle, updatedAtMs }) => {
174
197
  */
175
198
  const changeReleases = (db, inputs) => {
176
199
  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) => {
200
+ return require_labels.writeWithLabels(db, async (tx, labels) => {
178
201
  const results = [];
179
- for (const input of inputs) results.push(await changeRelease(tx, input));
202
+ for (const input of inputs) results.push(await changeRelease(tx, input, labels));
180
203
  return results;
181
204
  });
182
205
  };
183
- /** Whether `current` is what the scope's enabled releases compile to. */
184
- 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;
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);
185
229
  /** The scope a catalog row names. */
186
230
  const catalogRowScope = (row) => ({
187
231
  channelId: row.channel_id,
@@ -207,18 +251,20 @@ const preflightRebuild = async (db, scopeKey, updatedAtMs) => {
207
251
  const enabled = await drainReleases((cursor) => db.findMany("releases", enabledIn(scopeKey, cursor)));
208
252
  const compilation = await compileScope(scope, enabled);
209
253
  const changed = !isCurrent(scope, current, compilation);
254
+ const projectedCatalog = changed ? nextCatalog(scope, { catalog: current }, compilation, updatedAtMs) : current;
210
255
  return {
211
256
  changed,
257
+ labelsOnly: changed && differsInLabelsOnly(current, projectedCatalog),
212
258
  currentCatalog: current,
213
259
  diagnostics: compilation.diagnostics,
214
- projectedCatalog: changed ? nextCatalog(scope, { catalog: current }, compilation, updatedAtMs) : current
260
+ projectedCatalog
215
261
  };
216
262
  };
217
263
  /** Recompiles a scope's catalog from its enabled releases inside `tx`; an unchanged catalog is not rewritten. */
218
264
  const rebuildScope = async (tx, scope, updatedAtMs) => {
219
265
  checkScope(scope);
220
266
  const stored = await readCatalog(tx, scope.scopeKey);
221
- assertHistory(stored, await latestReleaseId(tx, scope.scopeKey) !== null);
267
+ assertHistory(stored, await latestRelease(tx, scope.scopeKey) !== null);
222
268
  const enabled = await enabledReleases(tx, scope.scopeKey);
223
269
  const compilation = await compileScope(scope, enabled);
224
270
  const current = stored.catalog;
@@ -228,6 +274,7 @@ const rebuildScope = async (tx, scope, updatedAtMs) => {
228
274
  changed: false,
229
275
  diagnostics: compilation.diagnostics
230
276
  };
277
+ refuseLaterCatalog(scope, current);
231
278
  const written = await writeCatalog(tx, scope, stored, enabled, updatedAtMs);
232
279
  return {
233
280
  catalog: written.catalog,
@@ -240,6 +287,7 @@ const rebuildScope = async (tx, scope, updatedAtMs) => {
240
287
  exports.catalogRowScope = catalogRowScope;
241
288
  exports.changeRelease = changeRelease;
242
289
  exports.changeReleases = changeReleases;
290
+ exports.differsInLabelsOnly = differsInLabelsOnly;
243
291
  exports.preflightRebuild = preflightRebuild;
244
292
  exports.readCatalog = readCatalog;
245
293
  exports.rebuildScope = rebuildScope;
@@ -1,6 +1,7 @@
1
1
  import { toCatalogRow, toReleaseRow } from "./reads.mjs";
2
+ import { catchUpLabels, writeWithLabels } from "./labels.mjs";
2
3
  import { insertBundle } from "./writes.mjs";
3
- import { ReleaseCatalogCompilationError, ReleaseCatalogMutationError, compileReleaseCatalog, createUUIDv7, createUUIDv7After, isUUIDv7, releaseRowToRelease } from "@hot-updater/plugin-core";
4
+ import { ReleaseCatalogCompilationError, ReleaseCatalogMutationError, compileReleaseCatalog, createUUIDv7, createUUIDv7After, isUUIDv7, readCompiledCatalogPayload, releaseRowToRelease } from "@hot-updater/plugin-core";
4
5
  import { MAX_COMPILED_CATALOG_BYTES, createReleaseCatalogScopeKey, decodeChannelKey, encodeChannelKey } from "@hot-updater/protocol";
5
6
  //#region src/core/releases.ts
6
7
  const PAGE = 500;
@@ -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) => {
@@ -109,15 +110,28 @@ const readCatalog = async (tx, scopeKey) => {
109
110
  catalog: row === null ? null : toCatalogRow(row)
110
111
  };
111
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 && 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
+ };
112
120
  /** A scope with releases and no compiled catalog lost its history. */
113
121
  const assertHistory = (stored, hasReleases) => {
114
122
  if (stored.catalog === null && hasReleases) fail("CATALOG_IDENTITY_MISSING", "Catalog history is missing. Restore its catalog row from backup before rebuilding or deploying.");
115
123
  };
116
- /** One release change and its scope's next catalog, inside `tx`. */
117
- 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) => {
118
131
  checkScope(scope);
119
132
  const stored = await readCatalog(tx, scope.scopeKey);
120
- const enabled = await enabledReleases(tx, scope.scopeKey);
133
+ refuseLaterCatalog(scope, stored.catalog);
134
+ let enabled = await enabledReleases(tx, scope.scopeKey);
121
135
  if (bundle !== void 0) {
122
136
  insertBundle(tx, bundle.row);
123
137
  for (const patch of bundle.patches) tx.create("bundle_patches", patch);
@@ -125,14 +139,22 @@ const changeRelease = async (tx, { scope, change, bundle, updatedAtMs }) => {
125
139
  let before = null;
126
140
  let release;
127
141
  if (change.operation === "insert") {
128
- 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;
129
145
  assertHistory(stored, latest !== null);
130
146
  const floor = [latest, bundle && isUUIDv7(bundle.row.id) ? bundle.row.id : null].filter((id) => id !== null).sort().at(-1);
131
147
  const id = change.row.id ?? createUUIDv7After(floor ?? null);
132
148
  if (latest !== null && id <= latest) fail("NON_MONOTONIC_RELEASE_ID", `Release "${id}" must sort after "${latest}"`);
149
+ const given = await 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);
133
154
  release = {
134
155
  ...change.row,
135
- id
156
+ id,
157
+ label: await labels.next(scope.channelId, scope.platform)
136
158
  };
137
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");
138
160
  tx.create("releases", release);
@@ -145,8 +167,9 @@ const changeRelease = async (tx, { scope, change, bundle, updatedAtMs }) => {
145
167
  await tx.delete("releases", row);
146
168
  release = null;
147
169
  } else {
170
+ const { label: _label, ...update } = change.update;
148
171
  const set = {
149
- ...change.update,
172
+ ...update,
150
173
  revision: before.revision + 1
151
174
  };
152
175
  tx.update("releases", row, set);
@@ -174,14 +197,35 @@ const changeRelease = async (tx, { scope, change, bundle, updatedAtMs }) => {
174
197
  */
175
198
  const changeReleases = (db, inputs) => {
176
199
  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) => {
200
+ return writeWithLabels(db, async (tx, labels) => {
178
201
  const results = [];
179
- for (const input of inputs) results.push(await changeRelease(tx, input));
202
+ for (const input of inputs) results.push(await changeRelease(tx, input, labels));
180
203
  return results;
181
204
  });
182
205
  };
183
- /** Whether `current` is what the scope's enabled releases compile to. */
184
- 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;
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 !== 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 = 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);
185
229
  /** The scope a catalog row names. */
186
230
  const catalogRowScope = (row) => ({
187
231
  channelId: row.channel_id,
@@ -207,18 +251,20 @@ const preflightRebuild = async (db, scopeKey, updatedAtMs) => {
207
251
  const enabled = await drainReleases((cursor) => db.findMany("releases", enabledIn(scopeKey, cursor)));
208
252
  const compilation = await compileScope(scope, enabled);
209
253
  const changed = !isCurrent(scope, current, compilation);
254
+ const projectedCatalog = changed ? nextCatalog(scope, { catalog: current }, compilation, updatedAtMs) : current;
210
255
  return {
211
256
  changed,
257
+ labelsOnly: changed && differsInLabelsOnly(current, projectedCatalog),
212
258
  currentCatalog: current,
213
259
  diagnostics: compilation.diagnostics,
214
- projectedCatalog: changed ? nextCatalog(scope, { catalog: current }, compilation, updatedAtMs) : current
260
+ projectedCatalog
215
261
  };
216
262
  };
217
263
  /** Recompiles a scope's catalog from its enabled releases inside `tx`; an unchanged catalog is not rewritten. */
218
264
  const rebuildScope = async (tx, scope, updatedAtMs) => {
219
265
  checkScope(scope);
220
266
  const stored = await readCatalog(tx, scope.scopeKey);
221
- assertHistory(stored, await latestReleaseId(tx, scope.scopeKey) !== null);
267
+ assertHistory(stored, await latestRelease(tx, scope.scopeKey) !== null);
222
268
  const enabled = await enabledReleases(tx, scope.scopeKey);
223
269
  const compilation = await compileScope(scope, enabled);
224
270
  const current = stored.catalog;
@@ -228,6 +274,7 @@ const rebuildScope = async (tx, scope, updatedAtMs) => {
228
274
  changed: false,
229
275
  diagnostics: compilation.diagnostics
230
276
  };
277
+ refuseLaterCatalog(scope, current);
231
278
  const written = await writeCatalog(tx, scope, stored, enabled, updatedAtMs);
232
279
  return {
233
280
  catalog: written.catalog,
@@ -237,4 +284,4 @@ const rebuildScope = async (tx, scope, updatedAtMs) => {
237
284
  };
238
285
  };
239
286
  //#endregion
240
- export { catalogRowScope, changeRelease, changeReleases, preflightRebuild, readCatalog, rebuildScope };
287
+ 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
  });