fix(storage): judge unreferenced files without a brake anyone can trip

The 20 % brake skipped a category and wiped its marks every night once a
fifth of it looked unreferenced. Any user could push a small install over
that line, a backlog from #2924 started braked, and a second install on the
same bucket below the line was not caught at all. It is gone:

- Each pass leaves a trek-owner-<install id> marker at the root of every
  category it judges. A category holding another install's marker is
  skipped as foreign_install, one where the marker cannot be written as
  owner_unknown. Backups leave the markers out.
- The install id lives in app_settings outside the storage.* prefix. The
  switch is stored as that id, so a database from another install reads as
  off, and every reopen (a restore) writes this install's id back, turns
  deletion off and drops the marks, confirmations and reports.
- More than a fifth unreferenced still marks and reports, but deletes only
  after an admin confirmed the count shown (POST .../reclaim/confirm). A
  larger count later waits again.

A skip no longer touches the marks, so a failed listing or lookup does not
restart the week. Check now runs in the background and answers 202; the
admin state says running and keeps the last deleting report apart, so a
report-only check never resets what was freed. A pass that deletes writes a
system audit entry, a pass that stops or fails keeps its partial counts and
marks the rest interrupted, a backend error stops deleting in its category,
and deleting stops for the rest of the pass once the switch is off or a
backup is reading the uploads. The usage scan waits for a pass still
running.

