feat(storage): settings-backed registry, StorageService facade, module wiring

This commit is contained in:
jubnl
2026-08-16 00:21:22 +02:00
parent 09d27d633a
commit 75d5bbcfc2
6 changed files with 1011 additions and 1 deletions
+2 -1
View File
@@ -46,6 +46,7 @@ import { TripInviteModule } from './trip-invite/trip-invite.module';
import { TransitModule } from './transit/transit.module';
import { FeedsModule } from './feeds/feeds.module';
import { SettingsModule } from './settings/settings.module';
import { StorageModule } from './storage/storage.module';
import { BackupModule } from './backup/backup.module';
import { BookingImportModule } from './booking-import/booking-import.module';
import { ReservationImportModule } from './reservation-import/reservation-import.module';
@@ -74,7 +75,7 @@ import { RealtimeGatewayModule } from './realtime/realtime-gateway.module';
* migrated.
*/
@Module({
imports: [AppConfigModule, DatabaseModule, RealtimeModule, RealtimeGatewayModule, SchedulingModule, McpModule.forRoot({ accessPolicy: trekMcpAccessPolicy, validateAccess: trekMcpValidateAccess }), HealthModule, PlatformModule, McpTransportModule, WeatherModule, HelpModule, AirportsModule, ConfigModule, SystemNoticesModule, GeoModule, MapsModule, PlaceEnrichmentModule, CategoriesModule, TagsModule, NotificationsModule, AtlasModule, VacayModule, PackingModule, TodoModule, BudgetModule, ReservationsModule, DaysModule, DayNotesModule, AccommodationsModule, AssignmentsModule, PlacesModule, TripsModule, CollabModule, FilesModule, PhotosModule, MemoriesModule, AirtrailModule, JourneyModule, CollectionsModule, ShareModule, TripInviteModule, TransitModule, FeedsModule, SettingsModule, BackupModule, AuthModule, OidcModule, OauthModule, AdminModule, AddonsModule, AuditModule, PermissionsModule, PluginsModule, BookingImportModule, ReservationImportModule, LlmParseModule, ManagedExtModule],
imports: [AppConfigModule, DatabaseModule, RealtimeModule, RealtimeGatewayModule, SchedulingModule, McpModule.forRoot({ accessPolicy: trekMcpAccessPolicy, validateAccess: trekMcpValidateAccess }), HealthModule, PlatformModule, McpTransportModule, WeatherModule, HelpModule, AirportsModule, ConfigModule, SystemNoticesModule, GeoModule, MapsModule, PlaceEnrichmentModule, CategoriesModule, TagsModule, NotificationsModule, AtlasModule, VacayModule, PackingModule, TodoModule, BudgetModule, ReservationsModule, DaysModule, DayNotesModule, AccommodationsModule, AssignmentsModule, PlacesModule, TripsModule, CollabModule, FilesModule, PhotosModule, MemoriesModule, AirtrailModule, JourneyModule, CollectionsModule, ShareModule, TripInviteModule, TransitModule, FeedsModule, SettingsModule, StorageModule, BackupModule, AuthModule, OidcModule, OauthModule, AdminModule, AddonsModule, AuditModule, PermissionsModule, PluginsModule, BookingImportModule, ReservationImportModule, LlmParseModule, ManagedExtModule],
providers: [
// Default-deny: a route is authenticated unless it carries @Public() or
// @OptionalAuth(), or declares its own @UseGuards chain. Protection used to
@@ -0,0 +1,280 @@
import fs from 'node:fs';
import { Injectable, Logger, type OnModuleInit } from '@nestjs/common';
import { DatabaseService } from '../database/database.service';
import { RuntimeEnvService } from '../app-config/runtime-env.service';
import { LocalDriver } from './drivers/local.driver';
import { MirrorDriver, type ReplicaFailure } from './drivers/mirror.driver';
import { DEFAULT_BACKUPS_ROOT, DEFAULT_UPLOADS_ROOT, GLOBAL_TEMP_DIR } from './storage-paths';
import {
STORAGE_CATEGORIES,
StorageBackendError,
type StorageCategory,
type StorageDriver,
} from './storage.types';
export interface ResolvedCategory {
driver: StorageDriver;
keyPrefix: string;
backendName: string;
}
interface LocalBackendConfig {
name: string;
type: 'local';
options: { root: string };
}
interface MirrorBackendConfig {
name: string;
type: 'mirror';
options: { primary: string; replicas: string[] };
}
type BackendConfig = LocalBackendConfig | MirrorBackendConfig;
interface RegistryState {
drivers: Map<string, StorageDriver>;
categories: Map<StorageCategory, { backendName: string; keyPrefix: string }>;
}
const BACKENDS_KEY = 'storage.backends';
const CATEGORIES_KEY = 'storage.categories';
const REPLICA_FAILURE_RING_SIZE = 50;
/**
* Category prefixes mirror the current uploads layout 1:1 so local keys map
* to existing paths and no data migration is required. `backups` is bare-key
* (the backend root IS the backups dir — spec rev 3.1), and `photos-google`
* flips to bare keys when it resolves to `place-photos-local` (the relocated
* TREK_PLACE_PHOTO_DIR layout, place-photo-cache.service.ts).
*/
const CATEGORY_PREFIXES: Record<StorageCategory, string> = {
files: 'files/',
journey: 'journey/',
covers: 'covers/',
avatars: 'avatars/',
places: 'places/',
photos: 'photos/',
'photos-google': 'photos/google/',
'photos-trek': 'photos/trek/',
backups: '',
};
/**
* Named backend instances + the category→backend map, config-driven and
* swappable — v1 groundwork for the future admin UI (which becomes a settings
* editor plus a reload() call).
*
* Unlike the codebase default of uncached per-request reads
* (allowed-file-types.service.ts documents that convention), the registry
* holds its validated config in memory and swaps it on reload() — the
* permissions-cache precedent. Rationale: this sits on every byte-serving hot
* path and its config changes only via admin action. Nothing outside this
* class may cache a driver reference; resolution happens per call.
*/
@Injectable()
export class StorageRegistryService implements OnModuleInit {
private readonly logger = new Logger(StorageRegistryService.name);
private state: RegistryState | null = null;
private failures: ReplicaFailure[] = [];
constructor(
private readonly db: DatabaseService,
private readonly env: RuntimeEnvService,
) {}
onModuleInit(): void {
this.load(true);
}
/** Re-read settings, validate, atomically swap. In-flight ops keep their resolved instances. */
reload(): void {
this.load(false);
}
resolve(category: StorageCategory): ResolvedCategory {
if (!this.state) throw new StorageBackendError('storage registry not initialized');
const assignment = this.state.categories.get(category);
if (!assignment) throw new StorageBackendError(`unknown storage category: ${category}`);
const driver = this.state.drivers.get(assignment.backendName);
if (!driver) {
throw new StorageBackendError(`storage backend '${assignment.backendName}' missing for category '${category}'`);
}
return { driver, keyPrefix: assignment.keyPrefix, backendName: assignment.backendName };
}
/** Driver-agnostic global scratch space (data/tmp). */
tempDir(): string {
return GLOBAL_TEMP_DIR;
}
recordReplicaFailure(failure: ReplicaFailure): void {
this.failures.push(failure);
if (this.failures.length > REPLICA_FAILURE_RING_SIZE) {
this.failures = this.failures.slice(-REPLICA_FAILURE_RING_SIZE);
}
}
replicaFailures(): readonly ReplicaFailure[] {
return this.failures;
}
/**
* Invalid settings never take the server down: on any failure the previous
* state is kept (at boot, when there is no previous state, the built-in
* defaults — which cannot be misconfigured — are loaded instead).
*/
private load(boot: boolean): void {
try {
this.state = this.build(this.readSettings(), boot);
} catch (err) {
const keeping = this.state ? 'last-good config' : 'built-in defaults';
this.logger.error(`invalid storage settings — keeping ${keeping}: ${err instanceof Error ? err.message : err}`);
if (!this.state) {
this.state = this.build({ backends: [], categories: {} }, boot);
}
}
}
private readSettings(): { backends: unknown; categories: unknown } {
const read = (key: string): unknown => {
const row = this.db.get<{ value: string }>('SELECT value FROM app_settings WHERE key = ?', key);
return row?.value ? (JSON.parse(row.value) as unknown) : undefined;
};
return { backends: read(BACKENDS_KEY), categories: read(CATEGORIES_KEY) };
}
private build(settings: { backends: unknown; categories: unknown }, boot: boolean): RegistryState {
// 1. Env is read fresh on every load (never snapshotted — RuntimeEnvService rule).
const paths = this.env.env().paths;
const uploadsRoot = paths.uploadsDir || DEFAULT_UPLOADS_ROOT;
const placePhotoDir = paths.placePhotoDir;
// 2. Built-in defaults; settings entries with the same name/category override.
const backends = new Map<string, BackendConfig>();
backends.set('uploads-local', { name: 'uploads-local', type: 'local', options: { root: uploadsRoot } });
backends.set('backups-local', { name: 'backups-local', type: 'local', options: { root: DEFAULT_BACKUPS_ROOT } });
if (placePhotoDir) {
backends.set('place-photos-local', { name: 'place-photos-local', type: 'local', options: { root: placePhotoDir } });
}
for (const config of parseBackendList(settings.backends)) backends.set(config.name, config);
const categoryBackends = new Map<StorageCategory, string>();
for (const category of STORAGE_CATEGORIES) categoryBackends.set(category, 'uploads-local');
categoryBackends.set('backups', 'backups-local');
if (placePhotoDir) categoryBackends.set('photos-google', 'place-photos-local');
for (const [category, backendName] of parseCategoryMap(settings.categories)) {
categoryBackends.set(category, backendName);
}
// 3. Validate the merged config as a whole.
validateConfig(backends, categoryBackends);
// 4. Category prefixes (photos-google mode decided from the final map).
const categories = new Map<StorageCategory, { backendName: string; keyPrefix: string }>();
for (const [category, backendName] of categoryBackends) {
const keyPrefix =
category === 'photos-google' && backendName === 'place-photos-local' ? '' : CATEGORY_PREFIXES[category];
categories.set(category, { backendName, keyPrefix });
}
// 5. Instantiate drivers: locals first (each ensures its own dirs; spool
// cleanup at boot only — a reload() could delete an in-flight upload's
// spool file), then mirrors over the local instances.
const drivers = new Map<string, StorageDriver>();
for (const config of backends.values()) {
if (config.type !== 'local') continue;
const driver = new LocalDriver({ id: config.name, root: config.options.root });
const ensurePrefixes = [...categories.entries()]
.filter(([, assignment]) => assignment.backendName === config.name)
.map(([, assignment]) => assignment.keyPrefix)
.filter((prefix) => prefix !== '');
driver.init({ ensurePrefixes, cleanSpool: boot });
drivers.set(config.name, driver);
}
for (const config of backends.values()) {
if (config.type !== 'mirror') continue;
drivers.set(
config.name,
new MirrorDriver({
id: config.name,
primary: drivers.get(config.options.primary)!,
replicas: config.options.replicas.map((name) => drivers.get(name)!),
tempDir: () => this.tempDir(),
onReplicaFailure: (failure) => this.recordReplicaFailure(failure),
}),
);
}
fs.mkdirSync(GLOBAL_TEMP_DIR, { recursive: true });
// 6. Single-assignment swap — callers mid-operation keep their instances.
return { drivers, categories };
}
}
// ── settings parsing / validation (pure helpers) ──────────────────────────────
function isRecord(value: unknown): value is Record<string, unknown> {
return typeof value === 'object' && value !== null && !Array.isArray(value);
}
function parseBackendList(raw: unknown): BackendConfig[] {
if (raw === undefined) return [];
if (!Array.isArray(raw)) throw new StorageBackendError(`'${BACKENDS_KEY}' must be a JSON array`);
return raw.map((entry): BackendConfig => {
if (!isRecord(entry) || typeof entry.name !== 'string' || !entry.name) {
throw new StorageBackendError(`'${BACKENDS_KEY}' entries need a non-empty string 'name'`);
}
const options = isRecord(entry.options) ? entry.options : {};
if (entry.type === 'local') {
if (typeof options.root !== 'string' || !options.root) {
throw new StorageBackendError(`local backend '${entry.name}' needs a non-empty 'options.root'`);
}
return { name: entry.name, type: 'local', options: { root: options.root } };
}
if (entry.type === 'mirror') {
const replicas = Array.isArray(options.replicas) ? options.replicas : null;
if (typeof options.primary !== 'string' || !replicas || replicas.some((r) => typeof r !== 'string')) {
throw new StorageBackendError(`mirror backend '${entry.name}' needs 'options.primary' and 'options.replicas'`);
}
return { name: entry.name, type: 'mirror', options: { primary: options.primary, replicas: replicas as string[] } };
}
throw new StorageBackendError(`backend '${entry.name}' has unknown type '${String(entry.type)}'`);
});
}
function parseCategoryMap(raw: unknown): Array<[StorageCategory, string]> {
if (raw === undefined) return [];
if (!isRecord(raw)) throw new StorageBackendError(`'${CATEGORIES_KEY}' must be a JSON object`);
return Object.entries(raw).map(([category, backendName]) => {
if (!(STORAGE_CATEGORIES as readonly string[]).includes(category)) {
throw new StorageBackendError(`'${CATEGORIES_KEY}' names unknown category '${category}'`);
}
if (typeof backendName !== 'string' || !backendName) {
throw new StorageBackendError(`category '${category}' must map to a backend name`);
}
return [category as StorageCategory, backendName];
});
}
function validateConfig(backends: Map<string, BackendConfig>, categories: Map<StorageCategory, string>): void {
for (const config of backends.values()) {
if (config.type !== 'mirror') continue;
for (const target of [config.options.primary, ...config.options.replicas]) {
const resolved = backends.get(target);
if (!resolved) {
throw new StorageBackendError(`mirror '${config.name}' references unknown backend '${target}'`);
}
if (resolved.type === 'mirror') {
throw new StorageBackendError(`mirror '${config.name}' nests mirror '${target}' — nesting is rejected`);
}
}
}
for (const [category, backendName] of categories) {
const backend = backends.get(backendName);
if (!backend) {
throw new StorageBackendError(`category '${category}' maps to unknown backend '${backendName}'`);
}
if (backend.type === 'mirror' && category !== 'backups') {
throw new StorageBackendError(`category '${category}' may not use a mirror backend (backups only)`);
}
}
}
+23
View File
@@ -0,0 +1,23 @@
import { Module } from '@nestjs/common';
import { AppConfigModule } from '../app-config/app-config.module';
import { StorageRegistryService } from './storage-registry.service';
import { StorageService } from './storage.service';
/**
* The storage core (spec:
* docs/superpowers/specs/2026-07-20-storage-backend-abstraction-design.md).
* Consuming modules import this explicitly (repo convention — SchedulingModule
* is deliberately not consumed via @Global either); AppConfigModule is listed
* even though it is @Global so an e2e TestingModule built around one domain
* still resolves RuntimeEnvService (the memories.module precedent).
* DatabaseModule IS consumed via @Global, like every other domain.
*
* No controller: v1 has no HTTP surface — the registry's reload() is wired to
* an admin route only when the admin UI lands (Deferred).
*/
@Module({
imports: [AppConfigModule],
providers: [StorageRegistryService, StorageService],
exports: [StorageService],
})
export class StorageModule {}
+178
View File
@@ -0,0 +1,178 @@
import fs from 'node:fs';
import path from 'node:path';
import { randomUUID } from 'node:crypto';
import { pipeline } from 'node:stream/promises';
import type { Readable } from 'node:stream';
import { Injectable } from '@nestjs/common';
import type { Response } from 'express';
import type { ReplicaFailure } from './drivers/mirror.driver';
import { assertValidKey } from './storage-keys';
import { StorageRegistryService } from './storage-registry.service';
import {
StorageNotFoundError,
type ByteRange,
type LocalTempFile,
type ObjectStat,
type PutOptions,
type StorageCategory,
type StorageDriver,
} from './storage.types';
export interface SendOptions {
contentType?: string;
disposition?: string;
}
interface Resolved {
driver: StorageDriver;
keyPrefix: string;
key: string;
}
/**
* The facade all call sites use — and the ONLY entry point: callers address
* storage exclusively as (category, name) on this injected service. They
* never import a driver, never hold a driver or backend reference, and never
* know which instance serves a category — resolution happens inside the
* registry on every call. That is what makes backend reconfiguration a
* config-plus-reload() operation instead of a code change.
*
* `sendToResponse` and `withLocalFile` are the two helpers that make a remote
* backend a driver-only change later: every byte-consumer goes through one of
* them, and each owns the local-fast-path vs stream branch exactly once.
*/
@Injectable()
export class StorageService {
constructor(private readonly registry: StorageRegistryService) {}
/** Driver-agnostic global scratch space (data/tmp). */
tempDir(): string {
return this.registry.tempDir();
}
/** The category backend's same-volume spool dir, else tempDir(). Resolved per call. */
spoolDirFor(category: StorageCategory): string {
return this.registry.resolve(category).driver.getSpoolDir?.() ?? this.tempDir();
}
// The read/write methods are async so key-validation failures surface as
// rejections, never synchronous throws — callers treat storage uniformly.
async put(
category: StorageCategory,
name: string,
source: Readable | LocalTempFile,
opts?: PutOptions,
): Promise<void> {
const { driver, key } = this.resolve(category, name);
return driver.put(key, source, opts);
}
async getStream(
category: StorageCategory,
name: string,
range?: ByteRange,
): Promise<{ stream: Readable; stat: ObjectStat }> {
const { driver, key } = this.resolve(category, name);
return driver.getStream(key, range);
}
async stat(category: StorageCategory, name: string): Promise<ObjectStat | null> {
const { driver, key } = this.resolve(category, name);
return driver.stat(key);
}
async exists(category: StorageCategory, name: string): Promise<boolean> {
return (await this.stat(category, name)) !== null;
}
async delete(category: StorageCategory, name: string): Promise<void> {
const { driver, key } = this.resolve(category, name);
return driver.delete(key);
}
/** Names in and out are category-relative — the key prefix stays a registry detail. */
async *list(category: StorageCategory, subPrefix = ''): AsyncIterable<ObjectStat> {
const { driver, keyPrefix } = this.registry.resolve(category);
for await (const stat of driver.list(keyPrefix + subPrefix)) {
yield { ...stat, key: stat.key.slice(keyPrefix.length) };
}
}
/**
* Serve an object into an Express response. Local backends use the
* root-relative res.sendFile form — absolute paths resolve against the
* rewritten req.url under the ExpressAdapter and spuriously 404
* (files-download.controller.ts) — which brings etag/range/conditional-GET
* for free. Path-less (remote) backends stream-pipe. A miss throws
* StorageNotFoundError: the caller owns the route's miss contract
* (404 envelope, 204-empty, or next()).
*/
async sendToResponse(category: StorageCategory, name: string, res: Response, opts?: SendOptions): Promise<void> {
const { driver, key } = this.resolve(category, name);
const localPath = driver.getLocalPath?.(key) ?? null;
if (localPath !== null) {
if (!(await driver.stat(key))) throw new StorageNotFoundError(key);
this.applyHeaders(res, opts);
await new Promise<void>((resolve, reject) => {
res.sendFile(path.basename(localPath), { root: path.dirname(localPath) }, (err) =>
err ? reject(err) : resolve(),
);
});
return;
}
const { stream, stat } = await driver.getStream(key);
res.setHeader('Content-Length', String(stat.size));
this.applyHeaders(res, opts);
await new Promise<void>((resolve, reject) => {
stream.on('error', reject);
res.on('error', reject);
res.on('finish', resolve);
stream.pipe(res);
});
}
/**
* Hand a consumer (Jimp, zip packing, Immich push, …) a real filesystem
* path: the local fast-path when the driver has one, else download to
* tempDir() and clean up afterwards — exactly the branch a remote driver
* will exercise.
*/
async withLocalFile<T>(category: StorageCategory, name: string, fn: (absPath: string) => Promise<T>): Promise<T> {
const { driver, key } = this.resolve(category, name);
const localPath = driver.getLocalPath?.(key) ?? null;
if (localPath !== null) {
if (!(await driver.stat(key))) throw new StorageNotFoundError(key);
return fn(localPath);
}
const tmp = path.join(this.tempDir(), randomUUID());
const { stream } = await driver.getStream(key);
await pipeline(stream, fs.createWriteStream(tmp));
try {
return await fn(tmp);
} finally {
await fs.promises.rm(tmp, { force: true });
}
}
/** Replica failures from mirror backends — logged there, surfaced here. */
health(): { replicaFailures: readonly ReplicaFailure[] } {
return { replicaFailures: this.registry.replicaFailures() };
}
private resolve(category: StorageCategory, name: string): Resolved {
const { driver, keyPrefix } = this.registry.resolve(category);
const key = keyPrefix + name;
assertValidKey(key);
return { driver, keyPrefix, key };
}
private applyHeaders(res: Response, opts?: SendOptions): void {
if (opts?.contentType) res.setHeader('Content-Type', opts.contentType);
if (opts?.disposition) res.setHeader('Content-Disposition', opts.disposition);
}
}
@@ -0,0 +1,268 @@
import { describe, it, expect, vi, beforeAll, beforeEach, afterEach } from 'vitest';
// ── DB setup (the permissions.service.test.ts pattern: real in-memory SQLite
// so the app_settings SQL is exercised faithfully) ────────────────────────────
const { testDb, dbMock } = vi.hoisted(() => {
const Database = require('better-sqlite3');
const db = new Database(':memory:');
db.exec('PRAGMA journal_mode = WAL');
db.exec('PRAGMA foreign_keys = ON');
db.exec('PRAGMA busy_timeout = 5000');
return { testDb: db, dbMock: { db, closeDb: () => {}, reinitialize: () => {} } };
});
vi.mock('../../../../src/db/database', () => dbMock);
import fs from 'node:fs';
import os from 'node:os';
import path from 'node:path';
import { Readable } from 'node:stream';
import { createTables } from '../../../../src/db/schema';
import { runMigrations } from '../../../../src/db/migrations';
import { DatabaseService } from '../../../../src/nest/database/database.service';
import type { RuntimeEnvService } from '../../../../src/nest/app-config/runtime-env.service';
import { StorageRegistryService } from '../../../../src/nest/storage/storage-registry.service';
import { LocalDriver } from '../../../../src/nest/storage/drivers/local.driver';
import { MirrorDriver, type ReplicaFailure } from '../../../../src/nest/storage/drivers/mirror.driver';
import { GLOBAL_TEMP_DIR, DEFAULT_BACKUPS_ROOT } from '../../../../src/nest/storage/storage-paths';
import { STORAGE_CATEGORIES } from '../../../../src/nest/storage/storage.types';
const db = new DatabaseService(testDb);
beforeAll(() => {
createTables(testDb);
runMigrations(testDb);
});
// ── helpers ───────────────────────────────────────────────────────────────────
const tmpDirs: string[] = [];
function makeTmpDir(): string {
const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'trek-registry-'));
tmpDirs.push(dir);
return dir;
}
interface EnvPaths {
uploadsDir?: string;
placePhotoDir?: string;
}
function makeEnvStub(initial: EnvPaths): { env: RuntimeEnvService; setPaths: (p: EnvPaths) => void } {
let paths = initial;
return {
env: { env: () => ({ paths }) } as unknown as RuntimeEnvService,
setPaths: (p) => {
paths = p;
},
};
}
function setSetting(key: string, value: string): void {
testDb.prepare('INSERT OR REPLACE INTO app_settings (key, value) VALUES (?, ?)').run(key, value);
}
/** Registry rooted in a fresh temp uploads dir; boots unless told not to. */
function makeRegistry(paths?: EnvPaths, opts: { boot?: boolean } = {}) {
const uploadsRoot = paths?.uploadsDir ?? makeTmpDir();
const stub = makeEnvStub({ uploadsDir: uploadsRoot, placePhotoDir: paths?.placePhotoDir });
const registry = new StorageRegistryService(db, stub.env);
if (opts.boot !== false) registry.onModuleInit();
return { registry, uploadsRoot, setPaths: stub.setPaths };
}
beforeEach(() => {
testDb.prepare("DELETE FROM app_settings WHERE key LIKE 'storage.%'").run();
});
afterEach(() => {
vi.restoreAllMocks();
while (tmpDirs.length) fs.rmSync(tmpDirs.pop()!, { recursive: true, force: true });
});
// ── defaults ──────────────────────────────────────────────────────────────────
describe('StorageRegistryService defaults', () => {
it('resolves every category with the built-in defaults and no settings rows', () => {
const { registry, uploadsRoot } = makeRegistry();
for (const category of STORAGE_CATEGORIES) {
expect(registry.resolve(category)).toBeDefined();
}
const files = registry.resolve('files');
expect(files.backendName).toBe('uploads-local');
expect(files.keyPrefix).toBe('files/');
expect(files.driver).toBeInstanceOf(LocalDriver);
expect(files.driver.getLocalPath!('files/x.pdf')).toBe(path.join(fs.realpathSync(uploadsRoot), 'files/x.pdf'));
// backups: bare keys, root IS the backups dir (spec rev 3.1)
const backups = registry.resolve('backups');
expect(backups.backendName).toBe('backups-local');
expect(backups.keyPrefix).toBe('');
expect(backups.driver.getLocalPath!('backup-1.zip')).toBe(path.join(fs.realpathSync(DEFAULT_BACKUPS_ROOT), 'backup-1.zip'));
// photos-google without TREK_PLACE_PHOTO_DIR: today's layout under uploads
const googlePhotos = registry.resolve('photos-google');
expect(googlePhotos.backendName).toBe('uploads-local');
expect(googlePhotos.keyPrefix).toBe('photos/google/');
});
it('honors TREK_PLACE_PHOTO_DIR via the conditional third backend (mode B: bare keys)', () => {
const photoDir = makeTmpDir();
const { registry } = makeRegistry({ placePhotoDir: photoDir });
const googlePhotos = registry.resolve('photos-google');
expect(googlePhotos.backendName).toBe('place-photos-local');
expect(googlePhotos.keyPrefix).toBe('');
expect(googlePhotos.driver.getLocalPath!('abc.jpg')).toBe(path.join(fs.realpathSync(photoDir), 'abc.jpg'));
// Everything else stays on uploads-local, unchanged.
expect(registry.resolve('photos-trek').backendName).toBe('uploads-local');
expect(registry.resolve('photos-trek').keyPrefix).toBe('photos/trek/');
});
it('creates roots, spools, category prefix dirs, and the global temp dir on load', () => {
const { uploadsRoot } = makeRegistry();
for (const sub of ['.tmp', 'files', 'journey', 'covers', 'avatars', 'places', 'photos', 'photos/trek', 'photos/google']) {
expect(fs.statSync(path.join(uploadsRoot, sub)).isDirectory()).toBe(true);
}
expect(fs.statSync(GLOBAL_TEMP_DIR).isDirectory()).toBe(true);
expect(fs.statSync(path.join(DEFAULT_BACKUPS_ROOT, '.tmp')).isDirectory()).toBe(true);
});
});
// ── settings merge + validation ───────────────────────────────────────────────
describe('StorageRegistryService settings', () => {
it('merges app_settings backends/categories over the defaults (backup mirror)', () => {
const nasRoot = makeTmpDir();
setSetting(
'storage.backends',
JSON.stringify([
{ name: 'nas-backups', type: 'local', options: { root: nasRoot } },
{ name: 'backup-mirror', type: 'mirror', options: { primary: 'backups-local', replicas: ['nas-backups'] } },
]),
);
setSetting('storage.categories', JSON.stringify({ backups: 'backup-mirror' }));
const { registry } = makeRegistry();
const backups = registry.resolve('backups');
expect(backups.backendName).toBe('backup-mirror');
expect(backups.keyPrefix).toBe('');
expect(backups.driver).toBeInstanceOf(MirrorDriver);
// untouched categories keep their defaults
expect(registry.resolve('files').backendName).toBe('uploads-local');
});
it.each([
['unknown backend name in categories', undefined, JSON.stringify({ files: 'nope' })],
[
'mirror assigned to a non-backups category',
JSON.stringify([
{ name: 'extra-local', type: 'local', options: { root: '/tmp/x' } },
{ name: 'm', type: 'mirror', options: { primary: 'uploads-local', replicas: ['extra-local'] } },
]),
JSON.stringify({ files: 'm' }),
],
[
'nested mirror',
JSON.stringify([
{ name: 'extra-local', type: 'local', options: { root: '/tmp/x' } },
{ name: 'm1', type: 'mirror', options: { primary: 'backups-local', replicas: ['extra-local'] } },
{ name: 'm2', type: 'mirror', options: { primary: 'm1', replicas: [] } },
]),
JSON.stringify({ backups: 'm2' }),
],
['unknown driver type', JSON.stringify([{ name: 'x', type: 's3', options: {} }]), undefined],
['unknown category name', undefined, JSON.stringify({ 'not-a-category': 'uploads-local' })],
['malformed JSON', 'not json at all', undefined],
])('falls back to built-in defaults at boot on invalid settings: %s', (_label, backendsRow, categoriesRow) => {
if (backendsRow !== undefined) setSetting('storage.backends', backendsRow);
if (categoriesRow !== undefined) setSetting('storage.categories', categoriesRow);
const { registry } = makeRegistry();
expect(registry.resolve('files').backendName).toBe('uploads-local');
expect(registry.resolve('backups').backendName).toBe('backups-local');
});
it('keeps the last-good config (not defaults) when a reload() sees invalid settings', () => {
const nasRoot = makeTmpDir();
setSetting(
'storage.backends',
JSON.stringify([
{ name: 'nas-backups', type: 'local', options: { root: nasRoot } },
{ name: 'backup-mirror', type: 'mirror', options: { primary: 'backups-local', replicas: ['nas-backups'] } },
]),
);
setSetting('storage.categories', JSON.stringify({ backups: 'backup-mirror' }));
const { registry } = makeRegistry();
expect(registry.resolve('backups').backendName).toBe('backup-mirror');
setSetting('storage.categories', 'garbage {');
registry.reload();
// last-good, i.e. the mirror config — NOT the built-in defaults
expect(registry.resolve('backups').backendName).toBe('backup-mirror');
});
});
// ── reload semantics ──────────────────────────────────────────────────────────
describe('StorageRegistryService reload', () => {
it('swaps the map atomically: new resolves see the new instance, held refs stay usable', async () => {
const { registry, setPaths } = makeRegistry();
const before = registry.resolve('files');
await before.driver.put('files/pre-reload.bin', Readable.from('old root'));
setPaths({ uploadsDir: makeTmpDir() });
registry.reload();
const after = registry.resolve('files');
expect(after.driver).not.toBe(before.driver);
expect(await after.driver.stat('files/pre-reload.bin')).toBeNull(); // new root is empty
// in-flight semantics: the held old driver still serves reads
const { stream } = await before.driver.getStream('files/pre-reload.bin');
const chunks: Buffer[] = [];
for await (const c of stream) chunks.push(Buffer.from(c as Buffer));
expect(Buffer.concat(chunks).toString()).toBe('old root');
});
it('cleans spool leftovers at boot only, never on reload()', () => {
const uploadsRoot = makeTmpDir();
const stray = path.join(uploadsRoot, '.tmp', 'in-flight.part');
fs.mkdirSync(path.dirname(stray), { recursive: true });
fs.writeFileSync(stray, 'crash leftover');
const { registry } = makeRegistry({ uploadsDir: uploadsRoot });
expect(fs.existsSync(stray)).toBe(false); // boot reclaimed it
fs.writeFileSync(stray, 'in-flight upload');
registry.reload();
expect(fs.existsSync(stray)).toBe(true); // reload must not touch it
});
});
// ── replica-failure health ────────────────────────────────────────────────────
describe('StorageRegistryService replica health', () => {
it('keeps a bounded ring of replica failures (last 50)', () => {
const { registry } = makeRegistry();
for (let i = 0; i < 60; i++) {
registry.recordReplicaFailure({
backend: 'nas-backups',
key: `backup-${i}.zip`,
op: 'put',
error: 'disk full',
at: i,
} satisfies ReplicaFailure);
}
const failures = registry.replicaFailures();
expect(failures).toHaveLength(50);
expect(failures[0].key).toBe('backup-10.zip'); // oldest 10 dropped
expect(failures[49].key).toBe('backup-59.zip');
});
});
@@ -0,0 +1,260 @@
import { describe, it, expect, afterEach } from 'vitest';
import fs from 'node:fs';
import os from 'node:os';
import path from 'node:path';
import { PassThrough, Readable } from 'node:stream';
import type { Response } from 'express';
import { LocalDriver } from '../../../../src/nest/storage/drivers/local.driver';
import type { ReplicaFailure } from '../../../../src/nest/storage/drivers/mirror.driver';
import type { StorageRegistryService, ResolvedCategory } from '../../../../src/nest/storage/storage-registry.service';
import { StorageService } from '../../../../src/nest/storage/storage.service';
import {
StorageInvalidKeyError,
StorageNotFoundError,
type ObjectStat,
type StorageDriver,
} from '../../../../src/nest/storage/storage.types';
// Facade over a stub registry (the weather.controller.test.ts casting style)
// backed by a REAL LocalDriver, so key composition, prefix stripping, and both
// sendToResponse/withLocalFile branches are exercised against actual files.
const tmpDirs: string[] = [];
function makeTmpDir(): string {
const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'trek-facade-'));
tmpDirs.push(dir);
return dir;
}
interface Fixture {
storage: StorageService;
driver: LocalDriver;
root: string;
tempDir: string;
failures: ReplicaFailure[];
}
function makeFixture(keyPrefix = 'files/'): Fixture {
const root = makeTmpDir();
const tempDir = makeTmpDir();
const driver = new LocalDriver({ id: 'stub-local', root });
driver.init({ cleanSpool: true });
const failures: ReplicaFailure[] = [];
const registry = {
resolve: (): ResolvedCategory => ({ driver, keyPrefix, backendName: 'stub-local' }),
tempDir: () => tempDir,
replicaFailures: () => failures,
} as unknown as StorageRegistryService;
return { storage: new StorageService(registry), driver, root, tempDir, failures };
}
/** A driver with no getLocalPath — the remote-driver branch every helper must handle. */
function makeStreamOnlyFixture(contents: string): Fixture & { driverCalls: string[] } {
const fx = makeFixture('');
const driverCalls: string[] = [];
const bytes = Buffer.from(contents);
const stat: ObjectStat = { key: 'remote.bin', size: bytes.length, mtimeMs: 1 };
const streamOnly: StorageDriver = {
id: 'stub-remote',
put: async () => undefined,
getStream: async (key: string) => {
driverCalls.push(`getStream:${key}`);
return { stream: Readable.from(bytes), stat: { ...stat, key } };
},
stat: async (key: string) => ({ ...stat, key }),
delete: async () => undefined,
list: async function* () {
yield* [] as ObjectStat[];
},
// no getLocalPath, no getSpoolDir
};
const registry = {
resolve: (): ResolvedCategory => ({ driver: streamOnly, keyPrefix: '', backendName: 'stub-remote' }),
tempDir: () => fx.tempDir,
replicaFailures: () => fx.failures,
} as unknown as StorageRegistryService;
return { ...fx, storage: new StorageService(registry), driverCalls };
}
afterEach(() => {
while (tmpDirs.length) fs.rmSync(tmpDirs.pop()!, { recursive: true, force: true });
});
describe('StorageService key composition', () => {
it('composes keyPrefix + name on writes and strips it back in list()', async () => {
const fx = makeFixture('files/');
await fx.storage.put('files', 'a.pdf', Readable.from('doc'));
await fx.storage.put('files', 'nested/b.pdf', Readable.from('doc2'));
// on disk under the driver prefix
expect(fs.existsSync(path.join(fx.root, 'files/a.pdf'))).toBe(true);
const names: string[] = [];
for await (const stat of fx.storage.list('files')) names.push(stat.key);
expect(names.sort()).toEqual(['a.pdf', 'nested/b.pdf']); // category-relative
const nested: string[] = [];
for await (const stat of fx.storage.list('files', 'nested/')) nested.push(stat.key);
expect(nested).toEqual(['nested/b.pdf']);
});
it('rejects a name that composes into an invalid key', async () => {
const fx = makeFixture('files/');
await expect(fx.storage.put('files', '../escape.bin', Readable.from('x'))).rejects.toBeInstanceOf(
StorageInvalidKeyError,
);
await expect(fx.storage.stat('files', '.tmp/spool.part')).rejects.toBeInstanceOf(StorageInvalidKeyError);
});
it('delegates stat/exists/delete/getStream with the composed key', async () => {
const fx = makeFixture('files/');
await fx.storage.put('files', 'c.bin', Readable.from('12345'));
expect((await fx.storage.stat('files', 'c.bin'))!.size).toBe(5);
expect(await fx.storage.exists('files', 'c.bin')).toBe(true);
expect(await fx.storage.exists('files', 'nope.bin')).toBe(false);
const { stream, stat } = await fx.storage.getStream('files', 'c.bin', { start: 1, end: 3 });
expect(stat.size).toBe(5);
const chunks: Buffer[] = [];
for await (const c of stream) chunks.push(Buffer.from(c as Buffer));
expect(Buffer.concat(chunks).toString()).toBe('234');
await fx.storage.delete('files', 'c.bin');
expect(await fx.storage.exists('files', 'c.bin')).toBe(false);
});
});
describe('StorageService spool + temp dirs', () => {
it('spoolDirFor returns the backend spool for local drivers and tempDir() otherwise', () => {
const fx = makeFixture();
expect(fx.storage.spoolDirFor('files')).toBe(path.join(fs.realpathSync(fx.root), '.tmp'));
expect(fx.storage.tempDir()).toBe(fx.tempDir);
const remote = makeStreamOnlyFixture('x');
expect(remote.storage.spoolDirFor('files')).toBe(remote.tempDir);
});
});
describe('StorageService withLocalFile', () => {
it('hands local drivers their real path', async () => {
const fx = makeFixture('files/');
await fx.storage.put('files', 'img.jpg', Readable.from('jpeg bytes'));
const result = await fx.storage.withLocalFile('files', 'img.jpg', async (absPath) => {
expect(absPath).toBe(path.join(fs.realpathSync(fx.root), 'files/img.jpg'));
return fs.readFileSync(absPath, 'utf8');
});
expect(result).toBe('jpeg bytes');
});
it('throws StorageNotFoundError for a local miss', async () => {
const fx = makeFixture('files/');
await expect(fx.storage.withLocalFile('files', 'ghost.jpg', async () => 'never')).rejects.toBeInstanceOf(
StorageNotFoundError,
);
});
it('downloads to tempDir for path-less drivers and cleans up, even when fn throws', async () => {
const remote = makeStreamOnlyFixture('remote bytes');
let seenPath = '';
const result = await remote.storage.withLocalFile('files', 'remote.bin', async (absPath) => {
seenPath = absPath;
return fs.readFileSync(absPath, 'utf8');
});
expect(result).toBe('remote bytes');
expect(seenPath.startsWith(remote.tempDir + path.sep)).toBe(true);
expect(fs.existsSync(seenPath)).toBe(false); // cleaned up
await expect(
remote.storage.withLocalFile('files', 'remote.bin', async (absPath) => {
seenPath = absPath;
throw new Error('processing failed');
}),
).rejects.toThrow('processing failed');
expect(fs.existsSync(seenPath)).toBe(false); // cleaned up on throw too
});
});
interface MockRes {
res: Response;
sendFileCalls: Array<{ name: string; root: string }>;
headers: Record<string, string>;
body: () => Promise<string>;
}
function makeRes(): MockRes {
const sink = new PassThrough();
const sendFileCalls: Array<{ name: string; root: string }> = [];
const headers: Record<string, string> = {};
const collected: Buffer[] = [];
sink.on('data', (c: Buffer) => collected.push(c));
const res = Object.assign(sink, {
setHeader: (key: string, value: string) => {
headers[key] = value;
return res;
},
sendFile: (name: string, opts: { root: string }, cb: (err?: Error) => void) => {
sendFileCalls.push({ name, root: opts.root });
cb();
},
}) as unknown as Response;
return {
res,
sendFileCalls,
headers,
// sendToResponse resolves on 'finish', so by the time a test reads the
// body the sink has already flushed everything into `collected`.
body: async () => Buffer.concat(collected).toString(),
};
}
describe('StorageService sendToResponse', () => {
it('serves local files via root-relative res.sendFile (the files-download quirk)', async () => {
const fx = makeFixture('files/');
await fx.storage.put('files', 'doc.pdf', Readable.from('%PDF'));
const mock = makeRes();
await fx.storage.sendToResponse('files', 'doc.pdf', mock.res, {
contentType: 'application/pdf',
disposition: 'inline',
});
expect(mock.sendFileCalls).toEqual([
{ name: 'doc.pdf', root: path.join(fs.realpathSync(fx.root), 'files') },
]);
expect(mock.headers['Content-Type']).toBe('application/pdf');
expect(mock.headers['Content-Disposition']).toBe('inline');
});
it('throws StorageNotFoundError on a miss (callers decide 404/204/next())', async () => {
const fx = makeFixture('files/');
const mock = makeRes();
await expect(fx.storage.sendToResponse('files', 'ghost.pdf', mock.res)).rejects.toBeInstanceOf(
StorageNotFoundError,
);
expect(mock.sendFileCalls).toEqual([]);
});
it('stream-pipes with Content-Length for path-less drivers', async () => {
const remote = makeStreamOnlyFixture('streamed body');
const mock = makeRes();
await remote.storage.sendToResponse('files', 'remote.bin', mock.res, { contentType: 'image/jpeg' });
expect(mock.sendFileCalls).toEqual([]); // no local fast-path available
expect(mock.headers['Content-Length']).toBe(String('streamed body'.length));
expect(mock.headers['Content-Type']).toBe('image/jpeg');
expect(await mock.body()).toBe('streamed body');
});
});
describe('StorageService health', () => {
it('surfaces the registry replica-failure ring', () => {
const fx = makeFixture();
fx.failures.push({ backend: 'nas', key: 'backup-1.zip', op: 'put', error: 'disk full', at: 1 });
expect(fx.storage.health().replicaFailures).toHaveLength(1);
expect(fx.storage.health().replicaFailures[0].backend).toBe('nas');
});
});