forked from mtusi2026/mtusi2026lab5
99 lines
2.0 KiB
TypeScript
99 lines
2.0 KiB
TypeScript
import { Injectable, Logger, OnModuleDestroy } from '@nestjs/common';
|
|
import { readFileSync } from 'fs';
|
|
import Redis from 'ioredis';
|
|
|
|
@Injectable()
|
|
export class CacheService implements OnModuleDestroy {
|
|
private readonly logger = new Logger('CacheService');
|
|
private readonly client: Redis | null;
|
|
private trusted = false;
|
|
|
|
constructor() {
|
|
const url = readCacheUrl();
|
|
this.client = url
|
|
? new Redis(url, {
|
|
enableOfflineQueue: false,
|
|
maxRetriesPerRequest: 0,
|
|
connectTimeout: 1000,
|
|
commandTimeout: 200,
|
|
})
|
|
: null;
|
|
this.client?.on('error', (error) =>
|
|
this.logger.warn(`redis unavailable: ${error.message}`),
|
|
);
|
|
this.client?.on('close', () => {
|
|
this.trusted = false;
|
|
});
|
|
this.client?.on('ready', () => {
|
|
this.client!.flushdb().then(
|
|
() => {
|
|
this.trusted = true;
|
|
},
|
|
() => this.distrust(),
|
|
);
|
|
});
|
|
}
|
|
|
|
async get(key: string): Promise<string | null> {
|
|
if (!this.client || !this.trusted) {
|
|
return null;
|
|
}
|
|
try {
|
|
return await this.client.get(key);
|
|
} catch {
|
|
this.distrust();
|
|
return null;
|
|
}
|
|
}
|
|
|
|
async set(
|
|
key: string,
|
|
value: string,
|
|
ttlMs: number,
|
|
onlyIfAbsent = false,
|
|
): Promise<void> {
|
|
if (!this.client || !this.trusted) {
|
|
return;
|
|
}
|
|
try {
|
|
if (onlyIfAbsent) {
|
|
await this.client.set(key, value, 'PX', ttlMs, 'NX');
|
|
} else {
|
|
await this.client.set(key, value, 'PX', ttlMs);
|
|
}
|
|
} catch {
|
|
this.distrust();
|
|
}
|
|
}
|
|
|
|
async setStrict(key: string, value: string, ttlMs: number): Promise<boolean> {
|
|
if (!this.client) {
|
|
return true;
|
|
}
|
|
if (!this.trusted) {
|
|
return false;
|
|
}
|
|
try {
|
|
await this.client.set(key, value, 'PX', ttlMs);
|
|
return true;
|
|
} catch {
|
|
this.distrust();
|
|
return false;
|
|
}
|
|
}
|
|
|
|
onModuleDestroy(): void {
|
|
this.client?.disconnect();
|
|
}
|
|
|
|
private distrust(): void {
|
|
this.trusted = false;
|
|
this.client?.disconnect(true);
|
|
}
|
|
}
|
|
|
|
function readCacheUrl(): string | undefined {
|
|
const file = process.env.CACHE_URL_FILE;
|
|
return file ? readFileSync(file, 'utf8').trim() : process.env.CACHE_URL;
|
|
}
|