Skip to content

armgit / TREK

Public Imported from GitHub
0

The most complete open-source travel planner: real-time collaboration, bookings, budgets, packing lists, journals, offline PWA, SSO and an AI-ready MCP server, with planet-wide place search and routing built in.

fix(demo): a demo instance keeps the files its baseline points at

Maurice42ed858853ef
diff --git a/server/src/nest/assistant/assistant-attachments.service.ts b/server/src/nest/assistant/assistant-attachments.service.ts
index e95c857af..aefebc165 100644
--- a/server/src/nest/assistant/assistant-attachments.service.ts
+++ b/server/src/nest/assistant/assistant-attachments.service.ts
@@ -9,7 +9,7 @@ import { dbNow } from '../../db/types';
import { logError, logInfo } from '../audit/audit-log.logger';
import { withRequestContext } from '../database/request-context';
import { LlmParseService } from '../llm-parse/llm-parse.service';
-import { StorageService } from '../storage/storage.service';
+import { ASSISTANT_FILES_PREFIX, StorageService } from '../storage/storage.service';
import type { AgentToolRun } from './assistant-agent';
import { NO_SUCH_ATTACHMENT, NO_TEXT, type AttachedTurn } from './assistant-attachment-tools';
import { AssistantKeepFileService } from './assistant-keep-file.service';
@@ -32,9 +32,10 @@ const DAY_MS = 24 * 60 * 60 * 1000;
/**
* Where the bytes sit: under the trip files' category, which is never served
* by path (`/uploads/files` refuses every request), in a folder of their own.
+ * Storage names the folder, so a demo instance still deletes these bytes.
*/
const STORAGE_CATEGORY = 'files';
-const KEY_PREFIX = 'assistant/';
+const KEY_PREFIX = ASSISTANT_FILES_PREFIX;
/** The most text kept of one file; a model is sent a window of it, never all of it. */
const MAX_STORED_TEXT_CHARS = 200_000;
diff --git a/server/src/nest/journey/journey.controller.ts b/server/src/nest/journey/journey.controller.ts
index f5695bf01..892aeb6c5 100644
--- a/server/src/nest/journey/journey.controller.ts
+++ b/server/src/nest/journey/journey.controller.ts
@@ -199,6 +199,7 @@ export class JourneyController {
* The commit has to happen first (the Immich mirror reads the final path), so
* every refusal after it has to take the bytes back out. Nothing sweeps
* orphans, and a loop of rejected POSTs would otherwise just fill the disk.
+ * A demo instance keeps them all the same (StorageService.delete).
*/
private async discardJourneyUploads(files: Express.Multer.File[]): Promise<void> {
for (const f of files) {
diff --git a/server/src/nest/memories/thumbnail.service.ts b/server/src/nest/memories/thumbnail.service.ts
index 948af924f..0a424cf2b 100644
--- a/server/src/nest/memories/thumbnail.service.ts
+++ b/server/src/nest/memories/thumbnail.service.ts
@@ -106,6 +106,8 @@ export class ThumbnailService {
let removed = 0;
for await (const stat of this.storage.list('journey', 'thumbs/')) {
if (!stat.key.endsWith('.jpg') || live.has(stat.key)) continue;
+ // A demo instance keeps it (StorageService.keepsOnDelete): not reclaimed, so not counted.
+ if (this.storage.keepsOnDelete('journey', stat.key)) continue;
try {
await this.storage.delete('journey', stat.key);
removed++;
diff --git a/server/src/nest/storage/storage.service.ts b/server/src/nest/storage/storage.service.ts
index d83d69196..cb890234b 100644
--- a/server/src/nest/storage/storage.service.ts
+++ b/server/src/nest/storage/storage.service.ts
@@ -1,3 +1,5 @@
+import { RuntimeEnvService } from '../app-config/runtime-env.service';
+import { logDebug } from '../audit/audit-log.logger';
import { contentTypeFor } from './content-type';
import type { ReplicaFailure } from './drivers/mirror.driver';
import { decideRange, isNotModified, validatorsFor, type ServingHeaders, type Validators } from './http-serving';
@@ -33,6 +35,47 @@ interface Resolved {
key: string;
}
+/**
+ * The folder under `files` the assistant keeps the files attached to a
+ * conversation in (assistant-attachments.service.ts takes it from here). They
+ * live by a retention of days, so no demo baseline can rely on their bytes, and
+ * a demo instance deletes them as any other does: attaching is not refused to
+ * the demo account, and kept bytes of a public visitor's files would stay for good.
+ */
+export const ASSISTANT_FILES_PREFIX = 'assistant/';
+
+/**
+ * What a delete does on a demo instance, per category: `true` leaves the
+ * object where it is. The hourly demo reset (src/demo/demo-reset.ts) puts only
+ * the database back to its baseline, so a file a visitor deleted in between
+ * would be missing from the restored rows for good. The categories holding
+ * content that rows point at are kept; the caches and the backups are deleted
+ * as on any other instance. A Record, so a new category does not compile until
+ * it is decided here.
+ */
+const KEPT_ON_DEMO: Readonly<Record<ServedCategory, boolean>> = {
+ // Trip files, collab note files and chat images. The assistant's attachments
+ // under ASSISTANT_FILES_PREFIX are the exception, see keepsOnDelete.
+ files: true,
+ // Journey photos, videos, posters, covers and thumbs. A thumb a row records
+ // is served as it is and never made again, so it stays with its photo.
+ journey: true,
+ // Trip and collection covers.
+ covers: true,
+ avatars: true,
+ // Images uploaded for places.
+ places: true,
+ // The legacy shared photo folder, served and backed up like the uploads.
+ photos: true,
+ // A cache of the photos the map providers hand back, written by every lookup
+ // and swept nightly. Kept, it would grow without bound on a public demo.
+ 'photos-google': false,
+ // A cache of Immich and Synology assets that lives an hour and is fetched again on a miss.
+ 'photos-trek': false,
+ // Never part of the baseline: the admin deletes them and auto-backup rotates them.
+ backups: false,
+};
+
/**
* The facade all call sites use — and the ONLY entry point: callers address
* storage exclusively as (category, name) on this injected service. They
@@ -47,7 +90,12 @@ interface Resolved {
*/
@Injectable()
export class StorageService {
- constructor(private readonly registry: StorageRegistryService) {}
+ constructor(
+ private readonly registry: StorageRegistryService,
+ // Whether DEMO_MODE is on, read on every delete. A hand-built facade (the
+ // unit suites) reads the same live env the container's provider does.
+ private readonly runtimeEnv: RuntimeEnvService = new RuntimeEnvService(),
+ ) {}
/** Driver-agnostic global scratch space (data/tmp). */
tempDir(): string {
@@ -90,8 +138,32 @@ export class StorageService {
return (await this.stat(category, name)) !== null;
}
+ /**
+ * Whether delete() leaves this object where it is: on a demo instance, one of
+ * a category KEPT_ON_DEMO keeps, the assistant's attachments excepted. A
+ * sweep asks first, so it never counts as reclaimed an object that stays.
+ */
+ keepsOnDelete(category: ServedCategory, name: string): boolean {
+ if (!KEPT_ON_DEMO[category]) return false;
+ if (category === 'files' && name.startsWith(ASSISTANT_FILES_PREFIX)) return false;
+ return this.runtimeEnv.isDemoMode();
+ }
+
+ /**
+ * Idempotent, like the drivers. On a demo instance an object keepsOnDelete()
+ * names is left alone and the call resolves as if it were gone; a later put()
+ * under the same name still replaces it. That holds for the bytes a request
+ * takes back out after a refused upload too: on a demo they stay, as a
+ * visitor's uploads already do once the hourly reset drops their rows. The
+ * name is validated first in both modes, so a hostile one is refused either way.
+ */
async delete(category: ServedCategory, name: string): Promise<void> {
const { driver, key } = this.resolve(category, name);
+ if (this.keepsOnDelete(category, name)) {
+ // The category only: the name can come from a request, and a log line is no place for it.
+ logDebug(`[storage] demo mode keeps a deleted ${category} object, the hourly reset restores rows that name it`);
+ return;
+ }
return driver.delete(key);
}
diff --git a/server/tests/unit/nest/storage/storage-demo-delete.test.ts b/server/tests/unit/nest/storage/storage-demo-delete.test.ts
new file mode 100644
index 000000000..46098649c
--- /dev/null
+++ b/server/tests/unit/nest/storage/storage-demo-delete.test.ts
@@ -0,0 +1,180 @@
+/**
+ * A demo instance keeps the uploads its baseline points at.
+ *
+ * The hourly demo reset (src/demo/demo-reset.ts) puts the database back to
+ * travel-baseline.db and leaves storage alone, so a file a visitor deleted in
+ * between stays gone while the restored rows still name it. StorageService
+ * .delete is the one place that stops it: with DEMO_MODE on it leaves the
+ * content categories alone, and the caches, the backups and the assistant's
+ * attachments are still deleted.
+ *
+ * The subject comes out of a Nest testing module with the real
+ * RuntimeEnvService, so DEMO_MODE is read the way the server reads it. The
+ * registry is a stub over a real LocalDriver, as in storage.service.test.ts,
+ * with every category under a prefix of its own name.
+ */
+import { RuntimeEnvService } from '../../../../src/nest/app-config/runtime-env.service';
+import { LocalDriver } from '../../../../src/nest/storage/drivers/local.driver';
+import { StorageRegistryService, type ResolvedCategory } from '../../../../src/nest/storage/storage-registry.service';
+import { StorageService } from '../../../../src/nest/storage/storage.service';
+import {
+ SERVED_CATEGORIES,
+ StorageInvalidKeyError,
+ type ServedCategory,
+} from '../../../../src/nest/storage/storage.types';
+import type { Provider } from '@nestjs/common';
+import { Test } from '@nestjs/testing';
+
+import fs from 'node:fs';
+import os from 'node:os';
+import path from 'node:path';
+import { Readable } from 'node:stream';
+import { afterEach, describe, expect, it } from 'vitest';
+
+/** The categories holding content that rows point at: a demo keeps their objects. */
+const KEPT: ServedCategory[] = ['files', 'journey', 'covers', 'avatars', 'places', 'photos'];
+/** The caches and the backups: a demo deletes them like any other instance. */
+const DELETED: ServedCategory[] = ['photos-google', 'photos-trek', 'backups'];
+
+const prevDemo = process.env.DEMO_MODE;
+const roots: string[] = [];
+
+afterEach(() => {
+ if (prevDemo === undefined) delete process.env.DEMO_MODE;
+ else process.env.DEMO_MODE = prevDemo;
+ for (const root of roots.splice(0)) fs.rmSync(root, { recursive: true, force: true });
+});
+
+interface Fixture {
+ storage: StorageService;
+ /** Writes an object through the facade and answers where it sits on disk. */
+ put(category: ServedCategory, name: string, body?: string): Promise<string>;
+}
+
+/** The facade out of a testing module; `runtimeEnv` replaces the real RuntimeEnvService when given. */
+async function build(runtimeEnv?: Pick<RuntimeEnvService, 'isDemoMode'>): Promise<Fixture> {
+ const root = fs.mkdtempSync(path.join(os.tmpdir(), 'trek-demo-delete-'));
+ roots.push(root);
+ const driver = new LocalDriver({ id: 'demo-local', root });
+ driver.init({ cleanSpool: true });
+ const registry = {
+ resolve: (category: ServedCategory): ResolvedCategory => ({
+ driver,
+ keyPrefix: `${category}/`,
+ backendName: 'demo-local',
+ }),
+ };
+ const env: Provider = runtimeEnv ? { provide: RuntimeEnvService, useValue: runtimeEnv } : RuntimeEnvService;
+ const moduleRef = await Test.createTestingModule({
+ providers: [StorageService, { provide: StorageRegistryService, useValue: registry }, env],
+ }).compile();
+ const storage = moduleRef.get(StorageService);
+ return {
+ storage,
+ put: async (category, name, body = 'bytes') => {
+ await storage.put(category, name, Readable.from([Buffer.from(body)]));
+ return path.join(root, category, name);
+ },
+ };
+}
+
+describe('StorageService.delete on a demo instance', () => {
+ it('STORAGE-DEMO-001: names every served category exactly once', () => {
+ expect([...KEPT, ...DELETED].sort()).toEqual([...SERVED_CATEGORIES].sort());
+ });
+
+ it.each(KEPT)('STORAGE-DEMO-002: keeps the %s object and resolves as if it were gone', async (category) => {
+ process.env.DEMO_MODE = 'true';
+ const fx = await build();
+ const onDisk = await fx.put(category, 'baseline.jpg');
+
+ await expect(fx.storage.delete(category, 'baseline.jpg')).resolves.toBeUndefined();
+
+ expect(fs.existsSync(onDisk)).toBe(true);
+ expect(await fx.storage.exists(category, 'baseline.jpg')).toBe(true);
+ });
+
+ it.each(DELETED)('STORAGE-DEMO-003: still deletes the %s object', async (category) => {
+ process.env.DEMO_MODE = 'true';
+ const fx = await build();
+ const onDisk = await fx.put(category, 'cached.jpg');
+
+ await fx.storage.delete(category, 'cached.jpg');
+
+ expect(fs.existsSync(onDisk)).toBe(false);
+ });
+
+ it.each([...SERVED_CATEGORIES])('STORAGE-DEMO-004: outside demo mode deletes the %s object', async (category) => {
+ delete process.env.DEMO_MODE;
+ const fx = await build();
+ const onDisk = await fx.put(category, 'any.jpg');
+
+ await fx.storage.delete(category, 'any.jpg');
+
+ expect(fs.existsSync(onDisk)).toBe(false);
+ });
+
+ it('STORAGE-DEMO-005: a put after a kept delete still replaces the object under the same name', async () => {
+ process.env.DEMO_MODE = 'true';
+ const fx = await build();
+ const onDisk = await fx.put('covers', 'cover.jpg', 'old');
+
+ await fx.storage.delete('covers', 'cover.jpg');
+ await fx.put('covers', 'cover.jpg', 'new');
+
+ expect(fs.readFileSync(onDisk, 'utf8')).toBe('new');
+ });
+
+ it('STORAGE-DEMO-006: refuses a hostile name in demo mode as it does outside it', async () => {
+ process.env.DEMO_MODE = 'true';
+ const fx = await build();
+
+ await expect(fx.storage.delete('covers', '../escape.jpg')).rejects.toBeInstanceOf(StorageInvalidKeyError);
+ });
+
+ it('STORAGE-DEMO-007: reads DEMO_MODE on every call, so a toggle takes effect without a restart', async () => {
+ const fx = await build();
+ const first = await fx.put('journey', 'first.jpg');
+ const second = await fx.put('journey', 'second.jpg');
+
+ process.env.DEMO_MODE = 'true';
+ await fx.storage.delete('journey', 'first.jpg');
+ delete process.env.DEMO_MODE;
+ await fx.storage.delete('journey', 'second.jpg');
+
+ expect(fs.existsSync(first)).toBe(true);
+ expect(fs.existsSync(second)).toBe(false);
+ });
+
+ it('STORAGE-DEMO-008: asks the RuntimeEnvService the container hands it', async () => {
+ delete process.env.DEMO_MODE;
+ const fx = await build({ isDemoMode: () => true });
+ const onDisk = await fx.put('avatars', 'face.jpg');
+
+ await fx.storage.delete('avatars', 'face.jpg');
+
+ expect(fs.existsSync(onDisk)).toBe(true);
+ });
+
+ it('STORAGE-DEMO-009: still deletes the assistant attachments, which no baseline relies on', async () => {
+ process.env.DEMO_MODE = 'true';
+ const fx = await build();
+ const attachment = await fx.put('files', 'assistant/a1.pdf');
+ const tripFile = await fx.put('files', 'trip.pdf');
+
+ expect(fx.storage.keepsOnDelete('files', 'assistant/a1.pdf')).toBe(false);
+ expect(fx.storage.keepsOnDelete('files', 'trip.pdf')).toBe(true);
+ await fx.storage.delete('files', 'assistant/a1.pdf');
+ await fx.storage.delete('files', 'trip.pdf');
+
+ expect(fs.existsSync(attachment)).toBe(false);
+ expect(fs.existsSync(tripFile)).toBe(true);
+ });
+
+ it('STORAGE-DEMO-010: keepsOnDelete answers false for every category outside demo mode', async () => {
+ delete process.env.DEMO_MODE;
+ const fx = await build();
+
+ expect(SERVED_CATEGORIES.filter((category) => fx.storage.keepsOnDelete(category, 'any.jpg'))).toEqual([]);
+ });
+});
diff --git a/server/tests/unit/nest/thumbnail.service.test.ts b/server/tests/unit/nest/thumbnail.service.test.ts
index 31f0c2645..e5d646f8d 100644
--- a/server/tests/unit/nest/thumbnail.service.test.ts
+++ b/server/tests/unit/nest/thumbnail.service.test.ts
@@ -185,4 +185,18 @@ describe('sweepOrphanThumbs (spec fix #2)', () => {
expect(await svc.sweepOrphanThumbs()).toBe(0);
expect(fs.existsSync(note)).toBe(true);
});
+
+ it('THUMB-SWEEP-005: a demo instance keeps every journey object, so the sweep reports none removed', async () => {
+ const prevDemo = process.env.DEMO_MODE;
+ process.env.DEMO_MODE = 'true';
+ try {
+ const stray = writeThumb('demostray0000000.jpg');
+
+ expect(await svc.sweepOrphanThumbs()).toBe(0);
+ expect(fs.existsSync(stray)).toBe(true);
+ } finally {
+ if (prevDemo === undefined) delete process.env.DEMO_MODE;
+ else process.env.DEMO_MODE = prevDemo;
+ }
+ });
});