From 46717209829ac5f2a275e51065266f0d9259a048 Mon Sep 17 00:00:00 2001 From: jubnl Date: Thu, 20 Aug 2026 22:45:49 +0200 Subject: [PATCH] =?UTF-8?q?feat(server):=20storage=20usage=20scan=20?= =?UTF-8?q?=E2=80=94=20nightly=20cron,=20on-demand=20service,=20persisted?= =?UTF-8?q?=20with=20computedAt?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../src/nest/storage/storage-stats.service.ts | 68 +++++++++++ .../nest/storage/storage-usage-scan.job.ts | 29 +++++ server/src/nest/storage/storage.module.ts | 15 ++- .../storage/storage-stats.service.test.ts | 109 ++++++++++++++++++ 4 files changed, 219 insertions(+), 2 deletions(-) create mode 100644 server/src/nest/storage/storage-stats.service.ts create mode 100644 server/src/nest/storage/storage-usage-scan.job.ts create mode 100644 server/tests/unit/nest/storage/storage-stats.service.test.ts diff --git a/server/src/nest/storage/storage-stats.service.ts b/server/src/nest/storage/storage-stats.service.ts new file mode 100644 index 000000000..f36da67e7 --- /dev/null +++ b/server/src/nest/storage/storage-stats.service.ts @@ -0,0 +1,68 @@ +import { Injectable, Logger } from '@nestjs/common'; +import { STORAGE_CATEGORIES, storageUsageSchema, type StorageUsage } from '@trek/shared'; +import { DatabaseService } from '../database/database.service'; +import { StorageService } from './storage.service'; + +export class StatsBusyError extends Error {} + +export const USAGE_KEY = 'storage.usage'; + +/** + * Usage scan (backfill/stats spec): walks every served category through the + * facade — a mirrored category therefore lists its PRIMARY, the source of + * truth — and persists one JSON row with computedAt. Local backends pay one + * stat per file; s3 sizes ride the paginated listing. photos-google / + * photos-trek nest under the legacy photos/ prefix in mode A, so the legacy + * walk must exclude their subtrees to avoid double counting — the same + * google/ trek/ skip the backup walk uses. + */ +@Injectable() +export class StorageStatsService { + private readonly logger = new Logger(StorageStatsService.name); + private scanning = false; + + constructor( + private readonly storage: StorageService, + private readonly db: DatabaseService, + ) {} + + async scan(): Promise { + if (this.scanning) throw new StatsBusyError('a usage scan is already running'); + this.scanning = true; + try { + const categories = {} as StorageUsage['categories']; + for (const category of STORAGE_CATEGORIES) { + let objects = 0; + let bytes = 0; + for await (const stat of this.storage.list(category)) { + objects += 1; + bytes += stat.size; + } + categories[category] = { objects, bytes }; + } + const legacyPhotos = { objects: 0, bytes: 0 }; + for await (const stat of this.storage.list('photos')) { + if (stat.key.startsWith('google/') || stat.key.startsWith('trek/')) continue; + legacyPhotos.objects += 1; + legacyPhotos.bytes += stat.size; + } + const usage: StorageUsage = { computedAt: Date.now(), categories, legacyPhotos }; + this.db.run('INSERT OR REPLACE INTO app_settings (key, value) VALUES (?, ?)', USAGE_KEY, JSON.stringify(usage)); + return usage; + } finally { + this.scanning = false; + } + } + + /** The stored row, parsed; null when absent or unparseable (logged, never a 500). */ + readUsage(): StorageUsage | null { + const row = this.db.get<{ value: string }>('SELECT value FROM app_settings WHERE key = ?', USAGE_KEY); + if (!row) return null; + try { + return storageUsageSchema.parse(JSON.parse(row.value)); + } catch { + this.logger.warn('stored storage.usage row is unparseable — treating as never computed'); + return null; + } + } +} diff --git a/server/src/nest/storage/storage-usage-scan.job.ts b/server/src/nest/storage/storage-usage-scan.job.ts new file mode 100644 index 000000000..956a6ce52 --- /dev/null +++ b/server/src/nest/storage/storage-usage-scan.job.ts @@ -0,0 +1,29 @@ +import { Injectable, Logger, OnApplicationBootstrap } from '@nestjs/common'; +import { CronRegistrarService } from '../scheduling/cron-registrar.service'; +import { StorageStatsService } from './storage-stats.service'; + +/** Nightly usage scan — 04:15, off the backup and thumb-sweep hours. */ +@Injectable() +export class StorageUsageScanJob implements OnApplicationBootstrap { + private readonly logger = new Logger(StorageUsageScanJob.name); + + constructor( + private readonly registrar: CronRegistrarService, + private readonly stats: StorageStatsService, + ) {} + + onApplicationBootstrap(): void { + if (!this.registrar.isEnabled()) return; + this.registrar.register('storage-usage-scan', '15 4 * * *', () => { + void this.tick(); + }); + } + + async tick(): Promise { + try { + await this.stats.scan(); + } catch (err) { + this.logger.error(`usage scan failed: ${err instanceof Error ? err.message : String(err)}`); + } + } +} diff --git a/server/src/nest/storage/storage.module.ts b/server/src/nest/storage/storage.module.ts index 43937b221..ad8fb644d 100644 --- a/server/src/nest/storage/storage.module.ts +++ b/server/src/nest/storage/storage.module.ts @@ -1,12 +1,15 @@ import { Module } from '@nestjs/common'; import { AppConfigModule } from '../app-config/app-config.module'; import { AuditModule } from '../audit/audit.module'; +import { SchedulingModule } from '../scheduling/scheduling.module'; import { StorageEventsService } from './storage-events.service'; import { StorageJobsService } from './storage-jobs.service'; import { StorageRegistryService } from './storage-registry.service'; import { StorageService } from './storage.service'; import { StorageAdminService } from './storage-admin.service'; import { StorageAdminController } from './storage-admin.controller'; +import { StorageStatsService } from './storage-stats.service'; +import { StorageUsageScanJob } from './storage-usage-scan.job'; /** * Storage container: registry (config), facade (byte-paths), admin surface. @@ -22,9 +25,17 @@ import { StorageAdminController } from './storage-admin.controller'; * may cache drivers or trigger reloads. */ @Module({ - imports: [AppConfigModule, AuditModule], + imports: [AppConfigModule, AuditModule, SchedulingModule], controllers: [StorageAdminController], - providers: [StorageRegistryService, StorageService, StorageAdminService, StorageEventsService, StorageJobsService], + providers: [ + StorageRegistryService, + StorageService, + StorageAdminService, + StorageEventsService, + StorageJobsService, + StorageStatsService, + StorageUsageScanJob, + ], exports: [StorageService, StorageEventsService], }) export class StorageModule {} diff --git a/server/tests/unit/nest/storage/storage-stats.service.test.ts b/server/tests/unit/nest/storage/storage-stats.service.test.ts new file mode 100644 index 000000000..a2a6bec66 --- /dev/null +++ b/server/tests/unit/nest/storage/storage-stats.service.test.ts @@ -0,0 +1,109 @@ +import { describe, it, expect, vi, beforeAll, beforeEach, afterEach } from 'vitest'; + +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'); + return { testDb: db, dbMock: { db, closeDb: () => {}, reinitialize: () => {} } }; +}); +vi.mock('../../../../src/db/database', () => dbMock); +vi.mock('../../../../src/config', () => ({ ENCRYPTION_KEY: 'storage-stats-test-key' })); + +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 { StorageEventsService } from '../../../../src/nest/storage/storage-events.service'; +import { StorageRegistryService } from '../../../../src/nest/storage/storage-registry.service'; +import { StorageService } from '../../../../src/nest/storage/storage.service'; +import { StatsBusyError, StorageStatsService } from '../../../../src/nest/storage/storage-stats.service'; + +const db = new DatabaseService(testDb); + +beforeAll(() => { + createTables(testDb); + runMigrations(testDb); +}); + +const tmpDirs: string[] = []; +function makeTmpDir(): string { + const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'trek-stats-')); + tmpDirs.push(dir); + return dir; +} +function setSetting(key: string, value: string): void { + testDb.prepare('INSERT OR REPLACE INTO app_settings (key, value) VALUES (?, ?)').run(key, value); +} +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 }); +}); + +function makeWorld() { + const uploadsRoot = makeTmpDir(); + const backupsRoot = makeTmpDir(); + setSetting( + 'storage.backends', + JSON.stringify([ + { name: 'uploads-local', type: 'local', options: { root: uploadsRoot } }, + { name: 'backups-local', type: 'local', options: { root: backupsRoot } }, + ]), + ); + const env = { env: () => ({ paths: {}, security: { encryptionKeySet: true } }) } as unknown as RuntimeEnvService; + const registry = new StorageRegistryService(db, env, new StorageEventsService()); + registry.onModuleInit(); + const storage = new StorageService(registry); + const stats = new StorageStatsService(storage, db); + return { storage, stats, uploadsRoot }; +} + +describe('StorageStatsService', () => { + it('STATS-001 sums objects and bytes per category, legacy photos separate, and persists with computedAt', async () => { + const { storage, stats } = makeWorld(); + await storage.put('files', 'a.pdf', Readable.from('12345')); // 5 bytes + await storage.put('files', 'b.pdf', Readable.from('123')); // 3 bytes + await storage.put('covers', 'c.jpg', Readable.from('1234567')); // 7 bytes + await storage.put('photos', 'legacy.jpg', Readable.from('12')); // legacy dir + const usage = await stats.scan(); + expect(usage.categories.files).toEqual({ objects: 2, bytes: 8 }); + expect(usage.categories.covers).toEqual({ objects: 1, bytes: 7 }); + expect(usage.categories.backups).toEqual({ objects: 0, bytes: 0 }); + expect(usage.legacyPhotos).toEqual({ objects: 1, bytes: 2 }); + expect(usage.computedAt).toBeGreaterThan(0); + // Persisted round-trip: + expect(stats.readUsage()).toEqual(usage); + const raw = testDb.prepare("SELECT value FROM app_settings WHERE key = 'storage.usage'").get() as { value: string }; + expect(JSON.parse(raw.value)).toEqual(usage); + }); + + it('STATS-002 photos-google/photos-trek nested content is NOT double-counted into legacy photos', async () => { + const { storage, stats } = makeWorld(); + await storage.put('photos-google', 'g.jpg', Readable.from('gggg')); + const usage = await stats.scan(); + expect(usage.categories['photos-google']).toEqual({ objects: 1, bytes: 4 }); + expect(usage.legacyPhotos).toEqual({ objects: 0, bytes: 0 }); + }); + + it('STATS-003 concurrent scans throw StatsBusyError', async () => { + const { storage, stats } = makeWorld(); + for (let i = 0; i < 30; i++) await storage.put('files', `f${i}.bin`, Readable.from('x'.repeat(500))); + const first = stats.scan(); + await expect(stats.scan()).rejects.toThrow(StatsBusyError); + await first; + }); + + it('STATS-004 readUsage returns null on absent or unparseable rows', () => { + const { stats } = makeWorld(); + expect(stats.readUsage()).toBeNull(); + setSetting('storage.usage', 'not json'); + expect(stats.readUsage()).toBeNull(); + }); +});