Add shared sessions, cached message history and transactional idempotency backed by PostgreSQL. Return readiness 503 during draining and finish in-flight requests before closing dependencies.
150 lines
4.0 KiB
TypeScript
150 lines
4.0 KiB
TypeScript
import {
|
|
Injectable,
|
|
Logger,
|
|
type OnModuleDestroy,
|
|
type OnModuleInit,
|
|
} from '@nestjs/common';
|
|
import { createHash, randomUUID } from 'node:crypto';
|
|
import Redis from 'ioredis';
|
|
|
|
export const CACHE_TTL = { entity: 300, page: 30 } as const;
|
|
const generationTtl = 600;
|
|
const storeIfCurrent = `
|
|
if redis.call('GET', KEYS[1]) == ARGV[1] then
|
|
return redis.call('SET', KEYS[2], ARGV[2], 'EX', ARGV[3])
|
|
end
|
|
return false`;
|
|
|
|
@Injectable()
|
|
export class CacheService implements OnModuleInit, OnModuleDestroy {
|
|
private readonly logger = new Logger(CacheService.name);
|
|
private readonly redis?: Redis;
|
|
private readonly prefix = process.env.CACHE_PREFIX ?? 'messenger:cache:v1';
|
|
private warned = false;
|
|
|
|
constructor() {
|
|
if (process.env.CACHE_URL) {
|
|
this.redis = new Redis(process.env.CACHE_URL, {
|
|
lazyConnect: true,
|
|
connectTimeout: 1000,
|
|
commandTimeout: 300,
|
|
maxRetriesPerRequest: 0,
|
|
enableOfflineQueue: false,
|
|
autoResendUnfulfilledCommands: false,
|
|
retryStrategy: () => 1000,
|
|
});
|
|
this.redis.on('error', () => this.unavailable());
|
|
this.redis.on('ready', () => {
|
|
this.warned = false;
|
|
});
|
|
}
|
|
}
|
|
|
|
async onModuleInit(): Promise<void> {
|
|
try {
|
|
await this.redis?.connect();
|
|
} catch {
|
|
this.unavailable();
|
|
}
|
|
}
|
|
|
|
onModuleDestroy(): void {
|
|
this.redis?.disconnect();
|
|
}
|
|
|
|
async remember<T>(
|
|
namespace: string,
|
|
parameters: unknown,
|
|
ttl: number,
|
|
load: () => Promise<T>,
|
|
epoch?: string,
|
|
): Promise<T> {
|
|
if (!this.redis || this.redis.status !== 'ready') return load();
|
|
if (epoch !== undefined) {
|
|
const digest = createHash('sha256')
|
|
.update(JSON.stringify(parameters))
|
|
.digest('hex');
|
|
const key = `${this.prefix}:${namespace}:epoch:${epoch}:${digest}`;
|
|
try {
|
|
const value = await this.redis.get(key);
|
|
if (value !== null) return JSON.parse(value) as T;
|
|
} catch {
|
|
this.unavailable();
|
|
}
|
|
const result = await load();
|
|
const serialized = JSON.stringify(result);
|
|
if (serialized !== undefined && this.redis.status === 'ready') {
|
|
try {
|
|
await this.redis.set(key, serialized, 'EX', ttl);
|
|
} catch {
|
|
this.unavailable();
|
|
}
|
|
}
|
|
return result;
|
|
}
|
|
const versionKey = `${this.prefix}:${namespace}:generation`;
|
|
let version: string | null = null;
|
|
let dataKey = '';
|
|
try {
|
|
await this.redis.set(versionKey, randomUUID(), 'EX', generationTtl, 'NX');
|
|
version = await this.redis.get(versionKey);
|
|
if (version) {
|
|
const digest = createHash('sha256')
|
|
.update(JSON.stringify(parameters))
|
|
.digest('hex');
|
|
dataKey = `${this.prefix}:${namespace}:${version}:${digest}`;
|
|
const value = await this.redis.get(dataKey);
|
|
if (value !== null) return JSON.parse(value) as T;
|
|
}
|
|
} catch {
|
|
this.unavailable();
|
|
}
|
|
|
|
const result = await load();
|
|
const serialized = JSON.stringify(result);
|
|
if (version && serialized !== undefined && this.redis.status === 'ready') {
|
|
try {
|
|
await this.redis.eval(
|
|
storeIfCurrent,
|
|
2,
|
|
versionKey,
|
|
dataKey,
|
|
version,
|
|
serialized,
|
|
ttl,
|
|
);
|
|
} catch {
|
|
this.unavailable();
|
|
}
|
|
}
|
|
return result;
|
|
}
|
|
|
|
async invalidate(...namespaces: string[]): Promise<void> {
|
|
if (!this.redis || this.redis.status !== 'ready' || namespaces.length === 0)
|
|
return;
|
|
try {
|
|
const transaction = this.redis.multi();
|
|
for (const namespace of new Set(namespaces)) {
|
|
transaction.set(
|
|
`${this.prefix}:${namespace}:generation`,
|
|
randomUUID(),
|
|
'EX',
|
|
generationTtl,
|
|
);
|
|
}
|
|
const results = await transaction.exec();
|
|
if (results?.some(([error]) => error !== null)) this.unavailable();
|
|
} catch {
|
|
this.unavailable();
|
|
}
|
|
}
|
|
|
|
private unavailable(): void {
|
|
if (!this.warned) {
|
|
this.logger.warn('Redis cache unavailable');
|
|
this.warned = true;
|
|
}
|
|
}
|
|
}
|