@hot-updater/server 1.0.0-rc.16 → 1.0.0-rc.18

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 (309) hide show
  1. package/dist/adapters/drizzle.cjs +5 -5
  2. package/dist/adapters/drizzle.mjs +4 -4
  3. package/dist/adapters/kysely.cjs +3 -3
  4. package/dist/adapters/kysely.mjs +2 -2
  5. package/dist/adapters/mongodb.cjs +3 -3
  6. package/dist/adapters/mongodb.mjs +2 -2
  7. package/dist/adapters/mongodbAdapter.cjs +19 -1
  8. package/dist/adapters/mongodbAdapter.mjs +19 -1
  9. package/dist/adapters/prisma.cjs +5 -5
  10. package/dist/adapters/prisma.mjs +4 -4
  11. package/dist/assembly/assemblePlugins.cjs +47 -28
  12. package/dist/assembly/assemblePlugins.d.cts +3 -7
  13. package/dist/assembly/assemblePlugins.d.mts +3 -7
  14. package/dist/assembly/assemblePlugins.mjs +46 -27
  15. package/dist/assembly/clientPlugins.cjs +86 -0
  16. package/dist/assembly/clientPlugins.d.cts +16 -0
  17. package/dist/assembly/clientPlugins.d.mts +16 -0
  18. package/dist/assembly/clientPlugins.mjs +86 -0
  19. package/dist/assembly/configError.cjs +7 -0
  20. package/dist/assembly/configError.d.cts +7 -0
  21. package/dist/assembly/configError.d.mts +7 -0
  22. package/dist/assembly/configError.mjs +7 -0
  23. package/dist/assembly/databasePlugins.cjs +5 -1
  24. package/dist/assembly/databasePlugins.d.cts +5 -5
  25. package/dist/assembly/databasePlugins.d.mts +5 -5
  26. package/dist/assembly/databasePlugins.mjs +5 -1
  27. package/dist/assembly/pluginCli.cjs +125 -0
  28. package/dist/assembly/pluginCli.d.cts +59 -0
  29. package/dist/assembly/pluginCli.d.mts +59 -0
  30. package/dist/assembly/pluginCli.mjs +121 -0
  31. package/dist/createHotUpdaterCore.cjs +14 -16
  32. package/dist/createHotUpdaterCore.d.cts +10 -3
  33. package/dist/createHotUpdaterCore.d.mts +10 -3
  34. package/dist/createHotUpdaterCore.mjs +11 -13
  35. package/dist/database/aggregateBatching.cjs +626 -0
  36. package/dist/database/aggregateBatching.d.cts +10 -0
  37. package/dist/database/aggregateBatching.d.mts +10 -0
  38. package/dist/database/aggregateBatching.mjs +625 -0
  39. package/dist/{insights/errors.cjs → database/busy.cjs} +2 -15
  40. package/dist/database/busy.d.cts +12 -0
  41. package/dist/database/busy.d.mts +12 -0
  42. package/dist/{insights/errors.mjs → database/busy.mjs} +3 -14
  43. package/dist/database/database.cjs +22 -3
  44. package/dist/database/database.d.cts +15 -2
  45. package/dist/database/database.d.mts +15 -2
  46. package/dist/database/database.mjs +22 -3
  47. package/dist/database/definitions.d.cts +10 -0
  48. package/dist/database/definitions.d.mts +10 -0
  49. package/dist/database/engine.d.cts +2 -1
  50. package/dist/database/engine.d.mts +2 -1
  51. package/dist/database/engineAggregates.cjs +7 -4
  52. package/dist/database/engineAggregates.mjs +8 -5
  53. package/dist/database/engineReads.cjs +5 -3
  54. package/dist/database/engineReads.mjs +6 -4
  55. package/dist/database/engineTransaction.cjs +2 -6
  56. package/dist/database/engineTransaction.mjs +2 -6
  57. package/dist/database/fence.cjs +2 -1
  58. package/dist/database/fence.mjs +2 -1
  59. package/dist/database/index.cjs +17 -8
  60. package/dist/database/index.d.cts +5 -4
  61. package/dist/database/index.d.mts +5 -4
  62. package/dist/database/index.mjs +6 -5
  63. package/dist/database/kv/kvAdapter.cjs +15 -3
  64. package/dist/database/kv/kvAdapter.d.cts +8 -0
  65. package/dist/database/kv/kvAdapter.d.mts +8 -0
  66. package/dist/database/kv/kvAdapter.mjs +16 -4
  67. package/dist/database/resolveSchema.cjs +4 -1
  68. package/dist/database/resolveSchema.d.cts +1 -1
  69. package/dist/database/resolveSchema.d.mts +1 -1
  70. package/dist/database/resolveSchema.mjs +4 -1
  71. package/dist/database/retention.cjs +92 -0
  72. package/dist/database/retention.mjs +90 -0
  73. package/dist/database/schema.cjs +5 -2
  74. package/dist/database/schema.d.cts +30 -1
  75. package/dist/database/schema.d.mts +30 -1
  76. package/dist/database/schema.mjs +5 -2
  77. package/dist/database/sql/sqlAdapter.cjs +8 -0
  78. package/dist/database/sql/sqlAdapter.mjs +9 -1
  79. package/dist/database/sql/sqlSchema.cjs +56 -0
  80. package/dist/database/sql/sqlSchema.mjs +55 -1
  81. package/dist/db/coreDatabase.cjs +85 -0
  82. package/dist/db/coreDatabase.d.cts +57 -0
  83. package/dist/db/coreDatabase.d.mts +57 -0
  84. package/dist/db/coreDatabase.mjs +78 -0
  85. package/dist/db/index.cjs +11 -3
  86. package/dist/db/index.d.cts +7 -3
  87. package/dist/db/index.d.mts +7 -3
  88. package/dist/db/index.mjs +6 -3
  89. package/dist/db/types.d.cts +3 -3
  90. package/dist/db/types.d.mts +3 -3
  91. package/dist/diff.cjs +3 -0
  92. package/dist/diff.d.cts +2 -0
  93. package/dist/diff.d.mts +2 -0
  94. package/dist/diff.mjs +2 -0
  95. package/dist/handler.cjs +2 -14
  96. package/dist/handler.mjs +1 -13
  97. package/dist/handlerReleaseCatalogRoutes.cjs +21 -2
  98. package/dist/handlerReleaseCatalogRoutes.mjs +21 -2
  99. package/dist/index.cjs +2 -6
  100. package/dist/index.d.cts +4 -7
  101. package/dist/index.d.mts +4 -7
  102. package/dist/index.mjs +2 -4
  103. package/dist/package.cjs +1 -1
  104. package/dist/package.mjs +1 -1
  105. package/dist/{apiKeys.cjs → plugins/api-keys/apiKeys.cjs} +1 -1
  106. package/dist/{apiKeys.d.cts → plugins/api-keys/apiKeys.d.cts} +2 -2
  107. package/dist/{apiKeys.d.mts → plugins/api-keys/apiKeys.d.mts} +2 -2
  108. package/dist/{apiKeys.mjs → plugins/api-keys/apiKeys.mjs} +1 -1
  109. package/dist/plugins/api-keys/cli.cjs +115 -0
  110. package/dist/plugins/api-keys/cli.mjs +114 -0
  111. package/dist/plugins/api-keys/index.cjs +9 -6
  112. package/dist/plugins/api-keys/index.d.cts +4 -5
  113. package/dist/plugins/api-keys/index.d.mts +4 -5
  114. package/dist/plugins/api-keys/index.mjs +9 -7
  115. package/dist/plugins/api-keys/model.d.cts +20 -2
  116. package/dist/plugins/api-keys/model.d.mts +20 -2
  117. package/dist/plugins/definePlugin.cjs +1 -1
  118. package/dist/plugins/definePlugin.d.cts +130 -3
  119. package/dist/plugins/definePlugin.d.mts +130 -3
  120. package/dist/plugins/definePlugin.mjs +1 -1
  121. package/dist/plugins/index.cjs +25 -4
  122. package/dist/plugins/index.d.cts +7 -4
  123. package/dist/plugins/index.d.mts +7 -4
  124. package/dist/plugins/index.mjs +6 -4
  125. package/dist/plugins/insights/contract.cjs +193 -0
  126. package/dist/plugins/insights/contract.mjs +189 -0
  127. package/dist/{insights → plugins/insights}/domain.d.cts +60 -15
  128. package/dist/{insights → plugins/insights}/domain.d.mts +60 -15
  129. package/dist/plugins/insights/errors.cjs +15 -0
  130. package/dist/plugins/insights/errors.mjs +14 -0
  131. package/dist/{insights → plugins/insights}/eventInput.cjs +155 -22
  132. package/dist/{insights → plugins/insights}/eventInput.mjs +155 -22
  133. package/dist/plugins/insights/eventRow.cjs +49 -0
  134. package/dist/plugins/insights/eventRow.d.cts +64 -0
  135. package/dist/plugins/insights/eventRow.d.mts +64 -0
  136. package/dist/plugins/insights/eventRow.mjs +47 -0
  137. package/dist/plugins/insights/index.cjs +106 -26
  138. package/dist/plugins/insights/index.d.cts +130 -27
  139. package/dist/plugins/insights/index.d.mts +130 -27
  140. package/dist/plugins/insights/index.mjs +106 -29
  141. package/dist/plugins/insights/model.cjs +2 -2
  142. package/dist/plugins/insights/model.d.cts +1 -1
  143. package/dist/plugins/insights/model.d.mts +1 -1
  144. package/dist/plugins/insights/model.mjs +1 -1
  145. package/dist/plugins/insights/modelTypes.d.cts +176 -0
  146. package/dist/plugins/insights/modelTypes.d.mts +176 -0
  147. package/dist/plugins/insights/overview.cjs +109 -0
  148. package/dist/plugins/insights/overview.d.cts +15 -0
  149. package/dist/plugins/insights/overview.d.mts +15 -0
  150. package/dist/plugins/insights/overview.mjs +107 -0
  151. package/dist/{insights → plugins/insights}/provider.cjs +33 -14
  152. package/dist/{insights → plugins/insights}/provider.d.cts +2 -2
  153. package/dist/{insights → plugins/insights}/provider.d.mts +2 -2
  154. package/dist/{insights → plugins/insights}/provider.mjs +30 -11
  155. package/dist/{insights → plugins/insights}/queryInput.cjs +2 -2
  156. package/dist/{insights → plugins/insights}/queryInput.mjs +2 -2
  157. package/dist/plugins/insights/reads.cjs +298 -88
  158. package/dist/plugins/insights/reads.d.cts +61 -0
  159. package/dist/plugins/insights/reads.d.mts +61 -0
  160. package/dist/plugins/insights/reads.mjs +298 -90
  161. package/dist/plugins/insights/recordEvent.cjs +223 -39
  162. package/dist/plugins/insights/recordEvent.d.cts +9 -4
  163. package/dist/plugins/insights/recordEvent.d.mts +9 -4
  164. package/dist/plugins/insights/recordEvent.mjs +221 -37
  165. package/dist/{insights → plugins/insights}/routes.cjs +3 -30
  166. package/dist/{insights → plugins/insights}/routes.mjs +4 -28
  167. package/dist/plugins/insights/schema.cjs +182 -40
  168. package/dist/plugins/insights/schema.d.cts +446 -6
  169. package/dist/plugins/insights/schema.d.mts +446 -6
  170. package/dist/plugins/insights/schema.mjs +180 -41
  171. package/dist/plugins/insights/testing/eventRow.d.mts +64 -0
  172. package/dist/plugins/insights/testing/expectInsightsIndex.mjs +18 -0
  173. package/dist/plugins/insights/testing/fixtures.d.mts +8 -0
  174. package/dist/plugins/insights/testing/fixtures.mjs +25 -0
  175. package/dist/plugins/insights/testing/index.d.mts +24 -0
  176. package/dist/plugins/insights/testing/index.mjs +25 -0
  177. package/dist/plugins/insights/testing/insightsModelTests.mjs +714 -0
  178. package/dist/plugins/insights/testing/modelTypes.d.mts +176 -0
  179. package/dist/plugins/insights/testing/setupInsightsHttpTestSuite.d.mts +11 -0
  180. package/dist/plugins/insights/testing/setupInsightsHttpTestSuite.mjs +107 -0
  181. package/dist/plugins/insights/testing/setupInsightsModelTestSuite.d.mts +11 -0
  182. package/dist/plugins/insights/testing/setupInsightsModelTestSuite.mjs +31 -0
  183. package/dist/plugins/insights/testing/types.d.mts +26 -0
  184. package/dist/{insights → plugins/insights}/types.d.cts +3 -2
  185. package/dist/{insights → plugins/insights}/types.d.mts +3 -2
  186. package/package.json +18 -7
  187. package/src/adapters/drizzle.conformance.integration.spec.ts +2 -2
  188. package/src/adapters/drizzle.readBudgets.integration.spec.ts +6 -4
  189. package/src/adapters/drizzle.spec.ts +15 -7
  190. package/src/adapters/drizzle.ts +6 -6
  191. package/src/adapters/kysely.conformance.integration.spec.ts +2 -2
  192. package/src/adapters/kysely.readBudgets.integration.spec.ts +4 -2
  193. package/src/adapters/kysely.spec.ts +13 -9
  194. package/src/adapters/kysely.ts +2 -2
  195. package/src/adapters/mongodb.integration.spec.ts +98 -7
  196. package/src/adapters/mongodb.ts +2 -2
  197. package/src/adapters/mongodbAdapter.ts +14 -0
  198. package/src/adapters/prisma.conformance.integration.spec.ts +2 -2
  199. package/src/adapters/prisma.integration.spec.ts +16 -8
  200. package/src/adapters/prisma.readBudgets.integration.spec.ts +5 -2
  201. package/src/adapters/prisma.spec.ts +17 -9
  202. package/src/adapters/prisma.ts +6 -6
  203. package/src/adapters/prismaTestClients.ts +8 -1
  204. package/src/assembly/assemblePlugins.ts +73 -40
  205. package/src/assembly/assembly.spec.ts +63 -11
  206. package/src/assembly/assembly.types.spec.ts +50 -2
  207. package/src/assembly/clientPlugins.ts +113 -0
  208. package/src/assembly/configError.ts +4 -0
  209. package/src/assembly/databasePlugins.ts +11 -5
  210. package/src/assembly/pluginCli.spec.ts +254 -0
  211. package/src/assembly/pluginCli.ts +248 -0
  212. package/src/assembly/{builtInRoutes.spec.ts → pluginRoutes.spec.ts} +10 -37
  213. package/src/createHotUpdaterCore.ts +21 -17
  214. package/src/database/aggregateBatching.spec.ts +577 -0
  215. package/src/database/aggregateBatching.ts +803 -0
  216. package/src/{insights/errors.spec.ts → database/busy.spec.ts} +2 -5
  217. package/src/{insights/errors.ts → database/busy.ts} +1 -13
  218. package/src/database/database.ts +39 -8
  219. package/src/database/definitions.ts +4 -0
  220. package/src/database/engineAggregates.spec.ts +4 -7
  221. package/src/database/engineAggregates.ts +5 -9
  222. package/src/database/engineReads.ts +7 -5
  223. package/src/database/engineTransaction.ts +1 -7
  224. package/src/database/fence.spec.ts +5 -5
  225. package/src/database/fence.ts +4 -0
  226. package/src/database/index.ts +13 -7
  227. package/src/database/kv/kvAdapter.batching.integration.spec.ts +15 -0
  228. package/src/database/kv/kvAdapter.conformance.integration.spec.ts +2 -0
  229. package/src/database/kv/kvAdapter.spec.ts +128 -1
  230. package/src/database/kv/kvAdapter.ts +30 -1
  231. package/src/database/kv/kvTestStore.ts +28 -1
  232. package/src/database/resolveSchema.ts +4 -1
  233. package/src/database/retention.spec.ts +314 -0
  234. package/src/database/retention.ts +129 -0
  235. package/src/database/schema.ts +44 -0
  236. package/src/database/sql/sqlAdapter.integration.spec.ts +4 -7
  237. package/src/database/sql/sqlAdapter.readBudgets.integration.spec.ts +18 -4
  238. package/src/database/sql/sqlAdapter.spec.ts +91 -3
  239. package/src/database/sql/sqlAdapter.ts +20 -0
  240. package/src/database/sql/sqlSchema.ts +81 -0
  241. package/src/databaseTestSuite.spec.ts +9 -4
  242. package/src/db/coreDatabase.ts +153 -0
  243. package/src/db/engineSql.spec.ts +8 -7
  244. package/src/db/index.ts +19 -2
  245. package/src/db/pluginTables.spec.ts +57 -27
  246. package/src/db/types.ts +3 -3
  247. package/src/diff.ts +6 -0
  248. package/src/handler-standalone.integration.spec.ts +2 -3
  249. package/src/handler.ts +1 -32
  250. package/src/handlerReleaseCatalogRoutes.ts +26 -2
  251. package/src/index.ts +0 -10
  252. package/src/{apiKeys.integration.spec.ts → plugins/api-keys/apiKeys.integration.spec.ts} +4 -4
  253. package/src/{apiKeys.spec.ts → plugins/api-keys/apiKeys.spec.ts} +3 -3
  254. package/src/{apiKeys.ts → plugins/api-keys/apiKeys.ts} +1 -1
  255. package/src/plugins/api-keys/apiKeysPlugin.spec.ts +11 -15
  256. package/src/plugins/api-keys/cli.spec.ts +187 -0
  257. package/src/plugins/api-keys/cli.ts +140 -0
  258. package/src/plugins/api-keys/index.ts +48 -41
  259. package/src/plugins/api-keys/model.ts +21 -2
  260. package/src/plugins/definePlugin.ts +144 -2
  261. package/src/plugins/index.ts +20 -2
  262. package/src/plugins/insights/contract.spec.ts +285 -0
  263. package/src/plugins/insights/contract.ts +372 -0
  264. package/src/{insights → plugins/insights}/domain.ts +73 -15
  265. package/src/plugins/insights/errors.ts +11 -0
  266. package/src/{insights → plugins/insights}/eventInput.ts +189 -29
  267. package/src/plugins/insights/eventRow.ts +209 -0
  268. package/src/plugins/insights/index.ts +181 -45
  269. package/src/{insights → plugins/insights}/insights.integration.spec.ts +330 -34
  270. package/src/plugins/insights/insightsRollout.integration.spec.ts +1 -2
  271. package/src/plugins/insights/model.spec.ts +3 -5
  272. package/src/plugins/insights/model.ts +2 -3
  273. package/src/plugins/insights/modelTypes.ts +197 -0
  274. package/src/plugins/insights/overview.spec.ts +64 -0
  275. package/src/plugins/insights/overview.ts +214 -0
  276. package/src/{insights → plugins/insights}/provider.spec.ts +21 -10
  277. package/src/{insights → plugins/insights}/provider.ts +58 -21
  278. package/src/{insights → plugins/insights}/queryInput.ts +2 -2
  279. package/src/plugins/insights/reads.spec.ts +340 -52
  280. package/src/plugins/insights/reads.ts +453 -123
  281. package/src/plugins/insights/recordEvent.spec.ts +474 -20
  282. package/src/plugins/insights/recordEvent.ts +301 -63
  283. package/src/plugins/insights/retention.spec.ts +115 -0
  284. package/src/{insights → plugins/insights}/routes.ts +1 -31
  285. package/src/plugins/insights/schema.ts +356 -176
  286. package/src/plugins/insights/testing/expectInsightsIndex.spec.ts +42 -0
  287. package/src/plugins/insights/testing/expectInsightsIndex.ts +20 -0
  288. package/src/plugins/insights/testing/fixtures.ts +30 -0
  289. package/src/plugins/insights/testing/index.ts +45 -0
  290. package/src/plugins/insights/testing/insightsModelTests.ts +860 -0
  291. package/src/plugins/insights/testing/setupInsightsHttpTestSuite.ts +152 -0
  292. package/src/plugins/insights/testing/setupInsightsModelTestSuite.ts +36 -0
  293. package/src/plugins/insights/testing/types.ts +30 -0
  294. package/src/{insights → plugins/insights}/types.ts +1 -1
  295. package/src/readBudgets.testFixtures.ts +2 -2
  296. package/src/releaseCatalogRoutes.integration.spec.ts +7 -0
  297. package/src/retention.spec.ts +73 -0
  298. package/src/runtime.spec.ts +11 -12
  299. package/src/runtime.testFixtures.ts +7 -2
  300. package/src/testUtilsMutation.integration.spec.ts +2 -1
  301. package/src/testUtilsPackage.integration.spec.ts +7 -3
  302. package/dist/db/builtInDatabase.cjs +0 -104
  303. package/dist/db/builtInDatabase.d.cts +0 -38
  304. package/dist/db/builtInDatabase.d.mts +0 -38
  305. package/dist/db/builtInDatabase.mjs +0 -97
  306. package/dist/plugins/builtIn.cjs +0 -7
  307. package/dist/plugins/builtIn.mjs +0 -6
  308. package/src/db/builtInDatabase.ts +0 -149
  309. package/src/plugins/builtIn.ts +0 -5
