@hot-updater/server 0.36.7 → 1.0.0-rc.1

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 (291) hide show
  1. package/dist/adapters/databaseConstraintErrors.cjs +23 -0
  2. package/dist/adapters/databaseConstraintErrors.mjs +21 -0
  3. package/dist/adapters/databasePluginUtils.cjs +117 -0
  4. package/dist/adapters/databasePluginUtils.mjs +106 -0
  5. package/dist/adapters/drizzle.cjs +53 -176
  6. package/dist/adapters/drizzle.d.cts +6 -4
  7. package/dist/adapters/drizzle.d.mts +6 -4
  8. package/dist/adapters/drizzle.mjs +54 -177
  9. package/dist/adapters/drizzleCrud.cjs +250 -0
  10. package/dist/adapters/drizzleCrud.mjs +249 -0
  11. package/dist/adapters/drizzleLazyDB.cjs +84 -36
  12. package/dist/adapters/drizzleLazyDB.mjs +84 -36
  13. package/dist/adapters/drizzleQuery.cjs +68 -0
  14. package/dist/adapters/drizzleQuery.mjs +67 -0
  15. package/dist/adapters/kysely.cjs +18 -138
  16. package/dist/adapters/kysely.d.cts +3 -12
  17. package/dist/adapters/kysely.d.mts +3 -12
  18. package/dist/adapters/kysely.mjs +19 -139
  19. package/dist/adapters/kyselyCrud.cjs +254 -0
  20. package/dist/adapters/kyselyCrud.mjs +253 -0
  21. package/dist/adapters/kyselyQuery.cjs +56 -0
  22. package/dist/adapters/kyselyQuery.mjs +55 -0
  23. package/dist/adapters/mongodb.cjs +21 -174
  24. package/dist/adapters/mongodb.d.cts +3 -2
  25. package/dist/adapters/mongodb.d.mts +3 -2
  26. package/dist/adapters/mongodb.mjs +21 -174
  27. package/dist/adapters/mongodbCollections.cjs +36 -0
  28. package/dist/adapters/mongodbCollections.mjs +30 -0
  29. package/dist/adapters/mongodbQuery.cjs +77 -0
  30. package/dist/adapters/mongodbQuery.mjs +70 -0
  31. package/dist/adapters/mongodbReads.cjs +148 -0
  32. package/dist/adapters/mongodbReads.mjs +147 -0
  33. package/dist/adapters/mongodbWrites.cjs +134 -0
  34. package/dist/adapters/mongodbWrites.mjs +133 -0
  35. package/dist/adapters/prisma.cjs +205 -180
  36. package/dist/adapters/prisma.d.cts +3 -3
  37. package/dist/adapters/prisma.d.mts +3 -3
  38. package/dist/adapters/prisma.mjs +206 -181
  39. package/dist/adapters/prismaQuery.cjs +58 -0
  40. package/dist/adapters/prismaQuery.mjs +56 -0
  41. package/dist/adapters/prismaRows.cjs +198 -0
  42. package/dist/adapters/prismaRows.mjs +188 -0
  43. package/dist/apiKeys.cjs +139 -0
  44. package/dist/apiKeys.d.cts +50 -0
  45. package/dist/apiKeys.d.mts +50 -0
  46. package/dist/apiKeys.mjs +133 -0
  47. package/dist/createHotUpdaterCore.cjs +48 -26
  48. package/dist/createHotUpdaterCore.d.cts +49 -17
  49. package/dist/createHotUpdaterCore.d.mts +49 -17
  50. package/dist/createHotUpdaterCore.mjs +51 -29
  51. package/dist/db/createBundleDiff.cjs +45 -68
  52. package/dist/db/createBundleDiff.d.cts +3 -3
  53. package/dist/db/createBundleDiff.d.mts +3 -3
  54. package/dist/db/createBundleDiff.mjs +47 -68
  55. package/dist/db/databasePluginCore.cjs +138 -0
  56. package/dist/db/databasePluginCore.mjs +137 -0
  57. package/dist/db/fixedMigrator.cjs +36 -93
  58. package/dist/db/fixedMigrator.mjs +36 -93
  59. package/dist/db/fixedMigratorMongo.cjs +319 -0
  60. package/dist/db/fixedMigratorMongo.mjs +319 -0
  61. package/dist/db/fixedMigratorShared.cjs +23 -0
  62. package/dist/db/fixedMigratorShared.mjs +18 -0
  63. package/dist/db/mongoMigrationExecution.cjs +11 -0
  64. package/dist/db/mongoMigrationExecution.mjs +11 -0
  65. package/dist/db/releaseCatalog.cjs +66 -0
  66. package/dist/db/releaseCatalog.d.cts +17 -0
  67. package/dist/db/releaseCatalog.d.mts +17 -0
  68. package/dist/db/releaseCatalog.mjs +64 -0
  69. package/dist/db/schema/mongodb.cjs +14 -6
  70. package/dist/db/schema/mongodb.mjs +14 -6
  71. package/dist/db/schema/registry.cjs +0 -2
  72. package/dist/db/schema/registry.mjs +1 -2
  73. package/dist/db/schema/sql.cjs +31 -14
  74. package/dist/db/schema/sql.mjs +32 -13
  75. package/dist/db/schema/sqlOperations.cjs +4 -4
  76. package/dist/db/schema/sqlOperations.mjs +5 -5
  77. package/dist/db/schemaGenerators.cjs +52 -18
  78. package/dist/db/schemaGenerators.mjs +52 -18
  79. package/dist/db/schemaReadiness.cjs +4 -3
  80. package/dist/db/schemaReadiness.mjs +4 -3
  81. package/dist/db/sqlMigrationExecution.cjs +67 -0
  82. package/dist/db/sqlMigrationExecution.mjs +66 -0
  83. package/dist/db/types.cjs +2 -6
  84. package/dist/db/types.d.cts +60 -16
  85. package/dist/db/types.d.mts +60 -16
  86. package/dist/db/types.mjs +3 -6
  87. package/dist/db/updateArtifacts.cjs +114 -60
  88. package/dist/db/updateArtifacts.mjs +117 -62
  89. package/dist/handler.cjs +108 -282
  90. package/dist/handler.d.cts +3 -46
  91. package/dist/handler.d.mts +3 -46
  92. package/dist/handler.mjs +107 -281
  93. package/dist/handlerBundleRoutes.cjs +155 -0
  94. package/dist/handlerBundleRoutes.mjs +155 -0
  95. package/dist/handlerErrors.cjs +9 -0
  96. package/dist/handlerErrors.mjs +9 -0
  97. package/dist/handlerParameters.cjs +39 -0
  98. package/dist/handlerParameters.mjs +34 -0
  99. package/dist/handlerReleaseCatalogRoutes.cjs +111 -0
  100. package/dist/handlerReleaseCatalogRoutes.mjs +110 -0
  101. package/dist/handlerReleaseManagementRoutes.cjs +125 -0
  102. package/dist/handlerReleaseManagementRoutes.mjs +124 -0
  103. package/dist/handlerTypes.d.cts +63 -0
  104. package/dist/handlerTypes.d.mts +63 -0
  105. package/dist/handlerVersionRoutes.cjs +10 -0
  106. package/dist/handlerVersionRoutes.d.cts +4 -0
  107. package/dist/handlerVersionRoutes.d.mts +4 -0
  108. package/dist/handlerVersionRoutes.mjs +9 -0
  109. package/dist/index.cjs +10 -1
  110. package/dist/index.d.cts +9 -3
  111. package/dist/index.d.mts +9 -3
  112. package/dist/index.mjs +5 -2
  113. package/dist/insights/bounded/activeOverview.cjs +87 -0
  114. package/dist/insights/bounded/activeOverview.mjs +85 -0
  115. package/dist/insights/bounded/installationSearch.cjs +42 -0
  116. package/dist/insights/bounded/installationSearch.mjs +42 -0
  117. package/dist/insights/bounded/persistence.cjs +39 -0
  118. package/dist/insights/bounded/persistence.mjs +38 -0
  119. package/dist/insights/bounded/provider.cjs +170 -0
  120. package/dist/insights/bounded/provider.d.cts +7 -0
  121. package/dist/insights/bounded/provider.d.mts +7 -0
  122. package/dist/insights/bounded/provider.mjs +170 -0
  123. package/dist/insights/bounded/scan.cjs +144 -0
  124. package/dist/insights/bounded/scan.mjs +138 -0
  125. package/dist/insights/domain.d.cts +121 -0
  126. package/dist/insights/domain.d.mts +121 -0
  127. package/dist/insights/errors.cjs +22 -0
  128. package/dist/insights/errors.mjs +20 -0
  129. package/dist/insights/eventInput.cjs +111 -0
  130. package/dist/insights/eventInput.mjs +111 -0
  131. package/dist/insights/persistence.d.cts +6 -0
  132. package/dist/insights/persistence.d.mts +6 -0
  133. package/dist/insights/queryInput.cjs +58 -0
  134. package/dist/insights/queryInput.mjs +55 -0
  135. package/dist/insights/routes.cjs +63 -0
  136. package/dist/insights/routes.mjs +61 -0
  137. package/dist/insights/types.d.cts +17 -0
  138. package/dist/insights/types.d.mts +17 -0
  139. package/dist/node.cjs +19 -12
  140. package/dist/node.d.cts +15 -10
  141. package/dist/node.d.mts +15 -10
  142. package/dist/node.mjs +19 -13
  143. package/dist/package.cjs +1 -1
  144. package/dist/package.mjs +1 -1
  145. package/dist/schema/dsl.cjs +19 -2
  146. package/dist/schema/dsl.mjs +17 -3
  147. package/dist/schema/index.cjs +1 -8
  148. package/dist/schema/index.mjs +2 -8
  149. package/dist/schema/types.cjs +3 -1
  150. package/dist/schema/types.mjs +3 -2
  151. package/dist/schema/v1_0_0.cjs +364 -0
  152. package/dist/schema/v1_0_0.mjs +357 -0
  153. package/dist/storageAccess.cjs +69 -25
  154. package/dist/storageAccess.mjs +68 -25
  155. package/dist/types/index.d.cts +4 -3
  156. package/dist/types/index.d.mts +5 -4
  157. package/package.json +8 -7
  158. package/src/adapters/databaseConstraintErrors.ts +25 -0
  159. package/src/adapters/databasePluginTestDatabase.ts +106 -0
  160. package/src/adapters/databasePluginUtils.spec.ts +29 -0
  161. package/src/adapters/databasePluginUtils.ts +214 -0
  162. package/src/adapters/drizzle.spec.ts +208 -47
  163. package/src/adapters/drizzle.ts +106 -293
  164. package/src/adapters/drizzleCrud.ts +419 -0
  165. package/src/adapters/drizzleLazyDB.ts +206 -100
  166. package/src/adapters/drizzleQuery.ts +164 -0
  167. package/src/adapters/kysely.spec.ts +126 -88
  168. package/src/adapters/kysely.ts +76 -334
  169. package/src/adapters/kyselyCrud.ts +588 -0
  170. package/src/adapters/kyselyQuery.ts +128 -0
  171. package/src/adapters/mongodb.spec.ts +141 -0
  172. package/src/adapters/mongodb.ts +60 -288
  173. package/src/adapters/mongodbCollections.ts +62 -0
  174. package/src/adapters/mongodbQuery.ts +226 -0
  175. package/src/adapters/mongodbReads.ts +311 -0
  176. package/src/adapters/mongodbRows.spec.ts +64 -0
  177. package/src/adapters/mongodbRows.ts +118 -0
  178. package/src/adapters/mongodbTestClient.ts +342 -0
  179. package/src/adapters/mongodbTestFilter.ts +166 -0
  180. package/src/adapters/mongodbWrites.ts +260 -0
  181. package/src/adapters/prisma.spec.ts +196 -0
  182. package/src/adapters/prisma.ts +417 -292
  183. package/src/adapters/prismaQuery.ts +129 -0
  184. package/src/adapters/prismaRows.spec.ts +98 -0
  185. package/src/adapters/prismaRows.ts +301 -0
  186. package/src/adapters/prismaTestClient.ts +396 -0
  187. package/src/apiKeys.integration.spec.ts +192 -0
  188. package/src/apiKeys.spec.ts +162 -0
  189. package/src/apiKeys.ts +220 -0
  190. package/src/createHotUpdaterCore.ts +164 -100
  191. package/src/db/bundleRows.spec.ts +164 -0
  192. package/src/db/bundleRows.ts +10 -140
  193. package/src/db/createBundleDiff.spec.ts +172 -127
  194. package/src/db/createBundleDiff.ts +91 -110
  195. package/src/db/databasePluginCore.spec.ts +62 -0
  196. package/src/db/databasePluginCore.testFixtures.ts +76 -0
  197. package/src/db/databasePluginCore.ts +185 -0
  198. package/src/db/databasePluginUpdateCheck.bench.ts +107 -0
  199. package/src/db/fixedMigrator.spec.ts +184 -42
  200. package/src/db/fixedMigrator.ts +64 -205
  201. package/src/db/fixedMigratorMongo.spec.ts +192 -0
  202. package/src/db/fixedMigratorMongo.ts +425 -0
  203. package/src/db/fixedMigratorShared.ts +36 -0
  204. package/src/db/hotUpdaterSchema.ts +0 -1
  205. package/src/db/index.spec.ts +333 -1025
  206. package/src/db/mongoMigrationExecution.ts +23 -0
  207. package/src/db/node-sqlite.d.ts +25 -0
  208. package/src/db/releaseCatalog.ts +148 -0
  209. package/src/db/schema/mongodb.ts +20 -6
  210. package/src/db/schema/sql.ts +52 -11
  211. package/src/db/schema/sqlOperations.ts +5 -4
  212. package/src/db/schemaGenerators.ts +107 -23
  213. package/src/db/schemaReadiness.ts +2 -1
  214. package/src/db/sqlMigrationExecution.spec.ts +65 -0
  215. package/src/db/sqlMigrationExecution.ts +108 -0
  216. package/src/db/types.spec.ts +55 -0
  217. package/src/db/types.ts +129 -65
  218. package/src/db/updateArtifacts.spec.ts +359 -0
  219. package/src/db/updateArtifacts.ts +290 -126
  220. package/src/handler-standalone.integration.spec.ts +401 -364
  221. package/src/handler.spec.ts +137 -582
  222. package/src/handler.testFixtures.ts +30 -0
  223. package/src/handler.ts +218 -616
  224. package/src/handlerAuth.integration.spec.ts +33 -0
  225. package/src/handlerBundleRoutes.ts +259 -0
  226. package/src/handlerErrors.ts +7 -0
  227. package/src/handlerManagement.spec.ts +262 -0
  228. package/src/handlerParameters.ts +105 -0
  229. package/src/handlerReleaseCatalogRoutes.ts +154 -0
  230. package/src/handlerReleaseManagementRoutes.ts +213 -0
  231. package/src/handlerTypes.ts +96 -0
  232. package/src/handlerVersionRoutes.ts +12 -0
  233. package/src/index.ts +22 -2
  234. package/src/insights/bounded/activeOverview.spec.ts +189 -0
  235. package/src/insights/bounded/activeOverview.ts +148 -0
  236. package/src/insights/bounded/installationSearch.spec.ts +130 -0
  237. package/src/insights/bounded/installationSearch.ts +69 -0
  238. package/src/insights/bounded/persistence.ts +43 -0
  239. package/src/insights/bounded/provider.spec.ts +219 -0
  240. package/src/insights/bounded/provider.ts +229 -0
  241. package/src/insights/bounded/scan.ts +235 -0
  242. package/src/insights/domain.ts +139 -0
  243. package/src/insights/errors.ts +18 -0
  244. package/src/insights/eventInput.ts +168 -0
  245. package/src/insights/insights.integration.spec.ts +144 -0
  246. package/src/insights/persistence.ts +10 -0
  247. package/src/insights/queryInput.ts +102 -0
  248. package/src/insights/routes.ts +123 -0
  249. package/src/insights/types.ts +44 -0
  250. package/src/node.spec.ts +79 -10
  251. package/src/node.ts +20 -17
  252. package/src/releaseCatalogRoutes.integration.spec.ts +238 -0
  253. package/src/runtime.spec.ts +126 -959
  254. package/src/runtime.testFixtures.ts +71 -0
  255. package/src/schema/dsl-all-versions.spec.ts +26 -17
  256. package/src/schema/dsl.ts +41 -2
  257. package/src/schema/index.ts +3 -9
  258. package/src/schema/types.ts +9 -3
  259. package/src/schema/v1_0_0.spec.ts +146 -0
  260. package/src/schema/v1_0_0.ts +465 -0
  261. package/src/storageAccess.spec.ts +127 -32
  262. package/src/storageAccess.ts +106 -55
  263. package/src/types/index.ts +2 -1
  264. package/dist/db/bundleRows.cjs +0 -82
  265. package/dist/db/bundleRows.d.cts +0 -33
  266. package/dist/db/bundleRows.d.mts +0 -33
  267. package/dist/db/bundleRows.mjs +0 -79
  268. package/dist/db/pluginCore.cjs +0 -242
  269. package/dist/db/pluginCore.mjs +0 -241
  270. package/dist/db/schema/sqlMigrations.cjs +0 -74
  271. package/dist/db/schema/sqlMigrations.mjs +0 -73
  272. package/dist/db/schemaEnhancements.cjs +0 -20
  273. package/dist/db/schemaEnhancements.mjs +0 -19
  274. package/dist/route.cjs +0 -7
  275. package/dist/route.mjs +0 -7
  276. package/dist/schema/v0_21_0.cjs +0 -38
  277. package/dist/schema/v0_21_0.mjs +0 -37
  278. package/dist/schema/v0_29_0.cjs +0 -45
  279. package/dist/schema/v0_29_0.mjs +0 -44
  280. package/dist/schema/v0_31_0.cjs +0 -82
  281. package/dist/schema/v0_31_0.mjs +0 -80
  282. package/src/db/pluginCore.spec.ts +0 -1095
  283. package/src/db/pluginCore.ts +0 -475
  284. package/src/db/pluginUpdateCheck.bench.ts +0 -254
  285. package/src/db/schema/sqlMigrations.ts +0 -219
  286. package/src/db/schemaEnhancements.ts +0 -55
  287. package/src/route.ts +0 -7
  288. package/src/schema/v0_21_0.ts +0 -52
  289. package/src/schema/v0_29_0.ts +0 -62
  290. package/src/schema/v0_31_0.spec.ts +0 -73
  291. package/src/schema/v0_31_0.ts +0 -120
