import Inject, { RegisterScoped } from "@entity-access/entity-access/dist/di/di.js"; import TempFileService from "../../storage/TempFileService.js"; import BaseStorage from "../../storage/BaseStorage.js"; import { globalServices } from "../../../globalServices.js"; import SocialMailContext from "../../model/SocialMailContext.js"; import CryptoService from "../CryptoService.js"; import DateTime from "@entity-access/entity-access/dist/types/DateTime.js"; import TimeSpan from "@entity-access/entity-access/dist/types/TimeSpan.js"; import { parse } from "path"; import { LocalFile } from "@entity-access/server-pages/dist/core/LocalFile.js"; import CachedItem from "../../model/entities/CachedItem.js"; import EntityAccessError from "@entity-access/entity-access/dist/common/EntityAccessError.js"; import { appendFile } from "fs/promises"; import DbLockService from "../db-lock/DbLockService.js"; import RateLimiterService from "../rate-limiter/RateLimiterService.js"; import ReadOnlySocialMailContext from "../../model/ReadOnlySocialMailContext.js"; @RegisterScoped export default class CacheService { @Inject private db: SocialMailContext; @Inject private replica: ReadOnlySocialMailContext; @Inject private storage: BaseStorage; @Inject private cryptoService: CryptoService; @Inject private tempFileService: TempFileService; @Inject private dbLockService: DbLockService; @Inject private rateLimiter: RateLimiterService; public async clear() { const now = DateTime.now; const files = await this.db.cachedItems.where({ now }, (x, p) => x.expiry <= p.now) .limit(10) .toArray(); for (const iterator of files) { const cloudPath = `cache/${iterator.itemID}`; await this.storage.deleteFile(cloudPath); await this.db.cachedItems.statements.delete(iterator); } } public async getItemsOrFail(keys: string[], name: string, contentType: string) { using scope = globalServices.createScope(); const db = scope.resolve(SocialMailContext); const { ext } = parse(name); const file = await this.tempFileService.createTempFile(ext, name, contentType); const tasks = [] as Promise<{ key: string, tmp: LocalFile}>[]; for (const key of keys) { const keyHash = await this.cryptoService.hashBuffer(Buffer.from(key, "utf-8")); const cachedItem = await db.cachedItems.where({ key, keyHash}, (x, p) => x.keyHash === p.keyHash && x.key === p.key) .first(); if (!cachedItem?.ready) { throw new EntityAccessError(`Cache not available for ${key}`); } const { base: fileName } = parse(key); const cloudPath = `cache/${cachedItem.itemID}`; tasks.push(this.tempFileService.downloadCloudFile(cloudPath, fileName).then((tmp) => ({ tmp, key }))); } for (const { tmp } of await Promise.all(tasks)) { await appendFile(file.path, await tmp.readAsBuffer()); } return file; } public async getOrFail(key) { using scope = globalServices.createScope(); const db = scope.resolve(SocialMailContext); const keyHash = await this.cryptoService.hashBuffer(Buffer.from(key, "utf-8")); const cachedItem = await db.cachedItems.where({ key, keyHash}, (x, p) => x.keyHash === p.keyHash && x.key === p.key) .first(); if (!cachedItem?.ready) { throw new EntityAccessError(`Cache not available for ${key}`); } const { base: fileName } = parse(key); const cloudPath = `cache/${cachedItem.itemID}`; return await this.tempFileService.downloadCloudFile(cloudPath, fileName); } public async put(key: string, file: LocalFile, ttl = TimeSpan.fromDays(30)) { using scope = globalServices.createScope(); const db = scope.resolve(SocialMailContext); const expiry = DateTime.now.add(ttl); const keyHash = await this.cryptoService.hashBuffer(Buffer.from(key, "utf-8")); const cachedItem = await db.cachedItems.statements.insert({ keyHash, key, ready: true, expiry }); const cloudPath = `cache/${cachedItem.itemID}`; await this.storage.createFile(cloudPath, file); } public async get(ck: { key: string, ttl: TimeSpan, factory: (c?: CachedItem) => Promise }): Promise { const { key, ttl, factory } = ck; const now = DateTime.now; const keyHash = await this.cryptoService.hashBuffer(Buffer.from(key, "utf-8")); const keys = { key, keyHash }; const { base: fileName } = parse(key); let file: LocalFile; let cloudPath: string; const expiry = now.add(ttl); let cachedItem = await this.replica.cachedItems.statements.select({}, keys); if (cachedItem?.ready) { if(DateTime.from(cachedItem.expiry).msSinceEpoch > Date.now()) { if (cachedItem.slide) { await this.db.cachedItems.statements.update({ expiry, },{ itemID: cachedItem.itemID }); } cloudPath = `cache/${cachedItem.itemID}`; return this.downloadCachedFile(ck, cachedItem, cloudPath, fileName); } } await using _dbLock = await this.dbLockService.lock(`ci-${keyHash}`, DateTime.now.addMinutes(5)); cachedItem = await this.db.cachedItems.statements.select({}, keys); if (cachedItem?.ready) { if(DateTime.from(cachedItem.expiry).msSinceEpoch > Date.now()) { if (cachedItem.slide) { await this.db.cachedItems.statements.update({ expiry, },{ itemID: cachedItem.itemID }); } cloudPath = `cache/${cachedItem.itemID}`; return this.downloadCachedFile(ck, cachedItem, cloudPath, fileName); } cachedItem.expiry = DateTime.now.addDays(30); await this.db.cachedItems.statements.update({ expiry, },{ itemID: cachedItem.itemID }); } await using _rl = await this.rateLimiter.acquireDisposable("0.0.0.0", "file-cache", 10); if (!cachedItem) { cachedItem = await this.db.cachedItems.statements.selectOrInsert( { ... keys, ready: false, slide: true, expiry, } , keys); } cloudPath = `cache/${cachedItem.itemID}`; try { file = await factory(cachedItem); await this.storage.createFile(cloudPath, file); await this.db.cachedItems.statements.update({ expiry: cachedItem.expiry, slide: cachedItem.slide, ready: true }, { itemID: cachedItem.itemID }); } catch (error) { // delete cache... using scope = globalServices.createScope(); const db = scope.resolve(SocialMailContext); await db.cachedItems.statements.delete({ itemID: cachedItem.itemID }); throw new Error(`Failed: ${error.stack ?? error}`); } return await this.tempFileService.downloadCloudFile(cloudPath, fileName); } async downloadCachedFile(ck, c: CachedItem, cloudPath: string, fileName: string) { try { return await this.tempFileService.downloadCloudFile(cloudPath, fileName); } catch (error) { await this.db.cachedItems.statements.delete({ itemID: c.itemID }); return this.get(ck); } } }