@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,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 };
|