Sources read each category once per pass and answer the pre-delete
re-check with a query narrowed to the keys' plain runs. Bare names keep
their raw spelling (a '#', '?' or trailing blank is part of an upload's
name), and local roots are resolved through their symlinks before the
overlap check. A pass lists only a category's root.
This commit is contained in:
Maurice
2026-11-01 16:18:08 +01:00
parent e59992d56d
commit 790fccb92c
48 changed files with 1786 additions and 661 deletions
@@ -56,8 +56,8 @@ export class StorageReclaimMarksRepository extends TrekRepository<StorageReclaim
return Number(result.numDeletedRows);
}
/** Drops every mark of a category, for a pass that could not judge it: the week starts over. */
async deleteCategory(category: string): Promise<number> {
return await this.nativeDelete({ category });
/** Drops every mark, for a database a restore brought back: its marks are another history's. */
async deleteAll(): Promise<number> {
return await this.nativeDelete({});
}
}
+3 -1
View File
@@ -32,7 +32,9 @@ const ACTION_LABELS: Record<string, string> = {
'admin.storage_backfill_cancel': 'cancelled a storage sync',
'admin.storage_stats_refresh': 'refreshed storage usage stats',
'admin.storage_reclaim_update': 'switched storage reclaim deletion',
'admin.storage_reclaim_run': 'ran a storage reclaim pass',
'admin.storage_reclaim_run': 'started a storage reclaim check',
'admin.storage_reclaim_confirm': 'confirmed deleting a large share of unreferenced storage objects',
'storage.reclaim_deleted': 'deleted unreferenced storage objects',
'admin.places_contribute_decision': 'decided on sharing place details with TREK Places',
'admin.places_contribute_withdraw': 'withdrew the place details this installation shared',
'immich.private_ip_configured': 'configured Immich with private IP',
@@ -1,5 +1,5 @@
import { Users } from '../../db/entities/Users.entity';
import { StorageReclaimSource } from '../storage/storage-reclaim-source.service';
import { likeAny, StorageReclaimSource } from '../storage/storage-reclaim-source.service';
import { Injectable } from '@nestjs/common';
/**
@@ -14,8 +14,10 @@ export class AuthStorageRefsService extends StorageReclaimSource {
readonly claims = [{ category: 'avatars', prefix: '' }] as const;
protected override readonly keyOptions = { bare: 'avatars' } as const;
protected async storedValues(): Promise<Array<string | null | undefined>> {
const rows = await this.em.getRepository(Users).find({ avatar: { $ne: null } }, { fields: ['avatar'] });
protected async storedValues(containing: readonly string[] | null): Promise<Array<string | null | undefined>> {
const rows = await this.em
.getRepository(Users)
.find(likeAny<Users>(['avatar'], containing), { fields: ['avatar'] });
return rows.map((row) => row.avatar);
}
}
+5
View File
@@ -9,6 +9,7 @@ import { invalidatePermissionsCache } from '../permissions/permissions-cache';
import { snapshotAllPluginDataDbs } from '../plugins/host/plugin-data.service';
import { pluginsCodeRoot, pluginsDataRoot } from '../plugins/paths';
import { stageExtractedPluginTrees, applyStagedRestoreNow } from '../plugins/plugin-backup';
import { storageOwnerMarkerInstall } from '../storage/storage-reclaim.types';
import type { StorageService } from '../storage/storage.service';
import { StorageInvalidKeyError } from '../storage/storage.types';
import { VALID_INTERVALS } from './auto-backup.settings';
@@ -217,6 +218,10 @@ export async function createBackup(
// In mode A the google/trek caches nest under the photos/ prefix — the
// category walk would sweep them back in without this skip.
if (category === 'photos' && (obj.key.startsWith('google/') || obj.key.startsWith('trek/'))) continue;
// The storage reclaim pass's owner marker names the install that wrote
// it; restored elsewhere, it would make that install's own uploads look
// shared with a foreign one.
if (storageOwnerMarkerInstall(obj.key) !== null) continue;
// Local path available (exists on disk right now — the fail-safe half
// of getLocalPathOrNull's contract) → push it directly: zero-copy, the
// default-install path. Otherwise (a remote/S3 primary, or a local
+8 -2
View File
@@ -32,8 +32,14 @@ export class BackupService {
listBackups() {
return svc.listBackups(this.storage);
}
createBackup(prefix?: 'backup' | 'auto-backup') {
return svc.createBackup(this.deps, prefix);
/** Marked running while it reads the uploads, so the storage reclaim pass deletes nothing it still archives. */
async createBackup(prefix?: 'backup' | 'auto-backup') {
this.jobs.beginBackup();
try {
return await svc.createBackup(this.deps, prefix);
} finally {
this.jobs.endBackup();
}
}
restoreFromZip(zipPath: string) {
return this.whileRestoring(() => svc.restoreFromZip(this.deps, zipPath));
@@ -1,6 +1,6 @@
import { CollectionPlaces } from '../../db/entities/CollectionPlaces.entity';
import { Collections } from '../../db/entities/Collections.entity';
import { StorageReclaimSource } from '../storage/storage-reclaim-source.service';
import { likeAny, StorageReclaimSource } from '../storage/storage-reclaim-source.service';
import { EVERY_RECLAIMABLE_CATEGORY } from '../storage/storage-reclaim.types';
import { Injectable } from '@nestjs/common';
@@ -16,13 +16,13 @@ export class CollectionsStorageRefsService extends StorageReclaimSource {
readonly id = 'collections';
readonly claims = EVERY_RECLAIMABLE_CATEGORY;
protected async storedValues(): Promise<Array<string | null | undefined>> {
protected async storedValues(containing: readonly string[] | null): Promise<Array<string | null | undefined>> {
const covers = await this.em
.getRepository(Collections)
.find({ cover_image: { $ne: null } }, { fields: ['cover_image'] });
.find(likeAny<Collections>(['cover_image'], containing), { fields: ['cover_image'] });
const images = await this.em
.getRepository(CollectionPlaces)
.find({ image_url: { $ne: null } }, { fields: ['image_url'] });
.find(likeAny<CollectionPlaces>(['image_url'], containing), { fields: ['image_url'] });
return [...covers.map((row) => row.cover_image), ...images.map((row) => row.image_url)];
}
}
@@ -134,6 +134,7 @@ export const MANAGED_ROUTE_ALLOW_LIST: string[] = [
'StorageAdminController.statsRefresh',
'StorageAdminController.test',
'StorageAdminController.update',
'StorageReclaimController.confirm',
'StorageReclaimController.run',
'StorageReclaimController.update',
];
@@ -1,5 +1,5 @@
import { TripFiles } from '../../db/entities/TripFiles.entity';
import { StorageReclaimSource } from '../storage/storage-reclaim-source.service';
import { likeAny, StorageReclaimSource } from '../storage/storage-reclaim-source.service';
import { Injectable } from '@nestjs/common';
/**
@@ -19,8 +19,10 @@ export class FilesStorageRefsService extends StorageReclaimSource {
readonly claims = [{ category: 'files', prefix: '' }] as const;
protected override readonly keyOptions = { bare: 'files', basename: true } as const;
protected async storedValues(): Promise<Array<string | null | undefined>> {
const rows = await this.em.getRepository(TripFiles).find({}, { fields: ['filename'] });
protected async storedValues(containing: readonly string[] | null): Promise<Array<string | null | undefined>> {
const rows = await this.em
.getRepository(TripFiles)
.find(likeAny<TripFiles>(['filename'], containing), { fields: ['filename'] });
return rows.map((row) => row.filename);
}
}
@@ -1,5 +1,5 @@
import { Journeys } from '../../db/entities/Journeys.entity';
import { StorageReclaimSource } from '../storage/storage-reclaim-source.service';
import { likeAny, StorageReclaimSource } from '../storage/storage-reclaim-source.service';
import { EVERY_RECLAIMABLE_CATEGORY } from '../storage/storage-reclaim.types';
import { Injectable } from '@nestjs/common';
@@ -15,10 +15,10 @@ export class JourneyStorageRefsService extends StorageReclaimSource {
readonly id = 'journey';
readonly claims = EVERY_RECLAIMABLE_CATEGORY;
protected async storedValues(): Promise<Array<string | null | undefined>> {
protected async storedValues(containing: readonly string[] | null): Promise<Array<string | null | undefined>> {
const rows = await this.em
.getRepository(Journeys)
.find({ cover_image: { $ne: null } }, { fields: ['cover_image'] });
.find(likeAny<Journeys>(['cover_image'], containing), { fields: ['cover_image'] });
return rows.map((row) => row.cover_image);
}
}
@@ -1,5 +1,5 @@
import { TrekPhotos } from '../../db/entities/TrekPhotos.entity';
import { StorageReclaimSource } from '../storage/storage-reclaim-source.service';
import { likeAny, StorageReclaimSource } from '../storage/storage-reclaim-source.service';
import { EVERY_RECLAIMABLE_CATEGORY } from '../storage/storage-reclaim.types';
import { Injectable } from '@nestjs/common';
@@ -20,13 +20,12 @@ export class PhotosStorageRefsService extends StorageReclaimSource {
readonly claims = EVERY_RECLAIMABLE_CATEGORY;
protected override readonly keyOptions = { bare: 'journey', basename: true } as const;
protected async storedValues(): Promise<Array<string | null | undefined>> {
protected async storedValues(containing: readonly string[] | null): Promise<Array<string | null | undefined>> {
const rows = await this.em
.getRepository(TrekPhotos)
.find(
{ $or: [{ file_path: { $ne: null } }, { thumbnail_path: { $ne: null } }] },
{ fields: ['file_path', 'thumbnail_path'] },
);
.find(likeAny<TrekPhotos>(['file_path', 'thumbnail_path'], containing), {
fields: ['file_path', 'thumbnail_path'],
});
return rows.flatMap((row) => [row.file_path, row.thumbnail_path]);
}
}
@@ -1,5 +1,5 @@
import { PlaceContribOutbox } from '../../db/entities/PlaceContribOutbox.entity';
import { StorageReclaimSource } from '../storage/storage-reclaim-source.service';
import { likeAny, StorageReclaimSource } from '../storage/storage-reclaim-source.service';
import { EVERY_RECLAIMABLE_CATEGORY } from '../storage/storage-reclaim.types';
import { Injectable } from '@nestjs/common';
@@ -15,8 +15,10 @@ export class PlaceContribStorageRefsService extends StorageReclaimSource {
readonly id = 'place-contrib';
readonly claims = EVERY_RECLAIMABLE_CATEGORY;
protected async storedValues(): Promise<Array<string | null | undefined>> {
const rows = await this.em.getRepository(PlaceContribOutbox).find({}, { fields: ['value'] });
protected async storedValues(containing: readonly string[] | null): Promise<Array<string | null | undefined>> {
const rows = await this.em
.getRepository(PlaceContribOutbox)
.find(likeAny<PlaceContribOutbox>(['value'], containing), { fields: ['value'] });
return rows.map((row) => row.value);
}
}
@@ -1,5 +1,5 @@
import { Places } from '../../db/entities/Places.entity';
import { StorageReclaimSource } from '../storage/storage-reclaim-source.service';
import { likeAny, StorageReclaimSource } from '../storage/storage-reclaim-source.service';
import { EVERY_RECLAIMABLE_CATEGORY } from '../storage/storage-reclaim.types';
import { Injectable } from '@nestjs/common';
@@ -16,8 +16,10 @@ export class PlacesStorageRefsService extends StorageReclaimSource {
readonly id = 'places';
readonly claims = EVERY_RECLAIMABLE_CATEGORY;
protected async storedValues(): Promise<Array<string | null | undefined>> {
const rows = await this.em.getRepository(Places).find({ image_url: { $ne: null } }, { fields: ['image_url'] });
protected async storedValues(containing: readonly string[] | null): Promise<Array<string | null | undefined>> {
const rows = await this.em
.getRepository(Places)
.find(likeAny<Places>(['image_url'], containing), { fields: ['image_url'] });
return rows.map((row) => row.image_url);
}
}
@@ -5,6 +5,7 @@ import {
StorageInvalidKeyError,
StorageNotFoundError,
type ByteRange,
type ListOptions,
type LocalTempFile,
type ObjectStat,
type StorageDriver,
@@ -175,13 +176,13 @@ export class LocalDriver implements StorageDriver {
}
}
async *list(prefix: string): AsyncIterable<ObjectStat> {
async *list(prefix: string, opts: ListOptions = {}): AsyncIterable<ObjectStat> {
assertValidPrefix(prefix);
const root = this.root();
yield* this.walk(prefix ? path.resolve(root, prefix) : root, root);
yield* this.walk(prefix ? path.resolve(root, prefix) : root, root, opts.shallow === true);
}
private async *walk(dir: string, root: string): AsyncIterable<ObjectStat> {
private async *walk(dir: string, root: string, shallow: boolean): AsyncIterable<ObjectStat> {
let entries: fs.Dirent[];
try {
entries = await fs.promises.readdir(dir, { withFileTypes: true });
@@ -195,7 +196,7 @@ export class LocalDriver implements StorageDriver {
if (entry.name.startsWith('.')) continue;
const entryPath = path.join(dir, entry.name);
if (entry.isDirectory()) {
yield* this.walk(entryPath, root);
if (!shallow) yield* this.walk(entryPath, root, false);
} else if (entry.isFile()) {
const st = await fs.promises.stat(entryPath);
yield {
@@ -6,6 +6,7 @@ import {
StorageInvalidKeyError,
StorageNotFoundError,
type ByteRange,
type ListOptions,
type LocalTempFile,
type ObjectStat,
type PutOptions,
@@ -195,11 +196,11 @@ export class MirrorDriver implements StorageDriver {
}
}
async *list(prefix: string): AsyncIterable<ObjectStat> {
async *list(prefix: string, opts: ListOptions = {}): AsyncIterable<ObjectStat> {
assertValidPrefix(prefix);
let yieldedAny = false;
try {
for await (const stat of this.primary.list(prefix)) {
for await (const stat of this.primary.list(prefix, opts)) {
yieldedAny = true;
yield stat;
}
@@ -210,7 +211,7 @@ export class MirrorDriver implements StorageDriver {
if (yieldedAny || !shouldFallback(err)) throw err;
for (const replica of this.replicas) {
try {
for await (const stat of replica.list(prefix)) yield stat;
for await (const stat of replica.list(prefix, opts)) yield stat;
return;
} catch {
/* try next replica */
+5 -2
View File
@@ -5,6 +5,7 @@ import {
StorageNotFoundError,
isLocalTempFile,
type ByteRange,
type ListOptions,
type LocalTempFile,
type ObjectStat,
type PutOptions,
@@ -403,13 +404,15 @@ export class S3Driver implements StorageDriver {
}
}
async *list(prefix: string): AsyncIterable<ObjectStat> {
async *list(prefix: string, opts: ListOptions = {}): AsyncIterable<ObjectStat> {
assertValidPrefix(prefix);
const s3 = await this.client();
// A delimiter makes S3 fold every deeper key into CommonPrefixes, which are not read.
const shallow = opts.shallow === true ? { Delimiter: '/' } : {};
let pages: AsyncIterable<{ Contents?: Array<{ Key?: string; Size?: number; LastModified?: Date }> }>;
try {
pages = await this.deadlined(
s3.ListObjectsV2({ Bucket: this.bucket, Prefix: this.keyPrefix + prefix, paginate: 'iterator' }),
s3.ListObjectsV2({ Bucket: this.bucket, Prefix: this.keyPrefix + prefix, paginate: 'iterator', ...shallow }),
`list '${prefix}'`,
);
} catch (err) {
+2 -2
View File
@@ -1,7 +1,7 @@
import {
storageConfigPutSchema,
storageMigrationRequestSchema,
storageReclaimRunRequestSchema,
storageReclaimConfirmRequestSchema,
storageReclaimSettingsRequestSchema,
storageTestRequestSchema,
} from '@trek/shared';
@@ -19,4 +19,4 @@ export class StorageConfigDto extends createZodDto(storageConfigPutSchema) {}
export class StorageTestRequestDto extends createZodDto(storageTestRequestSchema) {}
export class StorageMigrationRequestDto extends createZodDto(storageMigrationRequestSchema) {}
export class StorageReclaimSettingsDto extends createZodDto(storageReclaimSettingsRequestSchema) {}
export class StorageReclaimRunDto extends createZodDto(storageReclaimRunRequestSchema) {}
export class StorageReclaimConfirmDto extends createZodDto(storageReclaimConfirmRequestSchema) {}
@@ -4,7 +4,7 @@ import { UnitOfWork } from '../database/unit-of-work';
import { StorageJobsService } from './storage-jobs.service';
import { getSeedConfigPath } from './storage-paths';
import { ephemeralDriverFor, probeDriver, type ProbeTargetResult } from './storage-probe';
import { readReclaimState } from './storage-reclaim.settings';
import { StorageReclaimService } from './storage-reclaim.service';
import { BACKENDS_KEY, CATEGORIES_KEY, VERSION_KEY, StorageRegistryService } from './storage-registry.service';
import {
assertNoMaskSentinels,
@@ -44,6 +44,7 @@ export class StorageAdminService {
private readonly jobs: StorageJobsService,
private readonly stats: StorageStatsService,
private readonly uow: UnitOfWork,
private readonly reclaim: StorageReclaimService,
) {}
/** The effective world — secrets masked, categories cross-referenced per backend. */
@@ -64,7 +65,7 @@ export class StorageAdminService {
health: { replicaFailures: this.storage.health().replicaFailures.map((f) => ({ ...f })) },
seedFilePresent: fs.existsSync(getSeedConfigPath()),
usage: await this.stats.readUsage(),
reclaim: await readReclaimState(this.appSettings),
reclaim: await this.reclaim.state(),
backfills: this.jobs.statuses(),
migrations: this.jobs.migrationStatuses(),
version: await this.registry.currentConfigVersion(),
@@ -45,6 +45,8 @@ export class StorageJobsService {
private exclusive: string | null = null;
/** Restores in progress: no exclusive pass starts while one runs, and one in flight stops. */
private restores = 0;
/** Backups in progress: the reclaim pass deletes nothing while one reads the uploads. */
private backups = 0;
/** Settles once the exclusive pass holding the slot releases it; settled while none does. */
private exclusiveReleased: Promise<void> = Promise.resolve();
private onExclusiveReleased: (() => void) | null = null;
@@ -90,6 +92,33 @@ export class StorageJobsService {
return this.restores > 0;
}
/** True while a backup reads the uploads: the reclaim pass deletes nothing then, the archive may still want them. */
get backupRunning(): boolean {
return this.backups > 0;
}
/** The exclusive pass holding the one-job slot now, by name; null while none does. */
get exclusiveHolder(): string | null {
return this.exclusive;
}
/**
* Settles once no exclusive pass holds the slot (at once when none does): the
* nightly usage scan waits here, so its figures follow what a reclaim pass freed.
*/
async exclusiveIdle(): Promise<void> {
await this.exclusiveReleased;
}
/** A backup started reading the uploads; the caller calls `endBackup` in a finally. */
beginBackup(): void {
this.backups += 1;
}
endBackup(): void {
if (this.backups > 0) this.backups -= 1;
}
/**
* Marks a restore as running and waits until an exclusive pass in flight
* (the reclaim pass, which stops at its next check of `restoreRunning`) has
@@ -1,27 +1,32 @@
import { StorageReclaimRegistryService } from './storage-reclaim-registry.service';
import {
referencedAmong,
keySearchCore,
keysNamedIn,
type StorageKeyOptions,
type StorageReferenceClaim,
type StorageReferenceSource,
type StorageReferenceSourceId,
} from './storage-reclaim.types';
import type { ServedCategory } from './storage.types';
import { EntityManager } from '@mikro-orm/core';
import { EntityManager, type FilterQuery } from '@mikro-orm/core';
import { Injectable, type OnApplicationBootstrap } from '@nestjs/common';
/**
* The shape every owner's reference source shares: it registers itself with
* the reclaim registry once the app is up, and answers a page of keys by
* reading the values its own columns hold and parsing them with
* `referencedAmong`, so no source carries a parser of its own.
* the reclaim registry once the app is up, and answers by reading the values
* its own columns hold and parsing them with `keysNamedIn`, so no source
* carries a parser of its own.
*
* An owner extends this in its own domain, names its id and claims, and reads
* its columns through `em.getRepository(<its own entity>)`; storage never
* learns which tables those are. The values are read whole on every call:
* a column that takes any string (an absolute URL of this instance, a path
* with a query, another category's object) cannot be matched with `IN`, and
* a re-check right before a delete must see the rows as they are now.
* learns which tables those are. A column that takes any string (an absolute
* URL of this instance, a path with a query, another category's object)
* cannot be matched with `IN`, so the values are read and parsed here:
* - `namedKeys` reads every value once, for a pass that judges a whole category;
* - `referenced` reads only the rows whose value holds one of the keys' plain
* runs (`keySearchCore`, a `LIKE '%run%'` each), fresh, for the question a
* delete asks last and for a release right after a user's change. A key with
* no such run reads everything, as `namedKeys` does.
*/
@Injectable()
export abstract class StorageReclaimSource implements StorageReferenceSource, OnApplicationBootstrap {
@@ -39,11 +44,45 @@ export abstract class StorageReclaimSource implements StorageReferenceSource, On
this.registry.register(this);
}
async referenced(category: ServedCategory, keys: readonly string[]): Promise<Set<string>> {
if (keys.length === 0 || !this.claims.some((claim) => claim.category === category)) return new Set();
return referencedAmong(category, keys, await this.storedValues(), this.keyOptions);
async namedKeys(category: ServedCategory): Promise<Set<string>> {
if (!this.claimsCategory(category)) return new Set();
return keysNamedIn(category, await this.storedValues(null), this.keyOptions);
}
/** Every value the owner's columns hold that may name a stored object; null and empty ones may be among them. */
protected abstract storedValues(): Promise<Iterable<string | null | undefined>>;
async referenced(category: ServedCategory, keys: readonly string[]): Promise<Set<string>> {
if (keys.length === 0 || !this.claimsCategory(category)) return new Set();
const cores = keys.map(keySearchCore);
const narrow = cores.every((core): core is string => core !== null) ? [...new Set(cores)] : null;
const named = keysNamedIn(category, await this.storedValues(narrow), this.keyOptions);
return new Set(keys.filter((key) => named.has(key.toLowerCase())));
}
/**
* The values the owner's columns hold that may name a stored object; null
* and empty ones may be among them. With `containing`, only the rows whose
* value holds one of these lowercase runs are needed (`likeAny` builds the
* filter); more rows are fine, fewer would lose an object.
*/
protected abstract storedValues(containing: readonly string[] | null): Promise<Iterable<string | null | undefined>>;
private claimsCategory(category: ServedCategory): boolean {
return this.claims.some((claim) => claim.category === category);
}
}
/**
* The filter a source narrows its columns with: rows where one of `fields`
* holds one of the runs, or every row where one of them is set when there are
* none to narrow by. The runs are `[a-z0-9-]` only, so they need no LIKE
* escaping; SQLite's LIKE ignores ASCII case, as the parser does.
*/
export function likeAny<T>(
fields: ReadonlyArray<keyof T & string>,
containing: readonly string[] | null,
): FilterQuery<T> {
const terms =
containing === null
? fields.map((field) => ({ [field]: { $ne: null } }))
: fields.flatMap((field) => containing.map((run) => ({ [field]: { $like: `%${run}%` } })));
return { $or: terms } as unknown as FilterQuery<T>;
}
@@ -6,23 +6,19 @@ import { CurrentUser } from '../auth-core/current-user.decorator';
import { JwtAuthGuard } from '../auth-core/jwt-auth.guard';
import { ManagedForbidden } from '../common/managed';
import { ResponseContract } from '../common/response-contract';
import { StorageReclaimRunDto, StorageReclaimSettingsDto } from './storage-admin.dto';
import { StorageReclaimConfirmDto, StorageReclaimSettingsDto } from './storage-admin.dto';
import { StorageReclaimService } from './storage-reclaim.service';
import { Body, Controller, HttpCode, Post, Put, Req, UseGuards } from '@nestjs/common';
import {
storageReclaimReportSchema,
storageReclaimStateSchema,
type StorageReclaimReport,
type StorageReclaimState,
} from '@trek/shared';
import { storageReclaimRunStartedSchema, storageReclaimStateSchema, type StorageReclaimState } from '@trek/shared';
import type { Request } from 'express';
/**
* /api/admin/storage/reclaim: the admin's switch for the reclaim pass and a
* pass on demand. The state itself rides on GET /api/admin/storage. Deleting
* stays off until an admin turns it on here; a pass then still deletes only
* what has been unreferenced for a week (StorageReclaimService).
* /api/admin/storage/reclaim: the admin's switch for the reclaim pass, a check
* on demand and the confirmation a category with a large unreferenced share
* waits for. The state itself rides on GET /api/admin/storage. Deleting stays
* off until an admin turns it on here; a pass then still deletes only what has
* been unreferenced for a week (StorageReclaimService).
*/
@Controller('api/admin/storage/reclaim')
@UseGuards(JwtAuthGuard, AdminGuard)
@@ -50,27 +46,47 @@ export class StorageReclaimController {
return state;
}
/** One pass now, honouring the switch unless `reportOnly`. 409 on a demo or while another storage job runs. */
/**
* Starts a report-only pass in the background and answers 202 at once; the
* admin state says `running` until its report lands. 409 on a demo or while
* another storage job, a reclaim pass included, runs.
*/
@Post('run')
@HttpCode(200)
@ResponseContract(storageReclaimReportSchema)
async run(
@CurrentUser() user: User,
@Body() body: StorageReclaimRunDto,
@Req() req: Request,
): Promise<StorageReclaimReport> {
const report = await this.reclaim.run({ reportOnly: body.reportOnly === true });
const rows = Object.values(report.categories);
@HttpCode(202)
@ResponseContract(storageReclaimRunStartedSchema)
async run(@CurrentUser() user: User, @Req() req: Request): Promise<{ started: true }> {
this.reclaim.start();
await this.audit.writeAudit({
userId: user.id,
action: 'admin.storage_reclaim_run',
ip: getClientIp(req),
details: { mode: 'report' },
});
return { started: true };
}
/**
* Lets the pass delete in a category whose unreferenced share is over a
* fifth, up to the count the last report showed. 409 when nothing waits.
*/
@Post('confirm')
@HttpCode(200)
@ResponseContract(storageReclaimStateSchema)
async confirm(
@CurrentUser() user: User,
@Body() body: StorageReclaimConfirmDto,
@Req() req: Request,
): Promise<StorageReclaimState> {
const state = await this.reclaim.confirm(body.category);
await this.audit.writeAudit({
userId: user.id,
action: 'admin.storage_reclaim_confirm',
ip: getClientIp(req),
details: {
mode: report.mode,
deleted: rows.reduce((sum, row) => sum + row.deleted.objects, 0),
bytes: rows.reduce((sum, row) => sum + row.deleted.bytes, 0),
category: body.category,
unreferenced: state.lastRun?.categories[body.category].unreferenced.objects ?? 0,
},
});
return report;
return state;
}
}
+6 -22
View File
@@ -2,14 +2,15 @@ import { RuntimeEnvService } from '../app-config/runtime-env.service';
import { logDebug, logError, logInfo } from '../audit/audit-log.logger';
import { DomainError } from '../common/domain-error';
import { CronRegistrarService } from '../scheduling/cron-registrar.service';
import { reportSummary } from './storage-reclaim.report';
import { StorageReclaimService } from './storage-reclaim.service';
import { Injectable, type OnApplicationBootstrap } from '@nestjs/common';
import type { StorageReclaimReport } from '@trek/shared';
/**
* The nightly reclaim pass, 04:05: after the thumbnail sweep at 04:00 and
* before the usage scan at 04:15, so the next usage figures already show what
* it freed. No pass at boot: a pass that may delete waits for its hour.
* The nightly reclaim pass, 04:05: after the thumbnail sweep at 04:00. The
* usage scan at 04:15 waits for a pass still running (StorageUsageScanJob), so
* its figures show what the pass freed. No pass at boot: a pass that may
* delete waits for its hour. A pass that deletes audits itself.
*/
@Injectable()
export class StorageReclaimJob implements OnApplicationBootstrap {
@@ -32,7 +33,7 @@ export class StorageReclaimJob implements OnApplicationBootstrap {
if (this.runtimeEnv.isDemoMode()) return;
try {
const report = await this.reclaim.run({ now });
const line = summary(report);
const line = reportSummary(report);
if (line) logInfo(`Storage reclaim: ${line}`);
} catch (err: unknown) {
if (err instanceof DomainError && err.getStatus() === 409) {
@@ -43,20 +44,3 @@ export class StorageReclaimJob implements OnApplicationBootstrap {
}
}
}
/** One line when the pass found, deleted or refused something; null when there was nothing to say. */
function summary(report: StorageReclaimReport): string | null {
const rows = Object.values(report.categories);
const unreferenced = rows.reduce((sum, row) => sum + row.unreferenced.objects, 0);
const deleted = rows.reduce((sum, row) => sum + row.deleted.objects, 0);
const bytes = rows.reduce((sum, row) => sum + row.deleted.bytes, 0);
const braked = Object.entries(report.categories)
.filter(([, row]) => row.skipped !== null && row.skipped !== 'not_reclaimed')
.map(([category, row]) => `${category} (${row.skipped})`);
const parts: string[] = [];
if (unreferenced > 0) parts.push(`${unreferenced} unreferenced object(s)`);
if (deleted > 0) parts.push(`deleted ${deleted} (${bytes} bytes)`);
if (braked.length > 0) parts.push(`skipped ${braked.join(', ')}`);
if (report.stopped) parts.push(`stopped: ${report.stopped}`);
return parts.length > 0 ? parts.join('; ') : null;
}
@@ -1,7 +1,8 @@
import type { StorageReclaimableCategory, StorageReferenceSourceId } from './storage-reclaim.types';
import type { BackendSnapshot } from './storage-registry.service';
import type { ServedCategory } from './storage.types';
import type { BackendSnapshot, StorageRegistryService } from './storage-registry.service';
import { SERVED_CATEGORIES, type ServedCategory } from './storage.types';
import fs from 'node:fs';
import path from 'node:path';
export type ReclaimRule =
@@ -113,6 +114,17 @@ export function sharedLocationCategories(
return shared;
}
/** The categories whose resolved location overlaps another's, from the live registry. */
export function sharedLocationsOf(registry: StorageRegistryService): Set<ServedCategory> {
const assignments = new Map(
SERVED_CATEGORIES.map((category) => {
const { backendName, keyPrefix } = registry.resolve(category);
return [category, { backendName, keyPrefix }] as const;
}),
);
return sharedLocationCategories(assignments, registry.snapshot().backends);
}
function locationsOf(assignment: CategoryAssignment, backends: ReadonlyMap<string, BackendSnapshot>): string[] | null {
const backend = backends.get(assignment.backendName);
if (!backend) return null;
@@ -120,34 +132,54 @@ function locationsOf(assignment: CategoryAssignment, backends: ReadonlyMap<strin
backend.type === 'mirror'
? [backend.options.primary, ...asList(backend.options.replicas)].map((name) => backends.get(String(name)))
: [backend];
const bases: string[] = [];
const locations: string[] = [];
for (const member of members) {
const base = member ? baseOf(member) : null;
if (base === null) return null;
bases.push(base);
const location = member ? locationOf(member, assignment.keyPrefix) : null;
if (location === null) return null;
locations.push(location);
}
return bases.map((base) => base + assignment.keyPrefix.toLowerCase());
return locations;
}
/**
* Where a backend keeps its objects, lowercased: comparing more paths as equal
* than the volume does only excludes more, never less.
* Where a backend keeps a key prefix's objects, lowercased: comparing more
* paths as equal than the volume does only excludes more, never less. A local
* root is resolved through its symlinks as LocalDriver resolves it (the image
* links /app/server/uploads to /app/uploads), and the prefix's own folder too
* when it exists; a root that cannot be resolved reads as unknown, so shared.
*/
function baseOf(backend: BackendSnapshot): string | null {
function locationOf(backend: BackendSnapshot, keyPrefix: string): string | null {
const { options } = backend;
if (backend.type === 'local') {
if (typeof options.root !== 'string' || options.root === '') return null;
return `local:${trimSlashes(path.resolve(options.root).replace(/\\/g, '/'))}/`.toLowerCase();
const root = realOrNull(path.resolve(options.root));
if (root === null) return null;
const prefixed = keyPrefix === '' ? null : realOrNull(path.join(root, keyPrefix));
const base = prefixed === null ? `${slashed(root)}${keyPrefix}` : slashed(prefixed);
return `local:/${trimSlashes(base)}${base.endsWith('/') ? '/' : ''}`.toLowerCase();
}
if (backend.type === 's3') {
if (typeof options.endpoint !== 'string' || typeof options.bucket !== 'string') return null;
const keyPrefix = typeof options.keyPrefix === 'string' ? trimSlashes(options.keyPrefix) : '';
const bucketPrefix = typeof options.keyPrefix === 'string' ? trimSlashes(options.keyPrefix) : '';
const base = `s3:${trimSlashes(options.endpoint)}/${options.bucket}/`;
return (keyPrefix === '' ? base : `${base}${keyPrefix}/`).toLowerCase();
return `${bucketPrefix === '' ? base : `${base}${bucketPrefix}/`}${keyPrefix}`.toLowerCase();
}
return null;
}
function realOrNull(target: string): string | null {
try {
return fs.realpathSync(target);
} catch {
return null;
}
}
/** A resolved folder with forward slashes and one trailing slash. */
function slashed(folder: string): string {
return `${folder.replace(/\\/g, '/').replace(/\/+$/, '')}/`;
}
function asList(value: string | number | string[] | undefined): string[] {
return Array.isArray(value) ? value : [];
}
@@ -0,0 +1,68 @@
import type { StorageReclaimCategoryReport, StorageReclaimReport } from '@trek/shared';
/** One object a pass looks at. */
export interface ReclaimCandidate {
key: string;
size: number;
}
/**
* What a pass has found and done in one category so far. It is filled in as
* the pass goes, so a pass that stops part way still reports what it deleted.
*/
export interface CategoryProgress {
objects: number;
unreferenced: ReclaimCandidate[];
eligible: ReclaimCandidate[];
deleted: ReclaimCandidate[];
confirmationRequired: boolean;
skipped: StorageReclaimCategoryReport['skipped'];
}
export function newProgress(): CategoryProgress {
return { objects: 0, unreferenced: [], eligible: [], deleted: [], confirmationRequired: false, skipped: null };
}
export function reportOf(progress: CategoryProgress): StorageReclaimCategoryReport {
return {
objects: progress.objects,
unreferenced: countOf(progress.unreferenced),
eligible: countOf(progress.eligible),
deleted: countOf(progress.deleted),
confirmationRequired: progress.confirmationRequired,
skipped: progress.skipped,
};
}
function countOf(candidates: readonly ReclaimCandidate[]): { objects: number; bytes: number } {
return { objects: candidates.length, bytes: candidates.reduce((sum, candidate) => sum + candidate.size, 0) };
}
/** What a report says the pass deleted, over every category. */
export function deletedTotal(report: StorageReclaimReport): { objects: number; bytes: number } {
const rows = Object.values(report.categories);
return {
objects: rows.reduce((sum, row) => sum + row.deleted.objects, 0),
bytes: rows.reduce((sum, row) => sum + row.deleted.bytes, 0),
};
}
/** One line when the pass found, deleted or refused something; null when there was nothing to say. */
export function reportSummary(report: StorageReclaimReport): string | null {
const rows = Object.values(report.categories);
const unreferenced = rows.reduce((sum, row) => sum + row.unreferenced.objects, 0);
const deleted = deletedTotal(report);
const skipped = Object.entries(report.categories)
.filter(([, row]) => row.skipped !== null && row.skipped !== 'not_reclaimed')
.map(([category, row]) => `${category} (${row.skipped})`);
const waiting = Object.entries(report.categories)
.filter(([, row]) => row.confirmationRequired)
.map(([category]) => category);
const parts: string[] = [];
if (unreferenced > 0) parts.push(`${unreferenced} unreferenced object(s)`);
if (deleted.objects > 0) parts.push(`deleted ${deleted.objects} (${deleted.bytes} bytes)`);
if (waiting.length > 0) parts.push(`waiting for an admin to confirm ${waiting.join(', ')}`);
if (skipped.length > 0) parts.push(`skipped ${skipped.join(', ')}`);
if (report.stopped) parts.push(`stopped: ${report.stopped}`);
return parts.length > 0 ? parts.join('; ') : null;
}
+368 -179
View File
@@ -7,51 +7,71 @@ import type {
} from '../../db/repositories/StorageReclaimMarks.repository';
import { dbNow, parseDbTimestamp } from '../../db/types';
import { RuntimeEnvService } from '../app-config/runtime-env.service';
import { logError } from '../audit/audit-log.logger';
import { logError, logInfo, logWarn } from '../audit/audit-log.logger';
import { AuditService } from '../audit/audit.service';
import { DomainError } from '../common/domain-error';
import { DatabaseLifecycle } from '../database/database-lifecycle.service';
import { withRequestContext } from '../database/request-context';
import { UnitOfWork } from '../database/unit-of-work';
import { StorageJobsService } from './storage-jobs.service';
import { StorageReclaimRegistryService } from './storage-reclaim-registry.service';
import { inReclaimScope, RECLAIM_LEDGER, sharedLocationCategories } from './storage-reclaim.ledger';
import { inReclaimScope, RECLAIM_LEDGER, sharedLocationsOf } from './storage-reclaim.ledger';
import {
deletedTotal,
newProgress,
reportOf,
type CategoryProgress,
type ReclaimCandidate,
} from './storage-reclaim.report';
import {
INSTALL_ID_KEY,
RECLAIM_DELETE_KEY,
RECLAIM_DELETE_REPORT_KEY,
RECLAIM_REPORT_KEY,
RECLAIM_RESET_KEYS,
readReclaimConfirmations,
readReclaimDeleteEnabled,
readReclaimState,
readReclaimReport,
writeReclaimConfirmations,
} from './storage-reclaim.settings';
import type { StorageReferenceSource } from './storage-reclaim.types';
import { storageOwnerMarkerInstall, storageOwnerMarkerKey, type StorageReferenceSource } from './storage-reclaim.types';
import { StorageRegistryService } from './storage-registry.service';
import { StorageService } from './storage.service';
import { SERVED_CATEGORIES, type ServedCategory } from './storage.types';
import { MikroORM } from '@mikro-orm/core';
import { InjectRepository } from '@mikro-orm/nestjs';
import { Injectable, type OnModuleInit } from '@nestjs/common';
import { Injectable, type OnApplicationBootstrap, type OnModuleInit } from '@nestjs/common';
import type { StorageReclaimCategoryReport, StorageReclaimReport, StorageReclaimState } from '@trek/shared';
import { randomUUID } from 'node:crypto';
import { Readable } from 'node:stream';
const HOUR_MS = 60 * 60 * 1000;
/** An object younger than this is never judged: every writer puts the bytes before it inserts the row. */
const RECLAIM_GRACE_MS = 24 * HOUR_MS;
/** How long an object must stay unreferenced, on every pass, before a pass may delete it. */
const RECLAIM_DELAY_MS = 7 * 24 * HOUR_MS;
/** More unreferenced than this share of a category points at a bucket another install shares: hands off. */
const RECLAIM_BRAKE_SHARE = 0.2;
/** Keys per reference question, the page the sources are promised. */
const SOURCE_PAGE = 500;
/** More unreferenced than this share of a category waits for an admin's confirmation before anything goes. */
const CONFIRM_SHARE = 0.2;
/** Keys per re-check right before a delete: one fresh, narrowed question to every source. */
const RECHECK_BATCH = 100;
/** Deletes in flight at once. */
const DELETE_CONCURRENCY = 20;
/** Marks per statement: four bound values each, well under SQLite's limit. */
const MARK_BATCH = 100;
/** Deletes in flight at once. */
const DELETE_BATCH = 20;
/** Listed objects between two looks at whether a restore began, so a restore waits seconds, not a whole listing. */
const LIST_CHECK_EVERY = 500;
const JOB_NAME = 'a storage reclaim';
interface Candidate {
key: string;
size: number;
}
const INSTALL_ID = /^[a-z0-9-]{8,64}$/;
interface PassContext {
now: number;
installId: string;
/** Deletes may go now; turned off for the rest of the pass once the switch reads off or a backup starts. */
deleting: boolean;
sources: readonly StorageReferenceSource[];
shared: ReadonlySet<ServedCategory>;
confirmed: Partial<Record<ServedCategory, number>>;
generation: number;
}
@@ -61,33 +81,44 @@ interface ReclaimRunOptions {
now?: Date;
}
/**
* A restore began, or the database was swapped under the pass: nothing it
* learnt before holds any more. Reported as `database_reopened` either way.
*/
/** A restore began, or the database was swapped under the pass: nothing it learnt before holds any more. */
class ReclaimStopped extends Error {}
/**
* The reclaim pass (#2924): objects in upload storage that no row names any
* more, found in two phases and, only when the admin switched deletion on,
* deleted. A pass lists each category the ledger allows, skips objects younger
* than a day (the bytes of an upload land before its row), asks every
* registered reference source which keys are still named, and marks the rest
* with the time it first saw them. An object goes only once its mark is a week
* old, after one more question to every source about that single key, through
* `StorageService.delete` (so replicas follow and a demo keeps its bytes).
* deleted. A pass lists each category the ledger allows at its root, skips
* objects younger than a day (the bytes of an upload land before its row),
* reads once per category what every registered reference source names, and
* marks the rest with the time it first saw them. An object goes only once its
* mark is a week old, after one more fresh question to every source about its
* batch, through `StorageService.delete` (so replicas follow and a demo keeps
* its bytes). What a user deletes or replaces is released at once instead
* (StorageReleaseService); the pass is the net for whatever that left behind.
*
* Brakes, each failing closed: a category whose sources are not all
* registered, whose objects share a location with another category's, whose
* listing or lookups fail, or where more than a fifth of the objects look
* unreferenced is skipped and its marks start over. A pass never runs beside
* a backfill, a category migration or a restore (the one-job slot of
* StorageJobsService, which a restore waits on), never on a demo instance,
* and stops when a restore begins or the database is reopened under it.
* Safety, each failing closed:
* - a category whose sources are not all registered, whose location overlaps
* another category's, or where another installation's owner marker lies
* (or this one's cannot be written) is not judged;
* - a failed listing or lookup skips the category for the night; no skip
* touches the marks, so one bad night does not restart the week;
* - more than a fifth unreferenced deletes nothing until an admin confirmed
* that count (`confirm`), which no user action can do;
* - a delete that fails on the backend stops deleting in that category;
* - nothing is deleted while a backup reads the uploads, once the switch is
* turned off mid-pass, or on a demo instance;
* - a pass never runs beside a backfill, a category migration or a restore
* (the one-job slot of StorageJobsService, which a restore waits on), and
* stops when a restore begins or the database is reopened under it.
*
* Every restore turns deletion off and drops the marks, the confirmations and
* the reports: the restored rows may come from another installation, and this
* one keeps its own install id (written back over the restored one).
*/
@Injectable()
export class StorageReclaimService implements OnModuleInit {
export class StorageReclaimService implements OnModuleInit, OnApplicationBootstrap {
private generation = 0;
private knownInstallId: string | null = null;
constructor(
private readonly storage: StorageService,
@@ -96,38 +127,66 @@ export class StorageReclaimService implements OnModuleInit {
private readonly jobs: StorageJobsService,
private readonly lifecycle: DatabaseLifecycle,
private readonly runtimeEnv: RuntimeEnvService,
private readonly audit: AuditService,
private readonly uow: UnitOfWork,
private readonly orm: MikroORM,
@InjectRepository(StorageReclaimMarks) private readonly marks: StorageReclaimMarksRepository,
@InjectRepository(AppSettings) private readonly appSettings: AppSettingsRepository,
) {}
onModuleInit(): void {
this.lifecycle.onReopened(async () => {
this.generation += 1;
});
this.lifecycle.onReopened(() => this.afterReopen());
}
/** Makes the install id on the first boot, so a restore later has one of this install's own to keep. */
async onApplicationBootstrap(): Promise<void> {
try {
await withRequestContext(this.orm, () => this.installId());
} catch (err) {
logWarn(`[storage] could not read or make the install id: ${messageOf(err)}`);
}
}
/** Read only, so the admin state's GET never writes: an install id not made yet reads as deletion off. */
async state(): Promise<StorageReclaimState> {
return await readReclaimState(this.appSettings);
const installId = this.knownInstallId ?? (await this.appSettings.getValue(INSTALL_ID_KEY));
return {
deleteEnabled: installId !== null && (await readReclaimDeleteEnabled(this.appSettings, installId)),
running: this.jobs.exclusiveHolder === JOB_NAME,
lastRun: await readReclaimReport(this.appSettings, RECLAIM_REPORT_KEY),
lastDeleteRun: await readReclaimReport(this.appSettings, RECLAIM_DELETE_REPORT_KEY),
};
}
async setDeleteEnabled(enabled: boolean): Promise<StorageReclaimState> {
await this.appSettings.setValue(RECLAIM_DELETE_KEY, enabled ? 'true' : 'false');
if (enabled) await this.appSettings.upsertOrReplace(RECLAIM_DELETE_KEY, await this.installId());
else await this.appSettings.deleteValue(RECLAIM_DELETE_KEY);
return await this.state();
}
/**
* One pass over every category, its report persisted and returned. Refuses
* with a 409 on a demo instance and while another storage job holds the slot.
* The admin lets the pass delete in a category whose unreferenced share is
* over a fifth, up to the count the last report showed. 409 when the last
* report holds nothing that waits for it.
*/
async confirm(category: ServedCategory): Promise<StorageReclaimState> {
const row = (await readReclaimReport(this.appSettings, RECLAIM_REPORT_KEY))?.categories[category];
if (!row?.confirmationRequired) {
throw refusal('reclaim_nothing_to_confirm', 'nothing in this category waits for a confirmation');
}
const installId = await this.installId();
const counts = await readReclaimConfirmations(this.appSettings, installId);
await writeReclaimConfirmations(this.appSettings, installId, { ...counts, [category]: row.unreferenced.objects });
return await this.state();
}
/**
* One pass over every category in the caller, its report persisted and
* returned: the nightly job's. Refuses with a 409 on a demo instance and
* while another storage job holds the slot.
*/
async run(options: ReclaimRunOptions = {}): Promise<StorageReclaimReport> {
if (this.runtimeEnv.isDemoMode()) {
throw new DomainError(409, 'storage reclaim does not run on a demo instance', { code: 'reclaim_demo' });
}
if (!this.jobs.claimExclusive(JOB_NAME)) {
throw new DomainError(409, 'another storage job is running, one storage job at a time', {
code: 'reclaim_busy',
});
}
this.claimSlot();
try {
return await this.pass(options.reportOnly === true, options.now ?? new Date());
} finally {
@@ -135,152 +194,269 @@ export class StorageReclaimService implements OnModuleInit {
}
}
/**
* A report-only pass in the background, for the admin's check: it can take
* longer than a proxy waits for an answer. The same refusals as `run`, at
* once; the report lands on the admin state, which says `running` meanwhile.
*/
start(): void {
this.claimSlot();
void withRequestContext(this.orm, () => this.pass(true, new Date()))
.catch((err: unknown) => {
logError(`[storage] the reclaim check failed: ${messageOf(err)}`);
})
.finally(() => {
this.jobs.releaseExclusive(JOB_NAME);
});
}
private claimSlot(): void {
if (this.runtimeEnv.isDemoMode()) throw refusal('reclaim_demo', 'storage reclaim does not run on a demo instance');
if (!this.jobs.claimExclusive(JOB_NAME)) {
throw refusal('reclaim_busy', 'another storage job is running, one storage job at a time');
}
}
/**
* This install's id, made and stored on first use.
*
* @txStandalone an idempotent lazy provision: the row is made once and only
* read after, whatever the caller writes besides.
*/
private async installId(): Promise<string> {
if (this.knownInstallId) return this.knownInstallId;
let id = await this.appSettings.getValue(INSTALL_ID_KEY);
if (id === null || !INSTALL_ID.test(id)) {
id = randomUUID();
await this.appSettings.upsertOrReplace(INSTALL_ID_KEY, id);
}
this.knownInstallId = id;
return id;
}
/**
* A restore or a reopen swapped the database: a pass in flight stops, and
* the restored rows get this install's id back, deletion off and no marks,
* confirmations or reports. Contained: a listener that throws fails the reopen.
*/
private async afterReopen(): Promise<void> {
this.generation += 1;
try {
await withRequestContext(this.orm, () =>
this.uow.transactional(async () => {
const wasOn = this.knownInstallId !== null && (await this.appSettings.getValue(RECLAIM_DELETE_KEY)) !== null;
if (this.knownInstallId) await this.appSettings.upsertOrReplace(INSTALL_ID_KEY, this.knownInstallId);
await RECLAIM_RESET_KEYS.reduce<Promise<void>>(async (previous, key) => {
await previous;
await this.appSettings.deleteValue(key);
}, Promise.resolve());
await this.marks.deleteAll();
if (wasOn)
logInfo('[storage] the restored database had reclaim deletion on: it is off until an admin turns it on');
}),
);
} catch (err) {
logError(`[storage] could not reset the reclaim state after the database was reopened: ${messageOf(err)}`);
}
}
/**
* @txIndependent a sweep in passes: each category's marks and each delete
* stand on their own, and a pass cut short leaves the work done so far valid.
*/
private async pass(reportOnly: boolean, now: Date): Promise<StorageReclaimReport> {
const wallStart = Date.now();
const installId = await this.installId();
const deleting = !reportOnly && (await readReclaimDeleteEnabled(this.appSettings, installId));
const ctx: PassContext = {
now: now.getTime(),
deleting: !reportOnly && (await readReclaimDeleteEnabled(this.appSettings)),
installId,
deleting,
sources: [...this.references.sources()],
shared: this.sharedLocations(),
shared: sharedLocationsOf(this.registry),
confirmed: await readReclaimConfirmations(this.appSettings, installId),
generation: this.generation,
};
const categories = {} as Record<ServedCategory, StorageReclaimCategoryReport>;
let stopped: StorageReclaimReport['stopped'] = null;
await SERVED_CATEGORIES.reduce<Promise<void>>(async (previous, category) => {
await previous;
const progress = newProgress();
if (stopped === null) {
try {
categories[category] = await this.reclaimCategory(category, ctx);
return;
await this.reclaimCategory(category, ctx, progress);
} catch (err) {
if (!(err instanceof ReclaimStopped)) throw err;
stopped = 'database_reopened';
stopped = err instanceof ReclaimStopped ? 'database_reopened' : 'failed';
if (stopped === 'failed') logError(`[storage] the reclaim pass failed in '${category}': ${messageOf(err)}`);
progress.skipped = 'interrupted';
}
} else {
progress.skipped = 'interrupted';
}
categories[category] = emptyReport(null, 0);
categories[category] = reportOf(progress);
}, Promise.resolve());
const report: StorageReclaimReport = {
startedAt: ctx.now,
finishedAt: ctx.now + (Date.now() - wallStart),
mode: ctx.deleting ? 'delete' : 'report',
mode: deleting ? 'delete' : 'report',
stopped,
categories,
};
await this.appSettings.upsertOrReplace(RECLAIM_REPORT_KEY, JSON.stringify(report));
await this.persist(report);
return report;
}
/** The categories whose resolved location overlaps another's, from the live registry. */
private sharedLocations(): Set<ServedCategory> {
const assignments = new Map(
SERVED_CATEGORIES.map((category) => {
const { backendName, keyPrefix } = this.registry.resolve(category);
return [category, { backendName, keyPrefix }] as const;
}),
);
return sharedLocationCategories(assignments, this.registry.snapshot().backends);
/**
* The report as the last pass's, and as the last deleting pass's when it ran
* with deletion on; an audit entry (the system as actor) when it deleted.
*
* @txIndependent each row stands on its own: the report, the delete report
* and the audit entry describe one finished pass, whichever of them lands.
*/
private async persist(report: StorageReclaimReport): Promise<void> {
const text = JSON.stringify(report);
await this.appSettings.upsertOrReplace(RECLAIM_REPORT_KEY, text);
if (report.mode !== 'delete') return;
await this.appSettings.upsertOrReplace(RECLAIM_DELETE_REPORT_KEY, text);
const deleted = deletedTotal(report);
if (deleted.objects === 0) return;
await this.audit.writeAudit({
userId: null,
action: 'storage.reclaim_deleted',
details: {
deleted: deleted.objects,
bytes: deleted.bytes,
...(report.stopped ? { stopped: report.stopped } : {}),
categories: Object.fromEntries(
Object.entries(report.categories)
.filter(([, row]) => row.deleted.objects > 0)
.map(([category, row]) => [category, row.deleted.objects]),
),
},
});
}
/**
* Judges one category into `progress`, which the caller reports even when
* this throws part way.
*
* @txIndependent a sweep in passes: marks are written per batch and every
* delete stands alone, so a failure part way keeps what came before.
*/
private async reclaimCategory(category: ServedCategory, ctx: PassContext): Promise<StorageReclaimCategoryReport> {
private async reclaimCategory(category: ServedCategory, ctx: PassContext, progress: CategoryProgress): Promise<void> {
const rule = RECLAIM_LEDGER[category];
if (!rule.reclaim) return emptyReport('not_reclaimed', 0);
if (!rule.reclaim) {
progress.skipped = 'not_reclaimed';
return;
}
const sources = ctx.sources.filter((source) => claimsAny(source, category));
const answering = new Set(sources.filter((source) => answersFor(source, category)).map((source) => source.id));
if (rule.requiredSources.some((id) => !answering.has(id))) return this.skip(category, 'sources_missing', 0);
if (ctx.shared.has(category)) return this.skip(category, 'shared_location', 0);
let listed: { objects: number; old: Candidate[] };
try {
listed = await this.listOld(category, ctx.now);
} catch (err) {
logError(`[storage] reclaim could not list '${category}': ${messageOf(err)}`);
return this.skip(category, 'list_failed', 0);
if (rule.requiredSources.some((id) => !answering.has(id))) {
progress.skipped = 'sources_missing';
return;
}
let unreferenced: Candidate[];
if (ctx.shared.has(category)) {
progress.skipped = 'shared_location';
return;
}
let listed: { objects: number; old: ReclaimCandidate[]; owners: Set<string> };
try {
unreferenced = await this.unreferencedOf(category, listed.old, sources);
listed = await this.listOld(category, ctx);
} catch (err) {
if (err instanceof ReclaimStopped) throw err;
logError(`[storage] reclaim could not list '${category}': ${messageOf(err)}`);
progress.skipped = 'list_failed';
return;
}
progress.objects = listed.objects;
const owner = await this.ownerVerdict(category, listed.owners, ctx.installId);
if (owner !== null) {
progress.skipped = owner;
return;
}
let named: Set<string>;
try {
named = await this.namedIn(category, sources);
} catch (err) {
logError(`[storage] reclaim could not check the references of '${category}': ${messageOf(err)}`);
return this.skip(category, 'source_failed', listed.objects);
progress.skipped = 'source_failed';
return;
}
this.assertSameDatabase(ctx);
const unreferencedCount = countOf(unreferenced);
if (unreferenced.length > listed.objects * RECLAIM_BRAKE_SHARE) {
return {
...(await this.skip(category, 'too_many_unreferenced', listed.objects)),
unreferenced: unreferencedCount,
};
}
const unreferenced = listed.old.filter((candidate) => !named.has(candidate.key.toLowerCase()));
progress.unreferenced = unreferenced;
const marks = new Map((await this.marks.marksOf(category)).map((mark) => [mark.key, mark]));
await this.writeMarks(category, unreferenced, marks, ctx.now);
const cutoff = ctx.now - RECLAIM_DELAY_MS;
const eligible = unreferenced.filter((candidate) => markedBefore(marks.get(candidate.key), cutoff));
const deleted = ctx.deleting ? await this.deleteEligible(category, eligible, sources, ctx) : [];
return {
objects: listed.objects,
unreferenced: unreferencedCount,
eligible: countOf(eligible),
deleted: countOf(deleted),
skipped: null,
};
progress.eligible = unreferenced.filter((candidate) => markedBefore(marks.get(candidate.key), cutoff));
progress.confirmationRequired =
unreferenced.length > listed.objects * CONFIRM_SHARE && unreferenced.length > (ctx.confirmed[category] ?? 0);
if (ctx.deleting && !progress.confirmationRequired) await this.deleteEligible(category, sources, ctx, progress);
}
/** A category this pass cannot judge: nothing is deleted and its marks start over. */
private async skip(
/** The root-level objects of a category, of them the ones past the grace period, and the owner markers there. */
private async listOld(
category: ServedCategory,
reason: NonNullable<StorageReclaimCategoryReport['skipped']>,
objects: number,
): Promise<StorageReclaimCategoryReport> {
await this.marks.deleteCategory(category);
return emptyReport(reason, objects);
}
/** The root-level objects of a category, and of them the ones past the grace period. */
private async listOld(category: ServedCategory, now: number): Promise<{ objects: number; old: Candidate[] }> {
ctx: PassContext,
): Promise<{ objects: number; old: ReclaimCandidate[]; owners: Set<string> }> {
let objects = 0;
const old: Candidate[] = [];
for await (const stat of this.storage.list(category)) {
let seen = 0;
const old: ReclaimCandidate[] = [];
const owners = new Set<string>();
for await (const stat of this.storage.list(category, '', { shallow: true })) {
seen += 1;
if (seen % LIST_CHECK_EVERY === 0) this.assertSameDatabase(ctx);
if (!inReclaimScope(stat.key)) continue;
const owner = storageOwnerMarkerInstall(stat.key);
if (owner !== null) {
owners.add(owner);
continue;
}
objects += 1;
// A missing or zero modification time reads as infinitely old: such an object is kept.
if (!(stat.mtimeMs > 0) || now - stat.mtimeMs < RECLAIM_GRACE_MS) continue;
if (!(stat.mtimeMs > 0) || ctx.now - stat.mtimeMs < RECLAIM_GRACE_MS) continue;
old.push({ key: stat.key, size: stat.size });
}
return { objects, old };
}
/** The candidates no source names, asked a page at a time. */
private async unreferencedOf(
category: ServedCategory,
candidates: readonly Candidate[],
sources: readonly StorageReferenceSource[],
): Promise<Candidate[]> {
return chunk(candidates, SOURCE_PAGE).reduce<Promise<Candidate[]>>(async (previous, page) => {
const done = await previous;
const referenced = await this.referencedIn(
category,
page.map((candidate) => candidate.key),
sources,
);
done.push(...page.filter((candidate) => !referenced.has(candidate.key.toLowerCase())));
return done;
}, Promise.resolve([]));
return { objects, old, owners };
}
/**
* The keys some source still names, lowercased. Every key is claimed: the
* ledger's required sources answer for the whole category, and a category
* missing one never gets this far.
* Whether this installation may judge the place a category lives in: not
* where another one's owner marker lies, and not where its own could not be
* written, since then a second installation cannot see it either.
*/
private async ownerVerdict(
category: ServedCategory,
owners: ReadonlySet<string>,
installId: string,
): Promise<'foreign_install' | 'owner_unknown' | null> {
const foreign = [...owners].some((owner) => owner !== installId);
if (!owners.has(installId)) {
try {
await this.storage.put(category, storageOwnerMarkerKey(installId), Readable.from([installId]), {
contentType: 'text/plain',
});
} catch (err) {
logWarn(`[storage] reclaim could not write its owner marker into '${category}': ${messageOf(err)}`);
return foreign ? 'foreign_install' : 'owner_unknown';
}
}
if (foreign) logWarn(`[storage] another TREK installation keeps its uploads where '${category}' does: not judged`);
return foreign ? 'foreign_install' : null;
}
/** Every key of the category some source names, lowercased: one read per source for the whole category. */
private async namedIn(category: ServedCategory, sources: readonly StorageReferenceSource[]): Promise<Set<string>> {
const answers = await Promise.all(sources.map((source) => source.namedKeys(category)));
const named = new Set<string>();
for (const answer of answers) for (const key of answer) named.add(key);
return named;
}
/** The keys some source names right now, lowercased: the fresh question before a delete. */
private async referencedIn(
category: ServedCategory,
keys: readonly string[],
@@ -303,7 +479,7 @@ export class StorageReclaimService implements OnModuleInit {
*/
private async writeMarks(
category: ServedCategory,
unreferenced: readonly Candidate[],
unreferenced: readonly ReclaimCandidate[],
marks: ReadonlyMap<string, ReclaimMarkRow>,
now: number,
): Promise<void> {
@@ -322,48 +498,68 @@ export class StorageReclaimService implements OnModuleInit {
}
/**
* The eligible objects a batch at a time, while deleting may still go; a
* batch whose backend failed stops the category with `delete_failed`.
*
* @txIndependent a batch at a time, each delete standing alone, so a failure
* leaves the others' work standing.
*/
private async deleteEligible(
category: ServedCategory,
eligible: readonly Candidate[],
sources: readonly StorageReferenceSource[],
ctx: PassContext,
): Promise<Candidate[]> {
return chunk(eligible, DELETE_BATCH).reduce<Promise<Candidate[]>>(async (previous, batch) => {
const done = await previous;
done.push(...(await this.deleteBatch(category, batch, sources, ctx)));
return done;
}, Promise.resolve([]));
progress: CategoryProgress,
): Promise<void> {
await chunk(progress.eligible, RECHECK_BATCH).reduce<Promise<void>>(async (previous, batch) => {
await previous;
if (progress.skipped !== null || !(await this.mayDelete(ctx))) return;
this.assertSameDatabase(ctx);
const failed = await this.deleteBatch(category, batch, sources, ctx, progress);
if (failed) progress.skipped = 'delete_failed';
}, Promise.resolve());
}
/** Deleting goes on while the switch stays on and no backup reads the uploads; once off, off for the pass. */
private async mayDelete(ctx: PassContext): Promise<boolean> {
if (!ctx.deleting) return false;
if (this.jobs.backupRunning || !(await readReclaimDeleteEnabled(this.appSettings, ctx.installId))) {
ctx.deleting = false;
}
return ctx.deleting;
}
/**
* Checks each object is still the old one the pass judged, then asks every
* source about the batch again and deletes, at once, what none of them names.
* The question goes last so nothing slower than the delete itself sits
* between the answer and the delete, and once per batch so a pass reads each
* source's columns once per batch rather than once per object.
* Checks each object is still the old one the pass judged, asks every source
* about the batch again, fresh, and deletes what none of them names. The
* question goes last so nothing slower than the deletes sits between the
* answer and them. True when the backend failed, so the category stops.
*
* @txIndependent every object goes on its own, see deleteOne.
* @txIndependent every object goes on its own; its mark goes after it.
*/
private async deleteBatch(
category: ServedCategory,
batch: readonly Candidate[],
batch: readonly ReclaimCandidate[],
sources: readonly StorageReferenceSource[],
ctx: PassContext,
): Promise<Candidate[]> {
const stats = await Promise.all(batch.map((candidate) => this.storage.stat(category, candidate.key)));
progress: CategoryProgress,
): Promise<boolean> {
let stats: Awaited<ReturnType<StorageService['stat']>>[];
try {
stats = await Promise.all(batch.map((candidate) => this.storage.stat(category, candidate.key)));
} catch (err) {
logError(`[storage] reclaim stopped deleting in '${category}', the backend failed: ${messageOf(err)}`);
return true;
}
// Gone, or written again since it was judged: the next pass looks at it afresh.
const changed = batch.filter((_candidate, i) => {
const stat = stats[i];
return stat === null || !(stat.mtimeMs > 0) || ctx.now - stat.mtimeMs < RECLAIM_GRACE_MS;
return !stat || !(stat.mtimeMs > 0) || ctx.now - stat.mtimeMs < RECLAIM_GRACE_MS;
});
if (changed.length > 0) await this.marks.deleteKeys(category, keysOf(changed));
const due = batch.filter(
(candidate) => !changed.includes(candidate) && !this.storage.keepsOnDelete(category, candidate.key),
);
if (due.length === 0) return [];
if (due.length === 0) return false;
let referenced: Set<string>;
try {
referenced = await this.referencedIn(category, keysOf(due), sources);
@@ -371,30 +567,27 @@ export class StorageReclaimService implements OnModuleInit {
logError(
`[storage] reclaim kept ${due.length} '${category}' object(s), their re-check failed: ${messageOf(err)}`,
);
return [];
return false;
}
const named = due.filter((candidate) => referenced.has(candidate.key.toLowerCase()));
if (named.length > 0) await this.marks.deleteKeys(category, keysOf(named));
const unnamed = due.filter((candidate) => !referenced.has(candidate.key.toLowerCase()));
this.assertSameDatabase(ctx);
const results = await Promise.all(unnamed.map((candidate) => this.deleteOne(category, candidate)));
return unnamed.filter((_candidate, i) => results[i]);
}
/**
* Deletes one object the batch cleared, then its mark. False keeps it.
*
* @txIndependent the object goes first and the mark after, so a mark never
* outlives a delete that failed.
*/
private async deleteOne(category: ServedCategory, candidate: Candidate): Promise<boolean> {
try {
await this.storage.delete(category, candidate.key);
} catch (err) {
logError(`[storage] reclaim could not delete a '${category}' object: ${messageOf(err)}`);
return false;
}
await this.marks.deleteKeys(category, [candidate.key]);
const deleted: ReclaimCandidate[] = [];
let failure: unknown = null;
await chunk(unnamed, DELETE_CONCURRENCY).reduce<Promise<void>>(async (previous, group) => {
await previous;
if (failure !== null) return;
const results = await Promise.allSettled(group.map((candidate) => this.storage.delete(category, candidate.key)));
results.forEach((result, i) => {
if (result.status === 'fulfilled') deleted.push(group[i] as ReclaimCandidate);
else failure ??= result.reason;
});
}, Promise.resolve());
progress.deleted.push(...deleted);
if (deleted.length > 0) await this.marks.deleteKeys(category, keysOf(deleted));
if (failure === null) return false;
logError(`[storage] reclaim stopped deleting in '${category}' after a failed delete: ${messageOf(failure)}`);
return true;
}
@@ -405,13 +598,9 @@ export class StorageReclaimService implements OnModuleInit {
}
}
function emptyReport(skipped: StorageReclaimCategoryReport['skipped'], objects: number): StorageReclaimCategoryReport {
const none = { objects: 0, bytes: 0 };
return { objects, unreferenced: none, eligible: none, deleted: none, skipped };
}
function countOf(candidates: readonly Candidate[]): { objects: number; bytes: number } {
return { objects: candidates.length, bytes: candidates.reduce((sum, candidate) => sum + candidate.size, 0) };
/** A 409 whose body names the refusal in `code` next to the text, so the client can say it in the user's language. */
function refusal(code: 'reclaim_busy' | 'reclaim_demo' | 'reclaim_nothing_to_confirm', message: string): DomainError {
return new DomainError(409, message, { code, details: { code } });
}
function markedBefore(mark: ReclaimMarkRow | undefined, cutoff: number): boolean {
@@ -433,7 +622,7 @@ function claimsKey(source: StorageReferenceSource, category: ServedCategory, key
return source.claims.some((claim) => claim.category === category && key.startsWith(claim.prefix));
}
function keysOf(candidates: readonly Candidate[]): string[] {
function keysOf(candidates: readonly ReclaimCandidate[]): string[] {
return candidates.map((candidate) => candidate.key);
}
@@ -1,32 +1,91 @@
import type { AppSettingsRepository } from '../../db/repositories/AppSettings.repository';
import { logWarn } from '../audit/audit-log.logger';
import { storageReclaimReportSchema, type StorageReclaimReport, type StorageReclaimState } from '@trek/shared';
import type { ServedCategory } from './storage.types';
import { storageReclaimReportSchema, type StorageReclaimReport } from '@trek/shared';
/** The admin's switch: 'true' lets a pass delete. Absent, or anything else, means report only. */
import { z } from 'zod';
/**
* This installation's random id, made on its first boot. A backup restore
* brings back the app_settings of whatever install made the backup, so the
* reclaim pass keeps the id it booted with and writes it back over the
* restored one (StorageReclaimService, on every database reopen). Outside the
* `storage.` prefix on purpose: the documented reset of the storage config
* (deleting every `storage.%` row) must not make this install a stranger to
* the owner markers it wrote.
*/
export const INSTALL_ID_KEY = 'install_id';
/**
* The admin's switch, stored as the install id it was turned on for: any other
* value, a restored one from another install included, reads as off.
*/
export const RECLAIM_DELETE_KEY = 'storage.reclaim_delete';
/** The last pass's report, one JSON row (the `storage.usage` pattern). */
export const RECLAIM_REPORT_KEY = 'storage.reclaim_report';
/** The last report of a pass that ran with deletion on, which a check by hand never replaces. */
export const RECLAIM_DELETE_REPORT_KEY = 'storage.reclaim_delete_report';
/**
* Per category, the unreferenced count an admin confirmed when that was more
* than a fifth of the category, for the install it was confirmed on.
*/
const RECLAIM_CONFIRMED_KEY = 'storage.reclaim_confirmed';
/** Fail closed: only the exact stored 'true' switches deletion on. */
export async function readReclaimDeleteEnabled(appSettings: AppSettingsRepository): Promise<boolean> {
return (await appSettings.getValue(RECLAIM_DELETE_KEY)) === 'true';
/** Every row a restore or a foreign database must not carry over into this install's reclaim. */
export const RECLAIM_RESET_KEYS = [
RECLAIM_DELETE_KEY,
RECLAIM_REPORT_KEY,
RECLAIM_DELETE_REPORT_KEY,
RECLAIM_CONFIRMED_KEY,
] as const;
const confirmationsSchema = z.object({
installId: z.string(),
counts: z.record(z.string(), z.number().int().nonnegative()),
});
/** Fail closed: only this install's own id switches deletion on. */
export async function readReclaimDeleteEnabled(
appSettings: AppSettingsRepository,
installId: string,
): Promise<boolean> {
return (await appSettings.getValue(RECLAIM_DELETE_KEY)) === installId;
}
/** The stored report, parsed; null when there is none or it no longer parses (logged, never a 500). */
async function readReclaimReport(appSettings: AppSettingsRepository): Promise<StorageReclaimReport | null> {
const value = await appSettings.getValue(RECLAIM_REPORT_KEY);
/** A stored report, parsed; null when there is none or it no longer parses (logged, never a 500). */
export async function readReclaimReport(
appSettings: AppSettingsRepository,
key: typeof RECLAIM_REPORT_KEY | typeof RECLAIM_DELETE_REPORT_KEY,
): Promise<StorageReclaimReport | null> {
const value = await appSettings.getValue(key);
if (value == null) return null;
try {
return storageReclaimReportSchema.parse(JSON.parse(value));
} catch {
logWarn('[storage] the stored reclaim report is unparseable, treating it as never run');
logWarn(`[storage] the stored '${key}' row is unparseable, treating it as never run`);
return null;
}
}
export async function readReclaimState(appSettings: AppSettingsRepository): Promise<StorageReclaimState> {
return {
deleteEnabled: await readReclaimDeleteEnabled(appSettings),
lastRun: await readReclaimReport(appSettings),
};
/** The confirmed counts of this install; none for a row another install wrote or that no longer parses. */
export async function readReclaimConfirmations(
appSettings: AppSettingsRepository,
installId: string,
): Promise<Partial<Record<ServedCategory, number>>> {
const value = await appSettings.getValue(RECLAIM_CONFIRMED_KEY);
if (value == null) return {};
try {
const parsed = confirmationsSchema.parse(JSON.parse(value));
return parsed.installId === installId ? (parsed.counts as Partial<Record<ServedCategory, number>>) : {};
} catch {
logWarn('[storage] the stored reclaim confirmations are unparseable, treating them as none');
return {};
}
}
export async function writeReclaimConfirmations(
appSettings: AppSettingsRepository,
installId: string,
counts: Partial<Record<ServedCategory, number>>,
): Promise<void> {
await appSettings.upsertOrReplace(RECLAIM_CONFIRMED_KEY, JSON.stringify({ installId, counts }));
}
@@ -5,8 +5,7 @@ import { SERVED_CATEGORIES, type ServedCategory } from './storage.types';
* name stored objects (#2924). Storage cannot read those rows itself: it may
* import no domain that imports it, and it may not inject another domain's
* repositories. So each owner registers a source with
* `StorageReclaimRegistryService` and answers, for a page of keys, which of
* them its rows still name.
* `StorageReclaimRegistryService` and answers which keys its rows still name.
*
* The ids are a closed list: the ledger in storage names, per category, which
* of them must have answered before a single object of that category may be
@@ -53,11 +52,17 @@ export interface StorageReferenceSource {
*/
readonly claims: ReadonlyArray<StorageReferenceClaim>;
/**
* Of these category-relative keys (as `StorageService.list` yields them, at
* most a page of 500), the ones a row still names. A row that is trashed,
* Every key of `category` the rows name, lowercased: one read of the whole
* column set, which a pass makes once per category. A row that is trashed,
* pending or otherwise not gone counts. Throwing stops the pass for the
* category; it never deletes on a failed answer.
*/
namedKeys(category: ServedCategory): Promise<Set<string>>;
/**
* Of these category-relative keys (as `StorageService.list` yields them, a
* batch at a time), the ones a row names right now: the question a delete
* asks last, read fresh and narrowed to the rows that can name them.
*/
referenced(category: ServedCategory, keys: readonly string[]): Promise<Set<string>>;
}
@@ -76,16 +81,18 @@ export interface StorageKeyOptions {
}
const UPLOADS_PATH = /(?:^|\/)uploads\/([a-z0-9][a-z0-9-]*)\//gi;
const KEY_END = /[?#"'<>\r\n]/;
/** Where a key inside a longer text ends at the latest: a quote, markup or a line break. */
const TEXT_END = /["'<>\r\n]/;
const SUFFIX = /[?#]/;
const SERVED = new Set<string>(SERVED_CATEGORIES);
/**
* Every `/uploads/<category>/<key>` in a value, wherever it stands: a path, an
* absolute URL of this instance (`https://host/uploads/covers/x.jpg`), a leading
* `uploads/` without the slash, several in one text. A query or a fragment is
* dropped, the key is percent-decoded and trimmed. A key with a blank in it is
* reported both whole and cut at the blank, since a value may be a sentence:
* reporting one key too many only keeps an object, one too few would lose it.
* `uploads/` without the slash, several in one text. Each key is reported as it
* stands and in its other readings: cut at a query or fragment, percent-decoded,
* trimmed, cut at a blank. Reporting one key too many only keeps an object; one
* too few would lose it, so the raw spelling is always among them.
*/
export function uploadKeysIn(value: string | null | undefined): StorageKeyRef[] {
if (typeof value !== 'string' || value === '') return [];
@@ -94,7 +101,7 @@ export function uploadKeysIn(value: string | null | undefined): StorageKeyRef[]
const start = match.index + match[0].length;
const next = matches[i + 1];
const tail = value.slice(start, next ? next.index : value.length);
const end = tail.search(KEY_END);
const end = tail.search(TEXT_END);
const category = match[1].toLowerCase();
return keyVariants(end === -1 ? tail : tail.slice(0, end)).map((key) => ({ category, key }));
});
@@ -103,26 +110,28 @@ export function uploadKeysIn(value: string | null | undefined): StorageKeyRef[]
/**
* Every object a stored value can name: the upload paths above, the relative
* `<category>/<key>` spelling (`journeys.cover_image` holds `covers/x`), and
* with `options` the bare or legacy-prefixed name of one category. A value
* that names nothing this way (an https URL elsewhere, a data: URL, garbage)
* answers an empty list: it references nothing a pass can find.
* with `options` the bare or legacy-prefixed name of one category. A bare name
* is the object's exact name (`uuid. #4711`, `uuid.pdf `), so it is reported
* untouched first and in its other readings after. A value that names nothing
* this way (an https URL elsewhere, a data: URL, garbage) answers an empty list:
* it references nothing a pass can find.
*/
export function storageKeysIn(value: string | null | undefined, options: StorageKeyOptions = {}): StorageKeyRef[] {
if (typeof value !== 'string') return [];
const trimmed = stripSuffix(value).trim();
if (trimmed === '') return [];
if (typeof value !== 'string' || value === '') return [];
const refs = uploadKeysIn(value);
const relative = /^\.?\/?([a-z0-9][a-z0-9-]*)\/(.+)$/i.exec(trimmed);
if (relative && SERVED.has(relative[1].toLowerCase())) {
const category = relative[1].toLowerCase();
for (const key of keyVariants(relative[2])) refs.push({ category, key });
for (const form of new Set([value, value.trim(), stripSuffix(value).trim()])) {
const relative = /^\.?\/?([a-z0-9][a-z0-9-]*)\/(.+)$/is.exec(form);
if (relative && SERVED.has(relative[1].toLowerCase())) {
const category = relative[1].toLowerCase();
for (const key of keyVariants(relative[2])) refs.push({ category, key });
}
}
if (options.bare) {
const bare = options.bare;
if (!/[/\\:]/.test(trimmed)) {
for (const key of keyVariants(trimmed)) refs.push({ category: bare, key });
if (!/[/\\:]/.test(value)) {
for (const key of keyVariants(value)) refs.push({ category: bare, key });
} else if (options.basename) {
const last = trimmed.slice(Math.max(trimmed.lastIndexOf('/'), trimmed.lastIndexOf('\\')) + 1);
const last = value.slice(Math.max(value.lastIndexOf('/'), value.lastIndexOf('\\')) + 1);
for (const key of keyVariants(last)) refs.push({ category: bare, key });
}
}
@@ -130,14 +139,13 @@ export function storageKeysIn(value: string | null | undefined, options: Storage
}
/**
* The candidates of `category` that any of `values` names, compared without
* regard to case: a local volume on Windows or macOS serves `A.jpg` for `a.jpg`,
* so an object is kept when a value names it in either spelling. The helper a
* source builds `referenced()` from, so no source parses with a regex of its own.
* The keys of `category` any of `values` names, lowercased: a local volume on
* Windows or macOS serves `A.jpg` for `a.jpg`, so an object is kept when a value
* names it in either spelling. The helper a source builds its answers from, so
* no source parses with a regex of its own.
*/
export function referencedAmong(
export function keysNamedIn(
category: ServedCategory,
candidates: readonly string[],
values: Iterable<string | null | undefined>,
options: StorageKeyOptions = {},
): Set<string> {
@@ -147,25 +155,57 @@ export function referencedAmong(
if (ref.category === category) named.add(ref.key.toLowerCase());
}
}
return new Set(candidates.filter((key) => named.has(key.toLowerCase())));
return named;
}
/**
* The longest run of plain characters in a key (`[a-z0-9-]`, the random part
* of every name TREK writes): a row that names the key in any spelling holds
* this run verbatim, so a `LIKE '%run%'` finds every row worth parsing. Null
* when the key has no run long enough to narrow anything.
*/
export function keySearchCore(key: string): string | null {
const runs = key.toLowerCase().match(/[a-z0-9-]+/g) ?? [];
const longest = runs.reduce((best, run) => (run.length > best.length ? run : best), '');
return longest.length >= 8 ? longest : null;
}
/**
* The marker object a pass keeps at the root of each category it judges,
* naming this installation (`trek-owner-<install id>`). A second TREK
* installation that keeps its uploads in the same place writes its own, and
* from then on neither deletes there.
*/
const OWNER_MARKER_PREFIX = 'trek-owner-';
const OWNER_MARKER = /^trek-owner-([a-z0-9-]{8,64})$/;
export function storageOwnerMarkerKey(installId: string): string {
return `${OWNER_MARKER_PREFIX}${installId}`;
}
/** The install id an owner marker names, or null for any other key. Backups leave markers out. */
export function storageOwnerMarkerInstall(key: string): string | null {
return OWNER_MARKER.exec(key)?.[1] ?? null;
}
function stripSuffix(value: string): string {
const cut = value.search(/[?#]/);
const cut = value.search(SUFFIX);
return cut === -1 ? value : value.slice(0, cut);
}
/** The raw key, decoded, and cut at a blank; never an empty key or one that climbs out of its category. */
/** The raw key and its other readings; never an empty one. */
function keyVariants(raw: string): string[] {
const forms = new Set<string>();
const add = (key: string) => {
const clean = key.trim().replace(/^\/+/, '');
if (clean === '' || clean.split('/').some((segment) => segment === '..' || segment === '.')) return;
forms.add(clean);
if (key.trim() === '') return;
forms.add(key);
const unslashed = key.replace(/^\/+/, '');
if (unslashed.trim() !== '') forms.add(unslashed);
};
const whole = stripSuffix(raw);
for (const form of [whole, decoded(whole)]) {
const stripped = stripSuffix(raw);
for (const form of [raw, stripped, decoded(raw), decoded(stripped)]) {
add(form);
add(form.trim());
add(form.trim().split(/\s/)[0] ?? '');
}
return [...forms];
@@ -1,8 +1,13 @@
import { CronRegistrarService } from '../scheduling/cron-registrar.service';
import { StorageJobsService } from './storage-jobs.service';
import { StorageStatsService } from './storage-stats.service';
import { Injectable, Logger, OnApplicationBootstrap } from '@nestjs/common';
/** Nightly usage scan — 04:15, off the backup and thumb-sweep hours. */
/**
* Nightly usage scan — 04:15, off the backup and thumb-sweep hours. A reclaim
* pass still running from 04:05 is waited for first: the two would list the
* same backends at once, and the figures should show what the pass freed.
*/
@Injectable()
export class StorageUsageScanJob implements OnApplicationBootstrap {
private readonly logger = new Logger(StorageUsageScanJob.name);
@@ -10,6 +15,7 @@ export class StorageUsageScanJob implements OnApplicationBootstrap {
constructor(
private readonly registrar: CronRegistrarService,
private readonly stats: StorageStatsService,
private readonly jobs: StorageJobsService,
) {}
onApplicationBootstrap(): void {
@@ -21,6 +27,7 @@ export class StorageUsageScanJob implements OnApplicationBootstrap {
async tick(): Promise<void> {
try {
await this.jobs.exclusiveIdle();
await this.stats.scan();
} catch (err) {
this.logger.error(`usage scan failed: ${err instanceof Error ? err.message : String(err)}`);
+3 -2
View File
@@ -9,6 +9,7 @@ import {
isClientAbortError,
StorageNotFoundError,
type ByteRange,
type ListOptions,
type LocalTempFile,
type ObjectStat,
type PutOptions,
@@ -168,9 +169,9 @@ export class StorageService {
}
/** Names in and out are category-relative — the key prefix stays a registry detail. */
async *list(category: ServedCategory, subPrefix = ''): AsyncIterable<ObjectStat> {
async *list(category: ServedCategory, subPrefix = '', opts?: ListOptions): AsyncIterable<ObjectStat> {
const { driver, keyPrefix } = this.registry.resolve(category);
for await (const stat of driver.list(keyPrefix + subPrefix)) {
for await (const stat of driver.list(keyPrefix + subPrefix, opts)) {
yield { ...stat, key: stat.key.slice(keyPrefix.length) };
}
}
+6 -1
View File
@@ -98,6 +98,11 @@ export function isClientAbortError(err: unknown): boolean {
);
}
export interface ListOptions {
/** Only the objects directly under the prefix, none in a folder below it (the reclaim pass judges a category's root). */
shallow?: boolean;
}
export interface StorageDriver {
/** Backend instance name, e.g. 'uploads-local'. */
readonly id: string;
@@ -107,7 +112,7 @@ export interface StorageDriver {
stat(key: string): Promise<ObjectStat | null>;
/** Idempotent; resolving on a missing key is success. */
delete(key: string): Promise<void>;
list(prefix: string): AsyncIterable<ObjectStat>;
list(prefix: string, opts?: ListOptions): AsyncIterable<ObjectStat>;
/** Fast-path for local drivers; `null`/absent is exactly the remote-driver branch every caller must handle. */
getLocalPath?(key: string): string | null;
/** Same-filesystem spool dir (LocalDriver: `<root>/.tmp`), or null for drivers with no local filesystem. */
@@ -1,5 +1,5 @@
import { Trips } from '../../db/entities/Trips.entity';
import { StorageReclaimSource } from '../storage/storage-reclaim-source.service';
import { likeAny, StorageReclaimSource } from '../storage/storage-reclaim-source.service';
import { EVERY_RECLAIMABLE_CATEGORY } from '../storage/storage-reclaim.types';
import { Injectable } from '@nestjs/common';
@@ -15,8 +15,10 @@ export class TripsStorageRefsService extends StorageReclaimSource {
readonly id = 'trips';
readonly claims = EVERY_RECLAIMABLE_CATEGORY;
protected async storedValues(): Promise<Array<string | null | undefined>> {
const rows = await this.em.getRepository(Trips).find({ cover_image: { $ne: null } }, { fields: ['cover_image'] });
protected async storedValues(containing: readonly string[] | null): Promise<Array<string | null | undefined>> {
const rows = await this.em
.getRepository(Trips)
.find(likeAny<Trips>(['cover_image'], containing), { fields: ['cover_image'] });
return rows.map((row) => row.cover_image);
}
}