Skip to content

armgit / TREK

Public Imported from GitHub
0

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

fix(storage): re-check a batch right before its delete, and drop reads nothing calls

Mauriceb31666d1c969
diff --git a/server/src/db/repositories/CollectionPlaces.repository.ts b/server/src/db/repositories/CollectionPlaces.repository.ts
index 075e7a49f..78f7a4503 100644
--- a/server/src/db/repositories/CollectionPlaces.repository.ts
+++ b/server/src/db/repositories/CollectionPlaces.repository.ts
@@ -138,12 +138,6 @@ 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
@@ -454,23 +448,6 @@ export class CollectionPlacesRepository extends TrekRepository<CollectionPlaces>
// cache.service.ts` SV-PP6, `place-image.ts` SV-PLACEIMG-2) — additive.
// ---------------------------------------------------------------------
- /**
- * SV-PI2 (`places.service.ts::reclaimPlaceImage`) / SV-PLACEIMG-2
- * (`CollectionsService`'s own private `reclaimPlaceImage`, replacing
- * `place-image.ts`'s free function) — `SELECT 1 FROM collection_places
- * WHERE image_url = ? LIMIT 1`. Trip-agnostic, same shape as
- * `PlacesRepository.existsByImageUrl` for its own table.
- */
- async existsByImageUrl(imageUrl: string): Promise<boolean> {
- const row = await this.db_()
- .selectFrom('collection_places')
- .select('id')
- .where('image_url', '=', imageUrl)
- .limit(1)
- .executeTakeFirst();
- return !!row;
- }
-
/**
* SV-PP6 (`place-photo-cache.service.ts::isReferenced`) — `SELECT 1 FROM
* collection_places WHERE google_place_id = ? OR image_url = ? LIMIT 1`,
diff --git a/server/src/db/repositories/Collections.repository.ts b/server/src/db/repositories/Collections.repository.ts
index 78c498a1e..3503a272f 100644
--- a/server/src/db/repositories/Collections.repository.ts
+++ b/server/src/db/repositories/Collections.repository.ts
@@ -230,16 +230,6 @@ 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()
diff --git a/server/src/nest/storage/storage-reclaim.service.ts b/server/src/nest/storage/storage-reclaim.service.ts
index 7911757cc..9d9b0205d 100644
--- a/server/src/nest/storage/storage-reclaim.service.ts
+++ b/server/src/nest/storage/storage-reclaim.service.ts
@@ -322,8 +322,8 @@ export class StorageReclaimService implements OnModuleInit {
}
/**
- * @txIndependent one delete per object, each with its own re-check, so a
- * failure leaves the others' work standing.
+ * @txIndependent a batch at a time, each delete standing alone, so a failure
+ * leaves the others' work standing.
*/
private async deleteEligible(
category: ServedCategory,
@@ -333,44 +333,61 @@ export class StorageReclaimService implements OnModuleInit {
): Promise<Candidate[]> {
return chunk(eligible, DELETE_BATCH).reduce<Promise<Candidate[]>>(async (previous, batch) => {
const done = await previous;
- const results = await Promise.all(batch.map((candidate) => this.deleteOne(category, candidate, sources, ctx)));
- done.push(...batch.filter((_candidate, i) => results[i]));
+ done.push(...(await this.deleteBatch(category, batch, sources, ctx)));
return done;
}, Promise.resolve([]));
}
/**
- * Asks every source about this one key again, checks the object is still the
- * old one the pass judged, then deletes it and its mark. False keeps it.
+ * 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.
*
- * @txIndependent the object goes first and the mark after, so a mark never
- * outlives a delete that failed.
+ * @txIndependent every object goes on its own, see deleteOne.
*/
- private async deleteOne(
+ private async deleteBatch(
category: ServedCategory,
- candidate: Candidate,
+ batch: readonly Candidate[],
sources: readonly StorageReferenceSource[],
ctx: PassContext,
- ): Promise<boolean> {
+ ): Promise<Candidate[]> {
+ const stats = await Promise.all(batch.map((candidate) => this.storage.stat(category, candidate.key)));
+ // 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;
+ });
+ 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 [];
let referenced: Set<string>;
try {
- referenced = await this.referencedIn(category, [candidate.key], sources);
+ referenced = await this.referencedIn(category, keysOf(due), sources);
} catch (err) {
- logError(`[storage] reclaim kept a '${category}' object, its re-check failed: ${messageOf(err)}`);
- return false;
- }
- if (referenced.size > 0) {
- await this.marks.deleteKeys(category, [candidate.key]);
- return false;
- }
- const stat = await this.storage.stat(category, candidate.key);
- if (stat === null || !(stat.mtimeMs > 0) || ctx.now - stat.mtimeMs < RECLAIM_GRACE_MS) {
- // Gone, or written again since it was judged: the next pass looks at it afresh.
- await this.marks.deleteKeys(category, [candidate.key]);
- return false;
+ logError(
+ `[storage] reclaim kept ${due.length} '${category}' object(s), their re-check failed: ${messageOf(err)}`,
+ );
+ return [];
}
- if (this.storage.keepsOnDelete(category, candidate.key)) 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) {
@@ -416,6 +433,10 @@ 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[] {
+ return candidates.map((candidate) => candidate.key);
+}
+
function chunk<T>(items: readonly T[], size: number): T[][] {
return Array.from({ length: Math.ceil(items.length / size) }, (_page, i) => items.slice(i * size, (i + 1) * size));
}
diff --git a/server/tests/unit/nest/storage/storage-reclaim.service.test.ts b/server/tests/unit/nest/storage/storage-reclaim.service.test.ts
index ee19f5f5f..09c3a72aa 100644
--- a/server/tests/unit/nest/storage/storage-reclaim.service.test.ts
+++ b/server/tests/unit/nest/storage/storage-reclaim.service.test.ts
@@ -4,7 +4,7 @@
* fake reference sources standing in for the owner domains. The pass marks
* first, deletes a week later only with the switch on and only after asking
* every source about the single key again; every brake skips a category and
- * starts its marks over. RCLS-001 to RCLS-021.
+ * starts its marks over. RCLS-001 to RCLS-024.
*/
import { AppSettings } from '../../../../src/db/entities/AppSettings.entity';
import { StorageReclaimMarks } from '../../../../src/db/entities/StorageReclaimMarks.entity';
@@ -428,11 +428,14 @@ describe('StorageReclaimService: the delete itself', () => {
it('RCLS-017: an object gone or written again since it was judged is left and its mark dropped', async () => {
await markedWeekOld(['gone.jpg', 'fresh.jpg'], 8);
- onAsk = (_category, keys) => {
- if (keys.length !== 1) return;
- if (keys[0] === 'gone.jpg') fs.rmSync(objectPath('covers', 'gone.jpg'), { force: true });
- if (keys[0] === 'fresh.jpg') fs.utimesSync(objectPath('covers', 'fresh.jpg'), WEEK_LATER, WEEK_LATER);
- };
+ // Changed between the listing and the delete: the batch looks at each object again first.
+ const listed = storage.list.bind(storage);
+ vi.spyOn(storage, 'list').mockImplementation(async function* (category, prefix) {
+ yield* listed(category, prefix);
+ if (category !== 'covers') return;
+ fs.rmSync(objectPath('covers', 'gone.jpg'), { force: true });
+ fs.utimesSync(objectPath('covers', 'fresh.jpg'), WEEK_LATER, WEEK_LATER);
+ });
const report = await reclaim.run({ now: WEEK_LATER });
expect(report.categories.covers.eligible.objects).toBe(2);
expect(report.categories.covers.deleted.objects).toBe(0);
@@ -440,6 +443,20 @@ describe('StorageReclaimService: the delete itself', () => {
expect(await marksOf('covers')).toEqual([]);
});
+ it('RCLS-024: the re-check before the delete asks about the whole batch at once, not once per object', async () => {
+ await markedWeekOld(['a.jpg', 'b.jpg', 'c.jpg'], 12);
+ const asked: string[][] = [];
+ onAsk = (category, keys) => {
+ if (category === 'covers') asked.push([...keys].sort());
+ };
+ const report = await reclaim.run({ now: WEEK_LATER });
+ expect(report.categories.covers.deleted.objects).toBe(3);
+ // Per source: the listing's question, then one re-check for the three.
+ const rechecks = asked.filter((keys) => keys.length === 3 && keys.every((key) => !key.startsWith('kept-')));
+ expect(rechecks.length).toBe(STORAGE_REFERENCE_SOURCE_IDS.filter((id) => id !== 'auth' && id !== 'files').length);
+ expect(asked.some((keys) => keys.length === 1)).toBe(false);
+ });
+
it('RCLS-018: a delete that fails keeps the mark for the next pass', async () => {
await markedWeekOld(['orphan.jpg']);
vi.spyOn(storage, 'delete').mockRejectedValue(new Error('permission denied'));