@terreno/api 57.3.0 → 57.6.0

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 (412) hide show
  1. package/.ai/skills/mongoose-schema-safety/SKILL.md +23 -10
  2. package/README.md +11 -5
  3. package/bunfig.toml +1 -1
  4. package/dist/actions.js +197 -368
  5. package/dist/adminModelRouter.js +88 -173
  6. package/dist/adminTypes.d.ts +7 -0
  7. package/dist/adminTypes.js +6 -1
  8. package/dist/api.d.ts +10 -0
  9. package/dist/api.js +601 -792
  10. package/dist/audit/auditApp.d.ts +30 -0
  11. package/dist/audit/auditApp.js +114 -0
  12. package/dist/audit/auditEventModel.d.ts +29 -0
  13. package/dist/audit/auditEventModel.js +101 -0
  14. package/dist/audit/cloudTasksEnqueue.d.ts +32 -0
  15. package/dist/audit/cloudTasksEnqueue.js +69 -0
  16. package/dist/audit/diff.d.ts +10 -0
  17. package/dist/audit/diff.js +140 -0
  18. package/dist/audit/processQueue.d.ts +6 -0
  19. package/dist/audit/processQueue.js +56 -0
  20. package/dist/audit/rbacSink.d.ts +2 -0
  21. package/dist/audit/rbacSink.js +41 -0
  22. package/dist/audit/record.d.ts +56 -0
  23. package/dist/audit/record.js +251 -0
  24. package/dist/auth.js +432 -681
  25. package/dist/authRecovery.js +155 -269
  26. package/dist/authTokens.js +43 -118
  27. package/dist/betterAuth.d.ts +6 -0
  28. package/dist/betterAuthApp.js +25 -26
  29. package/dist/betterAuthSetup.js +258 -413
  30. package/dist/browserLogsRoute.d.ts +6 -0
  31. package/dist/browserLogsRoute.js +97 -0
  32. package/dist/collectionRegistry.d.ts +3 -1
  33. package/dist/collectionRegistry.js +43 -33
  34. package/dist/config.js +53 -122
  35. package/dist/configurationApp.js +180 -361
  36. package/dist/configurationPlugin.js +130 -302
  37. package/dist/consentApp.js +276 -421
  38. package/dist/docLoader.js +78 -126
  39. package/dist/envConfigurationPlugin.js +25 -147
  40. package/dist/errors.js +151 -247
  41. package/dist/example.js +28 -34
  42. package/dist/expressServer.d.ts +10 -0
  43. package/dist/expressServer.js +109 -255
  44. package/dist/frameworkModelNames.d.ts +24 -0
  45. package/dist/frameworkModelNames.js +31 -0
  46. package/dist/githubAuth.js +152 -216
  47. package/dist/httpClient.js +176 -264
  48. package/dist/index.d.ts +28 -1
  49. package/dist/index.js +53 -2
  50. package/dist/logger.js +145 -278
  51. package/dist/mcp/auth.js +76 -128
  52. package/dist/mcp/createMCPRequest.js +4 -5
  53. package/dist/mcp/handlers.js +268 -480
  54. package/dist/mcp/query.d.ts +0 -13
  55. package/dist/mcp/query.js +57 -151
  56. package/dist/mcp/registry.js +17 -30
  57. package/dist/mcp/schemaGenerator.js +95 -181
  58. package/dist/mcp/server.js +28 -100
  59. package/dist/mcp/serviceTokens.js +102 -191
  60. package/dist/mcp/toolGenerator.js +78 -191
  61. package/dist/middleware.js +15 -27
  62. package/dist/migrations/fixtures/all-down/20260910120000-one.d.ts +4 -0
  63. package/dist/migrations/fixtures/all-down/20260910120000-one.js +9 -0
  64. package/dist/migrations/fixtures/all-down/20260910120001-two.d.ts +4 -0
  65. package/dist/migrations/fixtures/all-down/20260910120001-two.js +9 -0
  66. package/dist/migrations/fixtures/bad-id/20260910120000-mismatch.d.ts +3 -0
  67. package/dist/migrations/fixtures/bad-id/20260910120000-mismatch.js +7 -0
  68. package/dist/migrations/fixtures/bad-name/not-a-migration.d.ts +3 -0
  69. package/dist/migrations/fixtures/bad-name/not-a-migration.js +7 -0
  70. package/dist/migrations/fixtures/missing-up/20260910120000-noup.d.ts +2 -0
  71. package/dist/migrations/fixtures/missing-up/20260910120000-noup.js +5 -0
  72. package/dist/migrations/fixtures/valid/20260910120000-alpha.d.ts +3 -0
  73. package/dist/migrations/fixtures/valid/20260910120000-alpha.js +7 -0
  74. package/dist/migrations/fixtures/valid/20260910120001-beta.d.ts +4 -0
  75. package/dist/migrations/fixtures/valid/20260910120001-beta.js +9 -0
  76. package/dist/migrations/generate.d.ts +17 -0
  77. package/dist/migrations/generate.js +155 -0
  78. package/dist/migrations/load.d.ts +20 -0
  79. package/dist/migrations/load.js +110 -0
  80. package/dist/migrations/lock.d.ts +13 -0
  81. package/dist/migrations/lock.js +73 -0
  82. package/dist/migrations/runner.d.ts +42 -0
  83. package/dist/migrations/runner.js +249 -0
  84. package/dist/migrations/schemaCatalog.d.ts +44 -0
  85. package/dist/migrations/schemaCatalog.js +185 -0
  86. package/dist/migrations/types.d.ts +87 -0
  87. package/dist/migrations/types.js +7 -0
  88. package/dist/models/consentForm.js +6 -6
  89. package/dist/models/consentResponse.js +5 -5
  90. package/dist/models/mcpServiceToken.js +66 -156
  91. package/dist/models/notification.d.ts +2 -0
  92. package/dist/models/notification.js +62 -0
  93. package/dist/models/notificationPreference.d.ts +2 -0
  94. package/dist/models/notificationPreference.js +49 -0
  95. package/dist/models/versionConfig.js +5 -5
  96. package/dist/notifications/notificationService.d.ts +40 -0
  97. package/dist/notifications/notificationService.js +183 -0
  98. package/dist/notifications/notificationsApp.d.ts +18 -0
  99. package/dist/notifications/notificationsApp.js +156 -0
  100. package/dist/notifications/notificationsBeforeSend.d.ts +14 -0
  101. package/dist/notifications/notificationsBeforeSend.js +32 -0
  102. package/dist/notifiers/googleChatNotifier.js +36 -117
  103. package/dist/notifiers/slackNotifier.d.ts +31 -2
  104. package/dist/notifiers/slackNotifier.js +170 -119
  105. package/dist/notifiers/zoomNotifier.js +60 -111
  106. package/dist/openApi.d.ts +1 -7
  107. package/dist/openApi.js +113 -127
  108. package/dist/openApiBuilder.d.ts +14 -3
  109. package/dist/openApiBuilder.js +117 -159
  110. package/dist/openApiCompat.js +81 -148
  111. package/dist/openApiEtag.js +7 -7
  112. package/dist/openApiValidator.d.ts +13 -1
  113. package/dist/openApiValidator.js +301 -246
  114. package/dist/orgs/orgContext.d.ts +23 -0
  115. package/dist/orgs/orgContext.js +128 -0
  116. package/dist/orgs/orgPermissions.d.ts +4 -0
  117. package/dist/orgs/orgPermissions.js +38 -0
  118. package/dist/orgs/orgPlugin.d.ts +13 -0
  119. package/dist/orgs/orgPlugin.js +66 -0
  120. package/dist/orgs/organizationModel.d.ts +13 -0
  121. package/dist/orgs/organizationModel.js +200 -0
  122. package/dist/orgs/organizationSettings.d.ts +19 -0
  123. package/dist/orgs/organizationSettings.js +113 -0
  124. package/dist/orgs/orgsApp.d.ts +28 -0
  125. package/dist/orgs/orgsApp.js +416 -0
  126. package/dist/permissions.d.ts +7 -13
  127. package/dist/permissions.js +95 -211
  128. package/dist/plugins.js +125 -218
  129. package/dist/populate.js +130 -240
  130. package/dist/rateLimit/applyTrustProxy.js +1 -1
  131. package/dist/rateLimit/createStore.js +7 -8
  132. package/dist/rateLimit/memoryStore.js +22 -100
  133. package/dist/rateLimit/middleware.d.ts +0 -8
  134. package/dist/rateLimit/middleware.js +49 -101
  135. package/dist/rateLimit/mongoStore.d.ts +1 -0
  136. package/dist/rateLimit/mongoStore.js +55 -112
  137. package/dist/rateLimit/policies.d.ts +0 -4
  138. package/dist/rateLimit/policies.js +44 -80
  139. package/dist/rateLimit/redisStore.d.ts +1 -0
  140. package/dist/rateLimit/redisStore.js +40 -133
  141. package/dist/rbac/access.js +122 -253
  142. package/dist/rbac/assertAllowed.js +95 -171
  143. package/dist/rbac/auditModel.js +14 -58
  144. package/dist/rbac/backfillAdmins.js +24 -130
  145. package/dist/rbac/fieldViews.js +46 -141
  146. package/dist/rbac/membershipOrgAdminSource.d.ts +6 -0
  147. package/dist/rbac/membershipOrgAdminSource.js +51 -0
  148. package/dist/rbac/middleware.js +30 -96
  149. package/dist/rbac/modelRouterAccess.d.ts +3 -0
  150. package/dist/rbac/modelRouterAccess.js +133 -307
  151. package/dist/rbac/permissionUtils.js +40 -179
  152. package/dist/rbac/realtimeAccess.js +81 -147
  153. package/dist/rbac/resolve.d.ts +1 -1
  154. package/dist/rbac/resolve.js +154 -319
  155. package/dist/rbac/roleManager.js +318 -700
  156. package/dist/rbac/roleModel.d.ts +2 -5
  157. package/dist/rbac/roleModel.js +60 -173
  158. package/dist/rbac/routes.js +93 -196
  159. package/dist/rbac/scopes.js +39 -133
  160. package/dist/rbac/statements.d.ts +10 -1
  161. package/dist/rbac/statements.js +42 -93
  162. package/dist/rbac/types.d.ts +5 -0
  163. package/dist/rbac/userPlugin.js +3 -29
  164. package/dist/realtime/changeStreamWatcher.d.ts +10 -4
  165. package/dist/realtime/changeStreamWatcher.js +499 -764
  166. package/dist/realtime/deprecation.d.ts +1 -0
  167. package/dist/realtime/deprecation.js +9 -10
  168. package/dist/realtime/queryMatcher.js +110 -191
  169. package/dist/realtime/queryStore.js +35 -118
  170. package/dist/realtime/realtimeApp.d.ts +1 -0
  171. package/dist/realtime/realtimeApp.js +248 -401
  172. package/dist/realtime/registry.js +19 -30
  173. package/dist/realtime/sessionRevalidation.js +132 -358
  174. package/dist/realtime/socketAuth.js +89 -208
  175. package/dist/realtime/socketUser.js +10 -56
  176. package/dist/requestContext.js +93 -139
  177. package/dist/schemaMetadata.js +181 -265
  178. package/dist/scriptRunner.js +96 -266
  179. package/dist/scrubAdminFields.js +36 -108
  180. package/dist/secretProviders.js +130 -299
  181. package/dist/seedRunner.js +221 -514
  182. package/dist/sync/adminBroadcastScope.d.ts +40 -0
  183. package/dist/sync/adminBroadcastScope.js +82 -0
  184. package/dist/sync/adminWindowAccess.d.ts +13 -0
  185. package/dist/sync/adminWindowAccess.js +25 -0
  186. package/dist/sync/adminWindowMutation.d.ts +88 -0
  187. package/dist/sync/adminWindowMutation.js +176 -0
  188. package/dist/sync/executors.d.ts +9 -3
  189. package/dist/sync/executors.js +425 -598
  190. package/dist/sync/loadHarness.js +392 -689
  191. package/dist/sync/models.js +181 -341
  192. package/dist/sync/mutationHandler.d.ts +5 -2
  193. package/dist/sync/mutationHandler.js +549 -697
  194. package/dist/sync/registrationSideEffects.js +41 -95
  195. package/dist/sync/registry.js +31 -47
  196. package/dist/sync/routes.d.ts +13 -0
  197. package/dist/sync/routes.js +484 -760
  198. package/dist/sync/scripts/compactTombstones.js +83 -228
  199. package/dist/sync/serialize.js +18 -58
  200. package/dist/sync/socketHandlers.d.ts +8 -2
  201. package/dist/sync/socketHandlers.js +271 -402
  202. package/dist/sync/streams.d.ts +2 -0
  203. package/dist/sync/streams.js +54 -116
  204. package/dist/sync/syncApp.d.ts +2 -1
  205. package/dist/sync/syncApp.js +14 -16
  206. package/dist/sync/syncBatch.d.ts +5 -2
  207. package/dist/sync/syncBatch.js +63 -168
  208. package/dist/sync/syncSeqPlugin.js +430 -702
  209. package/dist/sync/types.d.ts +18 -0
  210. package/dist/syncConsents.js +113 -253
  211. package/dist/terrenoApp.d.ts +29 -0
  212. package/dist/terrenoApp.js +184 -257
  213. package/dist/tests/createTestData.d.ts +1 -3
  214. package/dist/tests/createTestData.js +147 -259
  215. package/dist/tests/models.d.ts +1 -0
  216. package/dist/tests/models.js +23 -56
  217. package/dist/tests/mongoTestSetup.js +42 -103
  218. package/dist/tests/testHelper.d.ts +0 -5
  219. package/dist/tests/testHelper.js +32 -101
  220. package/dist/tests.js +12 -51
  221. package/dist/transformers.js +61 -164
  222. package/dist/types/authToken.d.ts +3 -3
  223. package/dist/types/mcpServiceToken.d.ts +2 -2
  224. package/dist/types/membership.d.ts +23 -0
  225. package/dist/types/membership.js +2 -0
  226. package/dist/types/notification.d.ts +28 -0
  227. package/dist/types/notification.js +2 -0
  228. package/dist/types/notificationPreference.d.ts +20 -0
  229. package/dist/types/notificationPreference.js +2 -0
  230. package/dist/types/organization.d.ts +36 -0
  231. package/dist/types/organization.js +2 -0
  232. package/dist/utils.js +31 -93
  233. package/dist/vendor/wesleytodd-openapi/index.js +37 -51
  234. package/dist/vendor/wesleytodd-openapi/lib/generate-doc.js +32 -40
  235. package/dist/vendor/wesleytodd-openapi/lib/layer-schema.js +3 -3
  236. package/dist/vendor/wesleytodd-openapi/lib/ui.js +50 -19
  237. package/dist/vendor/wesleytodd-openapi/lib/validate.js +19 -47
  238. package/dist/versionCheckPlugin.js +52 -100
  239. package/dist/webhooks/headerValue.js +2 -2
  240. package/dist/webhooks/idempotency/memoryStore.js +16 -59
  241. package/dist/webhooks/idempotency/mongoStore.js +55 -130
  242. package/dist/webhooks/idempotency/webhookReceipt.d.ts +4 -49
  243. package/dist/webhooks/idempotency/webhookReceipt.js +14 -14
  244. package/dist/webhooks/rawBody.d.ts +1 -0
  245. package/dist/webhooks/rawBody.js +2 -1
  246. package/dist/webhooks/timingSafeEqual.js +4 -5
  247. package/dist/webhooks/verifiers/hmac.js +17 -18
  248. package/dist/webhooks/verifiers/sendgrid.js +20 -22
  249. package/dist/webhooks/verifiers/stripe.js +31 -65
  250. package/dist/webhooks/verifiers/twilio.js +23 -73
  251. package/dist/webhooks/webhooksApp.js +78 -177
  252. package/dist/zodOpenApi.js +2 -2
  253. package/package.json +34 -28
  254. package/src/__snapshots__/openApi.test.ts.snap +192 -54
  255. package/src/__snapshots__/openApiBuilder.test.ts.snap +0 -18
  256. package/src/__snapshots__/schemaMetadata.test.ts.snap +0 -1
  257. package/src/__tests__/browserLogsRoute.test.ts +165 -0
  258. package/src/adminTypes.ts +8 -0
  259. package/src/api.test.ts +39 -2
  260. package/src/api.ts +68 -0
  261. package/src/audit/auditApp.test.ts +243 -0
  262. package/src/audit/auditApp.ts +139 -0
  263. package/src/audit/auditEventModel.ts +160 -0
  264. package/src/audit/auditRouter.test.ts +456 -0
  265. package/src/audit/cloudTasksEnqueue.test.ts +124 -0
  266. package/src/audit/cloudTasksEnqueue.ts +104 -0
  267. package/src/audit/diff.ts +163 -0
  268. package/src/audit/processQueue.ts +69 -0
  269. package/src/audit/rbacSink.test.ts +86 -0
  270. package/src/audit/rbacSink.ts +42 -0
  271. package/src/audit/record.test.ts +402 -0
  272. package/src/audit/record.ts +329 -0
  273. package/src/auth.test.ts +1 -1
  274. package/src/auth.ts +1 -1
  275. package/src/authRecovery.test.ts +43 -0
  276. package/src/authRecovery.ts +16 -10
  277. package/src/authTokens.ts +6 -2
  278. package/src/authVerification.test.ts +22 -0
  279. package/src/betterAuth.ts +7 -0
  280. package/src/betterAuthSetup.test.ts +27 -0
  281. package/src/betterAuthSetup.ts +1 -0
  282. package/src/browserLogsRoute.ts +110 -0
  283. package/src/collectionRegistry.test.ts +8 -9
  284. package/src/collectionRegistry.ts +21 -1
  285. package/src/configurationPlugin.test.ts +1 -11
  286. package/src/express.d.ts +2 -0
  287. package/src/expressServer.test.ts +50 -2
  288. package/src/expressServer.ts +10 -0
  289. package/src/frameworkModelNames.test.ts +62 -0
  290. package/src/frameworkModelNames.ts +33 -0
  291. package/src/index.ts +76 -0
  292. package/src/isolated/migrateCliConnect.isolated.ts +51 -0
  293. package/src/mcp/auth.test.ts +34 -1
  294. package/src/mcp/handlers.test.ts +275 -0
  295. package/src/mcp/query.ts +3 -3
  296. package/src/mcp/toolGenerator.test.ts +81 -0
  297. package/src/migrations/cli.test.ts +353 -0
  298. package/src/migrations/cli.ts +283 -0
  299. package/src/migrations/fixtures/all-down/20260910120000-one.ts +6 -0
  300. package/src/migrations/fixtures/all-down/20260910120001-two.ts +6 -0
  301. package/src/migrations/fixtures/bad-id/20260910120000-mismatch.ts +4 -0
  302. package/src/migrations/fixtures/bad-name/not-a-migration.ts +4 -0
  303. package/src/migrations/fixtures/missing-up/20260910120000-noup.ts +2 -0
  304. package/src/migrations/fixtures/valid/20260910120000-alpha.ts +4 -0
  305. package/src/migrations/fixtures/valid/20260910120001-beta.ts +6 -0
  306. package/src/migrations/generate.test.ts +333 -0
  307. package/src/migrations/generate.ts +216 -0
  308. package/src/migrations/load.test.ts +103 -0
  309. package/src/migrations/load.ts +124 -0
  310. package/src/migrations/lock.test.ts +133 -0
  311. package/src/migrations/lock.ts +118 -0
  312. package/src/migrations/runner.test.ts +504 -0
  313. package/src/migrations/runner.ts +358 -0
  314. package/src/migrations/schemaCatalog.test.ts +159 -0
  315. package/src/migrations/schemaCatalog.ts +262 -0
  316. package/src/migrations/types.ts +94 -0
  317. package/src/models/mcpServiceToken.ts +4 -3
  318. package/src/models/notification.ts +69 -0
  319. package/src/models/notificationPreference.ts +62 -0
  320. package/src/notifications/notificationService.ts +254 -0
  321. package/src/notifications/notificationsApp.test.ts +528 -0
  322. package/src/notifications/notificationsApp.ts +200 -0
  323. package/src/notifications/notificationsBeforeSend.ts +51 -0
  324. package/src/notifiers/slackNotifier.test.ts +186 -1
  325. package/src/notifiers/slackNotifier.ts +167 -8
  326. package/src/openApi.test.ts +0 -1
  327. package/src/openApi.ts +2 -1
  328. package/src/openApiBuilder.ts +14 -3
  329. package/src/openApiValidator.test.ts +221 -2
  330. package/src/openApiValidator.ts +218 -33
  331. package/src/orgs/orgAccessOptIn.test.ts +87 -0
  332. package/src/orgs/orgContext.test.ts +259 -0
  333. package/src/orgs/orgContext.ts +151 -0
  334. package/src/orgs/orgPermissions.test.ts +105 -0
  335. package/src/orgs/orgPermissions.ts +40 -0
  336. package/src/orgs/orgPlugin.test.ts +130 -0
  337. package/src/orgs/orgPlugin.ts +70 -0
  338. package/src/orgs/orgRbac.test.ts +267 -0
  339. package/src/orgs/orgSecurityDefects.test.ts +415 -0
  340. package/src/orgs/organizationModel.test.ts +205 -0
  341. package/src/orgs/organizationModel.ts +262 -0
  342. package/src/orgs/organizationSettings.test.ts +113 -0
  343. package/src/orgs/organizationSettings.ts +126 -0
  344. package/src/orgs/orgsApp.test.ts +382 -0
  345. package/src/orgs/orgsApp.ts +563 -0
  346. package/src/permissions.test.ts +62 -36
  347. package/src/permissions.ts +8 -30
  348. package/src/plugins.test.ts +5 -0
  349. package/src/plugins.ts +3 -0
  350. package/src/rateLimit/middleware.ts +1 -1
  351. package/src/rateLimit/mongoStore.ts +1 -0
  352. package/src/rateLimit/policies.ts +2 -2
  353. package/src/rateLimit/redisStore.ts +1 -0
  354. package/src/rbac/access.ts +11 -3
  355. package/src/rbac/membershipOrgAdminSource.ts +59 -0
  356. package/src/rbac/modelRouterAccess.ts +3 -0
  357. package/src/rbac/permissionUtils.test.ts +26 -5
  358. package/src/rbac/resolve.test.ts +34 -2
  359. package/src/rbac/resolve.ts +26 -7
  360. package/src/rbac/roleModel.test.ts +34 -1
  361. package/src/rbac/roleModel.ts +17 -1
  362. package/src/rbac/statements.test.ts +19 -0
  363. package/src/rbac/statements.ts +19 -1
  364. package/src/rbac/types.ts +5 -0
  365. package/src/realtime/changeStreamWatcher.ts +73 -33
  366. package/src/realtime/deprecation.ts +1 -0
  367. package/src/realtime/realtime.test.ts +357 -185
  368. package/src/realtime/realtimeApp.ts +2 -1
  369. package/src/schemaMetadata.test.ts +14 -0
  370. package/src/schemaMetadata.ts +5 -5
  371. package/src/sync/adminBroadcastConfig.test.ts +96 -0
  372. package/src/sync/adminBroadcastScope.test.ts +155 -0
  373. package/src/sync/adminBroadcastScope.ts +123 -0
  374. package/src/sync/adminWindowAccess.test.ts +57 -0
  375. package/src/sync/adminWindowAccess.ts +32 -0
  376. package/src/sync/adminWindowMutation.test.ts +450 -0
  377. package/src/sync/adminWindowMutation.ts +283 -0
  378. package/src/sync/executors.ts +33 -6
  379. package/src/sync/integration.test.ts +2 -2
  380. package/src/sync/mutationHandler.test.ts +277 -1
  381. package/src/sync/mutationHandler.ts +171 -29
  382. package/src/sync/registry.ts +4 -0
  383. package/src/sync/routes.ts +52 -8
  384. package/src/sync/socketHandlers.ts +154 -58
  385. package/src/sync/streams.ts +6 -0
  386. package/src/sync/sync.test.ts +3 -2
  387. package/src/sync/syncApp.ts +2 -1
  388. package/src/sync/syncBatch.ts +7 -2
  389. package/src/sync/syncRoutes.test.ts +297 -3
  390. package/src/sync/syncSocket.test.ts +229 -0
  391. package/src/sync/types.ts +20 -0
  392. package/src/terrenoApp.migrations.test.ts +114 -0
  393. package/src/terrenoApp.test.ts +41 -0
  394. package/src/terrenoApp.ts +97 -31
  395. package/src/tests/createTestData.ts +2 -2
  396. package/src/tests/models.ts +10 -2
  397. package/src/tests/testHelper.ts +1 -7
  398. package/src/types/authToken.ts +2 -4
  399. package/src/types/mcpServiceToken.ts +1 -7
  400. package/src/types/membership.ts +48 -0
  401. package/src/types/notification.ts +34 -0
  402. package/src/types/notificationPreference.ts +28 -0
  403. package/src/types/organization.ts +49 -0
  404. package/src/types.d.ts +1 -0
  405. package/src/webhooks/idempotency/webhookReceipt.ts +8 -10
  406. package/src/webhooks/rawBody.test.ts +33 -0
  407. package/src/webhooks/rawBody.ts +1 -0
  408. package/tsconfig.json +13 -54
  409. package/tsconfig.typedoc.json +4 -1
  410. package/dist/vendor/wesleytodd-openapi/lib/convert-yaml.d.ts +0 -2
  411. package/dist/vendor/wesleytodd-openapi/lib/convert-yaml.js +0 -13
  412. package/src/vendor/wesleytodd-openapi/lib/convert-yaml.js +0 -13
