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

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,7 +1,8 @@
1
1
  import { toCatalogRow, toReleaseRow } from "./reads.mjs";
2
+ import { catchUpLabels, writeWithLabels } from "./labels.mjs";
2
3
  import { insertBundle } from "./writes.mjs";
3
- import { ReleaseCatalogMutationError, compileReleaseCatalog, createUUIDv7, createUUIDv7After, isUUIDv7, releaseRowToRelease } from "@hot-updater/plugin-core";
4
- import { createReleaseCatalogScopeKey, encodeChannelKey } from "@hot-updater/protocol";
4
+ import { ReleaseCatalogCompilationError, ReleaseCatalogMutationError, compileReleaseCatalog, createUUIDv7, createUUIDv7After, isUUIDv7, readCompiledCatalogPayload, releaseRowToRelease } from "@hot-updater/plugin-core";
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;
7
8
  const fail = (code, message) => {
@@ -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(toReleaseRow));
39
- cursor = page.next;
30
+ const found = await page(cursor);
31
+ rows.push(...found.rows.map((row) => 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 : 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 compileReleaseCatalog({
56
- strategy: scope.strategy,
57
- releases: enabled.map(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 ?? 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 compileReleaseCatalog({
84
+ strategy: scope.strategy,
85
+ releases: enabled.map(releaseRowToRelease)
86
+ });
87
+ } catch (error) {
88
+ if (!(error instanceof ReleaseCatalogCompilationError) || error.code !== "CATALOG_OVERSIZE") throw error;
89
+ throw new ReleaseCatalogCompilationError("CATALOG_OVERSIZE", `The ${scope.platform} release catalog of channel "${scope.channelName}" would be over its ${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 : 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 && 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
  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 && isUUIDv7(bundle.row.id) ? bundle.row.id : null].filter((id) => id !== null).sort().at(-1);
112
147
  const id = change.row.id ?? 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 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 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 !== 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);
229
+ /** The scope a catalog row names. */
230
+ const catalogRowScope = (row) => ({
231
+ channelId: row.channel_id,
232
+ channelName: 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 = 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 compileReleaseCatalog({
171
- strategy: scope.strategy,
172
- releases: enabled.map(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 === 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,4 +284,4 @@ const rebuildScope = async (tx, scope, updatedAtMs) => {
187
284
  };
188
285
  };
189
286
  //#endregion
190
- export { changeRelease, changeReleases, 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;
@@ -29,8 +30,10 @@ const deleteBundle = async (tx, current) => {
29
30
  /**
30
31
  * Replaces a bundle's patches with `rows`: kept patches are updated where
31
32
  * they changed, others deleted or created, so no key is written twice.
33
+ * `checkNew` sees each patch it is about to create, and refuses one by
34
+ * throwing, which leaves the transaction's writes undone.
32
35
  */
33
- const replaceBundlePatches = async (tx, bundle, rows) => {
36
+ const replaceBundlePatches = async (tx, bundle, rows, checkNew) => {
34
37
  const wanted = new Map(rows.map((row) => [row.id, row]));
35
38
  const count = bundle._refs_bundle_patches_bundle_id ?? 0;
36
39
  let cursor;
@@ -55,6 +58,7 @@ const replaceBundlePatches = async (tx, bundle, rows) => {
55
58
  if (page.next === void 0) break;
56
59
  cursor = page.next;
57
60
  }
61
+ if (checkNew !== void 0) for (const row of wanted.values()) await checkNew(row);
58
62
  for (const row of wanted.values()) tx.create("bundle_patches", row);
59
63
  };
60
64
  /** A channel by name, created when missing; a concurrent creator's row is returned instead. */
@@ -77,7 +81,11 @@ const insertChannel = async (db, row) => {
77
81
  throw error;
78
82
  }
79
83
  };
80
- /** 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
+ */
81
89
  const deleteChannel = (db, id) => db.transaction(async (tx) => {
82
90
  const row = await tx.findOne("channels", { id });
83
91
  if (row === null) return {
@@ -97,6 +105,10 @@ const deleteChannel = (db, id) => db.transaction(async (tx) => {
97
105
  deleted: false,
98
106
  reason: "not_empty"
99
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
+ }
100
112
  await tx.delete("channels", row);
101
113
  return { deleted: true };
102
114
  });
@@ -1,4 +1,5 @@
1
1
  import { toChannelRow } from "./reads.mjs";
2
+ import { LABEL_PLATFORMS, labelSequenceId } from "./labels.mjs";
2
3
  import { DatabaseConstraintError } from "@hot-updater/plugin-core";
3
4
  //#region src/core/writes.ts
4
5
  const PAGE = 500;
@@ -29,8 +30,10 @@ const deleteBundle = async (tx, current) => {
29
30
  /**
30
31
  * Replaces a bundle's patches with `rows`: kept patches are updated where
31
32
  * they changed, others deleted or created, so no key is written twice.
33
+ * `checkNew` sees each patch it is about to create, and refuses one by
34
+ * throwing, which leaves the transaction's writes undone.
32
35
  */
33
- const replaceBundlePatches = async (tx, bundle, rows) => {
36
+ const replaceBundlePatches = async (tx, bundle, rows, checkNew) => {
34
37
  const wanted = new Map(rows.map((row) => [row.id, row]));
35
38
  const count = bundle._refs_bundle_patches_bundle_id ?? 0;
36
39
  let cursor;
@@ -55,6 +58,7 @@ const replaceBundlePatches = async (tx, bundle, rows) => {
55
58
  if (page.next === void 0) break;
56
59
  cursor = page.next;
57
60
  }
61
+ if (checkNew !== void 0) for (const row of wanted.values()) await checkNew(row);
58
62
  for (const row of wanted.values()) tx.create("bundle_patches", row);
59
63
  };
60
64
  /** A channel by name, created when missing; a concurrent creator's row is returned instead. */
@@ -77,7 +81,11 @@ const insertChannel = async (db, row) => {
77
81
  throw error;
78
82
  }
79
83
  };
80
- /** 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
+ */
81
89
  const deleteChannel = (db, id) => db.transaction(async (tx) => {
82
90
  const row = await tx.findOne("channels", { id });
83
91
  if (row === null) return {
@@ -97,6 +105,10 @@ const deleteChannel = (db, id) => db.transaction(async (tx) => {
97
105
  deleted: false,
98
106
  reason: "not_empty"
99
107
  };
108
+ for (const platform of LABEL_PLATFORMS) {
109
+ const counter = await tx.findOne("label_sequences", { id: labelSequenceId(id, platform) });
110
+ if (counter !== null) await tx.delete("label_sequences", counter);
111
+ }
100
112
  await tx.delete("channels", row);
101
113
  return { deleted: true };
102
114
  });
@@ -42,10 +42,8 @@ type RuntimeHotUpdaterAPI<TPlugins extends readonly AnyHotUpdaterPlugin[] = read
42
42
  /** The database's name, which `hot-updater db` commands read. */
43
43
  readonly adapterName: string;
44
44
  /**
45
- * Applies aggregate changes the database batches that are still pending:
46
- * this process's buffer, and the log rows no compaction has merged yet.
47
- * A long-lived server with `aggregateBatching: { mode: "memory" }` calls
48
- * it before it exits.
45
+ * Applies the log rows of batched aggregates that no compaction has merged
46
+ * yet. Nothing waits on it: they are durable, and a read compacts first.
49
47
  */
50
48
  readonly flush: () => Promise<void>;
51
49
  /**
@@ -42,10 +42,8 @@ type RuntimeHotUpdaterAPI<TPlugins extends readonly AnyHotUpdaterPlugin[] = read
42
42
  /** The database's name, which `hot-updater db` commands read. */
43
43
  readonly adapterName: string;
44
44
  /**
45
- * Applies aggregate changes the database batches that are still pending:
46
- * this process's buffer, and the log rows no compaction has merged yet.
47
- * A long-lived server with `aggregateBatching: { mode: "memory" }` calls
48
- * it before it exits.
45
+ * Applies the log rows of batched aggregates that no compaction has merged
46
+ * yet. Nothing waits on it: they are durable, and a read compacts first.
49
47
  */
50
48
  readonly flush: () => Promise<void>;
51
49
  /**
@@ -15,20 +15,35 @@ const drizzle = {
15
15
  }
16
16
  };
17
17
  const literal = (value) => JSON.stringify(value);
18
+ /** PostgreSQL's identifier limit, NAMEDATALEN - 1 bytes; longer names are cut. */
19
+ const POSTGRES_NAME_BYTES = 63;
20
+ /**
21
+ * The type drizzle-kit declares for a column. drizzle-kit reads a
22
+ * PostgreSQL column's type without its collation, so a type that names one
23
+ * never matches the database and every push would change it again: the
24
+ * collation goes, and `hot-updater db migrate` sets it.
25
+ */
26
+ const drizzleColumnType = (dialect, type) => dialect === "postgresql" ? type.replace(/ COLLATE "C"$/u, "") : dialect === "sqlite" ? type.toLowerCase() : type;
18
27
  /**
19
28
  * The Drizzle schema `drizzle-kit` applies for the engine's tables: every
20
- * column typed exactly as the engine's DDL, keys, indexes, index tables, and
21
- * the settings table. The engine keeps references itself, so there are no
22
- * foreign keys. `hot-updater db migrate` then writes only the settings rows.
29
+ * column typed as the engine's DDL, keys, indexes, index tables, and the
30
+ * settings table. The engine keeps references itself, so there are no
31
+ * foreign keys. It is what drizzle-kit reads back from the database, so a
32
+ * second `drizzle-kit push` plans nothing: a one-column key is the column's
33
+ * own, a composite key on PostgreSQL is named as PostgreSQL stores its
34
+ * default name, and PostgreSQL types leave out the collation, which
35
+ * `hot-updater db migrate` sets before it writes the settings rows.
23
36
  */
24
37
  const generateDrizzleEngineSchema = (dialect, schema) => {
25
38
  const { module, table: tableFunction } = drizzle[dialect];
26
39
  const tables = [...schema.tables, _hot_updater_plugin_core.SETTINGS_TABLE];
27
40
  const blocks = [];
28
41
  const emit = (shape) => {
29
- const columns = shape.columns.map((column) => ` ${literal(column.name)}: column(${literal(column.type)})(${literal(column.name)})${column.notNull ? ".notNull()" : ""}${column.default === void 0 ? "" : `.default(${column.default})`},`);
42
+ const ownKey = shape.key.length === 1 ? shape.key[0] : void 0;
43
+ const columns = shape.columns.map((column) => ` ${literal(column.name)}: column(${literal(drizzleColumnType(dialect, column.type))})(${literal(column.name)})${column.notNull ? ".notNull()" : ""}${column.name === ownKey ? ".primaryKey()" : ""}${column.default === void 0 ? "" : `.default(${column.default})`},`);
30
44
  const at = (name) => `table[${literal(name)}]`;
31
- const extras = [`primaryKey({ columns: [${shape.key.map(at).join(", ")}] })`, ...shape.indexes.flatMap((index) => index.kind === "index" ? [`${index.unique ? "uniqueIndex" : "index"}(${literal(index.name)}).on(${index.columns.map(at).join(", ")})`] : [])];
45
+ const keyName = `${shape.name}_${shape.key.join("_")}_pk`;
46
+ const extras = [...ownKey === void 0 ? [`primaryKey({ ${dialect !== "sqlite" && keyName.length > POSTGRES_NAME_BYTES ? `name: ${literal(dialect === "mysql" ? `${shape.name}_pk` : keyName.slice(0, POSTGRES_NAME_BYTES))}, ` : ""}columns: [${shape.key.map(at).join(", ")}] })`] : [], ...shape.indexes.flatMap((index) => index.kind === "index" ? [`${index.unique ? "uniqueIndex" : "index"}(${literal(index.name)}).on(${index.columns.map(at).join(", ")})`] : [])];
32
47
  blocks.push(`export const ${shape.name} = ${tableFunction}(${literal(shape.name)}, {\n${columns.join("\n")}\n}, (table) => [\n${extras.map((extra) => ` ${extra},`).join("\n")}\n]);`);
33
48
  for (const index of shape.indexes) if (index.kind === "table") emit(index.table);
34
49
  };
@@ -50,4 +65,5 @@ const generateDrizzleEngineSchema = (dialect, schema) => {
50
65
  ].join("\n");
51
66
  };
52
67
  //#endregion
68
+ exports.drizzleColumnType = drizzleColumnType;
53
69
  exports.generateDrizzleEngineSchema = generateDrizzleEngineSchema;
@@ -15,20 +15,35 @@ const drizzle = {
15
15
  }
16
16
  };
17
17
  const literal = (value) => JSON.stringify(value);
18
+ /** PostgreSQL's identifier limit, NAMEDATALEN - 1 bytes; longer names are cut. */
19
+ const POSTGRES_NAME_BYTES = 63;
20
+ /**
21
+ * The type drizzle-kit declares for a column. drizzle-kit reads a
22
+ * PostgreSQL column's type without its collation, so a type that names one
23
+ * never matches the database and every push would change it again: the
24
+ * collation goes, and `hot-updater db migrate` sets it.
25
+ */
26
+ const drizzleColumnType = (dialect, type) => dialect === "postgresql" ? type.replace(/ COLLATE "C"$/u, "") : dialect === "sqlite" ? type.toLowerCase() : type;
18
27
  /**
19
28
  * The Drizzle schema `drizzle-kit` applies for the engine's tables: every
20
- * column typed exactly as the engine's DDL, keys, indexes, index tables, and
21
- * the settings table. The engine keeps references itself, so there are no
22
- * foreign keys. `hot-updater db migrate` then writes only the settings rows.
29
+ * column typed as the engine's DDL, keys, indexes, index tables, and the
30
+ * settings table. The engine keeps references itself, so there are no
31
+ * foreign keys. It is what drizzle-kit reads back from the database, so a
32
+ * second `drizzle-kit push` plans nothing: a one-column key is the column's
33
+ * own, a composite key on PostgreSQL is named as PostgreSQL stores its
34
+ * default name, and PostgreSQL types leave out the collation, which
35
+ * `hot-updater db migrate` sets before it writes the settings rows.
23
36
  */
24
37
  const generateDrizzleEngineSchema = (dialect, schema) => {
25
38
  const { module, table: tableFunction } = drizzle[dialect];
26
39
  const tables = [...schema.tables, SETTINGS_TABLE];
27
40
  const blocks = [];
28
41
  const emit = (shape) => {
29
- const columns = shape.columns.map((column) => ` ${literal(column.name)}: column(${literal(column.type)})(${literal(column.name)})${column.notNull ? ".notNull()" : ""}${column.default === void 0 ? "" : `.default(${column.default})`},`);
42
+ const ownKey = shape.key.length === 1 ? shape.key[0] : void 0;
43
+ const columns = shape.columns.map((column) => ` ${literal(column.name)}: column(${literal(drizzleColumnType(dialect, column.type))})(${literal(column.name)})${column.notNull ? ".notNull()" : ""}${column.name === ownKey ? ".primaryKey()" : ""}${column.default === void 0 ? "" : `.default(${column.default})`},`);
30
44
  const at = (name) => `table[${literal(name)}]`;
31
- const extras = [`primaryKey({ columns: [${shape.key.map(at).join(", ")}] })`, ...shape.indexes.flatMap((index) => index.kind === "index" ? [`${index.unique ? "uniqueIndex" : "index"}(${literal(index.name)}).on(${index.columns.map(at).join(", ")})`] : [])];
45
+ const keyName = `${shape.name}_${shape.key.join("_")}_pk`;
46
+ const extras = [...ownKey === void 0 ? [`primaryKey({ ${dialect !== "sqlite" && keyName.length > POSTGRES_NAME_BYTES ? `name: ${literal(dialect === "mysql" ? `${shape.name}_pk` : keyName.slice(0, POSTGRES_NAME_BYTES))}, ` : ""}columns: [${shape.key.map(at).join(", ")}] })`] : [], ...shape.indexes.flatMap((index) => index.kind === "index" ? [`${index.unique ? "uniqueIndex" : "index"}(${literal(index.name)}).on(${index.columns.map(at).join(", ")})`] : [])];
32
47
  blocks.push(`export const ${shape.name} = ${tableFunction}(${literal(shape.name)}, {\n${columns.join("\n")}\n}, (table) => [\n${extras.map((extra) => ` ${extra},`).join("\n")}\n]);`);
33
48
  for (const index of shape.indexes) if (index.kind === "table") emit(index.table);
34
49
  };
@@ -50,4 +65,4 @@ const generateDrizzleEngineSchema = (dialect, schema) => {
50
65
  ].join("\n");
51
66
  };
52
67
  //#endregion
53
- export { generateDrizzleEngineSchema };
68
+ export { drizzleColumnType, generateDrizzleEngineSchema };
@@ -65,20 +65,12 @@ const generatePrismaEngineSchema = (provider, schema) => shapesOf(provider, sche
65
65
  return `model ${shape.name} {\n${lines.map((line) => ` ${line}`).join("\n")}\n}`;
66
66
  }).join("\n\n");
67
67
  /**
68
- * The collations Prisma cannot declare, which `hot-updater db migrate` sets
69
- * after Prisma created the tables: `COLLATE "C"` on PostgreSQL and binary
70
- * UTF-8 on MySQL, so strings compare by their bytes as the engine expects.
71
- * The settings table is only read by key, and the migrator has already read
72
- * it: altering it would invalidate PostgreSQL's cached plan for that read.
68
+ * Whether a column's collation is one Prisma cannot declare, which
69
+ * `hot-updater db migrate` sets after Prisma created the tables: `COLLATE "C"`
70
+ * on PostgreSQL and binary UTF-8 on MySQL, so strings compare by their bytes
71
+ * as the engine expects.
73
72
  */
74
- const prismaCollationStatements = (provider, schema) => {
75
- if (provider !== "postgresql" && provider !== "mysql") return [];
76
- const quote = (name) => (0, _hot_updater_plugin_core.quoteSql)(provider, name);
77
- return shapesOf(provider, schema).filter((shape) => shape.name !== _hot_updater_plugin_core.SETTINGS_TABLE.name).flatMap((shape) => {
78
- const changes = shape.columns.filter((column) => prismaColumn(provider, column).collate).map((column) => provider === "postgresql" ? `ALTER COLUMN ${quote(column.name)} TYPE ${column.type}` : `MODIFY ${quote(column.name)} ${column.type}${column.notNull ? " NOT NULL" : " NULL"}`);
79
- return changes.length === 0 ? [] : [`ALTER TABLE ${quote(shape.name)} ${changes.join(", ")}`];
80
- });
81
- };
73
+ const prismaCollates = (provider, column) => prismaColumn(provider, column).collate === true;
82
74
  //#endregion
83
75
  exports.generatePrismaEngineSchema = generatePrismaEngineSchema;
84
- exports.prismaCollationStatements = prismaCollationStatements;
76
+ exports.prismaCollates = prismaCollates;
@@ -1,4 +1,4 @@
1
- import { SETTINGS_TABLE, quoteSql, sqlTableShapes } from "@hot-updater/plugin-core";
1
+ import { SETTINGS_TABLE, sqlTableShapes } from "@hot-updater/plugin-core";
2
2
  //#region src/db/enginePrismaSchema.ts
3
3
  const SCALARS = {
4
4
  TEXT: "String",
@@ -65,19 +65,11 @@ const generatePrismaEngineSchema = (provider, schema) => shapesOf(provider, sche
65
65
  return `model ${shape.name} {\n${lines.map((line) => ` ${line}`).join("\n")}\n}`;
66
66
  }).join("\n\n");
67
67
  /**
68
- * The collations Prisma cannot declare, which `hot-updater db migrate` sets
69
- * after Prisma created the tables: `COLLATE "C"` on PostgreSQL and binary
70
- * UTF-8 on MySQL, so strings compare by their bytes as the engine expects.
71
- * The settings table is only read by key, and the migrator has already read
72
- * it: altering it would invalidate PostgreSQL's cached plan for that read.
68
+ * Whether a column's collation is one Prisma cannot declare, which
69
+ * `hot-updater db migrate` sets after Prisma created the tables: `COLLATE "C"`
70
+ * on PostgreSQL and binary UTF-8 on MySQL, so strings compare by their bytes
71
+ * as the engine expects.
73
72
  */
74
- const prismaCollationStatements = (provider, schema) => {
75
- if (provider !== "postgresql" && provider !== "mysql") return [];
76
- const quote = (name) => quoteSql(provider, name);
77
- return shapesOf(provider, schema).filter((shape) => shape.name !== SETTINGS_TABLE.name).flatMap((shape) => {
78
- const changes = shape.columns.filter((column) => prismaColumn(provider, column).collate).map((column) => provider === "postgresql" ? `ALTER COLUMN ${quote(column.name)} TYPE ${column.type}` : `MODIFY ${quote(column.name)} ${column.type}${column.notNull ? " NOT NULL" : " NULL"}`);
79
- return changes.length === 0 ? [] : [`ALTER TABLE ${quote(shape.name)} ${changes.join(", ")}`];
80
- });
81
- };
73
+ const prismaCollates = (provider, column) => prismaColumn(provider, column).collate === true;
82
74
  //#endregion
83
- export { generatePrismaEngineSchema, prismaCollationStatements };
75
+ export { generatePrismaEngineSchema, prismaCollates };
@@ -20,10 +20,15 @@ const releaseCatalogScopeKeyOf = (input) => input.strategy === "APP_VERSION" ? (
20
20
  platform: input.platform,
21
21
  strategy: "FINGERPRINT"
22
22
  });
23
- /** Projects a stored catalog row for one update check; null when the row is not this scope's. */
24
- const projectReleaseCatalogRow = (row, input, scopeKey = releaseCatalogScopeKeyOf(input)) => {
25
- if (row === null || row.platform !== input.platform || row.strategy !== input.strategy || row.channel_key !== input.channelKey || row.scope_key !== scopeKey || row.fingerprint_hash !== (input.strategy === "FINGERPRINT" ? input.fingerprintHash : null)) return null;
26
- const compiled = parseCompiledCatalog(row.payload, input.strategy);
23
+ const parseReleaseCatalogRow = ({ payload, ...row }) => ({
24
+ row,
25
+ compiled: parseCompiledCatalog(payload, row.strategy)
26
+ });
27
+ /** Projects a parsed catalog row for one update check; null when the row is not this scope's. */
28
+ const projectParsedReleaseCatalogRow = (parsed, input, scopeKey = releaseCatalogScopeKeyOf(input)) => {
29
+ if (parsed === null) return null;
30
+ const { row, compiled } = parsed;
31
+ if (row.platform !== input.platform || row.strategy !== input.strategy || row.channel_key !== input.channelKey || row.scope_key !== scopeKey || row.fingerprint_hash !== (input.strategy === "FINGERPRINT" ? input.fingerprintHash : null)) return null;
27
32
  const appVersion = input.strategy === "APP_VERSION" ? input.appVersion : void 0;
28
33
  return {
29
34
  catalogId: row.catalog_id,
@@ -36,7 +41,11 @@ const projectReleaseCatalogRow = (row, input, scopeKey = releaseCatalogScopeKeyO
36
41
  scopeKey
37
42
  };
38
43
  };
44
+ /** Projects a stored catalog row for one update check; null when the row is not this scope's. */
45
+ const projectReleaseCatalogRow = (row, input, scopeKey = releaseCatalogScopeKeyOf(input)) => projectParsedReleaseCatalogRow(row === null ? null : parseReleaseCatalogRow(row), input, scopeKey);
39
46
  //#endregion
40
47
  exports.parseCompiledCatalog = parseCompiledCatalog;
48
+ exports.parseReleaseCatalogRow = parseReleaseCatalogRow;
49
+ exports.projectParsedReleaseCatalogRow = projectParsedReleaseCatalogRow;
41
50
  exports.projectReleaseCatalogRow = projectReleaseCatalogRow;
42
51
  exports.releaseCatalogScopeKeyOf = releaseCatalogScopeKeyOf;
@@ -20,10 +20,15 @@ const releaseCatalogScopeKeyOf = (input) => input.strategy === "APP_VERSION" ? c
20
20
  platform: input.platform,
21
21
  strategy: "FINGERPRINT"
22
22
  });
23
- /** Projects a stored catalog row for one update check; null when the row is not this scope's. */
24
- const projectReleaseCatalogRow = (row, input, scopeKey = releaseCatalogScopeKeyOf(input)) => {
25
- if (row === null || row.platform !== input.platform || row.strategy !== input.strategy || row.channel_key !== input.channelKey || row.scope_key !== scopeKey || row.fingerprint_hash !== (input.strategy === "FINGERPRINT" ? input.fingerprintHash : null)) return null;
26
- const compiled = parseCompiledCatalog(row.payload, input.strategy);
23
+ const parseReleaseCatalogRow = ({ payload, ...row }) => ({
24
+ row,
25
+ compiled: parseCompiledCatalog(payload, row.strategy)
26
+ });
27
+ /** Projects a parsed catalog row for one update check; null when the row is not this scope's. */
28
+ const projectParsedReleaseCatalogRow = (parsed, input, scopeKey = releaseCatalogScopeKeyOf(input)) => {
29
+ if (parsed === null) return null;
30
+ const { row, compiled } = parsed;
31
+ if (row.platform !== input.platform || row.strategy !== input.strategy || row.channel_key !== input.channelKey || row.scope_key !== scopeKey || row.fingerprint_hash !== (input.strategy === "FINGERPRINT" ? input.fingerprintHash : null)) return null;
27
32
  const appVersion = input.strategy === "APP_VERSION" ? input.appVersion : void 0;
28
33
  return {
29
34
  catalogId: row.catalog_id,
@@ -36,5 +41,7 @@ const projectReleaseCatalogRow = (row, input, scopeKey = releaseCatalogScopeKeyO
36
41
  scopeKey
37
42
  };
38
43
  };
44
+ /** Projects a stored catalog row for one update check; null when the row is not this scope's. */
45
+ const projectReleaseCatalogRow = (row, input, scopeKey = releaseCatalogScopeKeyOf(input)) => projectParsedReleaseCatalogRow(row === null ? null : parseReleaseCatalogRow(row), input, scopeKey);
39
46
  //#endregion
40
- export { parseCompiledCatalog, projectReleaseCatalogRow, releaseCatalogScopeKeyOf };
47
+ export { parseCompiledCatalog, parseReleaseCatalogRow, projectParsedReleaseCatalogRow, projectReleaseCatalogRow, releaseCatalogScopeKeyOf };
package/dist/handler.cjs CHANGED
@@ -41,7 +41,8 @@ const createRequestHandler = ({ api, clientPolicy, privateResponses = false, rou
41
41
  let authenticated;
42
42
  try {
43
43
  authenticated = await clientPolicy.authenticate(request);
44
- } catch {
44
+ } catch (error) {
45
+ console.error("Hot Updater client authentication error:", error);
45
46
  return errorResponse("Service unavailable", 503);
46
47
  }
47
48
  if (!authenticated) return errorResponse("Unauthorized", 401);