@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.
- package/bootstrap.json +13 -13
- package/dist/admin/admin.schemas.d.ts +3 -0
- package/dist/catalog/marketplaces.service.d.ts +1 -1
- package/dist/channels/channels.module.js +4 -3
- package/dist/channels/file-delivery.d.ts +26 -11
- package/dist/channels/file-delivery.js +32 -11
- package/dist/channels/outbound.d.ts +3 -3
- package/dist/channels/outbound.js +15 -13
- package/dist/config/schema.d.ts +3 -0
- package/dist/config/schema.js +12 -0
- package/dist/conversations/artifacts.d.ts +20 -17
- package/dist/conversations/artifacts.js +30 -37
- package/dist/conversations/attachments.controller.d.ts +6 -19
- package/dist/conversations/attachments.controller.js +8 -59
- package/dist/conversations/attachments.service.d.ts +30 -74
- package/dist/conversations/attachments.service.js +51 -193
- package/dist/conversations/conversations.module.js +4 -0
- package/dist/conversations/conversations.service.d.ts +10 -9
- package/dist/conversations/conversations.service.js +28 -11
- package/dist/conversations/event-log.d.ts +1 -0
- package/dist/conversations/events.d.ts +49 -27
- package/dist/conversations/events.js +54 -7
- package/dist/conversations/files.d.ts +66 -64
- package/dist/conversations/files.js +127 -147
- package/dist/conversations/prompt-suggestion-request.js +2 -1
- package/dist/conversations/prompt-suggestions.d.ts +3 -3
- package/dist/conversations/prompt-suggestions.js +11 -10
- package/dist/conversations/queue.service.js +7 -2
- package/dist/ctx/create-ctx.d.ts +3 -1
- package/dist/ctx/create-ctx.js +19 -1
- package/dist/db/kernel-schema.d.ts +80 -2
- package/dist/errors.d.ts +19 -0
- package/dist/errors.js +19 -0
- package/dist/evals/canonical-json.d.ts +7 -0
- package/dist/evals/canonical-json.js +21 -0
- package/dist/evals/reconstruct.js +13 -1
- package/dist/evals/recorded-tools.d.ts +0 -2
- package/dist/evals/recorded-tools.js +1 -16
- package/dist/evals/snapshot.d.ts +26 -3
- package/dist/evals/snapshot.js +110 -57
- package/dist/evals/worker.d.ts +4 -3
- package/dist/evals/worker.js +8 -4
- package/dist/extensions/host.d.ts +3 -1
- package/dist/extensions/host.js +2 -0
- package/dist/extensions/instance.d.ts +3 -1
- package/dist/extensions/instance.js +4 -0
- package/dist/extensions/ledger.d.ts +1 -1
- package/dist/files/blob-objects.d.ts +124 -0
- package/dist/files/blob-objects.js +341 -0
- package/dist/files/blob-sweep.job.d.ts +122 -0
- package/dist/files/blob-sweep.job.js +389 -0
- package/dist/files/blobs.service.d.ts +135 -0
- package/dist/files/blobs.service.js +300 -0
- package/dist/files/conversation-media.d.ts +41 -0
- package/dist/files/conversation-media.js +124 -0
- package/dist/files/deliveries.d.ts +64 -0
- package/dist/files/deliveries.js +156 -0
- package/dist/files/deliveries.module.d.ts +6 -0
- package/dist/files/deliveries.module.js +24 -0
- package/dist/files/draft-cleanup.job.d.ts +26 -0
- package/dist/files/draft-cleanup.job.js +93 -0
- package/dist/files/files.module.d.ts +1 -1
- package/dist/files/files.module.js +3 -2
- package/dist/files/hash-job.d.ts +127 -0
- package/dist/files/hash-job.js +447 -0
- package/dist/files/library-backfill.d.ts +63 -0
- package/dist/files/library-backfill.js +143 -0
- package/dist/files/library-files.service.d.ts +255 -0
- package/dist/files/library-files.service.js +883 -0
- package/dist/files/library-jobs.module.d.ts +8 -0
- package/dist/files/library-jobs.module.js +27 -0
- package/dist/files/library-query.d.ts +127 -0
- package/dist/files/library-query.js +322 -0
- package/dist/files/library-read.module.d.ts +9 -0
- package/dist/files/library-read.module.js +30 -0
- package/dist/files/library.controller.d.ts +77 -0
- package/dist/files/library.controller.js +235 -0
- package/dist/files/library.module.d.ts +9 -0
- package/dist/files/library.module.js +29 -0
- package/dist/files/library.schemas.d.ts +46 -0
- package/dist/files/library.schemas.js +49 -0
- package/dist/files/previewers.controller.d.ts +20 -0
- package/dist/files/previewers.controller.js +47 -0
- package/dist/files/previewers.d.ts +25 -11
- package/dist/files/previewers.js +43 -27
- package/dist/files/referenced-files.d.ts +150 -0
- package/dist/files/referenced-files.js +234 -0
- package/dist/html/html-document.controller.d.ts +8 -1
- package/dist/html/html-document.controller.js +19 -1
- package/dist/html/html-document.service.d.ts +19 -4
- package/dist/html/html-document.service.js +43 -22
- package/dist/html/html-token.d.ts +10 -1
- package/dist/html/html-token.js +14 -0
- package/dist/html/html.module.js +8 -1
- package/dist/http/api.module.js +5 -0
- package/dist/identity/settings.d.ts +26 -0
- package/dist/identity/settings.js +33 -2
- package/dist/infra/outbox/registry.d.ts +82 -0
- package/dist/infra/outbox/registry.js +74 -2
- package/dist/infra/throttler/named-throttlers.d.ts +2 -0
- package/dist/infra/throttler/named-throttlers.js +14 -0
- package/dist/lifecycle/kernel-lifecycle.js +6 -0
- package/dist/models/purposes.js +1 -1
- package/dist/orgs/offboarding.js +1 -1
- package/dist/orgs/settings.service.d.ts +48 -2
- package/dist/orgs/settings.service.js +63 -3
- package/dist/platform/exclusions.js +45 -8
- package/dist/platform/file-ref.d.ts +18 -3
- package/dist/platform/file-ref.js +22 -11
- package/dist/platform/operation.js +4 -0
- package/dist/platform/ops/admin.ops.js +5 -2
- package/dist/platform/ops/files.ops.d.ts +18 -0
- package/dist/platform/ops/files.ops.js +267 -0
- package/dist/platform/ops/org-settings.ops.js +6 -2
- package/dist/platform/ops/orgs.ops.js +1 -0
- package/dist/platform/ops/shares.ops.js +2 -2
- package/dist/platform/platform-ops.module.d.ts +2 -1
- package/dist/platform/platform-ops.module.js +5 -0
- package/dist/platform/route-schemas.js +3 -0
- package/dist/roles/worker.module.js +15 -1
- package/dist/runtime/compaction-settings.service.d.ts +13 -1
- package/dist/runtime/compaction-settings.service.js +16 -1
- package/dist/runtime/compaction.service.d.ts +3 -1
- package/dist/runtime/compaction.service.js +3 -1
- package/dist/runtime/context/build.d.ts +18 -1
- package/dist/runtime/context/build.js +19 -8
- package/dist/runtime/context/cache-expiry.d.ts +31 -0
- package/dist/runtime/context/cache-expiry.js +60 -0
- package/dist/runtime/context/cache-ttl.d.ts +18 -0
- package/dist/runtime/context/cache-ttl.js +30 -0
- package/dist/runtime/context/compaction.d.ts +9 -2
- package/dist/runtime/context/compaction.js +50 -17
- package/dist/runtime/context/in-context-compaction.d.ts +156 -0
- package/dist/runtime/context/in-context-compaction.js +310 -0
- package/dist/runtime/hook-calls.d.ts +2 -1
- package/dist/runtime/hook-calls.js +5 -2
- package/dist/runtime/maintenance.d.ts +10 -2
- package/dist/runtime/maintenance.js +48 -8
- package/dist/runtime/model-call.d.ts +34 -5
- package/dist/runtime/model-call.js +207 -22
- package/dist/runtime/providers.js +11 -1
- package/dist/runtime/run-steps.d.ts +4 -2
- package/dist/runtime/run-steps.js +10 -5
- package/dist/runtime/runtime.module.js +3 -0
- package/dist/shares/liveness.d.ts +26 -12
- package/dist/shares/liveness.js +79 -20
- package/dist/shares/revoke.d.ts +16 -11
- package/dist/shares/revoke.js +18 -14
- package/dist/shares/share-objects.d.ts +16 -21
- package/dist/shares/share-objects.js +25 -55
- package/dist/shares/share-open.service.d.ts +8 -4
- package/dist/shares/share-open.service.js +14 -11
- package/dist/shares/shares.controller.d.ts +16 -5
- package/dist/shares/shares.controller.js +39 -5
- package/dist/shares/shares.module.d.ts +4 -4
- package/dist/shares/shares.module.js +7 -6
- package/dist/shares/shares.schemas.d.ts +4 -0
- package/dist/shares/shares.schemas.js +2 -0
- package/dist/shares/shares.service.d.ts +93 -54
- package/dist/shares/shares.service.js +292 -131
- package/dist/shares/sweep.job.d.ts +18 -39
- package/dist/shares/sweep.job.js +47 -206
- package/dist/tools/builtins/artifacts.d.ts +21 -13
- package/dist/tools/builtins/artifacts.js +81 -51
- package/dist/tools/builtins/builtin-tools.d.ts +7 -1
- package/dist/tools/builtins/builtin-tools.js +17 -6
- package/dist/tools/builtins/conversation-files.d.ts +23 -13
- package/dist/tools/builtins/conversation-files.js +62 -83
- package/dist/tools/builtins/image/generate.d.ts +7 -1
- package/dist/tools/builtins/image/generate.js +1 -1
- package/dist/tools/builtins/platform.js +1 -0
- package/dist/tools/builtins/sandbox/common.d.ts +6 -2
- package/dist/tools/builtins/sandbox/deliver.js +6 -7
- package/dist/tools/builtins/sandbox/fetch-attachment.d.ts +6 -5
- package/dist/tools/builtins/sandbox/fetch-attachment.js +19 -12
- package/dist/tools/tools.module.js +6 -0
- package/dist/ui/call-extension.d.ts +6 -4
- package/dist/ui/call-extension.js +5 -4
- package/dist/ui/embed-token.js +6 -3
- package/dist/ui/registry.d.ts +21 -5
- package/dist/ui/registry.js +24 -6
- package/dist/ui/ui.schemas.d.ts +22 -0
- package/dist/ui/ui.schemas.js +22 -4
- package/dist/ui/views.controller.d.ts +13 -3
- package/dist/ui/views.controller.js +33 -2
- package/dist/ui/views.d.ts +29 -1
- package/dist/ui/views.js +131 -7
- package/package.json +3 -3
- package/src/migrations/0190_file_library.sql +285 -0
- package/src/migrations/0191_file_library_copy.sql +4 -0
|
@@ -0,0 +1,156 @@
|
|
|
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 { EventLog } from "../conversations/event-log.js";
|
|
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 { BlobsService } from "./blobs.service.js";
|
|
16
|
+
/**
|
|
17
|
+
* A blob a delivery wanted to reference was no longer `ready` when its transaction locked it (a
|
|
18
|
+
* deletion claimed it after {@link BlobsService.ensureFromBytes} returned it). The transaction
|
|
19
|
+
* rolls back; the caller ensures the bytes again and retries.
|
|
20
|
+
*/
|
|
21
|
+
export class DeliveryBlobGoneError extends Error {
|
|
22
|
+
blobId;
|
|
23
|
+
constructor(blobId) {
|
|
24
|
+
super(`blob ${blobId} is no longer ready`);
|
|
25
|
+
this.blobId = blobId;
|
|
26
|
+
this.name = "DeliveryBlobGoneError";
|
|
27
|
+
}
|
|
28
|
+
}
|
|
29
|
+
/**
|
|
30
|
+
* Deliveries into the file library (file library spec §4 "Delivering"): the bytes of a delivered
|
|
31
|
+
* or generated file become a shared blob of the org ({@link ensureBlob}, intent first, reused by
|
|
32
|
+
* hash), then the `artifact_created` events and their `files` / `conversation_files` rows commit
|
|
33
|
+
* in one transaction ({@link appendDelivered}). The owner of a delivered file is the
|
|
34
|
+
* conversation's owner, its agent the conversation's agent. No process state.
|
|
35
|
+
*/
|
|
36
|
+
let FileDeliveries = class FileDeliveries {
|
|
37
|
+
db;
|
|
38
|
+
txHost;
|
|
39
|
+
blobs;
|
|
40
|
+
eventLog;
|
|
41
|
+
constructor(db, txHost, blobs, eventLog) {
|
|
42
|
+
this.db = db;
|
|
43
|
+
this.txHost = txHost;
|
|
44
|
+
this.blobs = blobs;
|
|
45
|
+
this.eventLog = eventLog;
|
|
46
|
+
}
|
|
47
|
+
/**
|
|
48
|
+
* The ready blob holding `bytes` (hex `sha256`): an existing one of the org, else a new one
|
|
49
|
+
* written intent first ({@link BlobsService.ensureFromBytes}). Unlocked: the transaction that
|
|
50
|
+
* references it locks it ({@link recordDelivered}).
|
|
51
|
+
*/
|
|
52
|
+
ensureBlob(orgId, sha256, bytes, opts) {
|
|
53
|
+
return this.blobs.ensureFromBytes(orgId, sha256, bytes, opts);
|
|
54
|
+
}
|
|
55
|
+
/**
|
|
56
|
+
* Appends `events` to the conversation's log and records the delivered file of every event this
|
|
57
|
+
* call wrote (`files[i]` belongs to `events[i]`; an event returned by its idempotency key, a
|
|
58
|
+
* parallel call's, records nothing), all in one transaction; announces the log after the commit.
|
|
59
|
+
* Throws {@link DeliveryBlobGoneError} (nothing written) when a blob is no longer ready.
|
|
60
|
+
*/
|
|
61
|
+
async appendDelivered(orgId, conversationId, events, files) {
|
|
62
|
+
const { events: out, toSeq } = await this.appendDeliveredIn(orgId, conversationId, events, files);
|
|
63
|
+
if (toSeq !== null)
|
|
64
|
+
await this.eventLog.notify(conversationId, toSeq);
|
|
65
|
+
return out;
|
|
66
|
+
}
|
|
67
|
+
// shared admission as the log's own appends (a tool step's are still admitted exclusively):
|
|
68
|
+
// nothing here takes an org-level lock
|
|
69
|
+
async appendDeliveredIn(orgId, conversationId, events, files) {
|
|
70
|
+
const { events: out, fresh } = await this.eventLog.appendInReport(conversationId, events);
|
|
71
|
+
const rows = [];
|
|
72
|
+
let toSeq = null;
|
|
73
|
+
for (const [i, ev] of out.entries()) {
|
|
74
|
+
if (!fresh[i])
|
|
75
|
+
continue;
|
|
76
|
+
toSeq = Math.max(toSeq ?? 0, ev.seq);
|
|
77
|
+
const f = files[i];
|
|
78
|
+
if (f !== undefined)
|
|
79
|
+
rows.push({ ...f, firstSeq: ev.seq });
|
|
80
|
+
}
|
|
81
|
+
await this.recordDelivered(orgId, conversationId, rows);
|
|
82
|
+
return { events: out, toSeq };
|
|
83
|
+
}
|
|
84
|
+
/**
|
|
85
|
+
* In the caller's transaction: locks every row's blob ({@link BlobsService.lockReady}, the gate
|
|
86
|
+
* of a new reference) and inserts the `files` rows (owner and agent the conversation's, status
|
|
87
|
+
* `ready`) and their `conversation_files` rows (`delivered`); idempotent by id. Throws
|
|
88
|
+
* {@link DeliveryBlobGoneError} when a blob is no longer ready.
|
|
89
|
+
*/
|
|
90
|
+
async recordDelivered(orgId, conversationId, rows) {
|
|
91
|
+
if (rows.length === 0)
|
|
92
|
+
return;
|
|
93
|
+
const locked = new Map();
|
|
94
|
+
for (const blobId of new Set(rows.map((r) => r.blobId))) {
|
|
95
|
+
const blob = await this.blobs.lockReady(orgId, blobId);
|
|
96
|
+
if (blob === null)
|
|
97
|
+
throw new DeliveryBlobGoneError(blobId);
|
|
98
|
+
locked.set(blobId, blob);
|
|
99
|
+
}
|
|
100
|
+
const trx = this.db.db;
|
|
101
|
+
const conv = await trx
|
|
102
|
+
.selectFrom("conversations")
|
|
103
|
+
.select(["account_id", "agent_id"])
|
|
104
|
+
.where("id", "=", conversationId)
|
|
105
|
+
.where("org_id", "=", orgId)
|
|
106
|
+
.executeTakeFirst();
|
|
107
|
+
if (!conv)
|
|
108
|
+
throw new Error(`conversation ${conversationId} not found in its org`);
|
|
109
|
+
await trx
|
|
110
|
+
.insertInto("files")
|
|
111
|
+
.values(rows.map((r) => ({
|
|
112
|
+
id: r.id,
|
|
113
|
+
org_id: orgId,
|
|
114
|
+
account_id: conv.account_id,
|
|
115
|
+
blob_id: r.blobId,
|
|
116
|
+
name: r.name,
|
|
117
|
+
content_type: r.contentType,
|
|
118
|
+
size: r.size,
|
|
119
|
+
origin: r.origin,
|
|
120
|
+
status: "ready",
|
|
121
|
+
agent_id: conv.agent_id,
|
|
122
|
+
source_conversation_id: conversationId,
|
|
123
|
+
source_path: r.sourcePath,
|
|
124
|
+
// the reference the model may see stays this blob's after a later merge
|
|
125
|
+
ref_key: locked.get(r.blobId)?.objectKey ?? null,
|
|
126
|
+
ref_etag: locked.get(r.blobId)?.etag ?? null,
|
|
127
|
+
})))
|
|
128
|
+
.onConflict((oc) => oc.column("id").doNothing())
|
|
129
|
+
.execute();
|
|
130
|
+
await trx
|
|
131
|
+
.insertInto("conversation_files")
|
|
132
|
+
.values(rows.map((r) => ({
|
|
133
|
+
conversation_id: conversationId,
|
|
134
|
+
file_id: r.id,
|
|
135
|
+
org_id: orgId,
|
|
136
|
+
role: "delivered",
|
|
137
|
+
first_seq: r.firstSeq,
|
|
138
|
+
})))
|
|
139
|
+
.onConflict((oc) => oc.columns(["conversation_id", "file_id"]).doNothing())
|
|
140
|
+
.execute();
|
|
141
|
+
}
|
|
142
|
+
};
|
|
143
|
+
__decorate([
|
|
144
|
+
Transactional({ propagation: "requires_new", admission: "shared" })
|
|
145
|
+
], FileDeliveries.prototype, "appendDeliveredIn", null);
|
|
146
|
+
__decorate([
|
|
147
|
+
Transactional({ propagation: "mandatory" })
|
|
148
|
+
], FileDeliveries.prototype, "recordDelivered", null);
|
|
149
|
+
FileDeliveries = __decorate([
|
|
150
|
+
Injectable(),
|
|
151
|
+
__param(0, Inject(KernelDb)),
|
|
152
|
+
__param(1, Inject(TransactionHost)),
|
|
153
|
+
__param(2, Inject(BlobsService)),
|
|
154
|
+
__param(3, Inject(EventLog))
|
|
155
|
+
], FileDeliveries);
|
|
156
|
+
export { FileDeliveries };
|
|
@@ -0,0 +1,24 @@
|
|
|
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
|
+
import { Module } from "@nestjs/common";
|
|
8
|
+
import { EventLogModule } from "../conversations/event-log.js";
|
|
9
|
+
import { FileDeliveries } from "./deliveries.js";
|
|
10
|
+
import { LibraryFilesModule } from "./library.module.js";
|
|
11
|
+
/**
|
|
12
|
+
* Delivered and generated files ({@link FileDeliveries}): the blobs of the file library and the
|
|
13
|
+
* conversation log, for the builtin tools that deliver files (`Deliver`, `GenerateImage`).
|
|
14
|
+
*/
|
|
15
|
+
let FileDeliveriesModule = class FileDeliveriesModule {
|
|
16
|
+
};
|
|
17
|
+
FileDeliveriesModule = __decorate([
|
|
18
|
+
Module({
|
|
19
|
+
imports: [LibraryFilesModule, EventLogModule],
|
|
20
|
+
providers: [FileDeliveries],
|
|
21
|
+
exports: [FileDeliveries],
|
|
22
|
+
})
|
|
23
|
+
], FileDeliveriesModule);
|
|
24
|
+
export { FileDeliveriesModule };
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
import { KernelDb } from "../infra/database/kernel-db.js";
|
|
2
|
+
import { LockService } from "../infra/lock/lock.service.js";
|
|
3
|
+
import type { KernelLogger } from "../log.js";
|
|
4
|
+
import { LibraryFilesService } from "./library-files.service.js";
|
|
5
|
+
/** The hourly cleanup's name (scheduler key and lock; no `:`). */
|
|
6
|
+
export declare const FILE_DRAFT_CLEANUP_JOB = "file-draft-cleanup";
|
|
7
|
+
/**
|
|
8
|
+
* The hourly cleanup of expired uploads and composer drafts (file library spec §3), a
|
|
9
|
+
* `@LockedCron` (once per tick across replicas, provided only under `WorkerModule`): finds the
|
|
10
|
+
* orgs with `uploading` / `draft` files past `expires_at`, then in each org's scope expires them
|
|
11
|
+
* batch by batch ({@link LibraryFilesService.expireBatch}: `deleted`, the staging object or the
|
|
12
|
+
* upload's own blob released through the outbox). Nothing is kept in process memory between
|
|
13
|
+
* runs; a run that stops midway is finished by the next one.
|
|
14
|
+
*/
|
|
15
|
+
export declare class FileDraftCleanupJob {
|
|
16
|
+
private readonly db;
|
|
17
|
+
private readonly files;
|
|
18
|
+
readonly lockService: LockService;
|
|
19
|
+
readonly log: KernelLogger;
|
|
20
|
+
constructor(db: KernelDb, files: Pick<LibraryFilesService, "expireBatch">, lockService: LockService, log: KernelLogger);
|
|
21
|
+
run(signal?: AbortSignal): Promise<void>;
|
|
22
|
+
/** One cleanup without the tick lock (the cron body; tests call it directly). */
|
|
23
|
+
runOnce(signal?: AbortSignal): Promise<number>;
|
|
24
|
+
/** The orgs that have expired uploads or drafts. */
|
|
25
|
+
private orgsWithExpired;
|
|
26
|
+
}
|
|
@@ -0,0 +1,93 @@
|
|
|
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, withOrgScope } from "../infra/database/org-scope.js";
|
|
14
|
+
import { LockService } from "../infra/lock/lock.service.js";
|
|
15
|
+
import { LockedCron } from "../infra/schedule/locked-cron.decorator.js";
|
|
16
|
+
import { KERNEL_LOGGER } from "../infra/tokens.js";
|
|
17
|
+
import { LibraryFilesService } from "./library-files.service.js";
|
|
18
|
+
/** The hourly cleanup's name (scheduler key and lock; no `:`). */
|
|
19
|
+
export const FILE_DRAFT_CLEANUP_JOB = "file-draft-cleanup";
|
|
20
|
+
/** Orgs one lookup of the cleanup takes. */
|
|
21
|
+
const ORG_BATCH = 500;
|
|
22
|
+
/**
|
|
23
|
+
* The hourly cleanup of expired uploads and composer drafts (file library spec §3), a
|
|
24
|
+
* `@LockedCron` (once per tick across replicas, provided only under `WorkerModule`): finds the
|
|
25
|
+
* orgs with `uploading` / `draft` files past `expires_at`, then in each org's scope expires them
|
|
26
|
+
* batch by batch ({@link LibraryFilesService.expireBatch}: `deleted`, the staging object or the
|
|
27
|
+
* upload's own blob released through the outbox). Nothing is kept in process memory between
|
|
28
|
+
* runs; a run that stops midway is finished by the next one.
|
|
29
|
+
*/
|
|
30
|
+
let FileDraftCleanupJob = class FileDraftCleanupJob {
|
|
31
|
+
db;
|
|
32
|
+
files;
|
|
33
|
+
lockService;
|
|
34
|
+
log;
|
|
35
|
+
constructor(db, files, lockService, log) {
|
|
36
|
+
this.db = db;
|
|
37
|
+
this.files = files;
|
|
38
|
+
this.lockService = lockService;
|
|
39
|
+
this.log = log;
|
|
40
|
+
}
|
|
41
|
+
async run(signal) {
|
|
42
|
+
const n = await this.runOnce(signal);
|
|
43
|
+
if (n > 0)
|
|
44
|
+
this.log.info("expired uploads and drafts deleted", { count: n });
|
|
45
|
+
}
|
|
46
|
+
/** One cleanup without the tick lock (the cron body; tests call it directly). */
|
|
47
|
+
async runOnce(signal) {
|
|
48
|
+
let expired = 0;
|
|
49
|
+
// pass after pass until a lookup finds nothing more to do (rows another run holds are skipped)
|
|
50
|
+
for (;;) {
|
|
51
|
+
let pass = 0;
|
|
52
|
+
for (const orgId of await this.orgsWithExpired()) {
|
|
53
|
+
for (;;) {
|
|
54
|
+
if (signal?.aborted)
|
|
55
|
+
return expired + pass;
|
|
56
|
+
const n = await withOrgScope(orgId, () => this.files.expireBatch(orgId));
|
|
57
|
+
pass += n;
|
|
58
|
+
if (n === 0)
|
|
59
|
+
break;
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
expired += pass;
|
|
63
|
+
if (pass === 0 || signal?.aborted)
|
|
64
|
+
return expired;
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
/** The orgs that have expired uploads or drafts. */
|
|
68
|
+
// org-filter: deployment-wide lookup of which orgs to clean; each org is then expired in its scope
|
|
69
|
+
orgsWithExpired() {
|
|
70
|
+
return asPlatform("deployment-wide lookup of orgs with expired uploads", async () => {
|
|
71
|
+
const rows = await this.db
|
|
72
|
+
.selectFrom("files")
|
|
73
|
+
.select("org_id")
|
|
74
|
+
.distinct()
|
|
75
|
+
.where("status", "in", ["uploading", "draft"])
|
|
76
|
+
.where("expires_at", "<", sql `now()`)
|
|
77
|
+
.limit(ORG_BATCH)
|
|
78
|
+
.execute();
|
|
79
|
+
return rows.map((r) => r.org_id);
|
|
80
|
+
});
|
|
81
|
+
}
|
|
82
|
+
};
|
|
83
|
+
__decorate([
|
|
84
|
+
LockedCron("0 * * * *", { name: FILE_DRAFT_CLEANUP_JOB })
|
|
85
|
+
], FileDraftCleanupJob.prototype, "run", null);
|
|
86
|
+
FileDraftCleanupJob = __decorate([
|
|
87
|
+
Injectable(),
|
|
88
|
+
__param(0, Inject(KernelDb)),
|
|
89
|
+
__param(1, Inject(LibraryFilesService)),
|
|
90
|
+
__param(2, Inject(LockService)),
|
|
91
|
+
__param(3, Inject(KERNEL_LOGGER))
|
|
92
|
+
], FileDraftCleanupJob);
|
|
93
|
+
export { FileDraftCleanupJob };
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* File previewers (`file-preview@1`): which previewers take a file (a conversation file, a share's
|
|
3
|
-
* snapshot, a skill file), the org's order, rendering.
|
|
3
|
+
* snapshot, a skill file, a library file), the org's order, rendering.
|
|
4
4
|
*/
|
|
5
5
|
export declare class FilesModule {
|
|
6
6
|
}
|
|
@@ -9,16 +9,17 @@ import { ConversationsModule } from "../conversations/conversations.module.js";
|
|
|
9
9
|
import { ExtensionsModule } from "../extensions/extensions.module.js";
|
|
10
10
|
import { SkillsModule } from "../skills/skills.module.js";
|
|
11
11
|
import { StorageModule } from "../storage/storage.module.js";
|
|
12
|
+
import { LibraryReadModule } from "./library-read.module.js";
|
|
12
13
|
import { PreviewerRegistry } from "./previewers.js";
|
|
13
14
|
/**
|
|
14
15
|
* File previewers (`file-preview@1`): which previewers take a file (a conversation file, a share's
|
|
15
|
-
* snapshot, a skill file), the org's order, rendering.
|
|
16
|
+
* snapshot, a skill file, a library file), the org's order, rendering.
|
|
16
17
|
*/
|
|
17
18
|
let FilesModule = class FilesModule {
|
|
18
19
|
};
|
|
19
20
|
FilesModule = __decorate([
|
|
20
21
|
Module({
|
|
21
|
-
imports: [ExtensionsModule, ConversationsModule, SkillsModule, StorageModule],
|
|
22
|
+
imports: [ExtensionsModule, ConversationsModule, LibraryReadModule, SkillsModule, StorageModule],
|
|
22
23
|
providers: [PreviewerRegistry],
|
|
23
24
|
exports: [PreviewerRegistry],
|
|
24
25
|
})
|
|
@@ -0,0 +1,127 @@
|
|
|
1
|
+
import { KernelConfigService } from "../infra/config/kernel-config.service.js";
|
|
2
|
+
import { KernelDb } from "../infra/database/kernel-db.js";
|
|
3
|
+
import { TransactionHost } from "../infra/database/transaction-host.js";
|
|
4
|
+
import { LockService } from "../infra/lock/lock.service.js";
|
|
5
|
+
import { OutboxService } from "../infra/outbox/outbox.service.js";
|
|
6
|
+
import type { KernelLogger } from "../log.js";
|
|
7
|
+
import { StorageService } from "../storage/storage.service.js";
|
|
8
|
+
import { BlobHashLock, BlobsService } from "./blobs.service.js";
|
|
9
|
+
import { FileLibraryBackfill } from "./library-backfill.js";
|
|
10
|
+
/** The hashing dispatcher's job name and deterministic id (no `:`). */
|
|
11
|
+
export declare const FILE_LIBRARY_HASH_JOB = "file-library-hash";
|
|
12
|
+
/** The job name of one org's hashing batch. */
|
|
13
|
+
export declare const FILE_LIBRARY_HASH_ORG_JOB = "file-library-hash-org";
|
|
14
|
+
/** The hourly kickoff's name (scheduler key and lock; no `:`). */
|
|
15
|
+
export declare const FILE_LIBRARY_KICKOFF_JOB = "file-library-kickoff";
|
|
16
|
+
/** The kickoff's period. */
|
|
17
|
+
export declare const FILE_LIBRARY_KICKOFF_PERIOD_MS: number;
|
|
18
|
+
/** Blobs one org batch hashes before it owes the next batch. */
|
|
19
|
+
export declare const HASH_BATCH = 50;
|
|
20
|
+
/**
|
|
21
|
+
* How long after a merge the duplicate's deletion runs: reads that resolved the old blob just
|
|
22
|
+
* before the merge (a stream, a short-lived link) finish first.
|
|
23
|
+
*/
|
|
24
|
+
export declare const MERGE_DELETE_DELAY_MS: number;
|
|
25
|
+
/** The longest the read of one blob may take (ms); a store that stalls longer is tried later. */
|
|
26
|
+
export declare const HASH_READ_TIMEOUT_MS: number;
|
|
27
|
+
/** Deterministic id of one org's batch starting after blob `after` (no `:`). */
|
|
28
|
+
export declare const fileLibraryHashOrgJobId: (orgId: string, after: string | null) => string;
|
|
29
|
+
/** The data of a {@link FILE_LIBRARY_HASH_ORG_JOB}. */
|
|
30
|
+
export interface HashOrgData {
|
|
31
|
+
orgId: string;
|
|
32
|
+
/** The cursor: the batch takes blobs with an id after it (null: from the start). */
|
|
33
|
+
after: string | null;
|
|
34
|
+
}
|
|
35
|
+
/** What hashing one blob did. */
|
|
36
|
+
export type HashOutcome = "hashed" | "merged" | "gone" | "skipped";
|
|
37
|
+
/** What one org batch did (returned for tests). */
|
|
38
|
+
export interface HashBatchResult {
|
|
39
|
+
/** False when another chain held the org's lock or the copy had not settled. */
|
|
40
|
+
ran: boolean;
|
|
41
|
+
outcomes: Partial<Record<HashOutcome | "failed", number>>;
|
|
42
|
+
/** The cursor of the next batch owed, null when none. */
|
|
43
|
+
next: string | null;
|
|
44
|
+
}
|
|
45
|
+
/** An unhashed blob as the batch reads it. */
|
|
46
|
+
interface UnhashedBlob {
|
|
47
|
+
id: string;
|
|
48
|
+
object_key: string;
|
|
49
|
+
size: string | number;
|
|
50
|
+
etag: string | null;
|
|
51
|
+
}
|
|
52
|
+
/**
|
|
53
|
+
* The hashing of migrated blobs (file library spec §9 step 2): every blob the kernel writes gets
|
|
54
|
+
* its sha256 when it settles, so the blobs with none are those 0190/0191 (and the catch-up copy)
|
|
55
|
+
* migrated. Resumable and multi-replica safe:
|
|
56
|
+
*
|
|
57
|
+
* - the dispatcher job `file-library-hash` (deterministic id) owes one batch job per org that has
|
|
58
|
+
* unhashed `ready` blobs, `file-library-hash-<orgId>-first`;
|
|
59
|
+
* - an org batch (`file-library-hash-<orgId>-<after>`, in the org's scope through `runJob`) holds
|
|
60
|
+
* the org's lock (one chain per org; a second chain stops at once), takes up to
|
|
61
|
+
* {@link HASH_BATCH} blobs with `sha256 IS NULL AND status = 'ready' AND dedup_after <= now()`
|
|
62
|
+
* by id after its cursor, hashes them one by one, releases the lock, then owes the next batch;
|
|
63
|
+
* - per blob: the object is read without the size check, but its head must match the row (size,
|
|
64
|
+
* and the etag when one was recorded; migrated artifacts and shares have none) or the blob is
|
|
65
|
+
* `gone`, as reads already treat it; a missing object is `gone` too (its files render the
|
|
66
|
+
* placeholder). Then, in one transaction under the hash's lock ({@link BlobHashLock}), the hash is
|
|
67
|
+
* set when no other blob holds it (a holder no longer `ready` gives it up); else, only when the
|
|
68
|
+
* holder is `ready` and dedupable (`dedup_after <= now()`), the files and shares are repointed to
|
|
69
|
+
* the holder (locked through `BlobsService.lockReady`), this blob becomes `deleting` and its
|
|
70
|
+
* deletion is owed (deferred {@link MERGE_DELETE_DELAY_MS}). Anything else leaves the blob for a
|
|
71
|
+
* later pass. A file keeps the reference it was first stored under (`ref_key` / `ref_etag`).
|
|
72
|
+
*
|
|
73
|
+
* Nothing merges before the catch-up copy settled ({@link FileLibraryBackfill.settled}).
|
|
74
|
+
*/
|
|
75
|
+
export declare class FileLibraryHashJob {
|
|
76
|
+
private readonly db;
|
|
77
|
+
readonly txHost: TransactionHost;
|
|
78
|
+
private readonly storage;
|
|
79
|
+
private readonly outbox;
|
|
80
|
+
private readonly hashLock;
|
|
81
|
+
private readonly blobs;
|
|
82
|
+
private readonly backfill;
|
|
83
|
+
private readonly locks;
|
|
84
|
+
private readonly log;
|
|
85
|
+
constructor(db: KernelDb, txHost: TransactionHost, storage: Pick<StorageService, "kernel">, outbox: Pick<OutboxService, "add" | "addMany">, hashLock: Pick<BlobHashLock, "lock">, blobs: Pick<BlobsService, "lockReady">, backfill: Pick<FileLibraryBackfill, "settled">, locks: Pick<LockService, "acquire">, log: Pick<KernelLogger, "info" | "warn">);
|
|
86
|
+
/** Whether any org has a blob to hash (the kickoff's test). */
|
|
87
|
+
anyUnhashed(): Promise<boolean>;
|
|
88
|
+
/** Owes the dispatcher (a no-op while it is owed or waiting: the same job id). */
|
|
89
|
+
oweDispatch(): Promise<boolean>;
|
|
90
|
+
/** The dispatcher job: owes the first batch of every live org with unhashed blobs. */
|
|
91
|
+
dispatch(): Promise<number>;
|
|
92
|
+
private oweFirstBatches;
|
|
93
|
+
/** One org batch (see the class comment), in the org's scope. */
|
|
94
|
+
runOrgBatch(data: HashOrgData): Promise<HashBatchResult>;
|
|
95
|
+
private orgBatch;
|
|
96
|
+
/** Up to {@link HASH_BATCH} blobs to hash after the cursor. */
|
|
97
|
+
private unhashed;
|
|
98
|
+
private oweNext;
|
|
99
|
+
/** Hashes one blob and settles the outcome (see the class comment). Throws on transient errors. */
|
|
100
|
+
hashOne(orgId: string, row: UnhashedBlob, stop?: AbortSignal): Promise<HashOutcome>;
|
|
101
|
+
/** The object is missing or replaced: the blob is `gone` (while still unhashed and `ready`). */
|
|
102
|
+
private markGone;
|
|
103
|
+
/** The transaction of {@link hashOne} once the hash is known (see the class comment). */
|
|
104
|
+
private settleHash;
|
|
105
|
+
}
|
|
106
|
+
/**
|
|
107
|
+
* The hourly kickoff of the file library's background work (`@LockedInterval`, once per tick
|
|
108
|
+
* across replicas, also once at worker start; provided only under `WorkerModule`): until the
|
|
109
|
+
* catch-up copy settled it owes {@link FileLibraryBackfill} (30 minutes later while the deploy is
|
|
110
|
+
* recent); afterwards, while unhashed blobs exist, it owes the hashing dispatcher. Both are owed
|
|
111
|
+
* under deterministic ids, so owing them again while they wait is a no-op.
|
|
112
|
+
*/
|
|
113
|
+
export declare class FileLibraryKickoffJob {
|
|
114
|
+
private readonly backfill;
|
|
115
|
+
private readonly hashing;
|
|
116
|
+
readonly config: KernelConfigService;
|
|
117
|
+
readonly lockService: LockService;
|
|
118
|
+
readonly log: KernelLogger;
|
|
119
|
+
constructor(backfill: Pick<FileLibraryBackfill, "settled" | "ensureOwed">, hashing: Pick<FileLibraryHashJob, "anyUnhashed" | "oweDispatch">, config: KernelConfigService, lockService: LockService, log: KernelLogger);
|
|
120
|
+
tick(): Promise<void>;
|
|
121
|
+
/** One kickoff without the tick lock (the interval body; tests call it directly). */
|
|
122
|
+
runOnce(): Promise<{
|
|
123
|
+
backfillOwed: boolean;
|
|
124
|
+
hashOwed: boolean;
|
|
125
|
+
}>;
|
|
126
|
+
}
|
|
127
|
+
export {};
|