@@ -1,15 +1,4 @@
1
1
  "use strict";
2
- var __assign = (this && this.__assign) || function () {
3
- __assign = Object.assign || function(t) {
4
- for (var s, i = 1, n = arguments.length; i < n; i++) {
5
- s = arguments[i];
6
- for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
7
- t[p] = s[p];
8
- }
9
- return t;
10
- };
11
- return __assign.apply(this, arguments);
12
- };
13
2
  var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
14
3
  if (k2 === undefined) k2 = k;
15
4
  var desc = Object.getOwnPropertyDescriptor(m, k);
@@ -43,78 +32,6 @@ var __importStar = (this && this.__importStar) || (function () {
43
32
  return result;
44
33
  };
45
34
  })();
46
- var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
47
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
48
- return new (P || (P = Promise))(function (resolve, reject) {
49
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
50
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
51
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
52
- step((generator = generator.apply(thisArg, _arguments || [])).next());
53
- });
54
- };
55
- var __generator = (this && this.__generator) || function (thisArg, body) {
56
- var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g = Object.create((typeof Iterator === "function" ? Iterator : Object).prototype);
57
- return g.next = verb(0), g["throw"] = verb(1), g["return"] = verb(2), typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
58
- function verb(n) { return function (v) { return step([n, v]); }; }
59
- function step(op) {
60
- if (f) throw new TypeError("Generator is already executing.");
61
- while (g && (g = 0, op[0] && (_ = 0)), _) try {
62
- if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
63
- if (y = 0, t) op = [op[0] & 2, t.value];
64
- switch (op[0]) {
65
- case 0: case 1: t = op; break;
66
- case 4: _.label++; return { value: op[1], done: false };
67
- case 5: _.label++; y = op[1]; op = [0]; continue;
68
- case 7: op = _.ops.pop(); _.trys.pop(); continue;
69
- default:
70
- if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
71
- if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
72
- if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
73
- if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
74
- if (t[2]) _.ops.pop();
75
- _.trys.pop(); continue;
76
- }
77
- op = body.call(thisArg, _);
78
- } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
79
- if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
80
- }
81
- };
82
- var __values = (this && this.__values) || function(o) {
83
- var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0;
84
- if (m) return m.call(o);
85
- if (o && typeof o.length === "number") return {
86
- next: function () {
87
- if (o && i >= o.length) o = void 0;
88
- return { value: o && o[i++], done: !o };
89
- }
90
- };
91
- throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined.");
92
- };
93
- var __read = (this && this.__read) || function (o, n) {
94
- var m = typeof Symbol === "function" && o[Symbol.iterator];
95
- if (!m) return o;
96
- var i = m.call(o), r, ar = [], e;
97
- try {
98
- while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
99
- }
100
- catch (error) { e = { error: error }; }
101
- finally {
102
- try {
103
- if (r && !r.done && (m = i["return"])) m.call(i);
104
- }
105
- finally { if (e) throw e.error; }
106
- }
107
- return ar;
108
- };
109
- var __spreadArray = (this && this.__spreadArray) || function (to, from, pack) {
110
- if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
111
- if (ar || !(i in from)) {
112
- if (!ar) ar = Array.prototype.slice.call(from, 0, i);
113
- ar[i] = from[i];
114
- }
115
- }
116
- return to.concat(ar || Array.prototype.slice.call(from));
117
- };
118
35
  var __importDefault = (this && this.__importDefault) || function (mod) {
119
36
  return (mod && mod.__esModule) ? mod : { "default": mod };
120
37
  };
