mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-11-23 13:13:46 +01:00
## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work > - One server process serves every request and agent turn on one thread. The same process saves each remote workspace as one encrypted archive in object storage, and restores it before a turn > - `server/src/services/remote-workspace-snapshot-storage.ts` hashed, encrypted and decrypted every byte of those archives on that thread. `server/src/storage/s3-multipart.ts` computed the Content-MD5 of each uploaded part on that thread too > - Hashes and ciphers are synchronous in Node. A CPU profile of a busy hosted server showed this work on the main thread, which was at 93% of one core > - Each megabyte of a snapshot delays every request and turn that waits behind it > - This pull request moves those passes to a small, bounded set of worker threads. The checks, their order, their failures and the stored format do not change > - The benefit is that a 1 GiB save uses about 0.7 s of the server's thread instead of about 2.8 s, and an unrelated request during the save is answered in 1.3 ms (p99) instead of 16.7 ms ## Linked Issues or Issue Description No public issue exists. I searched open and closed pull requests for `workspace snapshot hash encrypt`, `event loop` and `archive io`. Related merged work: #19900 gave these stream passes 1 MiB buffers, #20554 removed a read-back from migration, #20722 took runner artifact hashes off the event loop, #20709 records long event-loop blocks. No open pull request covers this change. **What happened?** A 30 second CPU profile of the main thread of a hosted server (commit1d153f62b6, Node 24, main thread at 93% of one core) showed: - the two stream transforms in the snapshot save at 3.9% and 1.6% inclusive. The first hashes the archive (SHA-256). The second hashes the ciphertext (SHA-256); - native hash `update` at 5.4% self time for the whole process. About 1.0 s of it was under those two transforms and 0.25 s was under `fileRangeMd5`; - the AES-256-GCM cipher of the same pipeline, and Buffer allocation under the file read streams. Garbage collection was 25% of the thread. What the code did with each byte, on the server's thread: | Path | Pass | Digest or cipher | Purpose | | --- | --- | --- | --- | | Save | read archive | SHA-256 of plaintext | bound into the wrapped key, checked on each restore | | Save | same read | AES-256-GCM | confidentiality and authenticity | | Save | same read | SHA-256 of stored bytes | recorded on the snapshot row, checked on each restore and read-back | | Save | read each part (S3) | MD5 | `Content-MD5`: the object store rejects a part it did not receive intact | | Save, read-back callers | read the kept file | SHA-256 of plaintext | proof that the published file is the saved archive | | Restore | download | SHA-256 of stored bytes | integrity of the object against the snapshot row | | Restore | read ciphertext | AES-256-GCM | authenticity | | Restore | read plaintext | SHA-256 of plaintext | integrity against the digest in the wrapped key | | Restore | read plaintext again | none (copy) | publication beside the destination | **Expected behavior** Digest and cipher passes over a snapshot do not run on the thread that serves requests. Every check stays, with the same failure. **Steps to reproduce** 1. On the parent commit, run `pnpm --filter @paperclipai/server exec tsx scripts/benchmark-workspace-snapshot-crypto.ts --mib=1024` (copy the script from this branch). 2. Read `upload.mainThreadCpuMs`, `upload.mainThreadBusyMs` and `upload.unrelatedRequest`. The benchmark uses the real save and restore functions, the real S3 client, and a local object store that checks each part's `Content-MD5`. A separate process requests a trivial route from the measured server and times each reply with its own clock. **Paperclip version or commit** `master` at9e910ff9ae. The profile is from1d153f62b6. **Deployment mode** All modes that save remote workspaces. The profile is from a hosted server with S3 storage. **Node.js version** Profile: Node 24. Local benchmark and tests: Node 26.4.0 on darwin arm64. ## What Changed - `server/src/storage/file-crypto-pool.ts` (new): runs file digests and AES-256-GCM passes on worker threads. - Bounds: at most 2 jobs run at once. Each worker has two reused 1 MiB read buffers and one write in flight. A waiting job holds file names and byte ranges, not file contents. Waiting jobs are served in order. - Cancellation: a waiting job is cancelled at once. A running job stops at its next chunk, closes its files, and then the caller sees the same `AbortError` as before. - Shutdown: an idle worker does not keep the process alive. A busy worker does, until its job ends or its caller's signal aborts it. - Key handling: the pool copies the data key for the worker, moves that copy (it is not cloned), and the worker erases it. A copy that never reaches a worker is erased on this thread. The caller keeps and erases its own key as before. - The worker program is sent as source text, as `remote-workspace-snapshot-archive.ts` already does. It needs no extra file in the build or the runtime bundle. - Save (`uploadWorkspaceSnapshot`): the one read that digests the archive, encrypts it and digests the stored bytes runs in a worker. The identity check around that read (`archive_changed`) stays on this thread and is unchanged. - Part upload (`fileRangeMd5`): the `Content-MD5` of each part is computed in a worker. The first round of parts is digested before any part is sent, so the parts still leave together and a rate limit still answers one burst (the existing throttle test covers this). Every digest of that round has ended, also after a failure or a cancellation, before the upload settles. - Restore (`loadWorkspaceSnapshotArchive`): the download no longer hashes on this thread. One worker digests the downloaded object while another decrypts it into private scratch. The results are then checked in the previous order: object size and digest, header, key, GCM tag. - Restore, one pass less: the decrypted archive was read twice (digest, then copy). It is now digested while it is copied beside the destination, and linked to the destination only when the digest matches. The digest covers exactly the published bytes. - Read-back callers (`verifiedArchivePath`): the digest of the kept file runs in a worker, through the same open descriptor. The file identity checks are unchanged. - `server/scripts/benchmark-workspace-snapshot-crypto.ts` (new): the reproduction and benchmark. - Docs: `doc/run-log-events.md` (what each `storage.snapshot.*` phase now does) and `doc/DEVELOPING.md` (the worker threads and the benchmark). Module boundaries (`rules/module-boundaries.mdc`): the pool is in `server/src/storage/` because both consumers are parts of the same upload, and storage must not import from services. Its contract is file paths, byte ranges, an algorithm, and AES-GCM parameters. The snapshot format (magic bytes, additional data, key wrapping, the order of checks) stays in the snapshot service. The part layout and `Content-MD5` stay in the S3 module. Not changed, and why: - The stored format, the ledger, attempt journaling, atomic publication, and `recoverWorkspaceSnapshotUpload` / `recoverWorkspaceSnapshotArchive`. - `verifyObject` (full read-back for a store that did not verify the upload, and for a retried save) still hashes on this thread. Its bytes arrive from the network on this thread. To move it, the object must first be written to disk. - Socket writes of part bodies stay on this thread. I measured 1 MiB part-body read chunks in place of 64 KiB: main-thread time did not change and the longest event-loop delay increased, so I did not keep it. - `remote-workspace-transport.ts` also hashes an archive on this thread. It is outside the snapshot storage path. ## Verification Regression tests, red then green (`cd server && pnpm exec vitest run src/services/remote-workspace-snapshot-storage.test.ts src/storage/file-crypto-pool.test.ts`): - Parent implementation with the tests of this branch: 3 tests fail. - `keeps encrypting a save while the server thread is occupied by other work`: `expected 4194323 to be 25166144`. The test blocks the thread until the encrypted file is complete. On the parent the file stops at 4 MiB. - `answers unrelated requests while a save is being encrypted, and digests or encrypts none of it on the server thread`: `expected 8388627 to be less than 65536` (bytes hashed on the thread). - `digests and decrypts none of a save or a restore on the server thread when the store verified the upload`: `expected 33556772 to be less than 65536`. - This branch: 58 of 58 and 6 of 6 pass. - The tests use synchronization, not time. A named pipe keeps a save in the encrypt step for as long as the test feeds it. Deadlines are 30 s and matter only for a failure. - Integrity tests that pass on both the parent implementation and this branch, which shows that the failures are the same: a truncated object (`object_hash_mismatch`), an oversized object (`object_size_mismatch`), an archive that grows, shrinks or is rewritten in place after its identity was read (`archive_changed`, before any upload), a ciphertext that was changed with the recorded digest changed to match (GCM failure), a plaintext that differs from the digest in the key (`plaintext_hash_mismatch`, staged copy removed), and the order object, header, key. - Cancellation: during encryption the save rejects with `AbortError`, and leaves no scratch file, no object and no recorded attempt. During the store write it leaves no object. - Part digests (`src/__tests__/storage-s3-multipart.test.ts`): `leaves no part digest running or waiting when the source is cancelled|removed during the first round`. Before the review fix ina354242865it failed with `{ running: 2, waiting: 0 }` at multipart cleanup. - Pool tests: digests equal single-threaded digests for a file, a range and a descriptor; encrypt and decrypt round trip; each damaged ciphertext is reported; at most 2 jobs run and the others wait in order; a waiting job and a running job are both cancelled. Benchmark, same machine, 5 alternating pairs (parent implementation, then this branch) for each size. Values are medians, with the range in parentheses. Command: `pnpm --filter @paperclipai/server exec tsx scripts/benchmark-workspace-snapshot-crypto.ts --mib=1024` (and `--mib=200`). 1 GiB archive: | Measure | Save, before | Save, after | Restore, before | Restore, after | | --- | --- | --- | --- | --- | | Main-thread CPU time | 2,834 ms (2,717 to 3,007) | 742 ms (658 to 881) | 1,602 ms (1,378 to 1,837) | 510 ms (470 to 589) | | Main-thread busy time (event-loop utilization) | 2,938 ms | 858 ms | 1,673 ms | 597 ms | | Total process CPU time | 6,735 ms | 4,762 ms | 5,564 ms | 3,306 ms | | Wall time | 3,914 ms (3,656 to 4,253) | 2,580 ms (2,507 to 3,200) | 2,502 ms (1,756 to 2,922) | 1,799 ms (1,508 to 2,492) | | Longest event-loop delay | 12.6 ms | 6.0 ms | 10.4 ms | 5.4 ms | | Event-loop delay p99 | 9.2 ms | 2.0 ms | 2.1 ms | 1.8 ms | | Unrelated request p99 (p50 is 0.2 to 0.3 ms in all runs) | 16.7 ms | 1.3 ms | 4.7 ms | 1.3 ms | | Unrelated request, slowest | 18.5 ms | 4.5 ms | 10.0 ms | 3.5 ms | | Peak resident memory | 495 MiB | 408 MiB | 524 MiB | 476 MiB | 200 MiB archive: | Measure | Save, before | Save, after | Restore, before | Restore, after | | --- | --- | --- | --- | --- | | Main-thread CPU time | 571 ms | 181 ms | 378 ms | 141 ms | | Main-thread busy time | 602 ms | 236 ms | 395 ms | 167 ms | | Total process CPU time | 1,235 ms | 935 ms | 1,385 ms | 840 ms | | Wall time | 842 ms | 679 ms | 538 ms | 382 ms | | Longest event-loop delay | 12.4 ms | 4.0 ms | 7.3 ms | 2.9 ms | | Unrelated request p99 | 16.5 ms | 2.0 ms | 1.9 ms | 1.9 ms | | Peak resident memory | 437 MiB | 398 MiB | 510 MiB | 424 MiB | How to read these numbers: - The parent did not block the thread for seconds at one time. It worked in 1 MiB slices, so the longest single delay was about 12 ms. The cost was the sum: the thread was busy for about 75% of a 1 GiB save. That sum is what the profile showed, and it is what decreases. - A worker thread moves CPU time; it does not remove it. Total CPU time also decreased here (about 29% for a save, 41% for a restore) because the workers reuse two buffers in place of one new 1 MiB Buffer for each chunk, and a restore reads the decrypted archive once in place of twice. - Wall time decreased because the part digests no longer wait for the thread that sends the parts, and a restore digests and decrypts at the same time. - What remains on the server's thread is network and file streaming: socket writes of the parts, the download, and the database calls. - Limits: the machine was shared with other work (1-minute load average 8 to 14 on 18 cores) and timings varied between runs, which is why the pairs alternate. Earlier runs on a busier machine (load 15 to 28) showed the same CPU-time ratios with wall times up to 4 times longer for both implementations. The object store was on loopback without TLS. Other checks: - `cd server && pnpm exec vitest run src/storage src/services/remote-workspace-snapshot-storage.test.ts src/services/remote-workspace-snapshot-reuse.test.ts src/__tests__/remote-workspace-file-resources.test.ts` and the 8 `src/__tests__/storage-s3-*.test.ts` files: 249 tests in 15 files pass. - `tsc --noEmit` over the changed TypeScript files: clean. `pnpm check:module-boundaries`: pass. - The pool, bundled with the options of `server/scripts/bundle-runtime.mjs` and run with plain `node`: encrypt, decrypt and digest round trip, and the process exits. - `pnpm verify` exits 2 (broader verification required, because of the new file in `server/scripts`). Required CI supplies that coverage. - Not verified: the hosted server after deploy, Linux x86 with Node 24 outside CI, a real object store with TLS, and archives larger than 1 GiB. ## Risks - This is integrity and confidentiality code. The mitigation is that each check and its failure is pinned by a test that passes on the parent implementation and on this branch, and that the format is unchanged, so objects saved before and after this change restore with either version. - Order of work in a restore: the ciphertext is now decrypted into private scratch while the object digest is computed, not after it. No output is used before the digest, header, key and tag checks pass, and the scratch directory is removed on every failure. A damaged object is reported with the same error, but after the decrypt work. - The staged copy beside the destination (`.workspace-snapshot-*.tmp`) is now written before the plaintext digest is known, and after the GCM tag is verified. It is removed on a mismatch. The destination itself is linked only after the digest matches, as before. - Resource trade-off: up to 2 more threads, each with about 2 MiB of buffers and a small heap (64 MB limit), that stay for the life of the process once used. In exchange the server's thread does about 70% less work for each snapshot. With more than 2 snapshot passes at one time, the others wait. A part digest can wait behind a long encryption. - Run-log timing shifts: `storage.snapshot.digest` is now about 0 ms, `storage.snapshot.verify_plaintext` includes the copy, and `storage.snapshot.publish` is only the link. `doc/run-log-events.md` describes this. - A worker that stops unexpectedly fails its job with `file_crypto_worker_exited`. The save or restore then fails as for any other I/O error, and the next job starts a new worker. > For core feature work, check [`ROADMAP.md`](ROADMAP.md) first and discuss it in `#dev` before opening the PR. Feature PRs that overlap with planned core work may need to be redirected — check the roadmap first. See `CONTRIBUTING.md`. ## Model Used - Claude Fable 5.2 (`claude-fable-5-2`), Anthropic, in Claude Code with tool use (shell, file edits, local test and benchmark runs). ## Checklist - [x] I have included a thinking path that traces from project context to this change - [x] I have specified the model used (with version and capability details) - [x] I have checked ROADMAP.md and confirmed this PR does not duplicate planned core work - [x] I have searched GitHub for duplicate or related PRs and linked them above - [x] I have either (a) linked existing issues with `Fixes: #` / `Closes #` / `Refs #` OR (b) described the issue in-PR following the relevant issue template - [x] I have not referenced internal/instance-local Paperclip issues or links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip` URLs) - [x] My branch name describes the change (e.g. `docs/...`, `fix/...`) and contains no internal Paperclip ticket id or instance-derived details - [x] I have run tests locally and they pass - [x] I have added or updated tests where applicable - [x] I have updated relevant documentation to reflect my changes - [x] I have considered and documented any risks above - [x] All Paperclip CI gates are green - [x] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [x] I will address all Greptile and reviewer comments before requesting merge 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude Fable 5.2 <noreply@anthropic.com>
585 lines
35 KiB
TypeScript
585 lines
35 KiB
TypeScript
import { createDecipheriv, createHash, randomBytes, randomUUID } from "node:crypto";
|
|
import { decryptFileOffThread, digestFileOffThread, encryptFileOffThread, type FileDecryption, type FileDigest } from "../storage/file-crypto-pool.js";
|
|
import { isStorageUnavailableError, sendThroughStorageOutage, storageOutageWaitFor, waitOutStorageOutages } from "../storage/storage-unavailable.js";
|
|
import { measureRunPhase, type ExecutionPhase } from "./execution-preparation-timing.js";
|
|
import { collectStorageRequestStats, newStorageRequestStats, type StorageRequestStats } from "../storage/request-stats.js";
|
|
import { constants, createReadStream, createWriteStream } from "node:fs";
|
|
import { link, lstat, mkdtemp, open, realpath, rm } from "node:fs/promises";
|
|
import os from "node:os";
|
|
import path from "node:path";
|
|
import { pipeline } from "node:stream/promises";
|
|
import { pipeline as streamPipeline, Readable, Transform } from "node:stream";
|
|
import { isDeepStrictEqual } from "node:util";
|
|
import { and, eq } from "drizzle-orm";
|
|
import { executionWorkspaceSnapshots, type Db } from "@paperclipai/db";
|
|
import { localEncryptedProvider } from "../secrets/local-encrypted-provider.js";
|
|
import type { StoredSecretVersionMaterial } from "../secrets/types.js";
|
|
import type { StorageService } from "../storage/types.js";
|
|
import { abortSnapshotAttemptUploads, notifyRemoteWorkspaceSnapshots, snapshotAttemptKeys, REMOTE_WORKSPACE_SNAPSHOT_GRACE_MS } from "./remote-workspace-snapshot-retention.js";
|
|
import { WORKSPACE_ARCHIVE_IO_BUFFER_BYTES } from "./remote-workspace-archive-io.js";
|
|
|
|
const SCHEMA = "paperclip.workspace-snapshot.v1";
|
|
const KEY_SCHEMA = "paperclip.workspace-snapshot-key.v1";
|
|
const MAGIC = Buffer.from("PCWSE1\n");
|
|
const FORMAT = "paperclip.remote-workspace-archive.v1";
|
|
const DOWNLOAD_IDLE_TIMEOUT_MS = 5 * 60_000;
|
|
type SnapshotRow = typeof executionWorkspaceSnapshots.$inferSelect;
|
|
export interface WorkspaceSnapshotRef {
|
|
schema: typeof SCHEMA;
|
|
id: string;
|
|
companyId: string;
|
|
workspaceId: string;
|
|
generation: number;
|
|
objectKey: string;
|
|
sha256: string;
|
|
byteSize: number;
|
|
key: StoredSecretVersionMaterial;
|
|
manifestDigest: string;
|
|
}
|
|
type UploadAttempt = Omit<WorkspaceSnapshotRef, "schema" | "companyId" | "workspaceId" | "generation" | "id">;
|
|
function failure(reason: string): never { throw new Error(`remote_workspace_snapshot_${reason}`); }
|
|
const aad = (ref: Pick<WorkspaceSnapshotRef, "companyId" | "workspaceId" | "id" | "generation">) =>
|
|
Buffer.from(JSON.stringify([SCHEMA, ref.companyId, ref.workspaceId, ref.id, ref.generation]));
|
|
const scope = (input: { companyId: string; workspaceId: string; snapshotId: string }) => and(
|
|
eq(executionWorkspaceSnapshots.id, input.snapshotId), eq(executionWorkspaceSnapshots.companyId, input.companyId),
|
|
eq(executionWorkspaceSnapshots.executionWorkspaceId, input.workspaceId),
|
|
);
|
|
function reference(row: SnapshotRow): WorkspaceSnapshotRef {
|
|
if (!row.objectKey || !row.sha256 || !row.byteSize || !row.key || !row.manifestDigest) failure("not_uploaded");
|
|
const value = { schema: SCHEMA, id: row.id, companyId: row.companyId, workspaceId: row.executionWorkspaceId,
|
|
generation: row.generation, objectKey: row.objectKey!, sha256: row.sha256!, byteSize: row.byteSize!, key: row.key!, manifestDigest: row.manifestDigest! } as WorkspaceSnapshotRef;
|
|
validateReference(value);
|
|
return value;
|
|
}
|
|
function validateReference(ref: WorkspaceSnapshotRef) {
|
|
if (ref.schema !== SCHEMA || !Number.isSafeInteger(ref.generation) || ref.generation < 1
|
|
|| !ref.objectKey.startsWith(`${ref.companyId}/workspace-snapshots/${ref.workspaceId}/${ref.id}/`)
|
|
|| !/^[a-f0-9]{64}$/.test(ref.sha256) || !/^[a-f0-9]{64}$/.test(ref.manifestDigest)
|
|
|| !Number.isSafeInteger(ref.byteSize) || ref.byteSize < MAGIC.length + 12 + 16
|
|
|| !ref.key || typeof ref.key !== "object") failure("reference_invalid");
|
|
}
|
|
async function verifyStoredSize(storage: StorageService, ref: WorkspaceSnapshotRef, signal?: AbortSignal) {
|
|
const head = await storage.headObject(ref.companyId, ref.objectKey, { signal });
|
|
if (!head.exists || head.contentLength !== ref.byteSize) failure("object_size_mismatch");
|
|
}
|
|
async function verifyObject(storage: StorageService, ref: WorkspaceSnapshotRef, signal?: AbortSignal) {
|
|
const object = await storage.getObject(ref.companyId, ref.objectKey, { signal });
|
|
const digest = createHash("sha256"); let size = 0;
|
|
try {
|
|
for await (const chunk of object.stream) {
|
|
signal?.throwIfAborted(); size += chunk.length;
|
|
if (size > ref.byteSize) failure("object_size_mismatch");
|
|
digest.update(chunk);
|
|
}
|
|
if (size !== ref.byteSize || digest.digest("hex") !== ref.sha256) failure("object_hash_mismatch");
|
|
} finally { object.stream.destroy(); }
|
|
}
|
|
|
|
export async function beginWorkspaceSnapshot(db: Db, input: {
|
|
companyId: string; workspaceId: string; operationId: string; runId?: string | null;
|
|
parentSnapshotId?: string | null; generation: number; epoch: number;
|
|
}) {
|
|
if (!Number.isSafeInteger(input.generation) || input.generation < 1 || !Number.isSafeInteger(input.epoch) || input.epoch < 0) failure("generation_invalid");
|
|
await db.transaction(async tx => {
|
|
await notifyRemoteWorkspaceSnapshots(tx, `workspace:${input.workspaceId}`);
|
|
await tx.insert(executionWorkspaceSnapshots).values({ companyId: input.companyId, executionWorkspaceId: input.workspaceId,
|
|
sourceOperationId: input.operationId, sourceRunId: input.runId ?? null, parentSnapshotId: input.parentSnapshotId ?? null,
|
|
generation: input.generation, epoch: input.epoch, format: FORMAT,
|
|
deleteAfter: new Date(Date.now() + REMOTE_WORKSPACE_SNAPSHOT_GRACE_MS) }).onConflictDoNothing();
|
|
});
|
|
const [row] = await db.select().from(executionWorkspaceSnapshots).where(and(
|
|
eq(executionWorkspaceSnapshots.companyId, input.companyId), eq(executionWorkspaceSnapshots.executionWorkspaceId, input.workspaceId),
|
|
eq(executionWorkspaceSnapshots.sourceOperationId, input.operationId),
|
|
));
|
|
if (!row || row.generation !== input.generation || row.epoch !== input.epoch || row.parentSnapshotId !== (input.parentSnapshotId ?? null)
|
|
|| row.sourceRunId !== (input.runId ?? null)) failure("operation_binding_changed");
|
|
return row!;
|
|
}
|
|
|
|
export async function getWorkspaceSnapshot(db: Db, input: { companyId: string; workspaceId: string; snapshotId: string }) {
|
|
const [row] = await db.select().from(executionWorkspaceSnapshots).where(scope(input));
|
|
return row && ["uploaded", "committed", "superseded"].includes(row.status) ? reference(row) : null;
|
|
}
|
|
|
|
export async function findUnchangedWorkspaceSnapshot(input: {
|
|
db: Db; storage: StorageService; snapshot: SnapshotRow; manifestDigest: string; archiveSha256: string; archiveBytes: number;
|
|
timing?: WorkspaceSnapshotStorageTiming;
|
|
}): Promise<WorkspaceSnapshotRef | null> {
|
|
return withRequestStats(input.timing, async () => {
|
|
const { snapshot } = input;
|
|
if (!snapshot.parentSnapshotId || snapshot.status !== "pending" || snapshot.objectKey !== null
|
|
|| snapshot.sha256 !== null || snapshot.byteSize !== null || snapshot.key !== null || snapshot.manifestDigest !== null
|
|
|| snapshot.metadata?.uploads !== undefined
|
|
&& (!Array.isArray(snapshot.metadata.uploads) || snapshot.metadata.uploads.length !== 0)) return null;
|
|
const [parent] = await input.db.select().from(executionWorkspaceSnapshots).where(and(
|
|
eq(executionWorkspaceSnapshots.companyId, snapshot.companyId),
|
|
eq(executionWorkspaceSnapshots.executionWorkspaceId, snapshot.executionWorkspaceId),
|
|
eq(executionWorkspaceSnapshots.id, snapshot.parentSnapshotId),
|
|
eq(executionWorkspaceSnapshots.status, "committed"),
|
|
eq(executionWorkspaceSnapshots.manifestDigest, input.manifestDigest)));
|
|
if (!parent) return null;
|
|
const ref = reference(parent);
|
|
const key = await snapshotKey(ref);
|
|
if (key.plaintextSha256 !== input.archiveSha256 || key.plaintextBytes !== input.archiveBytes) return null;
|
|
const head = await input.storage.headObject(ref.companyId, ref.objectKey);
|
|
return head.exists && head.contentLength === ref.byteSize ? ref : null;
|
|
});
|
|
}
|
|
|
|
export async function recoverWorkspaceSnapshotUpload(input: {
|
|
db: Db; storage: StorageService; snapshotId: string; companyId: string; workspaceId: string;
|
|
signal?: AbortSignal;
|
|
}): Promise<WorkspaceSnapshotRef | null> {
|
|
const [row] = await input.db.select().from(executionWorkspaceSnapshots).where(scope(input));
|
|
if (!row) failure("missing");
|
|
if (["uploaded", "committed", "superseded"].includes(row!.status)) {
|
|
return reference(row!);
|
|
}
|
|
if (row!.status !== "pending") failure("not_writable");
|
|
const attempts = Array.isArray(row!.metadata?.uploads) ? row!.metadata!.uploads as UploadAttempt[] : [];
|
|
for (const attempt of attempts) {
|
|
input.signal?.throwIfAborted();
|
|
const ref: WorkspaceSnapshotRef = { schema: SCHEMA, ...attempt, id: row!.id, companyId: row!.companyId,
|
|
workspaceId: row!.executionWorkspaceId, generation: row!.generation };
|
|
validateReference(ref);
|
|
if (!(await input.storage.headObject(ref.companyId, ref.objectKey, { signal: input.signal })).exists) continue;
|
|
return ref;
|
|
}
|
|
return null;
|
|
}
|
|
|
|
export async function recoverWorkspaceSnapshotArchive(input: {
|
|
db: Db; storage: StorageService; snapshotId: string; companyId: string; workspaceId: string;
|
|
targetPath: string; signal?: AbortSignal;
|
|
}): Promise<WorkspaceSnapshotRef | null> {
|
|
const ref = await recoverWorkspaceSnapshotUpload(input);
|
|
if (ref) await loadWorkspaceSnapshotArchive({ ...input, reference: ref });
|
|
return ref;
|
|
}
|
|
|
|
/**
|
|
* Where a workspace snapshot save or restore spends its time. Each step is
|
|
* also a `storage.snapshot.*` run phase, which reaches the run log when it runs
|
|
* inside run preparation (a restore before the turn). Durations in ms; counts
|
|
* only, no keys or paths.
|
|
*/
|
|
export type WorkspaceSnapshotStorageTiming = {
|
|
priorAttemptCheckMs?: number; encryptMs?: number; digestMs?: number; putMs?: number; verifyMs?: number;
|
|
downloadMs?: number; decryptMs?: number; plaintextVerifyMs?: number; publishMs?: number;
|
|
bytes?: number; requests: StorageRequestStats;
|
|
};
|
|
|
|
export function newWorkspaceSnapshotStorageTiming(): WorkspaceSnapshotStorageTiming {
|
|
return { requests: newStorageRequestStats() };
|
|
}
|
|
|
|
type TimedStep = "priorAttemptCheckMs" | "encryptMs" | "digestMs" | "putMs" | "verifyMs"
|
|
| "downloadMs" | "decryptMs" | "plaintextVerifyMs" | "publishMs";
|
|
|
|
/** Runs one snapshot step as a run phase and adds its duration to `timing`. */
|
|
async function timedStep<T>(timing: WorkspaceSnapshotStorageTiming | undefined, key: TimedStep, phase: ExecutionPhase,
|
|
work: () => Promise<T>): Promise<T> {
|
|
const started = performance.now();
|
|
try { return await measureRunPhase(phase, work); }
|
|
finally { if (timing) timing[key] = (timing[key] ?? 0) + Math.max(0, Math.round(performance.now() - started)); }
|
|
}
|
|
|
|
/** Collects the storage requests `work` sends into `timing`, when there is one. */
|
|
function withRequestStats<T>(timing: WorkspaceSnapshotStorageTiming | undefined, work: () => Promise<T>): Promise<T> {
|
|
return timing ? collectStorageRequestStats(timing.requests, work) : work();
|
|
}
|
|
|
|
type WorkspaceSnapshotUpload = {
|
|
db: Db; storage: StorageService; snapshotId: string; companyId: string; workspaceId: string;
|
|
archivePath: string; manifestDigest: string; signal?: AbortSignal; verifiedArchivePath?: string;
|
|
// Only an owner with an immutable logical source may replace an unavailable,
|
|
// unpublished capture. A recoverable or concurrently published attempt wins,
|
|
// and its returned manifest may differ from the new physical capture.
|
|
unpublishedRecapture?: { sourceOperationId: string };
|
|
/** Receives per-step durations and storage request counts. */
|
|
timing?: WorkspaceSnapshotStorageTiming;
|
|
verification?: "readback" | "upload";
|
|
};
|
|
|
|
/** Upload attempts are journaled before remote I/O. The caller owns publication. */
|
|
export async function uploadWorkspaceSnapshot(input: WorkspaceSnapshotUpload): Promise<WorkspaceSnapshotRef> {
|
|
return withRequestStats(input.timing, () => waitOutStorageOutages(() => storageOutageWaitFor("saving the workspace", () => uploadWorkspaceSnapshotTimed(input))));
|
|
}
|
|
|
|
async function uploadWorkspaceSnapshotTimed(input: WorkspaceSnapshotUpload): Promise<WorkspaceSnapshotRef> {
|
|
if (input.verification === "upload")
|
|
return uploadVerifiedWorkspaceSnapshot(input, assertWorkspaceSnapshotKeyReadable, { acceptServerVerifiedUpload: false });
|
|
if (input.verifiedArchivePath === undefined)
|
|
return uploadVerifiedWorkspaceSnapshot(input, ref => verifyObject(input.storage, ref, input.signal), { acceptServerVerifiedUpload: true });
|
|
input.signal?.throwIfAborted();
|
|
const target = input.verifiedArchivePath, parent = path.dirname(target);
|
|
if (!path.isAbsolute(target) || path.normalize(target) !== target) failure("readback_parent_invalid");
|
|
const owner = await lstat(parent);
|
|
const assertParent = async () => {
|
|
const current = await lstat(parent);
|
|
if (!current.isDirectory() || current.isSymbolicLink() || (current.mode & 0o777) !== 0o700
|
|
|| typeof process.getuid === "function" && current.uid !== process.getuid()
|
|
|| current.dev !== owner.dev || current.ino !== owner.ino || await realpath(parent) !== parent) failure("readback_parent_invalid");
|
|
};
|
|
await assertParent();
|
|
await lstat(target).then(() => failure("readback_target_exists"), (error: NodeJS.ErrnoException) => {
|
|
if (error.code !== "ENOENT") throw error;
|
|
});
|
|
const scratch = await mkdtemp(path.join(parent, ".workspace-upload-readback-"));
|
|
const verified: Array<{ ref: WorkspaceSnapshotRef; file: string }> = [];
|
|
const verify = async (ref: WorkspaceSnapshotRef) => {
|
|
if (verified.some(saved => isDeepStrictEqual(saved.ref, ref))) return;
|
|
const file = path.join(scratch, `${randomUUID()}.pcws`);
|
|
await loadWorkspaceSnapshotArchive({ storage: input.storage, reference: ref, targetPath: file,
|
|
signal: input.signal, temporaryParent: scratch });
|
|
verified.push({ ref: structuredClone(ref), file });
|
|
};
|
|
try {
|
|
// This caller keeps the read-back file, so every upload is read back.
|
|
const ref = await uploadVerifiedWorkspaceSnapshot(input, verify, { acceptServerVerifiedUpload: false });
|
|
await verify(ref);
|
|
const file = verified.find(saved => isDeepStrictEqual(saved.ref, ref))!.file;
|
|
const wrapped = await snapshotKey(ref), handle = await open(file, constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK);
|
|
try {
|
|
const before = await handle.stat();
|
|
if (!before.isFile() || (before.mode & 0o777) !== 0o600 || before.nlink !== 1
|
|
|| typeof process.getuid === "function" && before.uid !== process.getuid()) failure("readback_file_changed");
|
|
// Digested through this open descriptor, off the server's thread.
|
|
const kept = await digestFileOffThread({ fd: handle.fd, algorithm: "sha256" }, input.signal);
|
|
const after = await handle.stat(), named = await lstat(file);
|
|
if (!named.isFile() || named.isSymbolicLink() || named.dev !== before.dev || named.ino !== before.ino
|
|
|| named.nlink !== 1 || named.mode !== before.mode || after.size !== before.size
|
|
|| after.mtimeMs !== before.mtimeMs || after.ctimeMs !== before.ctimeMs
|
|
|| kept.bytes !== wrapped.plaintextBytes || kept.hex !== wrapped.plaintextSha256) failure("readback_file_changed");
|
|
await assertParent(); input.signal?.throwIfAborted();
|
|
await link(file, target);
|
|
} finally { await handle.close(); }
|
|
return ref;
|
|
} finally { await rm(scratch, { recursive: true, force: true }); }
|
|
}
|
|
|
|
async function uploadVerifiedWorkspaceSnapshot(input: WorkspaceSnapshotUpload, verify: (ref: WorkspaceSnapshotRef) => Promise<void>,
|
|
options: { acceptServerVerifiedUpload: boolean }): Promise<WorkspaceSnapshotRef> {
|
|
// Reusing an earlier upload still reads it back: time that too.
|
|
const verifyTimed = async (ref: WorkspaceSnapshotRef) => {
|
|
if (input.timing) input.timing.bytes = ref.byteSize;
|
|
await timedStep(input.timing, "verifyMs", "storage.snapshot.verify", () => verify(ref));
|
|
};
|
|
const [row] = await input.db.select().from(executionWorkspaceSnapshots).where(scope(input));
|
|
if (!row) failure("missing");
|
|
if (input.unpublishedRecapture && row!.sourceOperationId !== input.unpublishedRecapture.sourceOperationId) failure("operation_binding_changed");
|
|
if (["uploaded", "committed", "superseded"].includes(row!.status)) {
|
|
const saved = reference(row!);
|
|
if (saved.manifestDigest !== input.manifestDigest) failure("operation_content_changed");
|
|
await verifyTimed(saved); return saved;
|
|
}
|
|
if (row!.status !== "pending" || !/^[a-f0-9]{64}$/.test(input.manifestDigest)) failure("not_writable");
|
|
const recapture = Boolean(input.unpublishedRecapture);
|
|
const requireUnpublished = (current: SnapshotRow) => {
|
|
if (current.sourceOperationId !== input.unpublishedRecapture!.sourceOperationId
|
|
|| current.objectKey !== null || current.sha256 !== null || current.byteSize !== null
|
|
|| current.key !== null || current.manifestDigest !== null) failure("not_unpublished");
|
|
};
|
|
if (recapture) requireUnpublished(row!);
|
|
const identity = { id: row!.id, companyId: row!.companyId, workspaceId: row!.executionWorkspaceId, generation: row!.generation };
|
|
const publish = async (attempt: UploadAttempt) => {
|
|
const updated = await input.db.transaction(async tx => {
|
|
await notifyRemoteWorkspaceSnapshots(tx, `workspace:${input.workspaceId}`);
|
|
return (await tx.update(executionWorkspaceSnapshots).set({ ...attempt, status: "uploaded", updatedAt: new Date() })
|
|
.where(and(scope(input), eq(executionWorkspaceSnapshots.status, "pending"))).returning())[0];
|
|
});
|
|
const winning = updated ?? (await input.db.select().from(executionWorkspaceSnapshots).where(scope(input)))[0];
|
|
if (!winning || !["uploaded", "committed", "superseded"].includes(winning.status)) failure("publication_changed");
|
|
const saved = reference(winning!);
|
|
if (updated) await abortSnapshotAttemptUploads(input.storage, saved.companyId, snapshotAttemptKeys(updated));
|
|
if (!recapture && saved.manifestDigest !== input.manifestDigest) failure("operation_content_changed");
|
|
if (saved.objectKey !== attempt.objectKey) await verifyTimed(saved);
|
|
return saved;
|
|
};
|
|
// Recover a completed upload even when the previous process lost its reply
|
|
// and its scratch directory. Failed attempts remain referenced for cleanup.
|
|
const availableAttempt = async (attempts: UploadAttempt[]) => {
|
|
for (const attempt of attempts) {
|
|
input.signal?.throwIfAborted();
|
|
if (!recapture && attempt.manifestDigest !== input.manifestDigest) failure("operation_content_changed");
|
|
const ref = { schema: SCHEMA, ...identity, ...attempt } as WorkspaceSnapshotRef;
|
|
validateReference(ref);
|
|
if ((await input.storage.headObject(ref.companyId, ref.objectKey, { signal: input.signal })).exists) {
|
|
await verifyTimed(ref); return attempt;
|
|
}
|
|
}
|
|
return null;
|
|
};
|
|
const attempts = Array.isArray(row!.metadata?.uploads) ? row!.metadata!.uploads as UploadAttempt[] : [];
|
|
const available = await timedStep(input.timing, "priorAttemptCheckMs", "storage.snapshot.prior_attempts", () => availableAttempt(attempts));
|
|
if (available) return publish(available);
|
|
const scratch = await mkdtemp(path.join(os.tmpdir(), "pc-workspace-encrypt-"));
|
|
try {
|
|
const encrypted = path.join(scratch, "archive.encrypted"), dataKey = randomBytes(32), iv = randomBytes(12);
|
|
// One read of the archive digests it, encrypts it and digests the stored
|
|
// bytes, on a worker thread so the server's thread stays free. An unchanged
|
|
// file identity across that read replaces the separate digest pass.
|
|
const before = await lstat(input.archivePath);
|
|
const sealed = await timedStep(input.timing, "encryptMs", "storage.snapshot.encrypt", () => encryptFileOffThread({
|
|
source: input.archivePath, target: encrypted, prefix: Buffer.concat([MAGIC, iv]), key: dataKey, iv, aad: aad(identity),
|
|
}, input.signal));
|
|
const after = await lstat(input.archivePath);
|
|
if (!before.isFile() || before.isSymbolicLink() || sealed.plaintextBytes !== before.size || after.dev !== before.dev || after.ino !== before.ino
|
|
|| after.size !== before.size || after.mtimeMs !== before.mtimeMs || after.ctimeMs !== before.ctimeMs) failure("archive_changed");
|
|
const plaintext = { sha256: sealed.plaintextSha256, byteSize: sealed.plaintextBytes };
|
|
const { material } = await localEncryptedProvider.createVersion({ value: JSON.stringify({ schema: KEY_SCHEMA,
|
|
...identity, dataKey: dataKey.toString("base64"), plaintextSha256: plaintext.sha256, plaintextBytes: plaintext.byteSize }) });
|
|
dataKey.fill(0);
|
|
const content = await timedStep(input.timing, "digestMs", "storage.snapshot.digest", async () => ({
|
|
sha256: sealed.sha256, byteSize: sealed.byteSize,
|
|
}));
|
|
if (input.timing) input.timing.bytes = content.byteSize;
|
|
const attempt: UploadAttempt = { objectKey: `${identity.companyId}/workspace-snapshots/${identity.workspaceId}/${identity.id}/${randomUUID()}.pcws`,
|
|
...content, key: material, manifestDigest: input.manifestDigest };
|
|
// Recheck after encryption, then bind admission to the unchanged ledger.
|
|
// Remote I/O stays outside the row lock. An older upload completing after
|
|
// this check can still win the pending-to-uploaded publication below.
|
|
if (recapture) {
|
|
const recovered = await availableAttempt(attempts);
|
|
if (recovered) return publish(recovered);
|
|
}
|
|
const recorded = await input.db.transaction(async tx => {
|
|
const [current] = await tx.select().from(executionWorkspaceSnapshots).where(scope(input)).for("update");
|
|
if (!current || current.status !== "pending") return null;
|
|
const previous = Array.isArray(current.metadata?.uploads) ? current.metadata.uploads as UploadAttempt[] : [];
|
|
if (recapture) {
|
|
requireUnpublished(current);
|
|
if (!isDeepStrictEqual(previous, attempts)) failure("upload_attempts_changed");
|
|
} else if (previous.some(saved => saved.manifestDigest !== input.manifestDigest)) failure("operation_content_changed");
|
|
await notifyRemoteWorkspaceSnapshots(tx, `workspace:${input.workspaceId}`);
|
|
await tx.update(executionWorkspaceSnapshots).set({ metadata: { ...current.metadata, uploads: [...previous, attempt] }, updatedAt: new Date() }).where(scope(input));
|
|
return true;
|
|
});
|
|
if (!recorded) {
|
|
const saved = await getWorkspaceSnapshot(input.db, input);
|
|
if (!saved || (!recapture && saved.manifestDigest !== input.manifestDigest)) failure("publication_changed");
|
|
await verifyTimed(saved); return saved;
|
|
}
|
|
// The object key is unique per attempt, so a late losing uploader cannot
|
|
// overwrite an object already used by a committed generation.
|
|
let stored: Awaited<ReturnType<StorageService["putFile"]>>;
|
|
try {
|
|
stored = await timedStep(input.timing, "putMs", "storage.snapshot.put", () => input.storage.putFile({ companyId: identity.companyId, namespace: "workspace-snapshots", objectKey: attempt.objectKey,
|
|
originalFilename: null, contentType: "application/octet-stream", body: createReadStream(encrypted, { highWaterMark: WORKSPACE_ARCHIVE_IO_BUFFER_BYTES }),
|
|
byteSize: attempt.byteSize, sha256: attempt.sha256, sourceFile: encrypted, signal: input.signal }));
|
|
} catch (error) {
|
|
if (input.signal?.aborted) throw error;
|
|
const saved = await getWorkspaceSnapshot(input.db, input);
|
|
if (!saved || (!recapture && saved.manifestDigest !== input.manifestDigest)) throw error;
|
|
await verifyTimed(saved); return saved;
|
|
}
|
|
const uploaded = { schema: SCHEMA, ...identity, ...attempt } as WorkspaceSnapshotRef;
|
|
// The backend checked every part of this upload against digests of these
|
|
// exact bytes, so only its size needs confirming. Any other provider, and
|
|
// a caller that needs the bytes back, still reads the object back.
|
|
await timedStep(input.timing, "verifyMs", "storage.snapshot.verify", () =>
|
|
options.acceptServerVerifiedUpload && stored.integrity === "server_verified_md5"
|
|
? verifyStoredSize(input.storage, uploaded, input.signal) : verify(uploaded));
|
|
if (recapture) {
|
|
const recovered = await availableAttempt(attempts);
|
|
if (recovered) return publish(recovered);
|
|
}
|
|
return await publish(attempt);
|
|
} finally { await rm(scratch, { recursive: true, force: true }); }
|
|
}
|
|
|
|
async function snapshotKey(ref: WorkspaceSnapshotRef) {
|
|
validateReference(ref);
|
|
const wrapped = JSON.parse(await localEncryptedProvider.resolveVersion({ material: ref.key, externalRef: null }));
|
|
if (wrapped.schema !== KEY_SCHEMA || wrapped.companyId !== ref.companyId || wrapped.workspaceId !== ref.workspaceId
|
|
|| wrapped.id !== ref.id || wrapped.generation !== ref.generation || !/^[a-f0-9]{64}$/.test(wrapped.plaintextSha256 ?? "")
|
|
|| !Number.isSafeInteger(wrapped.plaintextBytes) || wrapped.plaintextBytes < 0) failure("key_binding_invalid");
|
|
return wrapped;
|
|
}
|
|
|
|
export async function assertWorkspaceSnapshotKeyReadable(reference: WorkspaceSnapshotRef): Promise<void> {
|
|
await snapshotKey(reference);
|
|
}
|
|
|
|
/** Authentication finishes in private scratch before any plaintext is published. */
|
|
export async function loadWorkspaceSnapshotArchive(input: {
|
|
storage: StorageService; reference: WorkspaceSnapshotRef; targetPath: string; signal?: AbortSignal; temporaryParent?: string;
|
|
/** Receives per-step durations and storage request counts. */
|
|
timing?: WorkspaceSnapshotStorageTiming;
|
|
}): Promise<void> {
|
|
return withRequestStats(input.timing, () => waitOutStorageOutages(() => storageOutageWaitFor("restoring the workspace", () => loadWorkspaceSnapshotArchiveTimed(input))));
|
|
}
|
|
|
|
async function loadWorkspaceSnapshotArchiveTimed(input: Parameters<typeof loadWorkspaceSnapshotArchive>[0]): Promise<void> {
|
|
input.signal?.throwIfAborted();
|
|
const ref = input.reference, wrapped = await snapshotKey(ref);
|
|
const scratch = await mkdtemp(path.join(input.temporaryParent ?? os.tmpdir(), "pc-workspace-decrypt-"));
|
|
try {
|
|
input.signal?.throwIfAborted();
|
|
const ciphertext = path.join(scratch, "ciphertext"), plaintext = path.join(scratch, "plaintext");
|
|
let received = 0;
|
|
const stalled = new DOMException("remote_workspace_snapshot_download_stalled", "TimeoutError");
|
|
const idle = new AbortController();
|
|
const signal = input.signal ? AbortSignal.any([input.signal, idle.signal]) : idle.signal;
|
|
const timer = setTimeout(() => idle.abort(stalled), DOWNLOAD_IDLE_TIMEOUT_MS);
|
|
timer.unref();
|
|
try {
|
|
let attempts = 0;
|
|
await timedStep(input.timing, "downloadMs", "storage.snapshot.download", () => sendThroughStorageOutage(async () => {
|
|
if (attempts++ > 0) {
|
|
timer.refresh();
|
|
received = 0;
|
|
await rm(ciphertext, { force: true });
|
|
}
|
|
const object = await input.storage.getObject(ref.companyId, ref.objectKey, { signal });
|
|
const bounded = new Transform({ transform(bytes, _encoding, callback) {
|
|
if (bytes.length > 0) timer.refresh();
|
|
received += bytes.length;
|
|
callback(received > ref.byteSize ? new Error("remote_workspace_snapshot_object_size_mismatch") : null, bytes);
|
|
} });
|
|
try { await pipeline(object.stream, bounded, createWriteStream(ciphertext, { flags: "wx", mode: 0o600, highWaterMark: WORKSPACE_ARCHIVE_IO_BUFFER_BYTES }), { signal }); }
|
|
finally { object.stream.destroy(); }
|
|
}, signal));
|
|
if (input.timing) input.timing.bytes = received;
|
|
} catch (error) {
|
|
if (signal.aborted && signal.reason === stalled) throw isStorageUnavailableError(error)
|
|
? Object.assign(new DOMException(stalled.message, stalled.name), { cause: error }) : stalled;
|
|
throw error;
|
|
} finally { clearTimeout(timer); }
|
|
if (received !== ref.byteSize) failure("object_hash_mismatch");
|
|
const file = await open(ciphertext, "r"), header = Buffer.alloc(MAGIC.length + 12), tag = Buffer.alloc(16);
|
|
try { await file.read(header, 0, header.length, 0); await file.read(tag, 0, tag.length, ref.byteSize - tag.length); } finally { await file.close(); }
|
|
const key = Buffer.from(wrapped.dataKey, "base64");
|
|
// The downloaded object is digested and its ciphertext is decrypted into
|
|
// private scratch at the same time, on worker threads. Nothing they
|
|
// produced is used until the checks below pass, in the order they have
|
|
// always run. Both jobs end before the scratch files are removed.
|
|
let stored: FileDigest, opened: FileDecryption | undefined;
|
|
try {
|
|
[stored, opened] = await timedStep(input.timing, "decryptMs", "storage.snapshot.decrypt", async () => {
|
|
const [digested, decrypted] = await Promise.allSettled([
|
|
digestFileOffThread({ file: ciphertext, algorithm: "sha256" }, input.signal),
|
|
key.length === 32 ? decryptFileOffThread({ source: ciphertext, target: plaintext, start: header.length,
|
|
end: ref.byteSize - tag.length, key, iv: header.subarray(MAGIC.length), aad: aad(ref), authTag: tag }, input.signal) : undefined,
|
|
]);
|
|
if (digested.status === "rejected") throw digested.reason;
|
|
if (decrypted.status === "rejected") throw decrypted.reason;
|
|
return [digested.value, decrypted.value] as const;
|
|
});
|
|
} finally { key.fill(0); }
|
|
if (stored.bytes !== ref.byteSize || stored.hex !== ref.sha256) failure("object_hash_mismatch");
|
|
if (!header.subarray(0, MAGIC.length).equals(MAGIC)) failure("ciphertext_header_invalid");
|
|
if (!opened) failure("key_invalid");
|
|
if (opened!.authenticationFailure) throw Object.assign(new Error(opened!.authenticationFailure.message),
|
|
opened!.authenticationFailure.code ? { code: opened!.authenticationFailure.code } : {});
|
|
// The authenticated archive is digested while it is copied beside the
|
|
// destination, so the digest covers exactly the bytes that get published.
|
|
// Publication never replaces an existing destination, and a failed or
|
|
// cancelled relay cannot leave a plaintext cache that looks complete.
|
|
const staged = path.join(path.dirname(input.targetPath), `.workspace-snapshot-${randomUUID()}.tmp`);
|
|
try {
|
|
const actual = await timedStep(input.timing, "plaintextVerifyMs", "storage.snapshot.verify_plaintext", () =>
|
|
digestFileOffThread({ file: plaintext, algorithm: "sha256", copyTo: staged }, input.signal));
|
|
if (actual.hex !== wrapped.plaintextSha256 || actual.bytes !== wrapped.plaintextBytes) failure("plaintext_hash_mismatch");
|
|
await timedStep(input.timing, "publishMs", "storage.snapshot.publish", async () => {
|
|
input.signal?.throwIfAborted(); await link(staged, input.targetPath);
|
|
});
|
|
} finally { await rm(staged, { force: true }); }
|
|
} finally { await rm(scratch, { recursive: true, force: true }); }
|
|
}
|
|
|
|
const GCM_HEADER_BYTES = MAGIC.length + 12;
|
|
const GCM_TAG_BYTES = 16;
|
|
const CTR_BLOCK_BYTES = 16;
|
|
const GCM_MAX_PLAINTEXT_BYTES = (2 ** 32 - 2) * CTR_BLOCK_BYTES;
|
|
|
|
export interface WorkspaceSnapshotRanges {
|
|
plaintextBytes: number;
|
|
plaintextSha256: string;
|
|
read(start: number, length: number, signal?: AbortSignal): Promise<Readable>;
|
|
close(): void;
|
|
}
|
|
|
|
export async function openWorkspaceSnapshotRanges(input: {
|
|
storage: StorageService; reference: WorkspaceSnapshotRef; signal?: AbortSignal; idleTimeoutMs?: number;
|
|
}): Promise<WorkspaceSnapshotRanges> {
|
|
input.signal?.throwIfAborted();
|
|
const idleTimeoutMs = input.idleTimeoutMs ?? DOWNLOAD_IDLE_TIMEOUT_MS;
|
|
const ref = input.reference, wrapped = await snapshotKey(ref);
|
|
if (ref.byteSize !== GCM_HEADER_BYTES + wrapped.plaintextBytes + GCM_TAG_BYTES
|
|
|| wrapped.plaintextBytes > GCM_MAX_PLAINTEXT_BYTES) failure("object_size_mismatch");
|
|
const header = Buffer.concat(await collect(await openObjectRange(input.storage, ref, 0, GCM_HEADER_BYTES, idleTimeoutMs, input.signal),
|
|
GCM_HEADER_BYTES));
|
|
if (header.length !== GCM_HEADER_BYTES) failure("range_truncated");
|
|
if (!header.subarray(0, MAGIC.length).equals(MAGIC)) failure("ciphertext_header_invalid");
|
|
const iv = header.subarray(MAGIC.length);
|
|
const key = Buffer.from(wrapped.dataKey, "base64");
|
|
if (key.length !== 32) { key.fill(0); failure("key_invalid"); }
|
|
let closed = false;
|
|
return {
|
|
plaintextBytes: wrapped.plaintextBytes,
|
|
plaintextSha256: wrapped.plaintextSha256,
|
|
async read(start, length, signal) {
|
|
if (closed) failure("ranges_closed");
|
|
if (!Number.isSafeInteger(start) || !Number.isSafeInteger(length) || start < 0 || length < 0
|
|
|| start + length > wrapped.plaintextBytes) failure("range_invalid");
|
|
if (length === 0) return Readable.from([]);
|
|
const block = Math.floor(start / CTR_BLOCK_BYTES), skip = start - block * CTR_BLOCK_BYTES;
|
|
const counter = Buffer.alloc(16); iv.copy(counter, 0); counter.writeUInt32BE(2 + block, 12);
|
|
const ciphertext = await openObjectRange(input.storage, ref, GCM_HEADER_BYTES + block * CTR_BLOCK_BYTES,
|
|
skip + length, idleTimeoutMs, signal);
|
|
let skipped = 0, emitted = 0;
|
|
const bounded = new Transform({ transform(bytes: Buffer, _encoding, callback) {
|
|
let part = bytes;
|
|
if (skipped < skip) { const drop = Math.min(skip - skipped, part.length); skipped += drop; part = part.subarray(drop); }
|
|
const room = length - emitted;
|
|
if (part.length > room) part = part.subarray(0, room);
|
|
emitted += part.length;
|
|
callback(null, part.length ? part : undefined);
|
|
}, flush(callback) { callback(emitted === length ? null : new Error("remote_workspace_snapshot_range_truncated")); } });
|
|
return streamPipeline(ciphertext, createDecipheriv("aes-256-ctr", key, counter), bounded, () => undefined);
|
|
},
|
|
close() { closed = true; key.fill(0); },
|
|
};
|
|
}
|
|
|
|
async function openObjectRange(storage: StorageService, ref: WorkspaceSnapshotRef, start: number, length: number,
|
|
idleTimeoutMs: number, signal?: AbortSignal): Promise<Readable> {
|
|
const stalled = new Error("remote_workspace_snapshot_download_stalled");
|
|
const idle = new AbortController();
|
|
let timer = setTimeout(() => idle.abort(stalled), idleTimeoutMs);
|
|
timer.unref();
|
|
const combined = signal ? AbortSignal.any([signal, idle.signal]) : idle.signal;
|
|
let object: Awaited<ReturnType<StorageService["getObject"]>>;
|
|
try {
|
|
object = await sendThroughStorageOutage(() => storage.getObject(ref.companyId, ref.objectKey, {
|
|
range: { start, end: start + length - 1 }, signal: combined }), combined);
|
|
} catch (error) { clearTimeout(timer); throw idle.signal.aborted ? stalled : error; }
|
|
let received = 0;
|
|
const guard = new Transform({ transform(bytes: Buffer, _encoding, callback) {
|
|
timer.refresh();
|
|
received += bytes.length;
|
|
callback(received > length ? new Error("remote_workspace_snapshot_object_size_mismatch") : null, bytes);
|
|
} });
|
|
const output = streamPipeline(object.stream, guard, () => clearTimeout(timer));
|
|
clearTimeout(timer);
|
|
timer = setTimeout(() => output.destroy(stalled), idleTimeoutMs);
|
|
timer.unref();
|
|
output.once("close", () => clearTimeout(timer));
|
|
return output;
|
|
}
|
|
|
|
async function collect(stream: Readable, limit: number): Promise<Buffer[]> {
|
|
const chunks: Buffer[] = [];
|
|
let size = 0;
|
|
try {
|
|
for await (const chunk of stream) {
|
|
const bytes = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);
|
|
size += bytes.length;
|
|
if (size > limit) failure("object_size_mismatch");
|
|
chunks.push(bytes);
|
|
}
|
|
} finally { stream.destroy(); }
|
|
return chunks;
|
|
}
|