refactor(cache): extract clearCache function

This commit is contained in:
WebStreamr 2026-01-22 15:16:03 +00:00
parent e5197fdb8b
commit 12ea135feb
No known key found for this signature in database
4 changed files with 20 additions and 24 deletions

View file

@ -1,4 +1,3 @@
import { promises as fs } from 'fs';
import { randomUUID } from 'node:crypto';
import axios from 'axios';
import { setupCache } from 'axios-cache-interceptor';
@ -6,7 +5,6 @@ import axiosRetry from 'axios-retry';
import express, { NextFunction, Request, Response } from 'express';
// eslint-disable-next-line import/no-named-as-default
import rateLimit from 'express-rate-limit';
import { glob } from 'glob';
import winston from 'winston';
import { ConfigureController, ExtractController, ManifestController, StreamController } from './controller';
import { BlockedError, logErrorAndReturnNiceString } from './error';
@ -15,7 +13,7 @@ import { createSources, Source } from './source';
import { HomeCine } from './source/HomeCine';
import { MeineCloud } from './source/MeineCloud';
import { MostraGuarda } from './source/MostraGuarda';
import { contextFromRequestAndResponse, envGet, envIsProd, Fetcher, getCacheDir, StreamResolver } from './utils';
import { clearCache, contextFromRequestAndResponse, envGet, envIsProd, Fetcher, StreamResolver } from './utils';
if (envIsProd()) {
console.log = console.warn = console.error = console.info = console.debug = () => { /* disable in favor of logger */ };
@ -58,10 +56,7 @@ if (envIsProd()) {
if (envGet('CACHE_FILES_DELETE_ON_START')) {
(async function () {
for (const file of await glob(`${getCacheDir()}/webstreamr*`)) {
logger.info(`Delete cache file ${file}`);
await fs.rm(file);
}
await clearCache(logger);
})();
}

View file

@ -1,11 +1,16 @@
/* istanbul ignore file */
import fs from 'node:fs';
import * as os from 'node:os';
// eslint-disable-next-line import/no-named-as-default
import KeyvSqlite from '@keyv/sqlite';
import { KeyvCacheableMemory } from 'cacheable';
import { glob } from 'glob';
import { KeyvStoreAdapter } from 'keyv';
import * as sqlite3 from 'sqlite3';
import { envIsTest, getCacheDir } from './env';
import winston from 'winston';
import { envGet, envIsTest } from './env';
const getCacheDir = (): string => envGet('CACHE_DIR') ?? os.tmpdir();
const scheduleKeyvSqliteCleanup = (keyvSqlite: KeyvSqlite): void => {
const filename = keyvSqlite.opts.db;
@ -24,13 +29,22 @@ const scheduleKeyvSqliteCleanup = (keyvSqlite: KeyvSqlite): void => {
};
export const createKeyvSqlite = (name: string): KeyvStoreAdapter => {
if (envIsTest()) {
const cacheDir = getCacheDir();
if (envIsTest() || !cacheDir) {
return new KeyvCacheableMemory();
}
const keyvSqlite = new KeyvSqlite(`sqlite://${getCacheDir()}/webstreamr-${name}.sqlite`);
const keyvSqlite = new KeyvSqlite(`sqlite://${cacheDir}/webstreamr-${name}.sqlite`);
scheduleKeyvSqliteCleanup(keyvSqlite);
return keyvSqlite;
};
export const clearCache = async (logger: winston.Logger): Promise<void> => {
for (const file of await glob(`${getCacheDir()}/webstreamr*`)) {
logger.info(`Delete cache file ${file}`);
fs.rmSync(file);
}
};

View file

@ -1,6 +1,5 @@
import * as os from 'node:os';
import { Request } from 'express';
import { envGet, envGetAppId, envGetAppName, envGetRequired, envIsProd, getCacheDir, isElfHostedInstance } from './env';
import { envGet, envGetAppId, envGetAppName, envGetRequired, envIsProd, isElfHostedInstance } from './env';
describe('env', () => {
test('envGet', () => {
@ -44,13 +43,4 @@ describe('env', () => {
expect(isElfHostedInstance({ host: 'someuser.elfhosted.com' } as Request)).toBeTruthy();
expect(isElfHostedInstance({ host: 'webstreamr.hayd.uk' } as Request)).toBeFalsy();
});
test('getCacheDir', () => {
const previousCacheDir = process.env['CACHE_DIR'];
delete process.env['CACHE_DIR'];
expect(getCacheDir()).toBe(os.tmpdir());
process.env['CACHE_DIR'] = previousCacheDir;
expect(getCacheDir()).toBe('/dev/null');
});
});

View file

@ -1,4 +1,3 @@
import * as os from 'node:os';
import { Request } from 'express';
export const envGet = (name: string): string | undefined => process.env[name];
@ -21,5 +20,3 @@ export const envIsProd = (): boolean => process.env['NODE_ENV'] === 'production'
export const envIsTest = (): boolean => process.env['NODE_ENV'] === 'test';
export const isElfHostedInstance = (req: Request): boolean => req.host.endsWith('elfhosted.com');
export const getCacheDir = (): string => envGet('CACHE_DIR') ?? os.tmpdir();