import crypto from 'crypto'; import type { QuerySpec } from './queryExecutor'; import type { TenantContext } from './tenantScope'; import { getRedisClient, isRedisConfigured } from './redisClient'; export interface CachedQueryPayload { data: unknown; error: null; count: number | null; } /** 热点读表:TTL 秒 + 单次可缓存最大行数 */ const HOT_CACHE_RULES: Record< string, { ttlSec: number; maxRows: number; requireLimit?: boolean } > = { categories: { ttlSec: 300, maxRows: 5000 }, branches: { ttlSec: 600, maxRows: 500 }, permissions: { ttlSec: 600, maxRows: 2000 }, role_definitions: { ttlSec: 600, maxRows: 500 }, role_permissions: { ttlSec: 300, maxRows: 5000 }, suppliers: { ttlSec: 120, maxRows: 500 }, customers: { ttlSec: 120, maxRows: 500 }, skus: { ttlSec: 90, maxRows: 200, requireLimit: true }, delivery_persons: { ttlSec: 120, maxRows: 500 }, smart_classification_rules: { ttlSec: 180, maxRows: 2000 }, purchaser_users: { ttlSec: 300, maxRows: 200 }, system_configs: { ttlSec: 600, maxRows: 200 }, market_prices: { ttlSec: 60, maxRows: 500, requireLimit: true }, }; const VERSION_PREFIX = 'qc:ver:'; function stableStringify(value: unknown): string { return JSON.stringify(value, (_key, val) => { if (Array.isArray(val)) return val; if (val && typeof val === 'object') { const obj = val as Record; return Object.keys(obj) .sort() .reduce>((acc, key) => { acc[key] = obj[key]; return acc; }, {}); } return val; }); } function hashSpec(value: unknown): string { return crypto.createHash('sha256').update(stableStringify(value)).digest('hex').slice(0, 32); } function resolveRowLimit(spec: QuerySpec): number | null { if (spec.range) return spec.range.to - spec.range.from + 1; if (typeof spec.limit === 'number') return spec.limit; return null; } export function isQueryCacheEnabled(): boolean { return isRedisConfigured(); } export function isCacheableSelect(spec: QuerySpec): boolean { if (spec.action !== 'select') return false; const rule = HOT_CACHE_RULES[spec.table]; if (!rule) return false; if ((spec.filters || []).some((filter) => filter.op === 'expr')) return false; const rowLimit = resolveRowLimit(spec); if (rule.requireLimit && rowLimit === null) return false; if (rowLimit !== null && rowLimit > rule.maxRows) return false; return true; } function cacheIdentity( spec: QuerySpec, ctx: TenantContext | null, operatingBranch: string | null ): string { return stableStringify({ table: spec.table, select: spec.select, filters: spec.filters, orders: spec.orders, limit: spec.limit, offset: spec.offset, range: spec.range, single: spec.single, count: spec.count, userId: ctx?.userId || null, branchCode: ctx?.branchCode || null, operatingBranch: operatingBranch || null, isSuperAdmin: ctx?.isSuperAdmin || false, supplierCode: ctx?.supplierCode || null, purchaserCode: ctx?.purchaserCode || null, }); } async function readTableVersion(table: string): Promise { const redis = getRedisClient(); if (!redis) return 0; try { const raw = await redis.get(`${VERSION_PREFIX}${table}`); return raw ? Number(raw) || 0 : 0; } catch { return 0; } } async function buildCacheKey( spec: QuerySpec, ctx: TenantContext | null, operatingBranch: string | null ): Promise { const version = await readTableVersion(spec.table); const identityHash = hashSpec(cacheIdentity(spec, ctx, operatingBranch)); return `qc:data:${spec.table}:v${version}:${identityHash}`; } function countResultRows(data: unknown): number { if (Array.isArray(data)) return data.length; return data == null ? 0 : 1; } export async function getCachedQuery( spec: QuerySpec, ctx: TenantContext | null, operatingBranch: string | null ): Promise { if (!isCacheableSelect(spec)) return null; const redis = getRedisClient(); if (!redis) return null; try { const key = await buildCacheKey(spec, ctx, operatingBranch); const raw = await redis.get(key); if (!raw) return null; const parsed = JSON.parse(raw) as CachedQueryPayload; if (!parsed || parsed.error !== null) return null; return parsed; } catch (error: any) { console.warn('[query-cache] read failed:', error?.message || error); return null; } } export async function setCachedQuery( spec: QuerySpec, ctx: TenantContext | null, operatingBranch: string | null, result: CachedQueryPayload ): Promise { if (!isCacheableSelect(spec)) return; const rule = HOT_CACHE_RULES[spec.table]; if (!rule) return; const rows = countResultRows(result.data); if (rows > rule.maxRows) return; const redis = getRedisClient(); if (!redis) return; try { const key = await buildCacheKey(spec, ctx, operatingBranch); await redis.set(key, JSON.stringify(result), 'EX', rule.ttlSec); } catch (error: any) { console.warn('[query-cache] write failed:', error?.message || error); } } /** 表写入后 bump 版本号,使该表历史查询缓存立即失效 */ export async function invalidateQueryCacheForTable(table: string): Promise { if (!HOT_CACHE_RULES[table]) return; const redis = getRedisClient(); if (!redis) return; try { await redis.incr(`${VERSION_PREFIX}${table}`); } catch (error: any) { console.warn('[query-cache] invalidate failed:', error?.message || error); } } /** 目录写操作会经触发器同步 legacy 表,需连带失效 */ const CACHE_INVALIDATE_RELATED: Record = { product_catalog: ['skus', 'categories'], skus: ['skus'], categories: ['categories'], }; export async function invalidateQueryCacheForSpecs(specs: QuerySpec[]): Promise { const tables = new Set(); for (const spec of specs) { if (spec.action === 'select') continue; if (HOT_CACHE_RULES[spec.table]) tables.add(spec.table); for (const related of CACHE_INVALIDATE_RELATED[spec.table] || []) { if (HOT_CACHE_RULES[related]) tables.add(related); } } await Promise.all([...tables].map((table) => invalidateQueryCacheForTable(table))); } export function listHotCacheTables(): string[] { return Object.keys(HOT_CACHE_RULES); }