@hot-updater/server 1.0.0-rc.0 → 1.0.0-rc.14

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 (213) hide show
  1. package/dist/_virtual/_rolldown/runtime.cjs +1 -1
  2. package/dist/adapters/databaseConstraintErrors.cjs +0 -1
  3. package/dist/adapters/databasePluginUtils.cjs +14 -1
  4. package/dist/adapters/databasePluginUtils.mjs +14 -2
  5. package/dist/adapters/drizzle.cjs +9 -4
  6. package/dist/adapters/drizzle.d.cts +0 -1
  7. package/dist/adapters/drizzle.d.mts +0 -1
  8. package/dist/adapters/drizzle.mjs +10 -4
  9. package/dist/adapters/drizzleCrud.cjs +93 -3
  10. package/dist/adapters/drizzleCrud.mjs +93 -5
  11. package/dist/adapters/drizzleLazyDB.cjs +2 -0
  12. package/dist/adapters/drizzleLazyDB.mjs +2 -0
  13. package/dist/adapters/drizzleQuery.cjs +3 -2
  14. package/dist/adapters/drizzleQuery.mjs +3 -1
  15. package/dist/adapters/kysely.cjs +1 -1
  16. package/dist/adapters/kysely.d.cts +0 -1
  17. package/dist/adapters/kysely.d.mts +0 -1
  18. package/dist/adapters/kysely.mjs +2 -1
  19. package/dist/adapters/kyselyCrud.cjs +44 -5
  20. package/dist/adapters/kyselyCrud.mjs +45 -6
  21. package/dist/adapters/kyselyQuery.cjs +2 -2
  22. package/dist/adapters/kyselyQuery.mjs +2 -1
  23. package/dist/adapters/mongodb.cjs +36 -1
  24. package/dist/adapters/mongodb.d.cts +1 -1
  25. package/dist/adapters/mongodb.d.mts +1 -1
  26. package/dist/adapters/mongodb.mjs +36 -0
  27. package/dist/adapters/mongodbCollections.cjs +2 -0
  28. package/dist/adapters/mongodbCollections.mjs +2 -0
  29. package/dist/adapters/mongodbQuery.cjs +17 -4
  30. package/dist/adapters/mongodbQuery.mjs +17 -4
  31. package/dist/adapters/mongodbReads.cjs +88 -30
  32. package/dist/adapters/mongodbReads.mjs +88 -29
  33. package/dist/adapters/mongodbWrites.cjs +1 -2
  34. package/dist/adapters/mongodbWrites.mjs +1 -1
  35. package/dist/adapters/prisma.cjs +44 -7
  36. package/dist/adapters/prisma.d.cts +0 -1
  37. package/dist/adapters/prisma.d.mts +0 -1
  38. package/dist/adapters/prisma.mjs +44 -6
  39. package/dist/adapters/prismaInsights.cjs +99 -0
  40. package/dist/adapters/prismaInsights.mjs +97 -0
  41. package/dist/adapters/prismaQuery.cjs +0 -1
  42. package/dist/adapters/prismaRows.cjs +7 -8
  43. package/dist/adapters/prismaRows.mjs +8 -8
  44. package/dist/apiKeys.cjs +6 -2
  45. package/dist/apiKeys.d.cts +0 -1
  46. package/dist/apiKeys.d.mts +0 -1
  47. package/dist/apiKeys.mjs +3 -3
  48. package/dist/createHotUpdaterCore.cjs +27 -12
  49. package/dist/createHotUpdaterCore.d.cts +8 -8
  50. package/dist/createHotUpdaterCore.d.mts +8 -8
  51. package/dist/createHotUpdaterCore.mjs +26 -12
  52. package/dist/db/createBundleDiff.cjs +2 -2
  53. package/dist/db/createBundleDiff.d.cts +1 -5
  54. package/dist/db/createBundleDiff.d.mts +1 -5
  55. package/dist/db/databasePluginCore.cjs +0 -1
  56. package/dist/db/fixedMigrator.cjs +2 -2
  57. package/dist/db/fixedMigrator.mjs +2 -2
  58. package/dist/db/fixedMigratorMongo.cjs +6 -4
  59. package/dist/db/fixedMigratorMongo.mjs +6 -4
  60. package/dist/db/index.d.cts +0 -1
  61. package/dist/db/index.d.mts +0 -1
  62. package/dist/db/releaseCatalog.cjs +0 -1
  63. package/dist/db/releaseCatalog.d.cts +0 -1
  64. package/dist/db/releaseCatalog.d.mts +0 -1
  65. package/dist/db/schema/insightsCollation.cjs +14 -0
  66. package/dist/db/schema/insightsCollation.mjs +14 -0
  67. package/dist/db/schema/sql.cjs +11 -7
  68. package/dist/db/schema/sql.mjs +8 -8
  69. package/dist/db/schemaGenerators.cjs +29 -9
  70. package/dist/db/schemaGenerators.mjs +29 -9
  71. package/dist/db/schemaReadiness.cjs +2 -0
  72. package/dist/db/schemaReadiness.d.cts +1 -0
  73. package/dist/db/schemaReadiness.d.mts +1 -0
  74. package/dist/db/schemaReadiness.mjs +2 -0
  75. package/dist/db/sqlMigrationExecution.cjs +1 -1
  76. package/dist/db/sqlMigrationExecution.mjs +1 -0
  77. package/dist/db/types.cjs +3 -1
  78. package/dist/db/types.d.cts +3 -6
  79. package/dist/db/types.d.mts +3 -6
  80. package/dist/db/types.mjs +2 -2
  81. package/dist/db/updateArtifacts.cjs +0 -1
  82. package/dist/handler.cjs +5 -5
  83. package/dist/handler.d.cts +1 -2
  84. package/dist/handler.d.mts +1 -2
  85. package/dist/handler.mjs +5 -5
  86. package/dist/handlerReleaseCatalogRoutes.cjs +0 -1
  87. package/dist/handlerReleaseManagementRoutes.cjs +0 -1
  88. package/dist/handlerTypes.d.cts +0 -1
  89. package/dist/handlerTypes.d.mts +0 -1
  90. package/dist/handlerVersionRoutes.d.cts +1 -0
  91. package/dist/handlerVersionRoutes.d.mts +1 -0
  92. package/dist/index.cjs +2 -2
  93. package/dist/index.d.cts +4 -4
  94. package/dist/index.d.mts +4 -4
  95. package/dist/index.mjs +2 -2
  96. package/dist/insights/domain.d.cts +92 -0
  97. package/dist/insights/domain.d.mts +92 -0
  98. package/dist/insights/errors.cjs +15 -0
  99. package/dist/insights/errors.mjs +14 -0
  100. package/dist/{analytics → insights}/eventInput.cjs +61 -16
  101. package/dist/{analytics → insights}/eventInput.mjs +61 -18
  102. package/dist/insights/provider.cjs +332 -0
  103. package/dist/insights/provider.d.cts +6 -0
  104. package/dist/insights/provider.d.mts +6 -0
  105. package/dist/insights/provider.mjs +332 -0
  106. package/dist/insights/queryInput.cjs +93 -0
  107. package/dist/insights/queryInput.mjs +91 -0
  108. package/dist/insights/routes.cjs +58 -0
  109. package/dist/insights/routes.mjs +56 -0
  110. package/dist/insights/types.d.cts +32 -0
  111. package/dist/insights/types.d.mts +32 -0
  112. package/dist/node.d.cts +0 -1
  113. package/dist/node.d.mts +0 -1
  114. package/dist/package.cjs +1 -1
  115. package/dist/package.mjs +1 -1
  116. package/dist/schema/index.cjs +17 -3
  117. package/dist/schema/index.mjs +4 -4
  118. package/dist/schema/v1_0_0.cjs +64 -35
  119. package/dist/schema/v1_0_0.mjs +64 -36
  120. package/dist/storageAccess.cjs +0 -1
  121. package/dist/types/index.d.cts +0 -1
  122. package/dist/types/index.d.mts +0 -1
  123. package/package.json +7 -7
  124. package/src/adapters/databasePluginTestDatabase.ts +15 -5
  125. package/src/adapters/databasePluginUtils.ts +24 -0
  126. package/src/adapters/drizzle.spec.ts +203 -5
  127. package/src/adapters/drizzle.ts +16 -4
  128. package/src/adapters/drizzleCrud.ts +200 -9
  129. package/src/adapters/drizzleLazyDB.ts +33 -6
  130. package/src/adapters/kysely.spec.ts +62 -0
  131. package/src/adapters/kysely.ts +7 -1
  132. package/src/adapters/kyselyCrud.ts +115 -7
  133. package/src/adapters/kyselyInsights.spec.ts +168 -0
  134. package/src/adapters/mongodb.integration.spec.ts +483 -0
  135. package/src/adapters/mongodb.spec.ts +89 -0
  136. package/src/adapters/mongodb.ts +59 -1
  137. package/src/adapters/mongodbCollections.ts +16 -0
  138. package/src/adapters/mongodbQuery.ts +22 -3
  139. package/src/adapters/mongodbReads.ts +78 -2
  140. package/src/adapters/mongodbTestClient.ts +107 -6
  141. package/src/adapters/mongodbTestFilter.ts +5 -1
  142. package/src/adapters/mongodbWrites.ts +1 -0
  143. package/src/adapters/prisma.spec.ts +270 -0
  144. package/src/adapters/prisma.ts +75 -2
  145. package/src/adapters/prismaInsights.ts +190 -0
  146. package/src/adapters/prismaRows.ts +17 -10
  147. package/src/adapters/prismaTestClient.ts +89 -7
  148. package/src/apiKeys.integration.spec.ts +3 -3
  149. package/src/createHotUpdaterCore.ts +30 -16
  150. package/src/db/databasePluginUpdateCheck.bench.ts +10 -0
  151. package/src/db/fixedMigrator.spec.ts +63 -0
  152. package/src/db/fixedMigratorMongo.spec.ts +70 -9
  153. package/src/db/fixedMigratorMongo.ts +10 -10
  154. package/src/db/index.spec.ts +6 -1
  155. package/src/db/schema/insightsCollation.ts +21 -0
  156. package/src/db/schema/sql.ts +8 -5
  157. package/src/db/schemaGenerators.ts +42 -13
  158. package/src/db/types.spec.ts +11 -3
  159. package/src/db/types.ts +13 -7
  160. package/src/handler-standalone.integration.spec.ts +6 -8
  161. package/src/handler.ts +12 -12
  162. package/src/index.ts +3 -3
  163. package/src/insights/domain.ts +106 -0
  164. package/src/insights/errors.ts +11 -0
  165. package/src/{analytics → insights}/eventInput.ts +66 -16
  166. package/src/insights/insights.integration.spec.ts +475 -0
  167. package/src/insights/provider.spec.ts +396 -0
  168. package/src/insights/provider.ts +611 -0
  169. package/src/insights/queryInput.ts +142 -0
  170. package/src/insights/routes.ts +104 -0
  171. package/src/insights/types.ts +55 -0
  172. package/src/schema/dsl-all-versions.spec.ts +1 -1
  173. package/src/schema/v1_0_0.spec.ts +77 -3
  174. package/src/schema/v1_0_0.ts +83 -37
  175. package/dist/analytics/bounded/activeOverview.cjs +0 -87
  176. package/dist/analytics/bounded/activeOverview.mjs +0 -85
  177. package/dist/analytics/bounded/installationSearch.cjs +0 -42
  178. package/dist/analytics/bounded/installationSearch.mjs +0 -42
  179. package/dist/analytics/bounded/persistence.cjs +0 -39
  180. package/dist/analytics/bounded/persistence.mjs +0 -38
  181. package/dist/analytics/bounded/provider.cjs +0 -170
  182. package/dist/analytics/bounded/provider.d.cts +0 -7
  183. package/dist/analytics/bounded/provider.d.mts +0 -7
  184. package/dist/analytics/bounded/provider.mjs +0 -170
  185. package/dist/analytics/bounded/scan.cjs +0 -144
  186. package/dist/analytics/bounded/scan.mjs +0 -138
  187. package/dist/analytics/domain.d.cts +0 -121
  188. package/dist/analytics/domain.d.mts +0 -121
  189. package/dist/analytics/errors.cjs +0 -22
  190. package/dist/analytics/errors.mjs +0 -20
  191. package/dist/analytics/persistence.d.cts +0 -6
  192. package/dist/analytics/persistence.d.mts +0 -6
  193. package/dist/analytics/queryInput.cjs +0 -58
  194. package/dist/analytics/queryInput.mjs +0 -55
  195. package/dist/analytics/routes.cjs +0 -63
  196. package/dist/analytics/routes.mjs +0 -61
  197. package/dist/analytics/types.d.cts +0 -17
  198. package/dist/analytics/types.d.mts +0 -17
  199. package/src/analytics/analytics.integration.spec.ts +0 -144
  200. package/src/analytics/bounded/activeOverview.spec.ts +0 -189
  201. package/src/analytics/bounded/activeOverview.ts +0 -148
  202. package/src/analytics/bounded/installationSearch.spec.ts +0 -130
  203. package/src/analytics/bounded/installationSearch.ts +0 -69
  204. package/src/analytics/bounded/persistence.ts +0 -43
  205. package/src/analytics/bounded/provider.spec.ts +0 -219
  206. package/src/analytics/bounded/provider.ts +0 -229
  207. package/src/analytics/bounded/scan.ts +0 -235
  208. package/src/analytics/domain.ts +0 -139
  209. package/src/analytics/errors.ts +0 -18
  210. package/src/analytics/persistence.ts +0 -10
  211. package/src/analytics/queryInput.ts +0 -102
  212. package/src/analytics/routes.ts +0 -123
  213. package/src/analytics/types.ts +0 -44
