73d56bddb8
- growth模块:新增游客承接、行为漏斗、推荐实验和站内生命周期运营 - 额度账本:事务预占、幂等结算、全站并发与字符预算保护 - 聊天与记忆:接入回答反馈、可控记忆和持久化异步提取 - 迁移020与回归:覆盖账号隔离、计数器死锁和真实MySQL并发场景
477 lines
17 KiB
TypeScript
477 lines
17 KiB
TypeScript
/** 已鉴权增长路由:运营指标与配置仅后台可见,前台只管理本人权益、记忆和反馈。 */
|
|
import { createHash, randomUUID } from "node:crypto";
|
|
import type { FastifyInstance } from "fastify";
|
|
import { z } from "zod";
|
|
import { ok } from "../../../shared/response";
|
|
import { badRequest, conflict, notFound } from "../../../shared/http-error";
|
|
import { rows, write, json, transaction, audit } from "../digital.repository";
|
|
import { ownConversation } from "../digital.chat";
|
|
import {
|
|
growthConfig,
|
|
identity,
|
|
clientEvents,
|
|
takeLimit,
|
|
} from "./growth.repository";
|
|
import { growthConfigSchema, validCampaignWindow } from "./growth.policy";
|
|
import { entitlement } from "./growth.quota";
|
|
import { recommend, invalidateRecommendations } from "./growth.recommendations";
|
|
import { campaignInbox, campaignAction, lifecycle } from "./growth.campaigns";
|
|
import { growthOverview } from "./growth.analytics";
|
|
const id = z.string().regex(/^[a-zA-Z0-9_-]{1,64}$/);
|
|
const feedbackSchema = z.object({
|
|
messageId: id,
|
|
rating: z.enum(["up", "down"]),
|
|
reason: z
|
|
.enum(["", "forgot", "repetition", "slow", "off_topic", "other"])
|
|
.default(""),
|
|
});
|
|
/** 批量事件不接受账号、价格、实验组或正文;同一事件UUID重复上报不重复计数。 */
|
|
export async function growthFrontRoutes(front: FastifyInstance) {
|
|
front.get("/growth", async (r) => {
|
|
const [rights, user, inbox, segment] = await Promise.all([
|
|
entitlement(r.user.sub),
|
|
identity(r.user.sub),
|
|
campaignInbox(r.user.sub),
|
|
lifecycle(r.user.sub),
|
|
]);
|
|
const { config, ...publicRights } = rights;
|
|
void config;
|
|
return ok({
|
|
entitlement: publicRights,
|
|
interests: user.interests ? json(user.interests) : [],
|
|
autoMemory: !!user.auto_memory,
|
|
inbox,
|
|
segment,
|
|
});
|
|
});
|
|
front.put("/growth/preferences", async (r) => {
|
|
await takeLimit(
|
|
`preferences:${r.user.sub}:${Math.floor(Date.now() / 60000)}`,
|
|
20,
|
|
180,
|
|
);
|
|
const b = z
|
|
.object({
|
|
interests: z.array(z.string().trim().min(1).max(40)).max(12),
|
|
autoMemory: z.boolean(),
|
|
})
|
|
.parse(r.body);
|
|
await identity(r.user.sub);
|
|
await transaction(async (c) => {
|
|
await rows(
|
|
"SELECT account FROM dh_growth_identities WHERE account=? FOR UPDATE",
|
|
[r.user.sub],
|
|
c,
|
|
);
|
|
await write(
|
|
"UPDATE dh_growth_identities SET interests=?,auto_memory=? WHERE account=?",
|
|
[JSON.stringify([...new Set(b.interests)]), b.autoMemory, r.user.sub],
|
|
c,
|
|
);
|
|
});
|
|
invalidateRecommendations(r.user.sub);
|
|
return ok({ saved: true });
|
|
});
|
|
front.get("/growth/recommendations", async (r) =>
|
|
ok(await recommend(r.user.sub)),
|
|
);
|
|
front.post("/growth/events", async (r) => {
|
|
const b = z
|
|
.object({
|
|
account: z.string(),
|
|
events: z
|
|
.array(
|
|
z.object({
|
|
id: z.uuid(),
|
|
event: z.enum(clientEvents),
|
|
entity: id.optional(),
|
|
receiptId: z.uuid().optional(),
|
|
occurredAt: z.number().int().nonnegative().optional(),
|
|
}),
|
|
)
|
|
.max(20),
|
|
})
|
|
.parse(r.body);
|
|
if (b.account !== r.user.sub)
|
|
throw badRequest("事件账号已变化,请重新打开页面");
|
|
await transaction(async (c) => {
|
|
await takeLimit(
|
|
`events:${r.user.sub}:${Math.floor(Date.now() / 60000)}`,
|
|
30,
|
|
180,
|
|
c,
|
|
);
|
|
for (const e of b.events) {
|
|
if (
|
|
e.event === "page_view" &&
|
|
e.entity &&
|
|
![
|
|
"discover",
|
|
"chats",
|
|
"library",
|
|
"profile",
|
|
"chat",
|
|
"detail",
|
|
].includes(e.entity)
|
|
)
|
|
throw badRequest("页面标识不合法");
|
|
if (e.event.startsWith("card_")) {
|
|
if (!e.entity) throw badRequest("缺少角色标识");
|
|
const [card] = await rows(
|
|
"SELECT id FROM dh_content WHERE id=? AND kind='character' AND status='published'",
|
|
[e.entity],
|
|
c,
|
|
);
|
|
if (!card) throw notFound("角色不可用");
|
|
}
|
|
if (e.receiptId) {
|
|
const [receipt] = await rows<{
|
|
items: unknown;
|
|
exposed_at: Date | null;
|
|
}>(
|
|
"SELECT items,exposed_at FROM dh_growth_recommendations WHERE id=? AND account=? AND created_at>DATE_SUB(NOW(3),INTERVAL 1 DAY)",
|
|
[e.receiptId, r.user.sub],
|
|
c,
|
|
);
|
|
if (
|
|
!receipt ||
|
|
(e.entity && !json<string[]>(receipt.items).includes(e.entity)) ||
|
|
(e.event === "card_open" && !receipt.exposed_at)
|
|
)
|
|
continue;
|
|
if (e.event === "recommendation_exposure")
|
|
await write(
|
|
"UPDATE dh_growth_recommendations SET exposed_at=COALESCE(exposed_at,NOW(3)) WHERE id=?",
|
|
[e.receiptId],
|
|
c,
|
|
);
|
|
} else if (e.event === "recommendation_exposure")
|
|
throw badRequest("缺少推荐回执");
|
|
await write(
|
|
"INSERT IGNORE INTO dh_growth_events(id,account,event,entity,receipt_id,occurred_at) VALUES (?,?,?,?,?,FROM_UNIXTIME(?))",
|
|
[
|
|
e.id,
|
|
r.user.sub,
|
|
e.event,
|
|
e.entity ?? null,
|
|
e.receiptId ?? null,
|
|
(e.occurredAt &&
|
|
e.occurredAt <= Date.now() + 5000 &&
|
|
e.occurredAt > Date.now() - 86400000
|
|
? e.occurredAt
|
|
: Date.now()) / 1000,
|
|
],
|
|
c,
|
|
);
|
|
}
|
|
});
|
|
if (b.events.some((e) => e.event === "card_skip"))
|
|
invalidateRecommendations(r.user.sub);
|
|
return ok({ received: true });
|
|
});
|
|
front.post("/growth/inbox/:id", async (r) => {
|
|
const p = z.object({ id: z.uuid() }).parse(r.params),
|
|
b = z.object({ action: z.enum(["exposure", "click"]) }).parse(r.body);
|
|
return ok(await campaignAction(r.user.sub, p.id, b.action));
|
|
});
|
|
front.get("/conversations/:id/memories", async (r) => {
|
|
const p = z.object({ id }).parse(r.params);
|
|
await ownConversation(p.id, r.user.sub);
|
|
return ok(
|
|
await rows(
|
|
"SELECT id,kind,content,version FROM dh_growth_memories WHERE account=? AND conversation_id=? AND deleted_at IS NULL ORDER BY created_at DESC LIMIT 80",
|
|
[r.user.sub, p.id],
|
|
),
|
|
);
|
|
});
|
|
front.post("/conversations/:id/memories", async (r) => {
|
|
const p = z.object({ id }).parse(r.params),
|
|
b = z
|
|
.object({ content: z.string().trim().min(1).max(600) })
|
|
.parse(r.body);
|
|
await ownConversation(p.id, r.user.sub);
|
|
await takeLimit(
|
|
`memory:${r.user.sub}:${Math.floor(Date.now() / 60000)}`,
|
|
30,
|
|
180,
|
|
);
|
|
await identity(r.user.sub);
|
|
const memoryId = randomUUID();
|
|
await transaction(async (c) => {
|
|
await rows(
|
|
"SELECT account FROM dh_growth_identities WHERE account=? FOR UPDATE",
|
|
[r.user.sub],
|
|
c,
|
|
);
|
|
const [count] = await rows<{ n: number }>(
|
|
"SELECT COUNT(*) n FROM dh_growth_memories WHERE account=? AND conversation_id=? AND deleted_at IS NULL",
|
|
[r.user.sub, p.id],
|
|
c,
|
|
);
|
|
if (Number(count.n) >= 80) throw badRequest("记忆已满,请先整理旧记忆");
|
|
await write(
|
|
"INSERT INTO dh_growth_memories(id,account,conversation_id,kind,content,source_key) VALUES (?,?,?,'manual',?,?)",
|
|
[memoryId, r.user.sub, p.id, b.content, `manual:${memoryId}`],
|
|
c,
|
|
);
|
|
});
|
|
return ok({ id: memoryId });
|
|
});
|
|
front.patch("/conversations/:id/memories/:memory", async (r) => {
|
|
const p = z.object({ id, memory: z.uuid() }).parse(r.params),
|
|
b = z
|
|
.object({
|
|
version: z.number().int().positive(),
|
|
content: z.string().trim().min(1).max(600).optional(),
|
|
deleted: z.boolean().optional(),
|
|
})
|
|
.parse(r.body);
|
|
await ownConversation(p.id, r.user.sub);
|
|
await transaction(async (c) => {
|
|
await rows(
|
|
"SELECT account FROM dh_growth_identities WHERE account=? FOR UPDATE",
|
|
[r.user.sub],
|
|
c,
|
|
);
|
|
const result = await write(
|
|
"UPDATE dh_growth_memories SET content=COALESCE(?,content),kind=IF(? IS NULL,kind,'manual'),deleted_at=IF(?=TRUE,NOW(3),deleted_at),version=version+1 WHERE id=? AND account=? AND conversation_id=? AND version=? AND deleted_at IS NULL",
|
|
[
|
|
b.content ?? null,
|
|
b.content ?? null,
|
|
b.deleted ?? false,
|
|
p.memory,
|
|
r.user.sub,
|
|
p.id,
|
|
b.version,
|
|
],
|
|
c,
|
|
);
|
|
if (!result.affectedRows) throw conflict("记忆已变化,请刷新后重试");
|
|
});
|
|
return ok({ saved: true });
|
|
});
|
|
front.post("/conversations/:id/feedback", async (r) => {
|
|
const p = z.object({ id }).parse(r.params),
|
|
b = feedbackSchema.parse(r.body);
|
|
await ownConversation(p.id, r.user.sub);
|
|
await takeLimit(
|
|
`feedback:${r.user.sub}:${Math.floor(Date.now() / 60000)}`,
|
|
60,
|
|
180,
|
|
);
|
|
const [message] = await rows(
|
|
"SELECT id FROM dh_messages WHERE id=? AND conversation_id=? AND role='assistant' AND status<>'generating' AND request_id IS NOT NULL",
|
|
[b.messageId, p.id],
|
|
);
|
|
if (!message) throw notFound("回复不可评价");
|
|
await write(
|
|
"INSERT INTO dh_growth_feedback(account,message_id,conversation_id,rating,reason) VALUES (?,?,?,?,?) ON DUPLICATE KEY UPDATE rating=VALUES(rating),reason=VALUES(reason)",
|
|
[
|
|
r.user.sub,
|
|
b.messageId,
|
|
p.id,
|
|
b.rating,
|
|
b.rating === "down" ? b.reason : "",
|
|
],
|
|
);
|
|
return ok({ saved: true });
|
|
});
|
|
front.get("/conversations/:id/feedback", async (r) => {
|
|
const p = z.object({ id }).parse(r.params);
|
|
await ownConversation(p.id, r.user.sub);
|
|
return ok(
|
|
await rows(
|
|
"SELECT message_id messageId,rating,reason FROM dh_growth_feedback WHERE account=? AND conversation_id=?",
|
|
[r.user.sub, p.id],
|
|
),
|
|
);
|
|
});
|
|
}
|
|
/** 权益授予是后台运营操作,需要理由与幂等请求号;不伪装为支付订单。 */
|
|
export async function growthAdminRoutes(admin: FastifyInstance) {
|
|
admin.get("/growth/overview", async (r) => {
|
|
const q = z
|
|
.object({ days: z.coerce.number().int().min(1).max(30).default(14) })
|
|
.parse(r.query);
|
|
return ok(await growthOverview(q.days));
|
|
});
|
|
admin.get("/growth/config", async () => ok(await growthConfig()));
|
|
admin.put("/growth/config", async (r) => {
|
|
const b = z
|
|
.object({
|
|
revision: z.number().int().positive(),
|
|
config: growthConfigSchema,
|
|
})
|
|
.parse(r.body);
|
|
await transaction(async (c) => {
|
|
const [before] = await rows<{ body: unknown; revision: number }>(
|
|
"SELECT body,revision FROM dh_growth_config WHERE id=1 FOR UPDATE",
|
|
[],
|
|
c,
|
|
);
|
|
if (before.revision !== b.revision)
|
|
throw conflict("策略已变化,请刷新后保存");
|
|
const old = growthConfigSchema.parse(json(before.body));
|
|
if (b.config.recommendationRevision < old.recommendationRevision)
|
|
throw badRequest("实验版本不能回退");
|
|
if (
|
|
(old.recommendationExperiment !== b.config.recommendationExperiment ||
|
|
old.explorationPercent !== b.config.explorationPercent) &&
|
|
b.config.recommendationRevision <= old.recommendationRevision
|
|
)
|
|
throw badRequest("变更推荐实验参数时须增加实验版本");
|
|
await write(
|
|
"UPDATE dh_growth_config SET body=?,revision=revision+1 WHERE id=1",
|
|
[JSON.stringify(b.config)],
|
|
c,
|
|
);
|
|
await audit(
|
|
r.user.sub,
|
|
"growth.config",
|
|
"growth",
|
|
{ before: old, after: b.config },
|
|
c,
|
|
);
|
|
});
|
|
return ok(await growthConfig());
|
|
});
|
|
admin.get("/growth/users", async () =>
|
|
ok(
|
|
await rows(
|
|
"SELECT u.id,CONCAT('user:',u.id) account,u.display_name displayName,g.member_until memberUntil,g.auto_memory autoMemory FROM dh_users u LEFT JOIN dh_growth_identities g ON g.account=CONCAT('user:',u.id) WHERE u.status='ACTIVE' ORDER BY u.id DESC LIMIT 200",
|
|
),
|
|
),
|
|
);
|
|
admin.post("/growth/entitlements", async (r) => {
|
|
const b = z
|
|
.object({
|
|
userId: z.number().int().positive(),
|
|
requestId: z.uuid(),
|
|
days: z.number().int().min(0).max(365),
|
|
reason: z.string().trim().min(4).max(200),
|
|
})
|
|
.parse(r.body),
|
|
account = `user:${b.userId}`;
|
|
await identity(account);
|
|
await transaction(async (c) => {
|
|
const fingerprint = createHash("sha256")
|
|
.update(JSON.stringify({ actor: r.user.sub, ...b }))
|
|
.digest("hex");
|
|
await write(
|
|
"INSERT INTO dh_growth_grants(request_id,fingerprint,account,actor) VALUES (?,?,?,?) ON DUPLICATE KEY UPDATE request_id=VALUES(request_id)",
|
|
[b.requestId, fingerprint, account, r.user.sub],
|
|
c,
|
|
);
|
|
const [existing] = await rows<{ fingerprint: string; applied: number }>(
|
|
"SELECT fingerprint,applied FROM dh_growth_grants WHERE request_id=? FOR UPDATE",
|
|
[b.requestId],
|
|
c,
|
|
);
|
|
if (existing.fingerprint !== fingerprint)
|
|
throw conflict("请求号已用于其他权益变更");
|
|
if (existing.applied) return;
|
|
await rows(
|
|
"SELECT account FROM dh_growth_identities WHERE account=? FOR UPDATE",
|
|
[account],
|
|
c,
|
|
);
|
|
const [before] = await rows<{ member_until: Date | null }>(
|
|
"SELECT member_until FROM dh_growth_identities WHERE account=?",
|
|
[account],
|
|
c,
|
|
);
|
|
await write(
|
|
"UPDATE dh_growth_identities SET member_until=IF(?=0,NULL,DATE_ADD(GREATEST(COALESCE(member_until,NOW(3)),NOW(3)),INTERVAL ? DAY)) WHERE account=?",
|
|
[b.days, b.days, account],
|
|
c,
|
|
);
|
|
await write(
|
|
"UPDATE dh_growth_grants SET applied=TRUE WHERE request_id=?",
|
|
[b.requestId],
|
|
c,
|
|
);
|
|
await audit(
|
|
r.user.sub,
|
|
"growth.entitlement",
|
|
b.requestId,
|
|
{
|
|
account,
|
|
days: b.days,
|
|
reason: b.reason,
|
|
before: before.member_until,
|
|
},
|
|
c,
|
|
);
|
|
});
|
|
return ok({ saved: true });
|
|
});
|
|
admin.get("/growth/campaigns", async () =>
|
|
ok(
|
|
await rows(
|
|
"SELECT *,DATE_FORMAT(starts_at,'%Y-%m-%d %H:%i:%s') startsAt,DATE_FORMAT(ends_at,'%Y-%m-%d %H:%i:%s') endsAt FROM dh_growth_campaigns ORDER BY created_at DESC LIMIT 100",
|
|
),
|
|
),
|
|
);
|
|
admin.put("/growth/campaigns/:id", async (r) => {
|
|
const p = z.object({ id: z.uuid() }).parse(r.params),
|
|
b = z
|
|
.object({
|
|
title: z.string().trim().min(1).max(80),
|
|
content: z.string().trim().min(1).max(500),
|
|
segment: z.enum(["new", "active", "dormant"]),
|
|
enabled: z.boolean(),
|
|
holdoutPercent: z.number().int().min(5).max(90),
|
|
startsAt: z.string().regex(/^\d{4}-\d\d-\d\d \d\d:\d\d:\d\d$/),
|
|
endsAt: z.string().regex(/^\d{4}-\d\d-\d\d \d\d:\d\d:\d\d$/),
|
|
revision: z.number().int().min(0),
|
|
})
|
|
.parse(r.body);
|
|
if (!validCampaignWindow(b.startsAt, b.endsAt))
|
|
throw badRequest("活动时间须在30天内且结束晚于开始");
|
|
await transaction(async (c) => {
|
|
if (b.revision === 0)
|
|
await write(
|
|
"INSERT INTO dh_growth_campaigns(id,title,content,segment,enabled,holdout_percent,starts_at,ends_at) VALUES (?,?,?,?,?,?,?,?)",
|
|
[
|
|
p.id,
|
|
b.title,
|
|
b.content,
|
|
b.segment,
|
|
b.enabled,
|
|
b.holdoutPercent,
|
|
b.startsAt,
|
|
b.endsAt,
|
|
],
|
|
c,
|
|
);
|
|
else {
|
|
const result = await write(
|
|
"UPDATE dh_growth_campaigns SET title=?,content=?,segment=?,enabled=?,holdout_percent=?,starts_at=?,ends_at=?,revision=revision+1 WHERE id=? AND revision=?",
|
|
[
|
|
b.title,
|
|
b.content,
|
|
b.segment,
|
|
b.enabled,
|
|
b.holdoutPercent,
|
|
b.startsAt,
|
|
b.endsAt,
|
|
p.id,
|
|
b.revision,
|
|
],
|
|
c,
|
|
);
|
|
if (!result.affectedRows) throw conflict("活动已更新,请刷新");
|
|
}
|
|
await audit(r.user.sub, "growth.campaign", p.id, { ...b }, c);
|
|
});
|
|
return ok({ saved: true });
|
|
});
|
|
admin.get("/growth/requests", async () =>
|
|
ok(
|
|
await rows(
|
|
"SELECT account,request_id requestId,conversation_id conversationId,state,purpose,outcome,estimate_reserved reservedCharacters,estimate_used usedCharacters,model,prompt_version promptVersion,first_token_ms firstTokenMs,duration_ms durationMs,created_at createdAt FROM dh_growth_requests ORDER BY created_at DESC LIMIT 100",
|
|
),
|
|
),
|
|
);
|
|
}
|