@@ -0,0 +1,372 @@
1
+ import { DatabasePluginInputError, isUUIDv7 } from "@hot-updater/plugin-core";
2
+
3
+ import {
4
+ type BundleEventRow,
5
+ isRecord,
6
+ validateBundleEventFields,
7
+ } from "./eventRow";
8
+ import type { InsightsEventFilter, InsightsModel } from "./modelTypes";
9
+
10
+ const encoder = new TextEncoder();
11
+
12
+ /** Exact UTF-8 byte ordering, without case folding or Unicode normalization. */
13
+ export const compareInsightsText = (left: string, right: string): number => {
14
+ const a = encoder.encode(left);
15
+ const b = encoder.encode(right);
16
+ for (let index = 0; index < Math.min(a.length, b.length); index += 1) {
17
+ if (a[index] !== b[index]) return a[index]! - b[index]!;
18
+ }
19
+ return a.length - b.length;
20
+ };
21
+
22
+ const isWellFormedText = (value: string): boolean => {
23
+ for (const character of value) {
24
+ const point = character.codePointAt(0)!;
25
+ if (point >= 0xd800 && point <= 0xdfff) return false;
26
+ }
27
+ return true;
28
+ };
29
+
30
+ const isIdentity = (value: unknown): value is string =>
31
+ typeof value === "string" &&
32
+ value.length > 0 &&
33
+ value.length <= 255 &&
34
+ isWellFormedText(value);
35
+
36
+ const isText = (value: unknown): value is string =>
37
+ typeof value === "string" && value.length > 0 && isWellFormedText(value);
38
+
39
+ const isTimestamp = (value: unknown): value is number =>
40
+ typeof value === "number" && Number.isSafeInteger(value) && value >= 0;
41
+
42
+ const isLimit = (value: unknown): value is number =>
43
+ isTimestamp(value) && value >= 1 && value <= 101;
44
+
45
+ const hasOnlyKeys = (
46
+ value: Readonly<Record<string, unknown>>,
47
+ keys: readonly string[],
48
+ ): boolean => Object.keys(value).every((key) => keys.includes(key));
49
+
50
+ const hasScope = (value: Readonly<Record<string, unknown>>): boolean =>
51
+ (value.platform === "ios" || value.platform === "android") &&
52
+ isText(value.channel);
53
+
54
+ const isBundleFilter = (value: unknown, withKind = false): boolean => {
55
+ if (!isRecord(value) || !hasScope(value)) return false;
56
+ const keys = ["platform", "channel", "type", ...(withKind ? ["kind"] : [])];
57
+ return value.type === "RECOVERED"
58
+ ? isText(value.fromBundleId) &&
59
+ hasOnlyKeys(value, [...keys, "fromBundleId"])
60
+ : (value.type === "UPDATE_DOWNLOADED" ||
61
+ value.type === "UPDATE_APPLIED" ||
62
+ value.type === "UPDATE_FAILED") &&
63
+ isText(value.toBundleId) &&
64
+ hasOnlyKeys(value, [...keys, "toBundleId"]);
65
+ };
66
+
67
+ const isEventFilter = (value: unknown): boolean => {
68
+ if (!isRecord(value)) return false;
69
+ if (value.kind === "all") return hasOnlyKeys(value, ["kind"]);
70
+ if (value.kind === "installationMovement") {
71
+ return (
72
+ isIdentity(value.installId) && hasOnlyKeys(value, ["kind", "installId"])
73
+ );
74
+ }
75
+ return value.kind === "bundle" && isBundleFilter(value, true);
76
+ };
77
+
78
+ const validateRow = (
79
+ model: "bundle_events",
80
+ row: unknown,
81
+ result = false,
82
+ ): void => {
83
+ try {
84
+ validateBundleEventFields(row);
85
+ if (
86
+ !isRecord(row) ||
87
+ typeof row.id !== "string" ||
88
+ !isUUIDv7(row.id) ||
89
+ [
90
+ ...Object.values(row),
91
+ ...(isRecord(row.metadata) ? Object.values(row.metadata) : []),
92
+ ].some((value) => typeof value === "string" && !isWellFormedText(value))
93
+ ) {
94
+ throw new DatabasePluginInputError("invalid-data");
95
+ }
96
+ } catch (error) {
97
+ if (result) throw new DatabasePluginInputError("invalid-result");
98
+ throw error;
99
+ }
100
+ };
101
+
102
+ /** Throws `invalid-data` unless `row` is a complete, well-formed bundle event row. */
103
+ export const assertBundleEventRow = (row: unknown): void =>
104
+ validateRow("bundle_events", row);
105
+
106
+ /** Downloads, applies, recoveries, and failed updates belong in installation history. */
107
+ export const isInsightsMovementEvent = (
108
+ event: Pick<BundleEventRow, "type">,
109
+ ): boolean =>
110
+ event.type === "UPDATE_DOWNLOADED" ||
111
+ event.type === "UPDATE_APPLIED" ||
112
+ event.type === "RECOVERED" ||
113
+ event.type === "UPDATE_FAILED";
114
+
115
+ export const matchesInsightsEventFilter = (
116
+ event: BundleEventRow,
117
+ filter: InsightsEventFilter,
118
+ ): boolean => {
119
+ if (filter.kind === "all") return true;
120
+ if (filter.kind === "installationMovement") {
121
+ return (
122
+ event.install_id === filter.installId && isInsightsMovementEvent(event)
123
+ );
124
+ }
125
+ // A failed check's `to_bundle_id` is the running bundle, not a target, so
126
+ // no bundle filter matches it.
127
+ return (
128
+ event.type === filter.type &&
129
+ event.platform === filter.platform &&
130
+ event.channel === filter.channel &&
131
+ (filter.type === "RECOVERED"
132
+ ? event.from_bundle_id === filter.fromBundleId
133
+ : event.to_bundle_id === filter.toBundleId &&
134
+ event.metadata.failure?.stage !== "check")
135
+ );
136
+ };
137
+
138
+ const invalidQuery = (): never => {
139
+ throw new DatabasePluginInputError("invalid-query");
140
+ };
141
+ const invalidResult = (): never => {
142
+ throw new DatabasePluginInputError("invalid-result");
143
+ };
144
+ const validateCount = (count: number): number =>
145
+ isTimestamp(count) ? count : invalidResult();
146
+
147
+ const isTimeRange = (value: unknown): value is { start: number; end: number } =>
148
+ isRecord(value) &&
149
+ hasOnlyKeys(value, ["start", "end"]) &&
150
+ isTimestamp(value.start) &&
151
+ isTimestamp(value.end) &&
152
+ (value.start as number) < (value.end as number);
153
+
154
+ const isReleaseReference = (value: unknown): boolean =>
155
+ isRecord(value) &&
156
+ hasOnlyKeys(value, ["releaseId", "platform", "channel"]) &&
157
+ isIdentity(value.releaseId) &&
158
+ hasScope(value);
159
+
160
+ const validateAggregateResult = (value: unknown): void => {
161
+ const result = isRecord(value) ? value : invalidResult();
162
+ if (!isTimestamp(result.measuredAtMs)) invalidResult();
163
+ const coverage = result.coverage;
164
+ if (
165
+ !isRecord(coverage) ||
166
+ (coverage.kind !== "complete" && coverage.kind !== "partial") ||
167
+ (coverage.sinceMs !== null && !isTimestamp(coverage.sinceMs))
168
+ ) {
169
+ invalidResult();
170
+ }
171
+ };
172
+
173
+ /** Validate custom and bundled providers at the same public boundary. */
174
+ export const createValidatedInsightsModel = (
175
+ model: InsightsModel,
176
+ ): InsightsModel => ({
177
+ async recordEvent(input) {
178
+ if (!isRecord(input) || !hasOnlyKeys(input, ["event"])) {
179
+ throw new DatabasePluginInputError("invalid-data");
180
+ }
181
+ validateRow("bundle_events", input.event);
182
+ await model.recordEvent(input);
183
+ },
184
+ async listEvents(input) {
185
+ if (
186
+ !isRecord(input) ||
187
+ !hasOnlyKeys(input, [
188
+ "filter",
189
+ "sinceMs",
190
+ "beforeReceivedAtMs",
191
+ "after",
192
+ "limit",
193
+ ]) ||
194
+ !isEventFilter(input.filter) ||
195
+ !isLimit(input.limit) ||
196
+ !isTimestamp(input.beforeReceivedAtMs) ||
197
+ (input.sinceMs !== undefined && !isTimestamp(input.sinceMs))
198
+ )
199
+ invalidQuery();
200
+ const sinceMs = input.sinceMs ?? 0;
201
+ if (
202
+ sinceMs > input.beforeReceivedAtMs ||
203
+ (input.after !== undefined &&
204
+ (!isRecord(input.after) ||
205
+ !hasOnlyKeys(input.after, ["receivedAtMs", "id"]) ||
206
+ !isTimestamp(input.after.receivedAtMs) ||
207
+ typeof input.after.id !== "string" ||
208
+ !isUUIDv7(input.after.id) ||
209
+ input.after.receivedAtMs < sinceMs ||
210
+ input.after.receivedAtMs >= input.beforeReceivedAtMs))
211
+ )
212
+ invalidQuery();
213
+ const rows = await model.listEvents(input);
214
+ if (!Array.isArray(rows) || rows.length > input.limit) invalidResult();
215
+ let previous = input.after;
216
+ for (const row of rows) {
217
+ validateRow("bundle_events", row, true);
218
+ if (
219
+ row.received_at_ms < sinceMs ||
220
+ row.received_at_ms >= input.beforeReceivedAtMs ||
221
+ !matchesInsightsEventFilter(row, input.filter) ||
222
+ (previous !== undefined &&
223
+ (row.received_at_ms > previous.receivedAtMs ||
224
+ (row.received_at_ms === previous.receivedAtMs &&
225
+ row.id >= previous.id)))
226
+ )
227
+ invalidResult();
228
+ previous = { receivedAtMs: row.received_at_ms, id: row.id };
229
+ }
230
+ return rows;
231
+ },
232
+ async findLatestEvents(input) {
233
+ if (!isRecord(input)) invalidQuery();
234
+ if ("installId" in input) {
235
+ if (!hasOnlyKeys(input, ["installId"]) || !isIdentity(input.installId))
236
+ invalidQuery();
237
+ } else if (
238
+ !hasOnlyKeys(input, ["userId", "afterInstallId", "limit"]) ||
239
+ !isIdentity(input.userId) ||
240
+ !isLimit(input.limit) ||
241
+ (input.afterInstallId !== undefined && !isIdentity(input.afterInstallId))
242
+ )
243
+ invalidQuery();
244
+ const rows = await model.findLatestEvents(input);
245
+ if (
246
+ !Array.isArray(rows) ||
247
+ rows.length > ("installId" in input ? 1 : input.limit)
248
+ )
249
+ invalidResult();
250
+ let previous = "installId" in input ? undefined : input.afterInstallId;
251
+ for (const row of rows) {
252
+ validateRow("bundle_events", row, true);
253
+ if (
254
+ "installId" in input
255
+ ? row.install_id !== input.installId
256
+ : row.user_id !== input.userId ||
257
+ (previous !== undefined &&
258
+ compareInsightsText(row.install_id, previous) <= 0)
259
+ )
260
+ invalidResult();
261
+ previous = row.install_id;
262
+ }
263
+ return rows;
264
+ },
265
+ async countLatestEvents(input) {
266
+ if (
267
+ !isRecord(input) ||
268
+ !hasOnlyKeys(input, ["platform", "channel", "sinceMs", "bundle"]) ||
269
+ !hasScope(input) ||
270
+ !isTimestamp(input.sinceMs) ||
271
+ (input.bundle !== undefined &&
272
+ (!Array.isArray(input.bundle) ||
273
+ input.bundle.length < 1 ||
274
+ input.bundle.length > 2 ||
275
+ input.bundle.some(
276
+ (bundle) =>
277
+ !isRecord(bundle) ||
278
+ !hasOnlyKeys(bundle, ["field", "value", "types"]) ||
279
+ (bundle.field !== "from_bundle_id" &&
280
+ bundle.field !== "to_bundle_id") ||
281
+ !isText(bundle.value) ||
282
+ !Array.isArray(bundle.types) ||
283
+ bundle.types.length === 0 ||
284
+ bundle.types.some(
285
+ (type) =>
286
+ ![
287
+ "UNCHANGED",
288
+ "UPDATE_DOWNLOADED",
289
+ "UPDATE_APPLIED",
290
+ "RECOVERED",
291
+ ].includes(type),
292
+ ),
293
+ )))
294
+ )
295
+ invalidQuery();
296
+ return validateCount(await model.countLatestEvents(input));
297
+ },
298
+ async countEvents(input) {
299
+ if (
300
+ !isRecord(input) ||
301
+ !hasOnlyKeys(input, ["filter", "sinceMs", "beforeReceivedAtMs"]) ||
302
+ !isBundleFilter(input.filter) ||
303
+ !isTimestamp(input.sinceMs) ||
304
+ !isTimestamp(input.beforeReceivedAtMs) ||
305
+ input.sinceMs > input.beforeReceivedAtMs
306
+ )
307
+ invalidQuery();
308
+ return validateCount(await model.countEvents(input));
309
+ },
310
+ async getReleaseActivity(input) {
311
+ if (
312
+ !isRecord(input) ||
313
+ !hasOnlyKeys(input, ["releases", "scope", "timeRange"])
314
+ ) {
315
+ invalidQuery();
316
+ }
317
+ const releases = input.releases;
318
+ const scope = input.scope;
319
+ const timeRange = input.timeRange;
320
+ const releaseQuery =
321
+ Array.isArray(releases) &&
322
+ releases.length > 0 &&
323
+ releases.length <= 100 &&
324
+ releases.every(isReleaseReference) &&
325
+ scope === undefined &&
326
+ (timeRange === undefined || isTimeRange(timeRange));
327
+ const scopeQuery =
328
+ releases === undefined &&
329
+ isRecord(scope) &&
330
+ hasOnlyKeys(scope, ["platform", "channel"]) &&
331
+ hasScope(scope) &&
332
+ isTimeRange(timeRange);
333
+ if (!releaseQuery && !scopeQuery) invalidQuery();
334
+ const result = await model.getReleaseActivity(input);
335
+ validateAggregateResult(result);
336
+ if (!Array.isArray(result.data)) invalidResult();
337
+ return result;
338
+ },
339
+ async getAppUsage(input) {
340
+ if (
341
+ !isRecord(input) ||
342
+ !hasOnlyKeys(input, [
343
+ "channel",
344
+ "platform",
345
+ "appVersion",
346
+ "timeRange",
347
+ "intervalMs",
348
+ ]) ||
349
+ !isText(input.channel) ||
350
+ !["all", "ios", "android"].includes(input.platform) ||
351
+ (input.appVersion !== undefined && !isText(input.appVersion)) ||
352
+ !isTimeRange(input.timeRange) ||
353
+ !isTimestamp(input.intervalMs) ||
354
+ input.intervalMs < 3_600_000
355
+ ) {
356
+ invalidQuery();
357
+ }
358
+ const result = await model.getAppUsage(input);
359
+ validateAggregateResult(result);
360
+ if (
361
+ !isTimestamp(result.activeInstallations) ||
362
+ !Array.isArray(result.points) ||
363
+ !Array.isArray(result.appVersions) ||
364
+ !Array.isArray(result.versions) ||
365
+ !Array.isArray(result.platforms) ||
366
+ !Array.isArray(result.bundleDistribution)
367
+ ) {
368
+ invalidResult();
369
+ }
370
+ return result;
371
+ },
372
+ });
@@ -1,3 +1,28 @@
1
+ import type {
2
+ BundleEventFailure,
3
+ BundleEventFailureReason,
4
+ BundleEventFailureStage,
5
+ DatabaseBundleEventMetadata,
6
+ } from "./eventRow";
7
+ import type { InsightsScope } from "./modelTypes";
8
+
9
+ /**
10
+ * Where an update failed and why, as a report carries it. Unknown values of
11
+ * its sets read as `unknown`, so a newer client's failure still counts.
12
+ */
13
+ export type BundleEventFailureInput = {
14
+ readonly stage: BundleEventFailureStage;
15
+ readonly reason: BundleEventFailureReason;
16
+ readonly resource?: NonNullable<BundleEventFailure["resource"]>;
17
+ /** The response status of an `http` failure. */
18
+ readonly httpStatus?: number;
19
+ readonly transport?: NonNullable<BundleEventFailure["transport"]>;
20
+ /** The storage origin's error code, such as `ExpiredToken`. */
21
+ readonly originCode?: string;
22
+ /** Android's `ApplicationExitInfo` reason for the process before this one. */
23
+ readonly previousProcessExit?: string;
24
+ };
25
+
1
26
  /**
2
27
  * The body of `POST /events`. Fields the server does not know are ignored, so
3
28
  * a newer client's report still records on an older server.
@@ -14,7 +39,6 @@ export type CreateBundleEventRequestBase = {
14
39
  readonly installId: string;
15
40
  readonly toBundleId: string;
16
41
  readonly userId?: string;
17
- readonly username?: string;
18
42
  readonly platform: "ios" | "android";
19
43
  readonly appVersion: string;
20
44
  readonly channel: string;
@@ -25,11 +49,38 @@ export type CreateBundleEventRequestBase = {
25
49
  readonly toReleaseId: string | null;
26
50
  };
27
51
 
52
+ type Movement = CreateBundleEventRequestBase & {
53
+ readonly fromBundleId: string;
54
+ readonly updateStrategy: "fingerprint" | "appVersion";
55
+ };
56
+
28
57
  export type CreateBundleEventRequest =
29
- | (CreateBundleEventRequestBase & {
30
- readonly type: "UPDATE_DOWNLOADED" | "UPDATE_APPLIED" | "RECOVERED";
31
- readonly fromBundleId: string;
32
- readonly updateStrategy: "fingerprint" | "appVersion";
58
+ | (Movement & {
59
+ readonly type: "UPDATE_DOWNLOADED";
60
+ readonly metadata?: {
61
+ /** How the bundle arrived. */
62
+ readonly delivery?: NonNullable<
63
+ DatabaseBundleEventMetadata["delivery"]
64
+ >;
65
+ /** A patch was tried, and the files or the archive came instead. */
66
+ readonly patchFallback?: true;
67
+ };
68
+ })
69
+ | (Movement & { readonly type: "UPDATE_APPLIED" })
70
+ | (Movement & {
71
+ readonly type: "RECOVERED";
72
+ readonly metadata?: {
73
+ /** Android's `ApplicationExitInfo` reason for the crashed process. */
74
+ readonly previousProcessExit?: string;
75
+ };
76
+ })
77
+ | (Movement & {
78
+ /**
79
+ * An update check, download, or install that failed: `fromBundleId`
80
+ * runs, and `toBundleId` is the target (for a check, the running bundle).
81
+ */
82
+ readonly type: "UPDATE_FAILED";
83
+ readonly metadata: { readonly failure: BundleEventFailureInput };
33
84
  })
