refactor(server): lift the memories vocabulary and the uploads anchor into nest

Two preparations the provider conversion needs, and neither changes behaviour.

The ServiceResult envelope, the provider-agnostic asset shapes and pipeAsset
move to nest/memories/memories.helpers.ts, which touches no database. The
controllers and the provider services can name them without importing each
other - the same reason notifications/notification-events.ts exists. What is
left in services/memories/helpersService.ts is the DB-backed half (the access
checks, the album-link lookups) and it folds with the providers.

pipeAsset stays a free function over the Express response on purpose. It is not
a StreamableFile candidate: it forwards the upstream's 206 and Content-Range so
a <video> can seek (#823), swaps Cache-Control to no-store on an error status,
and has to answer differently once headers are already sent. All three
controllers take @Res() anyway.

The three copies of `path.join(__dirname, '../../../uploads')` become one
UPLOADS_ROOT. __dirname moves with the file and none of these would have thrown
on a wrong depth - mkdirSync and multer create the wrong tree without a word,
and every stored photo lands somewhere nobody serves from. UPLOADS-ROOT-001
pins it. The depth happens to be identical for nest/memories, so nothing moves
today; the point is that the next move only has one place to get wrong.
This commit is contained in:
Maurice
2026-08-08 14:01:20 +02:00
committed by Maurice
parent aa4ed69677
commit 67c1633155
10 changed files with 207 additions and 150 deletions
@@ -0,0 +1,161 @@
import { pipeline } from 'node:stream/promises';
import { Readable } from 'node:stream';
import { Response } from 'express';
import { safeFetch, SsrfBlockedError, type SafeFetchOptions } from '../../utils/ssrfGuard';
/**
* The shared vocabulary of the memories domain: the ServiceResult envelope, the
* provider-agnostic asset shapes, and the asset proxy.
*
* No database and no DI, so the provider services, the resolver and the
* controllers can all name these without importing each other — the same reason
* notifications/notification-events.ts exists.
*/
// helpers for handling return types
type ServiceError = { success: false; error: { message: string; status: number } };
export type ServiceResult<T> = { success: true; data: T } | ServiceError;
export function fail(error: string, status: number): ServiceError {
return { success: false, error: { message: error, status } };
}
export function success<T>(data: T): ServiceResult<T> {
return { success: true, data: data };
}
export function mapDbError(error: Error, fallbackMessage: string): ServiceError {
if (error && /unique|constraint/i.test(error.message)) {
return fail('Resource already exists', 409);
}
return fail(error.message, 500);
}
export function handleServiceResult<T>(res: Response, result: ServiceResult<T>): void {
if ('error' in result) {
res.status(result.error.status).json({ error: result.error.message });
}
else {
res.json(result.data);
}
}
// ----------------------------------------------
// types used across memories services
export type Selection = {
provider: string;
asset_ids: string[];
passphrase?: string;
};
export type StatusResult = {
connected: true;
user: { name: string }
} | {
connected: false;
error: string
};
export type SyncAlbumResult = {
added: number;
total: number
};
export type AlbumsList = {
albums: Array<{ id: string; albumName: string; assetCount: number; passphrase?: string }>
};
export type Asset = {
id: string;
takenAt: string;
mediaType?: string;
city?: string | null;
country?: string | null;
lat?: number | null;
lng?: number | null;
};
export type AssetsList = {
assets: Asset[],
total: number,
hasMore: boolean
};
export type AssetInfo = {
id: string;
takenAt: string | null;
city: string | null;
country: string | null;
state?: string | null;
camera?: string | null;
lens?: string | null;
focalLength?: string | number | null;
aperture?: string | number | null;
shutter?: string | number | null;
iso?: string | number | null;
lat?: number | null;
lng?: number | null;
orientation?: number | null;
description?: string | null;
width?: number | null;
height?: number | null;
fileSize?: number | null;
fileName?: string | null;
}
/**
* Proxy an upstream asset straight to the client.
*
* It writes status, headers and body onto the Express response itself and is
* NOT a candidate for StreamableFile: it forwards the upstream's 206 and
* Content-Range so a <video> can seek (#823), swaps Cache-Control to no-store
* on an error status, and has to answer differently once headers are already
* sent. All three controllers take @Res() anyway.
*/
export async function pipeAsset(url: string, response: Response, headers?: Record<string, string>, signal?: AbortSignal, defaultCacheControl?: string, fetchOptions?: SafeFetchOptions): Promise<void> {
try {
const resp = await safeFetch(url, { headers, signal: signal as any }, fetchOptions);
response.status(resp.status);
if (resp.headers.get('content-type')) response.set('Content-Type', resp.headers.get('content-type') as string);
if (!resp.ok) {
response.set('Cache-Control', 'no-store, max-age=0');
} else if (resp.headers.get('cache-control')) {
response.set('Cache-Control', resp.headers.get('cache-control') as string);
} else if (defaultCacheControl) {
response.set('Cache-Control', defaultCacheControl);
}
if (resp.headers.get('content-length')) response.set('Content-Length', resp.headers.get('content-length') as string);
if (resp.headers.get('content-disposition')) response.set('Content-Disposition', resp.headers.get('content-disposition') as string);
// Pass byte-range metadata through so a <video> can seek (#823). Upstream
// returns 206 + Content-Range when the caller forwarded a Range header.
if (resp.headers.get('accept-ranges')) response.set('Accept-Ranges', resp.headers.get('accept-ranges') as string);
if (resp.headers.get('content-range')) response.set('Content-Range', resp.headers.get('content-range') as string);
if (!resp.body) {
response.end();
} else {
await pipeline(Readable.fromWeb(resp.body as any), response);
}
} catch (error) {
if (response.headersSent) {
response.end();
return;
}
if (error instanceof SsrfBlockedError) {
response.status(400).json({ error: error.message });
} else {
// Don't log the URL — it can carry a Synology _sid / passphrase.
console.error('pipeAsset: upstream fetch failed:', error);
response.status(500).json({ error: 'Failed to fetch asset' });
}
}
}
+1 -1
View File
@@ -37,7 +37,7 @@ import {
streamSynologyAsset,
} from '../../services/memories/synologyService';
import { canAccessUserPhoto } from '../../services/memories/helpersService';
import type { Selection } from '../../services/memories/helpersService';
import type { Selection } from './memories.helpers';
import type { TrekWsPayload, TrekWsTripEventName } from '@trek/shared';
import { RealtimeService } from '../realtime/realtime.service';
@@ -1,8 +1,8 @@
import { Body, Controller, Get, Headers, HttpCode, Param, Post, Put, Query, Res, UseGuards } from '@nestjs/common';
import type { Response } from 'express';
import type { User } from '../../types';
import type { ServiceResult } from '../../services/memories/helpersService';
import { fail, success } from '../../services/memories/helpersService';
import type { ServiceResult } from './memories.helpers';
import { fail, success } from './memories.helpers';
import { MemoriesService } from './memories.service';
import { JwtAuthGuard } from '../auth/jwt-auth.guard';
import { CurrentUser } from '../auth/current-user.decorator';
@@ -1,7 +1,7 @@
import { Body, Controller, Delete, Get, Headers, HttpCode, Param, Post, Put, Res, UseGuards } from '@nestjs/common';
import type { Response } from 'express';
import type { User } from '../../types';
import type { Selection } from '../../services/memories/helpersService';
import type { Selection } from './memories.helpers';
import { MemoriesService } from './memories.service';
import { JwtAuthGuard } from '../auth/jwt-auth.guard';
import { CurrentUser } from '../auth/current-user.decorator';
+14
View File
@@ -0,0 +1,14 @@
import path from 'node:path';
/**
* `<server>/uploads`, the one anchor for everything the app stores on disk.
*
* `__dirname` moves with the file, and three separate copies of this join used
* to live in services/memories/ — every one of them a silent breakage waiting
* for the next move (multer would have created the wrong directory without a
* word). One constant, one test (UPLOADS-ROOT-001), and the depth is stated
* rather than counted by hand: `server/{src,dist}/nest/memories` sits three
* levels under `server/`, the same depth `services/memories/` sat at — so the
* resolved path is unchanged by the move.
*/
export const UPLOADS_ROOT = path.resolve(__dirname, '..', '..', '..', 'uploads');
+5 -143
View File
@@ -1,108 +1,10 @@
import { pipeline } from 'node:stream/promises';
import { Readable } from 'node:stream';
import { Response } from 'express';
import { canAccessTrip, db } from "../../db/database";
import { safeFetch, SsrfBlockedError, type SafeFetchOptions } from '../../utils/ssrfGuard';
import { decrypt_api_key } from '../../nest/common/crypto/apiKeyCrypto';
// helpers for handling return types
type ServiceError = { success: false; error: { message: string; status: number } };
export type ServiceResult<T> = { success: true; data: T } | ServiceError;
export function fail(error: string, status: number): ServiceError {
return { success: false, error: { message: error, status } };
}
export function success<T>(data: T): ServiceResult<T> {
return { success: true, data: data };
}
export function mapDbError(error: Error, fallbackMessage: string): ServiceError {
if (error && /unique|constraint/i.test(error.message)) {
return fail('Resource already exists', 409);
}
return fail(error.message, 500);
}
export function handleServiceResult<T>(res: Response, result: ServiceResult<T>): void {
if ('error' in result) {
res.status(result.error.status).json({ error: result.error.message });
}
else {
res.json(result.data);
}
}
// ----------------------------------------------
// types used across memories services
export type Selection = {
provider: string;
asset_ids: string[];
passphrase?: string;
};
export type StatusResult = {
connected: true;
user: { name: string }
} | {
connected: false;
error: string
};
export type SyncAlbumResult = {
added: number;
total: number
};
export type AlbumsList = {
albums: Array<{ id: string; albumName: string; assetCount: number; passphrase?: string }>
};
export type Asset = {
id: string;
takenAt: string;
mediaType?: string;
city?: string | null;
country?: string | null;
lat?: number | null;
lng?: number | null;
};
export type AssetsList = {
assets: Asset[],
total: number,
hasMore: boolean
};
export type AssetInfo = {
id: string;
takenAt: string | null;
city: string | null;
country: string | null;
state?: string | null;
camera?: string | null;
lens?: string | null;
focalLength?: string | number | null;
aperture?: string | number | null;
shutter?: string | number | null;
iso?: string | number | null;
lat?: number | null;
lng?: number | null;
orientation?: number | null;
description?: string | null;
width?: number | null;
height?: number | null;
fileSize?: number | null;
fileName?: string | null;
}
// The ServiceResult envelope, the asset shapes and pipeAsset moved to
// nest/memories/memories.helpers.ts — this file is down to the DB-backed
// access checks and album-link lookups, and folds with the providers.
import { fail, success, type ServiceResult } from '../../nest/memories/memories.helpers';
export * from '../../nest/memories/memories.helpers';
//for loading routes to settings page, and validating which services user has connected
type PhotoProviderConfig = {
@@ -255,43 +157,3 @@ export function getAlbumLinkForSync(tripId: string, linkId: string, userId: numb
export function updateSyncTimeForAlbumLink(linkId: string): void {
db.prepare('UPDATE trip_album_links SET last_synced_at = CURRENT_TIMESTAMP WHERE id = ?').run(linkId);
}
export async function pipeAsset(url: string, response: Response, headers?: Record<string, string>, signal?: AbortSignal, defaultCacheControl?: string, fetchOptions?: SafeFetchOptions): Promise<void> {
try {
const resp = await safeFetch(url, { headers, signal: signal as any }, fetchOptions);
response.status(resp.status);
if (resp.headers.get('content-type')) response.set('Content-Type', resp.headers.get('content-type') as string);
if (!resp.ok) {
response.set('Cache-Control', 'no-store, max-age=0');
} else if (resp.headers.get('cache-control')) {
response.set('Cache-Control', resp.headers.get('cache-control') as string);
} else if (defaultCacheControl) {
response.set('Cache-Control', defaultCacheControl);
}
if (resp.headers.get('content-length')) response.set('Content-Length', resp.headers.get('content-length') as string);
if (resp.headers.get('content-disposition')) response.set('Content-Disposition', resp.headers.get('content-disposition') as string);
// Pass byte-range metadata through so a <video> can seek (#823). Upstream
// returns 206 + Content-Range when the caller forwarded a Range header.
if (resp.headers.get('accept-ranges')) response.set('Accept-Ranges', resp.headers.get('accept-ranges') as string);
if (resp.headers.get('content-range')) response.set('Content-Range', resp.headers.get('content-range') as string);
if (!resp.body) {
response.end();
} else {
await pipeline(Readable.fromWeb(resp.body as any), response);
}
} catch (error) {
if (response.headersSent) {
response.end();
return;
}
if (error instanceof SsrfBlockedError) {
response.status(400).json({ error: error.message });
} else {
// Don't log the URL — it can carry a Synology _sid / passphrase.
console.error('pipeAsset: upstream fetch failed:', error);
response.status(500).json({ error: 'Failed to fetch asset' });
}
}
}
@@ -4,6 +4,7 @@ import { maybe_encrypt_api_key, decrypt_api_key } from '../../nest/common/crypto
import { checkSsrf, safeFetch } from '../../utils/ssrfGuard';
import { writeAudit } from '../../nest/audit/audit.bridge';
import { getAlbumIdFromLink, updateSyncTimeForAlbumLink, Selection, pipeAsset } from './helpersService';
import { UPLOADS_ROOT } from '../../nest/memories/uploads-root';
// ── Credentials ────────────────────────────────────────────────────────────
@@ -534,7 +535,7 @@ export async function uploadToImmich(userId: number, filePath: string, fileName:
const fs = await import('node:fs');
const path = await import('node:path');
const fullPath = path.join(__dirname, '../../../uploads', filePath);
const fullPath = path.join(UPLOADS_ROOT, filePath);
if (!fs.existsSync(fullPath)) return null;
try {
@@ -6,6 +6,7 @@ import type { TrekPhoto } from '../../types';
// The trek_photos rows live in nest/photos now — this module is the provider
// dispatch half of what used to be one file.
import { resolveTrekPhoto } from '../../nest/photos/photos.bridge';
import { UPLOADS_ROOT } from '../../nest/memories/uploads-root';
import { streamImmichAsset, fetchImmichThumbnailBytes, getAssetInfo as getImmichAssetInfo } from './immichService';
import { streamSynologyAsset, fetchSynologyThumbnailBytes, getSynologyAssetInfo } from './synologyService';
import type { ServiceResult, AssetInfo } from './helpersService';
@@ -60,7 +61,7 @@ export async function streamPhoto(
}
if (photo.file_path) {
const uploadsRoot = path.join(__dirname, '../../../uploads');
const uploadsRoot = UPLOADS_ROOT;
if (kind === 'thumbnail') {
const isVideo = photo.media_type === 'video';
@@ -4,8 +4,9 @@ import fsPromises from 'node:fs/promises';
import crypto from 'node:crypto';
import { Response } from 'express';
import { db } from '../../db/database';
import { UPLOADS_ROOT } from '../../nest/memories/uploads-root';
const TREK_PHOTO_DIR = path.join(__dirname, '../../../uploads/photos/trek');
const TREK_PHOTO_DIR = path.join(UPLOADS_ROOT, 'photos/trek');
export const CACHE_TTL = 60 * 60 * 1000; // 1 hour
const inFlight = new Map<string, Promise<Buffer | null>>();
@@ -0,0 +1,17 @@
import { describe, it, expect } from 'vitest';
import path from 'node:path';
import { UPLOADS_ROOT } from '../../../src/nest/memories/uploads-root';
/**
* The anchor three separate `__dirname` joins used to duplicate. A wrong depth
* does not throw — multer and mkdirSync would happily create the wrong tree and
* every stored photo would land somewhere nobody serves from.
*/
describe('UPLOADS_ROOT', () => {
it('UPLOADS-ROOT-001: resolves to <server>/uploads, whatever the process cwd is', () => {
// tests run from server/, so the repo-relative answer is unambiguous
expect(UPLOADS_ROOT).toBe(path.resolve(process.cwd(), 'uploads'));
expect(path.basename(UPLOADS_ROOT)).toBe('uploads');
expect(path.basename(path.dirname(UPLOADS_ROOT))).toBe('server');
});
});