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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (51) hide show
  1. package/dist/adapters/drizzle.cjs +8 -4
  2. package/dist/adapters/drizzle.d.cts +3 -2
  3. package/dist/adapters/drizzle.d.mts +3 -2
  4. package/dist/adapters/drizzle.mjs +8 -4
  5. package/dist/adapters/drizzleExecutor.cjs +4 -2
  6. package/dist/adapters/drizzleExecutor.mjs +4 -2
  7. package/dist/adapters/kysely.cjs +3 -2
  8. package/dist/adapters/kysely.mjs +3 -2
  9. package/dist/adapters/mongodb.cjs +1 -1
  10. package/dist/adapters/mongodb.mjs +1 -1
  11. package/dist/adapters/mongodbAdapter.cjs +15 -3
  12. package/dist/adapters/mongodbAdapter.mjs +15 -3
  13. package/dist/adapters/prisma.cjs +9 -13
  14. package/dist/adapters/prisma.mjs +10 -14
  15. package/dist/adapters/prismaExecutor.cjs +25 -20
  16. package/dist/adapters/prismaExecutor.mjs +25 -20
  17. package/dist/core/api.cjs +2 -0
  18. package/dist/core/api.d.cts +48 -1
  19. package/dist/core/api.d.mts +48 -1
  20. package/dist/core/api.mjs +2 -0
  21. package/dist/core/iosDevices.cjs +306 -0
  22. package/dist/core/iosDevices.mjs +303 -0
  23. package/dist/core/labels.cjs +317 -0
  24. package/dist/core/labels.mjs +310 -0
  25. package/dist/core/nativeBuildDestinations.cjs +13 -0
  26. package/dist/core/nativeBuildDestinations.mjs +13 -0
  27. package/dist/core/nativeBuilds.cjs +291 -22
  28. package/dist/core/nativeBuilds.mjs +291 -23
  29. package/dist/core/operations.cjs +45 -24
  30. package/dist/core/operations.mjs +48 -27
  31. package/dist/core/reads.cjs +69 -5
  32. package/dist/core/reads.mjs +70 -6
  33. package/dist/core/releases.cjs +121 -38
  34. package/dist/core/releases.mjs +121 -41
  35. package/dist/core/writes.cjs +14 -2
  36. package/dist/core/writes.mjs +14 -2
  37. package/dist/createHotUpdaterCore.d.cts +2 -4
  38. package/dist/createHotUpdaterCore.d.mts +2 -4
  39. package/dist/db/engineDrizzleSchema.cjs +21 -5
  40. package/dist/db/engineDrizzleSchema.mjs +21 -6
  41. package/dist/db/enginePrismaSchema.cjs +6 -14
  42. package/dist/db/enginePrismaSchema.mjs +7 -15
  43. package/dist/db/releaseCatalog.cjs +13 -4
  44. package/dist/db/releaseCatalog.mjs +12 -5
  45. package/dist/handlerAdminRoutes.cjs +288 -16
  46. package/dist/handlerAdminRoutes.mjs +289 -17
  47. package/dist/handlerReleaseCatalogRoutes.cjs +43 -27
  48. package/dist/handlerReleaseCatalogRoutes.mjs +43 -27
  49. package/dist/package.cjs +1 -1
  50. package/dist/package.mjs +1 -1
  51. package/package.json +7 -14
