@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
@@ -121,20 +121,39 @@ const predicate = (where: AnyDatabaseWhere): Document => {
121
121
 
122
122
  const createMongoWhereDocument = (
123
123
  where: readonly AnyDatabaseWhere[] | undefined,
124
+ toPredicate: (condition: AnyDatabaseWhere) => Document = predicate,
124
125
  ): Document => {
125
126
  const items = Array.isArray(where) ? where : [];
126
127
  const first = items[0];
127
128
  if (first === undefined) return {};
128
129
 
129
- let result = predicate(first);
130
+ let result = toPredicate(first);
130
131
  for (const item of items.slice(1)) {
131
132
  result = {
132
- [item.connector === "OR" ? "$or" : "$and"]: [result, predicate(item)],
133
+ [item.connector === "OR" ? "$or" : "$and"]: [result, toPredicate(item)],
133
134
  };
134
135
  }
135
136
  return result;
136
137
  };
137
138
 
139
+ // Fixed Insights predicates use native fields so equality/range indexes apply.
140
+ const insightsPredicate = (where: AnyDatabaseWhere): Document => {
141
+ if ("mode" in where && where.mode === "insensitive") return predicate(where);
142
+ switch (where.operator) {
143
+ case undefined:
144
+ case "eq":
145
+ return { [where.field]: { $eq: where.value } };
146
+ case "gt":
147
+ case "gte":
148
+ case "lt":
149
+ case "lte":
150
+ case "in":
151
+ return { [where.field]: { [`$${where.operator}`]: where.value } };
152
+ default:
153
+ return predicate(where);
154
+ }
155
+ };
156
+
138
157
  export function createMongoBundleWhere(
139
158
  where: readonly DatabaseWhere<"bundles">[] | undefined,
140
159
  ): Filter<BundleRow>;
@@ -159,7 +178,7 @@ export function createMongoEventWhere(
159
178
  export function createMongoEventWhere(
160
179
  where: readonly DatabaseWhere<"bundle_events">[] | undefined,
161
180
  ): Document {
162
- return createMongoWhereDocument(where);
181
+ return createMongoWhereDocument(where, insightsPredicate);
163
182
  }
164
183
 
165
184
  export function createMongoApiKeyWhere(
@@ -1,4 +1,11 @@
1
- import { DatabasePluginInputError } from "@hot-updater/plugin-core";
1
+ import {
2
+ type BundleEventRow,
3
+ DatabasePluginInputError,
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
  DatabaseImplementationResult,
4
11
  DatabasePluginImplementation,
@@ -91,6 +98,8 @@ const findMongoRows = async (
91
98
  .find(createMongoEventWhere(input.where), {
92
99
  projection: WITHOUT_MONGO_ID,
93
100
  ...mongoSessionOptions(session),
101
+ collation: { locale: "simple" },
102
+ readPreference: "primary",
94
103
  })
95
104
  .skip(input.offset)
96
105
  .limit(input.limit);
@@ -100,6 +109,8 @@ const findMongoRows = async (
100
109
  .find(createMongoEventWhere(input.where), {
101
110
  projection: WITHOUT_MONGO_ID,
102
111
  ...mongoSessionOptions(session),
112
+ collation: { locale: "simple" },
113
+ readPreference: "primary",
103
114
  })
104
115
  .toArray();
105
116
  return sortRowsByOrder(rows, rawOrderBy).slice(
@@ -112,6 +123,7 @@ const findMongoRows = async (
112
123
  ? cursor.toArray()
113
124
  : cursor.sort(sort).toArray();
114
125
  }
126
+
115
127
  case "api_keys": {
116
128
  const cursor = collections.apiKeys
117
129
  .find(createMongoApiKeyWhere(input.where), {
@@ -221,13 +233,64 @@ const findMongoRows = async (
221
233
 
222
234
  type MongoReadImplementation = Pick<
223
235
  DatabasePluginImplementation,
224
- "count" | "findMany" | "findOne"
236
+ | "count"
237
+ | "findMany"
238
+ | "findOne"
239
+ | "findLatestInsightsEvents"
240
+ | "countLatestInsightsEvents"
225
241
  >;
226
242
 
227
243
  export const createMongoReads = (
228
244
  collections: MongoCollections,
229
245
  session?: ClientSession,
230
246
  ): MongoReadImplementation => ({
247
+ async findLatestInsightsEvents(input) {
248
+ return collections.bundleEventHeads
249
+ .aggregate<BundleEventRow>(
250
+ [
251
+ { $match: createMongoEventWhere(latestInsightsWhere(input)) },
252
+ { $sort: { install_id: 1 } },
253
+ { $limit: "installId" in input ? 1 : input.limit },
254
+ {
255
+ $lookup: {
256
+ from: "bundle_events",
257
+ localField: "id",
258
+ foreignField: "id",
259
+ as: "event",
260
+ },
261
+ },
262
+ { $unwind: "$event" },
263
+ { $replaceRoot: { newRoot: "$event" } },
264
+ { $project: WITHOUT_MONGO_ID },
265
+ ],
266
+ {
267
+ ...mongoSessionOptions(session),
268
+ collation: { locale: "simple" },
269
+ readPreference: "primary",
270
+ },
271
+ )
272
+ .toArray();
273
+ },
274
+ async countLatestInsightsEvents(input) {
275
+ const rows = await collections.bundleEventHeads
276
+ .aggregate<{ count: number }>(
277
+ [
278
+ {
279
+ $match: {
280
+ $or: latestInsightsCountGroups(input).map(createMongoEventWhere),
281
+ },
282
+ },
283
+ { $count: "count" },
284
+ ],
285
+ {
286
+ ...mongoSessionOptions(session),
287
+ collation: { locale: "simple" },
288
+ readPreference: "primary",
289
+ },
290
+ )
291
+ .toArray();
292
+ return rows[0]?.count ?? 0;
293
+ },
231
294
  count: async (input) => {
232
295
  if (input.distinct !== undefined) {
233
296
  throw new DatabasePluginInputError("invalid-operation");
@@ -248,6 +311,19 @@ export const createMongoReads = (
248
311
  createMongoReleaseWhere(input.where),
249
312
  mongoSessionOptions(session),
250
313
  );
314
+
315
+ case "bundle_events":
316
+ return collections.bundleEvents.countDocuments(
317
+ createMongoEventWhere(input.where),
318
+ {
319
+ ...mongoSessionOptions(session),
320
+ collation: { locale: "simple" },
321
+ readPreference: "primary",
322
+ ...(session === undefined
323
+ ? { readConcern: { level: "snapshot" } }
324
+ : {}),
325
+ },
326
+ );
251
327
  }
252
328
  },
253
329
  findOne: async (input) => {
@@ -12,6 +12,8 @@ type Tables = {
12
12
  bundle_patches: MongoTestRow[];
13
13
  bundles: MongoTestRow[];
14
14
  bundle_events: MongoTestRow[];
15
+ bundle_event_heads: MongoTestRow[];
16
+
15
17
  channels: MongoTestRow[];
16
18
  api_keys: MongoTestRow[];
17
19
  releases: MongoTestRow[];
@@ -25,6 +27,8 @@ type UpdateInput =
25
27
  type MongoTestHooks = {
26
28
  beforeBundlePatchInsert?: () => Promise<void>;
27
29
  failNextBundleTombstone: boolean;
30
+ failNextEventWrite: boolean;
31
+ failNextHeadWrite: boolean;
28
32
  operationCount: number;
29
33
  };
30
34
 
@@ -90,6 +94,65 @@ const createCollection = (
90
94
  model: keyof Tables,
91
95
  hooks: MongoTestHooks,
92
96
  ) => ({
97
+ aggregate: (pipeline: readonly Record<string, unknown>[]) => ({
98
+ async toArray() {
99
+ hooks.operationCount += 1;
100
+ let rows: Record<string, unknown>[] = structuredClone(tables[model]).map(
101
+ (row) => ({ ...row }),
102
+ );
103
+ for (const stage of pipeline) {
104
+ if ("$match" in stage)
105
+ rows = rows.filter((row) =>
106
+ matchesMongoTestFilter(row as MongoTestRow, stage.$match),
107
+ );
108
+ else if ("$sort" in stage)
109
+ rows = sortMongoTestRows(rows as MongoTestRow[], stage.$sort).map(
110
+ (row) => ({ ...row }),
111
+ );
112
+ else if ("$group" in stage) {
113
+ const grouped = new Map<unknown, Record<string, unknown>>();
114
+ for (const row of rows)
115
+ if (!grouped.has(row.install_id))
116
+ grouped.set(row.install_id, { _id: row.install_id, event: row });
117
+ rows = [...grouped.values()];
118
+ } else if ("$lookup" in stage) {
119
+ const lookup = stage.$lookup as {
120
+ from: keyof Tables;
121
+ localField: string;
122
+ foreignField: string;
123
+ as: string;
124
+ };
125
+ rows = rows.map((row) => ({
126
+ ...row,
127
+ [lookup.as]: tables[lookup.from].filter(
128
+ (other) =>
129
+ Reflect.get(other, lookup.foreignField) ===
130
+ row[lookup.localField],
131
+ ),
132
+ }));
133
+ } else if ("$unwind" in stage) {
134
+ const field = String(stage.$unwind).slice(1);
135
+ rows = rows.flatMap((row) =>
136
+ (row[field] as MongoTestRow[]).map((value) => ({
137
+ ...row,
138
+ [field]: value,
139
+ })),
140
+ );
141
+ } else if ("$replaceRoot" in stage)
142
+ rows = rows.map((row) => row.event as Record<string, unknown>);
143
+ else if ("$limit" in stage) rows = rows.slice(0, Number(stage.$limit));
144
+ else if ("$project" in stage)
145
+ rows = rows.map((row) => ({
146
+ ...projectMongoTestRow(row as MongoTestRow, stage.$project),
147
+ }));
148
+ else if ("$count" in stage)
149
+ rows = rows.length ? [{ [String(stage.$count)]: rows.length }] : [];
150
+ else
151
+ throw new MongoTestConstraintError("unsupported aggregation stage");
152
+ }
153
+ return rows;
154
+ },
155
+ }),
93
156
  countDocuments: async (filter?: unknown): Promise<number> => {
94
157
  hooks.operationCount += 1;
95
158
  return tables[model].filter((row) => matchesMongoTestFilter(row, filter))
@@ -149,6 +212,10 @@ const createCollection = (
149
212
  },
150
213
  insertOne: async (row: MongoTestRow): Promise<void> => {
151
214
  hooks.operationCount += 1;
215
+ if (model === "bundle_events" && hooks.failNextEventWrite) {
216
+ hooks.failNextEventWrite = false;
217
+ throw new MongoTestConstraintError("injected event write failure");
218
+ }
152
219
  if (model === "bundle_patches") await hooks.beforeBundlePatchInsert?.();
153
220
  const key = "id" in row ? row.id : row.scope_key;
154
221
  if (
@@ -197,6 +264,14 @@ const createCollection = (
197
264
  options?: { readonly upsert?: boolean },
198
265
  ): Promise<{ matchedCount: number; upsertedCount: number }> => {
199
266
  hooks.operationCount += 1;
267
+ if (model === "bundle_events" && hooks.failNextEventWrite) {
268
+ hooks.failNextEventWrite = false;
269
+ throw new MongoTestConstraintError("injected event write failure");
270
+ }
271
+ if (model === "bundle_event_heads" && hooks.failNextHeadWrite) {
272
+ hooks.failNextHeadWrite = false;
273
+ throw new MongoTestConstraintError("injected head write failure");
274
+ }
200
275
  const index = tables[model].findIndex((row) =>
201
276
  matchesMongoTestFilter(row, filter),
202
277
  );
@@ -209,19 +284,28 @@ const createCollection = (
209
284
  }
210
285
  return { matchedCount: 1, upsertedCount: 0 };
211
286
  }
212
- if (options?.upsert === true && "$setOnInsert" in update) {
287
+ if (options?.upsert === true) {
288
+ const values = (
289
+ "$setOnInsert" in update ? update.$setOnInsert : update.$set
290
+ ) as MongoTestRow;
213
291
  const key =
214
- "id" in update.$setOnInsert
215
- ? update.$setOnInsert.id
216
- : update.$setOnInsert.scope_key;
292
+ model === "bundle_event_heads"
293
+ ? Reflect.get(values, "install_id")
294
+ : "id" in values
295
+ ? values.id
296
+ : values.scope_key;
217
297
  if (
218
298
  tables[model].some((row) =>
219
- "id" in row ? row.id === key : row.scope_key === key,
299
+ model === "bundle_event_heads"
300
+ ? Reflect.get(row, "install_id") === key
301
+ : "id" in row
302
+ ? row.id === key
303
+ : row.scope_key === key,
220
304
  )
221
305
  ) {
222
306
  throw new MongoTestConstraintError("duplicate id");
223
307
  }
224
- tables[model].push(structuredClone(update.$setOnInsert));
308
+ tables[model].push(structuredClone(values));
225
309
  return { matchedCount: 0, upsertedCount: 1 };
226
310
  }
227
311
  return { matchedCount: 0, upsertedCount: 0 };
@@ -237,6 +321,9 @@ const createDatabase = (tables: Tables, hooks: MongoTestHooks) => ({
237
321
  return createCollection(tables, "bundle_patches", hooks);
238
322
  case "bundle_events":
239
323
  return createCollection(tables, "bundle_events", hooks);
324
+ case "bundle_event_heads":
325
+ return createCollection(tables, "bundle_event_heads", hooks);
326
+
240
327
  case "channels":
241
328
  return createCollection(tables, "channels", hooks);
242
329
  case "api_keys":
@@ -256,6 +343,8 @@ export const createMongoTestHarness = () => {
256
343
  bundle_patches: [],
257
344
  bundles: [],
258
345
  bundle_events: [],
346
+ bundle_event_heads: [],
347
+
259
348
  channels: [],
260
349
  api_keys: [],
261
350
  releases: [],
@@ -263,6 +352,8 @@ export const createMongoTestHarness = () => {
263
352
  };
264
353
  const hooks: MongoTestHooks = {
265
354
  failNextBundleTombstone: false,
355
+ failNextEventWrite: false,
356
+ failNextHeadWrite: false,
266
357
  operationCount: 0,
267
358
  };
268
359
  let activeTables = tables;
@@ -290,6 +381,7 @@ export const createMongoTestHarness = () => {
290
381
  tables.bundle_patches = staged.bundle_patches;
291
382
  tables.bundles = staged.bundles;
292
383
  tables.bundle_events = staged.bundle_events;
384
+ tables.bundle_event_heads = staged.bundle_event_heads;
293
385
  tables.channels = staged.channels;
294
386
  tables.api_keys = staged.api_keys;
295
387
  tables.releases = staged.releases;
@@ -309,11 +401,14 @@ export const createMongoTestHarness = () => {
309
401
  close: () => client.close(),
310
402
  reset: (): void => {
311
403
  hooks.failNextBundleTombstone = false;
404
+ hooks.failNextEventWrite = false;
405
+ hooks.failNextHeadWrite = false;
312
406
  hooks.operationCount = 0;
313
407
  transactionQueue = Promise.resolve();
314
408
  tables.bundle_patches = [];
315
409
  tables.bundles = [];
316
410
  tables.bundle_events = [];
411
+ tables.bundle_event_heads = [];
317
412
  tables.channels = [];
318
413
  tables.api_keys = [];
319
414
  tables.releases = [];
@@ -328,6 +423,12 @@ export const createMongoTestHarness = () => {
328
423
  failNextBundleTombstone: (): void => {
329
424
  hooks.failNextBundleTombstone = true;
330
425
  },
426
+ failNextEventWrite: (): void => {
427
+ hooks.failNextEventWrite = true;
428
+ },
429
+ failNextHeadWrite: (): void => {
430
+ hooks.failNextHeadWrite = true;
431
+ },
331
432
  setBundleField: (id: string, field: string, value: unknown): void => {
332
433
  const row = tables.bundles.find(
333
434
  (candidate) => "id" in candidate && candidate.id === id,
@@ -8,8 +8,11 @@ import type {
8
8
  ReleaseRow,
9
9
  } from "@hot-updater/plugin-core";
10
10
 
11
+ import type { MongoBundleEventHead } from "./mongodbCollections";
12
+
11
13
  export type MongoTestRow =
12
14
  | BundleEventRow
15
+ | MongoBundleEventHead
13
16
  | BundlePatchRow
14
17
  | BundleRow
15
18
  | ChannelRow
@@ -28,7 +31,7 @@ const compare = (left: unknown, right: unknown): number => {
28
31
  return left - right;
29
32
  }
30
33
  if (typeof left === "string" && typeof right === "string") {
31
- return left.localeCompare(right);
34
+ return Buffer.compare(Buffer.from(left), Buffer.from(right));
32
35
  }
33
36
  return 0;
34
37
  };
@@ -100,6 +103,7 @@ const resolveExpression = (row: MongoTestRow, expression: unknown): unknown => {
100
103
 
101
104
  const matchesField = (current: unknown, condition: unknown): boolean => {
102
105
  if (!isRecord(condition)) return Object.is(current, condition);
106
+ if ("$eq" in condition) return Object.is(current, condition["$eq"]);
103
107
  if (typeof condition["$exists"] === "boolean") {
104
108
  return condition["$exists"] ? current !== undefined : current === undefined;
105
109
  }
@@ -116,6 +116,7 @@ export const createMongoWrites = (
116
116
  mongoSessionOptions(session),
117
117
  );
118
118
  return input.data;
119
+
119
120
  case "releases":
120
121
  await collections.releases.insertOne(
121
122
  input.data,