@@ -140,63 +57,53 @@ Object.defineProperty(exports, "__esModule", { value: true });
140
57
  * pass/fail lines rather than thrown, so a single divergent client doesn't abort the
141
58
  * report. The process exits non-zero if any client fails to converge.
142
59
  */
143
- var node_http_1 = require("node:http");
144
- var syncdb_1 = require("@terreno/syncdb");
145
- var express_1 = __importDefault(require("express"));
146
- var luxon_1 = require("luxon");
147
- var mongoose_1 = __importStar(require("mongoose"));
148
- var passport_local_mongoose_1 = __importDefault(require("passport-local-mongoose"));
149
- var api_1 = require("../api");
150
- var auth_1 = require("../auth");
151
- var errors_1 = require("../errors");
152
- var logger_1 = require("../logger");
153
- var permissions_1 = require("../permissions");
154
- var plugins_1 = require("../plugins");
155
- var realtimeApp_1 = require("../realtime/realtimeApp");
156
- var registry_1 = require("./registry");
157
- var syncApp_1 = require("./syncApp");
158
- var syncSeqPlugin_1 = require("./syncSeqPlugin");
60
+ const node_http_1 = require("node:http");
61
+ const syncdb_1 = require("@terreno/syncdb");
62
+ const express_1 = __importDefault(require("express"));
63
+ const luxon_1 = require("luxon");
64
+ const mongoose_1 = __importStar(require("mongoose"));
65
+ const passport_local_mongoose_1 = __importDefault(require("passport-local-mongoose"));
66
+ const api_1 = require("../api");
67
+ const auth_1 = require("../auth");
68
+ const errors_1 = require("../errors");
69
+ const logger_1 = require("../logger");
70
+ const permissions_1 = require("../permissions");
71
+ const plugins_1 = require("../plugins");
72
+ const realtimeApp_1 = require("../realtime/realtimeApp");
73
+ const registry_1 = require("./registry");
74
+ const syncApp_1 = require("./syncApp");
75
+ const syncSeqPlugin_1 = require("./syncSeqPlugin");
159
76
  /** Simple `--flag=value` argv parser; no CLI framework needed for a one-off script. */
