fix(core): own cache transports and accept cleanup reviews
This commit is contained in:
parent
bd9332b2f6
commit
b4ac6460ef
24 changed files with 504 additions and 97 deletions
2
libs/core/cache/src/connection-manager.ts
vendored
2
libs/core/cache/src/connection-manager.ts
vendored
|
|
@ -50,6 +50,7 @@ export class RedisConnectionManager {
|
|||
* Create a new Redis connection
|
||||
*/
|
||||
private createConnection(config: RedisConfig): Redis {
|
||||
const retryDelay = config.retryDelay;
|
||||
return new Redis({
|
||||
host: config.host,
|
||||
port: config.port,
|
||||
|
|
@ -60,6 +61,7 @@ export class RedisConnectionManager {
|
|||
connectTimeout: config.connectTimeout ?? REDIS_DEFAULTS.CONNECT_TIMEOUT,
|
||||
commandTimeout: config.commandTimeout ?? REDIS_DEFAULTS.COMMAND_TIMEOUT,
|
||||
lazyConnect: false,
|
||||
...(retryDelay === undefined ? {} : { retryStrategy: () => retryDelay }),
|
||||
...(config.tls && { tls: config.tls }),
|
||||
});
|
||||
}
|
||||
|
|
|
|||
12
libs/core/cache/src/redis-cache.ts
vendored
12
libs/core/cache/src/redis-cache.ts
vendored
|
|
@ -8,6 +8,8 @@ import type { CacheOptions, CacheProvider, CacheStats } from './types';
|
|||
*/
|
||||
export class RedisCache implements CacheProvider {
|
||||
private redis: Redis;
|
||||
private readonly ownsConnection: boolean;
|
||||
private disconnected = false;
|
||||
private logger: NonNullable<CacheOptions['logger']>;
|
||||
private defaultTTL: number;
|
||||
private keyPrefix: string;
|
||||
|
|
@ -15,6 +17,7 @@ export class RedisCache implements CacheProvider {
|
|||
private startTime = Date.now();
|
||||
|
||||
constructor(options: CacheOptions) {
|
||||
this.ownsConnection = options.shared === false;
|
||||
this.defaultTTL = options.ttl ?? CACHE_DEFAULTS.TTL;
|
||||
this.keyPrefix = options.keyPrefix ?? CACHE_DEFAULTS.KEY_PREFIX;
|
||||
this.logger = options.logger || console;
|
||||
|
|
@ -30,6 +33,15 @@ export class RedisCache implements CacheProvider {
|
|||
});
|
||||
}
|
||||
|
||||
/** Only nonshared caches own their socket. Shared callers keep manager ownership. */
|
||||
async disconnect(): Promise<void> {
|
||||
if (this.ownsConnection && !this.disconnected) {
|
||||
this.disconnected = true;
|
||||
// A cache has no flush protocol; disconnect also stops retry handles when Redis is unavailable.
|
||||
this.redis.disconnect();
|
||||
}
|
||||
}
|
||||
|
||||
private getKey(key: string): string {
|
||||
return `${this.keyPrefix}${key}`;
|
||||
}
|
||||
|
|
|
|||
4
libs/core/cache/src/types.ts
vendored
4
libs/core/cache/src/types.ts
vendored
|
|
@ -9,6 +9,8 @@ export interface RedisConfig {
|
|||
keyPrefix?: string;
|
||||
maxRetriesPerRequest?: number;
|
||||
retryDelayOnFailover?: number;
|
||||
/** Fixed reconnect delay in milliseconds when explicitly configured. */
|
||||
retryDelay?: number;
|
||||
connectTimeout?: number;
|
||||
commandTimeout?: number;
|
||||
keepAlive?: number;
|
||||
|
|
@ -41,6 +43,8 @@ export interface CacheProvider {
|
|||
keys(pattern: string): Promise<string[]>;
|
||||
getStats(): CacheStats;
|
||||
health(): Promise<boolean>;
|
||||
/** Release an owned transport; borrowed/shared providers need not expose this. */
|
||||
disconnect?(): Promise<void>;
|
||||
|
||||
/**
|
||||
* Wait for the cache to be ready and connected
|
||||
|
|
|
|||
|
|
@ -25,8 +25,12 @@ export const questdbConfigSchema = z.object({
|
|||
database: z.string().default('questdb'),
|
||||
user: z.string().optional(), // No default - QuestDB doesn't require auth by default
|
||||
password: z.string().optional(), // No default - QuestDB doesn't require auth by default
|
||||
bufferSize: z.number().default(65536),
|
||||
flushInterval: z.number().default(1000),
|
||||
// Deprecated compatibility fields: DI uses the client, not a background buffered writer.
|
||||
bufferSize: z.number().default(65536).describe('Deprecated: no effect on QuestDB client/writer'),
|
||||
flushInterval: z
|
||||
.number()
|
||||
.default(1000)
|
||||
.describe('Deprecated: no effect on QuestDB client/writer'),
|
||||
});
|
||||
|
||||
// MongoDB configuration
|
||||
|
|
@ -52,10 +56,14 @@ export const dragonflyConfigSchema = z.object({
|
|||
password: z.string().optional(),
|
||||
db: z.number().min(0).max(15).default(0),
|
||||
username: z.string().optional(),
|
||||
keyPrefix: z.string().optional(),
|
||||
keyPrefix: z
|
||||
.string()
|
||||
.optional()
|
||||
.describe('Deprecated at DI boundary: service cache namespaces are fixed'),
|
||||
ttl: z.number().optional(),
|
||||
maxRetries: z.number().default(3),
|
||||
retryDelay: z.number().default(100),
|
||||
// Cache/rate-limiter request retries. BullMQ retains its dedicated worker/producer policy.
|
||||
maxRetries: z.number().default(3).describe('Cache/rate-limiter maxRetriesPerRequest'),
|
||||
retryDelay: z.number().default(100).describe('Fixed Redis reconnect delay in milliseconds'),
|
||||
});
|
||||
|
||||
// Combined database configuration
|
||||
|
|
|
|||
|
|
@ -23,6 +23,7 @@ export interface ServiceDefinitions {
|
|||
// Core services
|
||||
cache: CacheProvider | null;
|
||||
globalCache: CacheProvider | null;
|
||||
proxyCache: CacheProvider | null;
|
||||
proxyManager: ProxyManager | null;
|
||||
browser: Browser | null;
|
||||
queueManager: QueueManager | null;
|
||||
|
|
|
|||
|
|
@ -7,6 +7,13 @@ export function registerCacheServices(
|
|||
config: AppConfig
|
||||
): void {
|
||||
if (config.redis?.enabled) {
|
||||
if (config.redis.keyPrefix !== undefined) {
|
||||
container
|
||||
.resolve('logger')
|
||||
.warn(
|
||||
'Redis keyPrefix is deprecated at the DI boundary; service/global/proxy namespaces remain fixed'
|
||||
);
|
||||
}
|
||||
container.register({
|
||||
cache: asFunction(({ logger }) => {
|
||||
const { createServiceCache } = require('@stock-bot/queue');
|
||||
|
|
@ -21,11 +28,15 @@ export function registerCacheServices(
|
|||
port: config.redis.port,
|
||||
password: config.redis.password,
|
||||
username: config.redis.username,
|
||||
maxRetriesPerRequest: config.redis.maxRetries,
|
||||
retryDelay: config.redis.retryDelay,
|
||||
db: config.redis.db, // This will be overridden by ServiceCache
|
||||
},
|
||||
{ logger }
|
||||
{ logger, shared: false, ttl: config.redis.ttl }
|
||||
);
|
||||
}).singleton(),
|
||||
})
|
||||
.singleton()
|
||||
.disposer(cache => cache.disconnect()),
|
||||
|
||||
// Also provide global cache for shared data
|
||||
globalCache: asFunction(({ logger }) => {
|
||||
|
|
@ -39,10 +50,14 @@ export function registerCacheServices(
|
|||
port: config.redis.port,
|
||||
password: config.redis.password,
|
||||
username: config.redis.username,
|
||||
maxRetriesPerRequest: config.redis.maxRetries,
|
||||
retryDelay: config.redis.retryDelay,
|
||||
},
|
||||
{ global: true, logger }
|
||||
{ global: true, logger, shared: false, ttl: config.redis.ttl }
|
||||
);
|
||||
}).singleton(),
|
||||
})
|
||||
.singleton()
|
||||
.disposer(cache => cache.disconnect()),
|
||||
});
|
||||
} else {
|
||||
container.register({
|
||||
|
|
|
|||
|
|
@ -76,6 +76,16 @@ export function registerDatabaseServices(
|
|||
if (config.questdb?.enabled) {
|
||||
container.register({
|
||||
questdbClient: asFunction(({ logger }) => {
|
||||
// Compatibility fields never configured the writer. Warn on requested tuning,
|
||||
// rather than pretending bytes map to its explicit per-operation row batching.
|
||||
if (
|
||||
defined(config.questdb).bufferSize !== 65536 ||
|
||||
defined(config.questdb).flushInterval !== 1000
|
||||
) {
|
||||
logger.warn(
|
||||
'QuestDB bufferSize/flushInterval are deprecated and have no effect; configure explicit writer batch options instead'
|
||||
);
|
||||
}
|
||||
return new QuestDBClient(
|
||||
{
|
||||
host: defined(config.questdb).host,
|
||||
|
|
|
|||
|
|
@ -30,31 +30,35 @@ export function registerApplicationServices(
|
|||
// Proxy Manager
|
||||
if (config.proxy && config.redis?.enabled) {
|
||||
container.register({
|
||||
proxyManager: asFunction(({ logger }) => {
|
||||
proxyCache: asFunction(({ logger }) => {
|
||||
// Create a separate cache instance for proxy with global prefix
|
||||
const { createCache } = require('@stock-bot/cache');
|
||||
const proxyCache = createCache({
|
||||
return createCache({
|
||||
redisConfig: {
|
||||
host: config.redis.host,
|
||||
port: config.redis.port,
|
||||
password: config.redis.password,
|
||||
username: config.redis.username,
|
||||
maxRetriesPerRequest: config.redis.maxRetries,
|
||||
retryDelay: config.redis.retryDelay,
|
||||
db: 1, // Use cache DB (usually DB 1)
|
||||
},
|
||||
shared: false,
|
||||
keyPrefix: 'cache:proxy:',
|
||||
ttl: 86400, // 24 hours default
|
||||
enableMetrics: true,
|
||||
logger,
|
||||
});
|
||||
|
||||
const proxyManager = new ProxyManager(proxyCache, config.proxy, logger);
|
||||
|
||||
// Note: Initialization will be handled by the lifecycle manager
|
||||
return proxyManager;
|
||||
}).singleton(),
|
||||
})
|
||||
.singleton()
|
||||
.disposer(cache => cache.disconnect?.()),
|
||||
proxyManager: asFunction(
|
||||
({ logger, proxyCache }) => new ProxyManager(defined(proxyCache), config.proxy, logger)
|
||||
).singleton(),
|
||||
});
|
||||
} else {
|
||||
container.register({
|
||||
proxyCache: asValue(null),
|
||||
proxyManager: asValue(null),
|
||||
});
|
||||
}
|
||||
|
|
@ -72,6 +76,8 @@ export function registerApplicationServices(
|
|||
port: config.redis.port,
|
||||
password: config.redis.password,
|
||||
username: config.redis.username,
|
||||
maxRetriesPerRequest: config.redis.maxRetries,
|
||||
retryDelay: config.redis.retryDelay,
|
||||
db: config.redis.db,
|
||||
},
|
||||
defaultQueueOptions: {
|
||||
|
|
|
|||
|
|
@ -14,6 +14,8 @@ export class ServiceLifecycleManager {
|
|||
private readonly logger = getLogger('service-lifecycle');
|
||||
private readonly services = [
|
||||
{ name: 'cache', key: 'cache' as const },
|
||||
{ name: 'globalCache', key: 'globalCache' as const },
|
||||
{ name: 'proxyCache', key: 'proxyCache' as const },
|
||||
{ name: 'mongoClient', key: 'mongoClient' as const },
|
||||
{ name: 'postgresClient', key: 'postgresClient' as const },
|
||||
{ name: 'questdbClient', key: 'questdbClient' as const },
|
||||
|
|
|
|||
|
|
@ -61,13 +61,15 @@ export class QueueManager {
|
|||
this.redisConnection = getRedisConnection(config.redis);
|
||||
|
||||
// Create ioredis connection for rate limiter
|
||||
const retryDelay = config.redis.retryDelay;
|
||||
this.ioredisConnection = new Redis({
|
||||
host: config.redis.host,
|
||||
port: config.redis.port,
|
||||
password: config.redis.password,
|
||||
username: config.redis.username,
|
||||
db: config.redis.db || 0,
|
||||
maxRetriesPerRequest: 3,
|
||||
maxRetriesPerRequest: config.redis.maxRetriesPerRequest ?? 3,
|
||||
...(retryDelay === undefined ? {} : { retryStrategy: () => retryDelay }),
|
||||
enableReadyCheck: true,
|
||||
});
|
||||
|
||||
|
|
@ -205,6 +207,7 @@ export class QueueManager {
|
|||
if (!this.caches.has(queueName)) {
|
||||
const cacheProvider = createCache({
|
||||
redisConfig: this.config.redis,
|
||||
shared: false,
|
||||
keyPrefix: `batch:${queueName}:`,
|
||||
ttl: 86400, // 24 hours default
|
||||
enableMetrics: true,
|
||||
|
|
@ -499,6 +502,8 @@ export class QueueManager {
|
|||
await cache.clear();
|
||||
} catch (error) {
|
||||
this.logger.warn('Error clearing cache', { error: (error as Error).message });
|
||||
} finally {
|
||||
await cache.disconnect?.();
|
||||
}
|
||||
});
|
||||
|
||||
|
|
|
|||
|
|
@ -15,7 +15,8 @@ export class ServiceCache implements CacheProvider {
|
|||
serviceName: string,
|
||||
redisConfig: RedisConfig,
|
||||
isGlobalCache: boolean = false,
|
||||
logger?: LoggerLike
|
||||
logger?: LoggerLike,
|
||||
options: { shared?: boolean; ttl?: number } = {}
|
||||
) {
|
||||
// Determine Redis DB and prefix
|
||||
let db: number;
|
||||
|
|
@ -37,6 +38,8 @@ export class ServiceCache implements CacheProvider {
|
|||
...redisConfig,
|
||||
db,
|
||||
},
|
||||
shared: options.shared ?? true,
|
||||
...(options.ttl === undefined ? {} : { ttl: options.ttl }),
|
||||
keyPrefix: prefix + ':',
|
||||
logger,
|
||||
};
|
||||
|
|
@ -45,6 +48,10 @@ export class ServiceCache implements CacheProvider {
|
|||
this.prefix = prefix;
|
||||
}
|
||||
|
||||
async disconnect(): Promise<void> {
|
||||
await this.cache.disconnect?.();
|
||||
}
|
||||
|
||||
// Implement CacheProvider interface
|
||||
async get<T = unknown>(key: string): Promise<T | null> {
|
||||
return this.cache.get<T>(key);
|
||||
|
|
@ -173,7 +180,7 @@ export class ServiceCache implements CacheProvider {
|
|||
export function createServiceCache(
|
||||
serviceName: string,
|
||||
redisConfig: RedisConfig,
|
||||
options: { global?: boolean; logger?: LoggerLike } = {}
|
||||
options: { global?: boolean; logger?: LoggerLike; shared?: boolean; ttl?: number } = {}
|
||||
): ServiceCache {
|
||||
return new ServiceCache(serviceName, redisConfig, options.global, options.logger);
|
||||
return new ServiceCache(serviceName, redisConfig, options.global, options.logger, options);
|
||||
}
|
||||
|
|
|
|||
|
|
@ -44,6 +44,8 @@ export interface RedisConfig {
|
|||
password?: string;
|
||||
username?: string;
|
||||
db?: number;
|
||||
maxRetriesPerRequest?: number;
|
||||
retryDelay?: number;
|
||||
}
|
||||
|
||||
// Extended job options specific to this queue implementation
|
||||
|
|
|
|||
|
|
@ -9,6 +9,6 @@ export function getRedisConnection(config: RedisConfig) {
|
|||
connectTimeout: 3000,
|
||||
lazyConnect: false,
|
||||
keepAlive: 10000,
|
||||
retryStrategy: (times: number) => Math.min(times * 100, 3000),
|
||||
retryStrategy: (times: number) => config.retryDelay ?? Math.min(times * 100, 3000),
|
||||
};
|
||||
}
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue