@capybara-hq/kernel 0.1.0-rc.106 → 0.1.0-rc.108

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 (190) hide show
  1. package/bootstrap.json +13 -13
  2. package/dist/admin/admin.schemas.d.ts +3 -0
  3. package/dist/catalog/marketplaces.service.d.ts +1 -1
  4. package/dist/channels/channels.module.js +4 -3
  5. package/dist/channels/file-delivery.d.ts +26 -11
  6. package/dist/channels/file-delivery.js +32 -11
  7. package/dist/channels/outbound.d.ts +3 -3
  8. package/dist/channels/outbound.js +15 -13
  9. package/dist/config/schema.d.ts +3 -0
  10. package/dist/config/schema.js +12 -0
  11. package/dist/conversations/artifacts.d.ts +20 -17
  12. package/dist/conversations/artifacts.js +30 -37
  13. package/dist/conversations/attachments.controller.d.ts +6 -19
  14. package/dist/conversations/attachments.controller.js +8 -59
  15. package/dist/conversations/attachments.service.d.ts +30 -74
  16. package/dist/conversations/attachments.service.js +51 -193
  17. package/dist/conversations/conversations.module.js +4 -0
  18. package/dist/conversations/conversations.service.d.ts +10 -9
  19. package/dist/conversations/conversations.service.js +28 -11
  20. package/dist/conversations/event-log.d.ts +1 -0
  21. package/dist/conversations/events.d.ts +49 -27
  22. package/dist/conversations/events.js +54 -7
  23. package/dist/conversations/files.d.ts +66 -64
  24. package/dist/conversations/files.js +127 -147
  25. package/dist/conversations/prompt-suggestion-request.js +2 -1
  26. package/dist/conversations/prompt-suggestions.d.ts +3 -3
  27. package/dist/conversations/prompt-suggestions.js +11 -10
  28. package/dist/conversations/queue.service.js +7 -2
  29. package/dist/ctx/create-ctx.d.ts +3 -1
  30. package/dist/ctx/create-ctx.js +19 -1
  31. package/dist/db/kernel-schema.d.ts +80 -2
  32. package/dist/errors.d.ts +19 -0
  33. package/dist/errors.js +19 -0
  34. package/dist/evals/canonical-json.d.ts +7 -0
  35. package/dist/evals/canonical-json.js +21 -0
  36. package/dist/evals/reconstruct.js +13 -1
  37. package/dist/evals/recorded-tools.d.ts +0 -2
  38. package/dist/evals/recorded-tools.js +1 -16
  39. package/dist/evals/snapshot.d.ts +26 -3
  40. package/dist/evals/snapshot.js +110 -57
  41. package/dist/evals/worker.d.ts +4 -3
  42. package/dist/evals/worker.js +8 -4
  43. package/dist/extensions/host.d.ts +3 -1
  44. package/dist/extensions/host.js +2 -0
  45. package/dist/extensions/instance.d.ts +3 -1
  46. package/dist/extensions/instance.js +4 -0
  47. package/dist/extensions/ledger.d.ts +1 -1
  48. package/dist/files/blob-objects.d.ts +124 -0
  49. package/dist/files/blob-objects.js +341 -0
  50. package/dist/files/blob-sweep.job.d.ts +122 -0
  51. package/dist/files/blob-sweep.job.js +389 -0
  52. package/dist/files/blobs.service.d.ts +135 -0
  53. package/dist/files/blobs.service.js +300 -0
  54. package/dist/files/conversation-media.d.ts +41 -0
  55. package/dist/files/conversation-media.js +124 -0
  56. package/dist/files/deliveries.d.ts +64 -0
  57. package/dist/files/deliveries.js +156 -0
  58. package/dist/files/deliveries.module.d.ts +6 -0
  59. package/dist/files/deliveries.module.js +24 -0
  60. package/dist/files/draft-cleanup.job.d.ts +26 -0
  61. package/dist/files/draft-cleanup.job.js +93 -0
  62. package/dist/files/files.module.d.ts +1 -1
  63. package/dist/files/files.module.js +3 -2
  64. package/dist/files/hash-job.d.ts +127 -0
  65. package/dist/files/hash-job.js +447 -0
  66. package/dist/files/library-backfill.d.ts +63 -0
  67. package/dist/files/library-backfill.js +143 -0
  68. package/dist/files/library-files.service.d.ts +255 -0
  69. package/dist/files/library-files.service.js +883 -0
  70. package/dist/files/library-jobs.module.d.ts +8 -0
  71. package/dist/files/library-jobs.module.js +27 -0
  72. package/dist/files/library-query.d.ts +127 -0
  73. package/dist/files/library-query.js +322 -0
  74. package/dist/files/library-read.module.d.ts +9 -0
  75. package/dist/files/library-read.module.js +30 -0
  76. package/dist/files/library.controller.d.ts +77 -0
  77. package/dist/files/library.controller.js +235 -0
  78. package/dist/files/library.module.d.ts +9 -0
  79. package/dist/files/library.module.js +29 -0
  80. package/dist/files/library.schemas.d.ts +46 -0
  81. package/dist/files/library.schemas.js +49 -0
  82. package/dist/files/previewers.controller.d.ts +20 -0
  83. package/dist/files/previewers.controller.js +47 -0
  84. package/dist/files/previewers.d.ts +25 -11
  85. package/dist/files/previewers.js +43 -27
  86. package/dist/files/referenced-files.d.ts +150 -0
  87. package/dist/files/referenced-files.js +234 -0
  88. package/dist/html/html-document.controller.d.ts +8 -1
  89. package/dist/html/html-document.controller.js +19 -1
  90. package/dist/html/html-document.service.d.ts +19 -4
  91. package/dist/html/html-document.service.js +43 -22
  92. package/dist/html/html-token.d.ts +10 -1
  93. package/dist/html/html-token.js +14 -0
  94. package/dist/html/html.module.js +8 -1
  95. package/dist/http/api.module.js +5 -0
  96. package/dist/identity/settings.d.ts +26 -0
  97. package/dist/identity/settings.js +33 -2
  98. package/dist/infra/outbox/registry.d.ts +82 -0
  99. package/dist/infra/outbox/registry.js +74 -2
  100. package/dist/infra/throttler/named-throttlers.d.ts +2 -0
  101. package/dist/infra/throttler/named-throttlers.js +14 -0
  102. package/dist/lifecycle/kernel-lifecycle.js +6 -0
  103. package/dist/models/purposes.js +1 -1
  104. package/dist/orgs/offboarding.js +1 -1
  105. package/dist/orgs/settings.service.d.ts +48 -2
  106. package/dist/orgs/settings.service.js +63 -3
  107. package/dist/platform/exclusions.js +45 -8
  108. package/dist/platform/file-ref.d.ts +18 -3
  109. package/dist/platform/file-ref.js +22 -11
  110. package/dist/platform/operation.js +4 -0
  111. package/dist/platform/ops/admin.ops.js +5 -2
  112. package/dist/platform/ops/files.ops.d.ts +18 -0
  113. package/dist/platform/ops/files.ops.js +267 -0
  114. package/dist/platform/ops/org-settings.ops.js +6 -2
  115. package/dist/platform/ops/orgs.ops.js +1 -0
  116. package/dist/platform/ops/shares.ops.js +2 -2
  117. package/dist/platform/platform-ops.module.d.ts +2 -1
  118. package/dist/platform/platform-ops.module.js +5 -0
  119. package/dist/platform/route-schemas.js +3 -0
  120. package/dist/roles/worker.module.js +15 -1
  121. package/dist/runtime/compaction-settings.service.d.ts +13 -1
  122. package/dist/runtime/compaction-settings.service.js +16 -1
  123. package/dist/runtime/compaction.service.d.ts +3 -1
  124. package/dist/runtime/compaction.service.js +3 -1
  125. package/dist/runtime/context/build.d.ts +18 -1
  126. package/dist/runtime/context/build.js +19 -8
  127. package/dist/runtime/context/cache-expiry.d.ts +31 -0
  128. package/dist/runtime/context/cache-expiry.js +60 -0
  129. package/dist/runtime/context/cache-ttl.d.ts +18 -0
  130. package/dist/runtime/context/cache-ttl.js +30 -0
  131. package/dist/runtime/context/compaction.d.ts +9 -2
  132. package/dist/runtime/context/compaction.js +50 -17
  133. package/dist/runtime/context/in-context-compaction.d.ts +156 -0
  134. package/dist/runtime/context/in-context-compaction.js +310 -0
  135. package/dist/runtime/hook-calls.d.ts +2 -1
  136. package/dist/runtime/hook-calls.js +5 -2
  137. package/dist/runtime/maintenance.d.ts +10 -2
  138. package/dist/runtime/maintenance.js +48 -8
  139. package/dist/runtime/model-call.d.ts +34 -5
  140. package/dist/runtime/model-call.js +207 -22
  141. package/dist/runtime/providers.js +11 -1
  142. package/dist/runtime/run-steps.d.ts +4 -2
  143. package/dist/runtime/run-steps.js +10 -5
  144. package/dist/runtime/runtime.module.js +3 -0
  145. package/dist/shares/liveness.d.ts +26 -12
  146. package/dist/shares/liveness.js +79 -20
  147. package/dist/shares/revoke.d.ts +16 -11
  148. package/dist/shares/revoke.js +18 -14
  149. package/dist/shares/share-objects.d.ts +16 -21
  150. package/dist/shares/share-objects.js +25 -55
  151. package/dist/shares/share-open.service.d.ts +8 -4
  152. package/dist/shares/share-open.service.js +14 -11
  153. package/dist/shares/shares.controller.d.ts +16 -5
  154. package/dist/shares/shares.controller.js +39 -5
  155. package/dist/shares/shares.module.d.ts +4 -4
  156. package/dist/shares/shares.module.js +7 -6
  157. package/dist/shares/shares.schemas.d.ts +4 -0
  158. package/dist/shares/shares.schemas.js +2 -0
  159. package/dist/shares/shares.service.d.ts +93 -54
  160. package/dist/shares/shares.service.js +292 -131
  161. package/dist/shares/sweep.job.d.ts +18 -39
  162. package/dist/shares/sweep.job.js +47 -206
  163. package/dist/tools/builtins/artifacts.d.ts +21 -13
  164. package/dist/tools/builtins/artifacts.js +81 -51
  165. package/dist/tools/builtins/builtin-tools.d.ts +7 -1
  166. package/dist/tools/builtins/builtin-tools.js +17 -6
  167. package/dist/tools/builtins/conversation-files.d.ts +23 -13
  168. package/dist/tools/builtins/conversation-files.js +62 -83
  169. package/dist/tools/builtins/image/generate.d.ts +7 -1
  170. package/dist/tools/builtins/image/generate.js +1 -1
  171. package/dist/tools/builtins/platform.js +1 -0
  172. package/dist/tools/builtins/sandbox/common.d.ts +6 -2
  173. package/dist/tools/builtins/sandbox/deliver.js +6 -7
  174. package/dist/tools/builtins/sandbox/fetch-attachment.d.ts +6 -5
  175. package/dist/tools/builtins/sandbox/fetch-attachment.js +19 -12
  176. package/dist/tools/tools.module.js +6 -0
  177. package/dist/ui/call-extension.d.ts +6 -4
  178. package/dist/ui/call-extension.js +5 -4
  179. package/dist/ui/embed-token.js +6 -3
  180. package/dist/ui/registry.d.ts +21 -5
  181. package/dist/ui/registry.js +24 -6
  182. package/dist/ui/ui.schemas.d.ts +22 -0
  183. package/dist/ui/ui.schemas.js +22 -4
  184. package/dist/ui/views.controller.d.ts +13 -3
  185. package/dist/ui/views.controller.js +33 -2
  186. package/dist/ui/views.d.ts +29 -1
  187. package/dist/ui/views.js +131 -7
  188. package/package.json +3 -3
  189. package/src/migrations/0190_file_library.sql +285 -0
  190. package/src/migrations/0191_file_library_copy.sql +4 -0
@@ -1,6 +1,6 @@
1
1
  import { type DroppedUiContribution, type ExtensionManifest, type ExtensionPointRef, type ResolvedUiContribution, type StaticExtensionManifest } from "@capybara-hq/plugin-sdk";
2
2
  import { type ExtensionPointAccess, type KernelDeps, type KernelExtensionContext, LiveConfig, type RegisteredSetupCheck, type RegisteredTool, type Route } from "../ctx/create-ctx.js";
3
- import type { UiActionHandler, UiRender } from "../ui/registry.js";
3
+ import type { UiActionHandler, UiQueryHandler, UiRender } from "../ui/registry.js";
4
4
  import type { RegisteredHook } from "./hooks.js";
5
5
  import { InflightTracker } from "./inflight.js";
6
6
  import type { Registration } from "./ledger.js";
@@ -77,6 +77,8 @@ export declare class ExtensionInstance {
77
77
  get hooks(): readonly RegisteredHook[];
78
78
  get uiViews(): ReadonlyMap<string, UiRender>;
79
79
  get uiActions(): ReadonlyMap<string, UiActionHandler>;
80
+ /** Query handlers registered through `ctx.ui.query` (empty after revocation). */
81
+ get uiQueries(): ReadonlyMap<string, UiQueryHandler>;
80
82
  /** Setup checks registered through `ctx.setup.check` (empty after revocation). */
81
83
  get setupChecks(): ReadonlyMap<string, RegisteredSetupCheck>;
82
84
  /** The instance's `ctx.signal`: aborted when it is revoked or disposed. */
@@ -127,6 +127,10 @@ export class ExtensionInstance {
127
127
  get uiActions() {
128
128
  return this.ctx.uiActions;
129
129
  }
130
+ /** Query handlers registered through `ctx.ui.query` (empty after revocation). */
131
+ get uiQueries() {
132
+ return this.ctx.uiQueries;
133
+ }
130
134
  /** Setup checks registered through `ctx.setup.check` (empty after revocation). */
131
135
  get setupChecks() {
132
136
  return this.ctx.setupChecks;
@@ -1,5 +1,5 @@
1
1
  /** 插件经 ctx 做的一项登记的种类(C17)。 */
2
- export type RegistrationKind = "tool" | "route" | "queue" | "bus" | "lease" | "ui.view" | "ui.action" | "provide" | "hook" | "setup.check";
2
+ export type RegistrationKind = "tool" | "route" | "queue" | "bus" | "lease" | "ui.view" | "ui.action" | "ui.query" | "provide" | "hook" | "setup.check";
3
3
  /** 账上的一项:撤销时调用 `dispose()`。 */
4
4
  export interface Registration {
5
5
  kind: RegistrationKind;
@@ -0,0 +1,124 @@
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
+ import { StorageService } from "../storage/storage.service.js";
6
+ /**
7
+ * Blob and staging objects of the file library (file library spec §1, §3 and its builder
8
+ * amendment), all relative to the org's kernel prefix (`kernel/<orgId>/`): every blob the kernel
9
+ * writes is `blobs/<blobId>` (a key no upload form can write; a delivery's bytes and a finalized
10
+ * upload's verified copy alike), and an upload stages at `uploads/<fileId>` (a migrated upload kept
11
+ * its old key in `files.staging_key`). A staging object is never a blob. Deleting either kind is
12
+ * owed through the outbox by the transaction that stops using it; the handlers re-read the rows.
13
+ */
14
+ /** The object key of a blob the kernel writes, relative to the org prefix. */
15
+ export declare const blobObjectKey: (blobId: string) => string;
16
+ /** The staging key a new upload is presigned to, relative to the org prefix. */
17
+ export declare const stagingObjectKey: (fileId: string) => string;
18
+ /**
19
+ * How long a presigned upload form stays valid (seconds). Within it the uploader can write the
20
+ * staging object again; finalize copies the verified bytes to a kernel-owned key, so that only
21
+ * ever changes the uploader's own staging object.
22
+ */
23
+ export declare const FILE_UPLOAD_TTL_SECONDS = 300;
24
+ /** When an owed deletion of a file's staging object may run: after its upload form expired. */
25
+ export declare function afterUploadForm(fileCreatedAt: Date): Date | undefined;
26
+ /** The maintenance job that deletes one blob in `deleting` status (its object, then its row). */
27
+ export declare const BLOB_DELETE_JOB = "blob-delete";
28
+ /** The maintenance job that deletes one upload's staging object no blob adopted. */
29
+ export declare const FILE_STAGING_DELETE_JOB = "file-staging-delete";
30
+ /**
31
+ * The maintenance job that releases what a dropped upload held (a discard, the draft cleanup): its
32
+ * staging object, or its blob when nothing else points at it. Deferred and owed for every dropped
33
+ * upload alike, so the request that drops it does the same work whatever the org holds.
34
+ */
35
+ export declare const FILE_RELEASE_JOB = "file-release";
36
+ /** Deterministic outbox / BullMQ id of a dropped upload's release (no `:`). */
37
+ export declare const fileReleaseJobId: (fileId: string) => string;
38
+ /**
39
+ * How long after now a deferred job owed by a request runs: never due within the request, so no
40
+ * outbox fast path runs while the caller waits (its timing would depend on what the job found).
41
+ */
42
+ export declare const DEFERRED_JOB_DELAY_MS = 60000;
43
+ /** The run time of a job a request owes: {@link DEFERRED_JOB_DELAY_MS} from now at the earliest. */
44
+ export declare function deferred(at?: Date): Date;
45
+ /** Deterministic outbox / BullMQ id of a blob's deletion (no `:`). */
46
+ export declare const blobDeleteJobId: (blobId: string) => string;
47
+ /** Deterministic outbox / BullMQ id of a staging object's deletion (no `:`). */
48
+ export declare const fileStagingDeleteJobId: (fileId: string) => string;
49
+ /** The data of a {@link BLOB_DELETE_JOB}. */
50
+ export interface BlobDeleteData {
51
+ orgId: string;
52
+ blobId: string;
53
+ }
54
+ /** The data of a {@link FILE_RELEASE_JOB}. */
55
+ export interface FileReleaseData {
56
+ orgId: string;
57
+ fileId: string;
58
+ }
59
+ /** The data of a {@link FILE_STAGING_DELETE_JOB}. */
60
+ export interface FileStagingDeleteData {
61
+ orgId: string;
62
+ fileId: string;
63
+ objectKey: string;
64
+ }
65
+ /** Owes the deletion of a blob already set to `deleting`, in the caller's transaction. */
66
+ export declare function oweBlobDelete(outbox: Pick<OutboxService, "add">, orgId: string, blobId: string, runAt?: Date): Promise<void>;
67
+ /** Owes the deferred release of a dropped upload, in the caller's transaction. */
68
+ export declare function oweFileRelease(outbox: Pick<OutboxService, "add">, orgId: string, fileId: string, runAt: Date): Promise<void>;
69
+ /** Owes the deletion of a file's staging object, in the caller's transaction. */
70
+ export declare function oweStagingDelete(outbox: Pick<OutboxService, "add">, orgId: string, fileId: string, objectKey: string, runAt?: Date): Promise<void>;
71
+ /**
72
+ * Runs the {@link BLOB_DELETE_JOB} and {@link FILE_STAGING_DELETE_JOB} jobs (the maintenance
73
+ * processor dispatches them here). Delivered twice, each is harmless: deleting a missing object is
74
+ * a no-op and the rows are read again first.
75
+ *
76
+ * - A staging object is deleted only when the key is the file's own staging key, the file is no
77
+ * longer an upload in progress, and no blob of the org names that key (a blob adopted it).
78
+ * - A blob is deleted only while its row is `deleting` and no file or share points at it, checked
79
+ * under `FOR UPDATE` on the blob row, which the same transaction sets `gone` (so nothing, the
80
+ * blob sweep's restore included, ever takes it for live bytes again); then its object goes, then
81
+ * its row. A retry after a failed object delete finds it `gone` and goes on (references checked
82
+ * again). The invariant that
83
+ * makes the check final: every transaction that inserts or moves a reference to a blob (a file
84
+ * row, a share, a repoint) first calls `BlobsService.lockReady`, which locks the blob `FOR SHARE`
85
+ * and requires `ready`, so once a `deleting` blob is seen unreferenced under the lock, nothing can
86
+ * point at it again. A blob still referenced is left alone and logged: nothing turns a
87
+ * referenced blob into `deleting`, so that is a bug to look at, never bytes to drop.
88
+ */
89
+ export declare class BlobObjects {
90
+ private readonly db;
91
+ readonly txHost: TransactionHost;
92
+ private readonly storage;
93
+ private readonly outbox;
94
+ private readonly log;
95
+ constructor(db: KernelDb, txHost: TransactionHost, storage: Pick<StorageService, "kernel">, outbox: Pick<OutboxService, "add">, log: Pick<KernelLogger, "warn">);
96
+ /**
97
+ * Releases what a dropped (`deleted`) upload held: without a blob, its staging object (as
98
+ * {@link deleteStaging} does); with one, the blob when no other file or share points at it,
99
+ * checked under `FOR UPDATE` on the blob (a new reference passes `BlobsService.lockReady`, so it
100
+ * either committed first and is seen, or finds the blob `deleting`): the file lets go of it, the
101
+ * blob becomes `deleting` and its deletion is owed. A file not `deleted` is left alone.
102
+ */
103
+ releaseFile(data: FileReleaseData): Promise<void>;
104
+ /**
105
+ * The transaction of {@link releaseFile}: the staging key to delete when the file has no blob,
106
+ * else null (the blob released, or kept because something else points at it).
107
+ */
108
+ releaseBlob(data: FileReleaseData): Promise<string | null>;
109
+ /** Deletes one staging object; see the class comment. */
110
+ deleteStaging(data: FileStagingDeleteData): Promise<void>;
111
+ /** Deletes one `deleting` blob, its object first; see the class comment. */
112
+ deleteBlob(data: BlobDeleteData): Promise<void>;
113
+ /**
114
+ * Under `FOR UPDATE` on the blob: when it is `deleting` (or `gone`: a retry) and nothing points
115
+ * at it, sets it `gone` and returns its object key; else null (logged when it is still
116
+ * referenced).
117
+ */
118
+ claimUnreferenced(data: BlobDeleteData): Promise<string | null>;
119
+ /** The last step of {@link deleteBlob}: the row, while it is `gone` and nothing points at it. */
120
+ dropRow(data: BlobDeleteData): Promise<void>;
121
+ }
122
+ /** {@link BlobObjects} for the maintenance worker (storage and the database only). */
123
+ export declare class BlobObjectsModule {
124
+ }
@@ -0,0 +1,341 @@
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, Module } from "@nestjs/common";
11
+ import { sql } from "kysely";
12
+ import { KernelDb } from "../infra/database/kernel-db.js";
13
+ import { TransactionHost } from "../infra/database/transaction-host.js";
14
+ import { Transactional } from "../infra/database/transactional.decorator.js";
15
+ import { OutboxService } from "../infra/outbox/outbox.service.js";
16
+ import { KERNEL_LOGGER } from "../infra/tokens.js";
17
+ import { MAINTENANCE_QUEUE_NAME } from "../runtime/maintenance-queue.js";
18
+ import { StorageModule } from "../storage/storage.module.js";
19
+ import { StorageService } from "../storage/storage.service.js";
20
+ /**
21
+ * Blob and staging objects of the file library (file library spec §1, §3 and its builder
22
+ * amendment), all relative to the org's kernel prefix (`kernel/<orgId>/`): every blob the kernel
23
+ * writes is `blobs/<blobId>` (a key no upload form can write; a delivery's bytes and a finalized
24
+ * upload's verified copy alike), and an upload stages at `uploads/<fileId>` (a migrated upload kept
25
+ * its old key in `files.staging_key`). A staging object is never a blob. Deleting either kind is
26
+ * owed through the outbox by the transaction that stops using it; the handlers re-read the rows.
27
+ */
28
+ /** The object key of a blob the kernel writes, relative to the org prefix. */
29
+ export const blobObjectKey = (blobId) => `blobs/${blobId}`;
30
+ /** The staging key a new upload is presigned to, relative to the org prefix. */
31
+ export const stagingObjectKey = (fileId) => `uploads/${fileId}`;
32
+ /**
33
+ * How long a presigned upload form stays valid (seconds). Within it the uploader can write the
34
+ * staging object again; finalize copies the verified bytes to a kernel-owned key, so that only
35
+ * ever changes the uploader's own staging object.
36
+ */
37
+ export const FILE_UPLOAD_TTL_SECONDS = 300;
38
+ /**
39
+ * Slack added to a form's lifetime before an owed deletion of its staging object runs, so a form
40
+ * used again just before it expires cannot leave an object behind the deletion.
41
+ */
42
+ const FORM_SLACK_SECONDS = 60;
43
+ /** When an owed deletion of a file's staging object may run: after its upload form expired. */
44
+ export function afterUploadForm(fileCreatedAt) {
45
+ const at = fileCreatedAt.getTime() + (FILE_UPLOAD_TTL_SECONDS + FORM_SLACK_SECONDS) * 1000;
46
+ return at > Date.now() ? new Date(at) : undefined;
47
+ }
48
+ /** The maintenance job that deletes one blob in `deleting` status (its object, then its row). */
49
+ export const BLOB_DELETE_JOB = "blob-delete";
50
+ /** The maintenance job that deletes one upload's staging object no blob adopted. */
51
+ export const FILE_STAGING_DELETE_JOB = "file-staging-delete";
52
+ /**
53
+ * The maintenance job that releases what a dropped upload held (a discard, the draft cleanup): its
54
+ * staging object, or its blob when nothing else points at it. Deferred and owed for every dropped
55
+ * upload alike, so the request that drops it does the same work whatever the org holds.
56
+ */
57
+ export const FILE_RELEASE_JOB = "file-release";
58
+ /** Deterministic outbox / BullMQ id of a dropped upload's release (no `:`). */
59
+ export const fileReleaseJobId = (fileId) => `file-release-${fileId}`;
60
+ /**
61
+ * How long after now a deferred job owed by a request runs: never due within the request, so no
62
+ * outbox fast path runs while the caller waits (its timing would depend on what the job found).
63
+ */
64
+ export const DEFERRED_JOB_DELAY_MS = 60_000;
65
+ /** The run time of a job a request owes: {@link DEFERRED_JOB_DELAY_MS} from now at the earliest. */
66
+ export function deferred(at) {
67
+ const min = Date.now() + DEFERRED_JOB_DELAY_MS;
68
+ return at !== undefined && at.getTime() > min ? at : new Date(min);
69
+ }
70
+ /** Deterministic outbox / BullMQ id of a blob's deletion (no `:`). */
71
+ export const blobDeleteJobId = (blobId) => `blob-delete-${blobId}`;
72
+ /** Deterministic outbox / BullMQ id of a staging object's deletion (no `:`). */
73
+ export const fileStagingDeleteJobId = (fileId) => `file-staging-delete-${fileId}`;
74
+ /** Owes the deletion of a blob already set to `deleting`, in the caller's transaction. */
75
+ export async function oweBlobDelete(outbox, orgId, blobId, runAt) {
76
+ const data = { orgId, blobId };
77
+ await outbox.add({
78
+ queue: MAINTENANCE_QUEUE_NAME,
79
+ name: BLOB_DELETE_JOB,
80
+ jobId: blobDeleteJobId(blobId),
81
+ data,
82
+ orgId,
83
+ ...(runAt !== undefined && { runAt }),
84
+ });
85
+ }
86
+ /** Owes the deferred release of a dropped upload, in the caller's transaction. */
87
+ export async function oweFileRelease(outbox, orgId, fileId, runAt) {
88
+ const data = { orgId, fileId };
89
+ await outbox.add({
90
+ queue: MAINTENANCE_QUEUE_NAME,
91
+ name: FILE_RELEASE_JOB,
92
+ jobId: fileReleaseJobId(fileId),
93
+ data,
94
+ orgId,
95
+ runAt,
96
+ });
97
+ }
98
+ /** Owes the deletion of a file's staging object, in the caller's transaction. */
99
+ export async function oweStagingDelete(outbox, orgId, fileId, objectKey, runAt) {
100
+ const data = { orgId, fileId, objectKey };
101
+ await outbox.add({
102
+ queue: MAINTENANCE_QUEUE_NAME,
103
+ name: FILE_STAGING_DELETE_JOB,
104
+ jobId: fileStagingDeleteJobId(fileId),
105
+ data,
106
+ orgId,
107
+ ...(runAt !== undefined && { runAt }),
108
+ });
109
+ }
110
+ /**
111
+ * Runs the {@link BLOB_DELETE_JOB} and {@link FILE_STAGING_DELETE_JOB} jobs (the maintenance
112
+ * processor dispatches them here). Delivered twice, each is harmless: deleting a missing object is
113
+ * a no-op and the rows are read again first.
114
+ *
115
+ * - A staging object is deleted only when the key is the file's own staging key, the file is no
116
+ * longer an upload in progress, and no blob of the org names that key (a blob adopted it).
117
+ * - A blob is deleted only while its row is `deleting` and no file or share points at it, checked
118
+ * under `FOR UPDATE` on the blob row, which the same transaction sets `gone` (so nothing, the
119
+ * blob sweep's restore included, ever takes it for live bytes again); then its object goes, then
120
+ * its row. A retry after a failed object delete finds it `gone` and goes on (references checked
121
+ * again). The invariant that
122
+ * makes the check final: every transaction that inserts or moves a reference to a blob (a file
123
+ * row, a share, a repoint) first calls `BlobsService.lockReady`, which locks the blob `FOR SHARE`
124
+ * and requires `ready`, so once a `deleting` blob is seen unreferenced under the lock, nothing can
125
+ * point at it again. A blob still referenced is left alone and logged: nothing turns a
126
+ * referenced blob into `deleting`, so that is a bug to look at, never bytes to drop.
127
+ */
128
+ let BlobObjects = class BlobObjects {
129
+ db;
130
+ txHost;
131
+ storage;
132
+ outbox;
133
+ log;
134
+ constructor(db, txHost, storage, outbox, log) {
135
+ this.db = db;
136
+ this.txHost = txHost;
137
+ this.storage = storage;
138
+ this.outbox = outbox;
139
+ this.log = log;
140
+ }
141
+ /**
142
+ * Releases what a dropped (`deleted`) upload held: without a blob, its staging object (as
143
+ * {@link deleteStaging} does); with one, the blob when no other file or share points at it,
144
+ * checked under `FOR UPDATE` on the blob (a new reference passes `BlobsService.lockReady`, so it
145
+ * either committed first and is seen, or finds the blob `deleting`): the file lets go of it, the
146
+ * blob becomes `deleting` and its deletion is owed. A file not `deleted` is left alone.
147
+ */
148
+ async releaseFile(data) {
149
+ const staging = await this.releaseBlob(data);
150
+ if (staging !== null) {
151
+ await this.deleteStaging({ orgId: data.orgId, fileId: data.fileId, objectKey: staging });
152
+ }
153
+ }
154
+ /**
155
+ * The transaction of {@link releaseFile}: the staging key to delete when the file has no blob,
156
+ * else null (the blob released, or kept because something else points at it).
157
+ */
158
+ async releaseBlob(data) {
159
+ const trx = this.db.db;
160
+ const file = await trx
161
+ .selectFrom("files")
162
+ .select(["status", "blob_id", "staging_key"])
163
+ .where("id", "=", data.fileId)
164
+ .where("org_id", "=", data.orgId)
165
+ .forUpdate()
166
+ .executeTakeFirst();
167
+ if (file?.status !== "deleted")
168
+ return null;
169
+ if (file.blob_id === null)
170
+ return file.staging_key ?? stagingObjectKey(data.fileId);
171
+ const blob = await trx
172
+ .selectFrom("blobs")
173
+ .select(["id", "status"])
174
+ .where("id", "=", file.blob_id)
175
+ .where("org_id", "=", data.orgId)
176
+ .forUpdate()
177
+ .executeTakeFirst();
178
+ if (blob?.status !== "ready")
179
+ return null;
180
+ const otherFile = await trx
181
+ .selectFrom("files")
182
+ .select("id")
183
+ .where("org_id", "=", data.orgId)
184
+ .where("blob_id", "=", blob.id)
185
+ .where("id", "<>", data.fileId)
186
+ .limit(1)
187
+ .executeTakeFirst();
188
+ const share = await trx
189
+ .selectFrom("file_shares")
190
+ .select("id")
191
+ .where("org_id", "=", data.orgId)
192
+ .where("blob_id", "=", blob.id)
193
+ .limit(1)
194
+ .executeTakeFirst();
195
+ if (otherFile || share)
196
+ return null;
197
+ await trx
198
+ .updateTable("files")
199
+ .set({ blob_id: null })
200
+ .where("id", "=", data.fileId)
201
+ .where("org_id", "=", data.orgId)
202
+ .execute();
203
+ await trx
204
+ .updateTable("blobs")
205
+ .set({ status: "deleting" })
206
+ .where("id", "=", blob.id)
207
+ .where("org_id", "=", data.orgId)
208
+ .execute();
209
+ await oweBlobDelete(this.outbox, data.orgId, blob.id);
210
+ return null;
211
+ }
212
+ /** Deletes one staging object; see the class comment. */
213
+ async deleteStaging(data) {
214
+ const file = await this.db
215
+ .selectFrom("files")
216
+ .select([
217
+ "status",
218
+ "staging_key",
219
+ sql `expires_at IS NOT NULL AND expires_at <= now()`.as("expired"),
220
+ ])
221
+ .where("id", "=", data.fileId)
222
+ .where("org_id", "=", data.orgId)
223
+ .executeTakeFirst();
224
+ const ownKey = data.objectKey === stagingObjectKey(data.fileId) ||
225
+ (file !== undefined && file.staging_key === data.objectKey);
226
+ if (!ownKey) {
227
+ // never delete anything outside the file's own staging key, whatever the job data says
228
+ throw new Error(`file-staging-delete: unexpected object key for file ${data.fileId}`);
229
+ }
230
+ // an upload still in progress may yet be finalized
231
+ if (file?.status === "uploading" && !file.expired)
232
+ return;
233
+ // a backstop, not a path: finalize never adopts a staging object, and migrated blobs keep keys
234
+ // no staging row names; still, a key some blob uses is never deleted from here
235
+ const adopted = await this.db
236
+ .selectFrom("blobs")
237
+ .select("id")
238
+ .where("org_id", "=", data.orgId)
239
+ .where("object_key", "=", data.objectKey)
240
+ .executeTakeFirst();
241
+ if (adopted)
242
+ return;
243
+ await this.storage.kernel(data.orgId).delete(data.objectKey);
244
+ }
245
+ /** Deletes one `deleting` blob, its object first; see the class comment. */
246
+ async deleteBlob(data) {
247
+ const key = await this.claimUnreferenced(data);
248
+ if (key === null)
249
+ return;
250
+ await this.storage.kernel(data.orgId).delete(key);
251
+ await this.dropRow(data);
252
+ }
253
+ /**
254
+ * Under `FOR UPDATE` on the blob: when it is `deleting` (or `gone`: a retry) and nothing points
255
+ * at it, sets it `gone` and returns its object key; else null (logged when it is still
256
+ * referenced).
257
+ */
258
+ async claimUnreferenced(data) {
259
+ const trx = this.db.db;
260
+ const blob = await trx
261
+ .selectFrom("blobs")
262
+ .select(["status", "object_key"])
263
+ .where("id", "=", data.blobId)
264
+ .where("org_id", "=", data.orgId)
265
+ .forUpdate()
266
+ .executeTakeFirst();
267
+ if (blob?.status !== "deleting" && blob?.status !== "gone")
268
+ return null;
269
+ const file = await trx
270
+ .selectFrom("files")
271
+ .select("id")
272
+ .where("org_id", "=", data.orgId)
273
+ .where("blob_id", "=", data.blobId)
274
+ .limit(1)
275
+ .executeTakeFirst();
276
+ const share = await trx
277
+ .selectFrom("file_shares")
278
+ .select("id")
279
+ .where("org_id", "=", data.orgId)
280
+ .where("blob_id", "=", data.blobId)
281
+ .limit(1)
282
+ .executeTakeFirst();
283
+ if (file || share) {
284
+ this.log.warn("a blob marked for deletion is still referenced; keeping it", { ...data });
285
+ return null;
286
+ }
287
+ await trx
288
+ .updateTable("blobs")
289
+ .set({ status: "gone" })
290
+ .where("id", "=", data.blobId)
291
+ .where("org_id", "=", data.orgId)
292
+ .execute();
293
+ return blob.object_key;
294
+ }
295
+ /** The last step of {@link deleteBlob}: the row, while it is `gone` and nothing points at it. */
296
+ async dropRow(data) {
297
+ await this.db.db
298
+ .deleteFrom("blobs")
299
+ .where("id", "=", data.blobId)
300
+ .where("org_id", "=", data.orgId)
301
+ .where("status", "=", "gone")
302
+ .where((eb) => eb.and([
303
+ eb.not(eb.exists(eb
304
+ .selectFrom("files")
305
+ .select("files.id")
306
+ .where("files.org_id", "=", data.orgId)
307
+ .whereRef("files.blob_id", "=", "blobs.id"))),
308
+ eb.not(eb.exists(eb
309
+ .selectFrom("file_shares")
310
+ .select("file_shares.id")
311
+ .where("file_shares.org_id", "=", data.orgId)
312
+ .whereRef("file_shares.blob_id", "=", "blobs.id"))),
313
+ ]))
314
+ .execute();
315
+ }
316
+ };
317
+ __decorate([
318
+ Transactional()
319
+ ], BlobObjects.prototype, "releaseBlob", null);
320
+ __decorate([
321
+ Transactional()
322
+ ], BlobObjects.prototype, "claimUnreferenced", null);
323
+ __decorate([
324
+ Transactional()
325
+ ], BlobObjects.prototype, "dropRow", null);
326
+ BlobObjects = __decorate([
327
+ Injectable(),
328
+ __param(0, Inject(KernelDb)),
329
+ __param(1, Inject(TransactionHost)),
330
+ __param(2, Inject(StorageService)),
331
+ __param(3, Inject(OutboxService)),
332
+ __param(4, Inject(KERNEL_LOGGER))
333
+ ], BlobObjects);
334
+ export { BlobObjects };
335
+ /** {@link BlobObjects} for the maintenance worker (storage and the database only). */
336
+ let BlobObjectsModule = class BlobObjectsModule {
337
+ };
338
+ BlobObjectsModule = __decorate([
339
+ Module({ imports: [StorageModule], providers: [BlobObjects], exports: [BlobObjects] })
340
+ ], BlobObjectsModule);
341
+ export { BlobObjectsModule };
@@ -0,0 +1,122 @@
1
+ import type { BlobStatus } from "../db/kernel-schema.js";
2
+ import { KernelConfigService } from "../infra/config/kernel-config.service.js";
3
+ import { KernelDb } from "../infra/database/kernel-db.js";
4
+ import { TransactionHost } from "../infra/database/transaction-host.js";
5
+ import { LockService } from "../infra/lock/lock.service.js";
6
+ import { OutboxService } from "../infra/outbox/outbox.service.js";
7
+ import type { KernelLogger } from "../log.js";
8
+ import { StorageService } from "../storage/storage.service.js";
9
+ import { FileLibraryBackfill } from "./library-backfill.js";
10
+ /** The daily blob sweep's name (scheduler key and lock; no `:`). */
11
+ export declare const BLOB_SWEEP_JOB = "blob-sweep";
12
+ /** When the daily blob sweep runs (the deployment's time zone): after the share sweep (03:40). */
13
+ export declare const BLOB_SWEEP_CRON = "20 4 * * *";
14
+ /** A `ready` (or `gone`) blob nothing refers to is released once it is older than this (hours). */
15
+ export declare const UNREFERENCED_AFTER_HOURS = 24;
16
+ /** A `pending` blob with no file is abandoned once it is older than this (hours). */
17
+ export declare const PENDING_AFTER_HOURS = 1;
18
+ /**
19
+ * A `deleting` blob created more than this many hours ago is reconciled: its deletion is owed
20
+ * again when nothing refers to it (deduplicated by its job id while the first deletion still
21
+ * waits, e.g. a merge's deferred one), it is restored when something does. The age is the blob's
22
+ * `created_at` (no column records when it became `deleting`); a blob whose deletion already
23
+ * claimed it is `gone`, never `deleting`, so a restore never races its object's deletion.
24
+ */
25
+ export declare const STALE_DELETING_AFTER_HOURS = 24;
26
+ /** What one sweep did (logged; returned for tests). */
27
+ export interface BlobSweepResult {
28
+ /** `deleted` files past the retention whose rows were deleted. */
29
+ filesDeleted: number;
30
+ /** `ready` / `gone` blobs nothing refers to that became `deleting`. */
31
+ blobsReleased: number;
32
+ /** Abandoned `pending` blobs that became `deleting`. */
33
+ pendingReleased: number;
34
+ /** Stale `deleting` blobs nothing refers to whose deletion was owed again. */
35
+ deletionsReowed: number;
36
+ /** Stale `deleting` blobs something still refers to, back to `ready` (or `gone`). */
37
+ deletingRestored: number;
38
+ }
39
+ /** Which blobs a release pass takes: their statuses and the age they must have reached. */
40
+ interface ReleaseKind {
41
+ statuses: readonly BlobStatus[];
42
+ olderThanHours: number;
43
+ /** Only blobs with a sha256 (while the catch-up copy has not settled; see the class comment). */
44
+ hashedOnly?: boolean;
45
+ }
46
+ /**
47
+ * The daily blob sweep (file library spec §7), a `@LockedCron` (once per tick across replicas,
48
+ * provided only under `WorkerModule`). For each live org, in the org's scope:
49
+ *
50
+ * 1. `deleted` files whose `deleted_at` is older than `files.deletedRetentionDays` lose their rows
51
+ * (their `conversation_files` rows go with them; logs keep the refs and render the placeholder);
52
+ * 2. `ready` (and `gone`) blobs older than {@link UNREFERENCED_AFTER_HOURS} that no file row and no
53
+ * share refers to become `deleting`, their deletion owed (`blob-delete-<id>`) in the same
54
+ * transaction;
55
+ * 3. `pending` blobs older than {@link PENDING_AFTER_HOURS} with no file (a kernel write that never
56
+ * settled) likewise;
57
+ * 4. `deleting` blobs older than {@link STALE_DELETING_AFTER_HOURS} are reconciled: one nothing
58
+ * refers to has its deletion owed again (the job may have run out of attempts); one something
59
+ * refers to (only `file_library_copy` inserts a reference without `BlobsService.lockReady`, and
60
+ * the deletion job refuses a referenced blob before touching its bytes) is restored: `ready`
61
+ * when its object is still the recorded bytes, else `gone`.
62
+ *
63
+ * Until the catch-up copy settled ({@link FileLibraryBackfill.settled}) step 2 leaves unhashed
64
+ * (migrated) blobs alone: the copy may still point new files or shares at them.
65
+ *
66
+ * A claim locks its candidates `FOR UPDATE SKIP LOCKED` (a blob another transaction is pointing a
67
+ * reference at holds `FOR SHARE` through `BlobsService.lockReady` and is skipped), then sets
68
+ * `deleting` in a statement of its own that checks the references again: its fresh snapshot sees
69
+ * every reference committed before the rows were locked, and once they are locked a new reference
70
+ * waits and then finds the blob no longer `ready`. The `blob-delete` handler checks once more before
71
+ * deleting anything. Nothing is kept in process memory; a run that stops midway is finished by the
72
+ * next one. Deleted orgs are skipped (their objects go with `storage-org-purge`).
73
+ */
74
+ export declare class BlobSweepJob {
75
+ private readonly db;
76
+ readonly txHost: TransactionHost;
77
+ private readonly outbox;
78
+ private readonly config;
79
+ private readonly storage;
80
+ private readonly backfill;
81
+ readonly lockService: LockService;
82
+ readonly log: KernelLogger;
83
+ constructor(db: KernelDb, txHost: TransactionHost, outbox: Pick<OutboxService, "add">, config: Pick<KernelConfigService, "get">, storage: Pick<StorageService, "kernel">, backfill: Pick<FileLibraryBackfill, "settled">, lockService: LockService, log: KernelLogger);
84
+ sweep(signal?: AbortSignal): Promise<void>;
85
+ /** One sweep without the tick lock (the cron body; tests call it directly). */
86
+ runOnce(signal?: AbortSignal): Promise<BlobSweepResult>;
87
+ /** A page of live org ids after `after`. */
88
+ private orgPage;
89
+ /** The four steps for one org (in its scope). */
90
+ private sweepOrg;
91
+ /** Step 2 or 3 for one org, batch by batch along the blob ids. */
92
+ private releaseAll;
93
+ /**
94
+ * Step 1, one batch: deletes up to {@link BATCH} `deleted` files past the retention (rows another
95
+ * transaction holds are skipped; the condition is checked again on the locked rows). Their shares
96
+ * are revoked (`file_deleted`) in the same transaction, before the rows go and with them the
97
+ * shares' `source_file_id` (defense in depth: deleting the file already revoked them).
98
+ */
99
+ deleteExpiredFiles(orgId: string): Promise<number>;
100
+ /**
101
+ * Steps 2 and 3, one batch: claims up to {@link BATCH} candidates after `after` (see the class
102
+ * comment), turns the still unreferenced ones `deleting` and owes their deletions. `last` is the
103
+ * last candidate id (the next batch's cursor), null when there were no more candidates.
104
+ */
105
+ releaseBatch(orgId: string, kind: ReleaseKind, after: string | null): Promise<{
106
+ released: number;
107
+ last: string | null;
108
+ }>;
109
+ /**
110
+ * Step 4, one batch of up to {@link BATCH} stale `deleting` blobs after `after`: the objects of
111
+ * the referenced ones are checked first (outside any transaction), then one transaction locks the
112
+ * batch `FOR UPDATE SKIP LOCKED`, checks the references again in a statement of its own, restores
113
+ * the referenced ones and owes the deletion of the others again (deduplicated while it is owed).
114
+ */
115
+ private reconcileDeleting;
116
+ /** The transaction of {@link reconcileDeleting}. */
117
+ settleDeleting(orgId: string, ids: readonly string[], intact: ReadonlySet<string>): Promise<{
118
+ reowed: number;
119
+ restored: number;
120
+ }>;
121
+ }
122
+ export {};