@capybara-hq/kernel 0.1.0-rc.105 → 0.1.0-rc.107

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 (359) hide show
  1. package/dist/admin/admin.schemas.d.ts +3 -0
  2. package/dist/agents/agents.schemas.d.ts +9 -9
  3. package/dist/{schedules/schedules.controller.d.ts → automations/automations.controller.d.ts} +37 -32
  4. package/dist/{schedules/schedules.controller.js → automations/automations.controller.js} +68 -57
  5. package/dist/automations/automations.module.d.ts +16 -0
  6. package/dist/{schedules/schedules.module.js → automations/automations.module.js} +18 -15
  7. package/dist/{schedules/schedules.schemas.d.ts → automations/automations.schemas.d.ts} +151 -50
  8. package/dist/automations/automations.schemas.js +253 -0
  9. package/dist/{schedules/scheduled-tasks.service.d.ts → automations/automations.service.d.ts} +99 -52
  10. package/dist/{schedules/scheduled-tasks.service.js → automations/automations.service.js} +303 -134
  11. package/dist/{schedules → automations}/calendar.d.ts +8 -8
  12. package/dist/{schedules → automations}/calendar.js +2 -2
  13. package/dist/automations/effective-settings.d.ts +28 -0
  14. package/dist/automations/effective-settings.js +25 -0
  15. package/dist/automations/errors.d.ts +19 -0
  16. package/dist/automations/errors.js +19 -0
  17. package/dist/automations/events/coalesce.d.ts +28 -0
  18. package/dist/automations/events/coalesce.js +131 -0
  19. package/dist/automations/events/deadline.d.ts +10 -0
  20. package/dist/automations/events/deadline.js +24 -0
  21. package/dist/automations/events/dispatcher.d.ts +74 -0
  22. package/dist/automations/events/dispatcher.js +353 -0
  23. package/dist/automations/events/events.module.d.ts +7 -0
  24. package/dist/automations/events/events.module.js +26 -0
  25. package/dist/automations/events/guards.d.ts +32 -0
  26. package/dist/automations/events/guards.js +87 -0
  27. package/dist/automations/events/sweep.job.d.ts +49 -0
  28. package/dist/automations/events/sweep.job.js +202 -0
  29. package/dist/automations/events/token.d.ts +5 -0
  30. package/dist/automations/events/token.js +5 -0
  31. package/dist/automations/events/trigger-events.service.d.ts +47 -0
  32. package/dist/automations/events/trigger-events.service.js +254 -0
  33. package/dist/{schedules → automations}/fire.d.ts +57 -17
  34. package/dist/{schedules → automations}/fire.js +311 -79
  35. package/dist/{schedules → automations}/grant-rules.d.ts +1 -1
  36. package/dist/{schedules → automations}/grant-rules.js +5 -5
  37. package/dist/automations/job-ids.d.ts +113 -0
  38. package/dist/automations/job-ids.js +117 -0
  39. package/dist/{schedules → automations}/pause.d.ts +3 -3
  40. package/dist/{schedules → automations}/pause.js +3 -3
  41. package/dist/{schedules → automations}/run-tracker.d.ts +21 -10
  42. package/dist/{schedules → automations}/run-tracker.js +68 -56
  43. package/dist/{schedules → automations}/scan.job.d.ts +12 -8
  44. package/dist/{schedules → automations}/scan.job.js +39 -23
  45. package/dist/{schedules → automations}/schedule-math.d.ts +19 -12
  46. package/dist/{schedules → automations}/schedule-math.js +17 -7
  47. package/dist/{schedules → automations}/store.d.ts +57 -27
  48. package/dist/{schedules → automations}/store.js +102 -52
  49. package/dist/automations/store.module.d.ts +6 -0
  50. package/dist/{schedules → automations}/store.module.js +9 -9
  51. package/dist/automations/types.d.ts +178 -0
  52. package/dist/{schedules → automations}/unattended.d.ts +22 -11
  53. package/dist/{schedules → automations}/unattended.js +53 -30
  54. package/dist/catalog/marketplaces.service.d.ts +1 -1
  55. package/dist/channels/channels.module.js +7 -6
  56. package/dist/channels/file-delivery.d.ts +26 -11
  57. package/dist/channels/file-delivery.js +32 -11
  58. package/dist/channels/outbound.d.ts +8 -8
  59. package/dist/channels/outbound.js +32 -30
  60. package/dist/channels/threads.d.ts +1 -1
  61. package/dist/channels/threads.js +1 -1
  62. package/dist/config/schema.d.ts +8 -1
  63. package/dist/config/schema.js +56 -6
  64. package/dist/conversations/approval-profile.d.ts +2 -2
  65. package/dist/conversations/approval-profile.js +3 -3
  66. package/dist/conversations/artifacts.d.ts +20 -17
  67. package/dist/conversations/artifacts.js +30 -37
  68. package/dist/conversations/attachments.controller.d.ts +6 -19
  69. package/dist/conversations/attachments.controller.js +8 -59
  70. package/dist/conversations/attachments.service.d.ts +30 -74
  71. package/dist/conversations/attachments.service.js +51 -193
  72. package/dist/conversations/conversations.controller.d.ts +7 -1
  73. package/dist/conversations/conversations.controller.js +26 -10
  74. package/dist/conversations/conversations.module.js +4 -0
  75. package/dist/conversations/conversations.service.d.ts +112 -35
  76. package/dist/conversations/conversations.service.js +160 -43
  77. package/dist/conversations/event-log.d.ts +1 -0
  78. package/dist/conversations/events.d.ts +95 -27
  79. package/dist/conversations/events.js +108 -10
  80. package/dist/conversations/files.d.ts +66 -64
  81. package/dist/conversations/files.js +127 -147
  82. package/dist/conversations/message-context.d.ts +2 -2
  83. package/dist/conversations/message-context.js +1 -1
  84. package/dist/conversations/permission-profile-store.d.ts +2 -1
  85. package/dist/conversations/permission-profiles.controller.d.ts +3 -0
  86. package/dist/conversations/permission-profiles.service.js +1 -1
  87. package/dist/conversations/prompt-suggestion-request.d.ts +1 -1
  88. package/dist/conversations/prompt-suggestion-request.js +4 -2
  89. package/dist/conversations/prompt-suggestions.d.ts +3 -3
  90. package/dist/conversations/prompt-suggestions.js +11 -10
  91. package/dist/conversations/queue.d.ts +7 -4
  92. package/dist/conversations/queue.js +6 -2
  93. package/dist/conversations/queue.service.d.ts +5 -5
  94. package/dist/conversations/queue.service.js +27 -16
  95. package/dist/ctx/create-ctx.d.ts +23 -2
  96. package/dist/ctx/create-ctx.js +78 -3
  97. package/dist/db/kernel-schema.d.ts +184 -27
  98. package/dist/devices/device-project-files.service.d.ts +88 -0
  99. package/dist/devices/device-project-files.service.js +249 -0
  100. package/dist/devices/device-projects.service.d.ts +40 -0
  101. package/dist/devices/device-projects.service.js +16 -13
  102. package/dist/devices/devices.controller.d.ts +9 -3
  103. package/dist/devices/devices.controller.js +27 -5
  104. package/dist/devices/devices.module.js +9 -1
  105. package/dist/devices/devices.schemas.js +6 -1
  106. package/dist/devices/dto.d.ts +15 -0
  107. package/dist/devices/dto.js +11 -0
  108. package/dist/devices/project-paths.d.ts +29 -0
  109. package/dist/devices/project-paths.js +66 -0
  110. package/dist/devices/project-rules.d.ts +5 -1
  111. package/dist/devices/project-rules.js +5 -1
  112. package/dist/errors.d.ts +53 -13
  113. package/dist/errors.js +53 -13
  114. package/dist/evals/canonical-json.d.ts +7 -0
  115. package/dist/evals/canonical-json.js +21 -0
  116. package/dist/evals/reconstruct.d.ts +10 -1
  117. package/dist/evals/reconstruct.js +20 -1
  118. package/dist/evals/recorded-tools.d.ts +0 -2
  119. package/dist/evals/recorded-tools.js +1 -16
  120. package/dist/evals/snapshot.d.ts +26 -3
  121. package/dist/evals/snapshot.js +110 -57
  122. package/dist/evals/worker.d.ts +4 -3
  123. package/dist/evals/worker.js +8 -4
  124. package/dist/extensions/host.d.ts +9 -2
  125. package/dist/extensions/host.js +12 -0
  126. package/dist/extensions/instance.d.ts +3 -1
  127. package/dist/extensions/instance.js +4 -0
  128. package/dist/extensions/ledger.d.ts +1 -1
  129. package/dist/extensions/permission-set.d.ts +17 -1
  130. package/dist/extensions/permission-set.js +13 -1
  131. package/dist/extensions/permission-view.d.ts +1 -1
  132. package/dist/extensions/permission-view.js +4 -1
  133. package/dist/files/blob-objects.d.ts +124 -0
  134. package/dist/files/blob-objects.js +341 -0
  135. package/dist/files/blob-sweep.job.d.ts +122 -0
  136. package/dist/files/blob-sweep.job.js +389 -0
  137. package/dist/files/blobs.service.d.ts +135 -0
  138. package/dist/files/blobs.service.js +300 -0
  139. package/dist/files/conversation-media.d.ts +41 -0
  140. package/dist/files/conversation-media.js +124 -0
  141. package/dist/files/deliveries.d.ts +64 -0
  142. package/dist/files/deliveries.js +156 -0
  143. package/dist/files/deliveries.module.d.ts +6 -0
  144. package/dist/files/deliveries.module.js +24 -0
  145. package/dist/files/draft-cleanup.job.d.ts +26 -0
  146. package/dist/files/draft-cleanup.job.js +93 -0
  147. package/dist/files/files.module.d.ts +1 -1
  148. package/dist/files/files.module.js +3 -2
  149. package/dist/files/hash-job.d.ts +127 -0
  150. package/dist/files/hash-job.js +447 -0
  151. package/dist/files/library-backfill.d.ts +63 -0
  152. package/dist/files/library-backfill.js +143 -0
  153. package/dist/files/library-files.service.d.ts +255 -0
  154. package/dist/files/library-files.service.js +883 -0
  155. package/dist/files/library-jobs.module.d.ts +8 -0
  156. package/dist/files/library-jobs.module.js +27 -0
  157. package/dist/files/library-query.d.ts +127 -0
  158. package/dist/files/library-query.js +322 -0
  159. package/dist/files/library-read.module.d.ts +9 -0
  160. package/dist/files/library-read.module.js +30 -0
  161. package/dist/files/library.controller.d.ts +77 -0
  162. package/dist/files/library.controller.js +235 -0
  163. package/dist/files/library.module.d.ts +9 -0
  164. package/dist/files/library.module.js +29 -0
  165. package/dist/files/library.schemas.d.ts +46 -0
  166. package/dist/files/library.schemas.js +49 -0
  167. package/dist/files/previewers.controller.d.ts +20 -0
  168. package/dist/files/previewers.controller.js +47 -0
  169. package/dist/files/previewers.d.ts +25 -11
  170. package/dist/files/previewers.js +43 -27
  171. package/dist/files/referenced-files.d.ts +150 -0
  172. package/dist/files/referenced-files.js +234 -0
  173. package/dist/git/gateway.js +2 -2
  174. package/dist/html/html-document.controller.d.ts +8 -1
  175. package/dist/html/html-document.controller.js +19 -1
  176. package/dist/html/html-document.service.d.ts +19 -4
  177. package/dist/html/html-document.service.js +43 -22
  178. package/dist/html/html-token.d.ts +10 -1
  179. package/dist/html/html-token.js +14 -0
  180. package/dist/html/html.module.js +8 -1
  181. package/dist/http/api.module.js +10 -5
  182. package/dist/http/request-signal.d.ts +8 -0
  183. package/dist/http/request-signal.js +14 -0
  184. package/dist/identity/settings.d.ts +26 -0
  185. package/dist/identity/settings.js +33 -2
  186. package/dist/inbox/inbox.module.js +2 -2
  187. package/dist/inbox/inbox.service.d.ts +8 -8
  188. package/dist/inbox/inbox.service.js +7 -7
  189. package/dist/infra/config/kernel-config.service.js +10 -5
  190. package/dist/infra/outbox/registry.d.ts +111 -2
  191. package/dist/infra/outbox/registry.js +104 -9
  192. package/dist/infra/throttler/named-throttlers.d.ts +2 -0
  193. package/dist/infra/throttler/named-throttlers.js +14 -0
  194. package/dist/kernel.module.js +3 -0
  195. package/dist/lifecycle/kernel-lifecycle.js +6 -0
  196. package/dist/models/purposes.js +1 -1
  197. package/dist/orgs/offboarding.js +1 -1
  198. package/dist/orgs/roles.d.ts +1 -1
  199. package/dist/orgs/roles.js +3 -3
  200. package/dist/orgs/settings.controller.d.ts +1 -1
  201. package/dist/orgs/settings.service.d.ts +75 -13
  202. package/dist/orgs/settings.service.js +104 -26
  203. package/dist/platform/exclusions.js +45 -8
  204. package/dist/platform/file-ref.d.ts +18 -3
  205. package/dist/platform/file-ref.js +22 -11
  206. package/dist/platform/operation.js +6 -2
  207. package/dist/platform/ops/admin.ops.js +5 -2
  208. package/dist/platform/ops/{schedules.ops.d.ts → automations.ops.d.ts} +4 -4
  209. package/dist/platform/ops/automations.ops.js +560 -0
  210. package/dist/platform/ops/devices.ops.d.ts +3 -1
  211. package/dist/platform/ops/devices.ops.js +77 -3
  212. package/dist/platform/ops/files.ops.d.ts +18 -0
  213. package/dist/platform/ops/files.ops.js +267 -0
  214. package/dist/platform/ops/inbox.ops.js +4 -4
  215. package/dist/platform/ops/org-settings.ops.js +6 -2
  216. package/dist/platform/ops/orgs.ops.js +2 -1
  217. package/dist/platform/ops/platform.ops.js +4 -4
  218. package/dist/platform/ops/shares.ops.js +2 -2
  219. package/dist/platform/platform-ops.module.d.ts +3 -2
  220. package/dist/platform/platform-ops.module.js +10 -5
  221. package/dist/platform/route-schemas.js +6 -3
  222. package/dist/push/jobs.d.ts +3 -3
  223. package/dist/push/jobs.js +2 -2
  224. package/dist/push/preferences.service.js +1 -1
  225. package/dist/push/push-owed.d.ts +3 -3
  226. package/dist/push/push-owed.js +6 -6
  227. package/dist/push/push.schemas.d.ts +4 -4
  228. package/dist/push/push.schemas.js +3 -3
  229. package/dist/push/recipients.d.ts +4 -4
  230. package/dist/push/recipients.js +23 -23
  231. package/dist/push/texts.d.ts +3 -3
  232. package/dist/push/texts.js +2 -2
  233. package/dist/push/triggers.d.ts +1 -1
  234. package/dist/roles/worker.module.js +18 -4
  235. package/dist/runtime/compaction-settings.service.d.ts +13 -1
  236. package/dist/runtime/compaction-settings.service.js +16 -1
  237. package/dist/runtime/compaction.service.d.ts +3 -1
  238. package/dist/runtime/compaction.service.js +3 -1
  239. package/dist/runtime/context/build.d.ts +24 -1
  240. package/dist/runtime/context/build.js +33 -11
  241. package/dist/runtime/context/cache-expiry.d.ts +31 -0
  242. package/dist/runtime/context/cache-expiry.js +60 -0
  243. package/dist/runtime/context/cache-ttl.d.ts +18 -0
  244. package/dist/runtime/context/cache-ttl.js +30 -0
  245. package/dist/runtime/context/compaction.d.ts +9 -2
  246. package/dist/runtime/context/compaction.js +64 -21
  247. package/dist/runtime/context/in-context-compaction.d.ts +156 -0
  248. package/dist/runtime/context/in-context-compaction.js +310 -0
  249. package/dist/runtime/context/run-context.d.ts +38 -0
  250. package/dist/runtime/context/run-context.js +54 -0
  251. package/dist/runtime/hook-calls.d.ts +2 -1
  252. package/dist/runtime/hook-calls.js +5 -2
  253. package/dist/runtime/maintenance.d.ts +16 -4
  254. package/dist/runtime/maintenance.js +79 -18
  255. package/dist/runtime/model-call.d.ts +34 -5
  256. package/dist/runtime/model-call.js +207 -22
  257. package/dist/runtime/providers.js +11 -1
  258. package/dist/runtime/run-finish.d.ts +4 -4
  259. package/dist/runtime/run-finish.js +3 -3
  260. package/dist/runtime/run-queue.js +12 -7
  261. package/dist/runtime/run-steps.d.ts +4 -2
  262. package/dist/runtime/run-steps.js +10 -5
  263. package/dist/runtime/run-worker.js +7 -1
  264. package/dist/runtime/runtime.module.js +6 -3
  265. package/dist/runtime/subagents/dispatch.js +11 -3
  266. package/dist/sandbox/browse-roots.d.ts +8 -0
  267. package/dist/sandbox/browse-roots.js +22 -0
  268. package/dist/sandbox/network-grants.d.ts +4 -4
  269. package/dist/sandbox/network-grants.js +7 -7
  270. package/dist/sandbox/operation-authority.d.ts +10 -3
  271. package/dist/sandbox/operation-authority.js +20 -10
  272. package/dist/sandbox/operation-intents.d.ts +3 -1
  273. package/dist/sandbox/operation-intents.js +11 -4
  274. package/dist/sandbox/permission-call-grants.js +2 -2
  275. package/dist/sandbox/permission-facts.js +1 -1
  276. package/dist/sandbox/review/classifier.d.ts +2 -2
  277. package/dist/sandbox/review/classifier.js +22 -11
  278. package/dist/sandbox/review/permission-candidate.d.ts +1 -1
  279. package/dist/sandbox/review/permission-candidate.js +1 -1
  280. package/dist/sandbox/sandbox.service.d.ts +15 -5
  281. package/dist/sandbox/sandbox.service.js +14 -8
  282. package/dist/shares/liveness.d.ts +26 -12
  283. package/dist/shares/liveness.js +79 -20
  284. package/dist/shares/revoke.d.ts +16 -11
  285. package/dist/shares/revoke.js +18 -14
  286. package/dist/shares/share-objects.d.ts +16 -21
  287. package/dist/shares/share-objects.js +25 -55
  288. package/dist/shares/share-open.service.d.ts +8 -4
  289. package/dist/shares/share-open.service.js +14 -11
  290. package/dist/shares/shares.controller.d.ts +16 -5
  291. package/dist/shares/shares.controller.js +39 -5
  292. package/dist/shares/shares.module.d.ts +4 -4
  293. package/dist/shares/shares.module.js +7 -6
  294. package/dist/shares/shares.schemas.d.ts +4 -0
  295. package/dist/shares/shares.schemas.js +2 -0
  296. package/dist/shares/shares.service.d.ts +93 -54
  297. package/dist/shares/shares.service.js +292 -131
  298. package/dist/shares/sweep.job.d.ts +18 -39
  299. package/dist/shares/sweep.job.js +47 -206
  300. package/dist/storage/purge.d.ts +1 -1
  301. package/dist/storage/purge.js +2 -2
  302. package/dist/tools/approvals.service.d.ts +6 -6
  303. package/dist/tools/approvals.service.js +19 -19
  304. package/dist/tools/builtin-names.d.ts +12 -12
  305. package/dist/tools/builtin-names.js +29 -29
  306. package/dist/tools/builtins/artifacts.d.ts +21 -13
  307. package/dist/tools/builtins/artifacts.js +81 -51
  308. package/dist/tools/builtins/{schedules.d.ts → automations.d.ts} +35 -33
  309. package/dist/tools/builtins/{schedules.js → automations.js} +236 -105
  310. package/dist/tools/builtins/builtin-tools.d.ts +15 -9
  311. package/dist/tools/builtins/builtin-tools.js +33 -22
  312. package/dist/tools/builtins/conversation-files.d.ts +23 -13
  313. package/dist/tools/builtins/conversation-files.js +62 -83
  314. package/dist/tools/builtins/image/generate.d.ts +7 -1
  315. package/dist/tools/builtins/image/generate.js +1 -1
  316. package/dist/tools/builtins/platform.js +1 -0
  317. package/dist/tools/builtins/sandbox/common.d.ts +6 -2
  318. package/dist/tools/builtins/sandbox/deliver.js +6 -7
  319. package/dist/tools/builtins/sandbox/fetch-attachment.d.ts +6 -5
  320. package/dist/tools/builtins/sandbox/fetch-attachment.js +19 -12
  321. package/dist/tools/call-scope.d.ts +1 -1
  322. package/dist/tools/git-asks.js +1 -1
  323. package/dist/tools/git-push-policy.d.ts +3 -3
  324. package/dist/tools/git-push-policy.js +6 -6
  325. package/dist/tools/network-asks.d.ts +3 -3
  326. package/dist/tools/network-asks.js +3 -3
  327. package/dist/tools/pipeline.d.ts +4 -4
  328. package/dist/tools/pipeline.js +2 -2
  329. package/dist/tools/policy.d.ts +3 -3
  330. package/dist/tools/policy.js +3 -3
  331. package/dist/tools/tools.module.js +15 -9
  332. package/dist/ui/call-extension.d.ts +6 -4
  333. package/dist/ui/call-extension.js +5 -4
  334. package/dist/ui/embed-token.js +6 -3
  335. package/dist/ui/registry.d.ts +21 -5
  336. package/dist/ui/registry.js +24 -6
  337. package/dist/ui/ui.schemas.d.ts +22 -0
  338. package/dist/ui/ui.schemas.js +22 -4
  339. package/dist/ui/views.controller.d.ts +13 -3
  340. package/dist/ui/views.controller.js +33 -2
  341. package/dist/ui/views.d.ts +29 -1
  342. package/dist/ui/views.js +131 -7
  343. package/package.json +3 -3
  344. package/src/migrations/0188_automations_rename.sql +309 -0
  345. package/src/migrations/0189_event_automations.sql +136 -0
  346. package/src/migrations/0190_file_library.sql +285 -0
  347. package/src/migrations/0191_file_library_copy.sql +4 -0
  348. package/dist/platform/ops/schedules.ops.js +0 -509
  349. package/dist/schedules/effective-settings.d.ts +0 -22
  350. package/dist/schedules/effective-settings.js +0 -18
  351. package/dist/schedules/errors.d.ts +0 -8
  352. package/dist/schedules/errors.js +0 -8
  353. package/dist/schedules/job-ids.d.ts +0 -81
  354. package/dist/schedules/job-ids.js +0 -95
  355. package/dist/schedules/schedules.module.d.ts +0 -16
  356. package/dist/schedules/schedules.schemas.js +0 -213
  357. package/dist/schedules/store.module.d.ts +0 -6
  358. package/dist/schedules/types.d.ts +0 -110
  359. /package/dist/{schedules → automations}/types.js +0 -0
