Files
SupplierSystem/server/src/services/queryCacheService.ts
T
Ubuntu deb3e72750
CI / server typecheck + tests (push) Canceled after 0s
CI / web typecheck + tests + miniprogram syntax (push) Canceled after 0s
CI / eslint (观察项,C7 骨架) (push) Canceled after 0s
CI / npm audit (critical 硬拦) (push) Canceled after 0s
chore: 以 AI 生鲜配送系统 当前版本作为 SupplierSystem 起点
来源仓库:jxc/ai-fresh-delivery
来源提交:f0b1a180e2deb7e4673b9d1c8542619f7bc0f73d
快照树:  09f679334ff38f0ff25e907961c94a8223bcaedd(与来源 HEAD 工作树逐字节一致,3801 个文件)

按约定本仓库不带任何历史提交:来源仓库的历史中含真实凭据
(生产 SSH 私钥 deploy/id_rsa_tencent、server/.env、.env.tencent/.env.production/.env.gitea、
deploy/小程序AppSecret.txt,其中 MP_APPSECRET / S3 AccessKey 经哈希比对与线上同值),
整包推送会把这些凭据永久带入本仓库,故只取「当前版本」的单提交快照。
供应商系统后续开发自本提交开始。
2026-10-08 17:35:43 +08:00

206 lines
6.2 KiB
TypeScript

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<string, unknown>;
return Object.keys(obj)
.sort()
.reduce<Record<string, unknown>>((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<number> {
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<string> {
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<CachedQueryPayload | null> {
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<void> {
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<void> {
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<string, string[]> = {
product_catalog: ['skus', 'categories'],
skus: ['skus'],
categories: ['categories'],
};
export async function invalidateQueryCacheForSpecs(specs: QuerySpec[]): Promise<void> {
const tables = new Set<string>();
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);
}