来源仓库: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 经哈希比对与线上同值), 整包推送会把这些凭据永久带入本仓库,故只取「当前版本」的单提交快照。 供应商系统后续开发自本提交开始。
131 lines
5.3 KiB
TypeScript
131 lines
5.3 KiB
TypeScript
import { pool } from '../db';
|
||
|
||
/**
|
||
* 助手「待确认写操作」的**持久化**存储(跨实例可确认)。
|
||
*
|
||
* 背景(2026-09-22):原先只存在 `assistantSessionStore`(Redis / 进程内存,TTL 45 分钟)。
|
||
* 生产 `/api` 是 CLB 双活(test-api 用 127.0.0.1:6379,test-h51 用 10.206.16.9:6379,**两套 Redis**),
|
||
* 预览写在 A 机、确认请求落到 B 机 → 读不到 pendingWrite → 400 `confirm_mismatch`。
|
||
*
|
||
* 现改为随会话行落库(`assistant_conversations.pending_write`),确认时**先查库、再回退会话态**;
|
||
* 会话态(lastModule/traces)仍留在 Redis,丢了只影响上下文,不影响能否确认。
|
||
*
|
||
* 归属:按 `id + user_id` 校验(会话 id 为 UUID;branch_code 不参与,避免「当前操作分公司」与
|
||
* 会话所属分公司不一致时读不到)。过期:默认 45 分钟,与旧会话 TTL 对齐。
|
||
*/
|
||
|
||
export const ASSISTANT_PENDING_WRITE_TTL_MS = Math.max(
|
||
60_000,
|
||
Number(process.env.ASSISTANT_PENDING_WRITE_TTL_MS || 45 * 60 * 1000)
|
||
);
|
||
|
||
export type AssistantPendingWrite = { capability: string; args: Record<string, unknown> };
|
||
export type StoredAssistantPendingWrite = AssistantPendingWrite & { at: string };
|
||
|
||
const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
|
||
|
||
function isUuid(raw: unknown): boolean {
|
||
return UUID_RE.test(String(raw || '').trim());
|
||
}
|
||
|
||
/** 归一化待确认写操作:必须有 capability;args 只能是非数组对象;`confirm` 永远不落库。 */
|
||
export function normalizeAssistantPendingWrite(
|
||
raw: unknown
|
||
): StoredAssistantPendingWrite | null {
|
||
let row: unknown = raw;
|
||
if (typeof row === 'string') {
|
||
try {
|
||
row = JSON.parse(row);
|
||
} catch {
|
||
return null;
|
||
}
|
||
}
|
||
if (!row || typeof row !== 'object' || Array.isArray(row)) return null;
|
||
const source = row as { capability?: unknown; args?: unknown; at?: unknown };
|
||
const capability = String(source.capability || '').trim();
|
||
if (!capability) return null;
|
||
const args =
|
||
source.args && typeof source.args === 'object' && !Array.isArray(source.args)
|
||
? { ...(source.args as Record<string, unknown>) }
|
||
: {};
|
||
delete args.confirm;
|
||
return { capability, args, at: String(source.at || '').trim() };
|
||
}
|
||
|
||
/** 过期或缺少时间戳 → 视为无效(与旧会话 TTL 一致,避免陈旧预览被确认)。 */
|
||
export function isAssistantPendingWriteExpired(raw: unknown, nowMs: number = Date.now()): boolean {
|
||
const normalized = normalizeAssistantPendingWrite(raw);
|
||
if (!normalized) return true;
|
||
const at = Date.parse(normalized.at);
|
||
if (!Number.isFinite(at)) return true;
|
||
return nowMs - at > ASSISTANT_PENDING_WRITE_TTL_MS;
|
||
}
|
||
|
||
/** 落库(仅当该会话存在且属于该用户时生效);返回是否写入成功。 */
|
||
export async function saveAssistantPendingWrite(input: {
|
||
conversationId: string;
|
||
userId: string;
|
||
pending: AssistantPendingWrite;
|
||
}): Promise<boolean> {
|
||
const conversationId = String(input.conversationId || '').trim();
|
||
const userId = String(input.userId || '').trim();
|
||
if (!isUuid(conversationId) || !userId) return false;
|
||
const normalized = normalizeAssistantPendingWrite({ ...input.pending, at: new Date().toISOString() });
|
||
if (!normalized) return false;
|
||
const result = await pool.query(
|
||
`UPDATE assistant_conversations
|
||
SET pending_write = $2::jsonb
|
||
WHERE id = $1::uuid AND user_id = $3`,
|
||
[conversationId, JSON.stringify(normalized), userId]
|
||
);
|
||
return (result.rowCount ?? 0) > 0;
|
||
}
|
||
|
||
/** 读取未过期的待确认写操作;无 / 过期 / 不属于该用户 → null。 */
|
||
export async function loadAssistantPendingWrite(input: {
|
||
conversationId: string;
|
||
userId: string;
|
||
}): Promise<AssistantPendingWrite | null> {
|
||
const conversationId = String(input.conversationId || '').trim();
|
||
const userId = String(input.userId || '').trim();
|
||
if (!isUuid(conversationId) || !userId) return null;
|
||
const result = await pool.query(
|
||
`SELECT pending_write
|
||
FROM assistant_conversations
|
||
WHERE id = $1::uuid AND user_id = $2
|
||
LIMIT 1`,
|
||
[conversationId, userId]
|
||
);
|
||
const raw = result.rows[0]?.pending_write;
|
||
const normalized = normalizeAssistantPendingWrite(raw);
|
||
if (!normalized) return null;
|
||
if (isAssistantPendingWriteExpired(normalized)) {
|
||
return null;
|
||
}
|
||
return { capability: normalized.capability, args: normalized.args };
|
||
}
|
||
|
||
/** 清空(确认成功 / 取消 / 新一轮对话覆盖时调用)。 */
|
||
export async function clearAssistantPendingWrite(input: {
|
||
conversationId: string;
|
||
userId: string;
|
||
}): Promise<void> {
|
||
const conversationId = String(input.conversationId || '').trim();
|
||
const userId = String(input.userId || '').trim();
|
||
if (!isUuid(conversationId) || !userId) return;
|
||
await pool.query(
|
||
`UPDATE assistant_conversations
|
||
SET pending_write = NULL
|
||
WHERE id = $1::uuid AND user_id = $2`,
|
||
[conversationId, userId]
|
||
);
|
||
}
|
||
|
||
/** 只读诊断:不做过期判定,返回原始记录的摘要(供脚本/排查用)。 */
|
||
export function describeAssistantPendingWrite(raw: unknown): string {
|
||
const normalized = normalizeAssistantPendingWrite(raw);
|
||
if (!normalized) return '无';
|
||
const expired = isAssistantPendingWriteExpired(normalized);
|
||
return `${normalized.capability}(${expired ? '已过期' : '有效'},at=${normalized.at || '未记录'})`;
|
||
}
|