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

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 (49) 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 +39 -1
  19. package/dist/core/api.d.mts +39 -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/nativeBuildDestinations.cjs +13 -0
  24. package/dist/core/nativeBuildDestinations.mjs +13 -0
  25. package/dist/core/nativeBuilds.cjs +291 -22
  26. package/dist/core/nativeBuilds.mjs +291 -23
  27. package/dist/core/operations.cjs +8 -22
  28. package/dist/core/operations.mjs +11 -25
  29. package/dist/core/reads.cjs +44 -4
  30. package/dist/core/reads.mjs +44 -4
  31. package/dist/core/releases.cjs +78 -26
  32. package/dist/core/releases.mjs +79 -29
  33. package/dist/core/writes.cjs +4 -1
  34. package/dist/core/writes.mjs +4 -1
  35. package/dist/createHotUpdaterCore.d.cts +2 -4
  36. package/dist/createHotUpdaterCore.d.mts +2 -4
  37. package/dist/db/engineDrizzleSchema.cjs +21 -5
  38. package/dist/db/engineDrizzleSchema.mjs +21 -6
  39. package/dist/db/enginePrismaSchema.cjs +6 -14
  40. package/dist/db/enginePrismaSchema.mjs +7 -15
  41. package/dist/db/releaseCatalog.cjs +13 -4
  42. package/dist/db/releaseCatalog.mjs +12 -5
  43. package/dist/handlerAdminRoutes.cjs +254 -16
  44. package/dist/handlerAdminRoutes.mjs +255 -17
  45. package/dist/handlerReleaseCatalogRoutes.cjs +43 -27
  46. package/dist/handlerReleaseCatalogRoutes.mjs +43 -27
  47. package/dist/package.cjs +1 -1
  48. package/dist/package.mjs +1 -1
  49. package/package.json +7 -14
@@ -74,8 +74,16 @@ const drain = async (read) => {
74
74
  return rows;
75
75
  };
76
76
  /** 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. */
77
+ /** A keyset read's range on its index's order: past `after`, up to `through`. */
78
+ const after = (input) => {
79
+ const asc = (input.order ?? "asc") === "asc";
80
+ const range = {
81
+ ...input.after === void 0 ? {} : asc ? { gt: input.after } : { lt: input.after },
82
+ ...input.through === void 0 ? {} : asc ? { lte: input.through } : { gte: input.through }
83
+ };
84
+ return Object.keys(range).length === 0 ? {} : { range };
85
+ };
86
+ /** Core's reads, each through one declared index or key; plugins get `CoreReads`. */
79
87
  const createCoreReads = (db, storage) => {
80
88
  /** A bundle row's patches, exactly as many as its reference counter holds. */
81
89
  const detail = async (row) => {
@@ -263,8 +271,35 @@ const createCoreReads = (db, storage) => {
263
271
  ...after(input)
264
272
  })).rows.map(toCatalogRow);
265
273
  },
