mirror of
https://github.com/mauriceboe/TREK.git
synced 2026-11-27 07:07:31 +00:00
refactor(memories): trek photo cache internals through storage
This commit is contained in:
@@ -19,15 +19,19 @@ export class TrekPhotoCacheJob implements OnApplicationBootstrap {
|
||||
onApplicationBootstrap(): void {
|
||||
if (!this.registrar.isEnabled()) return;
|
||||
// Run once immediately on startup to evict any entries left over from a previous run
|
||||
try {
|
||||
this.cache.sweepExpired();
|
||||
} catch { /* cache dir may not exist yet — harmless */ }
|
||||
this.registrar.register('trek-photo-cache', '0 */2 * * *', () => this.tick(), { timezone: 'none' });
|
||||
void (async () => {
|
||||
try {
|
||||
await this.cache.sweepExpired();
|
||||
} catch { /* cache dir may not exist yet — harmless */ }
|
||||
})();
|
||||
this.registrar.register('trek-photo-cache', '0 */2 * * *', () => {
|
||||
void this.tick();
|
||||
}, { timezone: 'none' });
|
||||
}
|
||||
|
||||
tick(): void {
|
||||
async tick(): Promise<void> {
|
||||
try {
|
||||
this.cache.sweepExpired();
|
||||
await this.cache.sweepExpired();
|
||||
} catch (err: unknown) {
|
||||
logError(`Trek photo cache cleanup: ${err instanceof Error ? err.message : err}`);
|
||||
}
|
||||
|
||||
@@ -1,15 +1,11 @@
|
||||
import path from 'node:path';
|
||||
import fs from 'node:fs';
|
||||
import fsPromises from 'node:fs/promises';
|
||||
import crypto from 'node:crypto';
|
||||
import { Readable } from 'node:stream';
|
||||
import { Injectable } from '@nestjs/common';
|
||||
import { Response } from 'express';
|
||||
import { DatabaseService } from '../database/database.service';
|
||||
import { StorageService } from '../storage/storage.service';
|
||||
import { StorageNotFoundError } from '../storage/storage.types';
|
||||
import { UPLOADS_ROOT } from './uploads-root';
|
||||
|
||||
const TREK_PHOTO_DIR = path.join(UPLOADS_ROOT, 'photos/trek');
|
||||
export const CACHE_TTL = 60 * 60 * 1000; // 1 hour
|
||||
|
||||
/**
|
||||
@@ -25,17 +21,12 @@ export const CACHE_TTL = 60 * 60 * 1000; // 1 hour
|
||||
*/
|
||||
const inFlight = new Map<string, Promise<Buffer | null>>();
|
||||
|
||||
function ensureDir(): void {
|
||||
if (!fs.existsSync(TREK_PHOTO_DIR)) {
|
||||
fs.mkdirSync(TREK_PHOTO_DIR, { recursive: true });
|
||||
}
|
||||
/** Storage name (category 'photos-trek') for a cache key. */
|
||||
function objectName(key: string): string {
|
||||
return `${key}.bin`;
|
||||
}
|
||||
|
||||
function cachedFilePath(key: string): string {
|
||||
return path.join(TREK_PHOTO_DIR, `${key}.bin`);
|
||||
}
|
||||
|
||||
/** Disk + metadata cache for provider thumbnails and originals. */
|
||||
/** Storage + metadata cache for provider thumbnails and originals. */
|
||||
@Injectable()
|
||||
export class TrekPhotoCacheService {
|
||||
constructor(
|
||||
@@ -47,9 +38,7 @@ export class TrekPhotoCacheService {
|
||||
return crypto.createHash('sha1').update(`${provider}:${assetId}:${kind}:${ownerId}`).digest('hex');
|
||||
}
|
||||
|
||||
|
||||
|
||||
getFresh(key: string): { filePath: string; contentType: string } | null {
|
||||
async getFresh(key: string): Promise<{ contentType: string } | null> {
|
||||
const row = this.db.get<{ content_type: string; fetched_at: number }>(
|
||||
'SELECT content_type, fetched_at FROM trek_photo_cache_meta WHERE cache_key = ?', key,
|
||||
);
|
||||
@@ -61,22 +50,16 @@ export class TrekPhotoCacheService {
|
||||
return null;
|
||||
}
|
||||
|
||||
const fp = cachedFilePath(key);
|
||||
if (!fs.existsSync(fp)) {
|
||||
if (!(await this.storage.exists('photos-trek', objectName(key)))) {
|
||||
this.db.run('DELETE FROM trek_photo_cache_meta WHERE cache_key = ?', key);
|
||||
return null;
|
||||
}
|
||||
|
||||
return { filePath: fp, contentType: row.content_type };
|
||||
return { contentType: row.content_type };
|
||||
}
|
||||
|
||||
async put(key: string, bytes: Buffer, contentType: string): Promise<void> {
|
||||
ensureDir();
|
||||
const fp = cachedFilePath(key);
|
||||
const tmp = fp + '.tmp';
|
||||
|
||||
await fsPromises.writeFile(tmp, bytes);
|
||||
await fsPromises.rename(tmp, fp);
|
||||
await this.storage.put('photos-trek', objectName(key), Readable.from(bytes));
|
||||
|
||||
this.db.run(
|
||||
'INSERT OR REPLACE INTO trek_photo_cache_meta (cache_key, content_type, fetched_at) VALUES (?, ?, ?)',
|
||||
@@ -85,7 +68,7 @@ export class TrekPhotoCacheService {
|
||||
}
|
||||
|
||||
async serveFresh(res: Response, key: string): Promise<boolean> {
|
||||
const entry = this.getFresh(key);
|
||||
const entry = await this.getFresh(key);
|
||||
if (!entry) return false;
|
||||
|
||||
res.set('Content-Type', entry.contentType);
|
||||
@@ -93,7 +76,7 @@ export class TrekPhotoCacheService {
|
||||
try {
|
||||
// send() keeps a pre-set Content-Type, so entry.contentType survives the
|
||||
// .bin extension.
|
||||
await this.storage.sendToResponse('photos-trek', `${key}.bin`, res);
|
||||
await this.storage.sendToResponse('photos-trek', objectName(key), res);
|
||||
} catch (err) {
|
||||
// getFresh→send delete race: fall back like a cache miss.
|
||||
if (err instanceof StorageNotFoundError && !res.headersSent) return false;
|
||||
@@ -111,7 +94,7 @@ export class TrekPhotoCacheService {
|
||||
promise.finally(() => inFlight.delete(key));
|
||||
}
|
||||
|
||||
sweepExpired(): void {
|
||||
async sweepExpired(): Promise<void> {
|
||||
const cutoff = Date.now() - CACHE_TTL * 2;
|
||||
const stale = this.db.all<{ cache_key: string }>(
|
||||
'SELECT cache_key FROM trek_photo_cache_meta WHERE fetched_at < ?', cutoff,
|
||||
@@ -119,8 +102,7 @@ export class TrekPhotoCacheService {
|
||||
|
||||
for (const row of stale) {
|
||||
this.db.run('DELETE FROM trek_photo_cache_meta WHERE cache_key = ?', row.cache_key);
|
||||
const fp = cachedFilePath(row.cache_key);
|
||||
if (fs.existsSync(fp)) fs.unlinkSync(fp);
|
||||
await this.storage.delete('photos-trek', objectName(row.cache_key));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user