@@ -0,0 +1,229 @@
1
+ import type {
2
+ BundleEventInsightsWindow,
3
+ InstallationHistoryRow,
4
+ } from "../domain";
5
+ import type {
6
+ InsightsPersistence,
7
+ BundleEventPersistenceRow,
8
+ } from "../persistence";
9
+ import type { InsightsProvider } from "../types";
10
+ import { collectActiveInstallationOverview } from "./activeOverview";
11
+ import { searchEventInstallations } from "./installationSearch";
12
+ import { createBundleEventRow } from "./persistence";
13
+ import {
14
+ INSIGHTS_SCAN_MAX_ROWS,
15
+ collectEventActivity,
16
+ compareCodePoints,
17
+ compareEventNewest,
18
+ materializeActiveRows,
19
+ materializeEventRows,
20
+ materializeRowsForWindow,
21
+ } from "./scan";
22
+
23
+ type TransitionEventRow = BundleEventPersistenceRow & {
24
+ readonly type: "UPDATE_APPLIED" | "RECOVERED";
25
+ };
26
+
27
+ const isTransitionEventRow = (
28
+ row: BundleEventPersistenceRow,
29
+ ): row is TransitionEventRow =>
30
+ row.type === "UPDATE_APPLIED" || row.type === "RECOVERED";
31
+
32
+ const toHistoryRow = (row: TransitionEventRow): InstallationHistoryRow => ({
33
+ id: row.id,
34
+ type: row.type,
35
+ fromBundleId: row.from_bundle_id,
36
+ toBundleId: row.to_bundle_id,
37
+ username: row.username,
38
+ userId: row.user_id,
39
+ platform: row.platform,
40
+ appVersion: row.app_version,
41
+ channel: row.channel,
42
+ cohort: row.cohort,
43
+ receivedAtMs: row.received_at_ms,
44
+ });
45
+
46
+ const isInstalledForBundle = (
47
+ row: TransitionEventRow,
48
+ bundleId: string,
49
+ ): boolean => row.type === "UPDATE_APPLIED" && row.to_bundle_id === bundleId;
50
+
51
+ const isRecoveredFromBundle = (
52
+ row: TransitionEventRow,
53
+ bundleId: string,
54
+ ): boolean => row.type === "RECOVERED" && row.from_bundle_id === bundleId;
55
+
56
+ const countDistinctInstallations = (
57
+ rows: readonly BundleEventPersistenceRow[],
58
+ ): number => new Set(rows.map(({ install_id }) => install_id)).size;
59
+
60
+ const getInsightsResult = async (
61
+ persistence: InsightsPersistence,
62
+ bundleId: string,
63
+ window: BundleEventInsightsWindow,
64
+ limit: number,
65
+ offset: number,
66
+ ) => {
67
+ const scope = { persistence, cutoffMs: Date.now() };
68
+ const rows = (await materializeRowsForWindow(scope, window)).filter(
69
+ isTransitionEventRow,
70
+ );
71
+ const installedRows = rows.filter((row) =>
72
+ isInstalledForBundle(row, bundleId),
73
+ );
74
+ const recoveredRows = rows.filter((row) =>
75
+ isRecoveredFromBundle(row, bundleId),
76
+ );
77
+ const installed = collectEventActivity({
78
+ rows: installedRows,
79
+ window,
80
+ cutoffMs: scope.cutoffMs,
81
+ });
82
+ const recovered = collectEventActivity({
83
+ rows: recoveredRows,
84
+ window,
85
+ cutoffMs: scope.cutoffMs,
86
+ });
87
+ const recentRows = [...installedRows, ...recoveredRows].sort(
88
+ compareEventNewest,
89
+ );
90
+ return {
91
+ summary: { installed: installed.summary, recovered: recovered.summary },
92
+ series: { installed: installed.series, recovered: recovered.series },
93
+ cohorts: { installed: installed.cohorts, recovered: recovered.cohorts },
94
+ recentEvents: {
95
+ data: recentRows.slice(offset, offset + limit).map(toHistoryRow),
96
+ pagination: { total: recentRows.length, limit, offset },
97
+ },
98
+ };
99
+ };
100
+
101
+ const getInsightsSummaries = async (
102
+ persistence: InsightsPersistence,
103
+ bundleIds: readonly string[],
104
+ window: BundleEventInsightsWindow,
105
+ ) => {
106
+ const normalizedBundleIds = [...new Set(bundleIds)];
107
+ if (normalizedBundleIds.length === 0) return [];
108
+
109
+ const requestedBundleIds = new Set(normalizedBundleIds);
110
+ const installedByBundleId = new Map<string, Set<string>>();
111
+ const recoveredByBundleId = new Map<string, Set<string>>();
112
+ const rows = (
113
+ await materializeRowsForWindow(
114
+ { persistence, cutoffMs: Date.now() },
115
+ window,
116
+ )
117
+ ).filter(isTransitionEventRow);
118
+
119
+ for (const row of rows) {
120
+ const bundleId =
121
+ row.type === "UPDATE_APPLIED" ? row.to_bundle_id : row.from_bundle_id;
122
+ if (!requestedBundleIds.has(bundleId)) continue;
123
+
124
+ const counts =
125
+ row.type === "UPDATE_APPLIED" ? installedByBundleId : recoveredByBundleId;
126
+ const installIds = counts.get(bundleId) ?? new Set<string>();
127
+ installIds.add(row.install_id);
128
+ counts.set(bundleId, installIds);
129
+ }
130
+
131
+ return normalizedBundleIds.map((bundleId) => ({
132
+ bundleId,
133
+ installed: installedByBundleId.get(bundleId)?.size ?? 0,
134
+ recovered: recoveredByBundleId.get(bundleId)?.size ?? 0,
135
+ }));
136
+ };
137
+
138
+ export const createInsightsProvider = (
139
+ persistence: InsightsPersistence,
140
+ ): InsightsProvider =>
141
+ Object.freeze({
142
+ mode: "bounded",
143
+ maxMatchingRows: INSIGHTS_SCAN_MAX_ROWS,
144
+ async appendBundleEvent(input) {
145
+ await persistence.append(createBundleEventRow(input));
146
+ },
147
+ async getBundleEventSummary(bundleId) {
148
+ const rows = (
149
+ await materializeEventRows({ persistence, cutoffMs: Date.now() })
150
+ ).filter(isTransitionEventRow);
151
+ return {
152
+ installed: countDistinctInstallations(
153
+ rows.filter((row) => isInstalledForBundle(row, bundleId)),
154
+ ),
155
+ recovered: countDistinctInstallations(
156
+ rows.filter((row) => isRecoveredFromBundle(row, bundleId)),
157
+ ),
158
+ };
159
+ },
160
+ getBundleEventSummaries(bundleIds, window) {
161
+ return getInsightsSummaries(persistence, bundleIds, window);
162
+ },
163
+ getBundleEventInsights(bundleId, window, limit, offset) {
164
+ return getInsightsResult(persistence, bundleId, window, limit, offset);
165
+ },
166
+ async getBundleEventOverview() {
167
+ const rows = await materializeEventRows({
168
+ persistence,
169
+ cutoffMs: Date.now(),
170
+ });
171
+ const latestByInstall = new Map<string, BundleEventPersistenceRow>();
172
+ for (const row of rows) {
173
+ const current = latestByInstall.get(row.install_id);
174
+ if (current === undefined || compareEventNewest(row, current) < 0) {
175
+ latestByInstall.set(row.install_id, row);
176
+ }
177
+ }
178
+ const counts = new Map<string, number>();
179
+ for (const row of latestByInstall.values()) {
180
+ counts.set(row.to_bundle_id, (counts.get(row.to_bundle_id) ?? 0) + 1);
181
+ }
182
+ return {
183
+ trackedInstallations: latestByInstall.size,
184
+ bundles: [...counts]
185
+ .map(([bundleId, installations]) => ({ bundleId, installations }))
186
+ .sort(
187
+ (left, right) =>
188
+ right.installations - left.installations ||
189
+ compareCodePoints(left.bundleId, right.bundleId),
190
+ ),
191
+ };
192
+ },
193
+ async getActiveInstallationOverview(input) {
194
+ const asOfMs = Date.now();
195
+ const rows = await materializeActiveRows(
196
+ { persistence, cutoffMs: asOfMs },
197
+ input.window,
198
+ );
199
+ return collectActiveInstallationOverview({
200
+ rows,
201
+ asOfMs,
202
+ window: input.window,
203
+ ...(input.userId === undefined ? {} : { userId: input.userId }),
204
+ });
205
+ },
206
+ async searchInstallations(query, limit, offset) {
207
+ const rows = await materializeEventRows({
208
+ persistence,
209
+ cutoffMs: Date.now(),
210
+ });
211
+ return searchEventInstallations({ rows, query, limit, offset });
212
+ },
213
+ async getInstallationHistory(installId, limit, offset) {
214
+ const rows = await materializeEventRows({
215
+ persistence,
216
+ cutoffMs: Date.now(),
217
+ });
218
+ const ordered = rows
219
+ .filter(
220
+ (row): row is TransitionEventRow =>
221
+ row.install_id === installId && isTransitionEventRow(row),
222
+ )
223
+ .toSorted(compareEventNewest);
224
+ return {
225
+ data: ordered.slice(offset, offset + limit).map(toHistoryRow),
226
+ pagination: { total: ordered.length, limit, offset },
227
+ };
228
+ },
229
+ } satisfies InsightsProvider);
@@ -0,0 +1,235 @@
1
+ import type {
2
+ ActiveInstallationWindow,
3
+ BundleEventInsightsWindow,
4
+ } from "../domain";
5
+ import { InsightsScanLimitExceededError } from "../errors";
6
+ import type {
7
+ InsightsPersistence,
8
+ BundleEventPersistenceRow,
9
+ } from "../persistence";
10
+ import {
11
+ ACTIVE_BUNDLE_EVENT_TYPES,
12
+ getActiveWindowDefinition,
13
+ } from "./activeOverview";
14
+
15
+ export const INSIGHTS_SCAN_MAX_ROWS = 50_000;
16
+ export const INSIGHTS_MATERIALIZATION_LIMIT = INSIGHTS_SCAN_MAX_ROWS + 1;
17
+ export const INSIGHTS_SCAN_PAGE_SIZE = 1_000;
18
+ const INSIGHTS_LOWER_BOUND_ID = "00000000-0000-0000-0000-000000000000";
19
+
20
+ export type InsightsScanScope = {
21
+ readonly persistence: InsightsPersistence;
22
+ readonly cutoffMs: number;
23
+ readonly lowerBoundMs?: number;
24
+ };
25
+
26
+ type EventActivityRequest = {
27
+ readonly rows: readonly BundleEventPersistenceRow[];
28
+ readonly window: BundleEventInsightsWindow;
29
+ readonly cutoffMs: number;
30
+ };
31
+
32
+ export const compareCodePoints = (left: string, right: string): number => {
33
+ if (left < right) return -1;
34
+ if (left > right) return 1;
35
+ return 0;
36
+ };
37
+
38
+ export const compareEventNewest = (
39
+ left: BundleEventPersistenceRow,
40
+ right: BundleEventPersistenceRow,
41
+ ): number =>
42
+ right.received_at_ms - left.received_at_ms ||
43
+ compareCodePoints(right.id, left.id);
44
+
45
+ const compareEventOldest = (
46
+ left: { readonly received_at_ms: number; readonly id: string },
47
+ right: { readonly received_at_ms: number; readonly id: string },
48
+ ): number =>
49
+ left.received_at_ms - right.received_at_ms ||
50
+ compareCodePoints(left.id, right.id);
51
+
52
+ export const materializeEventRows = async (
53
+ scope: InsightsScanScope,
54
+ ): Promise<readonly BundleEventPersistenceRow[]> => {
55
+ const rows: BundleEventPersistenceRow[] = [];
56
+ const seenIds = new Set<string>();
57
+ let after =
58
+ scope.lowerBoundMs === undefined
59
+ ? undefined
60
+ : { receivedAtMs: scope.lowerBoundMs, id: INSIGHTS_LOWER_BOUND_ID };
61
+ while (rows.length < INSIGHTS_MATERIALIZATION_LIMIT) {
62
+ const limit = Math.min(
63
+ INSIGHTS_SCAN_PAGE_SIZE,
64
+ INSIGHTS_MATERIALIZATION_LIMIT - rows.length,
65
+ );
66
+ const page = await scope.persistence.scan({
67
+ beforeReceivedAtMs: scope.cutoffMs,
68
+ ...(after === undefined ? {} : { after }),
69
+ limit,
70
+ });
71
+ if (page.length === 0) break;
72
+ if (page.length > limit) throw new InsightsPersistenceOrderError();
73
+ let previous =
74
+ after === undefined
75
+ ? undefined
76
+ : { received_at_ms: after.receivedAtMs, id: after.id };
77
+ for (const row of page) {
78
+ if (
79
+ row.received_at_ms >= scope.cutoffMs ||
80
+ (previous !== undefined && compareEventOldest(previous, row) >= 0) ||
81
+ seenIds.has(row.id)
82
+ ) {
83
+ throw new InsightsPersistenceOrderError();
84
+ }
85
+ seenIds.add(row.id);
86
+ rows.push(row);
87
+ previous = row;
88
+ }
89
+ const last = page.at(-1);
90
+ if (last !== undefined) {
91
+ after = { receivedAtMs: last.received_at_ms, id: last.id };
92
+ }
93
+ if (rows.length > INSIGHTS_SCAN_MAX_ROWS) {
94
+ throw new InsightsScanLimitExceededError(INSIGHTS_SCAN_MAX_ROWS);
95
+ }
96
+ }
97
+ return rows;
98
+ };
99
+
100
+ export class InsightsPersistenceOrderError extends Error {
101
+ readonly name = "InsightsPersistenceOrderError";
102
+
103
+ constructor() {
104
+ super("Insights persistence did not advance its scan cursor.");
105
+ }
106
+ }
107
+
108
+ export const materializeActiveRows = async (
109
+ scope: InsightsScanScope,
110
+ window: ActiveInstallationWindow,
111
+ ): Promise<readonly BundleEventPersistenceRow[]> => {
112
+ const definition = getActiveWindowDefinition(window);
113
+ const durationMs = definition.bucketCount * definition.bucketSizeMs;
114
+ return (
115
+ await materializeEventRows({
116
+ ...scope,
117
+ lowerBoundMs: scope.cutoffMs - durationMs,
118
+ })
119
+ ).filter(
120
+ (row) =>
121
+ row.received_at_ms >= scope.cutoffMs - durationMs &&
122
+ ACTIVE_BUNDLE_EVENT_TYPES.includes(row.type),
123
+ );
124
+ };
125
+
126
+ const startOfUtcHour = (value: number): number => {
127
+ const date = new Date(value);
128
+ return Date.UTC(
129
+ date.getUTCFullYear(),
130
+ date.getUTCMonth(),
131
+ date.getUTCDate(),
132
+ date.getUTCHours(),
133
+ );
134
+ };
135
+
136
+ const startOfUtcDay = (value: number): number => {
137
+ const date = new Date(value);
138
+ return Date.UTC(date.getUTCFullYear(), date.getUTCMonth(), date.getUTCDate());
139
+ };
140
+
141
+ export const getWindowRange = (
142
+ window: Exclude<BundleEventInsightsWindow, "all">,
143
+ now: number,
144
+ ): { readonly sizeMs: number; readonly rangeStart: number } => {
145
+ if (window === "24h") {
146
+ return {
147
+ sizeMs: 60 * 60 * 1_000,
148
+ rangeStart: startOfUtcHour(now) - 23 * 60 * 60 * 1_000,
149
+ };
150
+ }
151
+ const days = window === "7d" ? 7 : 30;
152
+ return {
153
+ sizeMs: 24 * 60 * 60 * 1_000,
154
+ rangeStart: startOfUtcDay(now) - (days - 1) * 24 * 60 * 60 * 1_000,
155
+ };
156
+ };
157
+
158
+ export const materializeRowsForWindow = async (
159
+ scope: InsightsScanScope,
160
+ window: BundleEventInsightsWindow,
161
+ ): Promise<readonly BundleEventPersistenceRow[]> => {
162
+ if (window === "all") return materializeEventRows(scope);
163
+ const range = getWindowRange(window, scope.cutoffMs);
164
+ const rows = await materializeEventRows({
165
+ ...scope,
166
+ lowerBoundMs: range.rangeStart,
167
+ });
168
+ return rows.filter(
169
+ ({ received_at_ms }) => received_at_ms >= range.rangeStart,
170
+ );
171
+ };
172
+
173
+ const bucketStart = (receivedAtMs: number, sizeMs: number): number =>
174
+ sizeMs === 60 * 60 * 1_000
175
+ ? startOfUtcHour(receivedAtMs)
176
+ : startOfUtcDay(receivedAtMs);
177
+
178
+ const createSeries = (request: EventActivityRequest) => {
179
+ const range =
180
+ request.window === "all"
181
+ ? undefined
182
+ : getWindowRange(request.window, request.cutoffMs);
183
+ const sizeMs = range?.sizeMs ?? 24 * 60 * 60 * 1_000;
184
+ const installIdsByBucket = new Map<number, Set<string>>();
185
+ let oldestMs = request.cutoffMs;
186
+ for (const row of request.rows) {
187
+ oldestMs = Math.min(oldestMs, row.received_at_ms);
188
+ const start = bucketStart(row.received_at_ms, sizeMs);
189
+ const installIds = installIdsByBucket.get(start) ?? new Set<string>();
190
+ installIds.add(row.install_id);
191
+ installIdsByBucket.set(start, installIds);
192
+ }
193
+ const first = range?.rangeStart ?? startOfUtcDay(oldestMs);
194
+ const last = bucketStart(request.cutoffMs, sizeMs);
195
+ return Array.from(
196
+ { length: Math.floor((last - first) / sizeMs) + 1 },
197
+ (_, index) => {
198
+ const start = first + index * sizeMs;
199
+ return {
200
+ bucketStartMs: start,
201
+ value: installIdsByBucket.get(start)?.size ?? 0,
202
+ };
203
+ },
204
+ );
205
+ };
206
+
207
+ export const collectEventActivity = (request: EventActivityRequest) => {
208
+ const range =
209
+ request.window === "all"
210
+ ? undefined
211
+ : getWindowRange(request.window, request.cutoffMs);
212
+ const rows =
213
+ range === undefined
214
+ ? request.rows
215
+ : request.rows.filter(
216
+ ({ received_at_ms }) =>
217
+ received_at_ms >= range.rangeStart &&
218
+ received_at_ms < request.cutoffMs,
219
+ );
220
+ const installs = new Set<string>();
221
+ const installsByCohort = new Map<string, Set<string>>();
222
+ for (const row of rows) {
223
+ installs.add(row.install_id);
224
+ const cohort = installsByCohort.get(row.cohort) ?? new Set<string>();
225
+ cohort.add(row.install_id);
226
+ installsByCohort.set(row.cohort, cohort);
227
+ }
228
+ return {
229
+ summary: installs.size,
230
+ cohorts: [...installsByCohort]
231
+ .sort(([left], [right]) => compareCodePoints(left, right))
232
+ .map(([cohort, installIds]) => ({ cohort, value: installIds.size })),
233
+ series: createSeries({ ...request, rows }),
234
+ };
235
+ };
@@ -0,0 +1,139 @@
1
+ export type CreateBundleEventRequestBase = {
2
+ readonly installId: string;
3
+ readonly toBundleId: string;
4
+ readonly userId?: string;
5
+ readonly username?: string;
6
+ readonly platform: "ios" | "android";
7
+ readonly appVersion: string;
8
+ readonly channel: string;
9
+ readonly cohort: string;
10
+ readonly fingerprintHash: string | null;
11
+ readonly sdkVersion?: string | null;
12
+ readonly fromReleaseId: string | null;
13
+ readonly toReleaseId: string | null;
14
+ };
15
+
16
+ export type CreateBundleEventRequest =
17
+ | (CreateBundleEventRequestBase & {
18
+ readonly type: "UPDATE_APPLIED";
19
+ readonly fromBundleId: string;
20
+ readonly updateStrategy: "fingerprint" | "appVersion";
21
+ })
22
+ | (CreateBundleEventRequestBase & {
23
+ readonly type: "RECOVERED";
24
+ readonly fromBundleId: string;
25
+ readonly updateStrategy: "fingerprint" | "appVersion";
26
+ })
27
+ | (CreateBundleEventRequestBase & {
28
+ readonly type: "RELEASE_ADOPTED";
29
+ readonly fromBundleId: string;
30
+ readonly updateStrategy: "fingerprint" | "appVersion";
31
+ })
32
+ | (CreateBundleEventRequestBase & {
33
+ readonly type: "UNCHANGED";
34
+ readonly fromBundleId: null;
35
+ readonly updateStrategy: null;
36
+ });
37
+
38
+ export type BundleEventSummary = {
39
+ readonly installed: number;
40
+ readonly recovered: number;
41
+ };
42
+
43
+ export type BundleEventSummaryByBundle = BundleEventSummary & {
44
+ readonly bundleId: string;
45
+ };
46
+
47
+ export type BundleEventInsightsWindow = "24h" | "7d" | "30d" | "all";
48
+ export type ActiveInstallationWindow = "24h" | "7d" | "30d";
49
+
50
+ export type InstallationSearchRow = {
51
+ readonly installId: string;
52
+ readonly username: string | null;
53
+ readonly userId: string | null;
54
+ readonly lastKnownBundleId: string;
55
+ readonly latestStatus:
56
+ | "UPDATE_APPLIED"
57
+ | "RECOVERED"
58
+ | "RELEASE_ADOPTED"
59
+ | "UNCHANGED";
60
+ readonly platform: "ios" | "android";
61
+ readonly appVersion: string;
62
+ readonly channel: string;
63
+ readonly cohort: string;
64
+ readonly receivedAtMs: number;
65
+ };
66
+
67
+ export type InstallationHistoryRow = {
68
+ readonly id: string;
69
+ readonly type: "UPDATE_APPLIED" | "RECOVERED";
70
+ readonly fromBundleId: string;
71
+ readonly toBundleId: string;
72
+ readonly username: string | null;
73
+ readonly userId: string | null;
74
+ readonly platform: "ios" | "android";
75
+ readonly appVersion: string;
76
+ readonly channel: string;
77
+ readonly cohort: string;
78
+ readonly receivedAtMs: number;
79
+ };
80
+
81
+ export type OffsetPaginationResult<TData> = {
82
+ readonly data: readonly TData[];
83
+ readonly pagination: {
84
+ readonly total: number;
85
+ readonly limit: number;
86
+ readonly offset: number;
87
+ };
88
+ };
89
+
90
+ export type InsightsSeriesPoint = {
91
+ readonly bucketStartMs: number;
92
+ readonly value: number;
93
+ };
94
+
95
+ export type InsightsCohortPoint = {
96
+ readonly cohort: string;
97
+ readonly value: number;
98
+ };
99
+
100
+ export type BundleEventInsightsResult = {
101
+ readonly summary: BundleEventSummary;
102
+ readonly series: {
103
+ readonly installed: readonly InsightsSeriesPoint[];
104
+ readonly recovered: readonly InsightsSeriesPoint[];
105
+ };
106
+ readonly cohorts: {
107
+ readonly installed: readonly InsightsCohortPoint[];
108
+ readonly recovered: readonly InsightsCohortPoint[];
109
+ };
110
+ readonly recentEvents: OffsetPaginationResult<InstallationHistoryRow>;
111
+ };
112
+
113
+ export type BundleEventOverview = {
114
+ readonly trackedInstallations: number;
115
+ readonly bundles: readonly {
116
+ readonly bundleId: string;
117
+ readonly installations: number;
118
+ }[];
119
+ };
120
+
121
+ export type ActiveInstallationOverview = {
122
+ readonly asOfMs: number;
123
+ readonly window: ActiveInstallationWindow;
124
+ readonly activeInstallations: number;
125
+ readonly series: readonly InsightsSeriesPoint[];
126
+ readonly bundleSeries: readonly {
127
+ readonly bundleId: string;
128
+ readonly series: readonly InsightsSeriesPoint[];
129
+ }[];
130
+ readonly bundles: readonly {
131
+ readonly bundleId: string;
132
+ readonly installations: number;
133
+ }[];
134
+ };
135
+
136
+ export type ActiveInstallationInput = {
137
+ readonly window: ActiveInstallationWindow;
138
+ readonly userId?: string;
139
+ };
@@ -0,0 +1,18 @@
1
+ export class InsightsScanLimitExceededError extends Error {
2
+ constructor(readonly limit: number) {
3
+ super(`Insights event scan exceeded ${limit} rows.`);
4
+ this.name = "InsightsScanLimitExceededError";
5
+ }
6
+ }
7
+
8
+ export class InsightsBadRequestError extends Error {
9
+ readonly name = "InsightsBadRequestError";
10
+ }
11
+
12
+ export class InsightsPayloadTooLargeError extends Error {
13
+ readonly name = "InsightsPayloadTooLargeError";
14
+
15
+ constructor(readonly maximumBytes: number) {
16
+ super(`Event payload exceeds ${maximumBytes} bytes`);
17
+ }
18
+ }