@@ -1,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, 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);
@@ -94,11 +114,16 @@ const readCatalog = async (tx, scopeKey) => {
94
114
  const assertHistory = (stored, hasReleases) => {
95
115
  if (stored.catalog === null && hasReleases) fail("CATALOG_IDENTITY_MISSING", "Catalog history is missing. Restore its catalog row from backup before rebuilding or deploying.");
96
116
  };
97
- /** One release change and its scope's next catalog, inside `tx`. */
98
- const changeRelease = async (tx, { scope, change, bundle, updatedAtMs }) => {
117
+ /**
118
+ * One release change and its scope's next catalog, inside `tx`. An insert
119
+ * takes its channel and platform's next label from `labels`, after labeling
120
+ * the releases a server of an earlier release wrote in the scope since its
121
+ * last labeled one.
122
+ */
123
+ const changeRelease = async (tx, { scope, change, bundle, updatedAtMs }, labels) => {
99
124
  checkScope(scope);
100
125
  const stored = await readCatalog(tx, scope.scopeKey);
101
- const enabled = await enabledReleases(tx, scope.scopeKey);
126
+ let enabled = await enabledReleases(tx, scope.scopeKey);
102
127
  if (bundle !== void 0) {
103
128
  insertBundle(tx, bundle.row);
104
129
  for (const patch of bundle.patches) tx.create("bundle_patches", patch);
@@ -106,14 +131,22 @@ const changeRelease = async (tx, { scope, change, bundle, updatedAtMs }) => {
106
131
  let before = null;
107
132
  let release;
108
133
  if (change.operation === "insert") {
109
- const latest = await latestReleaseId(tx, scope.scopeKey);
134
+ if (labels === void 0) throw new Error("A release insert takes its label from an allocator.");
135
+ const newest = await latestRelease(tx, scope.scopeKey);
136
+ const latest = newest?.id ?? null;
110
137
  assertHistory(stored, latest !== null);
111
138
  const floor = [latest, bundle && isUUIDv7(bundle.row.id) ? bundle.row.id : null].filter((id) => id !== null).sort().at(-1);
112
139
  const id = change.row.id ?? createUUIDv7After(floor ?? null);
113
140
  if (latest !== null && id <= latest) fail("NON_MONOTONIC_RELEASE_ID", `Release "${id}" must sort after "${latest}"`);
141
+ const given = await catchUpLabels(tx, labels, newest);
142
+ if (given.size > 0) enabled = enabled.map((row) => given.has(row.id) ? {
143
+ ...row,
144
+ label: given.get(row.id)
145
+ } : row);
114
146
  release = {
115
147
  ...change.row,
116
- id
148
+ id,
149
+ label: await labels.next(scope.channelId, scope.platform)
117
150
  };
118
151
  if (release.scope_key !== scope.scopeKey || release.channel_id !== scope.channelId || release.platform !== scope.platform || release.strategy !== scope.strategy || release.fingerprint_hash !== scope.fingerprintHash || release.revision !== 1) fail("INVALID_SCOPE", "Inserted Release does not match its catalog scope");
119
152
  tx.create("releases", release);
@@ -126,8 +159,9 @@ const changeRelease = async (tx, { scope, change, bundle, updatedAtMs }) => {
126
159
  await tx.delete("releases", row);
127
160
  release = null;
128
161
  } else {
162
+ const { label: _label, ...update } = change.update;
129
163
  const set = {
130
- ...change.update,
164
+ ...update,
131
165
  revision: before.revision + 1
132
166
  };
133
167
  tx.update("releases", row, set);
@@ -155,24 +189,70 @@ const changeRelease = async (tx, { scope, change, bundle, updatedAtMs }) => {
155
189
  */
156
190
  const changeReleases = (db, inputs) => {
157
191
  if (new Set(inputs.map(({ scope }) => scope.scopeKey)).size !== inputs.length) fail("INVALID_SCOPE", "A batch cannot change one catalog scope twice");
158
- return db.transaction(async (tx) => {
192
+ return writeWithLabels(db, async (tx, labels) => {
159
193
  const results = [];
160
- for (const input of inputs) results.push(await changeRelease(tx, input));
194
+ for (const input of inputs) results.push(await changeRelease(tx, input, labels));
161
195
  return results;
162
196
  });
163
197
  };
198
+ /** Whether `current` is what the scope's enabled releases compile to. */
199
+ const isCurrent = (scope, current, compilation) => current.strategy === scope.strategy && current.channel_id === scope.channelId && current.channel_key === encodeChannelKey(scope.channelName) && current.platform === scope.platform && current.fingerprint_hash === scope.fingerprintHash && current.catalog_hash === compilation.catalogHash;
200
+ /** A compiled payload with its descriptors' labels left out. */
201
+ const withoutLabels = (payload) => {
202
+ const parsed = JSON.parse(payload);
203
+ return JSON.stringify({
204
+ ...parsed,
205
+ releaseDescriptors: (parsed.releaseDescriptors ?? []).map(({ label: _label, ...descriptor }) => descriptor)
206
+ });
207
+ };
208
+ /**
209
+ * Whether `projected` differs from `current` only by release labels, as a
210
+ * catalog compiled before its releases had them does.
211
+ */
212
+ const differsInLabelsOnly = (current, projected) => current.payload !== projected.payload && current.strategy === projected.strategy && current.channel_id === projected.channel_id && current.channel_key === projected.channel_key && current.platform === projected.platform && current.fingerprint_hash === projected.fingerprint_hash && withoutLabels(current.payload) === withoutLabels(projected.payload);
213
+ /** The scope a catalog row names. */
214
+ const catalogRowScope = (row) => ({
215
+ channelId: row.channel_id,
216
+ channelName: decodeChannelKey(row.channel_key),
217
+ fingerprintHash: row.fingerprint_hash,
218
+ platform: row.platform,
219
+ scopeKey: row.scope_key,
220
+ strategy: row.strategy
221
+ });
222
+ /**
223
+ * What a rebuild of the scope's catalog would write, without writing: one
224
+ * read of the catalog row and one of the scope's enabled releases. It needs
225
+ * no transaction, whose guards would read the catalog again for each read
226
+ * beneath it, nor the scope's newest release, which matters only to a scope
227
+ * without a catalog row; that one is not found.
228
+ */
229
+ const preflightRebuild = async (db, scopeKey, updatedAtMs) => {
230
+ const row = await db.findOne("release_catalogs", { scope_key: scopeKey });
231
+ if (row === null) throw new Error(`Release catalog "${scopeKey}" was not found.`);
232
+ const current = toCatalogRow(row);
233
+ const scope = catalogRowScope(current);
234
+ checkScope(scope);
235
+ const enabled = await drainReleases((cursor) => db.findMany("releases", enabledIn(scopeKey, cursor)));
236
+ const compilation = await compileScope(scope, enabled);
237
+ const changed = !isCurrent(scope, current, compilation);
238
+ const projectedCatalog = changed ? nextCatalog(scope, { catalog: current }, compilation, updatedAtMs) : current;
239
+ return {
240
+ changed,
241
+ labelsOnly: changed && differsInLabelsOnly(current, projectedCatalog),
242
+ currentCatalog: current,
243
+ diagnostics: compilation.diagnostics,
244
+ projectedCatalog
245
+ };
246
+ };
164
247
  /** Recompiles a scope's catalog from its enabled releases inside `tx`; an unchanged catalog is not rewritten. */
165
248
  const rebuildScope = async (tx, scope, updatedAtMs) => {
166
249
  checkScope(scope);
167
250
  const stored = await readCatalog(tx, scope.scopeKey);
168
- assertHistory(stored, await latestReleaseId(tx, scope.scopeKey) !== null);
251
+ assertHistory(stored, await latestRelease(tx, scope.scopeKey) !== null);
169
252
  const enabled = await enabledReleases(tx, scope.scopeKey);
170
- const compilation = await compileReleaseCatalog({
171
- strategy: scope.strategy,
172
- releases: enabled.map(releaseRowToRelease)
173
- });
253
+ const compilation = await compileScope(scope, enabled);
174
254
  const current = stored.catalog;
175
- if (current !== null && current.strategy === scope.strategy && current.channel_id === scope.channelId && current.channel_key === encodeChannelKey(scope.channelName) && current.platform === scope.platform && current.fingerprint_hash === scope.fingerprintHash && current.catalog_hash === compilation.catalogHash) return {
255
+ if (current !== null && isCurrent(scope, current, compilation)) return {
176
256
  catalog: current,
177
257
  current,
178
258
  changed: false,
@@ -187,4 +267,4 @@ const rebuildScope = async (tx, scope, updatedAtMs) => {
187
267
  };
188
268
  };
189
269
  //#endregion
190
- export { changeRelease, changeReleases, readCatalog, rebuildScope };
270
+ 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 };