160
- var parseFlags = function (argv) {
161
- var e_1, _a;
162
- var _b, _c;
163
- var flags = new Map();
164
- try {
165
- for (var argv_1 = __values(argv), argv_1_1 = argv_1.next(); !argv_1_1.done; argv_1_1 = argv_1.next()) {
166
- var arg = argv_1_1.value;
167
- var match = /^--([^=]+)=(.*)$/.exec(arg);
168
- if (match) {
169
- flags.set(match[1], match[2]);
170
- }
171
- }
172
- }
173
- catch (e_1_1) { e_1 = { error: e_1_1 }; }
174
- finally {
175
- try {
176
- if (argv_1_1 && !argv_1_1.done && (_a = argv_1.return)) _a.call(argv_1);
77
+ const parseFlags = (argv) => {
78
+ const flags = new Map();
79
+ for (const arg of argv) {
80
+ const match = /^--([^=]+)=(.*)$/.exec(arg);
81
+ if (match) {
82
+ flags.set(match[1], match[2]);
177
83
  }
178
- finally { if (e_1) throw e_1.error; }
179
84
  }
180
- var num = function (key, fallback) {
181
- var raw = flags.get(key);
85
+ const num = (key, fallback) => {
86
+ const raw = flags.get(key);
182
87
  if (raw === undefined) {
183
88
  return fallback;
184
89
  }
185
- var parsed = Number(raw);
90
+ const parsed = Number(raw);
186
91
  return Number.isFinite(parsed) ? parsed : fallback;
187
92
  };
188
93
  return {
189
94
  clients: num("clients", 20),
190
95
  durationSec: num("durationSec", 30),
191
- mongoUri: (_c = (_b = flags.get("mongoUri")) !== null && _b !== void 0 ? _b : process.env.MONGO_URI) !== null && _c !== void 0 ? _c : "mongodb://127.0.0.1:27017/terreno-sync-load?replicaSet=rs0",
96
+ mongoUri: flags.get("mongoUri") ??
97
+ process.env.MONGO_URI ??
98
+ "mongodb://127.0.0.1:27017/terreno-sync-load?replicaSet=rs0",
192
99
  port: num("port", 0),
193
- seedDocs: num("seedDocs", 5000),
100
+ seedDocs: num("seedDocs", 5_000),
194
101
  targetRate: num("targetRate", 200),
195
102
  };
196
103
  };
197
- var loadTodoSchema = new mongoose_1.Schema({
104
+ const loadTodoSchema = new mongoose_1.Schema({
198
105
  _id: {
199
- default: function () { return new mongoose_1.default.Types.ObjectId().toHexString(); },
106
+ default: () => new mongoose_1.default.Types.ObjectId().toHexString(),
200
107
  description: "The document id (string so offline clients can mint ids)",
201
108
  type: String,
202
109
  },
@@ -211,605 +118,401 @@ var loadTodoSchema = new mongoose_1.Schema({
211
118
  loadTodoSchema.plugin(plugins_1.isDeletedPlugin);
212
119
  loadTodoSchema.plugin(plugins_1.createdUpdatedPlugin);
213
120
  loadTodoSchema.plugin(syncSeqPlugin_1.syncPlugin);
214
- var LoadTodoModel = (0, mongoose_1.model)("LoadHarnessTodo", loadTodoSchema);
215
- var COLLECTION = "loadHarnessTodos";
121
+ const LoadTodoModel = (0, mongoose_1.model)("LoadHarnessTodo", loadTodoSchema);
122
+ const COLLECTION = "loadHarnessTodos";
216
123
  // ─────────────────────────────────────────────────────────────────────────────
217
124
  // Percentile helper
218
125
  // ─────────────────────────────────────────────────────────────────────────────
219
- var percentile = function (samples, p) {
126
+ const percentile = (samples, p) => {
220
127
  if (samples.length === 0) {
221
128
  return 0;
222
129
  }
223
- var sorted = __spreadArray([], __read(samples), false).sort(function (a, b) { return a - b; });
224
- var index = Math.min(sorted.length - 1, Math.max(0, Math.ceil((p / 100) * sorted.length) - 1));
130
+ const sorted = [...samples].sort((a, b) => a - b);
131
+ const index = Math.min(sorted.length - 1, Math.max(0, Math.ceil((p / 100) * sorted.length) - 1));
225
132
  return sorted[index];
226
133
  };
227
134
  // ─────────────────────────────────────────────────────────────────────────────
228
135
  // Rig helpers
229
136
  // ─────────────────────────────────────────────────────────────────────────────
230
137
  /** Poll until the predicate holds, or throw naming the failed wait. */
231
- var waitFor = function (predicate_1) {
232
- var args_1 = [];
233
- for (var _i = 1; _i < arguments.length; _i++) {
234
- args_1[_i - 1] = arguments[_i];
138
+ const waitFor = async (predicate, { label = "condition", timeoutMs = 30_000, intervalMs = 25, } = {}) => {
139
+ const start = luxon_1.DateTime.now().toMillis();
140
+ while (luxon_1.DateTime.now().toMillis() - start < timeoutMs) {
141
+ if (await predicate()) {
142
+ return;
143
+ }
144
+ await new Promise((resolve) => setTimeout(resolve, intervalMs));
235
145
  }
236
- return __awaiter(void 0, __spreadArray([predicate_1], __read(args_1), false), void 0, function (predicate, _a) {
237
- var start;
238
- var _b = _a === void 0 ? {} : _a, _c = _b.label, label = _c === void 0 ? "condition" : _c, _d = _b.timeoutMs, timeoutMs = _d === void 0 ? 30000 : _d, _e = _b.intervalMs, intervalMs = _e === void 0 ? 25 : _e;
239
- return __generator(this, function (_f) {
240
- switch (_f.label) {
241
- case 0:
242
- start = luxon_1.DateTime.now().toMillis();
243
- _f.label = 1;
244
- case 1:
245
- if (!(luxon_1.DateTime.now().toMillis() - start < timeoutMs)) return [3 /*break*/, 4];
246
- return [4 /*yield*/, predicate()];
247
- case 2:
248
- if (_f.sent()) {
249
- return [2 /*return*/];
250
- }
251
- return [4 /*yield*/, new Promise(function (resolve) { return setTimeout(resolve, intervalMs); })];
252
- case 3:
253
- _f.sent();
254
- return [3 /*break*/, 1];
255
- case 4: throw new errors_1.APIError({
256
- status: 500,
257
- title: "Timed out after ".concat(timeoutMs, "ms waiting for ").concat(label),
258
- });
259
- }
260
- });
146
+ throw new errors_1.APIError({
147
+ status: 500,
148
+ title: `Timed out after ${timeoutMs}ms waiting for ${label}`,
261
149
  });
262
150
  };
263
- var makeAuthProvider = function (user) { return ({
264
- getToken: function () { return __awaiter(void 0, void 0, void 0, function () { var _a; return __generator(this, function (_b) {
265
- switch (_b.label) {
266
- case 0: return [4 /*yield*/, (0, auth_1.generateTokens)(user)];
267
- case 1: return [2 /*return*/, (_a = (_b.sent()).token) !== null && _a !== void 0 ? _a : null];
268
- }
269
- }); }); },
270
- getUserId: function () { return __awaiter(void 0, void 0, void 0, function () { return __generator(this, function (_a) {
271
- return [2 /*return*/, String(user._id)];
272
- }); }); },
273
- onAuthChange: function () { return function () { }; },
274
- }); };
275
- var makeHarnessClient = function (_a) {
276
- var name = _a.name, user = _a.user, baseUrl = _a.baseUrl;
277
- var authProvider = makeAuthProvider(user);
278
- var fetchImpl = function (input, init) { return fetch(input, init); };
279
- var httpChannel = (0, syncdb_1.createHttpChannel)({ authProvider: authProvider, baseUrl: baseUrl, fetchImpl: fetchImpl });
280
- var transport = (0, syncdb_1.createSocketTransport)({ authProvider: authProvider, baseUrl: baseUrl, timeoutMs: 8000 });
151
+ const makeAuthProvider = (user) => ({
152
+ getToken: async () => (await (0, auth_1.generateTokens)(user)).token ?? null,
153
+ getUserId: async () => String(user._id),
154
+ onAuthChange: () => () => { },
155
+ });
156
+ const makeHarnessClient = ({ name, user, baseUrl, }) => {
157
+ const authProvider = makeAuthProvider(user);
158
+ const fetchImpl = (input, init) => fetch(input, init);
159
+ const httpChannel = (0, syncdb_1.createHttpChannel)({ authProvider, baseUrl, fetchImpl });
160
+ const transport = (0, syncdb_1.createSocketTransport)({ authProvider, baseUrl, timeoutMs: 8_000 });
281
161
  (0, syncdb_1.clearMemoryPersisterData)({ databaseName: name });
282
- var client = (0, syncdb_1.createSyncDb)({
283
- authProvider: authProvider,
162
+ const client = (0, syncdb_1.createSyncDb)({
163
+ authProvider,
284
164
  collections: [COLLECTION],
285
- httpChannel: httpChannel,
286
- name: name,
165
+ httpChannel,
166
+ name,
287
167
  persisterFactory: syncdb_1.memoryPersisterFactory,
288
168
  reconcileIntervalMs: 0,
289
- transport: transport,
169
+ transport,
290
170
  });
291
- return { client: client, httpChannel: httpChannel, name: name, ownerId: String(user._id), transport: transport, user: user };
171
+ return { client, httpChannel, name, ownerId: String(user._id), transport, user };
292
172
  };
293
173
  /** Build the Express + Socket.io rig: synced model, SyncApp, RealtimeApp, listening server. */
294
- var buildRig = function (config) { return __awaiter(void 0, void 0, void 0, function () {
295
- var userSchema, UserModel, registration, app, authUserModel, realtimeApp, httpServer, port, baseUrl;
296
- var _a, _b, _c, _d, _e;
297
- return __generator(this, function (_f) {
298
- switch (_f.label) {
299
- case 0:
300
- process.env.TOKEN_SECRET = (_a = process.env.TOKEN_SECRET) !== null && _a !== void 0 ? _a : "load-harness-token-secret";
301
- process.env.TOKEN_ISSUER = (_b = process.env.TOKEN_ISSUER) !== null && _b !== void 0 ? _b : "terreno-load-harness";
302
- process.env.REFRESH_TOKEN_SECRET =
303
- (_c = process.env.REFRESH_TOKEN_SECRET) !== null && _c !== void 0 ? _c : "load-harness-refresh-secret";
304
- process.env.SESSION_SECRET = (_d = process.env.SESSION_SECRET) !== null && _d !== void 0 ? _d : "load-harness-session-secret";
305
- (0, registry_1.clearSyncRegistry)();
306
- userSchema = new mongoose_1.Schema({
307
- admin: { default: false, description: "Whether the user has admin privileges", type: Boolean },
308
- email: { description: "The user's email", type: String },
309
- });
310
- userSchema.plugin(passport_local_mongoose_1.default, { usernameField: "email" });
311
- UserModel = (_e = mongoose_1.default.models.LoadHarnessUser) !== null && _e !== void 0 ? _e : (0, mongoose_1.model)("LoadHarnessUser", userSchema);
312
- registration = (0, api_1.modelRouter)("/loadHarnessTodos", LoadTodoModel, {
313
- permissions: {
314
- create: [permissions_1.Permissions.IsAuthenticated],
315
- delete: [permissions_1.Permissions.IsOwner],
316
- list: [permissions_1.Permissions.IsAuthenticated],
317
- read: [permissions_1.Permissions.IsOwner],
318
- update: [permissions_1.Permissions.IsOwner],
319
- },
320
- preCreate: function (body, req) {
321
- var _a, _b;
322
- var user = req.user;
323
- return __assign(__assign({}, body), { ownerId: String((_b = (_a = user === null || user === void 0 ? void 0 : user._id) !== null && _a !== void 0 ? _a : user === null || user === void 0 ? void 0 : user.id) !== null && _b !== void 0 ? _b : "") });
324
- },
325
- sync: { scope: { type: "owner" } },
326
- });
327
- app = (0, express_1.default)();
328
- app.use(express_1.default.json());
329
- authUserModel = UserModel;
330
- (0, auth_1.setupAuth)(app, authUserModel);
331
- (0, auth_1.addAuthRoutes)(app, authUserModel);
332
- new syncApp_1.SyncApp({}).register(app);
333
- app.use(registration.path, registration.router);
334
- realtimeApp = new realtimeApp_1.RealtimeApp({});
335
- realtimeApp.register(app);
336
- httpServer = (0, node_http_1.createServer)(app);
337
- return [4 /*yield*/, new Promise(function (resolve) {
338
- httpServer.listen(config.port, function () { return resolve(); });
339
- })];
340
- case 1:
341
- _f.sent();
342
- port = httpServer.address().port;
343
- baseUrl = "http://127.0.0.1:".concat(port);
344
- realtimeApp.onServerCreated(httpServer);
345
- // Give the change-stream cursor a moment to open before any writes happen.
346
- return [4 /*yield*/, new Promise(function (resolve) { return setTimeout(resolve, 300); })];
347
- case 2:
348
- // Give the change-stream cursor a moment to open before any writes happen.
349
- _f.sent();
350
- return [2 /*return*/, { baseUrl: baseUrl, httpServer: httpServer, realtimeApp: realtimeApp }];
351
- }
174
+ const buildRig = async (config) => {
175
+ process.env.TOKEN_SECRET = process.env.TOKEN_SECRET ?? "load-harness-token-secret";
176
+ process.env.TOKEN_ISSUER = process.env.TOKEN_ISSUER ?? "terreno-load-harness";
177
+ process.env.REFRESH_TOKEN_SECRET =
178
+ process.env.REFRESH_TOKEN_SECRET ?? "load-harness-refresh-secret";
179
+ process.env.SESSION_SECRET = process.env.SESSION_SECRET ?? "load-harness-session-secret";
180
+ (0, registry_1.clearSyncRegistry)();
181
+ // Fresh User model bound to this script's own mongoose connection. setupAuth requires
182
+ // a passport-local-mongoose-backed model (createStrategy/serializeUser/deserializeUser),
183
+ // even though the harness only ever mints JWTs directly via generateTokens and never
184
+ // exercises the password login route.
185
+ const userSchema = new mongoose_1.Schema({
186
+ admin: { default: false, description: "Whether the user has admin privileges", type: Boolean },
187
+ email: { description: "The user's email", type: String },
188
+ });
189
+ userSchema.plugin(passport_local_mongoose_1.default, { usernameField: "email" });
190
+ const UserModel = mongoose_1.default.models.LoadHarnessUser ?? (0, mongoose_1.model)("LoadHarnessUser", userSchema);
191
+ // modelRouter's 3-argument form both registers the sync entry AND returns the
192
+ // Express router to mount, so a single call does both — no need to call it twice.
193
+ const registration = (0, api_1.modelRouter)("/loadHarnessTodos", LoadTodoModel, {
194
+ permissions: {
195
+ create: [permissions_1.Permissions.IsAuthenticated],
196
+ delete: [permissions_1.Permissions.IsOwner],
197
+ list: [permissions_1.Permissions.IsAuthenticated],
198
+ read: [permissions_1.Permissions.IsOwner],
199
+ update: [permissions_1.Permissions.IsOwner],
200
+ },
201
+ preCreate: (body, req) => {
202
+ const user = req.user;
203
+ return { ...body, ownerId: String(user?._id ?? user?.id ?? "") };
204
+ },
205
+ sync: { scope: { type: "owner" } },
352
206
  });
353
- }); };
207
+ const app = (0, express_1.default)();
208
+ app.use(express_1.default.json());
209
+ // passport-local-mongoose adds createStrategy/serializeUser at runtime, so the compiled
210
+ // model's static type does not carry them — bridge to the auth package's UserModel shape.
211
+ const authUserModel = UserModel;
212
+ (0, auth_1.setupAuth)(app, authUserModel);
213
+ (0, auth_1.addAuthRoutes)(app, authUserModel);
214
+ new syncApp_1.SyncApp({}).register(app);
215
+ app.use(registration.path, registration.router);
216
+ const realtimeApp = new realtimeApp_1.RealtimeApp({});
217
+ realtimeApp.register(app);
218
+ const httpServer = (0, node_http_1.createServer)(app);
219
+ await new Promise((resolve) => {
220
+ httpServer.listen(config.port, () => resolve());
221
+ });
222
+ const { port } = httpServer.address();
223
+ const baseUrl = `http://127.0.0.1:${port}`;
224
+ realtimeApp.onServerCreated(httpServer);
225
+ // Give the change-stream cursor a moment to open before any writes happen.
226
+ await new Promise((resolve) => setTimeout(resolve, 300));
227
+ return { baseUrl, httpServer, realtimeApp };
228
+ };
354
229
  // ─────────────────────────────────────────────────────────────────────────────
355
230
  // Main
356
231
  // ─────────────────────────────────────────────────────────────────────────────
357
- var main = function () { return __awaiter(void 0, void 0, void 0, function () {
358
- var config, _a, httpServer, realtimeApp, baseUrl, exitCode, harnessClients, UserModel, users, i, user, i, perOwnerCount_1, seeds, bootstrapStart, bootstrapWallMs, mutateLatenciesMs_1, fanoutLagsMs_1, conflictCount_1, ackCount_1, nackCount_1, duplicateCount_1, trackMutation, randomClient, knownEntityIds, _b, _c, _d, i, hc, _e, _f, entity, loadPromises, intervalMs_1, loadEnd, _loop_1, harnessClients_1, harnessClients_1_1, hc, _g, _h, conflict, convergenceFailures, harnessClients_2, harnessClients_2_1, hc, localEntities, serverDocs, serverMap, matches, localEntities_1, localEntities_1_1, _j, id, local, server, localData, e_2_1, report, error_1, harnessClients_3, harnessClients_3_1, hc, e_3_1;
359
- var e_4, _k, e_5, _l, e_6, _m, e_7, _o, e_2, _p, e_8, _q, e_3, _r;
360
- var _s, _t, _u, _v;
361
- return __generator(this, function (_w) {
362
- switch (_w.label) {
363
- case 0:
364
- config = parseFlags(process.argv.slice(2));
365
- logger_1.logger.info("[loadHarness] starting", config);
366
- return [4 /*yield*/, mongoose_1.default.connect(config.mongoUri)];
367
- case 1:
368
- _w.sent();
369
- return [4 /*yield*/, Promise.all([
370
- LoadTodoModel.collection.deleteMany({}),
371
- (_s = mongoose_1.default.connection.db) === null || _s === void 0 ? void 0 : _s.collection("syncmutations").deleteMany({}),
372
- (_t = mongoose_1.default.connection.db) === null || _t === void 0 ? void 0 : _t.collection("synccounters").deleteMany({}),
373
- ])];
374
- case 2:
375
- _w.sent();
376
- return [4 /*yield*/, buildRig(config)];
377
- case 3:
378
- _a = _w.sent(), httpServer = _a.httpServer, realtimeApp = _a.realtimeApp, baseUrl = _a.baseUrl;
379
- exitCode = 0;
380
- harnessClients = [];
381
- _w.label = 4;
382
- case 4:
383
- _w.trys.push([4, 27, 28, 39]);
384
- UserModel = mongoose_1.default.models.LoadHarnessUser;
385
- users = [];
386
- i = 0;
387
- _w.label = 5;
388
- case 5:
389
- if (!(i < config.clients)) return [3 /*break*/, 8];
390
- return [4 /*yield*/, UserModel.create({ admin: false, email: "load-client-".concat(i, "@example.com") })];
391
- case 6:
392
- user = _w.sent();
393
- users.push(user);
394
- _w.label = 7;
395
- case 7:
396
- i++;
397
- return [3 /*break*/, 5];
398
- case 8:
399
- for (i = 0; i < config.clients; i++) {
400
- harnessClients.push(makeHarnessClient({ baseUrl: baseUrl, name: "load-client-".concat(i), user: users[i] }));
232
+ const main = async () => {
233
+ const config = parseFlags(process.argv.slice(2));
234
+ logger_1.logger.info("[loadHarness] starting", config);
235
+ await mongoose_1.default.connect(config.mongoUri);
236
+ await Promise.all([
237
+ LoadTodoModel.collection.deleteMany({}),
238
+ mongoose_1.default.connection.db?.collection("syncmutations").deleteMany({}),
239
+ mongoose_1.default.connection.db?.collection("synccounters").deleteMany({}),
240
+ ]);
241
+ const { httpServer, realtimeApp, baseUrl } = await buildRig(config);
242
+ let exitCode = 0;
243
+ const harnessClients = [];
244
+ try {
245
+ // ── N users, one owner stream each ──────────────────────────────────────
246
+ const UserModel = mongoose_1.default.models.LoadHarnessUser;
247
+ const users = [];
248
+ for (let i = 0; i < config.clients; i++) {
249
+ const user = await UserModel.create({ admin: false, email: `load-client-${i}@example.com` });
250
+ users.push(user);
251
+ }
252
+ for (let i = 0; i < config.clients; i++) {
253
+ harnessClients.push(makeHarnessClient({ baseUrl, name: `load-client-${i}`, user: users[i] }));
254
+ }
255
+ // ── Start all clients, wait for online ──────────────────────────────────
256
+ await Promise.all(harnessClients.map((hc) => hc.client.start()));
257
+ await waitFor(() => harnessClients.every((hc) => hc.client.getSyncStatus().isOnline), {
258
+ label: "all clients online",
259
+ timeoutMs: 30_000,
260
+ });
261
+ logger_1.logger.info(`[loadHarness] ${harnessClients.length} clients online`);
262
+ // ── Seed docs round-robin across owners; measure bootstrap wall time ────
263
+ const perOwnerCount = new Map();
264
+ const seeds = Array.from({ length: config.seedDocs }, (_, i) => {
265
+ const owner = harnessClients[i % harnessClients.length];
266
+ perOwnerCount.set(owner.ownerId, (perOwnerCount.get(owner.ownerId) ?? 0) + 1);
267
+ return { ownerId: owner.ownerId, title: `seed-${i}` };
268
+ });
269
+ const bootstrapStart = luxon_1.DateTime.now().toMillis();
270
+ if (seeds.length > 0) {
271
+ await LoadTodoModel.insertMany(seeds);
272
+ }
273
+ await waitFor(() => harnessClients.every((hc) => {
274
+ const expected = perOwnerCount.get(hc.ownerId) ?? 0;
275
+ return hc.client.store.listEntities({ collection: COLLECTION }).length >= expected;
276
+ }), { label: `bootstrap convergence at ${config.seedDocs} docs`, timeoutMs: 120_000 });
277
+ const bootstrapWallMs = luxon_1.DateTime.now().toMillis() - bootstrapStart;
278
+ logger_1.logger.info(`[loadHarness] bootstrap converged in ${bootstrapWallMs}ms`);
279
+ // ── Driven mutation load ─────────────────────────────────────────────────
280
+ const mutateLatenciesMs = [];
281
+ const fanoutLagsMs = [];
282
+ let conflictCount = 0;
283
+ let ackCount = 0;
284
+ let nackCount = 0;
285
+ let duplicateCount = 0;
286
+ /** Poll the outbox for a mutation to reach a terminal status, recording latency. */
287
+ const trackMutation = async (hc, mutationId, startedAt) => {
288
+ try {
289
+ await waitFor(() => {
290
+ const mutation = hc.client.outbox.getMutation({ mutationId });
291
+ return (mutation === undefined ||
292
+ mutation.status === "acked" ||
293
+ mutation.status === "conflicted" ||
294
+ mutation.status === "failed");
295
+ }, { intervalMs: 8, label: `mutation ${mutationId} terminal`, timeoutMs: 15_000 });
296
+ mutateLatenciesMs.push(luxon_1.DateTime.now().toMillis() - startedAt);
297
+ const mutation = hc.client.outbox.getMutation({ mutationId });
298
+ if (mutation?.status === "conflicted") {
299
+ conflictCount += 1;
401
300
  }
402
- // ── Start all clients, wait for online ──────────────────────────────────
403
- return [4 /*yield*/, Promise.all(harnessClients.map(function (hc) { return hc.client.start(); }))];
404
- case 9:
405
- // ── Start all clients, wait for online ──────────────────────────────────
406
- _w.sent();
407
- return [4 /*yield*/, waitFor(function () { return harnessClients.every(function (hc) { return hc.client.getSyncStatus().isOnline; }); }, {
408
- label: "all clients online",
409
- timeoutMs: 30000,
410
- })];
411
- case 10:
412
- _w.sent();
413
- logger_1.logger.info("[loadHarness] ".concat(harnessClients.length, " clients online"));
414
- perOwnerCount_1 = new Map();
415
- seeds = Array.from({ length: config.seedDocs }, function (_, i) {
416
- var _a;
417
- var owner = harnessClients[i % harnessClients.length];
418
- perOwnerCount_1.set(owner.ownerId, ((_a = perOwnerCount_1.get(owner.ownerId)) !== null && _a !== void 0 ? _a : 0) + 1);
419
- return { ownerId: owner.ownerId, title: "seed-".concat(i) };
420
- });
421
- bootstrapStart = luxon_1.DateTime.now().toMillis();
422
- if (!(seeds.length > 0)) return [3 /*break*/, 12];
423
- return [4 /*yield*/, LoadTodoModel.insertMany(seeds)];
424
- case 11:
425
- _w.sent();
426
- _w.label = 12;
427
- case 12: return [4 /*yield*/, waitFor(function () {
428
- return harnessClients.every(function (hc) {
429
- var _a;
430
- var expected = (_a = perOwnerCount_1.get(hc.ownerId)) !== null && _a !== void 0 ? _a : 0;
431
- return hc.client.store.listEntities({ collection: COLLECTION }).length >= expected;
432
- });
433
- }, { label: "bootstrap convergence at ".concat(config.seedDocs, " docs"), timeoutMs: 120000 })];
434
- case 13:
435
- _w.sent();
436
- bootstrapWallMs = luxon_1.DateTime.now().toMillis() - bootstrapStart;
437
- logger_1.logger.info("[loadHarness] bootstrap converged in ".concat(bootstrapWallMs, "ms"));
438
- mutateLatenciesMs_1 = [];
439
- fanoutLagsMs_1 = [];
440
- conflictCount_1 = 0;
441
- ackCount_1 = 0;
442
- nackCount_1 = 0;
443
- duplicateCount_1 = 0;
444
- trackMutation = function (hc, mutationId, startedAt) { return __awaiter(void 0, void 0, void 0, function () {
445
- var mutation, _a;
446
- return __generator(this, function (_b) {
447
- switch (_b.label) {
448
- case 0:
449
- _b.trys.push([0, 2, , 3]);
450
- return [4 /*yield*/, waitFor(function () {
451
- var mutation = hc.client.outbox.getMutation({ mutationId: mutationId });
452
- return (mutation === undefined ||
453
- mutation.status === "acked" ||
454
- mutation.status === "conflicted" ||
455
- mutation.status === "failed");
456
- }, { intervalMs: 8, label: "mutation ".concat(mutationId, " terminal"), timeoutMs: 15000 })];
457
- case 1:
458
- _b.sent();
459
- mutateLatenciesMs_1.push(luxon_1.DateTime.now().toMillis() - startedAt);
460
- mutation = hc.client.outbox.getMutation({ mutationId: mutationId });
461
- if ((mutation === null || mutation === void 0 ? void 0 : mutation.status) === "conflicted") {
462
- conflictCount_1 += 1;
463
- }
464
- else if ((mutation === null || mutation === void 0 ? void 0 : mutation.status) === "failed") {
465
- nackCount_1 += 1;
466
- }
467
- else {
468
- ackCount_1 += 1;
469
- }
470
- return [3 /*break*/, 3];
471
- case 2:
472
- _a = _b.sent();
473
- // Timed out waiting; still record whatever elapsed so the report reflects it.
474
- mutateLatenciesMs_1.push(luxon_1.DateTime.now().toMillis() - startedAt);
475
- return [3 /*break*/, 3];
476
- case 3: return [2 /*return*/];
477
- }
478
- });
479
- }); };
480
- randomClient = function () {
481
- return harnessClients[Math.floor(Math.random() * harnessClients.length)];
482
- };
483
- knownEntityIds = [];
484
- try {
485
- for (_b = __values(harnessClients.entries()), _c = _b.next(); !_c.done; _c = _b.next()) {
486
- _d = __read(_c.value, 2), i = _d[0], hc = _d[1];
487
- try {
488
- for (_e = (e_5 = void 0, __values(hc.client.store.listEntities({ collection: COLLECTION }))), _f = _e.next(); !_f.done; _f = _e.next()) {
489
- entity = _f.value;
490
- knownEntityIds.push({ clientIndex: i, id: entity.id });
491
- }
492
- }
493
- catch (e_5_1) { e_5 = { error: e_5_1 }; }
494
- finally {
495
- try {
496
- if (_f && !_f.done && (_l = _e.return)) _l.call(_e);
497
- }
498
- finally { if (e_5) throw e_5.error; }
499
- }
500
- }
301
+ else if (mutation?.status === "failed") {
302
+ nackCount += 1;
501
303
  }
502
- catch (e_4_1) { e_4 = { error: e_4_1 }; }
503
- finally {
504
- try {
505
- if (_c && !_c.done && (_k = _b.return)) _k.call(_b);
506
- }
507
- finally { if (e_4) throw e_4.error; }
304
+ else {
305
+ ackCount += 1;
508
306
  }
509
- loadPromises = [];
510
- intervalMs_1 = 1000 / config.targetRate;
511
- loadEnd = luxon_1.DateTime.now().plus({ seconds: config.durationSec }).toMillis();
512
- _loop_1 = function () {
513
- var hc, opRoll, startedAt, mutationId, target, owner_1, startedAt, mutationId, dupRequest_1, idx, target, owner, startedAt, mutationId, anyOwner, writeStart_1, doc, id_1;
514
- return __generator(this, function (_x) {
515
- switch (_x.label) {
516
- case 0:
517
- hc = randomClient();
518
- opRoll = Math.random();
519
- if (opRoll < 0.5 || knownEntityIds.length === 0) {
520
- startedAt = luxon_1.DateTime.now().toMillis();
521
- mutationId = hc.client.mutate({
522
- collection: COLLECTION,
523
- data: {
524
- title: "load-".concat(luxon_1.DateTime.now().toMillis(), "-").concat(Math.random().toString(36).slice(2, 8)),
525
- },
526
- operation: "create",
527
- }).mutationId;
528
- loadPromises.push(trackMutation(hc, mutationId, startedAt));
529
- }
530
- else if (opRoll < 0.85) {
531
- target = knownEntityIds[Math.floor(Math.random() * knownEntityIds.length)];
532
- owner_1 = harnessClients[target.clientIndex];
533
- startedAt = luxon_1.DateTime.now().toMillis();
534
- mutationId = owner_1.client.mutate({
535
- collection: COLLECTION,
536
- data: { title: "updated-".concat(luxon_1.DateTime.now().toMillis()) },
537
- id: target.id,
538
- operation: "update",
539
- }).mutationId;
540
- loadPromises.push(trackMutation(owner_1, mutationId, startedAt));
541
- // Deliberate mid-batch conflict: race a second, server-side write against the
542
- // SAME entity underneath this client's just-queued optimistic edit, mirroring
543
- // integration.test.ts's 4a/4b conflict scenarios (server moves on while the
544
- // client's mutation is still in flight/queued).
545
- if (Math.random() < 0.1) {
546
- void LoadTodoModel.findById(target.id)
547
- .then(function (doc) {
548
- if (!doc) {
549
- return;
550
- }
551
- doc.title = "server-race-".concat(luxon_1.DateTime.now().toMillis());
552
- return doc.save();
553
- })
554
- .catch(function () { });
555
- }
556
- // Deliberate duplicate mutationId resend: replay the exact same request via the
557
- // lower-level httpChannel.sendMutation (mutate() always mints a fresh id, so a
558
- // real duplicate delivery must go through the transport-level API directly, per
559
- // integration.test.ts test "5.").
560
- if (Math.random() < 0.05) {
561
- dupRequest_1 = {
562
- collection: COLLECTION,
563
- data: { title: "dup-".concat(luxon_1.DateTime.now().toMillis()) },
564
- mutationId: "load-dup-".concat(luxon_1.DateTime.now().toMillis(), "-").concat(Math.random()
565
- .toString(36)
566
- .slice(2, 8)),
567
- operation: "create",
568
- };
569
- loadPromises.push(owner_1.httpChannel
570
- .sendMutation(dupRequest_1)
571
- .then(function () { return owner_1.httpChannel.sendMutation(dupRequest_1); })
572
- .then(function () {
573
- duplicateCount_1 += 1;
574
- })
575
- .catch(function () { }));
576
- }
577
- }
578
- else {
579
- idx = Math.floor(Math.random() * knownEntityIds.length);
580
- target = knownEntityIds[idx];
581
- owner = harnessClients[target.clientIndex];
582
- startedAt = luxon_1.DateTime.now().toMillis();
583
- mutationId = owner.client.mutate({
584
- collection: COLLECTION,
585
- id: target.id,
586
- operation: "delete",
587
- }).mutationId;
588
- loadPromises.push(trackMutation(owner, mutationId, startedAt));
589
- knownEntityIds.splice(idx, 1);
590
- }
591
- if (!(Math.random() < 0.02)) return [3 /*break*/, 2];
592
- anyOwner = randomClient();
593
- writeStart_1 = luxon_1.DateTime.now().toMillis();
594
- return [4 /*yield*/, LoadTodoModel.create({
595
- ownerId: anyOwner.ownerId,
596
- title: "fanout-".concat(writeStart_1),
597
- })];
598
- case 1:
599
- doc = _x.sent();
600
- id_1 = String(doc._id);
601
- knownEntityIds.push({ clientIndex: harnessClients.indexOf(anyOwner), id: id_1 });
602
- loadPromises.push(waitFor(function () {
603
- return harnessClients.every(function (hc2) { return hc2.client.store.getEntity({ collection: COLLECTION, id: id_1 }) !== undefined; });
604
- }, {
605
- intervalMs: 8,
606
- label: "fanout delta for ".concat(id_1),
607
- timeoutMs: 15000,
608
- })
609
- .then(function () {
610
- fanoutLagsMs_1.push(luxon_1.DateTime.now().toMillis() - writeStart_1);
611
- })
612
- .catch(function () { }));
613
- _x.label = 2;
614
- case 2: return [4 /*yield*/, new Promise(function (resolve) { return setTimeout(resolve, intervalMs_1); })];
615
- case 3:
616
- _x.sent();
617
- return [2 /*return*/];
618
- }
619
- });
620
- };
621
- _w.label = 14;
622
- case 14:
623
- if (!(luxon_1.DateTime.now().toMillis() < loadEnd)) return [3 /*break*/, 16];
624
- return [5 /*yield**/, _loop_1()];
625
- case 15:
626
- _w.sent();
627
- return [3 /*break*/, 14];
628
- case 16: return [4 /*yield*/, Promise.all(loadPromises)];
629
- case 17:
630
- _w.sent();
631
- try {
632
- // Resolve any conflicts left over from the deliberate server-race scenario the load
633
- // phase injects (useServer: the canonical server doc wins) — exactly what a real
634
- // client eventually does, either via user action or an auto-resolve policy. Without
635
- // this, a conflicted mutation sits in the outbox forever and both `queuedCount` and
636
- // the final convergence check would spuriously never settle.
637
- for (harnessClients_1 = __values(harnessClients), harnessClients_1_1 = harnessClients_1.next(); !harnessClients_1_1.done; harnessClients_1_1 = harnessClients_1.next()) {
638
- hc = harnessClients_1_1.value;
639
- try {
640
- for (_g = (e_7 = void 0, __values((0, syncdb_1.listConflicts)({ store: hc.client.store }))), _h = _g.next(); !_h.done; _h = _g.next()) {
641
- conflict = _h.value;
642
- hc.client.resolveConflict({ mutationId: conflict.mutationId, strategy: "useServer" });
643
- }
644
- }
645
- catch (e_7_1) { e_7 = { error: e_7_1 }; }
646
- finally {
647
- try {
648
- if (_h && !_h.done && (_o = _g.return)) _o.call(_g);
649
- }
650
- finally { if (e_7) throw e_7.error; }
307
+ }
308
+ catch {
309
+ // Timed out waiting; still record whatever elapsed so the report reflects it.
310
+ mutateLatenciesMs.push(luxon_1.DateTime.now().toMillis() - startedAt);
311
+ }
312
+ };
313
+ const randomClient = () => harnessClients[Math.floor(Math.random() * harnessClients.length)];
314
+ const knownEntityIds = [];
315
+ for (const [i, hc] of harnessClients.entries()) {
316
+ for (const entity of hc.client.store.listEntities({ collection: COLLECTION })) {
317
+ knownEntityIds.push({ clientIndex: i, id: entity.id });
318
+ }
319
+ }
320
+ const loadPromises = [];
321
+ const intervalMs = 1000 / config.targetRate;
322
+ const loadEnd = luxon_1.DateTime.now().plus({ seconds: config.durationSec }).toMillis();
323
+ while (luxon_1.DateTime.now().toMillis() < loadEnd) {
324
+ const hc = randomClient();
325
+ const opRoll = Math.random();
326
+ if (opRoll < 0.5 || knownEntityIds.length === 0) {
327
+ // Create.
328
+ const startedAt = luxon_1.DateTime.now().toMillis();
329
+ const { mutationId } = hc.client.mutate({
330
+ collection: COLLECTION,
331
+ data: {
332
+ title: `load-${luxon_1.DateTime.now().toMillis()}-${Math.random().toString(36).slice(2, 8)}`,
333
+ },
334
+ operation: "create",
335
+ });
336
+ loadPromises.push(trackMutation(hc, mutationId, startedAt));
337
+ }
338
+ else if (opRoll < 0.85) {
339
+ // Update.
340
+ const target = knownEntityIds[Math.floor(Math.random() * knownEntityIds.length)];
341
+ const owner = harnessClients[target.clientIndex];
342
+ const startedAt = luxon_1.DateTime.now().toMillis();
343
+ const { mutationId } = owner.client.mutate({
344
+ collection: COLLECTION,
345
+ data: { title: `updated-${luxon_1.DateTime.now().toMillis()}` },
346
+ id: target.id,
347
+ operation: "update",
348
+ });
349
+ loadPromises.push(trackMutation(owner, mutationId, startedAt));
350
+ // Deliberate mid-batch conflict: race a second, server-side write against the
351
+ // SAME entity underneath this client's just-queued optimistic edit, mirroring
352
+ // integration.test.ts's 4a/4b conflict scenarios (server moves on while the
353
+ // client's mutation is still in flight/queued).
354
+ if (Math.random() < 0.1) {
355
+ void LoadTodoModel.findById(target.id)
356
+ .then((doc) => {
357
+ if (!doc) {
358
+ return;
651
359
  }
652
- }
360
+ doc.title = `server-race-${luxon_1.DateTime.now().toMillis()}`;
361
+ return doc.save();
362
+ })
363
+ .catch(() => { });
653
364
  }
654
- catch (e_6_1) { e_6 = { error: e_6_1 }; }
655
- finally {
656
- try {
657
- if (harnessClients_1_1 && !harnessClients_1_1.done && (_m = harnessClients_1.return)) _m.call(harnessClients_1);
658
- }
659
- finally { if (e_6) throw e_6.error; }
365
+ // Deliberate duplicate mutationId resend: replay the exact same request via the
366
+ // lower-level httpChannel.sendMutation (mutate() always mints a fresh id, so a
367
+ // real duplicate delivery must go through the transport-level API directly, per
368
+ // integration.test.ts test "5.").
369
+ if (Math.random() < 0.05) {
370
+ const dupRequest = {
371
+ collection: COLLECTION,
372
+ data: { title: `dup-${luxon_1.DateTime.now().toMillis()}` },
373
+ mutationId: `load-dup-${luxon_1.DateTime.now().toMillis()}-${Math.random()
374
+ .toString(36)
375
+ .slice(2, 8)}`,
376
+ operation: "create",
377
+ };
378
+ loadPromises.push(owner.httpChannel
379
+ .sendMutation(dupRequest)
380
+ .then(() => owner.httpChannel.sendMutation(dupRequest))
381
+ .then(() => {
382
+ duplicateCount += 1;
383
+ })
384
+ .catch(() => { }));
660
385
  }
661
- // Drain any outstanding queued mutations before checking convergence.
662
- return [4 /*yield*/, waitFor(function () { return harnessClients.every(function (hc) { return hc.client.getSyncStatus().queuedCount === 0; }); }, {
663
- label: "all clients drained",
664
- timeoutMs: 60000,
665
- }).catch(function (error) {
666
- logger_1.logger.warn("[loadHarness] drain wait: ".concat(String(error)));
667
- })];
668
- case 18:
669
- // Drain any outstanding queued mutations before checking convergence.
670
- _w.sent();
671
- convergenceFailures = 0;
672
- _w.label = 19;
673
- case 19:
674
- _w.trys.push([19, 24, 25, 26]);
675
- harnessClients_2 = __values(harnessClients), harnessClients_2_1 = harnessClients_2.next();
676
- _w.label = 20;
677
- case 20:
678
- if (!!harnessClients_2_1.done) return [3 /*break*/, 23];
679
- hc = harnessClients_2_1.value;
680
- localEntities = new Map(hc.client.store
681
- .listEntities({ collection: COLLECTION })
682
- .map(function (entity) { return [entity.id, { data: entity.data, seq: entity.seq }]; }));
683
- return [4 /*yield*/, LoadTodoModel.find({ deleted: { $ne: true }, ownerId: hc.ownerId })];
684
- case 21:
685
- serverDocs = _w.sent();
686
- serverMap = new Map(serverDocs.map(function (doc) {
687
- var _a;
688
- return [
689
- String(doc._id),
690
- { seq: (_a = doc._syncSeq) !== null && _a !== void 0 ? _a : 0, title: doc.title },
691
- ];
692
- }));
693
- matches = localEntities.size === serverMap.size;
694
- if (matches) {
695
- try {
696
- for (localEntities_1 = (e_8 = void 0, __values(localEntities)), localEntities_1_1 = localEntities_1.next(); !localEntities_1_1.done; localEntities_1_1 = localEntities_1.next()) {
697
- _j = __read(localEntities_1_1.value, 2), id = _j[0], local = _j[1];
698
- server = serverMap.get(id);
699
- localData = local.data;
700
- if (!server || server.seq !== local.seq || server.title !== (localData === null || localData === void 0 ? void 0 : localData.title)) {
701
- matches = false;
702
- break;
703
- }
704
- }
705
- }
706
- catch (e_8_1) { e_8 = { error: e_8_1 }; }
707
- finally {
708
- try {
709
- if (localEntities_1_1 && !localEntities_1_1.done && (_q = localEntities_1.return)) _q.call(localEntities_1);
710
- }
711
- finally { if (e_8) throw e_8.error; }
386
+ }
387
+ else {
388
+ // Delete.
389
+ const idx = Math.floor(Math.random() * knownEntityIds.length);
390
+ const target = knownEntityIds[idx];
391
+ const owner = harnessClients[target.clientIndex];
392
+ const startedAt = luxon_1.DateTime.now().toMillis();
393
+ const { mutationId } = owner.client.mutate({
394
+ collection: COLLECTION,
395
+ id: target.id,
396
+ operation: "delete",
397
+ });
398
+ loadPromises.push(trackMutation(owner, mutationId, startedAt));
399
+ knownEntityIds.splice(idx, 1);
400
+ }
401
+ // ── Fan-out lag sample: an out-of-band server write, measured against every
402
+ // connected client's local store reflecting it ─────────────────────────────
403
+ if (Math.random() < 0.02) {
404
+ const anyOwner = randomClient();
405
+ const writeStart = luxon_1.DateTime.now().toMillis();
406
+ const doc = await LoadTodoModel.create({
407
+ ownerId: anyOwner.ownerId,
408
+ title: `fanout-${writeStart}`,
409
+ });
410
+ const id = String(doc._id);
411
+ knownEntityIds.push({ clientIndex: harnessClients.indexOf(anyOwner), id });
412
+ loadPromises.push(waitFor(() => harnessClients.every((hc2) => hc2.client.store.getEntity({ collection: COLLECTION, id }) !== undefined), {
413
+ intervalMs: 8,
414
+ label: `fanout delta for ${id}`,
415
+ timeoutMs: 15_000,
416
+ })
417
+ .then(() => {
418
+ fanoutLagsMs.push(luxon_1.DateTime.now().toMillis() - writeStart);
419
+ })
420
+ .catch(() => { }));
421
+ }
422
+ await new Promise((resolve) => setTimeout(resolve, intervalMs));
423
+ }
424
+ await Promise.all(loadPromises);
425
+ // Resolve any conflicts left over from the deliberate server-race scenario the load
426
+ // phase injects (useServer: the canonical server doc wins) — exactly what a real
427
+ // client eventually does, either via user action or an auto-resolve policy. Without
428
+ // this, a conflicted mutation sits in the outbox forever and both `queuedCount` and
429
+ // the final convergence check would spuriously never settle.
430
+ for (const hc of harnessClients) {
431
+ for (const conflict of (0, syncdb_1.listConflicts)({ store: hc.client.store })) {
432
+ hc.client.resolveConflict({ mutationId: conflict.mutationId, strategy: "useServer" });
433
+ }
434
+ }
435
+ // Drain any outstanding queued mutations before checking convergence.
436
+ await waitFor(() => harnessClients.every((hc) => hc.client.getSyncStatus().queuedCount === 0), {
437
+ label: "all clients drained",
438
+ timeoutMs: 60_000,
439
+ }).catch((error) => {
440
+ logger_1.logger.warn(`[loadHarness] drain wait: ${String(error)}`);
441
+ });
442
+ // ── Final-state convergence check ───────────────────────────────────────
443
+ let convergenceFailures = 0;
444
+ for (const hc of harnessClients) {
445
+ const localEntities = new Map(hc.client.store
446
+ .listEntities({ collection: COLLECTION })
447
+ .map((entity) => [entity.id, { data: entity.data, seq: entity.seq }]));
448
+ const serverDocs = await LoadTodoModel.find({ deleted: { $ne: true }, ownerId: hc.ownerId });
449
+ const serverMap = new Map(serverDocs.map((doc) => [
450
+ String(doc._id),
451
+ { seq: doc._syncSeq ?? 0, title: doc.title },
452
+ ]));
453
+ let matches = localEntities.size === serverMap.size;
454
+ if (matches) {
455
+ for (const [id, local] of localEntities) {
456
+ const server = serverMap.get(id);
457
+ const localData = local.data;
458
+ if (!server || server.seq !== local.seq || server.title !== localData?.title) {
459
+ matches = false;
460
+ break;
712
461
  }
713
462
  }
714
- if (!matches) {
715
- convergenceFailures += 1;
716
- }
717
- logger_1.logger.info("[loadHarness] convergence ".concat(matches ? "PASS" : "FAIL", " for ").concat(hc.name, " (local=").concat(localEntities.size, ", server=").concat(serverMap.size, ")"));
718
- _w.label = 22;
719
- case 22:
720
- harnessClients_2_1 = harnessClients_2.next();
721
- return [3 /*break*/, 20];
722
- case 23: return [3 /*break*/, 26];
723
- case 24:
724
- e_2_1 = _w.sent();
725
- e_2 = { error: e_2_1 };
726
- return [3 /*break*/, 26];
727
- case 25:
728
- try {
729
- if (harnessClients_2_1 && !harnessClients_2_1.done && (_p = harnessClients_2.return)) _p.call(harnessClients_2);
730
- }
731
- finally { if (e_2) throw e_2.error; }
732
- return [7 /*endfinally*/];
733
- case 26:
734
- report = [
735
- "",
736
- "==================== SyncDB Load Harness Report ====================",
737
- "clients=".concat(config.clients, " seedDocs=").concat(config.seedDocs, " targetRate=").concat(config.targetRate, "/s durationSec=").concat(config.durationSec),
738
- "",
739
- "Bootstrap wall time @ ".concat(config.seedDocs, " docs: ").concat(bootstrapWallMs, "ms"),
740
- "",
741
- "Mutate round-trip latency (ms):",
742
- " p50=".concat(percentile(mutateLatenciesMs_1, 50).toFixed(1), " p95=").concat(percentile(mutateLatenciesMs_1, 95).toFixed(1), " p99=").concat(percentile(mutateLatenciesMs_1, 99).toFixed(1), " (n=").concat(mutateLatenciesMs_1.length, ")"),
743
- " acked=".concat(ackCount_1, " conflicted=").concat(conflictCount_1, " failed=").concat(nackCount_1, " duplicateResends=").concat(duplicateCount_1),
744
- "",
745
- "Change-stream -> sync:delta fan-out lag across all sockets (ms):",
746
- fanoutLagsMs_1.length > 0
747
- ? " min=".concat(Math.min.apply(Math, __spreadArray([], __read(fanoutLagsMs_1), false)).toFixed(1), " p50=").concat(percentile(fanoutLagsMs_1, 50).toFixed(1), " p95=").concat(percentile(fanoutLagsMs_1, 95).toFixed(1), " max=").concat(Math.max.apply(Math, __spreadArray([], __read(fanoutLagsMs_1), false)).toFixed(1), " (n=").concat(fanoutLagsMs_1.length, ")")
748
- : " (no samples collected)",
749
- "",
750
- "Final-state convergence: ".concat(harnessClients.length - convergenceFailures, "/").concat(harnessClients.length, " clients PASS"),
751
- "======================================================================",
752
- "",
753
- ].join("\n");
754
- // Deliberately plain stdout output for a load report — not a structured log line.
755
- process.stdout.write(report);
756
- if (convergenceFailures > 0) {
757
- exitCode = 1;
758
- }
759
- return [3 /*break*/, 39];
760
- case 27:
761
- error_1 = _w.sent();
762
- logger_1.logger.error("[loadHarness] fatal error: ".concat(String(error_1)));
763
- exitCode = 1;
764
- return [3 /*break*/, 39];
765
- case 28:
766
- _w.trys.push([28, 33, 34, 35]);
767
- harnessClients_3 = __values(harnessClients), harnessClients_3_1 = harnessClients_3.next();
768
- _w.label = 29;
769
- case 29:
770
- if (!!harnessClients_3_1.done) return [3 /*break*/, 32];
771
- hc = harnessClients_3_1.value;
772
- return [4 /*yield*/, hc.client.stop().catch(function () { })];
773
- case 30:
774
- _w.sent();
775
- _w.label = 31;
776
- case 31:
777
- harnessClients_3_1 = harnessClients_3.next();
778
- return [3 /*break*/, 29];
779
- case 32: return [3 /*break*/, 35];
780
- case 33:
781
- e_3_1 = _w.sent();
782
- e_3 = { error: e_3_1 };
783
- return [3 /*break*/, 35];
784
- case 34:
785
- try {
786
- if (harnessClients_3_1 && !harnessClients_3_1.done && (_r = harnessClients_3.return)) _r.call(harnessClients_3);
787
- }
788
- finally { if (e_3) throw e_3.error; }
789
- return [7 /*endfinally*/];
790
- case 35:
791
- (_u = realtimeApp.getIo()) === null || _u === void 0 ? void 0 : _u.disconnectSockets(true);
792
- (_v = httpServer.closeAllConnections) === null || _v === void 0 ? void 0 : _v.call(httpServer);
793
- return [4 /*yield*/, realtimeApp.close().catch(function () { })];
794
- case 36:
795
- _w.sent();
796
- return [4 /*yield*/, new Promise(function (resolve) {
797
- httpServer.close(function () { return resolve(); });
798
- })];
799
- case 37:
800
- _w.sent();
801
- (0, registry_1.clearSyncRegistry)();
802
- return [4 /*yield*/, mongoose_1.default.disconnect()];
803
- case 38:
804
- _w.sent();
805
- return [7 /*endfinally*/];
806
- case 39:
807
- process.exit(exitCode);
808
- return [2 /*return*/];
463
+ }
464
+ if (!matches) {
465
+ convergenceFailures += 1;
466
+ }
467
+ logger_1.logger.info(`[loadHarness] convergence ${matches ? "PASS" : "FAIL"} for ${hc.name} (local=${localEntities.size}, server=${serverMap.size})`);
809
468
  }
810
- });
811
- }); };
812
- main().catch(function (error) {
813
- logger_1.logger.error("[loadHarness] unhandled error: ".concat(String(error)));
469
+ // ── Report ───────────────────────────────────────────────────────────────
470
+ const report = [
471
+ "",
472
+ "==================== SyncDB Load Harness Report ====================",
473
+ `clients=${config.clients} seedDocs=${config.seedDocs} targetRate=${config.targetRate}/s durationSec=${config.durationSec}`,
474
+ "",
475
+ `Bootstrap wall time @ ${config.seedDocs} docs: ${bootstrapWallMs}ms`,
476
+ "",
477
+ "Mutate round-trip latency (ms):",
478
+ ` p50=${percentile(mutateLatenciesMs, 50).toFixed(1)} p95=${percentile(mutateLatenciesMs, 95).toFixed(1)} p99=${percentile(mutateLatenciesMs, 99).toFixed(1)} (n=${mutateLatenciesMs.length})`,
479
+ ` acked=${ackCount} conflicted=${conflictCount} failed=${nackCount} duplicateResends=${duplicateCount}`,
480
+ "",
481
+ "Change-stream -> sync:delta fan-out lag across all sockets (ms):",
482
+ fanoutLagsMs.length > 0
483
+ ? ` min=${Math.min(...fanoutLagsMs).toFixed(1)} p50=${percentile(fanoutLagsMs, 50).toFixed(1)} p95=${percentile(fanoutLagsMs, 95).toFixed(1)} max=${Math.max(...fanoutLagsMs).toFixed(1)} (n=${fanoutLagsMs.length})`
484
+ : " (no samples collected)",
485
+ "",
486
+ `Final-state convergence: ${harnessClients.length - convergenceFailures}/${harnessClients.length} clients PASS`,
487
+ "======================================================================",
488
+ "",
489
+ ].join("\n");
490
+ // Deliberately plain stdout output for a load report — not a structured log line.
491
+ process.stdout.write(report);
492
+ if (convergenceFailures > 0) {
493
+ exitCode = 1;
494
+ }
495
+ }
496
+ catch (error) {
497
+ logger_1.logger.error(`[loadHarness] fatal error: ${String(error)}`);
498
+ exitCode = 1;
499
+ }
500
+ finally {
501
+ for (const hc of harnessClients) {
502
+ await hc.client.stop().catch(() => { });
503
+ }
504
+ realtimeApp.getIo()?.disconnectSockets(true);
505
+ httpServer.closeAllConnections?.();
506
+ await realtimeApp.close().catch(() => { });
507
+ await new Promise((resolve) => {
508
+ httpServer.close(() => resolve());
509
+ });
510
+ (0, registry_1.clearSyncRegistry)();
511
+ await mongoose_1.default.disconnect();
512
+ }
513
+ process.exit(exitCode);
514
+ };
515
+ main().catch((error) => {
516
+ logger_1.logger.error(`[loadHarness] unhandled error: ${String(error)}`);
814
517
  process.exit(1);
815
518
  });