@@ -0,0 +1,447 @@
1
+ var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
2
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
3
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
4
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
5
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
6
+ };
7
+ var __param = (this && this.__param) || function (paramIndex, decorator) {
8
+ return function (target, key) { decorator(target, key, paramIndex); }
9
+ };
10
+ import { createHash } from "node:crypto";
11
+ import { Inject, Injectable } from "@nestjs/common";
12
+ import { sql } from "kysely";
13
+ import { KernelConfigService } from "../infra/config/kernel-config.service.js";
14
+ import { KernelDb } from "../infra/database/kernel-db.js";
15
+ import { asPlatform, withOrgScope } from "../infra/database/org-scope.js";
16
+ import { TransactionHost } from "../infra/database/transaction-host.js";
17
+ import { Transactional } from "../infra/database/transactional.decorator.js";
18
+ import { LockService } from "../infra/lock/lock.service.js";
19
+ import { OutboxService } from "../infra/outbox/outbox.service.js";
20
+ import { LockedInterval } from "../infra/schedule/locked-interval.js";
21
+ import { KERNEL_LOGGER } from "../infra/tokens.js";
22
+ import { MAINTENANCE_QUEUE_NAME } from "../runtime/maintenance-queue.js";
23
+ import { StorageService } from "../storage/storage.service.js";
24
+ import { oweBlobDelete } from "./blob-objects.js";
25
+ import { BlobHashLock, BlobsService, blobContentMatches } from "./blobs.service.js";
26
+ import { FileLibraryBackfill } from "./library-backfill.js";
27
+ /** The hashing dispatcher's job name and deterministic id (no `:`). */
28
+ export const FILE_LIBRARY_HASH_JOB = "file-library-hash";
29
+ /** The job name of one org's hashing batch. */
30
+ export const FILE_LIBRARY_HASH_ORG_JOB = "file-library-hash-org";
31
+ /** The hourly kickoff's name (scheduler key and lock; no `:`). */
32
+ export const FILE_LIBRARY_KICKOFF_JOB = "file-library-kickoff";
33
+ /** The kickoff's period. */
34
+ export const FILE_LIBRARY_KICKOFF_PERIOD_MS = 60 * 60_000;
35
+ /** Blobs one org batch hashes before it owes the next batch. */
36
+ export const HASH_BATCH = 50;
37
+ /**
38
+ * How long after a merge the duplicate's deletion runs: reads that resolved the old blob just
39
+ * before the merge (a stream, a short-lived link) finish first.
40
+ */
41
+ export const MERGE_DELETE_DELAY_MS = 60 * 60_000;
42
+ /** The longest the read of one blob may take (ms); a store that stalls longer is tried later. */
43
+ export const HASH_READ_TIMEOUT_MS = 10 * 60_000;
44
+ /** The lock of one org's hashing (no `:`): one batch chain per org at a time. */
45
+ const orgLockKey = (orgId) => `file-library-hash-${orgId}`;
46
+ /** The lock's lifetime without renewal (renewed while the batch runs). */
47
+ const ORG_LOCK_TTL_MS = 60_000;
48
+ /** Deterministic id of one org's batch starting after blob `after` (no `:`). */
49
+ export const fileLibraryHashOrgJobId = (orgId, after) => `file-library-hash-${orgId}-${after ?? "first"}`;
50
+ /**
51
+ * The hashing of migrated blobs (file library spec §9 step 2): every blob the kernel writes gets
52
+ * its sha256 when it settles, so the blobs with none are those 0190/0191 (and the catch-up copy)
53
+ * migrated. Resumable and multi-replica safe:
54
+ *
55
+ * - the dispatcher job `file-library-hash` (deterministic id) owes one batch job per org that has
56
+ * unhashed `ready` blobs, `file-library-hash-<orgId>-first`;
57
+ * - an org batch (`file-library-hash-<orgId>-<after>`, in the org's scope through `runJob`) holds
58
+ * the org's lock (one chain per org; a second chain stops at once), takes up to
59
+ * {@link HASH_BATCH} blobs with `sha256 IS NULL AND status = 'ready' AND dedup_after <= now()`
60
+ * by id after its cursor, hashes them one by one, releases the lock, then owes the next batch;
61
+ * - per blob: the object is read without the size check, but its head must match the row (size,
62
+ * and the etag when one was recorded; migrated artifacts and shares have none) or the blob is
63
+ * `gone`, as reads already treat it; a missing object is `gone` too (its files render the
64
+ * placeholder). Then, in one transaction under the hash's lock ({@link BlobHashLock}), the hash is
65
+ * set when no other blob holds it (a holder no longer `ready` gives it up); else, only when the
66
+ * holder is `ready` and dedupable (`dedup_after <= now()`), the files and shares are repointed to
67
+ * the holder (locked through `BlobsService.lockReady`), this blob becomes `deleting` and its
68
+ * deletion is owed (deferred {@link MERGE_DELETE_DELAY_MS}). Anything else leaves the blob for a
69
+ * later pass. A file keeps the reference it was first stored under (`ref_key` / `ref_etag`).
70
+ *
71
+ * Nothing merges before the catch-up copy settled ({@link FileLibraryBackfill.settled}).
72
+ */
73
+ let FileLibraryHashJob = class FileLibraryHashJob {
74
+ db;
75
+ txHost;
76
+ storage;
77
+ outbox;
78
+ hashLock;
79
+ blobs;
80
+ backfill;
81
+ locks;
82
+ log;
83
+ constructor(db, txHost, storage, outbox, hashLock, blobs, backfill, locks, log) {
84
+ this.db = db;
85
+ this.txHost = txHost;
86
+ this.storage = storage;
87
+ this.outbox = outbox;
88
+ this.hashLock = hashLock;
89
+ this.blobs = blobs;
90
+ this.backfill = backfill;
91
+ this.locks = locks;
92
+ this.log = log;
93
+ }
94
+ /** Whether any org has a blob to hash (the kickoff's test). */
95
+ anyUnhashed() {
96
+ return asPlatform("file library hashing: whether any blob is unhashed", async () => {
97
+ // deployment-wide existence check of the hashing kickoff; deleted orgs are left to the purge
98
+ const row = await this.db
99
+ .selectFrom("blobs")
100
+ .innerJoin("orgs", "orgs.id", "blobs.org_id")
101
+ .select("blobs.id")
102
+ .where("orgs.deleted_at", "is", null)
103
+ .where("blobs.sha256", "is", null)
104
+ .where("blobs.status", "=", "ready")
105
+ .where("blobs.dedup_after", "<=", sql `now()`)
106
+ .limit(1)
107
+ .executeTakeFirst();
108
+ return row !== undefined;
109
+ });
110
+ }
111
+ /** Owes the dispatcher (a no-op while it is owed or waiting: the same job id). */
112
+ async oweDispatch() {
113
+ return this.outbox.add({
114
+ queue: MAINTENANCE_QUEUE_NAME,
115
+ name: FILE_LIBRARY_HASH_JOB,
116
+ jobId: FILE_LIBRARY_HASH_JOB,
117
+ data: null,
118
+ });
119
+ }
120
+ /** The dispatcher job: owes the first batch of every live org with unhashed blobs. */
121
+ async dispatch() {
122
+ if (!(await this.backfill.settled()))
123
+ return 0;
124
+ const orgs = await asPlatform("file library hashing: the orgs with unhashed blobs", async () => {
125
+ // deployment-wide: which orgs to hash (each org then hashes in its scope)
126
+ const rows = await this.db
127
+ .selectFrom("blobs")
128
+ .innerJoin("orgs", "orgs.id", "blobs.org_id")
129
+ .select("blobs.org_id")
130
+ .distinct()
131
+ .where("orgs.deleted_at", "is", null)
132
+ .where("blobs.sha256", "is", null)
133
+ .where("blobs.status", "=", "ready")
134
+ .where("blobs.dedup_after", "<=", sql `now()`)
135
+ .execute();
136
+ return rows.map((r) => r.org_id);
137
+ });
138
+ if (orgs.length > 0)
139
+ await this.oweFirstBatches(orgs);
140
+ return orgs.length;
141
+ }
142
+ async oweFirstBatches(orgIds) {
143
+ await this.outbox.addMany(orgIds.map((orgId) => ({
144
+ queue: MAINTENANCE_QUEUE_NAME,
145
+ name: FILE_LIBRARY_HASH_ORG_JOB,
146
+ jobId: fileLibraryHashOrgJobId(orgId, null),
147
+ data: { orgId, after: null },
148
+ orgId,
149
+ })));
150
+ }
151
+ /** One org batch (see the class comment), in the org's scope. */
152
+ runOrgBatch(data) {
153
+ return withOrgScope(data.orgId, () => this.orgBatch(data));
154
+ }
155
+ async orgBatch(data) {
156
+ const result = { ran: false, outcomes: {}, next: null };
157
+ const handle = await this.locks.acquire(orgLockKey(data.orgId), { ttlMs: ORG_LOCK_TTL_MS });
158
+ // another chain hashes this org now; it owes its own next batches
159
+ if (!handle)
160
+ return result;
161
+ try {
162
+ if (!(await this.backfill.settled()))
163
+ return result;
164
+ result.ran = true;
165
+ const rows = await this.unhashed(data);
166
+ for (const row of rows) {
167
+ // the lock is lost: stop here, the next pass starts again (merges are checked anyway)
168
+ if (handle.lost.aborted)
169
+ return result;
170
+ let outcome;
171
+ try {
172
+ outcome = await this.hashOne(data.orgId, row, handle.lost);
173
+ }
174
+ catch (err) {
175
+ // transient (storage, a short read): a later pass tries it again
176
+ this.log.warn("cannot hash a file library blob; will retry later", {
177
+ orgId: data.orgId,
178
+ blobId: row.id,
179
+ err,
180
+ });
181
+ outcome = "failed";
182
+ }
183
+ result.outcomes[outcome] = (result.outcomes[outcome] ?? 0) + 1;
184
+ }
185
+ if (rows.length === HASH_BATCH)
186
+ result.next = rows.at(-1).id;
187
+ }
188
+ finally {
189
+ await handle.release();
190
+ }
191
+ // owed after the lock is released, so the next batch can take it
192
+ if (result.next !== null)
193
+ await this.oweNext(data.orgId, result.next);
194
+ return result;
195
+ }
196
+ /** Up to {@link HASH_BATCH} blobs to hash after the cursor. */
197
+ unhashed(data) {
198
+ return this.db
199
+ .selectFrom("blobs")
200
+ .select(["id", "object_key", "size", "etag"])
201
+ .where("org_id", "=", data.orgId)
202
+ .where("sha256", "is", null)
203
+ .where("status", "=", "ready")
204
+ .where("dedup_after", "<=", sql `now()`)
205
+ .$if(data.after !== null, (q) => q.where("id", ">", data.after))
206
+ .orderBy("id")
207
+ .limit(HASH_BATCH)
208
+ .execute();
209
+ }
210
+ async oweNext(orgId, after) {
211
+ await this.outbox.add({
212
+ queue: MAINTENANCE_QUEUE_NAME,
213
+ name: FILE_LIBRARY_HASH_ORG_JOB,
214
+ jobId: fileLibraryHashOrgJobId(orgId, after),
215
+ data: { orgId, after },
216
+ orgId,
217
+ });
218
+ }
219
+ /** Hashes one blob and settles the outcome (see the class comment). Throws on transient errors. */
220
+ async hashOne(orgId, row, stop) {
221
+ const recorded = { size: Number(row.size), etag: row.etag };
222
+ // a lost org lock or a stuck store ends the read (the blob is tried again on a later pass)
223
+ const timeout = AbortSignal.timeout(HASH_READ_TIMEOUT_MS);
224
+ const signal = stop ? AbortSignal.any([stop, timeout]) : timeout;
225
+ const got = await this.storage.kernel(orgId).get(row.object_key, { signal });
226
+ if (!got)
227
+ return this.markGone(orgId, row.id);
228
+ if (!blobContentMatches(recorded, got.head)) {
229
+ // replaced after it was recorded (a staging object written again): reads treat it as gone
230
+ await got.body.cancel().catch(() => { });
231
+ return this.markGone(orgId, row.id);
232
+ }
233
+ const hash = createHash("sha256");
234
+ let read = 0;
235
+ const reader = got.body.getReader();
236
+ let onAbort = () => { };
237
+ const aborted = new Promise((_, reject) => {
238
+ onAbort = () => reject(signal.reason);
239
+ if (signal.aborted)
240
+ onAbort();
241
+ else
242
+ signal.addEventListener("abort", onAbort, { once: true });
243
+ });
244
+ aborted.catch(() => { });
245
+ try {
246
+ for (;;) {
247
+ // a read stalled in the store is interrupted by the abort, not only checked between chunks
248
+ const { done, value } = await Promise.race([reader.read(), aborted]);
249
+ if (done)
250
+ break;
251
+ hash.update(value);
252
+ read += value.byteLength;
253
+ }
254
+ }
255
+ finally {
256
+ signal.removeEventListener("abort", onAbort);
257
+ if (signal.aborted)
258
+ await reader.cancel().catch(() => { });
259
+ try {
260
+ reader.releaseLock();
261
+ }
262
+ catch {
263
+ // a read still pending after the cancel: the stream is dropped with the reader
264
+ }
265
+ }
266
+ if (read !== recorded.size) {
267
+ throw new Error(`read ${read} bytes of blob ${row.id}, expected ${recorded.size}`);
268
+ }
269
+ return this.settleHash(orgId, row.id, hash.digest("hex"));
270
+ }
271
+ /** The object is missing or replaced: the blob is `gone` (while still unhashed and `ready`). */
272
+ async markGone(orgId, blobId) {
273
+ const r = await this.db.db
274
+ .updateTable("blobs")
275
+ .set({ status: "gone" })
276
+ .where("id", "=", blobId)
277
+ .where("org_id", "=", orgId)
278
+ .where("status", "=", "ready")
279
+ .where("sha256", "is", null)
280
+ .executeTakeFirst();
281
+ return Number(r.numUpdatedRows) > 0 ? "gone" : "skipped";
282
+ }
283
+ /** The transaction of {@link hashOne} once the hash is known (see the class comment). */
284
+ async settleHash(orgId, blobId, sha256) {
285
+ const trx = this.db.db;
286
+ await this.hashLock.lock(orgId, sha256);
287
+ // the rows a merge moves, locked file rows first and then the blob, the order every other
288
+ // writer of a file and its blob takes (a release, a delete), so the two never deadlock
289
+ await trx
290
+ .selectFrom("files")
291
+ .select("id")
292
+ .where("org_id", "=", orgId)
293
+ .where("blob_id", "=", blobId)
294
+ .orderBy("id")
295
+ .forUpdate()
296
+ .execute();
297
+ const own = await trx
298
+ .selectFrom("blobs")
299
+ .select(["id", "object_key", "etag", "size", "status", "sha256"])
300
+ .where("id", "=", blobId)
301
+ .where("org_id", "=", orgId)
302
+ .forUpdate()
303
+ .executeTakeFirst();
304
+ if (own?.status !== "ready" || own.sha256 !== null)
305
+ return "skipped";
306
+ const holder = await trx
307
+ .selectFrom("blobs")
308
+ .select(["id", "status", sql `dedup_after <= now()`.as("dedupable")])
309
+ .where("org_id", "=", orgId)
310
+ .where("sha256", "=", sha256)
311
+ .executeTakeFirst();
312
+ if (holder === undefined || holder.status !== "ready") {
313
+ // a holder being deleted or gone gives the hash up (as `BlobsService.settle` does)
314
+ if (holder !== undefined) {
315
+ await trx
316
+ .updateTable("blobs")
317
+ .set({ sha256: null })
318
+ .where("id", "=", holder.id)
319
+ .where("org_id", "=", orgId)
320
+ .where("status", "<>", "ready")
321
+ .execute();
322
+ }
323
+ await trx
324
+ .updateTable("blobs")
325
+ .set({ sha256 })
326
+ .where("id", "=", blobId)
327
+ .where("org_id", "=", orgId)
328
+ .execute();
329
+ return "hashed";
330
+ }
331
+ if (!holder.dedupable)
332
+ return "skipped";
333
+ const winner = await this.blobs.lockReady(orgId, holder.id);
334
+ if (winner === null)
335
+ return "skipped";
336
+ if (winner.size !== Number(own.size)) {
337
+ this.log.warn("two blobs with one sha256 differ in size; not merging", {
338
+ orgId,
339
+ blobId,
340
+ holderId: winner.id,
341
+ });
342
+ return "skipped";
343
+ }
344
+ // files keep the reference the model saw: the key and etag of the blob they were stored on
345
+ await trx
346
+ .updateTable("files")
347
+ .set({
348
+ blob_id: winner.id,
349
+ ref_key: sql `coalesce(ref_key, ${own.object_key})`,
350
+ ref_etag: sql `CASE WHEN ref_key IS NULL THEN ${own.etag}::text ELSE ref_etag END`,
351
+ })
352
+ .where("org_id", "=", orgId)
353
+ .where("blob_id", "=", blobId)
354
+ .execute();
355
+ await trx
356
+ .updateTable("file_shares")
357
+ .set({ blob_id: winner.id })
358
+ .where("org_id", "=", orgId)
359
+ .where("blob_id", "=", blobId)
360
+ .execute();
361
+ await trx
362
+ .updateTable("blobs")
363
+ .set({ status: "deleting" })
364
+ .where("id", "=", blobId)
365
+ .where("org_id", "=", orgId)
366
+ .execute();
367
+ await oweBlobDelete(this.outbox, orgId, blobId, new Date(Date.now() + MERGE_DELETE_DELAY_MS));
368
+ return "merged";
369
+ }
370
+ };
371
+ __decorate([
372
+ Transactional()
373
+ ], FileLibraryHashJob.prototype, "oweDispatch", null);
374
+ __decorate([
375
+ Transactional()
376
+ ], FileLibraryHashJob.prototype, "oweFirstBatches", null);
377
+ __decorate([
378
+ Transactional()
379
+ ], FileLibraryHashJob.prototype, "oweNext", null);
380
+ __decorate([
381
+ Transactional()
382
+ ], FileLibraryHashJob.prototype, "markGone", null);
383
+ __decorate([
384
+ Transactional()
385
+ ], FileLibraryHashJob.prototype, "settleHash", null);
386
+ FileLibraryHashJob = __decorate([
387
+ Injectable(),
388
+ __param(0, Inject(KernelDb)),
389
+ __param(1, Inject(TransactionHost)),
390
+ __param(2, Inject(StorageService)),
391
+ __param(3, Inject(OutboxService)),
392
+ __param(4, Inject(BlobHashLock)),
393
+ __param(5, Inject(BlobsService)),
394
+ __param(6, Inject(FileLibraryBackfill)),
395
+ __param(7, Inject(LockService)),
396
+ __param(8, Inject(KERNEL_LOGGER))
397
+ ], FileLibraryHashJob);
398
+ export { FileLibraryHashJob };
399
+ /**
400
+ * The hourly kickoff of the file library's background work (`@LockedInterval`, once per tick
401
+ * across replicas, also once at worker start; provided only under `WorkerModule`): until the
402
+ * catch-up copy settled it owes {@link FileLibraryBackfill} (30 minutes later while the deploy is
403
+ * recent); afterwards, while unhashed blobs exist, it owes the hashing dispatcher. Both are owed
404
+ * under deterministic ids, so owing them again while they wait is a no-op.
405
+ */
406
+ let FileLibraryKickoffJob = class FileLibraryKickoffJob {
407
+ backfill;
408
+ hashing;
409
+ config;
410
+ lockService;
411
+ log;
412
+ constructor(backfill, hashing, config, lockService, log) {
413
+ this.backfill = backfill;
414
+ this.hashing = hashing;
415
+ this.config = config;
416
+ this.lockService = lockService;
417
+ this.log = log;
418
+ }
419
+ async tick() {
420
+ const r = await this.runOnce();
421
+ if (r.backfillOwed || r.hashOwed)
422
+ this.log.info("file library jobs owed", { ...r });
423
+ }
424
+ /** One kickoff without the tick lock (the interval body; tests call it directly). */
425
+ async runOnce() {
426
+ if (!(await this.backfill.settled())) {
427
+ return { backfillOwed: await this.backfill.ensureOwed(), hashOwed: false };
428
+ }
429
+ if (!(await this.hashing.anyUnhashed()))
430
+ return { backfillOwed: false, hashOwed: false };
431
+ return { backfillOwed: false, hashOwed: await this.hashing.oweDispatch() };
432
+ }
433
+ };
434
+ __decorate([
435
+ LockedInterval(FILE_LIBRARY_KICKOFF_JOB, () => FILE_LIBRARY_KICKOFF_PERIOD_MS, {
436
+ runOnStart: true,
437
+ })
438
+ ], FileLibraryKickoffJob.prototype, "tick", null);
439
+ FileLibraryKickoffJob = __decorate([
440
+ Injectable(),
441
+ __param(0, Inject(FileLibraryBackfill)),
442
+ __param(1, Inject(FileLibraryHashJob)),
443
+ __param(2, Inject(KernelConfigService)),
444
+ __param(3, Inject(LockService)),
445
+ __param(4, Inject(KERNEL_LOGGER))
446
+ ], FileLibraryKickoffJob);
447
+ export { FileLibraryKickoffJob };
@@ -0,0 +1,63 @@
1
+ import { KernelDb } from "../infra/database/kernel-db.js";
2
+ import { TransactionHost } from "../infra/database/transaction-host.js";
3
+ import { OutboxService } from "../infra/outbox/outbox.service.js";
4
+ import type { KernelLogger } from "../log.js";
5
+ /** The one-off catch-up copy's job name and deterministic id (no `:`). */
6
+ export declare const FILE_LIBRARY_BACKFILL_JOB = "file-library-backfill";
7
+ /**
8
+ * The `deployment_settings` key that records the catch-up copy settled (it ran, or it was skipped
9
+ * because the deploy is too long ago). Not a setting a person edits: the settings reader ignores
10
+ * keys it does not know.
11
+ */
12
+ export declare const FILE_LIBRARY_COPY_SETTLED = "fileLibraryCopySettled";
13
+ /** The migration that created the file library and its copy function. */
14
+ export declare const FILE_LIBRARY_MIGRATION = "0190_file_library.sql";
15
+ /** How long after it is owed the catch-up runs: once the rolling window of the deploy is over. */
16
+ export declare const BACKFILL_DELAY_MS: number;
17
+ /** After this many days since the migration the catch-up is skipped (nothing old is left). */
18
+ export declare const BACKFILL_WINDOW_DAYS = 7;
19
+ /** The value stored under {@link FILE_LIBRARY_COPY_SETTLED}. */
20
+ interface CopySettled {
21
+ outcome: "copied" | "skipped";
22
+ at: string;
23
+ }
24
+ /**
25
+ * The one-off catch-up of the file library's data copy (plan amendment K9). During a rolling deploy
26
+ * old replicas keep writing chat attachments, artifacts and shares the old way after migration
27
+ * 0191 copied them; once the window is over this job runs `file_library_copy(<0190 applied_at - 1
28
+ * hour>)` (idempotent) so those rows become library files, blobs and references too. It runs once
29
+ * (deterministic job id `file-library-backfill`, the settled marker in the copy's own transaction)
30
+ * and is skipped more than {@link BACKFILL_WINDOW_DAYS} days after the migration.
31
+ *
32
+ * The hashing job merges no blob before the marker exists ({@link settled}): the copy re-points a
33
+ * share whose blob differs from the blob of its legacy `object_key`, so a share merged before the
34
+ * copy would be pointed back at the merged duplicate.
35
+ */
36
+ export declare class FileLibraryBackfill {
37
+ private readonly db;
38
+ readonly txHost: TransactionHost;
39
+ private readonly outbox;
40
+ private readonly log;
41
+ constructor(db: KernelDb, txHost: TransactionHost, outbox: Pick<OutboxService, "add">, log: Pick<KernelLogger, "info">);
42
+ /** Whether the catch-up copy settled (ran or was skipped): the hashing job may merge blobs. */
43
+ settled(): Promise<boolean>;
44
+ /**
45
+ * Owes the catch-up unless it settled: {@link BACKFILL_DELAY_MS} from now while the migration is
46
+ * within the window (the worker start of a deploy), at once otherwise (it only records the skip).
47
+ * Owing it again while it is waiting is a no-op (the same job id). Returns whether a row was
48
+ * written.
49
+ */
50
+ ensureOwed(): Promise<boolean>;
51
+ private owe;
52
+ /**
53
+ * The job (deployment-wide): the copy from an hour before the migration, or the skip when the
54
+ * migration is older than the window; either way the settled marker, in the same transaction.
55
+ * Nothing to do once settled.
56
+ */
57
+ run(): Promise<CopySettled["outcome"] | "settled">;
58
+ private copyOnce;
59
+ /** When the migration was applied (the migrator's own bookkeeping), undefined when it was not. */
60
+ private appliedAt;
61
+ private withinWindow;
62
+ }
63
+ export {};
@@ -0,0 +1,143 @@
1
+ var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
2
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
3
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
4
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
5
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
6
+ };
7
+ var __param = (this && this.__param) || function (paramIndex, decorator) {
8
+ return function (target, key) { decorator(target, key, paramIndex); }
9
+ };
10
+ import { Inject, Injectable } from "@nestjs/common";
11
+ import { sql } from "kysely";
12
+ import { KernelDb } from "../infra/database/kernel-db.js";
13
+ import { asPlatform } from "../infra/database/org-scope.js";
14
+ import { TransactionHost } from "../infra/database/transaction-host.js";
15
+ import { Transactional } from "../infra/database/transactional.decorator.js";
16
+ import { OutboxService } from "../infra/outbox/outbox.service.js";
17
+ import { KERNEL_LOGGER } from "../infra/tokens.js";
18
+ import { MAINTENANCE_QUEUE_NAME } from "../runtime/maintenance-queue.js";
19
+ /** The one-off catch-up copy's job name and deterministic id (no `:`). */
20
+ export const FILE_LIBRARY_BACKFILL_JOB = "file-library-backfill";
21
+ /**
22
+ * The `deployment_settings` key that records the catch-up copy settled (it ran, or it was skipped
23
+ * because the deploy is too long ago). Not a setting a person edits: the settings reader ignores
24
+ * keys it does not know.
25
+ */
26
+ export const FILE_LIBRARY_COPY_SETTLED = "fileLibraryCopySettled";
27
+ /** The migration that created the file library and its copy function. */
28
+ export const FILE_LIBRARY_MIGRATION = "0190_file_library.sql";
29
+ /** How long after it is owed the catch-up runs: once the rolling window of the deploy is over. */
30
+ export const BACKFILL_DELAY_MS = 30 * 60_000;
31
+ /** After this many days since the migration the catch-up is skipped (nothing old is left). */
32
+ export const BACKFILL_WINDOW_DAYS = 7;
33
+ /** How far before the migration the catch-up copies from (rows written around the deploy). */
34
+ const BACKFILL_LOOKBACK = "1 hour";
35
+ /**
36
+ * The one-off catch-up of the file library's data copy (plan amendment K9). During a rolling deploy
37
+ * old replicas keep writing chat attachments, artifacts and shares the old way after migration
38
+ * 0191 copied them; once the window is over this job runs `file_library_copy(<0190 applied_at - 1
39
+ * hour>)` (idempotent) so those rows become library files, blobs and references too. It runs once
40
+ * (deterministic job id `file-library-backfill`, the settled marker in the copy's own transaction)
41
+ * and is skipped more than {@link BACKFILL_WINDOW_DAYS} days after the migration.
42
+ *
43
+ * The hashing job merges no blob before the marker exists ({@link settled}): the copy re-points a
44
+ * share whose blob differs from the blob of its legacy `object_key`, so a share merged before the
45
+ * copy would be pointed back at the merged duplicate.
46
+ */
47
+ let FileLibraryBackfill = class FileLibraryBackfill {
48
+ db;
49
+ txHost;
50
+ outbox;
51
+ log;
52
+ constructor(db, txHost, outbox, log) {
53
+ this.db = db;
54
+ this.txHost = txHost;
55
+ this.outbox = outbox;
56
+ this.log = log;
57
+ }
58
+ /** Whether the catch-up copy settled (ran or was skipped): the hashing job may merge blobs. */
59
+ async settled() {
60
+ const row = await this.db
61
+ .selectFrom("deployment_settings")
62
+ .select("key")
63
+ .where("key", "=", FILE_LIBRARY_COPY_SETTLED)
64
+ .executeTakeFirst();
65
+ return row !== undefined;
66
+ }
67
+ /**
68
+ * Owes the catch-up unless it settled: {@link BACKFILL_DELAY_MS} from now while the migration is
69
+ * within the window (the worker start of a deploy), at once otherwise (it only records the skip).
70
+ * Owing it again while it is waiting is a no-op (the same job id). Returns whether a row was
71
+ * written.
72
+ */
73
+ async ensureOwed() {
74
+ if (await this.settled())
75
+ return false;
76
+ const applied = await this.appliedAt();
77
+ if (applied === undefined)
78
+ return false;
79
+ const runAt = this.withinWindow(applied) ? new Date(Date.now() + BACKFILL_DELAY_MS) : undefined;
80
+ return this.owe(runAt);
81
+ }
82
+ async owe(runAt) {
83
+ return this.outbox.add({
84
+ queue: MAINTENANCE_QUEUE_NAME,
85
+ name: FILE_LIBRARY_BACKFILL_JOB,
86
+ jobId: FILE_LIBRARY_BACKFILL_JOB,
87
+ data: null,
88
+ ...(runAt !== undefined && { runAt }),
89
+ });
90
+ }
91
+ /**
92
+ * The job (deployment-wide): the copy from an hour before the migration, or the skip when the
93
+ * migration is older than the window; either way the settled marker, in the same transaction.
94
+ * Nothing to do once settled.
95
+ */
96
+ run() {
97
+ return asPlatform("file library catch-up copy across every org", () => this.copyOnce());
98
+ }
99
+ async copyOnce() {
100
+ if (await this.settled())
101
+ return "settled";
102
+ const applied = await this.appliedAt();
103
+ if (applied === undefined)
104
+ throw new Error(`${FILE_LIBRARY_MIGRATION} is not applied`);
105
+ let outcome = "skipped";
106
+ if (this.withinWindow(applied)) {
107
+ // the function names the tables itself, each statement deployment-wide by design
108
+ await sql `SELECT capybara.file_library_copy(${applied}::timestamptz - ${BACKFILL_LOOKBACK}::interval)`.execute(this.db.db);
109
+ outcome = "copied";
110
+ }
111
+ const value = { outcome, at: new Date().toISOString() };
112
+ await this.db.db
113
+ .insertInto("deployment_settings")
114
+ .values({ key: FILE_LIBRARY_COPY_SETTLED, value: JSON.stringify(value) })
115
+ .onConflict((oc) => oc.column("key").doNothing())
116
+ .execute();
117
+ this.log.info("file library catch-up copy settled", { outcome });
118
+ return outcome;
119
+ }
120
+ /** When the migration was applied (the migrator's own bookkeeping), undefined when it was not. */
121
+ async appliedAt() {
122
+ const r = await sql `SELECT applied_at FROM capybara._migrations
123
+ WHERE name = ${FILE_LIBRARY_MIGRATION}`.execute(this.db.db);
124
+ return r.rows[0]?.applied_at;
125
+ }
126
+ withinWindow(applied) {
127
+ return Date.now() - applied.getTime() <= BACKFILL_WINDOW_DAYS * 24 * 3_600_000;
128
+ }
129
+ };
130
+ __decorate([
131
+ Transactional()
132
+ ], FileLibraryBackfill.prototype, "owe", null);
133
+ __decorate([
134
+ Transactional()
135
+ ], FileLibraryBackfill.prototype, "copyOnce", null);
136
+ FileLibraryBackfill = __decorate([
137
+ Injectable(),
138
+ __param(0, Inject(KernelDb)),
139
+ __param(1, Inject(TransactionHost)),
140
+ __param(2, Inject(OutboxService)),
141
+ __param(3, Inject(KERNEL_LOGGER))
142
+ ], FileLibraryBackfill);
143
+ export { FileLibraryBackfill };