feat(growth): 建立C端增长与权益服务闭环
- growth模块:新增游客承接、行为漏斗、推荐实验和站内生命周期运营 - 额度账本:事务预占、幂等结算、全站并发与字符预算保护 - 聊天与记忆:接入回答反馈、可控记忆和持久化异步提取 - 迁移020与回归:覆盖账号隔离、计数器死锁和真实MySQL并发场景
This commit is contained in:
@@ -0,0 +1,102 @@
|
||||
/** 有界推荐缓存、曝光回执和可解释打分;缓存不会跨账号或实验版本复用。 */
|
||||
import { randomUUID } from "node:crypto";
|
||||
import { rows, write, json } from "../digital.repository";
|
||||
import { growthConfig, identity } from "./growth.repository";
|
||||
import { rankCharacters, bucket } from "./growth.policy";
|
||||
const cache = new Map<
|
||||
string,
|
||||
{
|
||||
until: number;
|
||||
value: {
|
||||
receiptId: string;
|
||||
variant: string;
|
||||
items: { id: string; reason: string }[];
|
||||
};
|
||||
}
|
||||
>();
|
||||
/** 用户改偏好、跳过或反馈后使该账号的推荐立即失效。 */
|
||||
export function invalidateRecommendations(account: string) {
|
||||
for (const key of cache.keys())
|
||||
if (key.startsWith(account + "|")) cache.delete(key);
|
||||
}
|
||||
/** 热度以完成回答衡量,点击不能直接伪造有效开聊;兴趣信号只读取当前账号。 */
|
||||
export async function recommend(account: string) {
|
||||
const [config, user] = await Promise.all([growthConfig(), identity(account)]);
|
||||
const variant = config.recommendationExperiment
|
||||
? bucket(user.subject, `recommendation:${config.recommendationRevision}`) <
|
||||
5000
|
||||
? "popular"
|
||||
: "personalized"
|
||||
: "personalized";
|
||||
const key = `${account}|${config.revision}|${variant}`;
|
||||
const hit = cache.get(key);
|
||||
if (hit && hit.until > Date.now()) return hit.value;
|
||||
const [cards, signals] = await Promise.all([
|
||||
rows<{ id: string; tags: unknown; popularity: number }>(
|
||||
"SELECT c.id,JSON_EXTRACT(c.body,'$.tags') tags,COALESCE(p.popularity,0) popularity FROM dh_content c LEFT JOIN (SELECT d.character_id,COUNT(*) popularity FROM dh_growth_events e JOIN dh_conversations d ON d.id=e.entity WHERE e.event='reply_complete' AND e.created_at>DATE_SUB(NOW(3),INTERVAL 7 DAY) GROUP BY d.character_id) p ON p.character_id=c.id WHERE c.kind='character' AND c.status='published' ORDER BY c.id LIMIT 500",
|
||||
),
|
||||
rows<{ id: string; score: number }>(
|
||||
"SELECT entity id,SUM(CASE event WHEN 'card_skip' THEN -4 WHEN 'card_open' THEN 1 WHEN 'card_impression' THEN 0 ELSE 0 END) score FROM dh_growth_events WHERE account=? AND created_at>DATE_SUB(NOW(3),INTERVAL 30 DAY) GROUP BY entity",
|
||||
[account],
|
||||
),
|
||||
]);
|
||||
const interests = user.interests ? json<string[]>(user.interests) : [],
|
||||
weights = Object.fromEntries(signals.map((s) => [s.id, Number(s.score)]));
|
||||
const completed = await rows<{ id: string; n: number }>(
|
||||
"SELECT d.character_id id,COUNT(*) n FROM dh_growth_requests r JOIN dh_conversations d ON d.id=r.conversation_id WHERE r.account=? AND r.outcome='complete' AND r.created_at>DATE_SUB(NOW(3),INTERVAL 30 DAY) GROUP BY d.character_id",
|
||||
[account],
|
||||
);
|
||||
for (const c of completed)
|
||||
weights[c.id] = (weights[c.id] ?? 0) + 2 * Math.log1p(Number(c.n));
|
||||
const [profile] = await rows<{ body: unknown }>(
|
||||
"SELECT body FROM dh_profiles WHERE account=?",
|
||||
[account],
|
||||
);
|
||||
for (const id of profile
|
||||
? (json<{ favorites?: string[] }>(profile.body).favorites ?? [])
|
||||
: [])
|
||||
weights[id] = (weights[id] ?? 0) + 6;
|
||||
const ids = rankCharacters(
|
||||
cards.map((c) => ({
|
||||
id: c.id,
|
||||
tags: c.tags ? json<string[]>(c.tags) : [],
|
||||
popularity: Number(c.popularity),
|
||||
})),
|
||||
interests,
|
||||
weights,
|
||||
user.subject,
|
||||
variant === "personalized",
|
||||
config.explorationPercent,
|
||||
);
|
||||
const receiptId = randomUUID();
|
||||
await write(
|
||||
"INSERT INTO dh_growth_recommendations(id,account,experiment_revision,variant,items) VALUES (?,?,?,?,?)",
|
||||
[
|
||||
receiptId,
|
||||
account,
|
||||
config.recommendationRevision,
|
||||
config.recommendationExperiment ? variant : "off",
|
||||
JSON.stringify(ids),
|
||||
],
|
||||
);
|
||||
const value = {
|
||||
receiptId,
|
||||
variant,
|
||||
items: ids.map((id) => ({
|
||||
id,
|
||||
reason:
|
||||
variant === "popular"
|
||||
? "近期故事热度"
|
||||
: interests.some((t) =>
|
||||
json<string[]>(
|
||||
cards.find((c) => c.id === id)!.tags ?? [],
|
||||
).includes(t),
|
||||
)
|
||||
? "符合你的题材偏好"
|
||||
: "为你探索新的故事",
|
||||
})),
|
||||
};
|
||||
if (cache.size >= 1000) cache.delete(cache.keys().next().value!);
|
||||
cache.set(key, { until: Date.now() + 60000, value });
|
||||
return value;
|
||||
}
|
||||
Reference in New Issue
Block a user