mirror of
https://github.com/mauriceboe/TREK.git
synced 2026-11-27 15:17:30 +00:00
fix(storage): delete what a delete or a replace left unnamed right away again
Leaving every replaced cover, place image and deleted journey photo to the nightly pass kept them publicly fetchable by URL for a week at least, and for good while deletion was off. Owners now hand the values a delete or a replace left behind to StorageReleaseService once their write committed. It asks every registered reference source, with the same parser as the nightly pass, and deletes at once what no row names any more: an object a trip copy, a journey or a saved place still shows stays, which the old inline deletes got wrong. The release holds the pass's guards (reclaimable categories at their root only, never an owner marker, never while a restore runs, never with a required source missing or an overlapping location), never fails the request and logs at debug. It runs for trip covers (update, upload, trip delete), collection covers and saved-place images, place images (update, bulk update, delete), journey covers and journey or gallery photos (their thumbnail goes with a file that went), avatars (change, delete, account deletion), trip files (permanent delete, empty trash) and collab note and chat attachments. A trip file row now goes before its bytes, so a failing backend no longer fails the delete. The objects of a deleted trip's places and files are left to the nightly pass: their rows are other domains'. PlacesService drops the collection places repository nothing read any more. Size, warning and boundary baselines follow the shrunk files.
This commit is contained in:
@@ -138,6 +138,12 @@ export class CollectionPlacesRepository extends TrekRepository<CollectionPlaces>
|
||||
// CL47/CL48 — updatePlace
|
||||
// ---------------------------------------------------------------------
|
||||
|
||||
/** CL47 (`updatePlace`'s pre-image read, dup text also `deletePlace`/`deletePlacesMany`/`setPlaceImage`) — `SELECT image_url FROM collection_places WHERE id=?`. Plain (non-FK) column — safe through the entity API, `fields: ['image_url']`. */
|
||||
async imageUrl(id: number): Promise<string | null | undefined> {
|
||||
const row = await this.findOne({ id }, { fields: ['image_url'] });
|
||||
return row?.image_url;
|
||||
}
|
||||
|
||||
/**
|
||||
* CL48 (`updatePlace`, TX) — the allow-listed dynamic `UPDATE
|
||||
* collection_places SET ... WHERE id=?`, including the cross-list move
|
||||
|
||||
@@ -230,6 +230,16 @@ export class CollectionsRepository extends TrekRepository<Collections> {
|
||||
.execute();
|
||||
}
|
||||
|
||||
/** CL31 (`setCollectionCover`) — `SELECT cover_image FROM collections WHERE id=?`. */
|
||||
async coverImage(id: number): Promise<string | null | undefined> {
|
||||
const row = await this.readDb()
|
||||
.selectFrom('collections')
|
||||
.select('cover_image')
|
||||
.where('id', '=', id)
|
||||
.executeTakeFirst();
|
||||
return row?.cover_image;
|
||||
}
|
||||
|
||||
/** CL32 (`setCollectionCover`) — `UPDATE collections SET cover_image=?, updated_at=<dbNow()> WHERE id=?`. */
|
||||
async setCoverImage(id: number, coverUrl: string | null): Promise<void> {
|
||||
await this.readDb()
|
||||
|
||||
@@ -28,6 +28,7 @@ import { BudgetService } from '../budget/budget.service';
|
||||
import { UnitOfWork } from '../database/unit-of-work';
|
||||
import { pluginsDataRoot } from '../plugins/paths';
|
||||
import { enqueueHookUserDataErasures } from '../plugins/user-erasure-enqueue';
|
||||
import { StorageReleaseService } from '../storage/storage-release.service';
|
||||
import { InjectRepository } from '@mikro-orm/nestjs';
|
||||
import { Injectable } from '@nestjs/common';
|
||||
|
||||
@@ -73,6 +74,7 @@ export class UserCleanupService {
|
||||
@InjectRepository(Plugins) private readonly pluginsRepo: PluginsRepository,
|
||||
@InjectRepository(PluginUserErasureQueue)
|
||||
private readonly pluginUserErasureQueueRepo: PluginUserErasureQueueRepository,
|
||||
private readonly release: StorageReleaseService,
|
||||
) {}
|
||||
|
||||
/**
|
||||
@@ -188,10 +190,15 @@ export class UserCleanupService {
|
||||
* stays raw, per each method's own docstring.
|
||||
*/
|
||||
async deleteUserCompletely(userId: number): Promise<void> {
|
||||
const avatar = await this.usersRepo.getAvatar(userId);
|
||||
await this.uow.transactional(async () => {
|
||||
await this.cleanupUserReferences(userId);
|
||||
await this.erasePluginUserData(userId);
|
||||
await this.usersRepo.deleteById(userId);
|
||||
});
|
||||
// After the commit, the uploaded avatar goes unless another row names it.
|
||||
// What the user's trips and journeys named is the nightly reclaim pass's:
|
||||
// those rows are other domains' and went with the cascade.
|
||||
await this.release.releaseValues([avatar], { bare: 'avatars' });
|
||||
}
|
||||
}
|
||||
|
||||
@@ -22,7 +22,7 @@ import {
|
||||
writeInstanceApiKey,
|
||||
type InstanceApiKeyName,
|
||||
} from '../settings/instance-api-keys';
|
||||
import { StorageService } from '../storage/storage.service';
|
||||
import { StorageReleaseService } from '../storage/storage-release.service';
|
||||
import { EMAIL_REGEX, mask_stored_api_key } from './auth.helpers';
|
||||
import { InjectRepository } from '@mikro-orm/nestjs';
|
||||
import { Injectable } from '@nestjs/common';
|
||||
@@ -30,6 +30,9 @@ import { Injectable } from '@nestjs/common';
|
||||
/** A key check is a single request to a provider; one that hangs must not hold the settings page. */
|
||||
const KEY_CHECK_TIMEOUT_MS = 10_000;
|
||||
|
||||
/** `users.avatar` holds the bare name of an uploaded avatar. */
|
||||
const AVATAR_KEYS = { bare: 'avatars' } as const;
|
||||
|
||||
/**
|
||||
* The account a user administers about themselves: display settings, avatar,
|
||||
* the third-party API keys they paste in, and the directory listing other
|
||||
@@ -51,7 +54,7 @@ const KEY_CHECK_TIMEOUT_MS = 10_000;
|
||||
@Injectable()
|
||||
export class UserProfileService {
|
||||
constructor(
|
||||
private readonly storage: StorageService,
|
||||
private readonly release: StorageReleaseService,
|
||||
private readonly uow: UnitOfWork,
|
||||
@InjectRepository(AppSettings) private readonly appSettings: AppSettingsRepository,
|
||||
@InjectRepository(Users) private readonly usersRepo: UsersRepository,
|
||||
@@ -359,16 +362,10 @@ export class UserProfileService {
|
||||
|
||||
async saveAvatar(userId: number, filename: string) {
|
||||
const current = await this.usersRepo.getAvatar(userId);
|
||||
// Only a locally uploaded file has something to clean up. An OIDC picture URL
|
||||
// (#1399) has no storage object, so skip the delete entirely.
|
||||
if (current && !/^https:\/\//i.test(current)) {
|
||||
// Fire-and-forget parity: leftover objects are harmless; the DB update is
|
||||
// the source of truth for which avatar is current. The catch also
|
||||
// swallows a hostile stored value the central key validation rejects.
|
||||
await this.storage.delete('avatars', current).catch(() => {});
|
||||
}
|
||||
|
||||
await this.usersRepo.setAvatar(userId, filename);
|
||||
// The replaced upload goes once the row names the new one. An OIDC picture
|
||||
// URL (#1399) names no object of ours, and a hostile value names nothing.
|
||||
await this.release.releaseValues([current], AVATAR_KEYS);
|
||||
|
||||
const updated = await this.usersRepo.findProfileBasic(userId);
|
||||
return { success: true, avatar_url: avatarUrl(updated || {}) };
|
||||
@@ -376,11 +373,8 @@ export class UserProfileService {
|
||||
|
||||
async deleteAvatar(userId: number) {
|
||||
const current = await this.usersRepo.getAvatar(userId);
|
||||
// An OIDC picture URL (#1399) has no storage object — only delete an uploaded one.
|
||||
if (current && !/^https:\/\//i.test(current)) {
|
||||
await this.storage.delete('avatars', current).catch(() => {});
|
||||
}
|
||||
await this.usersRepo.setAvatar(userId, null);
|
||||
await this.release.releaseValues([current], AVATAR_KEYS); // an OIDC picture URL (#1399) names no object
|
||||
return { success: true };
|
||||
}
|
||||
|
||||
|
||||
@@ -26,15 +26,16 @@ import { UnitOfWork } from '../database/unit-of-work';
|
||||
import { NotificationsService } from '../notifications/notifications.service';
|
||||
import { PermissionsService } from '../permissions/permissions.service';
|
||||
import { RealtimeService } from '../realtime/realtime.service';
|
||||
import { StorageService } from '../storage/storage.service';
|
||||
import { StorageReleaseService } from '../storage/storage-release.service';
|
||||
import { InjectRepository } from '@mikro-orm/nestjs';
|
||||
import { Injectable } from '@nestjs/common';
|
||||
import type { TrekWsPayload, TrekWsTripEventName } from '@trek/shared';
|
||||
|
||||
import path from 'path';
|
||||
|
||||
type Trip = TripAccess;
|
||||
|
||||
/** How a `trip_files.filename` names its object: the bare name, after any legacy path. */
|
||||
const TRIP_FILE_KEYS = { bare: 'files', basename: true } as const;
|
||||
|
||||
// Half a megabyte of markup is far more than any og:/<title> block needs, and
|
||||
// the URL is caller-supplied, so read no further than that.
|
||||
const MAX_PREVIEW_BYTES = 512 * 1024;
|
||||
@@ -169,7 +170,7 @@ export class CollabService {
|
||||
private readonly permissions: PermissionsService,
|
||||
private readonly realtime: RealtimeService,
|
||||
private readonly notifications: NotificationsService,
|
||||
private readonly storage: StorageService,
|
||||
private readonly release: StorageReleaseService,
|
||||
private readonly rateLimit: RateLimitService,
|
||||
private readonly uow: UnitOfWork,
|
||||
@InjectRepository(CollabMessageReactions) private readonly messageReactionsRepo: CollabMessageReactionsRepository,
|
||||
@@ -381,20 +382,18 @@ export class CollabService {
|
||||
const existing = await this.notesRepo.findInTrip(idNum, tripIdNum);
|
||||
if (!existing) return false;
|
||||
|
||||
// Clean up attached objects first (delete-first is intentional — a failed
|
||||
// row delete leaves dangling rows, never orphaned files). basename()
|
||||
// tolerates any legacy 'files/'-prefixed row the boot migration has not
|
||||
// seen.
|
||||
// The rows go first, then the release of what they named: a failed delete
|
||||
// keeps note, rows and bytes together, and an attachment another row still
|
||||
// names (a trip copy's file) keeps its bytes (#2924).
|
||||
const noteFiles = await this.notesRepo.listFilenamesForNote(existing.id);
|
||||
for (const f of noteFiles) {
|
||||
await this.storage.delete('files', path.basename(f.filename)).catch(() => {
|
||||
/* ignore */
|
||||
});
|
||||
}
|
||||
await this.uow.transactional(async () => {
|
||||
await this.notesRepo.deleteAttachmentsForNote(existing.id);
|
||||
await this.notesRepo.delete(existing.id);
|
||||
});
|
||||
await this.release.releaseValues(
|
||||
noteFiles.map((f) => f.filename),
|
||||
TRIP_FILE_KEYS,
|
||||
);
|
||||
return true;
|
||||
}
|
||||
|
||||
@@ -449,11 +448,8 @@ export class CollabService {
|
||||
const file = await this.notesRepo.findScopedForNote(fileIdNum, noteIdNum, tripIdNum);
|
||||
if (!file) return false;
|
||||
|
||||
await this.storage.delete('files', path.basename(file.filename)).catch(() => {
|
||||
/* ignore */
|
||||
});
|
||||
|
||||
await this.notesRepo.deleteAttachmentById(file.id);
|
||||
await this.release.releaseValues([file.filename], TRIP_FILE_KEYS);
|
||||
return true;
|
||||
}
|
||||
|
||||
@@ -750,11 +746,10 @@ export class CollabService {
|
||||
// Only once the rows are actually gone. Dropping the blobs first left a
|
||||
// live message pointing at attachments whose bytes no longer existed
|
||||
// whenever the second statement failed.
|
||||
for (const file of attachments) {
|
||||
void this.storage.delete('files', path.basename(file.filename)).catch(() => {
|
||||
/* best effort */
|
||||
});
|
||||
}
|
||||
await this.release.releaseValues(
|
||||
attachments.map((file) => file.filename),
|
||||
TRIP_FILE_KEYS,
|
||||
);
|
||||
// Read before the delete; see the class docstring's `username` note.
|
||||
return { username: author?.username };
|
||||
}
|
||||
|
||||
@@ -5,7 +5,7 @@ import { InjectRepository } from '@mikro-orm/nestjs';
|
||||
import { PermissionsService } from '../permissions/permissions.service';
|
||||
import { RealtimeService } from '../realtime/realtime.service';
|
||||
import { PlacesService } from '../places/places.service';
|
||||
import { StorageService } from '../storage/storage.service';
|
||||
import { StorageReleaseService } from '../storage/storage-release.service';
|
||||
import { Collections } from '../../db/entities/Collections.entity';
|
||||
import { CollectionsRepository, type CollectionPlaceRow } from '../../db/repositories/Collections.repository';
|
||||
import { CollectionMembers } from '../../db/entities/CollectionMembers.entity';
|
||||
@@ -77,18 +77,13 @@ import { PlaceImportService, type ExportedCollectionFile } from '../place-import
|
||||
import { UnitOfWork } from '../database/unit-of-work';
|
||||
import { parseLinks, serializeLinks } from './collections.helpers';
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Errors — thrown as plain Errors carrying a status; TrekExceptionFilter maps
|
||||
// `err.status` → that HTTP code with an `{ error: message }` body.
|
||||
// ---------------------------------------------------------------------------
|
||||
// Errors: a DomainError carrying a status; TrekExceptionFilter maps it to that code with an `{ error }` body.
|
||||
|
||||
function httpError(status: number, message: string): never {
|
||||
throw new DomainError(status, message);
|
||||
}
|
||||
|
||||
/** Re-exported under this service's historical name — the underlying type
|
||||
* now lives in `_shared/collection-role.ts` (R6), the ONE shared predicate
|
||||
* `isVisible`/`isOwner`/`roleOf` all resolve through. */
|
||||
/** Re-exported under this service's historical name; the type lives in `_shared/collection-role.ts` (R6). */
|
||||
export type EffectiveRole = CollectionRole;
|
||||
|
||||
type PlaceRow = CollectionPlaceRow;
|
||||
@@ -110,7 +105,7 @@ export class CollectionsService {
|
||||
private readonly permissions: PermissionsService,
|
||||
private readonly realtime: RealtimeService,
|
||||
private readonly notifications: NotificationsService,
|
||||
private readonly storage: StorageService,
|
||||
private readonly release: StorageReleaseService, // replaced and deleted images, after the write
|
||||
private readonly uow: UnitOfWork,
|
||||
@InjectRepository(Collections) private readonly collectionsRepo: CollectionsRepository,
|
||||
@InjectRepository(CollectionMembers) private readonly members: CollectionMembersRepository,
|
||||
@@ -601,13 +596,12 @@ export class CollectionsService {
|
||||
return { ...col, is_owner: col.owner_id === userId };
|
||||
}
|
||||
|
||||
/**
|
||||
* Set (or clear) a list's cover image. The previous file stays where another
|
||||
* row may name it; the storage reclaim job removes it once nothing does.
|
||||
*/
|
||||
/** Set (or clear) a list's cover image; the previous file goes unless another row still names it. */
|
||||
async setCollectionCover(userId: number, id: number, coverUrl: string | null, socketId?: string): Promise<Collection> {
|
||||
await this.assertCanEdit(userId, id);
|
||||
const prev = (await this.collectionsRepo.coverImage(id)) ?? null;
|
||||
await this.collectionsRepo.setCoverImage(id, coverUrl);
|
||||
await this.release.releaseValues([prev]);
|
||||
await this.notifyCollectionUsers(id, socketId, 'collections:updated');
|
||||
const col = await this.getCollectionRow(id);
|
||||
return { ...col, is_owner: col.owner_id === userId };
|
||||
@@ -876,6 +870,7 @@ export class CollectionsService {
|
||||
async updatePlace(userId: number, placeId: number, body: CollectionPlaceUpdateRequest, socketId?: string): Promise<CollectionPlace> {
|
||||
const currentCollection = await this.collectionIdOfPlace(placeId);
|
||||
await this.assertCanEdit(userId, currentCollection);
|
||||
const prevImage = body.image_url !== undefined ? (await this.collectionPlaces.imageUrl(placeId)) ?? null : null;
|
||||
|
||||
const write: Parameters<CollectionPlacesRepository['updateFields']>[1] = {};
|
||||
if (body.name !== undefined) write.name = body.name;
|
||||
@@ -898,8 +893,7 @@ export class CollectionsService {
|
||||
movedTo = body.collection_id;
|
||||
}
|
||||
|
||||
// Field update + tag rewrite + label rewrite are one logical write — atomic
|
||||
// since the post-fold quirk pass.
|
||||
// Field update + tag rewrite + label rewrite are one logical write, so one transaction.
|
||||
await this.uow.transactional(async () => {
|
||||
await this.collectionPlaces.updateFields(placeId, write);
|
||||
|
||||
@@ -913,6 +907,7 @@ export class CollectionsService {
|
||||
if (movedTo) await this.collectionPlaces.deleteLabelAssignments(placeId);
|
||||
if (body.label_ids !== undefined) await this.setPlaceLabels(placeId, movedTo ?? currentCollection, body.label_ids);
|
||||
});
|
||||
await this.release.releaseValues([prevImage]); // a replaced custom thumbnail (#1136), unless a copy names it
|
||||
|
||||
await this.notifyCollectionUsers(currentCollection, socketId, 'collections:updated');
|
||||
if (movedTo) await this.notifyCollectionUsers(movedTo, socketId, 'collections:updated');
|
||||
@@ -944,34 +939,36 @@ export class CollectionsService {
|
||||
return this.getPlaceById(placeId);
|
||||
}
|
||||
|
||||
// A saved place's uploaded image is never deleted here: copy-to-trip and
|
||||
// save-to-collection share it by reference, and other columns can name it
|
||||
// too. The storage reclaim job removes it once no row does (#2924).
|
||||
// A saved place's image goes with it unless a trip place it was copied to (or from) still names it (#2924).
|
||||
async deletePlace(userId: number, placeId: number, socketId?: string): Promise<void> {
|
||||
const collectionId = await this.collectionIdOfPlace(placeId);
|
||||
await this.assertCanDelete(userId, collectionId);
|
||||
const image = (await this.collectionPlaces.imageUrl(placeId)) ?? null;
|
||||
await this.collectionPlaces.deleteById(placeId); // CASCADE drops tags. NO photo-cache reclaim.
|
||||
await this.release.releaseValues([image]);
|
||||
await this.notifyCollectionUsers(collectionId, socketId, 'collections:updated');
|
||||
}
|
||||
|
||||
async deletePlacesMany(userId: number, ids: number[], socketId?: string): Promise<number[]> {
|
||||
// All-or-nothing since the post-fold quirk pass: every id is resolved and
|
||||
// permission-checked BEFORE any delete (the relocated legacy interleaved
|
||||
// checks with deletes, so a mid-list 403/404 left earlier deletes committed),
|
||||
// and the deletes then run in one transaction.
|
||||
// All-or-nothing: every id is resolved and permission-checked BEFORE any delete (the legacy interleaved
|
||||
// them, so a mid-list 403/404 left earlier deletes committed), then the deletes run in one transaction.
|
||||
const deleted: number[] = [];
|
||||
const touched = new Set<number>();
|
||||
const reads: Promise<string | null | undefined>[] = [];
|
||||
for (const id of ids) {
|
||||
const collectionId = await this.collectionIdOfPlace(id);
|
||||
await this.assertCanDelete(userId, collectionId);
|
||||
touched.add(collectionId);
|
||||
reads.push(this.collectionPlaces.imageUrl(id).catch(() => null)); // to release once the rows are gone
|
||||
}
|
||||
const images = await Promise.all(reads);
|
||||
await this.uow.transactional(async () => {
|
||||
for (const id of ids) {
|
||||
await this.collectionPlaces.deleteById(id);
|
||||
deleted.push(id);
|
||||
}
|
||||
});
|
||||
await this.release.releaseValues(images);
|
||||
for (const cid of touched) await this.notifyCollectionUsers(cid, socketId, 'collections:updated');
|
||||
return deleted;
|
||||
}
|
||||
@@ -1059,11 +1056,13 @@ export class CollectionsService {
|
||||
return this.collectionPlaces.matchingByTripSource(collectionIds, tripId, place, COORD_DEDUP_TOLERANCE);
|
||||
}
|
||||
|
||||
/** Set (or clear) a saved place's custom thumbnail; the storage reclaim job takes the replaced upload. */
|
||||
/** Set (or clear) a saved place's custom thumbnail; the replaced upload goes unless another row names it. */
|
||||
async setPlaceImage(userId: number, placeId: number, imageUrl: string | null, socketId?: string): Promise<CollectionPlace> {
|
||||
const collectionId = await this.collectionIdOfPlace(placeId);
|
||||
await this.assertCanEdit(userId, collectionId);
|
||||
const prev = (await this.collectionPlaces.imageUrl(placeId)) ?? null;
|
||||
await this.collectionPlaces.setImageUrl(placeId, imageUrl);
|
||||
await this.release.releaseValues([prev]);
|
||||
await this.notifyCollectionUsers(collectionId, socketId, 'collections:updated');
|
||||
return this.getPlaceById(placeId);
|
||||
}
|
||||
|
||||
@@ -23,6 +23,7 @@ import { restTripWriter, type TripWriter } from '../common/trip-writer';
|
||||
import { UnitOfWork } from '../database/unit-of-work';
|
||||
import { PermissionsService } from '../permissions/permissions.service';
|
||||
import { RealtimeService } from '../realtime/realtime.service';
|
||||
import { StorageReleaseService } from '../storage/storage-release.service';
|
||||
import { StorageService } from '../storage/storage.service';
|
||||
import { StorageNotFoundError, StorageInvalidKeyError, type ObjectStat } from '../storage/storage.types';
|
||||
import { TripAccessService } from '../trip-membership/trip-access.service';
|
||||
@@ -73,6 +74,9 @@ export interface FileLink {
|
||||
*/
|
||||
export const FILE_CONTENT_MAX = 10 * 1024 * 1024;
|
||||
|
||||
/** How `trip_files.filename` names its object: the bare name, after any legacy path (every reader basename()s it). */
|
||||
const TRIP_FILE_KEYS = { bare: 'files', basename: true } as const;
|
||||
|
||||
/** Why a content read was refused. Each caller maps it onto its own error shape. */
|
||||
export type FileContentRefusal = 'not-found' | 'too-large' | 'not-accessible';
|
||||
|
||||
@@ -155,6 +159,7 @@ export class FilesService {
|
||||
@InjectRepository(Places) private readonly placesRepo: PlacesRepository,
|
||||
@InjectRepository(DayAssignments) private readonly dayAssignmentsRepo: DayAssignmentsRepository,
|
||||
@InjectRepository(BudgetItems) private readonly budgetItemsRepo: BudgetItemsRepository,
|
||||
private readonly release: StorageReleaseService,
|
||||
) {}
|
||||
|
||||
async verifyTripAccess(tripId: string | number, userId: number) {
|
||||
@@ -490,46 +495,31 @@ export class FilesService {
|
||||
return formatFile(restored!);
|
||||
}
|
||||
|
||||
/**
|
||||
* Drops the row, then releases its object: the bytes go unless another row
|
||||
* (a trip copy's file, a doc-sync copy) still names them (#2924). A release
|
||||
* never fails the delete; what it leaves is the nightly reclaim pass's.
|
||||
*/
|
||||
async permanentDeleteFile(file: TripFileRow): Promise<void> {
|
||||
// storage.delete is idempotent on a missing object (the old rm force:true
|
||||
// contract). Only drop the DB row when the delete either succeeded or the
|
||||
// object was already gone — otherwise a permission / ENOSPC failure
|
||||
// would orphan the bytes with no DB pointer left to clean them.
|
||||
try {
|
||||
await this.storage.delete('files', path.basename(file.filename));
|
||||
} catch (e) {
|
||||
console.error(`[files] unlink failed for ${file.filename}, keeping DB row:`, e);
|
||||
throw e;
|
||||
}
|
||||
await this.tripFilesRepo.deleteById(file.id);
|
||||
await this.release.releaseValues([file.filename], TRIP_FILE_KEYS);
|
||||
}
|
||||
|
||||
/** R2: the storage-delete loop stays outside any transaction (rule 24); only the final bulk `trip_files` delete (FL23) runs inside one. */
|
||||
/**
|
||||
* Every trashed file of the trip, rows first, then the release of what they
|
||||
* named, as for permanentDeleteFile. The bulk `trip_files` delete (FL23) is
|
||||
* one statement, so it needs no transaction (task-8-review.md L1/U1).
|
||||
*/
|
||||
async emptyTrash(tripId: string | number): Promise<number> {
|
||||
const tripIdNum = toRowId(tripId) ?? -1;
|
||||
const trashed = await this.tripFilesRepo.listTrashed(tripIdNum);
|
||||
// Collect successful IDs separately so we only DELETE rows whose disk
|
||||
// content was actually removed — failing unlinks keep their DB row
|
||||
// and a retry via the single-file delete path can try again.
|
||||
const successfullyUnlinked: number[] = [];
|
||||
await Promise.all(
|
||||
trashed.map(async (file) => {
|
||||
try {
|
||||
await this.storage.delete('files', path.basename(file.filename));
|
||||
successfullyUnlinked.push(file.id);
|
||||
} catch (e) {
|
||||
console.error(`[files] unlink failed for ${file.filename}, keeping DB row:`, e);
|
||||
}
|
||||
}),
|
||||
if (trashed.length === 0) return 0;
|
||||
await this.tripFilesRepo.deleteMany(trashed.map((file) => file.id));
|
||||
await this.release.releaseValues(
|
||||
trashed.map((file) => file.filename),
|
||||
TRIP_FILE_KEYS,
|
||||
);
|
||||
// A single statement is already atomic — no `uow.transactional` wrapper
|
||||
// needed here (task-8-review.md L1/U1: the wrapper this method used to
|
||||
// carry was vacuous, and FILE-SVC-062's "rollback" claim never actually
|
||||
// exercised it — removing it keeps every test green).
|
||||
if (successfullyUnlinked.length > 0) {
|
||||
await this.tripFilesRepo.deleteMany(successfullyUnlinked);
|
||||
}
|
||||
return successfullyUnlinked.length;
|
||||
return trashed.length;
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
@@ -14,6 +14,7 @@ import { PluginGuardsModule } from '../../nest-rpc/plugin-guards.module';
|
||||
import { TrekPhotosModule } from '../photos/trek-photos.module';
|
||||
import { RealtimeModule } from '../realtime/realtime.module';
|
||||
import { SettingsModule } from '../settings/settings.module';
|
||||
import { StorageModule } from '../storage/storage.module';
|
||||
import { JourneyDomainService } from './journey-domain.service';
|
||||
import { JourneyEntryStaysService } from './journey-entry-stays.service';
|
||||
import { JourneyMapService } from './journey-map.service';
|
||||
@@ -88,6 +89,8 @@ import { Module } from '@nestjs/common';
|
||||
TrekPhotosModule,
|
||||
PluginGuardsModule,
|
||||
SettingsModule,
|
||||
// JourneySettingsService releases a replaced cover's object after the write.
|
||||
StorageModule,
|
||||
MikroOrmModule.forFeature([
|
||||
Journeys,
|
||||
JourneyContributors,
|
||||
|
||||
@@ -2,6 +2,7 @@ import { Journeys } from '../../db/entities/Journeys.entity';
|
||||
import type { JourneysRepository } from '../../db/repositories/Journeys.repository';
|
||||
import type { Journey } from '../../types';
|
||||
import { UnitOfWork } from '../database/unit-of-work';
|
||||
import { StorageReleaseService } from '../storage/storage-release.service';
|
||||
import { JourneyDomainService } from './journey-domain.service';
|
||||
import {
|
||||
journeySettingsPatch,
|
||||
@@ -24,7 +25,9 @@ interface JourneySettingsUpdate {
|
||||
* of the input and the same owner check), with the stored values of exactly
|
||||
* the columns it wrote, read in the same transaction. That is what takes the
|
||||
* change back: the assistant's undo writes those values again through the
|
||||
* same tool. The broadcast goes out after the commit.
|
||||
* same tool. The broadcast goes out after the commit, and so does the release
|
||||
* of a replaced cover: its object goes unless another row (the trip it was
|
||||
* inherited from, a gallery photo) still names it (#2924).
|
||||
*/
|
||||
@Injectable()
|
||||
export class JourneySettingsService {
|
||||
@@ -32,6 +35,7 @@ export class JourneySettingsService {
|
||||
private readonly journeys: JourneyDomainService,
|
||||
private readonly uow: UnitOfWork,
|
||||
@InjectRepository(Journeys) private readonly journeysRepo: JourneysRepository,
|
||||
private readonly release: StorageReleaseService,
|
||||
) {}
|
||||
|
||||
/** Null for anyone but the owner, who alone reshapes the journey itself, as on the route. */
|
||||
@@ -50,6 +54,7 @@ export class JourneySettingsService {
|
||||
return previousSettings(before as unknown as Readonly<Record<string, unknown>> | undefined, patch);
|
||||
});
|
||||
if (written) await this.journeys.broadcastJourneyEvent(journeyId, 'journey:updated', {}, sid);
|
||||
if (typeof previous.cover_image === 'string') await this.release.releaseValues([previous.cover_image]);
|
||||
const journey = (await this.journeysRepo.findById(journeyId)) as Journey | undefined;
|
||||
return journey ? { journey, previous } : null;
|
||||
}
|
||||
|
||||
@@ -25,6 +25,8 @@ import type { User } from '../../types';
|
||||
import { RuntimeEnvService } from '../app-config/runtime-env.service';
|
||||
import { isDemoWriteBlocked, DEMO_WRITE_ERROR } from '../common/demo-write';
|
||||
import { StorageService } from '../storage/storage.service';
|
||||
import { StorageReleaseService } from '../storage/storage-release.service';
|
||||
import { journeyThumbName } from '../memories/thumbnail.service';
|
||||
import { JourneyService } from './journey.service';
|
||||
import { JourneyBookService } from './journey-book.service';
|
||||
import { JourneyPhotoCaptureService, type ProviderPhotoBatch, type ProviderPhotoTarget } from './journey-photo-capture.service';
|
||||
@@ -175,6 +177,8 @@ export class JourneyController {
|
||||
private readonly photoLinks: JourneyPhotoLinksService,
|
||||
// Whether DEMO_MODE is on, read on every upload (refuseDemoUpload).
|
||||
private readonly env: RuntimeEnvService,
|
||||
// What a deleted photo named, once its row is gone (#2924).
|
||||
private readonly release: StorageReleaseService,
|
||||
) {}
|
||||
|
||||
/**
|
||||
@@ -459,16 +463,27 @@ export class JourneyController {
|
||||
@Delete('photos/:photoId')
|
||||
@ResponseContract(successResponseSchema)
|
||||
async deletePhoto(@CurrentUser() user: User, @Param('photoId') photoId: string) {
|
||||
// The bytes stay: another journey, a trip or a cover may name the same
|
||||
// object. Once the photo row is gone the storage reclaim job takes the file
|
||||
// and its poster, and the thumbnail sweep its thumbnail (#2924).
|
||||
const photo = await this.journey.deletePhoto(Number(photoId), user.id);
|
||||
if (!photo) {
|
||||
throw new HttpException({ error: 'Photo not found' }, 404);
|
||||
}
|
||||
await this.releasePhoto(photo);
|
||||
return { success: true };
|
||||
}
|
||||
|
||||
/**
|
||||
* After a photo's row went: its file and its poster go at once unless another
|
||||
* row (another journey's photo, a journey cover) still names them, and the
|
||||
* thumbnail derived from a file that went goes with it (#2924).
|
||||
*/
|
||||
private async releasePhoto(photo: { file_path?: string | null; thumbnail_path?: string | null }): Promise<void> {
|
||||
const released = await this.release.releaseValues([photo.file_path, photo.thumbnail_path], { bare: 'journey' });
|
||||
const filePath = photo.file_path;
|
||||
if (!filePath?.startsWith('journey/')) return;
|
||||
if (!released.some((ref) => ref.category === 'journey' && `journey/${ref.key}` === filePath)) return;
|
||||
await this.storage.delete('journey', journeyThumbName(filePath)).catch(() => { /* already gone */ });
|
||||
}
|
||||
|
||||
// ── Gallery (prefix /:id/gallery — before /:id) ─────────────────────────
|
||||
@Post(':id/gallery/photos')
|
||||
@UseInterceptors(FilesInterceptor('photos'))
|
||||
@@ -546,11 +561,11 @@ export class JourneyController {
|
||||
@HttpCode(204)
|
||||
@ResponseContract(emptyResponseSchema)
|
||||
async deleteGalleryPhoto(@CurrentUser() user: User, @Param('journeyPhotoId') journeyPhotoId: string): Promise<void> {
|
||||
// The bytes stay, as for deletePhoto above.
|
||||
const photo = await this.journey.deleteGalleryPhoto(Number(journeyPhotoId), user.id);
|
||||
if (!photo) {
|
||||
throw new HttpException({ error: 'Photo not found or not allowed' }, 404);
|
||||
}
|
||||
await this.releasePhoto(photo);
|
||||
}
|
||||
|
||||
// ── Journeys /:id ───────────────────────────────────────────────────────
|
||||
|
||||
@@ -6,6 +6,7 @@ import { PhotoProviderRegistry } from '../memories/photo-provider.registry';
|
||||
import { PhotoResolverService } from '../memories/photo-resolver.service';
|
||||
import { JourneyDomainService } from './journey-domain.service';
|
||||
import { JourneyMapService } from './journey-map.service';
|
||||
import { JourneySettingsService } from './journey-settings.service';
|
||||
import { JourneyShareService } from './journey-share.service';
|
||||
import { Injectable } from '@nestjs/common';
|
||||
|
||||
@@ -28,6 +29,7 @@ export class JourneyService {
|
||||
private readonly share: JourneyShareService,
|
||||
private readonly immichRepo: UserImmichRepository,
|
||||
private readonly map: JourneyMapService,
|
||||
private readonly settings: JourneySettingsService,
|
||||
) {}
|
||||
|
||||
async journeyAddonEnabled(): Promise<boolean> {
|
||||
@@ -44,8 +46,14 @@ export class JourneyService {
|
||||
getJourneyFull(id: number, userId: number) {
|
||||
return this.journey.getJourneyFull(id, userId);
|
||||
}
|
||||
updateJourney(id: number, userId: number, data: Parameters<typeof this.journey.updateJourney>[2], sid?: string) {
|
||||
return this.journey.updateJourney(id, userId, data, sid);
|
||||
/** The settings update the MCP tool makes too, so a replaced cover is released the same way on both. */
|
||||
async updateJourney(
|
||||
id: number,
|
||||
userId: number,
|
||||
data: Parameters<typeof this.journey.updateJourney>[2],
|
||||
sid?: string,
|
||||
) {
|
||||
return (await this.settings.updateWithPrevious(id, userId, data, sid))?.journey ?? null;
|
||||
}
|
||||
deleteJourney(id: number, userId: number, sid?: string) {
|
||||
return this.journey.deleteJourney(id, userId, sid);
|
||||
|
||||
@@ -25,6 +25,7 @@ import { MAX_PLACE_IMAGE_SIZE, PLACE_IMAGE_EXTENSIONS } from '../common/place-im
|
||||
import { randomUUID } from 'node:crypto';
|
||||
import { JourneyDomainService } from '../journey/journey-domain.service';
|
||||
import { StorageService } from '../storage/storage.service';
|
||||
import { StorageReleaseService } from '../storage/storage-release.service';
|
||||
import { AccommodationsService } from '../accommodations/accommodations.service';
|
||||
import { Places } from '../../db/entities/Places.entity';
|
||||
import { Tags } from '../../db/entities/Tags.entity';
|
||||
@@ -42,8 +43,6 @@ import type { CategoriesRepository } from '../../db/repositories/Categories.repo
|
||||
import type { TripsRepository } from '../../db/repositories/Trips.repository';
|
||||
import { BudgetItems } from '../../db/entities/BudgetItems.entity';
|
||||
import type { BudgetItemsRepository } from '../../db/repositories/BudgetItems.repository';
|
||||
import { CollectionPlaces } from '../../db/entities/CollectionPlaces.entity';
|
||||
import type { CollectionPlacesRepository } from '../../db/repositories/CollectionPlaces.repository';
|
||||
|
||||
/** Rows a place delete took down with the nights booked there, for the caller to announce. */
|
||||
export interface CancelledStays {
|
||||
@@ -157,17 +156,11 @@ export class PlacesService {
|
||||
@InjectRepository(TripMembers) private readonly tripMembersRepo: TripMembersRepository,
|
||||
@InjectRepository(DayAssignments) private readonly dayAssignmentsRepo: DayAssignmentsRepository,
|
||||
@InjectRepository(Categories) private readonly categoriesRepo: CategoriesRepository,
|
||||
// Task 9 fix wave (B-M2 / A-L3 ruling): `DatabaseService.getTripTitle`
|
||||
// does not stay — it was the one method on that class this domain's own
|
||||
// PL28 comment said should convert like its siblings once concurrent
|
||||
// implementers stopped colliding on this file. `Trips` is already on
|
||||
// `PlacesModule`'s `forFeature` list, so this needs no module change.
|
||||
// Task 9 fix wave (B-M2 / A-L3): PL28's trip title, read here since `DatabaseService.getTripTitle` went.
|
||||
@InjectRepository(Trips) private readonly tripsRepo: TripsRepository,
|
||||
// Plan 3e Task 2 (budget) — additive, PL15/PL18/PL22 only.
|
||||
@InjectRepository(BudgetItems) private readonly budgetItemsRepo: BudgetItemsRepository,
|
||||
// Plan 3h Task 6 (survivors): read by nothing since the storage reclaim job
|
||||
// took over the image ref-count (#2924); kept so the constructor stays put.
|
||||
@InjectRepository(CollectionPlaces) private readonly collectionPlacesRepo: CollectionPlacesRepository,
|
||||
private readonly release: StorageReleaseService, // the images a change or a delete left unnamed (#2924)
|
||||
// Reading files and shared lists; this service only persists what it reads.
|
||||
private readonly placeImport: PlaceImportService,
|
||||
) {}
|
||||
@@ -418,7 +411,8 @@ export class PlacesService {
|
||||
body: PlaceUpdateInput,
|
||||
ifMatch?: string,
|
||||
): Promise<PlaceWithTags | UpdateConflict | null> {
|
||||
const { result } = await this.uow.transactional(() => this.applyUpdate(tripId, placeId, body, ifMatch));
|
||||
const { result, previousImage } = await this.uow.transactional(() => this.applyUpdate(tripId, placeId, body, ifMatch));
|
||||
await this.release.releaseValues([previousImage]); // after the commit: kept while a copy or a cover names it
|
||||
return result;
|
||||
}
|
||||
|
||||
@@ -431,7 +425,7 @@ export class PlacesService {
|
||||
placeId: string,
|
||||
body: PlaceUpdateInput,
|
||||
ifMatch?: string,
|
||||
): Promise<{ result: PlaceWithTags | UpdateConflict | null }> {
|
||||
): Promise<{ result: PlaceWithTags | UpdateConflict | null; previousImage?: string | null }> {
|
||||
// PL9 — the pre-image read every `!== undefined` fallback below needs.
|
||||
// `toRowId` first (Task 3 review H1, absorbed here): every write in
|
||||
// this method (`updatePlace`, `tagsRepo.deleteForPlace`/`insertIgnore`)
|
||||
@@ -524,9 +518,8 @@ export class PlacesService {
|
||||
if (tags.length > 0) await this.tagsRepo.insertIgnore(id, await this.tagsOnTrip(tid, tags)); // PL13
|
||||
}
|
||||
|
||||
// A replaced or cleared custom upload (#1136) stays: a copy of this place or
|
||||
// a cover may name it, and the storage reclaim job removes it once none does.
|
||||
return { result: await this.placesRepo.findWithTagsAndRatings(id) }; // PL14
|
||||
// PL14; the image this write replaced (#1136), for the caller to release once the transaction committed.
|
||||
return { result: await this.placesRepo.findWithTagsAndRatings(id), previousImage: image_url !== undefined ? existingPlace.image_url : null };
|
||||
}
|
||||
|
||||
// -------------------------------------------------------------------------
|
||||
@@ -618,6 +611,7 @@ export class PlacesService {
|
||||
await this.placesRepo.deleteById(id);
|
||||
});
|
||||
await reclaimPhotoCache(this.photoCache, place.google_place_id, place.image_url);
|
||||
await this.release.releaseValues([place.image_url]);
|
||||
return { deleted: true, deletedTourPlaceIds: wasTour ? [id] : [], cancelled };
|
||||
}
|
||||
|
||||
@@ -663,6 +657,7 @@ export class PlacesService {
|
||||
for (const row of reclaimable) {
|
||||
await reclaimPhotoCache(this.photoCache, row.google_place_id, row.image_url);
|
||||
}
|
||||
await this.release.releaseValues(reclaimable.map((row) => row.image_url));
|
||||
return { deleted, deletedTourPlaceIds, cancelled };
|
||||
}
|
||||
|
||||
@@ -690,14 +685,17 @@ export class PlacesService {
|
||||
async updateMany(tripId: string, ids: number[], body: PlaceUpdateInput): Promise<PlaceWithTags[]> {
|
||||
if (ids.length === 0) return [];
|
||||
const updated: PlaceWithTags[] = [];
|
||||
const previousImages: (string | null | undefined)[] = [];
|
||||
await this.uow.transactional(async () => {
|
||||
for (const id of ids) {
|
||||
// Bulk update sends no If-Match, so applyUpdate() never returns a
|
||||
// conflict here; the guard keeps the types honest.
|
||||
const { result: place } = await this.applyUpdate(tripId, String(id), body);
|
||||
const { result: place, previousImage } = await this.applyUpdate(tripId, String(id), body);
|
||||
if (place && !isUpdateConflict(place)) updated.push(place);
|
||||
previousImages.push(previousImage);
|
||||
}
|
||||
});
|
||||
await this.release.releaseValues(previousImages); // one bulk value may have replaced many uploads
|
||||
return updated;
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,141 @@
|
||||
import { logDebug, logWarn } from '../audit/audit-log.logger';
|
||||
import { StorageJobsService } from './storage-jobs.service';
|
||||
import { isValidKey } from './storage-keys';
|
||||
import { StorageReclaimRegistryService } from './storage-reclaim-registry.service';
|
||||
import { inReclaimScope, RECLAIM_LEDGER, sharedLocationsOf } from './storage-reclaim.ledger';
|
||||
import {
|
||||
storageKeysIn,
|
||||
storageOwnerMarkerInstall,
|
||||
type StorageKeyOptions,
|
||||
type StorageKeyRef,
|
||||
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 { Injectable } from '@nestjs/common';
|
||||
|
||||
const SERVED = new Set<string>(SERVED_CATEGORIES);
|
||||
|
||||
/**
|
||||
* Deletes what a user's change left unnamed, right after it: a replaced or
|
||||
* removed cover, place image or avatar, a deleted journey photo or trip file.
|
||||
* The owner calls it once its transaction committed, with the values the rows
|
||||
* held, and every registered reference source (the nightly pass's sources and
|
||||
* parser) is asked whether anything still names each object. Only what no row
|
||||
* names goes, through `StorageService.delete` (replicas follow, a demo keeps
|
||||
* its bytes), so an object a trip copy, a journey or a saved place still shows
|
||||
* stays, unlike before (#2924), while a deleted photo is gone at once as it
|
||||
* always was.
|
||||
*
|
||||
* The pass's own guards hold: only the root of a reclaimable category, never
|
||||
* an owner marker, never while a restore runs, never where a required source
|
||||
* is missing or the category's location overlaps another's. It never fails
|
||||
* the caller's request: anything it leaves (an error, a guard) is the nightly
|
||||
* pass's to find. Releases are logged at debug, not audited one by one.
|
||||
*/
|
||||
@Injectable()
|
||||
export class StorageReleaseService {
|
||||
constructor(
|
||||
private readonly storage: StorageService,
|
||||
private readonly registry: StorageRegistryService,
|
||||
private readonly references: StorageReclaimRegistryService,
|
||||
private readonly jobs: StorageJobsService,
|
||||
) {}
|
||||
|
||||
/**
|
||||
* The objects these stored values name (any spelling a column holds), each
|
||||
* deleted when no row names it any more. Answers the ones that went.
|
||||
*/
|
||||
async releaseValues(
|
||||
values: ReadonlyArray<string | null | undefined>,
|
||||
options: StorageKeyOptions = {},
|
||||
): Promise<StorageKeyRef[]> {
|
||||
const byCategory = new Map<ServedCategory, Set<string>>();
|
||||
for (const value of values) {
|
||||
for (const ref of storageKeysIn(value, options)) {
|
||||
if (!SERVED.has(ref.category)) continue;
|
||||
const category = ref.category as ServedCategory;
|
||||
const keys = byCategory.get(category) ?? new Set<string>();
|
||||
keys.add(ref.key);
|
||||
byCategory.set(category, keys);
|
||||
}
|
||||
}
|
||||
const released = await Promise.all(
|
||||
[...byCategory].map(async ([category, keys]) =>
|
||||
(await this.releaseIfUnreferenced(category, [...keys])).map((key) => ({ category, key })),
|
||||
),
|
||||
);
|
||||
return released.flat();
|
||||
}
|
||||
|
||||
/** These keys of one category, each deleted when it exists and no row names it. Answers the ones that went. */
|
||||
async releaseIfUnreferenced(category: ServedCategory, keys: readonly string[]): Promise<string[]> {
|
||||
try {
|
||||
const candidates = [...new Set(keys)].filter(
|
||||
(key) => inReclaimScope(key) && isValidKey(key) && storageOwnerMarkerInstall(key) === null,
|
||||
);
|
||||
if (candidates.length === 0) return [];
|
||||
const sources = this.sourcesFor(category);
|
||||
if (sources === null) return [];
|
||||
const referenced = await this.referencedIn(category, candidates, sources);
|
||||
const unnamed = candidates.filter(
|
||||
(key) => !referenced.has(key.toLowerCase()) && !this.storage.keepsOnDelete(category, key),
|
||||
);
|
||||
const released = await Promise.all(unnamed.map((key) => this.deleteIfPresent(category, key)));
|
||||
return unnamed.filter((_key, i) => released[i]);
|
||||
} catch (err) {
|
||||
logWarn(`[storage] could not release '${category}' objects, the nightly pass will: ${messageOf(err)}`);
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
/** The sources to ask, or null when the category may not be released from now. */
|
||||
private sourcesFor(category: ServedCategory): readonly StorageReferenceSource[] | null {
|
||||
const rule = RECLAIM_LEDGER[category];
|
||||
if (!rule.reclaim || this.jobs.restoreRunning) return null;
|
||||
const sources = this.references.sources().filter((source) => source.claims.some((c) => c.category === category));
|
||||
const whole = new Set(
|
||||
sources
|
||||
.filter((source) => source.claims.some((c) => c.category === category && c.prefix === ''))
|
||||
.map((source) => source.id),
|
||||
);
|
||||
if (rule.requiredSources.some((id) => !whole.has(id))) return null;
|
||||
if (sharedLocationsOf(this.registry).has(category)) return null;
|
||||
return sources;
|
||||
}
|
||||
|
||||
private async referencedIn(
|
||||
category: ServedCategory,
|
||||
keys: readonly string[],
|
||||
sources: readonly StorageReferenceSource[],
|
||||
): Promise<Set<string>> {
|
||||
const answers = await Promise.all(
|
||||
sources.map(async (source) => {
|
||||
const asked = keys.filter((key) =>
|
||||
source.claims.some((claim) => claim.category === category && key.startsWith(claim.prefix)),
|
||||
);
|
||||
return asked.length === 0 ? new Set<string>() : await source.referenced(category, asked);
|
||||
}),
|
||||
);
|
||||
const referenced = new Set<string>();
|
||||
for (const answer of answers) for (const key of answer) referenced.add(key.toLowerCase());
|
||||
return referenced;
|
||||
}
|
||||
|
||||
private async deleteIfPresent(category: ServedCategory, key: string): Promise<boolean> {
|
||||
try {
|
||||
if ((await this.storage.stat(category, key)) === null) return false;
|
||||
await this.storage.delete(category, key);
|
||||
logDebug(`[storage] released an unreferenced '${category}' object`);
|
||||
return true;
|
||||
} catch (err) {
|
||||
logWarn(`[storage] could not release a '${category}' object, the nightly pass will: ${messageOf(err)}`);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function messageOf(err: unknown): string {
|
||||
return err instanceof Error ? err.message : String(err);
|
||||
}
|
||||
@@ -13,6 +13,7 @@ import { StorageReclaimController } from './storage-reclaim.controller';
|
||||
import { StorageReclaimJob } from './storage-reclaim.job';
|
||||
import { StorageReclaimService } from './storage-reclaim.service';
|
||||
import { StorageRegistryService } from './storage-registry.service';
|
||||
import { StorageReleaseService } from './storage-release.service';
|
||||
import { StorageStatsService } from './storage-stats.service';
|
||||
import { StorageUsageScanJob } from './storage-usage-scan.job';
|
||||
import { StorageService } from './storage.service';
|
||||
@@ -37,8 +38,11 @@ import { Module } from '@nestjs/common';
|
||||
* and follows database reopens (DatabaseLifecycleModule); the domains whose
|
||||
* rows name stored objects register their reference sources with the exported
|
||||
* StorageReclaimRegistryService, so storage never imports them.
|
||||
* StorageJobsService is exported for the backup restore, which marks itself
|
||||
* running there and waits for a reclaim pass in flight to let go.
|
||||
* StorageJobsService is exported for the backups: a restore marks itself
|
||||
* running there and waits for a reclaim pass in flight to let go, a backup
|
||||
* marks itself so the pass deletes nothing it still reads.
|
||||
* StorageReleaseService is exported for the owners, which hand it the values a
|
||||
* delete or a replace left unnamed right after their write.
|
||||
*/
|
||||
@Module({
|
||||
imports: [
|
||||
@@ -60,7 +64,14 @@ import { Module } from '@nestjs/common';
|
||||
StorageReclaimRegistryService,
|
||||
StorageReclaimService,
|
||||
StorageReclaimJob,
|
||||
StorageReleaseService,
|
||||
],
|
||||
exports: [
|
||||
StorageService,
|
||||
StorageEventsService,
|
||||
StorageJobsService,
|
||||
StorageReclaimRegistryService,
|
||||
StorageReleaseService,
|
||||
],
|
||||
exports: [StorageService, StorageEventsService, StorageJobsService, StorageReclaimRegistryService],
|
||||
})
|
||||
export class StorageModule {}
|
||||
|
||||
@@ -3,6 +3,7 @@ import { DomainError } from '../common/domain-error';
|
||||
import { restTripWriter, type TripWriter } from '../common/trip-writer';
|
||||
import { PermissionsService } from '../permissions/permissions.service';
|
||||
import { RealtimeService } from '../realtime/realtime.service';
|
||||
import { StorageReleaseService } from '../storage/storage-release.service';
|
||||
import { TripsService, type DeleteTripInfo } from './trips.service';
|
||||
import { Injectable } from '@nestjs/common';
|
||||
|
||||
@@ -36,6 +37,7 @@ export class TripWritesService {
|
||||
private readonly trips: TripsService,
|
||||
private readonly permissions: PermissionsService,
|
||||
private readonly realtime: RealtimeService,
|
||||
private readonly release: StorageReleaseService,
|
||||
) {}
|
||||
|
||||
/** REST's writer for a trip: the room minus the tab that sent the request. */
|
||||
@@ -62,10 +64,17 @@ export class TripWritesService {
|
||||
return newTripId;
|
||||
}
|
||||
|
||||
/** Deletes a trip and tells everyone in its room, once the delete is committed. */
|
||||
/**
|
||||
* Deletes a trip and tells everyone in its room, once the delete is
|
||||
* committed. Its cover goes with it unless another row (a trip copy, a
|
||||
* journey) still names it; the objects its places and files named are the
|
||||
* nightly reclaim pass's, since their rows belong to other domains.
|
||||
*/
|
||||
async remove(tripId: string | number, writer: TripWriter): Promise<DeleteTripInfo> {
|
||||
const cover = ((await this.trips.getRaw(tripId)) as { cover_image?: string | null } | undefined)?.cover_image;
|
||||
const info = await this.trips.remove(tripId, writer.userId, writer.role);
|
||||
writer.events.emit('trip:deleted', { id: info.tripId });
|
||||
await this.release.releaseValues([cover]);
|
||||
return info;
|
||||
}
|
||||
|
||||
|
||||
@@ -8,6 +8,7 @@ import { JwtAuthGuard } from '../auth-core/jwt-auth.guard';
|
||||
import { CalendarService } from '../calendar/calendar.service';
|
||||
import { contentDisposition } from '../common/content-disposition';
|
||||
import { isDemoWriteBlocked, DEMO_WRITE_ERROR } from '../common/demo-write';
|
||||
import { StorageReleaseService } from '../storage/storage-release.service';
|
||||
import { StorageService } from '../storage/storage.service';
|
||||
import { TripReadModelService } from '../trip-read-model/trip-read-model.service';
|
||||
import { UnsplashService } from '../unsplash/unsplash.service';
|
||||
@@ -84,6 +85,7 @@ export class TripsController {
|
||||
private readonly readModel: TripReadModelService,
|
||||
private readonly storage: StorageService,
|
||||
private readonly tripWrites: TripWritesService,
|
||||
private readonly release: StorageReleaseService,
|
||||
) {}
|
||||
|
||||
@Get()
|
||||
@@ -257,11 +259,11 @@ export class TripsController {
|
||||
}
|
||||
// Commit the spooled upload to its final storage location (atomic
|
||||
// same-volume rename) before anything references the final path.
|
||||
// The replaced cover stays: a trip copy or a journey may show the same
|
||||
// object, and the storage reclaim job removes it once nothing names it.
|
||||
await this.storage.put('covers', file.filename, { tmpPath: file.path });
|
||||
const coverUrl = `/uploads/covers/${file.filename}`;
|
||||
await this.trips.updateCoverImage(id, coverUrl);
|
||||
// The replaced cover goes unless a trip copy or a journey still shows it.
|
||||
await this.release.releaseValues([trip.cover_image]);
|
||||
return { cover_image: coverUrl };
|
||||
}
|
||||
|
||||
|
||||
@@ -43,7 +43,7 @@ import { BudgetService, type CurrencyRebase } from '../budget/budget.service';
|
||||
import { ReservationsService } from '../reservations/reservations.service';
|
||||
import { VacayService } from '../vacay/vacay.service';
|
||||
import { UnsplashService } from '../unsplash/unsplash.service';
|
||||
import { StorageService } from '../storage/storage.service';
|
||||
import { StorageReleaseService } from '../storage/storage-release.service';
|
||||
import { SettingsService } from '../settings/settings.service';
|
||||
import { escapeLikePattern } from '../places/places.helpers';
|
||||
import { NotFoundError, ValidationError } from '../common/domain-errors';
|
||||
@@ -154,7 +154,7 @@ export class TripsService {
|
||||
private readonly vacay: VacayService,
|
||||
private readonly realtime: RealtimeService,
|
||||
private readonly unsplash: UnsplashService,
|
||||
private readonly storage: StorageService,
|
||||
private readonly release: StorageReleaseService, // the cover a change replaced, released after the commit
|
||||
private readonly uow: UnitOfWork,
|
||||
// Plan 3c Task 0b (task-0a-review-security.md F-A1): `canAccessTrip`/
|
||||
// `isOwner` below resolve `TripsRepository` directly through this,
|
||||
@@ -537,6 +537,7 @@ export class TripsService {
|
||||
}
|
||||
});
|
||||
if (vacayId !== undefined) await this.vacay.notifyPlanUsers(vacayId, undefined);
|
||||
if (cover_image !== undefined) await this.release.releaseValues([trip.cover_image]); // kept while any row names it
|
||||
|
||||
const changes: Record<string, unknown> = {};
|
||||
if (title && title !== trip.title) changes.title = title;
|
||||
|
||||
Reference in New Issue
Block a user