import type { PoolClient } from 'pg'; import { pool } from '../db'; import { getRedisClient, isRedisConfigured } from './redisClient'; import type Redis from 'ioredis'; function lockName(lockKey: string): string { return `distlock:${String(lockKey || '').trim()}`; } /** * M11 可观测性(2026-09-24 加):**只统计、不改任何锁语义**。 * * 为什么需要它:Redis 路径的锁带 `EX ttlSec`(持有者崩了会到点自动释放), * 而**无 Redis 时的 PG advisory lock 是会话级、不带 TTL** —— 传入的 ttlSec 在回退路径上 * 完全没被使用。若持有者"卡住但连接不断",其他实例会一直拿不到锁,任务**静默不再执行**。 * 这里把「回退次数」「抢锁失败次数」「持有时长」「持有超过 ttlSec 的次数」记在进程内存, * 供 `/api/health/details`(需登录)查看,先积累证据再决定是否给 PG 路径补真正的 TTL。 * * ⚠️ 统计是**进程内**的:多实例各自一份、重启清零(只作观察用,不作判据)。 */ export type LockStat = { key: string; backend: 'redis' | 'pg'; acquired: number; skipped: number; /** 持有时长超过传入 ttlSec 的次数(PG 回退路径没有 TTL,这是关键信号) */ overTtl: number; lastHoldMs: number; maxHoldMs: number; lastAt: string; }; const lockStats = new Map(); /** 回退到 PG 的次数与原因(无 Redis / 客户端不可用 / Redis 报错) */ const fallbackStats = { unset: 0, unavailable: 0, redisError: 0, lastFallbackAt: '' }; function recordLock( key: string, backend: 'redis' | 'pg', patch: Partial>, holdMs?: number ): void { const now = new Date().toISOString(); const cur = lockStats.get(key) || ({ key, backend, acquired: 0, skipped: 0, overTtl: 0, lastHoldMs: 0, maxHoldMs: 0, lastAt: now, } satisfies LockStat); if (patch.acquired) cur.acquired += patch.acquired; if (patch.skipped) cur.skipped += patch.skipped; if (patch.overTtl) cur.overTtl += patch.overTtl; if (typeof holdMs === 'number') { cur.lastHoldMs = holdMs; if (holdMs > cur.maxHoldMs) cur.maxHoldMs = holdMs; } cur.backend = backend; cur.lastAt = now; lockStats.set(key, cur); } export function getDistributedLockStats(): { fallback: typeof fallbackStats; locks: LockStat[]; } { return { fallback: { ...fallbackStats }, locks: [...lockStats.values()].sort((a, b) => b.maxHoldMs - a.maxHoldMs), }; } async function withRedisLock( redis: Redis, lockKey: string, ttlSec: number, fn: () => Promise ): Promise { const token = `${Date.now()}-${Math.random().toString(36).slice(2, 10)}`; const key = `lock:${lockKey}`; const startedAt = Date.now(); try { const ok = await redis.set(key, token, 'EX', Math.max(5, ttlSec), 'NX'); if (ok !== 'OK') { console.log(`[lock] skip ${lockKey} (redis held)`); recordLock(lockKey, 'redis', { skipped: 1 }); return null; } recordLock(lockKey, 'redis', { acquired: 1 }); return await fn(); } finally { const holdMs = Date.now() - startedAt; recordLock(lockKey, 'redis', {}, holdMs); if (holdMs > Math.max(5, ttlSec) * 1000) { recordLock(lockKey, 'redis', { overTtl: 1 }); console.warn( `[lock] ${lockKey} 持有 ${Math.round(holdMs / 1000)}s 超过 ttlSec=${ttlSec}(redis 到期后可能已被他人接管)` ); } try { const cur = await redis.get(key); if (cur === token) await redis.del(key); } catch { /* ignore */ } } } /** * 无 Redis 时的单集群互斥:session 级 try_advisory_lock。 * 抢不到返回 null(与 Redis NX 一致),禁止静默直接跑 fn。 * ⚠️ 该路径**没有 TTL**:只由 finally 的 unlock / 会话结束释放(M11)。 */ async function withPgAdvisoryLock( lockKey: string, ttlSec: number, fn: () => Promise ): Promise { const name = lockName(lockKey); let client: PoolClient; try { client = await pool.connect(); } catch (error) { console.error( `[lock] PG connect failed for ${lockKey}:`, error instanceof Error ? error.message : error ); return null; } let locked = false; const startedAt = Date.now(); try { const got = await client.query<{ ok: boolean }>( `SELECT pg_try_advisory_lock(hashtextextended($1, 0)) AS ok`, [name] ); locked = Boolean(got.rows[0]?.ok); if (!locked) { console.log(`[lock] skip ${lockKey} (pg held)`); recordLock(lockKey, 'pg', { skipped: 1 }); return null; } recordLock(lockKey, 'pg', { acquired: 1 }); return await fn(); } finally { const holdMs = Date.now() - startedAt; if (locked) { recordLock(lockKey, 'pg', {}, holdMs); if (holdMs > Math.max(5, ttlSec) * 1000) { recordLock(lockKey, 'pg', { overTtl: 1 }); console.warn( `[lock] ${lockKey} 在 PG 回退路径持有 ${Math.round(holdMs / 1000)}s 超过 ttlSec=${ttlSec}` + `(该路径无 TTL:直到 unlock 或会话结束才释放,期间其他实例一直拿不到锁)` ); } await client .query(`SELECT pg_advisory_unlock(hashtextextended($1, 0))`, [name]) .catch((error: unknown) => { console.warn( `[lock] pg unlock failed ${lockKey}:`, error instanceof Error ? error.message : error ); }); } client.release(); } } /** * 分布式锁:优先 Redis SET NX EX;未配置或不可用时回退 PostgreSQL advisory lock。 * 抢锁失败返回 null,不执行 fn。 */ export async function withDistributedLock( lockKey: string, ttlSec: number, fn: () => Promise ): Promise { const key = String(lockKey || '').trim(); if (!key) throw new Error('withDistributedLock: lockKey required'); if (isRedisConfigured()) { const redis = getRedisClient(); if (redis) { try { return await withRedisLock(redis, key, ttlSec, fn); } catch (error: unknown) { console.warn( `[lock] Redis lock failed for ${key}, fallback to PG:`, error instanceof Error ? error.message : error ); fallbackStats.redisError += 1; fallbackStats.lastFallbackAt = new Date().toISOString(); } } else { console.warn(`[lock] Redis configured but client unavailable for ${key}, fallback to PG`); fallbackStats.unavailable += 1; fallbackStats.lastFallbackAt = new Date().toISOString(); } } else { console.warn(`[lock] REDIS_URL unset, using PG advisory lock for ${key}`); fallbackStats.unset += 1; fallbackStats.lastFallbackAt = new Date().toISOString(); } return withPgAdvisoryLock(key, ttlSec, fn); }