@@ -11,6 +11,7 @@ import {
11
11
  import { drizzle } from "drizzle-orm/pglite";
12
12
  import { describe, expect, it, vi } from "vitest";
13
13
 
14
+ import { createBundleEventRowFixture } from "../../../test-utils/src/databaseTestFixtures";
14
15
  import { setupDatabasePluginTestSuite } from "../../../test-utils/src/setupDatabasePluginTestSuite";
15
16
  import type { DatabaseAdapterWithCapabilities } from "../db/types";
16
17
  import {
@@ -86,7 +87,7 @@ const bundleEvents = pgTable("bundle_events", {
86
87
  type: text("type").notNull(),
87
88
  install_id: text("install_id").notNull(),
88
89
  user_id: text("user_id"),
89
- username: text("username"),
90
+ metadata: jsonb("metadata").notNull(),
90
91
  from_release_id: text("from_release_id"),
91
92
  from_bundle_id: text("from_bundle_id"),
92
93
  to_release_id: text("to_release_id"),
@@ -94,12 +95,20 @@ const bundleEvents = pgTable("bundle_events", {
94
95
  platform: text("platform").notNull(),
95
96
  app_version: text("app_version").notNull(),
96
97
  channel: text("channel").notNull(),
97
- cohort: text("cohort").notNull(),
98
- update_strategy: text("update_strategy"),
99
- fingerprint_hash: text("fingerprint_hash"),
100
- sdk_version: text("sdk_version"),
98
+
101
99
  received_at_ms: integer("received_at_ms").notNull(),
102
100
  });
101
+ const bundleEventHeads = pgTable("bundle_event_heads", {
102
+ install_id: text("install_id").primaryKey(),
103
+ id: text("id").notNull(),
104
+ received_at_ms: integer("received_at_ms").notNull(),
105
+ user_id: text("user_id"),
106
+ platform: text("platform").notNull(),
107
+ channel: text("channel").notNull(),
108
+ type: text("type").notNull(),
109
+ from_bundle_id: text("from_bundle_id"),
110
+ to_bundle_id: text("to_bundle_id").notNull(),
111
+ });
103
112
  const apiKeys = pgTable("api_keys", {
104
113
  id: text("id").primaryKey(),
105
114
  hash: text("hash").notNull().unique(),
@@ -111,6 +120,8 @@ const apiKeys = pgTable("api_keys", {
111
120
  });
112
121
  const schema = {
113
122
  bundle_events: bundleEvents,
123
+ bundle_event_heads: bundleEventHeads,
124
+
114
125
  bundle_patches: bundlePatches,
115
126
  bundles,
116
127
  channels,
@@ -156,6 +167,191 @@ setupDatabasePluginTestSuite({
156
167
  });
157
168
 
158
169
  describe("drizzleAdapter schema requirements", () => {
170
+ it("counts MySQL predicate overlap and nullable sources in one SQL snapshot", async () => {
171
+ const db = new PGlite();
172
+ await db.exec(DATABASE_PLUGIN_TEST_SCHEMA_SQL);
173
+ const native = drizzle(db, { schema });
174
+ const writer = drizzleAdapter({ db: native, provider: "postgresql" }).models
175
+ .insights;
176
+ const applied = createBundleEventRowFixture("711", 100);
177
+ const overlap = { ...applied, from_bundle_id: applied.to_bundle_id };
178
+ const unchanged = {
179
+ ...createBundleEventRowFixture("712", 100),
180
+ type: "UNCHANGED" as const,
181
+ from_bundle_id: null,
182
+ to_bundle_id: applied.to_bundle_id,
183
+ metadata: { ...applied.metadata, update_strategy: null },
184
+ };
185
+ const count = drizzleAdapter({
186
+ db: async () => native,
187
+ schema,
188
+ provider: "mysql",
189
+ transaction: false,
190
+ }).models.insights.countLatestEvents;
191
+ const scope = {
192
+ platform: "ios" as const,
193
+ channel: "production",
194
+ sinceMs: 0,
195
+ };
196
+ const from = {
197
+ field: "from_bundle_id" as const,
198
+ value: applied.to_bundle_id,
199
+ types: ["UPDATE_APPLIED", "UNCHANGED"] as const,
200
+ };
201
+ const to = { ...from, field: "to_bundle_id" as const };
202
+ try {
203
+ await writer.recordEvent({ event: overlap });
204
+ await writer.recordEvent({ event: unchanged });
205
+ for (const bundle of [
206
+ [from, to],
207
+ [to, from],
208
+ [to, to],
209
+ ]) {
210
+ await expect(count({ ...scope, bundle })).resolves.toBe(2);
211
+ }
212
+ await expect(count({ ...scope, bundle: [from] })).resolves.toBe(1);
213
+ await expect(count(scope)).resolves.toBe(2);
214
+ } finally {
215
+ await db.close();
216
+ }
217
+ });
218
+ it.each([undefined, false])(
219
+ "keeps lazy Insights writes atomic with catalog transaction option %s",
220
+ async (transaction) => {
221
+ const db = new PGlite();
222
+ await db.exec(DATABASE_PLUGIN_TEST_SCHEMA_SQL);
223
+ const native = drizzle(db, { schema });
224
+ const callbackTransaction = vi
225
+ .spyOn(native, "transaction")
226
+ .mockImplementation(() => {
227
+ throw new Error("callback transactions are unavailable");
228
+ });
229
+ const plugin = drizzleAdapter({
230
+ db: async () => native,
231
+ provider: "postgresql",
232
+ schema,
233
+ transaction,
234
+ });
235
+ const previous = createBundleEventRowFixture("709", 100);
236
+ const next = {
237
+ ...createBundleEventRowFixture("710", 200),
238
+ install_id: previous.install_id,
239
+ };
240
+ try {
241
+ await plugin.models.insights.recordEvent({ event: previous });
242
+ await db.exec(
243
+ "alter table bundle_event_heads add constraint reject_head check (received_at_ms < 200)",
244
+ );
245
+ await expect(
246
+ plugin.models.insights.recordEvent({ event: next }),
247
+ ).rejects.toThrow();
248
+ expect((await db.query("select id from bundle_events")).rows).toEqual([
249
+ { id: previous.id },
250
+ ]);
251
+ await expect(
252
+ plugin.models.insights.findLatestEvents({
253
+ installId: previous.install_id,
254
+ }),
255
+ ).resolves.toEqual([previous]);
256
+ await db.exec(
257
+ "alter table bundle_event_heads drop constraint reject_head",
258
+ );
259
+ await plugin.models.insights.recordEvent({ event: next });
260
+ await plugin.models.insights.recordEvent({
261
+ event: { ...next, received_at_ms: 300, user_id: "incorrect-user" },
262
+ });
263
+ await expect(
264
+ plugin.models.insights.findLatestEvents({
265
+ installId: previous.install_id,
266
+ }),
267
+ ).resolves.toEqual([next]);
268
+ expect(callbackTransaction).not.toHaveBeenCalled();
269
+ } finally {
270
+ await db.close();
271
+ }
272
+ },
273
+ );
274
+ it("rolls back a Bun SQLite event when its head cannot be written", async () => {
275
+ const { stdout } = await promisify(execFile)(
276
+ new URL("../../../../node_modules/.bin/bun", import.meta.url).pathname,
277
+ [
278
+ "-e",
279
+ `
280
+ import { Database } from "bun:sqlite";
281
+ import { drizzle } from "drizzle-orm/bun-sqlite";
282
+ import { drizzleAdapter } from "./src/adapters/drizzle.ts";
283
+ import { createTableSql } from "./src/db/schema/sql.ts";
284
+ import { createBundleEventRowFixture } from "../test-utils/src/databaseTestFixtures.ts";
285
+ import * as schema from "../../examples-server/elysia-drizzle-libsql/hot-updater-schema.ts";
286
+ const db = new Database(":memory:");
287
+ db.exec(createTableSql("sqlite").join(";"));
288
+ db.exec("create trigger reject_head before insert on bundle_event_heads begin select raise(abort, 'injected head failure'); end;");
289
+ const plugin = drizzleAdapter({ db: drizzle(db, { schema }), provider: "sqlite" });
290
+ const event = createBundleEventRowFixture("708", 100);
291
+ const input = { event };
292
+ let rejected = false;
293
+ try { await plugin.models.insights.recordEvent(input); } catch { rejected = true; }
294
+ if (!rejected || db.query("select count(*) as total from bundle_events").get().total !== 0) throw new Error("transaction failed to roll back");
295
+ db.exec("drop trigger reject_head");
296
+ await plugin.models.insights.recordEvent(input);
297
+ await plugin.models.insights.recordEvent(input);
298
+ if (db.query("select count(*) as total from bundle_events").get().total !== 1) throw new Error("retry did not commit exactly one report");
299
+ const stored = db.query("select json_type(cast(metadata as text)) as kind from bundle_events").get();
300
+ if (stored.kind !== "object") throw new Error("event metadata was double encoded");
301
+ const latest = await plugin.models.insights.findLatestEvents({ installId: event.install_id });
302
+ if (JSON.stringify(latest[0].metadata) !== JSON.stringify(event.metadata)) throw new Error("metadata did not round trip");
303
+ db.close();
304
+ console.log("atomic retry verified");
305
+ `,
306
+ ],
307
+ { cwd: new URL("../..", import.meta.url).pathname },
308
+ );
309
+ expect(stdout).toContain("atomic retry verified");
310
+ });
311
+ it("keeps failed event inserts absent and permits retry", async () => {
312
+ const db = new PGlite();
313
+ await db.exec(DATABASE_PLUGIN_TEST_SCHEMA_SQL);
314
+ await db.exec(
315
+ "alter table bundle_events add constraint reject_event check (install_id <> 'install-701')",
316
+ );
317
+ const plugin = drizzleAdapter({
318
+ db: drizzle(db, { schema }),
319
+ provider: "postgresql",
320
+ });
321
+ const event = createBundleEventRowFixture("701", 100);
322
+ const input = { event };
323
+ try {
324
+ await expect(plugin.models.insights.recordEvent(input)).rejects.toThrow();
325
+ expect((await db.query("select id from bundle_events")).rows).toEqual([]);
326
+ await db.exec("alter table bundle_events drop constraint reject_event");
327
+ await plugin.models.insights.recordEvent(input);
328
+ await expect(
329
+ plugin.models.insights.findLatestEvents({
330
+ installId: event.install_id,
331
+ }),
332
+ ).resolves.toEqual([input.event]);
333
+ } finally {
334
+ await db.close();
335
+ }
336
+ });
337
+
338
+ it("resolves the lazy database when recording an event", async () => {
339
+ const getDB = vi.fn(() => {
340
+ throw new DrizzleTestStateError();
341
+ });
342
+ const plugin = drizzleAdapter({
343
+ db: getDB,
344
+ provider: "postgresql",
345
+ schema,
346
+ });
347
+ const event = createBundleEventRowFixture("702", 100);
348
+ await expect(
349
+ plugin.models.insights.recordEvent({
350
+ event,
351
+ }),
352
+ ).rejects.toThrow(DrizzleTestStateError);
353
+ expect(getDB).toHaveBeenCalledOnce();
354
+ });
159
355
  it("does not resolve a lazy database while generating a schema", () => {
160
356
  const getDB = vi.fn(() => {
161
357
  throw new DrizzleTestStateError();
@@ -235,3 +431,5 @@ describe("drizzleAdapter schema requirements", () => {
235
431
  );
236
432
  });
237
433
  });
434
+ import { execFile } from "node:child_process";
435
+ import { promisify } from "node:util";
@@ -15,7 +15,7 @@ import type {
15
15
  ORMProvider,
16
16
  SchemaGenerator,
17
17
  } from "../db/types";
18
- import { createDrizzleCrud } from "./drizzleCrud";
18
+ import { createDrizzleCrud, recordDrizzleInsights } from "./drizzleCrud";
19
19
  import { createLazyDB } from "./drizzleLazyDB";
20
20
 
21
21
  export type DrizzleProvider = Exclude<
@@ -38,6 +38,13 @@ const createImplementation = (
38
38
  const transaction = db.transaction?.bind(db);
39
39
  return {
40
40
  ...crud,
41
+ recordInsights: async (input) => {
42
+ await recordDrizzleInsights(
43
+ db.resolve === undefined ? db : await db.resolve(),
44
+ config.provider,
45
+ input,
46
+ );
47
+ },
41
48
  deleteChannel: (input) => {
42
49
  if (transaction === undefined) {
43
50
  throw new Error(
@@ -115,9 +122,14 @@ export const drizzleAdapter = (
115
122
  list: (input) => getAdapter().models.channels.list(input),
116
123
  delete: (input) => getAdapter().models.channels.delete(input),
117
124
  },
118
- analytics: {
119
- append: (row) => getAdapter().models.analytics.append(row),
120
- scan: (input) => getAdapter().models.analytics.scan(input),
125
+ insights: {
126
+ recordEvent: (input) => getAdapter().models.insights.recordEvent(input),
127
+ listEvents: (input) => getAdapter().models.insights.listEvents(input),
128
+ findLatestEvents: (input) =>
129
+ getAdapter().models.insights.findLatestEvents(input),
130
+ countLatestEvents: (input) =>
131
+ getAdapter().models.insights.countLatestEvents(input),
132
+ countEvents: (input) => getAdapter().models.insights.countEvents(input),
121
133
  },
122
134
  apiKeys: {
123
135
  create: (row) => getAdapter().models.apiKeys.create(row),
@@ -1,14 +1,32 @@
1
- import { DatabasePluginInputError } from "@hot-updater/plugin-core";
1
+ import {
2
+ DatabasePluginInputError,
3
+ type InsightsRecordEventInput,
4
+ } from "@hot-updater/plugin-core";
5
+ import {
6
+ latestInsightsWhere,
7
+ latestInsightsCountGroups,
8
+ } from "@hot-updater/plugin-core/internal";
2
9
  import type {
3
10
  DatabasePluginImplementation,
4
11
  TransactionDatabasePluginImplementation,
5
12
  } from "@hot-updater/plugin-core/internal";
6
- import { asc, desc, eq, sql, type SQLWrapper } from "drizzle-orm";
13
+ import {
14
+ or,
15
+ asc,
16
+ desc,
17
+ eq,
18
+ sql,
19
+ getTableColumns,
20
+ is,
21
+ Table,
22
+ type SQLWrapper,
23
+ } from "drizzle-orm";
7
24
 
8
25
  import {
9
26
  isChannelDeleteReferencedError,
10
27
  translateChannelDeleteError,
11
28
  } from "./databaseConstraintErrors";
29
+ import { fromStoredBundleEventRow } from "./databasePluginUtils";
12
30
  import {
13
31
  fromStoredBundleRow,
14
32
  fromStoredReleaseCatalogRow,
@@ -78,9 +96,117 @@ const executeInsert = async (
78
96
  await ignored.execute();
79
97
  };
80
98
 
99
+ export const recordDrizzleInsights = (
100
+ db: DrizzleDB,
101
+ provider: DrizzleProvider,
102
+ { event }: InsightsRecordEventInput,
103
+ ): void | Promise<void> => {
104
+ const events = getDrizzleTable(db, "bundle_events");
105
+ const heads = getDrizzleTable(db, "bundle_event_heads");
106
+ if (!is(heads, Table) || !is(events, Table)) {
107
+ throw new DrizzleAdapterInvariantError();
108
+ }
109
+ const fields = Object.keys(getTableColumns(heads));
110
+ if (provider === "mysql") {
111
+ if (!db.transaction) throw new DrizzleAdapterInvariantError();
112
+ return db.transaction(async (transaction) => {
113
+ const accepted = transaction
114
+ .insert(events)
115
+ .values(event)
116
+ .onDuplicateKeyUpdate?.({ set: { id: sql`id` } });
117
+ if (!accepted || !transaction.execute)
118
+ throw new DrizzleAdapterInvariantError();
119
+ await accepted.execute();
120
+ const wins = sql`VALUES(received_at_ms) > bundle_event_heads.received_at_ms OR (VALUES(received_at_ms) = bundle_event_heads.received_at_ms AND VALUES(id) > bundle_event_heads.id)`;
121
+ // Drizzle orders UPDATE assignments by schema columns. Emit these explicitly
122
+ // so MySQL compares against the old tuple until every payload field is set.
123
+ const ordered = [
124
+ ...fields.filter(
125
+ (field) => !["install_id", "id", "received_at_ms"].includes(field),
126
+ ),
127
+ "id",
128
+ "received_at_ms",
129
+ ];
130
+ const columns = sql.join(
131
+ fields.map((field) => sql.identifier(field)),
132
+ sql`, `,
133
+ );
134
+ const assignments = sql.join(
135
+ ordered.map(
136
+ (field) =>
137
+ sql`${sql.identifier(field)} = CASE WHEN ${wins} THEN VALUES(${sql.identifier(field)}) ELSE bundle_event_heads.${sql.identifier(field)} END`,
138
+ ),
139
+ sql`, `,
140
+ );
141
+ await transaction.execute(
142
+ sql`INSERT INTO bundle_event_heads (${columns}) SELECT ${columns} FROM bundle_events WHERE id = ${event.id} ON DUPLICATE KEY UPDATE ${assignments}`,
143
+ );
144
+ });
145
+ }
146
+ const newer = sql`excluded.received_at_ms > bundle_event_heads.received_at_ms OR (excluded.received_at_ms = bundle_event_heads.received_at_ms AND excluded.id > bundle_event_heads.id)`;
147
+ const mutations = (executor: DrizzleDB, fromInserted = false) => {
148
+ const insert = executor.insert(events).values(event);
149
+ const accepted = insert.onConflictDoNothing?.();
150
+ // Read the immutable accepted row, never a possibly altered duplicate input.
151
+ const select = fromInserted
152
+ ? sql`SELECT ${sql.join(
153
+ fields.map((field) => sql.identifier(field)),
154
+ sql`, `,
155
+ )} FROM inserted`
156
+ : sql`SELECT ${sql.join(
157
+ fields.map((field) => sql.identifier(field)),
158
+ sql`, `,
159
+ )} FROM bundle_events WHERE id = ${event.id}`;
160
+ const headInsert = executor.insert(heads).select?.(select);
161
+ const head = headInsert?.onConflictDoUpdate?.({
162
+ target: getDrizzleColumn(heads, "install_id"),
163
+ set: Object.fromEntries(
164
+ fields
165
+ .filter((field) => field !== "install_id")
166
+ .map((field) => [field, sql`excluded.${sql.identifier(field)}`]),
167
+ ),
168
+ setWhere: newer,
169
+ });
170
+ if (accepted === undefined || head === undefined)
171
+ throw new DrizzleAdapterInvariantError();
172
+ return { accepted, head };
173
+ };
174
+ if (provider === "postgresql") {
175
+ const { accepted, head } = mutations(db, true);
176
+ const returning =
177
+ "returning" in accepted && typeof accepted.returning === "function"
178
+ ? accepted.returning(getTableColumns(events))
179
+ : undefined;
180
+ if (!returning?.getSQL || !head.getSQL || !db.execute)
181
+ throw new DrizzleAdapterInvariantError();
182
+ return db
183
+ .execute(sql`WITH inserted AS (${returning.getSQL()}) ${head.getSQL()}`)
184
+ .then(() => undefined);
185
+ }
186
+ if (db.batch !== undefined) {
187
+ const { accepted, head } = mutations(db);
188
+ return db.batch([accepted, head]).then(() => undefined);
189
+ }
190
+ if (db.transaction === undefined) throw new DrizzleAdapterInvariantError();
191
+ return db.transaction((transaction) => {
192
+ const { accepted, head } = mutations(transaction);
193
+ if (db.resultKind === "sync") {
194
+ if (!accepted.run || !head.run) throw new DrizzleAdapterInvariantError();
195
+ accepted.run();
196
+ head.run();
197
+ return;
198
+ }
199
+ return accepted
200
+ .execute()
201
+ .then(() => head.execute())
202
+ .then(() => undefined);
203
+ });
204
+ };
205
+
81
206
  const toOrderBy = (
82
207
  table: DrizzleTable,
83
208
  input: {
209
+ model?: string;
84
210
  orderBy?: readonly {
85
211
  field: string;
86
212
  direction: "asc" | "desc";
@@ -91,6 +217,9 @@ const toOrderBy = (
91
217
  const clauses = input.orderBy;
92
218
  return clauses?.flatMap((clause) => {
93
219
  const column = getDrizzleColumn(table, clause.field);
220
+ if (input.model === "bundle_events") {
221
+ return [clause.direction === "asc" ? asc(column) : desc(column)];
222
+ }
94
223
  const nulls =
95
224
  clause.nulls ?? (clause.direction === "asc" ? "last" : "first");
96
225
  return [
@@ -106,15 +235,68 @@ export const createDrizzleCrud = (
106
235
  db: DrizzleDB,
107
236
  provider: DrizzleProvider,
108
237
  ): TransactionDatabasePluginImplementation &
109
- Pick<DatabasePluginImplementation, "deleteChannel" | "insertChannel"> => {
238
+ Pick<
239
+ DatabasePluginImplementation,
240
+ | "deleteChannel"
241
+ | "insertChannel"
242
+ | "findLatestInsightsEvents"
243
+ | "countLatestInsightsEvents"
244
+ > => {
110
245
  const bundles = getDrizzleTable(db, "bundles");
111
246
  const patches = getDrizzleTable(db, "bundle_patches");
112
247
  const events = getDrizzleTable(db, "bundle_events");
248
+ const heads = getDrizzleTable(db, "bundle_event_heads");
113
249
  const releases = getDrizzleTable(db, "releases");
114
250
  const releaseCatalogs = getDrizzleTable(db, "release_catalogs");
115
251
  const channels = getDrizzleTable(db, "channels");
116
252
  const apiKeys = getDrizzleTable(db, "api_keys");
117
253
  return {
254
+ async findLatestInsightsEvents(input) {
255
+ const where = sql.join(
256
+ latestInsightsWhere(input).map((condition) =>
257
+ condition.operator === "gt"
258
+ ? sql`${sql.identifier(condition.field)} > ${condition.value}`
259
+ : sql`${sql.identifier(condition.field)} = ${condition.value}`,
260
+ ),
261
+ sql` AND `,
262
+ );
263
+ const rows = await db.query.bundle_events.findMany({
264
+ where: sql`${getDrizzleColumn(events, "id")} IN (SELECT id FROM (SELECT id FROM bundle_event_heads WHERE ${where} ORDER BY install_id ASC LIMIT ${"installId" in input ? 1 : input.limit}) AS latest)`,
265
+ orderBy: [asc(getDrizzleColumn(events, "install_id"))],
266
+ limit: "installId" in input ? 1 : input.limit,
267
+ });
268
+ return rows.map(fromStoredBundleEventRow);
269
+ },
270
+ async countLatestInsightsEvents(input) {
271
+ const groups = latestInsightsCountGroups(input).map((where) =>
272
+ buildDrizzleWhere(provider, heads, where),
273
+ );
274
+ if (provider === "mysql" && groups.length === 2) {
275
+ const native = db.resolve === undefined ? db : await db.resolve();
276
+ if (!native.select) throw new DrizzleAdapterInvariantError();
277
+ // Separate index ranges in one snapshot, excluding overlap including NULL.
278
+ const result = await native
279
+ .select({
280
+ count: sql`(SELECT COUNT(*) FROM bundle_event_heads WHERE ${groups[0]}) + (SELECT COUNT(*) FROM bundle_event_heads WHERE ${groups[1]} AND (${groups[0]}) IS NOT TRUE)`,
281
+ })
282
+ .from(sql`(SELECT 1) AS counted`)
283
+ .execute();
284
+ const row = result[0];
285
+ const count =
286
+ typeof row === "object" && row !== null
287
+ ? Reflect.get(row, "count")
288
+ : undefined;
289
+ if (
290
+ typeof count !== "number" &&
291
+ typeof count !== "string" &&
292
+ typeof count !== "bigint"
293
+ ) {
294
+ throw new DrizzleAdapterInvariantError();
295
+ }
296
+ return Number(count);
297
+ }
298
+ return db.$count(heads, or(...groups));
299
+ },
118
300
  async deleteChannel({ id }) {
119
301
  const idPredicate = eq(getDrizzleColumn(channels, "id"), id);
120
302
  const existing = await db.query.channels.findFirst({
@@ -169,6 +351,7 @@ export const createDrizzleCrud = (
169
351
  case "bundle_events":
170
352
  await executeInsert(db, provider, events, input.data, undefined);
171
353
  return input.data;
354
+
172
355
  case "releases":
173
356
  await executeInsert(
174
357
  db,
@@ -296,6 +479,11 @@ export const createDrizzleCrud = (
296
479
  throw new DatabasePluginInputError("invalid-operation");
297
480
  }
298
481
  switch (input.model) {
482
+ case "bundle_events":
483
+ return db.$count(
484
+ events,
485
+ buildDrizzleWhere(provider, events, input.where),
486
+ );
299
487
  case "bundles":
300
488
  return db.$count(
301
489
  bundles,
@@ -368,12 +556,15 @@ export const createDrizzleCrud = (
368
556
  return rows.map(fromStoredBundleRow);
369
557
  }
370
558
  case "bundle_events":
371
- return db.query.bundle_events.findMany({
372
- where: buildDrizzleWhere(provider, events, input.where),
373
- orderBy: toOrderBy(events, input),
374
- limit: input.limit,
375
- offset: input.offset,
376
- });
559
+ return (
560
+ await db.query.bundle_events.findMany({
561
+ where: buildDrizzleWhere(provider, events, input.where),
562
+ orderBy: toOrderBy(events, input),
563
+ limit: input.limit,
564
+ offset: input.offset,
565
+ })
566
+ ).map(fromStoredBundleEventRow);
567
+
377
568
  case "api_keys":
378
569
  return db.query.api_keys.findMany({
379
570
  where: buildDrizzleWhere(provider, apiKeys, input.where),
@@ -1,27 +1,42 @@
1
1
  import type {
2
- BundleEventRow,
3
2
  BundlePatchRow,
4
3
  ChannelRow,
5
4
  ApiKeyRow,
6
5
  ReleaseCatalogRow,
7
6
  } from "@hot-updater/plugin-core";
7
+ import type { SQL } from "drizzle-orm";
8
8
 
9
- import type { StoredBundleRow, StoredReleaseRow } from "./databasePluginUtils";
9
+ import type {
10
+ StoredBundleEventRow,
11
+ StoredBundleRow,
12
+ StoredReleaseRow,
13
+ } from "./databasePluginUtils";
10
14
  import type { DrizzleConfig } from "./drizzle";
11
15
 
12
16
  export type DrizzleTable = Record<string, unknown>;
13
17
 
14
18
  type DrizzleMutation = {
15
19
  readonly execute: () => Promise<unknown>;
20
+ readonly getSQL?: () => SQL;
21
+ readonly all?: () => unknown[];
22
+ readonly run?: () => unknown;
16
23
  };
17
24
 
18
25
  export type DrizzleInsertMutation = DrizzleMutation & {
19
- readonly onConflictDoNothing?: () => DrizzleMutation;
26
+ readonly onDuplicateKeyUpdate?: (config: { set: object }) => DrizzleMutation;
27
+ readonly onConflictDoNothing?: () => DrizzleInsertMutation;
28
+ readonly returning?: (fields: Record<string, unknown>) => DrizzleMutation;
29
+ readonly onConflictDoUpdate?: (config: {
30
+ target: unknown;
31
+ set: object;
32
+ setWhere: SQL;
33
+ }) => DrizzleMutation;
20
34
  };
21
35
 
22
36
  type DrizzleInsertBuilder = {
23
37
  readonly ignore?: () => Pick<DrizzleInsertBuilder, "values">;
24
38
  readonly values: (value: unknown) => DrizzleInsertMutation;
39
+ readonly select?: (query: SQL) => DrizzleInsertMutation;
25
40
  };
26
41
 
27
42
  type DrizzleQuery<TRow> = {
@@ -30,6 +45,15 @@ type DrizzleQuery<TRow> = {
30
45
  };
31
46
 
32
47
  export type DrizzleDB = {
48
+ readonly resolve?: () => Promise<DrizzleDB>;
49
+ readonly execute?: (query: SQL) => Promise<unknown>;
50
+ readonly batch?: (queries: readonly DrizzleMutation[]) => Promise<unknown>;
51
+ readonly select?: (fields: Record<string, SQL>) => {
52
+ readonly from: (source: SQL) => {
53
+ readonly execute: () => Promise<readonly unknown[]>;
54
+ };
55
+ };
56
+ readonly resultKind?: "sync" | "async";
33
57
  readonly _: { readonly fullSchema: Record<string, DrizzleTable> };
34
58
  readonly $count: (table: DrizzleTable, where?: unknown) => Promise<number>;
35
59
  readonly delete: (table: DrizzleTable) => {
@@ -40,7 +64,8 @@ export type DrizzleDB = {
40
64
  readonly bundles: DrizzleQuery<StoredBundleRow>;
41
65
  readonly channels: DrizzleQuery<ChannelRow>;
42
66
  readonly bundle_patches: DrizzleQuery<BundlePatchRow>;
43
- readonly bundle_events: DrizzleQuery<BundleEventRow>;
67
+ readonly bundle_events: DrizzleQuery<StoredBundleEventRow>;
68
+
44
69
  readonly api_keys: DrizzleQuery<ApiKeyRow>;
45
70
  readonly releases: DrizzleQuery<StoredReleaseRow>;
46
71
  readonly release_catalogs: DrizzleQuery<ReleaseCatalogRow>;
@@ -51,7 +76,7 @@ export type DrizzleDB = {
51
76
  };
52
77
  };
53
78
  readonly transaction?: <TResult>(
54
- operation: (transaction: DrizzleDB) => Promise<TResult>,
79
+ operation: (transaction: DrizzleDB) => TResult | Promise<TResult>,
55
80
  ) => Promise<TResult>;
56
81
  };
57
82
 
@@ -148,6 +173,7 @@ export const createLazyDB = (config: DrizzleConfig): DrizzleDB => {
148
173
  return resolvedDB;
149
174
  };
150
175
  return {
176
+ resolve: getDB,
151
177
  _: { fullSchema: parseSchema(config.schema) },
152
178
  $count: async (table, where) => (await getDB()).$count(table, where),
153
179
  delete: (table) => ({
@@ -193,6 +219,7 @@ export const createLazyDB = (config: DrizzleConfig): DrizzleDB => {
193
219
  findMany: async (args) =>
194
220
  (await getDB()).query.bundle_events.findMany(args),
195
221
  },
222
+
196
223
  bundle_patches: {
197
224
  findFirst: async (args) =>
198
225
  (await getDB()).query.bundle_patches.findFirst(args),
@@ -241,7 +268,7 @@ export const createLazyDB = (config: DrizzleConfig): DrizzleDB => {
241
268
  ...(config.transaction === true
242
269
  ? {
243
270
  transaction: async <TResult>(
244
- operation: (transaction: DrizzleDB) => Promise<TResult>,
271
+ operation: (transaction: DrizzleDB) => TResult | Promise<TResult>,
245
272
  ): Promise<TResult> => {
246
273
  const db = await getDB();
247
274
  if (db.transaction === undefined) {