Files
access-manage/src/modules/digital/growth/growth.repository.ts
T
湛兮 73d56bddb8 feat(growth): 建立C端增长与权益服务闭环
- growth模块:新增游客承接、行为漏斗、推荐实验和站内生命周期运营
- 额度账本:事务预占、幂等结算、全站并发与字符预算保护
- 聊天与记忆:接入回答反馈、可控记忆和持久化异步提取
- 迁移020与回归:覆盖账号隔离、计数器死锁和真实MySQL并发场景
2026-10-28 21:17:45 +08:00

261 lines
8.2 KiB
TypeScript

/** 增长配置、匿名身份和事件写入;所有账号来源均为已校验令牌。 */
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<Identity>(
"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<Identity>(
"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<?",
[bucket, maximum],
c,
);
if (!r.affectedRows)
throw new HttpError(429, "RATE_LIMIT", "操作过于频繁,请稍后再试");
}
/** 客户端事件只接受白名单和有限字段,不能上报收入、回复完成或伪造实验组。 */
export const clientEvents = [
"page_view",
"card_impression",
"card_open",
"card_skip",
"recommendation_exposure",
] as const;
/** 业务事件使用确定性键或UUID防重复,不写入聊天内容。 */
export async function growthEvent(
account: string,
event: string,
entity?: string,
id: string = randomUUID(),
receipt?: string,
c?: PoolConnection,
) {
const eventId = createHash("sha256")
.update(JSON.stringify([event, entity ?? account, id]))
.digest("hex");
await write(
"INSERT IGNORE INTO dh_growth_events(id,account,event,entity,receipt_id,server_event) VALUES (?,?,?,?,?,TRUE)",
[eventId, account, event, entity ?? null, receipt ?? null],
c,
);
}
/** 游客创建有全站每日上限;不采集设备指纹,不把客户端IP当作可信身份。 */
export async function createGuest() {
const config = await growthConfig();
if (!config.guestEnabled) throw forbidden("游客体验暂未开放");
const account = `guest:${randomUUID()}`;
await transaction(async (c) => {
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<Identity>(
"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<Identity>(
"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,
);
});
}