mirror of
https://github.com/mauriceboe/TREK.git
synced 2026-12-05 02:14:05 +00:00
feat(storage): settings-backed registry, StorageService facade, module wiring
This commit is contained in:
@@ -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)`);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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 {}
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user