266
- /** Every channel, by name. */
267
- async listChannels() {
274
+ /**
275
+ * Up to `limit` scope keys that have releases, ascending after `after`:
276
+ * one limit-1 seek of the `scopes` index past each scope, so the reads
277
+ * grow with the scopes, not with their releases.
278
+ */
279
+ async listReleaseScopeKeys(input) {
280
+ const scopeKeys = [];
281
+ for (let last = input.after ?? ""; scopeKeys.length < input.limit;) {
282
+ const { rows } = await db.findMany("releases", {
283
+ index: "scopes",
284
+ where: {},
285
+ limit: 1,
286
+ range: { gt: last }
287
+ });
288
+ if (rows[0] === void 0) break;
289
+ last = rows[0].scope_key;
290
+ scopeKeys.push(last);
291
+ }
292
+ return scopeKeys;
293
+ },
294
+ /** Every channel by name; with `input`, one keyset page of them. */
295
+ async listChannels(input) {
296
+ if (input !== void 0) return (await db.findMany("channels", {
297
+ index: "all",
298
+ where: {},
299
+ order: input.order ?? "asc",
300
+ limit: input.limit,
301
+ ...after(input)
302
+ })).rows.map(toChannelRow);
268
303
  return (await drain((page) => db.findMany("channels", {
269
304
  index: "all",
270
305
  where: {},
@@ -272,6 +307,11 @@ const createCoreReads = (db, storage) => {
272
307
  ...page
273
308
  }))).map(toChannelRow);
274
309
  },
310
+ async getChannels(ids) {
311
+ const unique = [...new Set(ids)];
312
+ if (unique.length === 0) return [];
313
+ return (await db.findByKeys("channels", unique.map((id) => ({ id })))).flatMap((row) => row ? [toChannelRow(row)] : []);
314
+ },
275
315
  async findChannelByName(name) {
276
316
  const row = await db.findOne("channels", { name });
277
317
  return row === null ? null : toChannelRow(row);
@@ -21,25 +21,28 @@ const checkScope = (scope) => {
21
21
  });
22
22
  if (scope.strategy === "FINGERPRINT" !== (scope.fingerprintHash !== null) || scope.scopeKey !== expected) fail("INVALID_SCOPE", "Release catalog scope metadata is inconsistent");
23
23
  };
24
- /** A scope's enabled releases, all of them, under the catalog's guard. */
25
- const enabledReleases = async (tx, scopeKey) => {
24
+ /** Every row of a paged read, as release rows. */
25
+ const drainReleases = async (page) => {
26
26
  const rows = [];
27
27
  let cursor;
28
28
  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;
29
+ const found = await page(cursor);
30
+ rows.push(...found.rows.map((row) => require_reads.toReleaseRow(row)));
31
+ cursor = found.next;
40
32
  } while (cursor !== void 0);
41
33
  return rows;
42
34
  };
35
+ const enabledIn = (scopeKey, cursor) => ({
36
+ index: "byScopeEnabled",
37
+ where: {
38
+ scope_key: scopeKey,
39
+ enabled: true
40
+ },
41
+ limit: PAGE,
42
+ ...cursor === void 0 ? {} : { cursor }
43
+ });
44
+ /** A scope's enabled releases, all of them, under the catalog's guard. */
45
+ const enabledReleases = (tx, scopeKey) => drainReleases((cursor) => tx.findMany("releases", enabledIn(scopeKey, cursor)));
43
46
  /** The scope's newest release id: `byScope` descending, limit 1. */
44
47
  const latestReleaseId = async (tx, scopeKey) => {
45
48
  const { rows } = await tx.findMany("releases", {
@@ -50,15 +53,11 @@ const latestReleaseId = async (tx, scopeKey) => {
50
53
  });
51
54
  return rows[0]?.id ?? null;
52
55
  };
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;
56
+ /** The scope's next catalog generation, compiled as `compilation`. */
57
+ const nextCatalog = (scope, stored, compilation, updatedAtMs) => {
58
+ const generation = (stored.catalog?.generation ?? 0) + 1;
60
59
  if (!Number.isSafeInteger(generation)) fail("CATALOG_GENERATION_EXHAUSTED", `Catalog "${scope.scopeKey}" exhausted its generation counter`);
61
- const catalog = {
60
+ return {
62
61
  scope_key: scope.scopeKey,
63
62
  catalog_id: stored.catalog?.catalog_id ?? (0, _hot_updater_plugin_core.createUUIDv7)(),
64
63
  strategy: scope.strategy,
@@ -73,6 +72,26 @@ const writeCatalog = async (tx, scope, stored, enabled, updatedAtMs) => {
73
72
  is_tombstone: compilation.payload.releaseDescriptors.length === 0,
74
73
  updated_at_ms: updatedAtMs
75
74
  };
75
+ };
76
+ /**
77
+ * Compiles a scope's enabled releases. A catalog over the size limit is
78
+ * refused naming its channel and platform, and what frees room in it.
79
+ */
80
+ const compileScope = async (scope, enabled) => {
81
+ try {
82
+ return await (0, _hot_updater_plugin_core.compileReleaseCatalog)({
83
+ strategy: scope.strategy,
84
+ releases: enabled.map(_hot_updater_plugin_core.releaseRowToRelease)
85
+ });
86
+ } catch (error) {
87
+ if (!(error instanceof _hot_updater_plugin_core.ReleaseCatalogCompilationError) || error.code !== "CATALOG_OVERSIZE") throw error;
88
+ 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.`);
89
+ }
90
+ };
91
+ /** Compiles `enabled` and writes it as the scope's next catalog generation. */
92
+ const writeCatalog = async (tx, scope, stored, enabled, updatedAtMs) => {
93
+ const compilation = await compileScope(scope, enabled);
94
+ const catalog = nextCatalog(scope, stored, compilation, updatedAtMs);
76
95
  const { scope_key: _scopeKey, ...set } = catalog;
77
96
  if (stored.row === null) tx.create("release_catalogs", catalog);
78
97
  else tx.update("release_catalogs", stored.row, set);
@@ -161,18 +180,49 @@ const changeReleases = (db, inputs) => {
161
180
  return results;
162
181
  });
163
182
  };
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;
185
+ /** The scope a catalog row names. */
186
+ const catalogRowScope = (row) => ({
187
+ channelId: row.channel_id,
188
+ channelName: (0, _hot_updater_protocol.decodeChannelKey)(row.channel_key),
189
+ fingerprintHash: row.fingerprint_hash,
190
+ platform: row.platform,
191
+ scopeKey: row.scope_key,
192
+ strategy: row.strategy
193
+ });
194
+ /**
195
+ * What a rebuild of the scope's catalog would write, without writing: one
196
+ * read of the catalog row and one of the scope's enabled releases. It needs
197
+ * no transaction, whose guards would read the catalog again for each read
198
+ * beneath it, nor the scope's newest release, which matters only to a scope
199
+ * without a catalog row; that one is not found.
200
+ */
201
+ const preflightRebuild = async (db, scopeKey, updatedAtMs) => {
202
+ const row = await db.findOne("release_catalogs", { scope_key: scopeKey });
203
+ if (row === null) throw new Error(`Release catalog "${scopeKey}" was not found.`);
204
+ const current = require_reads.toCatalogRow(row);
205
+ const scope = catalogRowScope(current);
206
+ checkScope(scope);
207
+ const enabled = await drainReleases((cursor) => db.findMany("releases", enabledIn(scopeKey, cursor)));
208
+ const compilation = await compileScope(scope, enabled);
209
+ const changed = !isCurrent(scope, current, compilation);
210
+ return {
211
+ changed,
212
+ currentCatalog: current,
213
+ diagnostics: compilation.diagnostics,
214
+ projectedCatalog: changed ? nextCatalog(scope, { catalog: current }, compilation, updatedAtMs) : current
215
+ };
216
+ };
164
217
  /** Recompiles a scope's catalog from its enabled releases inside `tx`; an unchanged catalog is not rewritten. */
165
218
  const rebuildScope = async (tx, scope, updatedAtMs) => {
166
219
  checkScope(scope);
167
220
  const stored = await readCatalog(tx, scope.scopeKey);
168
221
  assertHistory(stored, await latestReleaseId(tx, scope.scopeKey) !== null);
169
222
  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
- });
223
+ const compilation = await compileScope(scope, enabled);
174
224
  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 {
225
+ if (current !== null && isCurrent(scope, current, compilation)) return {
176
226
  catalog: current,
177
227
  current,
178
228
  changed: false,
@@ -187,7 +237,9 @@ const rebuildScope = async (tx, scope, updatedAtMs) => {
187
237
  };
188
238
  };
189
239
  //#endregion
240
+ exports.catalogRowScope = catalogRowScope;
190
241
  exports.changeRelease = changeRelease;
191
242
  exports.changeReleases = changeReleases;
243
+ exports.preflightRebuild = preflightRebuild;
192
244
  exports.readCatalog = readCatalog;
193
245
  exports.rebuildScope = rebuildScope;
@@ -1,7 +1,7 @@
1
1
  import { toCatalogRow, toReleaseRow } from "./reads.mjs";
2
2
  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";
3
+ import { ReleaseCatalogCompilationError, ReleaseCatalogMutationError, compileReleaseCatalog, createUUIDv7, createUUIDv7After, isUUIDv7, releaseRowToRelease } from "@hot-updater/plugin-core";
4
+ import { MAX_COMPILED_CATALOG_BYTES, createReleaseCatalogScopeKey, decodeChannelKey, encodeChannelKey } from "@hot-updater/protocol";
5
5
  //#region src/core/releases.ts
6
6
  const PAGE = 500;
7
7
  const fail = (code, message) => {
@@ -21,25 +21,28 @@ const checkScope = (scope) => {
21
21
  });
22
22
  if (scope.strategy === "FINGERPRINT" !== (scope.fingerprintHash !== null) || scope.scopeKey !== expected) fail("INVALID_SCOPE", "Release catalog scope metadata is inconsistent");
23
23
  };
24
- /** A scope's enabled releases, all of them, under the catalog's guard. */
25
- const enabledReleases = async (tx, scopeKey) => {
24
+ /** Every row of a paged read, as release rows. */
25
+ const drainReleases = async (page) => {
26
26
  const rows = [];
27
27
  let cursor;
28
28
  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;
29
+ const found = await page(cursor);
30
+ rows.push(...found.rows.map((row) => toReleaseRow(row)));
31
+ cursor = found.next;
40
32
  } while (cursor !== void 0);
41
33
  return rows;
42
34
  };
35
+ const enabledIn = (scopeKey, cursor) => ({
36
+ index: "byScopeEnabled",
37
+ where: {
38
+ scope_key: scopeKey,
39
+ enabled: true
40
+ },
41
+ limit: PAGE,
42
+ ...cursor === void 0 ? {} : { cursor }
43
+ });
44
+ /** A scope's enabled releases, all of them, under the catalog's guard. */
45
+ const enabledReleases = (tx, scopeKey) => drainReleases((cursor) => tx.findMany("releases", enabledIn(scopeKey, cursor)));
43
46
  /** The scope's newest release id: `byScope` descending, limit 1. */
44
47
  const latestReleaseId = async (tx, scopeKey) => {
45
48
  const { rows } = await tx.findMany("releases", {
@@ -50,15 +53,11 @@ const latestReleaseId = async (tx, scopeKey) => {
50
53
  });
51
54
  return rows[0]?.id ?? null;
52
55
  };
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;
56
+ /** The scope's next catalog generation, compiled as `compilation`. */
57
+ const nextCatalog = (scope, stored, compilation, updatedAtMs) => {
58
+ const generation = (stored.catalog?.generation ?? 0) + 1;
60
59
  if (!Number.isSafeInteger(generation)) fail("CATALOG_GENERATION_EXHAUSTED", `Catalog "${scope.scopeKey}" exhausted its generation counter`);
61
- const catalog = {
60
+ return {
62
61
  scope_key: scope.scopeKey,
63
62
  catalog_id: stored.catalog?.catalog_id ?? createUUIDv7(),
64
63
  strategy: scope.strategy,
@@ -73,6 +72,26 @@ const writeCatalog = async (tx, scope, stored, enabled, updatedAtMs) => {
73
72
  is_tombstone: compilation.payload.releaseDescriptors.length === 0,
74
73
  updated_at_ms: updatedAtMs
75
74
  };
75
+ };
76
+ /**
77
+ * Compiles a scope's enabled releases. A catalog over the size limit is
78
+ * refused naming its channel and platform, and what frees room in it.
79
+ */
80
+ const compileScope = async (scope, enabled) => {
81
+ try {
82
+ return await compileReleaseCatalog({
83
+ strategy: scope.strategy,
84
+ releases: enabled.map(releaseRowToRelease)
85
+ });
86
+ } catch (error) {
87
+ if (!(error instanceof ReleaseCatalogCompilationError) || error.code !== "CATALOG_OVERSIZE") throw error;
88
+ 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.`);
89
+ }
90
+ };
91
+ /** Compiles `enabled` and writes it as the scope's next catalog generation. */
92
+ const writeCatalog = async (tx, scope, stored, enabled, updatedAtMs) => {
93
+ const compilation = await compileScope(scope, enabled);
94
+ const catalog = nextCatalog(scope, stored, compilation, updatedAtMs);
76
95
  const { scope_key: _scopeKey, ...set } = catalog;
77
96
  if (stored.row === null) tx.create("release_catalogs", catalog);
78
97
  else tx.update("release_catalogs", stored.row, set);
@@ -161,18 +180,49 @@ const changeReleases = (db, inputs) => {
161
180
  return results;
162
181
  });
163
182
  };
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;
185
+ /** The scope a catalog row names. */
186
+ const catalogRowScope = (row) => ({
187
+ channelId: row.channel_id,
188
+ channelName: decodeChannelKey(row.channel_key),
189
+ fingerprintHash: row.fingerprint_hash,
190
+ platform: row.platform,
191
+ scopeKey: row.scope_key,
192
+ strategy: row.strategy
193
+ });
194
+ /**
195
+ * What a rebuild of the scope's catalog would write, without writing: one
196
+ * read of the catalog row and one of the scope's enabled releases. It needs
197
+ * no transaction, whose guards would read the catalog again for each read
198
+ * beneath it, nor the scope's newest release, which matters only to a scope
199
+ * without a catalog row; that one is not found.
200
+ */
201
+ const preflightRebuild = async (db, scopeKey, updatedAtMs) => {
202
+ const row = await db.findOne("release_catalogs", { scope_key: scopeKey });
203
+ if (row === null) throw new Error(`Release catalog "${scopeKey}" was not found.`);
204
+ const current = toCatalogRow(row);
205
+ const scope = catalogRowScope(current);
206
+ checkScope(scope);
207
+ const enabled = await drainReleases((cursor) => db.findMany("releases", enabledIn(scopeKey, cursor)));
208
+ const compilation = await compileScope(scope, enabled);
209
+ const changed = !isCurrent(scope, current, compilation);
210
+ return {
211
+ changed,
212
+ currentCatalog: current,
213
+ diagnostics: compilation.diagnostics,
214
+ projectedCatalog: changed ? nextCatalog(scope, { catalog: current }, compilation, updatedAtMs) : current
215
+ };
216
+ };
164
217
  /** Recompiles a scope's catalog from its enabled releases inside `tx`; an unchanged catalog is not rewritten. */
165
218
  const rebuildScope = async (tx, scope, updatedAtMs) => {
166
219
  checkScope(scope);
167
220
  const stored = await readCatalog(tx, scope.scopeKey);
168
221
  assertHistory(stored, await latestReleaseId(tx, scope.scopeKey) !== null);
169
222
  const enabled = await enabledReleases(tx, scope.scopeKey);
170
- const compilation = await compileReleaseCatalog({
171
- strategy: scope.strategy,
172
- releases: enabled.map(releaseRowToRelease)
173
- });
223
+ const compilation = await compileScope(scope, enabled);
174
224
  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 {
225
+ if (current !== null && isCurrent(scope, current, compilation)) return {
176
226
  catalog: current,
177
227
  current,
178
228
  changed: false,
@@ -187,4 +237,4 @@ const rebuildScope = async (tx, scope, updatedAtMs) => {
187
237
  };
188
238
  };
189
239
  //#endregion
190
- export { changeRelease, changeReleases, readCatalog, rebuildScope };
240
+ export { catalogRowScope, changeRelease, changeReleases, preflightRebuild, readCatalog, rebuildScope };
@@ -29,8 +29,10 @@ const deleteBundle = async (tx, current) => {
29
29
  /**
30
30
  * Replaces a bundle's patches with `rows`: kept patches are updated where
31
31
  * they changed, others deleted or created, so no key is written twice.
32
+ * `checkNew` sees each patch it is about to create, and refuses one by
33
+ * throwing, which leaves the transaction's writes undone.
32
34
  */
33
- const replaceBundlePatches = async (tx, bundle, rows) => {
35
+ const replaceBundlePatches = async (tx, bundle, rows, checkNew) => {
34
36
  const wanted = new Map(rows.map((row) => [row.id, row]));
35
37
  const count = bundle._refs_bundle_patches_bundle_id ?? 0;
36
38
  let cursor;
@@ -55,6 +57,7 @@ const replaceBundlePatches = async (tx, bundle, rows) => {
55
57
  if (page.next === void 0) break;
56
58
  cursor = page.next;
57
59
  }
60
+ if (checkNew !== void 0) for (const row of wanted.values()) await checkNew(row);
58
61
  for (const row of wanted.values()) tx.create("bundle_patches", row);
59
62
  };
60
63
  /** A channel by name, created when missing; a concurrent creator's row is returned instead. */
@@ -29,8 +29,10 @@ const deleteBundle = async (tx, current) => {
29
29
  /**
30
30
  * Replaces a bundle's patches with `rows`: kept patches are updated where
31
31
  * they changed, others deleted or created, so no key is written twice.
32
+ * `checkNew` sees each patch it is about to create, and refuses one by
33
+ * throwing, which leaves the transaction's writes undone.
32
34
  */
33
- const replaceBundlePatches = async (tx, bundle, rows) => {
35
+ const replaceBundlePatches = async (tx, bundle, rows, checkNew) => {
34
36
  const wanted = new Map(rows.map((row) => [row.id, row]));
35
37
  const count = bundle._refs_bundle_patches_bundle_id ?? 0;
36
38
  let cursor;
@@ -55,6 +57,7 @@ const replaceBundlePatches = async (tx, bundle, rows) => {
55
57
  if (page.next === void 0) break;
56
58
  cursor = page.next;
57
59
  }
60
+ if (checkNew !== void 0) for (const row of wanted.values()) await checkNew(row);
58
61
  for (const row of wanted.values()) tx.create("bundle_patches", row);
59
62
  };
60
63
  /** A channel by name, created when missing; a concurrent creator's row is returned instead. */
@@ -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;