/** 增长配置、匿名身份和事件写入;所有账号来源均为已校验令牌。 */ import { createHash, randomUUID } from "node:crypto"; import type { PoolConnection } from "mysql2/promise"; import { rows, write, json, transaction, audit } from "../digital.repository"; import { forbidden, unauthorized, HttpError, conflict, } from "../../../shared/http-error"; import { mergeDigitalProfile, parseDigitalProfile } from "../digital.profile"; import { growthConfigSchema } from "./growth.policy"; /** 后台版本号防止并发覆盖增长策略。 */ export async function growthConfig() { const [r] = await rows<{ revision: number; body: unknown }>( "SELECT revision,body FROM dh_growth_config WHERE id=1", ); return { revision: r?.revision ?? 1, ...growthConfigSchema.parse(r ? json(r.body) : {}), }; } /** 已登录账号按原开户时间建立增长身份;不发放可重复领取的注册赠送。 */ export async function identity(account: string, c?: PoolConnection) { if (account.startsWith("guest:")) { const [guest] = await rows( "SELECT * FROM dh_growth_identities WHERE account=? AND merged_into IS NULL AND expires_at>NOW(3)", [account], c, ); if (!guest) throw unauthorized("游客体验已过期,请登录继续"); return guest; } await write( "INSERT IGNORE INTO dh_growth_identities(account,subject,created_at) SELECT ?,?,created_at FROM dh_users WHERE id=?", [account, account, account.slice(5)], c, ); const [found] = await rows( "SELECT * FROM dh_growth_identities WHERE account=?", [account], c, ); if (!found) throw unauthorized("账号不存在"); return found; } /** 资料不包含凭据;游客合并后原令牌立即失效。 */ export type Identity = { account: string; subject: string; merged_into: string | null; member_until: Date | null; interests: unknown; auto_memory: number; created_at: Date; }; /** 持久化限流同时约束多进程;同一桶原子计数,过期桶由后台任务清理。 */ export async function takeLimit( bucket: string, maximum: number, seconds: number, c?: PoolConnection, ) { await write( "INSERT INTO dh_growth_limits(bucket,used,expires_at) VALUES (?,0,DATE_ADD(NOW(3),INTERVAL ? SECOND)) ON DUPLICATE KEY UPDATE bucket=VALUES(bucket)", [bucket, seconds], c, ); const r = await write( "UPDATE dh_growth_limits SET used=used+1 WHERE bucket=? AND used { const [day] = await rows<{ day: string }>( "SELECT DATE_FORMAT(CURDATE(),'%Y-%m-%d') day", [], c, ); await takeLimit( `guest-start:${day.day}`, config.guestDailyStarts, 86400, c, ); await write( "INSERT INTO dh_growth_identities(account,subject,expires_at) VALUES (?,?,DATE_ADD(NOW(3),INTERVAL 7 DAY))", [account, account], c, ); await growthEvent( account, "guest_started", undefined, randomUUID(), undefined, c, ); }); return account; } /** 凭游客令牌与成功登录共同承接数据,锁定身份并拒绝迁移仍在生成的对话。 */ export async function mergeGuest(guest: string, account: string) { await transaction(async (c) => { const [source] = await rows( "SELECT * FROM dh_growth_identities WHERE account=? FOR UPDATE", [guest], c, ); if (!source) throw unauthorized("游客会话不存在"); if (source.merged_into === account) return; if (source.merged_into) throw unauthorized("游客会话已承接"); const unsettled = await rows( "SELECT request_id FROM dh_growth_requests WHERE account=? AND state='reserved' FOR UPDATE", [guest], c, ); if (unsettled.length) throw conflict("游客回复额度正在结算,请稍后登录"); const active = await rows( "SELECT id FROM dh_conversations WHERE account=? AND lease_until>NOW(3) FOR UPDATE", [guest], c, ); if (active.length) throw conflict("请先停止游客回复,再登录承接故事"); const [existing] = await rows( "SELECT * FROM dh_growth_identities WHERE account=? FOR UPDATE", [account], c, ); if (!existing) await write( "INSERT INTO dh_growth_identities(account,subject,created_at,interests,auto_memory) SELECT ?,?,created_at,?,? FROM dh_users WHERE id=?", [ account, source.subject, JSON.stringify(source.interests ? json(source.interests) : []), !!source.auto_memory, account.slice(5), ], c, ); const profiles = await rows<{ account: string; body: unknown }>( "SELECT account,body FROM dh_profiles WHERE account IN (?,?) ORDER BY account FOR UPDATE", [guest, account], c, ); const guestProfile = profiles.find((p) => p.account === guest), existingProfile = profiles.find((p) => p.account === account); if (guestProfile) { const sourceProfile = parseDigitalProfile(guestProfile.body), targetProfile = parseDigitalProfile(existingProfile?.body); await mergeDigitalProfile( account, { ...(existingProfile ? {} : { persona: sourceProfile.persona, userName: sourceProfile.userName, }), favorites: [ ...new Set([ ...targetProfile.favorites, ...sourceProfile.favorites, ]), ].slice(0, 200), }, c, ); } const [day] = await rows<{ day: string }>( "SELECT DATE_FORMAT(CURDATE(),'%Y-%m-%d') day", [], c, ); // 游客已用次数计入登录当日额度,承接不能重新领取免费轮次。 const [usage] = await rows<{ used: number }>( "SELECT used FROM dh_growth_quota WHERE account=? AND period=? FOR UPDATE", [guest, "1970-01-01"], c, ); await write( "INSERT INTO dh_growth_quota(account,period,used) VALUES (?,?,?) ON DUPLICATE KEY UPDATE used=used+VALUES(used)", [account, day.day, usage?.used ?? 0], c, ); await write( "UPDATE dh_conversations SET account=?,updated_at=updated_at WHERE account=?", [account, guest], c, ); for (const table of [ "dh_growth_events", "dh_growth_recommendations", "dh_growth_feedback", "dh_growth_memories", "dh_growth_memory_jobs", "dh_growth_requests", ]) await write( `UPDATE ${table} SET account=? WHERE account=?`, [account, guest], c, ); await write( "UPDATE dh_growth_identities SET merged_into=? WHERE account=?", [account, guest], c, ); await growthEvent( account, "guest_linked", undefined, randomUUID(), undefined, c, ); await audit( account, "guest.link", guest, { conversationsPreserved: true }, c, ); }); }