Files
Shade/packages/shade-files/src/client/upload-directory.ts

311 lines
10 KiB
TypeScript
Raw Normal View History

feat(files): @shade/files 0.3.0 — E2EE filesystem RPC primitive M-Files-1..6 land the full files-RPC layer + everything 0.3.0 needs to ship. Apps keep their own UI; this layer ships the typed RPC, the streams bridge for content I/O, and production hooks (rate limit, retention, fingerprint gate, metrics). @shade/files (NEW) - Standard ops: list/stat/mkdir/delete/move/read/write/getThumbnail with Zod-validated wire schemas + clean user-handler types. - Custom ops: typed via TypeScript declaration merging on CustomOpsMap + per-op Zod schemas; client.custom('app.foo', {...}) is fully typed. - Content I/O: inline (≤ 256 KiB plaintext) base64-in-RPC; streams (> 256 KiB) ride @shade/transfer via userMetadata.shadeFilesWriteId / shadeFilesReadStreamId correlation. Server-side TransformStream bridges accept inbound transfers immediately (engine rejects chunks that arrive before accept) and park the readable for the matching RPC. - Directory ops: walk(path, opts) async-iterable depth-first walker; uploadDirectory()/downloadDirectory() with bounded concurrency pool (default 4, cap 16), aggregated progress, abort. - Production hooks (callback-based, vendor-neutral): rate-limit (op + byte), idempotency cache (LRU + TTL + in-flight de-dupe), path policy (traversal + percent-decode hardening), fingerprint gate (required/optional/reject), pluggable Ed25519 sig verification with ±5 min replay window, onMetric sink (standard names). - React hooks (subpath @shade/files/react): ShadeFilesProvider, useShadeFiles, useFileList, useFileTransfer/Upload/Download. - Shade.files.serve(handler) + Shade.files.client(peer) high-level entrypoint in @shade/sdk; lazy + memoized; one handler per Shade. Wire format bump - @shade/proto wire VERSION 0x01 → 0x02. Length prefixes changed from u16 to u32. The previous u16 silently truncated payloads above 64 KiB — a hard correctness ceiling that blocked inline file ops up to 256 KiB. Wire-incompatible with 0.2.x peers; new sessions only. Cross-platform Kotlin port (android/shade-android) updated to match; test-vectors/wire-format.json regenerated. Concurrency safety - ShadeSessionManager.encrypt/.decrypt now run under per-peer mutex. Concurrent decryptions of the same peer raced ratchet state (manifested as sporadic "Failed to decrypt — wrong key or tampered data" under load — surfaced once concurrent uploadDirectory pumped many writes in flight). Encrypt was already serialized via Shade.send's encryptChains; decrypt is now serialized at the manager layer too. @shade/streams extension - StreamMetadata.userMetadata?: Record<string, string> for application-level key/value pairs that round-trip verbatim through stream-init plaintext. Used by @shade/files for write/read correlation; available to any consumer. @shade/sdk extension - Shade.files getter (lazy + memoized). - BackgroundHooks.onPruneFiles + periodic timer (default 5 min) + BackgroundTasks.setHook(name, fn) for runtime hook registration. Bundles in-flight 0.2.0 work - packages/shade-streams/, packages/shade-transfer/, related shade-sdk streams-bridge + shade-widgets transfer hooks were uncommitted prior to this session. Including them keeps the workspace consistent at 0.3.0 since @shade/files depends on them. Tests - 74 new tests in @shade/files (572 → 646 workspace pass; 0 fail; 3× stable). Coverage spans unit (inline-threshold + concurrency), integration (read-write inline + streams up to 1 MiB, walk + upload/download directory, custom-op, metrics, SDK namespace end-to-end), and security (tampered-envelope sig verification, replay window, fingerprint gate, rate-limit + quota). Release artifacts - All packages bumped to 0.3.0 via scripts/bump-version.ts. - scripts/publish-all.ts PACKAGES updated with shade-files in topological order (after shade-transfer, before shade-sdk). - bun run publish:dry clean (14 packed, 0 failed). - examples/08-files-browser/ — three-process CLI demo (prekey + Bob server + Alice CLI) covering list/stat/mkdir/delete/upload/download. - docs/files.md — full API + design doc. - CHANGELOG.md 0.3.0 entry. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-02 14:00:01 +02:00
/**
* Upload an entire local directory tree to a remote peer via a `FileClient`.
*
* Walks the local `DirectoryHandleLike` lazily, creates remote directories
* via `client.mkdir({ recursive: true })`, and uploads each file with
* `client.write` (which routes inline or streams based on size). A bounded
* concurrency pool keeps memory and inflight RPCs in check.
*
* Returns a `BulkTransferHandle` whose `events` stream emits `'plan'`,
* `'file-start'`, `'file-progress'` (currently emitted at file start +
* end), `'file-done'` / `'file-error'`, aggregate `'progress'`, and a
* final `'complete'` (or `'abort'`).
*/
import { posixJoin } from '../utils/path.js';
import { runWithConcurrency } from './concurrency.js';
import type { FileClient } from './client.js';
import {
DEFAULT_BULK_CONCURRENCY,
MAX_BULK_CONCURRENCY,
type BulkOpts,
type BulkTransferEvent,
type BulkTransferHandle,
type BulkTransferResult,
type DirectoryHandleLike,
type FileHandleLike,
} from './directory-types.js';
import { CancelledError } from '../schemas/errors.js';
interface PlannedFile {
/** Local file handle. */
handle: FileHandleLike;
/** Path relative to the upload root. */
relativePath: string;
/** Absolute remote path. */
remoteAbsPath: string;
}
interface PlannedDir {
remoteAbsPath: string;
}
export interface UploadDirectoryOptions extends BulkOpts {
/**
* Pre-create remote directories before uploading files. Default true.
* Disable if the server-side `write` already mkdir-p's parents.
*/
precreateDirs?: boolean;
}
export function uploadDirectory(
client: Pick<FileClient, 'write' | 'mkdir'>,
local: DirectoryHandleLike,
remoteRoot: string,
opts: UploadDirectoryOptions = {},
): BulkTransferHandle {
const concurrency = Math.max(
1,
Math.min(MAX_BULK_CONCURRENCY, opts.concurrency ?? DEFAULT_BULK_CONCURRENCY),
);
const precreateDirs = opts.precreateDirs ?? true;
const continueOnError = opts.continueOnError ?? false;
const externalSignal = opts.signal;
const internalAbort = new AbortController();
const combinedSignal = mergeSignals(externalSignal, internalAbort.signal);
const events: BulkTransferEvent[] = [];
const eventResolvers: ((v: IteratorResult<BulkTransferEvent>) => void)[] = [];
let eventsClosed = false;
function emit(event: BulkTransferEvent): void {
if (eventsClosed) return;
if (eventResolvers.length > 0) {
eventResolvers.shift()!({ value: event, done: false });
} else {
events.push(event);
}
}
function closeEvents(): void {
if (eventsClosed) return;
eventsClosed = true;
while (eventResolvers.length > 0) {
eventResolvers.shift()!({ value: undefined as never, done: true });
}
}
let resolveDone!: (r: BulkTransferResult) => void;
let rejectDone!: (err: unknown) => void;
const donePromise = new Promise<BulkTransferResult>((resolve, reject) => {
resolveDone = resolve;
rejectDone = reject;
});
const startedAt = Date.now();
let filesDone = 0;
let bytesDone = 0;
let bytesTotal = 0;
// Run the upload pipeline asynchronously.
void (async () => {
try {
// 1. Plan: walk local tree, collect dirs + files
const plannedDirs: PlannedDir[] = [];
const plannedFiles: PlannedFile[] = [];
try {
await collect(local, '', remoteRoot, plannedDirs, plannedFiles, combinedSignal);
} catch (err) {
emit({ type: 'abort', reason: errMsg(err) });
closeEvents();
rejectDone(err);
return;
}
const totalFiles = plannedFiles.length;
bytesTotal = plannedFiles.reduce(
(acc, f) => acc + (f.handle as FileHandleLike & { _size?: number })._size!,
0,
);
// Note: bytesTotal is computed lazily in collect() via cached sizes.
emit({ type: 'plan', totalFiles, totalBytes: bytesTotal });
if (combinedSignal.aborted) {
emit({ type: 'abort', reason: errMsg(combinedSignal.reason) });
closeEvents();
rejectDone(combinedSignal.reason ?? new CancelledError());
return;
}
// 2. Pre-create remote directories sequentially (cheap, avoids races
// when many uploads target the same parent).
if (precreateDirs) {
for (const d of plannedDirs) {
if (combinedSignal.aborted) break;
try {
await client.mkdir(d.remoteAbsPath, { recursive: true });
} catch (err) {
if (!isAlreadyExistsError(err)) {
if (!continueOnError) {
emit({ type: 'abort', reason: errMsg(err) });
closeEvents();
rejectDone(err);
return;
}
}
}
}
}
// 3. Upload files with bounded concurrency
try {
await runWithConcurrency(
asyncIterableOf(plannedFiles),
async (planned) => {
if (combinedSignal.aborted) {
throw new CancelledError('upload aborted');
}
const file = await planned.handle.getFile();
const size = file.size;
emit({ type: 'file-start', path: planned.relativePath, size });
try {
const writeOpts: { contentType?: string; signal?: AbortSignal } = {};
if (file.type !== '') writeOpts.contentType = file.type;
writeOpts.signal = combinedSignal;
if (size === 0) {
// Edge case: empty file — write empty buffer.
await client.write(planned.remoteAbsPath, new Uint8Array(0), writeOpts);
} else {
await client.write(
planned.remoteAbsPath,
{ stream: file.stream(), size, ...(file.type !== '' ? { contentType: file.type } : {}) },
writeOpts,
);
}
filesDone++;
bytesDone += size;
emit({ type: 'file-done', path: planned.relativePath, bytesDone: size });
emit({
type: 'progress',
filesDone,
filesTotal: totalFiles,
bytesDone,
bytesTotal,
});
} catch (err) {
emit({ type: 'file-error', path: planned.relativePath, error: err });
throw err;
}
},
{
concurrency,
signal: combinedSignal,
continueOnError,
onError: () => {
/* already emitted as 'file-error' */
},
},
);
} catch (err) {
emit({ type: 'abort', reason: errMsg(err) });
closeEvents();
rejectDone(err);
return;
}
const durationMs = Date.now() - startedAt;
emit({ type: 'complete', filesDone, bytesDone, durationMs });
closeEvents();
resolveDone({ filesDone, bytesDone, durationMs });
} catch (err) {
// Belt-and-suspenders: any unhandled error reaches here.
closeEvents();
rejectDone(err);
}
})();
// Suppress unhandled-rejection until consumer awaits done().
donePromise.catch(() => {
/* deliberate */
});
return {
events: {
[Symbol.asyncIterator]() {
return {
next(): Promise<IteratorResult<BulkTransferEvent>> {
if (events.length > 0) {
return Promise.resolve({ value: events.shift()!, done: false });
}
if (eventsClosed) {
return Promise.resolve({ value: undefined as never, done: true });
}
return new Promise((resolve) => eventResolvers.push(resolve));
},
return(): Promise<IteratorResult<BulkTransferEvent>> {
// Caller broke out — stop iterating but keep the bulk going.
return Promise.resolve({ value: undefined as never, done: true });
},
};
},
},
async abort(reason) {
internalAbort.abort(new CancelledError(reason ?? 'manual abort'));
},
done: () => donePromise,
};
}
// ─── Helpers ─────────────────────────────────────────────────
async function collect(
dir: DirectoryHandleLike,
relPrefix: string,
remoteRoot: string,
plannedDirs: PlannedDir[],
plannedFiles: PlannedFile[],
signal: AbortSignal,
): Promise<void> {
for await (const [name, handle] of dir.entries()) {
if (signal.aborted) return;
const relPath = relPrefix === '' ? name : `${relPrefix}/${name}`;
if (handle.kind === 'directory') {
const remoteAbs = posixJoin(remoteRoot, relPath);
plannedDirs.push({ remoteAbsPath: remoteAbs });
await collect(handle as DirectoryHandleLike, relPath, remoteRoot, plannedDirs, plannedFiles, signal);
} else {
// Cache size on the handle so the planning total is accurate.
const file = await (handle as FileHandleLike).getFile();
(handle as FileHandleLike & { _size?: number })._size = file.size;
plannedFiles.push({
handle: handle as FileHandleLike,
relativePath: relPath,
remoteAbsPath: posixJoin(remoteRoot, relPath),
});
}
}
}
async function* asyncIterableOf<T>(arr: T[]): AsyncIterable<T> {
for (const item of arr) yield item;
}
function isAlreadyExistsError(err: unknown): boolean {
if (err === null || typeof err !== 'object') return false;
const code = (err as { code?: string; payload?: { code?: string } }).code;
if (code === 'SHADE_FS_CONFLICT') return true;
const payloadCode = (err as { payload?: { code?: string } }).payload?.code;
return payloadCode === 'CONFLICT';
}
function errMsg(err: unknown): string {
if (err instanceof Error) return err.message;
return String(err ?? 'unknown error');
}
function mergeSignals(
external: AbortSignal | undefined,
internal: AbortSignal,
): AbortSignal {
if (external === undefined) return internal;
if (external.aborted) return external;
const controller = new AbortController();
const onAbort = (sig: AbortSignal): void => {
controller.abort(sig.reason);
};
external.addEventListener('abort', () => onAbort(external), { once: true });
internal.addEventListener('abort', () => onAbort(internal), { once: true });
return controller.signal;
}