34
85
  | (CreateBundleEventRequestBase & {
35
86
  readonly type: "UNCHANGED";
@@ -46,26 +97,37 @@ export type EventHistoryRow = {
46
97
  | "UPDATE_DOWNLOADED"
47
98
  | "UPDATE_APPLIED"
48
99
  | "RECOVERED"
100
+ | "UPDATE_FAILED"
49
101
  | "UNCHANGED";
50
102
  readonly fromBundleId: string | null;
51
103
  readonly toBundleId: string;
52
- readonly username: string | null;
53
104
  readonly userId: string | null;
54
105
  readonly platform: "ios" | "android";
55
106
  readonly appVersion: string;
56
107
  readonly channel: string;
57
108
  readonly cohort: string;
58
109
  readonly receivedAtMs: number;
110
+ /** `UPDATE_FAILED`: where the update failed and why. */
111
+ readonly failure?: BundleEventFailureInput;
112
+ /** `UPDATE_DOWNLOADED`: how the bundle arrived, when the client said. */
113
+ readonly delivery?: NonNullable<DatabaseBundleEventMetadata["delivery"]>;
114
+ /** `UPDATE_DOWNLOADED`: a patch failed, and the files or the archive came instead. */
115
+ readonly patchFallback?: true;
116
+ /** `RECOVERED`: Android's reason the crashed process exited. */
117
+ readonly previousProcessExit?: string;
59
118
  };
60
119
 
61
120
  export type InstallationHistoryRow = EventHistoryRow & {
62
- readonly type: "UPDATE_DOWNLOADED" | "UPDATE_APPLIED" | "RECOVERED";
121
+ readonly type:
122
+ | "UPDATE_DOWNLOADED"
123
+ | "UPDATE_APPLIED"
124
+ | "RECOVERED"
125
+ | "UPDATE_FAILED";
63
126
  readonly fromBundleId: string;
64
127
  };
65
128
 
66
129
  export type InstallationRow = {
67
130
  readonly installId: string;
68
- readonly username: string | null;
69
131
  readonly userId: string | null;
70
132
  readonly lastKnownBundleId: string;
71
133
  readonly pendingBundleId: string | null;
@@ -87,14 +149,10 @@ export type EventCursorPage<T extends EventHistoryRow> = CursorPage<T> & {
87
149
  readonly beforeReceivedAtMs: number;
88
150
  };
89
151
 
90
- export type InsightsScope = {
91
- readonly platform: "ios" | "android";
92
- readonly channel: string;
93
- };
94
-
95
152
  export type InsightsBundleSelection = InsightsScope & {
96
153
  readonly bundleId: string;
97
- readonly outcome: "downloaded" | "applied" | "recovered" | "unchanged";
154
+ /** `failed`: update failures that targeted the bundle. */
155
+ readonly outcome: "downloaded" | "applied" | "recovered" | "failed";
98
156
  };
99
157
 
100
158
  export type InsightsCountMeasurement = {
@@ -113,6 +171,6 @@ export type ReportingOverview = InsightsScope & {
113
171
  readonly downloadedReports: InsightsCountMeasurement;
114
172
  readonly appliedReports: InsightsCountMeasurement;
115
173
  readonly recoveredReports: InsightsCountMeasurement;
116
- readonly unchangedReports: InsightsCountMeasurement;
174
+ readonly failedReports: InsightsCountMeasurement;
117
175
  };
118
176
  };
@@ -0,0 +1,11 @@
1
+ export class InsightsBadRequestError extends Error {
2
+ readonly name = "InsightsBadRequestError";
3
+ }
4
+
5
+ export class InsightsPayloadTooLargeError extends Error {
6
+ readonly name = "InsightsPayloadTooLargeError";
7
+
8
+ constructor(readonly maximumBytes: number) {
9
+ super(`Event payload exceeds ${maximumBytes} bytes`);
10
+ }
11
+ }