mirror of
https://github.com/mauriceboe/TREK.git
synced 2026-11-26 06:37:33 +00:00
feat(storage): find and reclaim upload objects no row names any more
Domains whose rows name stored objects register a reference source with StorageReclaimRegistryService; storage never imports them. A ledger in storage decides per category whether it is reclaimed at all and which sources must have answered first, and a category whose resolved location overlaps another one is left alone. A nightly pass at 04:05 lists the root level of files, journey, covers, avatars and places, skips objects younger than a day or without a modification time, asks every source in pages of 500 and marks the rest. Only with deletion switched on, and only for marks a week old, it asks every source about the single key again and deletes through StorageService. A category is skipped and its marks start over when a source is missing or fails, the listing fails, or more than a fifth of its objects look unreferenced. A pass shares the one-job slot with backfills and migrations, never runs on a demo instance and stops when the database is reopened. Admins switch deletion and run a pass on demand under /api/admin/storage/reclaim; both are audited, and GET /api/admin/storage carries the switch and the last report. Deletion is off after install and upgrade.
This commit is contained in:
@@ -0,0 +1,85 @@
|
||||
/**
|
||||
* StorageReclaimController over a stub service: what it forwards, what it
|
||||
* audits, and that a refusal of the service reaches the client unchanged.
|
||||
* RCLC-001 to RCLC-004.
|
||||
*/
|
||||
import type { AuditService } from '../../../../src/nest/audit/audit.service';
|
||||
import { DomainError } from '../../../../src/nest/common/domain-error';
|
||||
import type { StorageReclaimRunDto, StorageReclaimSettingsDto } from '../../../../src/nest/storage/storage-admin.dto';
|
||||
import { StorageReclaimController } from '../../../../src/nest/storage/storage-reclaim.controller';
|
||||
import type { StorageReclaimService } from '../../../../src/nest/storage/storage-reclaim.service';
|
||||
import { StorageModule } from '../../../../src/nest/storage/storage.module';
|
||||
import type { User } from '../../../../src/types';
|
||||
import { expectRegisteredController } from '../../../helpers/module-providers';
|
||||
import { STORAGE_RECLAIM_CATEGORIES, type StorageReclaimReport } from '@trek/shared';
|
||||
|
||||
import type { Request } from 'express';
|
||||
import { describe, expect, it, vi } from 'vitest';
|
||||
|
||||
const user = { id: 7 } as User;
|
||||
const req = { headers: {}, socket: { remoteAddress: '127.0.0.1' } } as unknown as Request;
|
||||
|
||||
function report(): StorageReclaimReport {
|
||||
const none = { objects: 0, bytes: 0 };
|
||||
const row = { objects: 0, unreferenced: none, eligible: none, deleted: none, skipped: null };
|
||||
return {
|
||||
startedAt: 1,
|
||||
finishedAt: 2,
|
||||
mode: 'delete',
|
||||
stopped: null,
|
||||
categories: {
|
||||
...(Object.fromEntries(STORAGE_RECLAIM_CATEGORIES.map((c) => [c, row])) as StorageReclaimReport['categories']),
|
||||
covers: { ...row, objects: 9, deleted: { objects: 2, bytes: 40 } },
|
||||
places: { ...row, objects: 3, deleted: { objects: 1, bytes: 2 } },
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
function makeController(over: Partial<Record<keyof StorageReclaimService, unknown>> = {}) {
|
||||
const writeAudit = vi.fn();
|
||||
const service = {
|
||||
setDeleteEnabled: vi.fn(async (enabled: boolean) => ({ deleteEnabled: enabled, lastRun: null })),
|
||||
run: vi.fn(async () => report()),
|
||||
...over,
|
||||
} as unknown as StorageReclaimService;
|
||||
const controller = new StorageReclaimController(service, { writeAudit } as unknown as AuditService);
|
||||
return { controller, service, writeAudit };
|
||||
}
|
||||
|
||||
describe('StorageReclaimController', () => {
|
||||
it('RCLC-001: is registered in StorageModule', () => {
|
||||
expectRegisteredController(StorageModule, StorageReclaimController);
|
||||
});
|
||||
|
||||
it('RCLC-002: PUT stores the switch, answers the fresh state and audits the value', async () => {
|
||||
const { controller, service, writeAudit } = makeController();
|
||||
const body = { deleteEnabled: true } as StorageReclaimSettingsDto;
|
||||
expect(await controller.update(user, body, req)).toEqual({ deleteEnabled: true, lastRun: null });
|
||||
expect(service.setDeleteEnabled).toHaveBeenCalledWith(true);
|
||||
expect(writeAudit).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ userId: 7, action: 'admin.storage_reclaim_update', details: { deleteEnabled: true } }),
|
||||
);
|
||||
});
|
||||
|
||||
it('RCLC-003: POST run forwards reportOnly, answers the report and audits the totals', async () => {
|
||||
const { controller, service, writeAudit } = makeController();
|
||||
const answer = await controller.run(user, { reportOnly: true } as StorageReclaimRunDto, req);
|
||||
expect(answer.categories.covers.deleted.objects).toBe(2);
|
||||
expect(service.run).toHaveBeenCalledWith({ reportOnly: true });
|
||||
await controller.run(user, {} as StorageReclaimRunDto, req);
|
||||
expect(service.run).toHaveBeenLastCalledWith({ reportOnly: false });
|
||||
expect(writeAudit).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
action: 'admin.storage_reclaim_run',
|
||||
details: { mode: 'delete', deleted: 3, bytes: 42 },
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
it('RCLC-004: a refused pass propagates as the DomainError and writes no audit row', async () => {
|
||||
const refusal = new DomainError(409, 'another storage job is running, one storage job at a time');
|
||||
const { controller, writeAudit } = makeController({ run: vi.fn().mockRejectedValue(refusal) });
|
||||
await expect(controller.run(user, {} as StorageReclaimRunDto, req)).rejects.toBe(refusal);
|
||||
expect(writeAudit).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,135 @@
|
||||
/**
|
||||
* StorageReclaimJob: the nightly 04:05 pass. It hands the registrar the pass's
|
||||
* own promise, so the lease covers the whole run, skips a demo instance and a
|
||||
* busy slot quietly, and logs one line only when the pass had something to say.
|
||||
* RCLJ-001 to RCLJ-006.
|
||||
*/
|
||||
import type { RuntimeEnvService } from '../../../../src/nest/app-config/runtime-env.service';
|
||||
import { logDebug, logError, logInfo } from '../../../../src/nest/audit/audit-log.logger';
|
||||
import { DomainError } from '../../../../src/nest/common/domain-error';
|
||||
import type { CronRegistrarService } from '../../../../src/nest/scheduling/cron-registrar.service';
|
||||
import { StorageReclaimJob } from '../../../../src/nest/storage/storage-reclaim.job';
|
||||
import type { StorageReclaimService } from '../../../../src/nest/storage/storage-reclaim.service';
|
||||
import { STORAGE_RECLAIM_CATEGORIES, type StorageReclaimReport } from '@trek/shared';
|
||||
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
|
||||
vi.mock('../../../../src/nest/audit/audit-log.logger', async (importOriginal) => ({
|
||||
...(await importOriginal<typeof import('../../../../src/nest/audit/audit-log.logger')>()),
|
||||
logInfo: vi.fn(),
|
||||
logDebug: vi.fn(),
|
||||
logError: vi.fn(),
|
||||
logWarn: vi.fn(),
|
||||
}));
|
||||
|
||||
function registrarStub(enabled = true) {
|
||||
return {
|
||||
isEnabled: vi.fn(() => enabled),
|
||||
register: vi.fn((_name: string, _expression: string, _onTick: () => void | Promise<void>) => enabled),
|
||||
unregister: vi.fn(),
|
||||
};
|
||||
}
|
||||
|
||||
function report(
|
||||
over: Partial<StorageReclaimReport['categories']> = {},
|
||||
stopped: StorageReclaimReport['stopped'] = null,
|
||||
) {
|
||||
const none = { objects: 0, bytes: 0 };
|
||||
const row = { objects: 0, unreferenced: none, eligible: none, deleted: none, skipped: null };
|
||||
return {
|
||||
startedAt: 1,
|
||||
finishedAt: 2,
|
||||
mode: 'delete',
|
||||
stopped,
|
||||
categories: { ...Object.fromEntries(STORAGE_RECLAIM_CATEGORIES.map((c) => [c, row])), ...over },
|
||||
} as StorageReclaimReport;
|
||||
}
|
||||
|
||||
function makeJob(run: () => Promise<StorageReclaimReport>, opts: { enabled?: boolean; demo?: boolean } = {}) {
|
||||
const registrar = registrarStub(opts.enabled ?? true);
|
||||
const reclaim = { run: vi.fn(run) };
|
||||
const env = { isDemoMode: () => opts.demo === true };
|
||||
const job = new StorageReclaimJob(
|
||||
registrar as unknown as CronRegistrarService,
|
||||
reclaim as unknown as StorageReclaimService,
|
||||
env as unknown as RuntimeEnvService,
|
||||
);
|
||||
return { job, registrar, reclaim };
|
||||
}
|
||||
|
||||
beforeEach(() => vi.clearAllMocks());
|
||||
|
||||
describe('StorageReclaimJob', () => {
|
||||
it('RCLJ-001: registers at 04:05 and hands the registrar the pass promise itself', async () => {
|
||||
let finish: (value: StorageReclaimReport) => void = () => undefined;
|
||||
const { job, registrar, reclaim } = makeJob(() => new Promise((resolve) => (finish = resolve)));
|
||||
job.onApplicationBootstrap();
|
||||
expect(registrar.register).toHaveBeenCalledWith('storage-reclaim', '5 4 * * *', expect.any(Function));
|
||||
const onTick = registrar.register.mock.calls[0]![2];
|
||||
const ticking = onTick();
|
||||
expect(ticking).toBeInstanceOf(Promise);
|
||||
let settled = false;
|
||||
void (ticking as Promise<void>).then(() => (settled = true));
|
||||
await Promise.resolve();
|
||||
expect(settled).toBe(false);
|
||||
finish(report());
|
||||
await ticking;
|
||||
expect(reclaim.run).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('RCLJ-002: does not register under the test gate, and never sweeps at boot', () => {
|
||||
const { job, registrar, reclaim } = makeJob(async () => report(), { enabled: false });
|
||||
job.onApplicationBootstrap();
|
||||
expect(registrar.register).not.toHaveBeenCalled();
|
||||
expect(reclaim.run).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('RCLJ-003: a demo instance is skipped without a pass', async () => {
|
||||
const { job, reclaim } = makeJob(async () => report(), { demo: true });
|
||||
await job.tick();
|
||||
expect(reclaim.run).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('RCLJ-004: logs one line only when something was found, deleted, skipped or stopped', async () => {
|
||||
const quiet = makeJob(async () => report({ photos: { ...report().categories.photos, skipped: 'not_reclaimed' } }));
|
||||
await quiet.job.tick(new Date(5));
|
||||
expect(quiet.reclaim.run).toHaveBeenCalledWith({ now: new Date(5) });
|
||||
expect(logInfo).not.toHaveBeenCalled();
|
||||
|
||||
const busy = report(
|
||||
{
|
||||
covers: {
|
||||
objects: 10,
|
||||
unreferenced: { objects: 2, bytes: 30 },
|
||||
eligible: { objects: 1, bytes: 10 },
|
||||
deleted: { objects: 1, bytes: 10 },
|
||||
skipped: null,
|
||||
},
|
||||
avatars: { ...report().categories.avatars, skipped: 'sources_missing' },
|
||||
},
|
||||
'database_reopened',
|
||||
);
|
||||
await makeJob(async () => busy).job.tick();
|
||||
expect(logInfo).toHaveBeenCalledWith(
|
||||
'Storage reclaim: 2 unreferenced object(s); deleted 1 (10 bytes); skipped avatars (sources_missing); stopped: database_reopened',
|
||||
);
|
||||
});
|
||||
|
||||
it('RCLJ-005: a refusal (busy, demo) is a debug line, not an error', async () => {
|
||||
const { job } = makeJob(async () => {
|
||||
throw new DomainError(409, 'another storage job is running', { code: 'reclaim_busy' });
|
||||
});
|
||||
await expect(job.tick()).resolves.toBeUndefined();
|
||||
expect(logDebug).toHaveBeenCalledWith('Storage reclaim skipped: another storage job is running');
|
||||
expect(logError).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('RCLJ-006: any other failure is contained in one error line', async () => {
|
||||
await makeJob(async () => {
|
||||
throw new Error('registry not initialized');
|
||||
}).job.tick();
|
||||
expect(logError).toHaveBeenCalledWith('Storage reclaim: registry not initialized');
|
||||
await makeJob(vi.fn<() => Promise<StorageReclaimReport>>().mockRejectedValue('plain')).job.tick();
|
||||
expect(logError).toHaveBeenCalledWith('Storage reclaim: plain');
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,194 @@
|
||||
/**
|
||||
* The reclaim ledger and the location check (#2924), plus the registry the
|
||||
* reference sources land in. RCLL-001 to RCLL-011.
|
||||
*/
|
||||
import { StorageReclaimRegistryService } from '../../../../src/nest/storage/storage-reclaim-registry.service';
|
||||
import {
|
||||
inReclaimScope,
|
||||
RECLAIM_LEDGER,
|
||||
reclaimableCategories,
|
||||
requiredReclaimSources,
|
||||
sharedLocationCategories,
|
||||
type CategoryAssignment,
|
||||
type ReclaimRule,
|
||||
} from '../../../../src/nest/storage/storage-reclaim.ledger';
|
||||
import {
|
||||
STORAGE_RECLAIMABLE_CATEGORIES,
|
||||
STORAGE_REFERENCE_SOURCE_IDS,
|
||||
type StorageReferenceSource,
|
||||
} from '../../../../src/nest/storage/storage-reclaim.types';
|
||||
import type { BackendSnapshot } from '../../../../src/nest/storage/storage-registry.service';
|
||||
import { CATEGORY_PREFIXES } from '../../../../src/nest/storage/storage-registry.service';
|
||||
import { SERVED_CATEGORIES, type ServedCategory } from '../../../../src/nest/storage/storage.types';
|
||||
|
||||
import path from 'node:path';
|
||||
import { describe, expect, it, vi } from 'vitest';
|
||||
|
||||
vi.mock('../../../../src/nest/audit/audit-log.logger', async (importOriginal) => ({
|
||||
...(await importOriginal<typeof import('../../../../src/nest/audit/audit-log.logger')>()),
|
||||
logInfo: vi.fn(),
|
||||
logDebug: vi.fn(),
|
||||
logError: vi.fn(),
|
||||
logWarn: vi.fn(),
|
||||
}));
|
||||
|
||||
const UPLOADS = path.resolve('/srv/trek/uploads');
|
||||
const BACKUPS = path.resolve('/srv/trek/backups');
|
||||
|
||||
function local(name: string, root: string): BackendSnapshot {
|
||||
return { name, type: 'local', source: 'settings', options: { root } };
|
||||
}
|
||||
|
||||
/** The default layout: every served category on uploads-local, backups on its own backend. */
|
||||
function defaults(overrides: Partial<Record<ServedCategory, CategoryAssignment>> = {}) {
|
||||
const map = new Map<ServedCategory, CategoryAssignment>();
|
||||
for (const category of SERVED_CATEGORIES) {
|
||||
map.set(category, { backendName: 'uploads-local', keyPrefix: CATEGORY_PREFIXES[category] });
|
||||
}
|
||||
map.set('backups', { backendName: 'backups-local', keyPrefix: '' });
|
||||
for (const [category, assignment] of Object.entries(overrides)) map.set(category as ServedCategory, assignment);
|
||||
return map;
|
||||
}
|
||||
|
||||
const BASE_BACKENDS = [local('uploads-local', UPLOADS), local('backups-local', BACKUPS)];
|
||||
|
||||
describe('RECLAIM_LEDGER', () => {
|
||||
it('RCLL-001: reclaims exactly the five content categories and never a cache, the backups or legacy photos', () => {
|
||||
expect(reclaimableCategories().sort()).toEqual([...STORAGE_RECLAIMABLE_CATEGORIES].sort());
|
||||
for (const category of ['photos', 'photos-google', 'photos-trek', 'backups'] as const) {
|
||||
const rule: ReclaimRule = RECLAIM_LEDGER[category];
|
||||
expect(rule.reclaim).toBe(false);
|
||||
if (!rule.reclaim) expect(rule.reason.length).toBeGreaterThan(10);
|
||||
}
|
||||
});
|
||||
|
||||
it('RCLL-002: every reclaimable category waits for all the free-form owners, files and avatars for their own too', () => {
|
||||
const freeForm = ['trips', 'collections', 'places', 'journey', 'photos'];
|
||||
for (const category of STORAGE_RECLAIMABLE_CATEGORIES) {
|
||||
const rule = RECLAIM_LEDGER[category];
|
||||
expect(rule.reclaim).toBe(true);
|
||||
if (rule.reclaim) expect(rule.requiredSources).toEqual(expect.arrayContaining(freeForm));
|
||||
}
|
||||
const files = RECLAIM_LEDGER.files;
|
||||
const avatars = RECLAIM_LEDGER.avatars;
|
||||
expect(files.reclaim && files.requiredSources).toContain('files');
|
||||
expect(avatars.reclaim && avatars.requiredSources).toContain('auth');
|
||||
expect([...requiredReclaimSources()].sort()).toEqual([...STORAGE_REFERENCE_SOURCE_IDS].sort());
|
||||
});
|
||||
|
||||
it('RCLL-003: only root-level keys are in scope', () => {
|
||||
expect(inReclaimScope('a.jpg')).toBe(true);
|
||||
expect(inReclaimScope('assistant/a.pdf')).toBe(false);
|
||||
expect(inReclaimScope('thumbs/x.jpg')).toBe(false);
|
||||
expect(inReclaimScope('')).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe('sharedLocationCategories', () => {
|
||||
it('RCLL-004: the default layout shares only the legacy photos folder, which holds both caches', () => {
|
||||
expect(sharedLocationCategories(defaults(), BASE_BACKENDS)).toEqual(new Set(['photos']));
|
||||
});
|
||||
|
||||
it('RCLL-005: TREK_PLACE_PHOTO_DIR inside the uploads folder overlaps the category it lands in', () => {
|
||||
const backends = [...BASE_BACKENDS, local('place-photos-local', path.join(UPLOADS, 'places'))];
|
||||
const shared = sharedLocationCategories(
|
||||
defaults({ 'photos-google': { backendName: 'place-photos-local', keyPrefix: '' } }),
|
||||
backends,
|
||||
);
|
||||
expect(shared.has('places')).toBe(true);
|
||||
expect(shared.has('photos-google')).toBe(true);
|
||||
expect(shared.has('covers')).toBe(false);
|
||||
});
|
||||
|
||||
it('RCLL-006: backups on the uploads backend sit at its root and contain everything, yet only backups is excluded', () => {
|
||||
const shared = sharedLocationCategories(defaults({ backups: { backendName: 'uploads-local', keyPrefix: '' } }), [
|
||||
local('uploads-local', UPLOADS),
|
||||
]);
|
||||
expect(shared.has('backups')).toBe(true);
|
||||
expect(shared.has('covers')).toBe(false);
|
||||
});
|
||||
|
||||
it('RCLL-007: two backends of other names on one folder overlap, compared without regard to case', () => {
|
||||
const backends = [...BASE_BACKENDS, local('again', UPLOADS.toUpperCase() + path.sep)];
|
||||
const shared = sharedLocationCategories(
|
||||
defaults({ avatars: { backendName: 'again', keyPrefix: 'covers/' } }),
|
||||
backends,
|
||||
);
|
||||
expect(shared.has('covers')).toBe(true);
|
||||
expect(shared.has('avatars')).toBe(true);
|
||||
expect(shared.has('files')).toBe(false);
|
||||
});
|
||||
|
||||
it('RCLL-008: two s3 backends on one bucket and key prefix overlap, a different key prefix does not', () => {
|
||||
const s3 = (name: string, keyPrefix: string): BackendSnapshot => ({
|
||||
name,
|
||||
type: 's3',
|
||||
source: 'settings',
|
||||
options: { endpoint: 'https://s3.example.com/', bucket: 'trek', keyPrefix },
|
||||
});
|
||||
const backends = [...BASE_BACKENDS, s3('a', '/prod/'), s3('b', 'prod'), s3('c', 'dev'), s3('d', '')];
|
||||
const shared = sharedLocationCategories(
|
||||
defaults({
|
||||
covers: { backendName: 'a', keyPrefix: 'covers/' },
|
||||
avatars: { backendName: 'b', keyPrefix: 'covers/' },
|
||||
places: { backendName: 'c', keyPrefix: 'places/' },
|
||||
files: { backendName: 'd', keyPrefix: 'files/' },
|
||||
}),
|
||||
backends,
|
||||
);
|
||||
expect(shared.has('covers')).toBe(true);
|
||||
expect(shared.has('avatars')).toBe(true);
|
||||
expect(shared.has('places')).toBe(false);
|
||||
expect(shared.has('files')).toBe(false);
|
||||
});
|
||||
|
||||
it('RCLL-009: a mirror counts its primary and every replica; a replica inside another category excludes it', () => {
|
||||
const backends: BackendSnapshot[] = [
|
||||
...BASE_BACKENDS,
|
||||
local('primary', path.resolve('/mnt/primary')),
|
||||
local('replica', path.join(UPLOADS, 'journey')),
|
||||
{ name: 'm', type: 'mirror', source: 'settings', options: { primary: 'primary', replicas: ['replica'] } },
|
||||
];
|
||||
const shared = sharedLocationCategories(defaults({ covers: { backendName: 'm', keyPrefix: 'covers/' } }), backends);
|
||||
// The replica's copy of covers lands at uploads/journey/covers/, inside journey's location.
|
||||
expect(shared.has('journey')).toBe(true);
|
||||
expect(shared.has('covers')).toBe(false);
|
||||
});
|
||||
|
||||
it('RCLL-010: a location that cannot be resolved fails closed, for itself and for every other category', () => {
|
||||
const backends: BackendSnapshot[] = [
|
||||
...BASE_BACKENDS,
|
||||
{ name: 'odd', type: 'local', source: 'settings', options: { root: '' } },
|
||||
{ name: 'odd-s3', type: 's3', source: 'settings', options: { bucket: 'x' } },
|
||||
{ name: 'odd-mirror', type: 'mirror', source: 'settings', options: { primary: 'gone', replicas: 'x' } },
|
||||
];
|
||||
expect(
|
||||
sharedLocationCategories(defaults({ covers: { backendName: 'odd', keyPrefix: 'covers/' } }), backends).has(
|
||||
'files',
|
||||
),
|
||||
).toBe(true);
|
||||
for (const backendName of ['odd-s3', 'odd-mirror', 'missing']) {
|
||||
const shared = sharedLocationCategories(defaults({ covers: { backendName, keyPrefix: 'covers/' } }), backends);
|
||||
expect(shared.has('covers')).toBe(true);
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe('StorageReclaimRegistryService', () => {
|
||||
const source = (id: StorageReferenceSource['id']): StorageReferenceSource => ({
|
||||
id,
|
||||
claims: [{ category: 'covers', prefix: '' }],
|
||||
referenced: async () => new Set<string>(),
|
||||
});
|
||||
|
||||
it('RCLL-011: registers once per instance, keeps two sources of one id, and answers the ids', () => {
|
||||
const registry = new StorageReclaimRegistryService();
|
||||
const trips = source('trips');
|
||||
registry.register(trips);
|
||||
registry.register(trips);
|
||||
registry.register(source('trips'));
|
||||
registry.register(source('auth'));
|
||||
expect(registry.sources()).toHaveLength(3);
|
||||
expect(registry.ids()).toEqual(new Set(['trips', 'auth']));
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,465 @@
|
||||
/**
|
||||
* The storage reclaim pass (#2924) over a real StorageModule: a real registry
|
||||
* and LocalDriver on temp folders, the marks table in the snapshot db, and
|
||||
* fake reference sources standing in for the owner domains. The pass marks
|
||||
* first, deletes a week later only with the switch on and only after asking
|
||||
* every source about the single key again; every brake skips a category and
|
||||
* starts its marks over. RCLS-001 to RCLS-021.
|
||||
*/
|
||||
import { AppSettings } from '../../../../src/db/entities/AppSettings.entity';
|
||||
import { StorageReclaimMarks } from '../../../../src/db/entities/StorageReclaimMarks.entity';
|
||||
import { dbNow } from '../../../../src/db/types';
|
||||
import { RuntimeEnvService } from '../../../../src/nest/app-config/runtime-env.service';
|
||||
import { logError } from '../../../../src/nest/audit/audit-log.logger';
|
||||
import { DomainError } from '../../../../src/nest/common/domain-error';
|
||||
import { DatabaseLifecycle } from '../../../../src/nest/database/database-lifecycle.service';
|
||||
import { StorageAdminService } from '../../../../src/nest/storage/storage-admin.service';
|
||||
import { StorageJobsService } from '../../../../src/nest/storage/storage-jobs.service';
|
||||
import { StorageReclaimRegistryService } from '../../../../src/nest/storage/storage-reclaim-registry.service';
|
||||
import { StorageReclaimService } from '../../../../src/nest/storage/storage-reclaim.service';
|
||||
import {
|
||||
STORAGE_RECLAIMABLE_CATEGORIES,
|
||||
STORAGE_REFERENCE_SOURCE_IDS,
|
||||
type StorageReferenceClaim,
|
||||
type StorageReferenceSource,
|
||||
type StorageReferenceSourceId,
|
||||
} from '../../../../src/nest/storage/storage-reclaim.types';
|
||||
import { StorageModule } from '../../../../src/nest/storage/storage.module';
|
||||
import { StorageService } from '../../../../src/nest/storage/storage.service';
|
||||
import type { ServedCategory } from '../../../../src/nest/storage/storage.types';
|
||||
import { createSnapshotTestDb } from '../../../helpers/db-mock';
|
||||
import { deleteRows } from '../../../helpers/factories/rows';
|
||||
import { readAppSetting, setAppSetting } from '../../../helpers/factories/settings';
|
||||
import { createTestModule, type TestModule } from '../../../helpers/test-module';
|
||||
import { createTestOrm, type TestOrm } from '../../../helpers/test-orm';
|
||||
|
||||
import fs from 'node:fs';
|
||||
import os from 'node:os';
|
||||
import path from 'node:path';
|
||||
import { Readable } from 'node:stream';
|
||||
import { afterAll, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
|
||||
vi.mock('../../../../src/nest/audit/audit-log.logger', async (importOriginal) => ({
|
||||
...(await importOriginal<typeof import('../../../../src/nest/audit/audit-log.logger')>()),
|
||||
logInfo: vi.fn(),
|
||||
logDebug: vi.fn(),
|
||||
logError: vi.fn(),
|
||||
logWarn: vi.fn(),
|
||||
}));
|
||||
|
||||
const DAY = 24 * 60 * 60 * 1000;
|
||||
const db = createSnapshotTestDb();
|
||||
let t: TestModule;
|
||||
let orm: TestOrm;
|
||||
let uploadsRoot: string;
|
||||
let backupsRoot: string;
|
||||
let reclaim: StorageReclaimService;
|
||||
let storage: StorageService;
|
||||
let references: StorageReclaimRegistryService;
|
||||
let reopen: () => Promise<void>;
|
||||
/** What the fake sources still name, per category. */
|
||||
let named: Map<ServedCategory, Set<string>>;
|
||||
/** Called on every question a source is asked, before it answers. */
|
||||
let onAsk: ((category: ServedCategory, keys: readonly string[]) => void | Promise<void>) | null;
|
||||
|
||||
function fakeSource(id: StorageReferenceSourceId): StorageReferenceSource {
|
||||
const categories: readonly ServedCategory[] =
|
||||
id === 'auth' ? ['avatars'] : id === 'files' ? ['files'] : STORAGE_RECLAIMABLE_CATEGORIES;
|
||||
return {
|
||||
id,
|
||||
claims: categories.map((category): StorageReferenceClaim => ({ category, prefix: '' })),
|
||||
async referenced(category, keys) {
|
||||
await onAsk?.(category, keys);
|
||||
const set = named.get(category) ?? new Set<string>();
|
||||
return new Set(keys.filter((key) => set.has(key)));
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
function backends(extra: unknown[] = []): string {
|
||||
return JSON.stringify([
|
||||
{ name: 'uploads-local', type: 'local', options: { root: uploadsRoot } },
|
||||
{ name: 'backups-local', type: 'local', options: { root: backupsRoot } },
|
||||
...extra,
|
||||
]);
|
||||
}
|
||||
|
||||
async function put(category: ServedCategory, key: string, body = '12345'): Promise<void> {
|
||||
await storage.put(category, key, Readable.from(body));
|
||||
}
|
||||
|
||||
function objectPath(category: string, key: string): string {
|
||||
return path.join(uploadsRoot, category, key);
|
||||
}
|
||||
|
||||
/** The orphans plus `kept` named covers, so the orphans stay under the brake's fifth. */
|
||||
async function seedCovers(orphans: string[], kept = 4): Promise<void> {
|
||||
const keptKeys = Array.from({ length: kept }, (_unused, i) => `kept-${i}.jpg`);
|
||||
await Promise.all([...orphans, ...keptKeys].map((key) => put('covers', key)));
|
||||
named.set('covers', new Set(keptKeys));
|
||||
}
|
||||
|
||||
async function marksOf(category: string): Promise<Array<{ key: string; first_seen_at: string }>> {
|
||||
const rows = await orm.repo(StorageReclaimMarks).marksOf(category);
|
||||
return rows
|
||||
.map((row) => ({ key: row.key, first_seen_at: row.first_seen_at }))
|
||||
.sort((a, b) => a.key.localeCompare(b.key));
|
||||
}
|
||||
|
||||
beforeAll(async () => {
|
||||
uploadsRoot = fs.mkdtempSync(path.join(os.tmpdir(), 'trek-reclaim-uploads-'));
|
||||
backupsRoot = fs.mkdtempSync(path.join(os.tmpdir(), 'trek-reclaim-backups-'));
|
||||
orm = await createTestOrm(db);
|
||||
await setAppSetting(orm, 'storage.backends', backends());
|
||||
t = await createTestModule({
|
||||
db,
|
||||
imports: [StorageModule],
|
||||
init: true,
|
||||
overrides: [
|
||||
{
|
||||
provide: DatabaseLifecycle,
|
||||
useValue: {
|
||||
onReopened: (listener: () => Promise<void>) => {
|
||||
reopen = listener;
|
||||
},
|
||||
},
|
||||
},
|
||||
],
|
||||
});
|
||||
reclaim = t.get(StorageReclaimService);
|
||||
storage = t.get(StorageService);
|
||||
references = t.get(StorageReclaimRegistryService);
|
||||
for (const id of STORAGE_REFERENCE_SOURCE_IDS) references.register(fakeSource(id));
|
||||
});
|
||||
|
||||
beforeEach(async () => {
|
||||
vi.restoreAllMocks();
|
||||
vi.mocked(logError).mockClear();
|
||||
for (const entry of fs.readdirSync(uploadsRoot)) {
|
||||
if (entry !== '.tmp') fs.rmSync(path.join(uploadsRoot, entry), { recursive: true, force: true });
|
||||
}
|
||||
await deleteRows(orm, StorageReclaimMarks);
|
||||
await deleteRows(orm, AppSettings, { key: { $like: 'storage.reclaim%' } });
|
||||
named = new Map();
|
||||
onAsk = null;
|
||||
});
|
||||
|
||||
afterAll(async () => {
|
||||
await t.close();
|
||||
await orm.close();
|
||||
db.close();
|
||||
fs.rmSync(uploadsRoot, { recursive: true, force: true });
|
||||
fs.rmSync(backupsRoot, { recursive: true, force: true });
|
||||
});
|
||||
|
||||
const T0 = new Date(Date.now() + 2 * DAY);
|
||||
const WEEK_LATER = new Date(T0.getTime() + 8 * DAY);
|
||||
|
||||
describe('StorageReclaimService: mark, then sweep', () => {
|
||||
it('RCLS-001: a first pass only reports and marks; the report is persisted and the state carries it', async () => {
|
||||
await seedCovers(['orphan.jpg']);
|
||||
const report = await reclaim.run({ now: T0 });
|
||||
expect(report.mode).toBe('report');
|
||||
expect(report.stopped).toBeNull();
|
||||
expect(report.categories.covers).toEqual({
|
||||
objects: 5,
|
||||
unreferenced: { objects: 1, bytes: 5 },
|
||||
eligible: { objects: 0, bytes: 0 },
|
||||
deleted: { objects: 0, bytes: 0 },
|
||||
skipped: null,
|
||||
});
|
||||
expect(report.categories.files).toMatchObject({ objects: 0, skipped: null });
|
||||
for (const category of ['photos', 'photos-google', 'photos-trek', 'backups'] as const) {
|
||||
expect(report.categories[category].skipped).toBe('not_reclaimed');
|
||||
}
|
||||
expect(await marksOf('covers')).toEqual([{ key: 'orphan.jpg', first_seen_at: dbNow(T0) }]);
|
||||
expect(await reclaim.state()).toEqual({ deleteEnabled: false, lastRun: report });
|
||||
expect((await t.get(StorageAdminService).state()).reclaim).toEqual({ deleteEnabled: false, lastRun: report });
|
||||
});
|
||||
|
||||
it('RCLS-002: with deletion on, a mark a week old goes through the facade and takes its mark along', async () => {
|
||||
await seedCovers(['orphan.jpg']);
|
||||
await reclaim.setDeleteEnabled(true);
|
||||
const first = await reclaim.run({ now: T0 });
|
||||
expect(first.mode).toBe('delete');
|
||||
expect(first.categories.covers.deleted.objects).toBe(0);
|
||||
expect(fs.existsSync(objectPath('covers', 'orphan.jpg'))).toBe(true);
|
||||
|
||||
const second = await reclaim.run({ now: WEEK_LATER });
|
||||
expect(second.categories.covers.eligible).toEqual({ objects: 1, bytes: 5 });
|
||||
expect(second.categories.covers.deleted).toEqual({ objects: 1, bytes: 5 });
|
||||
expect(fs.existsSync(objectPath('covers', 'orphan.jpg'))).toBe(false);
|
||||
expect(fs.existsSync(objectPath('covers', 'kept-0.jpg'))).toBe(true);
|
||||
expect(await marksOf('covers')).toEqual([]);
|
||||
});
|
||||
|
||||
it('RCLS-003: a report-only pass deletes nothing even with deletion on', async () => {
|
||||
await seedCovers(['orphan.jpg']);
|
||||
await reclaim.setDeleteEnabled(true);
|
||||
await reclaim.run({ now: T0 });
|
||||
const report = await reclaim.run({ now: WEEK_LATER, reportOnly: true });
|
||||
expect(report.mode).toBe('report');
|
||||
expect(report.categories.covers.eligible.objects).toBe(1);
|
||||
expect(report.categories.covers.deleted.objects).toBe(0);
|
||||
expect(fs.existsSync(objectPath('covers', 'orphan.jpg'))).toBe(true);
|
||||
});
|
||||
|
||||
it('RCLS-004: an object named again loses its mark, and its week starts over once it is unnamed', async () => {
|
||||
await seedCovers(['orphan.jpg']);
|
||||
await reclaim.setDeleteEnabled(true);
|
||||
await reclaim.run({ now: T0 });
|
||||
named.get('covers')!.add('orphan.jpg');
|
||||
const renamed = await reclaim.run({ now: new Date(T0.getTime() + DAY) });
|
||||
expect(renamed.categories.covers.unreferenced.objects).toBe(0);
|
||||
expect(await marksOf('covers')).toEqual([]);
|
||||
|
||||
named.get('covers')!.delete('orphan.jpg');
|
||||
const again = await reclaim.run({ now: WEEK_LATER });
|
||||
expect(again.categories.covers.eligible.objects).toBe(0);
|
||||
expect(fs.existsSync(objectPath('covers', 'orphan.jpg'))).toBe(true);
|
||||
expect(await marksOf('covers')).toEqual([{ key: 'orphan.jpg', first_seen_at: dbNow(WEEK_LATER) }]);
|
||||
});
|
||||
|
||||
it('RCLS-005: the single-key re-check right before the delete keeps an object named in between', async () => {
|
||||
await seedCovers(['orphan.jpg']);
|
||||
await reclaim.setDeleteEnabled(true);
|
||||
await reclaim.run({ now: T0 });
|
||||
onAsk = (category, keys) => {
|
||||
if (category === 'covers' && keys.length === 1) named.get('covers')!.add(keys[0]!);
|
||||
};
|
||||
const report = await reclaim.run({ now: WEEK_LATER });
|
||||
expect(report.categories.covers.eligible.objects).toBe(1);
|
||||
expect(report.categories.covers.deleted.objects).toBe(0);
|
||||
expect(fs.existsSync(objectPath('covers', 'orphan.jpg'))).toBe(true);
|
||||
expect(await marksOf('covers')).toEqual([]);
|
||||
});
|
||||
|
||||
it('RCLS-006: young objects, a missing modification time and nested subtrees are never judged', async () => {
|
||||
await put('covers', 'young.jpg');
|
||||
await put('covers', 'zero.jpg');
|
||||
await put('files', 'assistant/attached.pdf');
|
||||
await put('journey', 'thumbs/abcdef.jpg');
|
||||
const now = T0;
|
||||
fs.utimesSync(
|
||||
objectPath('covers', 'young.jpg'),
|
||||
new Date(now.getTime() - 60_000),
|
||||
new Date(now.getTime() - 60_000),
|
||||
);
|
||||
fs.utimesSync(objectPath('covers', 'zero.jpg'), 0, 0);
|
||||
const report = await reclaim.run({ now });
|
||||
expect(report.categories.covers).toMatchObject({ objects: 2, unreferenced: { objects: 0, bytes: 0 } });
|
||||
expect(report.categories.files.objects).toBe(0);
|
||||
expect(report.categories.journey.objects).toBe(0);
|
||||
expect(await marksOf('covers')).toEqual([]);
|
||||
});
|
||||
});
|
||||
|
||||
describe('StorageReclaimService: brakes', () => {
|
||||
it('RCLS-007: more than a fifth unreferenced skips the category, deletes nothing and clears its marks', async () => {
|
||||
await seedCovers(['o1.jpg', 'o2.jpg'], 1);
|
||||
await orm.repo(StorageReclaimMarks).insertMissing('covers', [{ key: 'o1.jpg', size: 5 }], dbNow(new Date(0)));
|
||||
await reclaim.setDeleteEnabled(true);
|
||||
const report = await reclaim.run({ now: WEEK_LATER });
|
||||
expect(report.categories.covers).toEqual({
|
||||
objects: 3,
|
||||
unreferenced: { objects: 2, bytes: 10 },
|
||||
eligible: { objects: 0, bytes: 0 },
|
||||
deleted: { objects: 0, bytes: 0 },
|
||||
skipped: 'too_many_unreferenced',
|
||||
});
|
||||
expect(fs.existsSync(objectPath('covers', 'o1.jpg'))).toBe(true);
|
||||
expect(await marksOf('covers')).toEqual([]);
|
||||
});
|
||||
|
||||
it('RCLS-008: a category whose required source is missing, or answers for a part only, is skipped', async () => {
|
||||
await seedCovers(['orphan.jpg']);
|
||||
const all = [...references.sources()];
|
||||
const withoutAuth = all.filter((source) => source.id !== 'auth');
|
||||
vi.spyOn(references, 'sources').mockReturnValue(withoutAuth);
|
||||
let report = await reclaim.run({ now: T0 });
|
||||
expect(report.categories.avatars.skipped).toBe('sources_missing');
|
||||
expect(report.categories.covers.skipped).toBeNull();
|
||||
|
||||
const partialTrips: StorageReferenceSource = {
|
||||
id: 'trips',
|
||||
claims: [{ category: 'covers', prefix: 'sub/' }],
|
||||
referenced: async () => new Set<string>(),
|
||||
};
|
||||
vi.spyOn(references, 'sources').mockReturnValue([...all.filter((source) => source.id !== 'trips'), partialTrips]);
|
||||
report = await reclaim.run({ now: T0 });
|
||||
expect(report.categories.covers.skipped).toBe('sources_missing');
|
||||
expect(await marksOf('covers')).toEqual([]);
|
||||
});
|
||||
|
||||
it('RCLS-009: a source answering for a subtree only is not asked about root keys', async () => {
|
||||
await seedCovers(['orphan.jpg']);
|
||||
const subtree = vi.fn(async () => new Set<string>());
|
||||
vi.spyOn(references, 'sources').mockReturnValue([
|
||||
...references.sources(),
|
||||
{ id: 'trips', claims: [{ category: 'covers', prefix: 'sub/' }], referenced: subtree },
|
||||
]);
|
||||
const report = await reclaim.run({ now: T0 });
|
||||
expect(report.categories.covers.unreferenced.objects).toBe(1);
|
||||
expect(subtree).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('RCLS-010: a category whose location holds another category is skipped', async () => {
|
||||
await seedCovers(['orphan.jpg']);
|
||||
const nestedRoot = path.join(uploadsRoot, 'covers');
|
||||
await setAppSetting(
|
||||
orm,
|
||||
'storage.backends',
|
||||
backends([{ name: 'nested', type: 'local', options: { root: nestedRoot } }]),
|
||||
);
|
||||
await setAppSetting(orm, 'storage.categories', JSON.stringify({ 'photos-trek': 'nested' }));
|
||||
await storage.reloadConfig();
|
||||
try {
|
||||
const report = await reclaim.run({ now: T0 });
|
||||
expect(report.categories.covers.skipped).toBe('shared_location');
|
||||
expect(report.categories.files.skipped).toBeNull();
|
||||
} finally {
|
||||
await setAppSetting(orm, 'storage.backends', backends());
|
||||
await deleteRows(orm, AppSettings, { key: 'storage.categories' });
|
||||
await storage.reloadConfig();
|
||||
}
|
||||
});
|
||||
|
||||
it('RCLS-011: a listing that fails skips the category and clears its marks', async () => {
|
||||
await orm.repo(StorageReclaimMarks).insertMissing('covers', [{ key: 'x.jpg', size: 1 }], dbNow(new Date(0)));
|
||||
vi.spyOn(storage, 'list').mockImplementation(() => ({
|
||||
[Symbol.asyncIterator]: () => ({ next: () => Promise.reject(new Error('backend down')) }),
|
||||
}));
|
||||
const report = await reclaim.run({ now: T0 });
|
||||
expect(report.categories.covers.skipped).toBe('list_failed');
|
||||
expect(report.categories.files.skipped).toBe('list_failed');
|
||||
expect(logError).toHaveBeenCalledWith(expect.stringContaining('backend down'));
|
||||
expect(await marksOf('covers')).toEqual([]);
|
||||
});
|
||||
|
||||
it('RCLS-012: a source that fails skips the category, never reads it as unreferenced', async () => {
|
||||
await seedCovers(['orphan.jpg']);
|
||||
onAsk = (category) => {
|
||||
if (category === 'covers') throw new Error('trips table locked');
|
||||
};
|
||||
const report = await reclaim.run({ now: T0 });
|
||||
expect(report.categories.covers).toMatchObject({ objects: 5, skipped: 'source_failed' });
|
||||
expect(report.categories.places.skipped).toBeNull();
|
||||
expect(logError).toHaveBeenCalledWith(expect.stringContaining('trips table locked'));
|
||||
});
|
||||
|
||||
it('RCLS-013: a pass refuses on a demo instance and while another storage job holds the slot', async () => {
|
||||
const demo = vi.spyOn(t.get(RuntimeEnvService), 'isDemoMode').mockReturnValue(true);
|
||||
await expect(reclaim.run()).rejects.toMatchObject({ code: 'reclaim_demo' });
|
||||
demo.mockRestore();
|
||||
|
||||
const jobs = t.get(StorageJobsService);
|
||||
expect(jobs.claimExclusive('a test')).toBe(true);
|
||||
try {
|
||||
const refusal = await reclaim.run().catch((err: unknown) => err);
|
||||
expect(refusal).toBeInstanceOf(DomainError);
|
||||
expect(refusal).toMatchObject({ code: 'reclaim_busy' });
|
||||
expect((refusal as DomainError).getStatus()).toBe(409);
|
||||
} finally {
|
||||
jobs.releaseExclusive('a test');
|
||||
}
|
||||
});
|
||||
|
||||
it('RCLS-014: while a pass holds the slot, a migration is refused with its name, and the slot is free after', async () => {
|
||||
const jobs = t.get(StorageJobsService);
|
||||
let refusal: unknown = null;
|
||||
onAsk = async (category) => {
|
||||
if (category !== 'covers' || refusal) return;
|
||||
refusal = await jobs.startMigration('covers', 'backups-local').catch((err: unknown) => err);
|
||||
};
|
||||
await seedCovers(['orphan.jpg']);
|
||||
await reclaim.run({ now: T0 });
|
||||
expect(String(refusal)).toContain('a storage reclaim is running, one storage job at a time');
|
||||
expect(jobs.claimExclusive('after')).toBe(true);
|
||||
jobs.releaseExclusive('after');
|
||||
});
|
||||
|
||||
it('RCLS-015: a database reopened mid-pass stops it before anything else is judged', async () => {
|
||||
await seedCovers(['orphan.jpg']);
|
||||
await put('places', 'p.jpg');
|
||||
let reopened = false;
|
||||
onAsk = async (category) => {
|
||||
if (category === 'covers' && !reopened) {
|
||||
reopened = true;
|
||||
await reopen();
|
||||
}
|
||||
};
|
||||
const report = await reclaim.run({ now: T0 });
|
||||
expect(report.stopped).toBe('database_reopened');
|
||||
expect(report.categories.covers.unreferenced.objects).toBe(0);
|
||||
expect(report.categories.places.objects).toBe(0);
|
||||
expect(await marksOf('covers')).toEqual([]);
|
||||
expect((await reclaim.state()).lastRun?.stopped).toBe('database_reopened');
|
||||
});
|
||||
});
|
||||
|
||||
describe('StorageReclaimService: the delete itself', () => {
|
||||
async function markedWeekOld(orphans: string[], kept = 4): Promise<void> {
|
||||
await seedCovers(orphans, kept);
|
||||
await reclaim.setDeleteEnabled(true);
|
||||
await reclaim.run({ now: T0 });
|
||||
}
|
||||
|
||||
it('RCLS-016: a re-check that fails keeps the object', async () => {
|
||||
await markedWeekOld(['orphan.jpg']);
|
||||
onAsk = (_category, keys) => {
|
||||
if (keys.length === 1) throw new Error('lookup timed out');
|
||||
};
|
||||
const report = await reclaim.run({ now: WEEK_LATER });
|
||||
expect(report.categories.covers.deleted.objects).toBe(0);
|
||||
expect(fs.existsSync(objectPath('covers', 'orphan.jpg'))).toBe(true);
|
||||
expect(logError).toHaveBeenCalledWith(expect.stringContaining('lookup timed out'));
|
||||
});
|
||||
|
||||
it('RCLS-017: an object gone or written again since it was judged is left and its mark dropped', async () => {
|
||||
await markedWeekOld(['gone.jpg', 'fresh.jpg'], 8);
|
||||
onAsk = (_category, keys) => {
|
||||
if (keys.length !== 1) return;
|
||||
if (keys[0] === 'gone.jpg') fs.rmSync(objectPath('covers', 'gone.jpg'), { force: true });
|
||||
if (keys[0] === 'fresh.jpg') fs.utimesSync(objectPath('covers', 'fresh.jpg'), WEEK_LATER, WEEK_LATER);
|
||||
};
|
||||
const report = await reclaim.run({ now: WEEK_LATER });
|
||||
expect(report.categories.covers.eligible.objects).toBe(2);
|
||||
expect(report.categories.covers.deleted.objects).toBe(0);
|
||||
expect(fs.existsSync(objectPath('covers', 'fresh.jpg'))).toBe(true);
|
||||
expect(await marksOf('covers')).toEqual([]);
|
||||
});
|
||||
|
||||
it('RCLS-018: a delete that fails keeps the mark for the next pass', async () => {
|
||||
await markedWeekOld(['orphan.jpg']);
|
||||
vi.spyOn(storage, 'delete').mockRejectedValue(new Error('permission denied'));
|
||||
const report = await reclaim.run({ now: WEEK_LATER });
|
||||
expect(report.categories.covers.deleted.objects).toBe(0);
|
||||
expect(await marksOf('covers')).toEqual([{ key: 'orphan.jpg', first_seen_at: dbNow(T0) }]);
|
||||
expect(logError).toHaveBeenCalledWith(expect.stringContaining('permission denied'));
|
||||
});
|
||||
|
||||
it('RCLS-019: an object the facade keeps on delete is not counted as reclaimed', async () => {
|
||||
await markedWeekOld(['orphan.jpg']);
|
||||
vi.spyOn(storage, 'keepsOnDelete').mockReturnValue(true);
|
||||
const report = await reclaim.run({ now: WEEK_LATER });
|
||||
expect(report.categories.covers.deleted.objects).toBe(0);
|
||||
expect(fs.existsSync(objectPath('covers', 'orphan.jpg'))).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe('StorageReclaimService: the switch and the stored report', () => {
|
||||
it('RCLS-020: the switch is stored as true or false and only the exact true deletes', async () => {
|
||||
expect((await reclaim.setDeleteEnabled(true)).deleteEnabled).toBe(true);
|
||||
expect(await readAppSetting(orm, 'storage.reclaim_delete')).toBe('true');
|
||||
expect((await reclaim.setDeleteEnabled(false)).deleteEnabled).toBe(false);
|
||||
await setAppSetting(orm, 'storage.reclaim_delete', 'yes');
|
||||
expect((await reclaim.state()).deleteEnabled).toBe(false);
|
||||
});
|
||||
|
||||
it('RCLS-021: a stored report that no longer parses reads as never run', async () => {
|
||||
await setAppSetting(orm, 'storage.reclaim_report', '{not json');
|
||||
expect((await reclaim.state()).lastRun).toBeNull();
|
||||
await setAppSetting(orm, 'storage.reclaim_report', JSON.stringify({ startedAt: 'yesterday' }));
|
||||
expect((await reclaim.state()).lastRun).toBeNull();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,125 @@
|
||||
/**
|
||||
* The reference parser every reclaim source builds on (#2924): which objects a
|
||||
* stored value names, in every spelling the columns hold. A key reported too
|
||||
* many only keeps an object; one missed would delete it, so the cases lean on
|
||||
* the spellings the validators let through (absolute self-URLs, queries,
|
||||
* relative journey covers, legacy file names). RCLP-001 to RCLP-012.
|
||||
*/
|
||||
import {
|
||||
referencedAmong,
|
||||
storageKeysIn,
|
||||
uploadKeysIn,
|
||||
type StorageKeyOptions,
|
||||
type StorageKeyRef,
|
||||
} from '../../../../src/nest/storage/storage-reclaim.types';
|
||||
|
||||
import { describe, expect, it } from 'vitest';
|
||||
|
||||
const ref = (category: string, key: string): StorageKeyRef => ({ category, key });
|
||||
|
||||
describe('uploadKeysIn', () => {
|
||||
it('RCLP-001: finds the path in its plain, slash-less and absolute self-URL spellings', () => {
|
||||
expect(uploadKeysIn('/uploads/covers/a.jpg')).toEqual([ref('covers', 'a.jpg')]);
|
||||
expect(uploadKeysIn('uploads/files/b.pdf')).toEqual([ref('files', 'b.pdf')]);
|
||||
expect(uploadKeysIn('https://trip.example.com/uploads/places/c.png')).toEqual([ref('places', 'c.png')]);
|
||||
expect(uploadKeysIn('HTTPS://HOST/Uploads/Covers/D.JPG')).toEqual([ref('covers', 'D.JPG')]);
|
||||
});
|
||||
|
||||
it('RCLP-002: drops a query or a fragment, decodes and trims the key', () => {
|
||||
expect(uploadKeysIn('/uploads/places/x.jpg?v=2')).toEqual([ref('places', 'x.jpg')]);
|
||||
expect(uploadKeysIn('/uploads/places/x.jpg#top')).toEqual([ref('places', 'x.jpg')]);
|
||||
expect(uploadKeysIn(' /uploads/covers/y.jpg ')).toEqual([ref('covers', 'y.jpg')]);
|
||||
expect(uploadKeysIn('/uploads/photos/my%20photo.jpg')).toEqual([
|
||||
ref('photos', 'my%20photo.jpg'),
|
||||
ref('photos', 'my photo.jpg'),
|
||||
ref('photos', 'my'),
|
||||
]);
|
||||
});
|
||||
|
||||
it('RCLP-003: finds every path in a text, each cut where the next begins or the text ends', () => {
|
||||
expect(uploadKeysIn('see /uploads/covers/a.jpg and "/uploads/places/b.jpg" too')).toEqual([
|
||||
ref('covers', 'a.jpg and'),
|
||||
ref('covers', 'a.jpg'),
|
||||
ref('places', 'b.jpg'),
|
||||
]);
|
||||
expect(uploadKeysIn('/uploads/covers/a.jpg/uploads/places/b.jpg')).toEqual([
|
||||
ref('covers', 'a.jpg'),
|
||||
ref('places', 'b.jpg'),
|
||||
]);
|
||||
});
|
||||
|
||||
it('RCLP-004: keeps a nested key whole and refuses empty or climbing keys', () => {
|
||||
expect(uploadKeysIn('/uploads/journey/thumbs/abc.jpg')).toEqual([ref('journey', 'thumbs/abc.jpg')]);
|
||||
expect(uploadKeysIn('/uploads/covers/')).toEqual([]);
|
||||
expect(uploadKeysIn('/uploads/covers/../avatars/a.jpg')).toEqual([]);
|
||||
expect(uploadKeysIn('/uploads/covers/%2E%2E/x')).toEqual([ref('covers', '%2E%2E/x')]);
|
||||
});
|
||||
|
||||
it('RCLP-005: names nothing for empty values, other hosts and other paths', () => {
|
||||
expect(uploadKeysIn(null)).toEqual([]);
|
||||
expect(uploadKeysIn(undefined)).toEqual([]);
|
||||
expect(uploadKeysIn('')).toEqual([]);
|
||||
expect(uploadKeysIn('https://images.unsplash.com/photo-123?w=800')).toEqual([]);
|
||||
expect(uploadKeysIn('/api/maps/place-photo/abc/bytes')).toEqual([]);
|
||||
expect(uploadKeysIn('/my-uploads/covers/a.jpg')).toEqual([]);
|
||||
});
|
||||
|
||||
it('RCLP-006: a broken percent sequence keeps the raw key', () => {
|
||||
expect(uploadKeysIn('/uploads/covers/100%.jpg')).toEqual([ref('covers', '100%.jpg')]);
|
||||
});
|
||||
});
|
||||
|
||||
describe('storageKeysIn', () => {
|
||||
it('RCLP-007: reads the relative <category>/<key> spelling of journey covers', () => {
|
||||
expect(storageKeysIn('covers/a.jpg')).toEqual([ref('covers', 'a.jpg')]);
|
||||
expect(storageKeysIn('journey/b.jpg?x=1')).toEqual([ref('journey', 'b.jpg')]);
|
||||
expect(storageKeysIn('./journey/thumbs/c.jpg')).toEqual([ref('journey', 'thumbs/c.jpg')]);
|
||||
expect(storageKeysIn('notacategory/a.jpg')).toEqual([]);
|
||||
});
|
||||
|
||||
it('RCLP-008: a bare name belongs to the column category, a URL or a path does not', () => {
|
||||
expect(storageKeysIn('a1b2.jpg', { bare: 'avatars' })).toEqual([ref('avatars', 'a1b2.jpg')]);
|
||||
expect(storageKeysIn('https://idp.example.com/pic.jpg', { bare: 'avatars' })).toEqual([]);
|
||||
expect(storageKeysIn('some/dir/x.pdf', { bare: 'files' })).toEqual([]);
|
||||
expect(storageKeysIn('a1b2.jpg')).toEqual([]);
|
||||
});
|
||||
|
||||
it('RCLP-009: with basename, a legacy path still names its last segment', () => {
|
||||
expect(storageKeysIn('files/x.pdf', { bare: 'files', basename: true })).toEqual([
|
||||
ref('files', 'x.pdf'),
|
||||
ref('files', 'x.pdf'),
|
||||
]);
|
||||
expect(storageKeysIn('/uploads/files/y.pdf', { bare: 'files', basename: true })).toEqual([
|
||||
ref('files', 'y.pdf'),
|
||||
ref('files', 'y.pdf'),
|
||||
]);
|
||||
expect(storageKeysIn('C:\\old\\uploads\\z.pdf', { bare: 'files', basename: true })).toEqual([
|
||||
ref('files', 'z.pdf'),
|
||||
]);
|
||||
});
|
||||
|
||||
it('RCLP-010: names nothing for a blank or a non-string', () => {
|
||||
expect(storageKeysIn(' ', { bare: 'files' })).toEqual([]);
|
||||
expect(storageKeysIn('?only=query', { bare: 'files' })).toEqual([]);
|
||||
expect(storageKeysIn(null)).toEqual([]);
|
||||
expect(storageKeysIn(42 as unknown as string)).toEqual([]);
|
||||
});
|
||||
});
|
||||
|
||||
describe('referencedAmong', () => {
|
||||
it('RCLP-011: answers the candidates of one category the values name, without regard to case', () => {
|
||||
const values = ['/uploads/covers/A.JPG', 'covers/b.jpg', '/uploads/places/c.jpg', null, 'https://elsewhere/x'];
|
||||
expect(referencedAmong('covers', ['a.jpg', 'b.jpg', 'c.jpg', 'd.jpg'], values)).toEqual(
|
||||
new Set(['a.jpg', 'b.jpg']),
|
||||
);
|
||||
expect(referencedAmong('places', ['c.jpg'], values)).toEqual(new Set(['c.jpg']));
|
||||
});
|
||||
|
||||
it('RCLP-012: passes the column options on, so a bare avatar name keeps its object', () => {
|
||||
const avatarColumn: StorageKeyOptions = { bare: 'avatars' };
|
||||
expect(referencedAmong('avatars', ['u1.png'], ['u1.png'], avatarColumn)).toEqual(new Set(['u1.png']));
|
||||
expect(
|
||||
referencedAmong('avatars', ['u1.png', 'u2.png'], ['u1.png', 'https://idp/u2.png'], { bare: 'avatars' }),
|
||||
).toEqual(new Set(['u1.png']));
|
||||
});
|
||||
});
|
||||
Reference in New Issue
Block a user