feat(growth): 建立C端增长与权益服务闭环
- growth模块:新增游客承接、行为漏斗、推荐实验和站内生命周期运营 - 额度账本:事务预占、幂等结算、全站并发与字符预算保护 - 聊天与记忆:接入回答反馈、可控记忆和持久化异步提取 - 迁移020与回归:覆盖账号隔离、计数器死锁和真实MySQL并发场景
This commit is contained in:
@@ -0,0 +1,89 @@
|
||||
/** 增长分析读取真实事件、服务端完成流水和曝光回执,空样本不伪造提升结论。 */
|
||||
import { rows } from "../digital.repository";
|
||||
import { orderedFunnel, allocationHealth } from "./growth.policy";
|
||||
/** 时间范围以数据库自然日为准;漏斗阶段按账号严格先后,超过采样边界明确标记。 */
|
||||
export async function growthOverview(days: number) {
|
||||
const [
|
||||
events,
|
||||
quality,
|
||||
feedback,
|
||||
experiments,
|
||||
retention,
|
||||
campaigns,
|
||||
budget,
|
||||
risks,
|
||||
] = await Promise.all([
|
||||
rows<{ account: string; event: string; at: number }>(
|
||||
"SELECT account,event,UNIX_TIMESTAMP(occurred_at)*1000 at FROM dh_growth_events WHERE occurred_at>=DATE_SUB(NOW(3),INTERVAL ? DAY) ORDER BY occurred_at,id LIMIT 50001",
|
||||
[days],
|
||||
),
|
||||
rows(
|
||||
"SELECT COUNT(*) requests,SUM(state='consumed') consumed,SUM(state='released') released,SUM(state='reserved') reserved,SUM(estimate_used) estimatedCharacters,AVG(first_token_ms) avgFirstTokenMs,AVG(duration_ms) avgDurationMs,purpose,SUM(outcome='failed') failed,SUM(outcome='stopped') stopped,model,prompt_version promptVersion FROM dh_growth_requests WHERE created_at>=DATE_SUB(NOW(3),INTERVAL ? DAY) GROUP BY model,prompt_version,purpose",
|
||||
[days],
|
||||
),
|
||||
rows(
|
||||
"SELECT rating,reason,COUNT(*) count FROM dh_growth_feedback WHERE updated_at>=DATE_SUB(NOW(3),INTERVAL ? DAY) GROUP BY rating,reason",
|
||||
[days],
|
||||
),
|
||||
rows(
|
||||
"SELECT r.experiment_revision revision,r.variant,COUNT(DISTINCT r.account) assignedUsers,COUNT(DISTINCT CASE WHEN r.exposed_at IS NOT NULL THEN r.account END) exposedUsers,COUNT(DISTINCT CASE WHEN e.event='card_open' THEN e.account END) clickUsers,COUNT(DISTINCT CASE WHEN e.event='conversation_started' THEN e.account END) startUsers,COUNT(DISTINCT CASE WHEN e.event='conversation_activated' THEN e.account END) activatedUsers FROM dh_growth_recommendations r LEFT JOIN dh_growth_events e ON e.receipt_id=r.id WHERE r.created_at>=DATE_SUB(NOW(3),INTERVAL ? DAY) GROUP BY r.experiment_revision,r.variant",
|
||||
[days],
|
||||
),
|
||||
rows(
|
||||
"SELECT DATE_FORMAT(f.first_day,'%Y-%m-%d') cohort,COUNT(*) users,SUM(EXISTS(SELECT 1 FROM dh_growth_events e WHERE e.account=f.account AND e.event IN ('page_view','chat_requested') AND DATE(e.occurred_at)=DATE_ADD(f.first_day,INTERVAL 1 DAY))) returned FROM (SELECT account,DATE(MIN(occurred_at)) first_day FROM dh_growth_events WHERE event='page_view' GROUP BY account) f WHERE f.first_day>=DATE_SUB(CURDATE(),INTERVAL ? DAY) AND f.first_day<CURDATE() GROUP BY f.first_day ORDER BY f.first_day",
|
||||
[days],
|
||||
),
|
||||
rows(
|
||||
"SELECT c.id,c.title,d.campaign_revision revision,d.held_out heldOut,COUNT(*) assigned,SUM(d.exposed_at IS NOT NULL) exposed,SUM(d.clicked_at IS NOT NULL) clicked,SUM(EXISTS(SELECT 1 FROM dh_growth_events e WHERE e.account=d.account AND e.event='reply_complete' AND e.created_at>d.created_at AND e.created_at<DATE_ADD(d.created_at,INTERVAL 1 DAY))) returnedToChat FROM dh_growth_deliveries d JOIN dh_growth_campaigns c ON c.id=d.campaign_id WHERE d.created_at>=DATE_SUB(NOW(3),INTERVAL ? DAY) GROUP BY c.id,c.title,d.campaign_revision,d.held_out",
|
||||
[days],
|
||||
),
|
||||
rows(
|
||||
"SELECT period,used,reserved FROM dh_growth_budget ORDER BY period DESC LIMIT 14",
|
||||
),
|
||||
rows(
|
||||
"SELECT event,COUNT(*) count FROM dh_growth_events WHERE event IN ('quota_denied','rate_denied','budget_denied','guest_linked') AND created_at>=DATE_SUB(NOW(3),INTERVAL ? DAY) GROUP BY event",
|
||||
[days],
|
||||
),
|
||||
]);
|
||||
const crossovers = await rows<{ count: number }>(
|
||||
"SELECT COUNT(DISTINCT account) count FROM (SELECT account,experiment_revision FROM dh_growth_recommendations WHERE exposed_at IS NOT NULL AND variant<>'off' AND created_at>=DATE_SUB(NOW(3),INTERVAL ? DAY) GROUP BY account,experiment_revision HAVING COUNT(DISTINCT variant)>1) x",
|
||||
[days],
|
||||
);
|
||||
return {
|
||||
days,
|
||||
truncated: events.length > 50000,
|
||||
funnel: orderedFunnel(
|
||||
events.slice(0, 50000).map((e) => ({ ...e, at: Number(e.at) })),
|
||||
[
|
||||
"page_view",
|
||||
"card_open",
|
||||
"conversation_started",
|
||||
"chat_requested",
|
||||
"reply_complete",
|
||||
"conversation_activated",
|
||||
],
|
||||
),
|
||||
quality,
|
||||
feedback,
|
||||
experiments,
|
||||
retention,
|
||||
campaigns,
|
||||
budget,
|
||||
risks,
|
||||
crossovers: Number(crossovers[0]?.count ?? 0),
|
||||
allocationHealth: allocationHealth(
|
||||
experiments as {
|
||||
revision: number;
|
||||
variant: string;
|
||||
assignedUsers: number;
|
||||
}[],
|
||||
),
|
||||
definitions: {
|
||||
activation: "同一故事累计3次服务端完整回复",
|
||||
cost: "字符数估算预算,不是供应商Token账单或收入",
|
||||
retention: "全量首次访问队列的次日回访,排除尚未满一天的队列",
|
||||
experiments: "只按服务端回执归因;跨组账号单独计数,不自动宣称显著性",
|
||||
campaigns: "分配后24小时完整回复;对照组不展示,观测相关性不等于因果结论",
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,94 @@
|
||||
/** 站内生命周期运营:服务端分群、稳定对照组、每日频控与独立曝光/点击回执。 */
|
||||
import { randomUUID } from "node:crypto";
|
||||
import { rows, write, transaction } from "../digital.repository";
|
||||
import { bucket } from "./growth.policy";
|
||||
import { identity, growthEvent } from "./growth.repository";
|
||||
/** 新用户优先激活,7天未访问则进入回访分群;不会向外部渠道发送消息。 */
|
||||
export async function lifecycle(account: string) {
|
||||
const user = await identity(account);
|
||||
const [activity] = await rows<{
|
||||
age: number;
|
||||
inactive: number | null;
|
||||
replies: number;
|
||||
}>(
|
||||
"SELECT TIMESTAMPDIFF(DAY,?,NOW(3)) age,(SELECT TIMESTAMPDIFF(DAY,MAX(created_at),NOW(3)) FROM dh_growth_events WHERE account=? AND event='page_view') inactive,(SELECT COUNT(*) FROM dh_growth_requests WHERE account=? AND state='consumed') replies",
|
||||
[user.created_at, account, account],
|
||||
);
|
||||
return activity.age <= 7 && Number(activity.replies) < 3
|
||||
? "new"
|
||||
: (activity.inactive ?? activity.age) >= 7
|
||||
? "dormant"
|
||||
: "active";
|
||||
}
|
||||
/** 返回最近的一张站内卡片,控制组保留分配但不展示;按访问前行为识别召回用户。 */
|
||||
export async function campaignInbox(account: string) {
|
||||
if (account.startsWith("guest:")) return [];
|
||||
const [segment, user] = await Promise.all([
|
||||
lifecycle(account),
|
||||
identity(account),
|
||||
]);
|
||||
await transaction(async (c) => {
|
||||
await rows(
|
||||
"SELECT account FROM dh_growth_identities WHERE account=? FOR UPDATE",
|
||||
[account],
|
||||
c,
|
||||
);
|
||||
const [frequency] = await rows<{ n: number }>(
|
||||
"SELECT COUNT(*) n FROM dh_growth_deliveries WHERE account=? AND created_at>DATE_SUB(NOW(3),INTERVAL 1 DAY)",
|
||||
[account],
|
||||
c,
|
||||
);
|
||||
if (Number(frequency.n) >= 1) return;
|
||||
const [campaign] = await rows<{
|
||||
id: string;
|
||||
revision: number;
|
||||
holdout_percent: number;
|
||||
}>(
|
||||
"SELECT id,revision,holdout_percent FROM dh_growth_campaigns WHERE enabled=TRUE AND segment=? AND starts_at<=NOW(3) AND ends_at>NOW(3) AND NOT EXISTS(SELECT 1 FROM dh_growth_deliveries d WHERE d.campaign_id=dh_growth_campaigns.id AND d.account=? AND d.campaign_revision=dh_growth_campaigns.revision) ORDER BY starts_at DESC LIMIT 1",
|
||||
[segment, account],
|
||||
c,
|
||||
);
|
||||
if (campaign)
|
||||
await write(
|
||||
"INSERT IGNORE INTO dh_growth_deliveries(id,campaign_id,account,campaign_revision,held_out) VALUES (?,?,?,?,?)",
|
||||
[
|
||||
randomUUID(),
|
||||
campaign.id,
|
||||
account,
|
||||
campaign.revision,
|
||||
bucket(user.subject, `campaign:${campaign.id}:${campaign.revision}`) <
|
||||
campaign.holdout_percent * 100,
|
||||
],
|
||||
c,
|
||||
);
|
||||
});
|
||||
return rows<{ id: string; title: string; content: string }>(
|
||||
"SELECT d.id,c.title,c.content FROM dh_growth_deliveries d JOIN dh_growth_campaigns c ON c.id=d.campaign_id AND c.revision=d.campaign_revision WHERE d.account=? AND d.held_out=FALSE AND c.enabled=TRUE AND c.starts_at<=NOW(3) AND c.ends_at>NOW(3) AND d.created_at>DATE_SUB(NOW(3),INTERVAL 1 DAY) ORDER BY d.created_at DESC LIMIT 1",
|
||||
[account],
|
||||
);
|
||||
}
|
||||
/** 只有本人真实分配到且尚未失效的卡片能确认曝光与点击。 */
|
||||
export async function campaignAction(
|
||||
account: string,
|
||||
id: string,
|
||||
action: "exposure" | "click",
|
||||
) {
|
||||
const field = action === "exposure" ? "exposed_at" : "clicked_at";
|
||||
await transaction(async (c) => {
|
||||
const r = await write(
|
||||
`UPDATE dh_growth_deliveries d JOIN dh_growth_campaigns p ON p.id=d.campaign_id AND p.revision=d.campaign_revision SET d.${field}=COALESCE(d.${field},NOW(3)) WHERE d.id=? AND d.account=? AND d.held_out=FALSE AND p.enabled=TRUE AND p.ends_at>NOW(3) AND d.created_at>DATE_SUB(NOW(3),INTERVAL 1 DAY)${action === "click" ? " AND d.exposed_at IS NOT NULL" : ""}`,
|
||||
[id, account],
|
||||
c,
|
||||
);
|
||||
if (r.affectedRows)
|
||||
await growthEvent(
|
||||
account,
|
||||
`campaign_${action}`,
|
||||
id,
|
||||
`campaign:${action}:${id}`,
|
||||
undefined,
|
||||
c,
|
||||
);
|
||||
});
|
||||
return { received: true };
|
||||
}
|
||||
@@ -0,0 +1,135 @@
|
||||
/** 用户可控记忆及持久化提取任务;原文摘要是摘录,避免把模型台词当作用户事实。 */
|
||||
import { randomUUID } from "node:crypto";
|
||||
import { rows, write, transaction } from "../digital.repository";
|
||||
import { extractMemoryFacts, selectMemories } from "./growth.policy";
|
||||
import { identity } from "./growth.repository";
|
||||
/** 自动记忆关闭后不再检索自动事实;手动记忆仍由用户明确授权。 */
|
||||
export async function contextMemories(
|
||||
account: string,
|
||||
conversation: string,
|
||||
query: string,
|
||||
) {
|
||||
const user = await identity(account);
|
||||
const items = await rows<{ kind: string; content: string }>(
|
||||
"SELECT kind,content FROM dh_growth_memories WHERE account=? AND conversation_id=? AND deleted_at IS NULL AND (kind='manual' OR ?=TRUE) ORDER BY created_at DESC LIMIT 80",
|
||||
[account, conversation, !!user.auto_memory],
|
||||
);
|
||||
const labelled = items.map((m) => ({
|
||||
...m,
|
||||
content: `[${m.kind === "summary" ? "历史原文摘录" : m.kind === "manual" ? "手动更正优先" : "用户明确背景"}] ${m.content}`,
|
||||
}));
|
||||
return selectMemories(labelled, query, 1600)
|
||||
.map((m) => m.content)
|
||||
.join("\n");
|
||||
}
|
||||
/** 使用完成消息作为任务幂等键,异步任务不会阻塞流式正文。 */
|
||||
export async function scheduleMemory(
|
||||
account: string,
|
||||
conversation: string,
|
||||
message: string,
|
||||
c?: import("mysql2/promise").PoolConnection,
|
||||
) {
|
||||
await write(
|
||||
"INSERT IGNORE INTO dh_growth_memory_jobs(id,account,conversation_id) SELECT ?,?,? FROM dh_growth_identities WHERE account=? AND auto_memory=TRUE",
|
||||
[message, account, conversation, account],
|
||||
c,
|
||||
);
|
||||
}
|
||||
/** 持久化任务可在重启后重领;最多重试3次,任务读取和用户删除使用同一身份锁串行化。 */
|
||||
export async function processMemoryJobs() {
|
||||
const jobs = await rows<{
|
||||
id: string;
|
||||
account: string;
|
||||
conversation_id: string;
|
||||
}>(
|
||||
"SELECT id,account,conversation_id FROM dh_growth_memory_jobs WHERE attempts<3 AND (state='pending' OR (state='running' AND lease_until<NOW(3))) ORDER BY created_at LIMIT 10",
|
||||
);
|
||||
for (const job of jobs) {
|
||||
const claim = await write(
|
||||
"UPDATE dh_growth_memory_jobs SET state='running',attempts=attempts+1,lease_until=DATE_ADD(NOW(3),INTERVAL 60 SECOND) WHERE id=? AND (state='pending' OR (state='running' AND lease_until<NOW(3)))",
|
||||
[job.id],
|
||||
);
|
||||
if (!claim.affectedRows) continue;
|
||||
try {
|
||||
await transaction(async (c) => {
|
||||
const [user] = await rows<{ auto_memory: number }>(
|
||||
"SELECT auto_memory FROM dh_growth_identities WHERE account=? FOR UPDATE",
|
||||
[job.account],
|
||||
c,
|
||||
);
|
||||
const [conversation] = await rows(
|
||||
"SELECT id FROM dh_conversations WHERE id=? AND account=? AND deleted_at IS NULL",
|
||||
[job.conversation_id, job.account],
|
||||
c,
|
||||
);
|
||||
if (user?.auto_memory && conversation) {
|
||||
const messages = await rows<{
|
||||
id: string;
|
||||
role: string;
|
||||
content: string;
|
||||
}>(
|
||||
"SELECT id,role,content FROM dh_messages WHERE conversation_id=? AND status IN ('complete','stopped') AND sequence_id<=(SELECT sequence_id FROM dh_messages WHERE id=?) ORDER BY sequence_id DESC LIMIT 20",
|
||||
[job.conversation_id, job.id],
|
||||
c,
|
||||
);
|
||||
messages.reverse();
|
||||
const [capacity] = await rows<{ n: number }>(
|
||||
"SELECT COUNT(*) n FROM dh_growth_memories WHERE account=? AND conversation_id=? AND deleted_at IS NULL",
|
||||
[job.account, job.conversation_id],
|
||||
c,
|
||||
);
|
||||
let room = Math.max(0, 80 - Number(capacity.n));
|
||||
for (const fact of extractMemoryFacts(messages).slice(0, room)) {
|
||||
room--;
|
||||
await write(
|
||||
"INSERT IGNORE INTO dh_growth_memories(id,account,conversation_id,kind,content,source_key) VALUES (?,?,?,'fact',?,?)",
|
||||
[
|
||||
randomUUID(),
|
||||
job.account,
|
||||
job.conversation_id,
|
||||
fact.content,
|
||||
fact.sourceKey,
|
||||
],
|
||||
c,
|
||||
);
|
||||
}
|
||||
// 每20条消息形成一份摘录;源键保证用户删除后不会由重试重新创建。
|
||||
const [count] = await rows<{ n: number }>(
|
||||
"SELECT COUNT(*) n FROM dh_messages WHERE conversation_id=? AND sequence_id<=(SELECT sequence_id FROM dh_messages WHERE id=?)",
|
||||
[job.conversation_id, job.id],
|
||||
c,
|
||||
);
|
||||
if (Number(count.n) >= 20 && Number(count.n) % 20 <= 1) {
|
||||
const summary = messages
|
||||
.filter((m) => m.role === "user")
|
||||
.map((m) => m.content.slice(0, 160))
|
||||
.join("\n")
|
||||
.slice(0, 1600);
|
||||
if (summary && room > 0)
|
||||
await write(
|
||||
"INSERT IGNORE INTO dh_growth_memories(id,account,conversation_id,kind,content,source_key) VALUES (?,?,?,'summary',?,?)",
|
||||
[
|
||||
randomUUID(),
|
||||
job.account,
|
||||
job.conversation_id,
|
||||
summary,
|
||||
`summary:${Math.floor(Number(count.n) / 20)}`,
|
||||
],
|
||||
c,
|
||||
);
|
||||
}
|
||||
}
|
||||
await write(
|
||||
"UPDATE dh_growth_memory_jobs SET state='done',lease_until=NULL WHERE id=?",
|
||||
[job.id],
|
||||
c,
|
||||
);
|
||||
});
|
||||
} catch {
|
||||
await write(
|
||||
"UPDATE dh_growth_memory_jobs SET state=IF(attempts>=3,'failed','pending'),lease_until=NULL WHERE id=?",
|
||||
[job.id],
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,148 @@
|
||||
/** 增长策略的纯函数:可解释推荐、稳定分组和有界上下文,不依赖模型或浏览器身份。 */
|
||||
import { createHash } from "node:crypto";
|
||||
import { z } from "zod";
|
||||
/** 所有额度为回复次数,成本预算为字符数估算,不代表供应商账单或人民币。 */
|
||||
export const growthConfigSchema = z.object({
|
||||
guestEnabled: z.boolean().default(true),
|
||||
guestLifetime: z.number().int().min(0).max(20).default(3),
|
||||
guestDailyStarts: z.number().int().min(0).max(10000).default(100),
|
||||
freeDaily: z.number().int().min(0).max(1000).default(30),
|
||||
memberDaily: z.number().int().min(0).max(5000).default(150),
|
||||
dailyCharacterBudget: z.number().int().min(0).max(100000000).default(2000000),
|
||||
generationEnabled: z.boolean().default(true),
|
||||
recommendationExperiment: z.boolean().default(false),
|
||||
recommendationRevision: z.number().int().positive().default(1),
|
||||
explorationPercent: z.number().int().min(0).max(50).default(20),
|
||||
});
|
||||
/** 固定命名空间避免推荐实验与运营对照组使用同一随机变量。 */
|
||||
export function bucket(subject: string, namespace: string) {
|
||||
return (
|
||||
createHash("sha256")
|
||||
.update(`${namespace}:${subject}`)
|
||||
.digest()
|
||||
.readUInt32BE(0) % 10000
|
||||
);
|
||||
}
|
||||
/** 按兴趣、有效对话和跳过行为排序;探索槽位不被热门角色永久占据。 */
|
||||
export function rankCharacters(
|
||||
cards: { id: string; tags: string[]; popularity: number }[],
|
||||
interests: string[],
|
||||
signals: Record<string, number>,
|
||||
subject: string,
|
||||
personalized: boolean,
|
||||
explorationPercent: number,
|
||||
) {
|
||||
const score = (c: (typeof cards)[number]) =>
|
||||
personalized
|
||||
? c.tags.reduce((n, t) => n + (interests.includes(t) ? 4 : 0), 0) +
|
||||
(signals[c.id] ?? 0) +
|
||||
Math.log1p(Math.max(0, c.popularity))
|
||||
: Math.log1p(Math.max(0, c.popularity));
|
||||
const sorted = [...cards].sort(
|
||||
(a, b) => score(b) - score(a) || a.id.localeCompare(b.id),
|
||||
);
|
||||
const count = Math.min(8, sorted.length),
|
||||
explore = Math.floor((count * explorationPercent) / 100);
|
||||
const main = sorted.slice(0, count - explore);
|
||||
const rest = sorted
|
||||
.filter((c) => !main.some((m) => m.id === c.id))
|
||||
.sort((a, b) => bucket(subject, a.id) - bucket(subject, b.id));
|
||||
return [...main, ...rest.slice(0, explore)].map((c) => c.id);
|
||||
}
|
||||
/** 自动提取只接受用户明确要求记住的内容,忽略模型台词与隐式个人推断。 */
|
||||
export function extractMemoryFacts(
|
||||
messages: { id: string; role: string; content: string }[],
|
||||
) {
|
||||
return messages
|
||||
.filter((m) => m.role === "user")
|
||||
.flatMap((m) => {
|
||||
const match = m.content.match(
|
||||
/(?:请记住|记住:|记住:)[::\s]*([^\n]{2,180})/u,
|
||||
);
|
||||
return match
|
||||
? [{ sourceKey: `fact:${m.id}`, content: match[1].trim() }]
|
||||
: [];
|
||||
});
|
||||
}
|
||||
/** 检索将手动记忆优先置入预算;摘要为原文摘录,不能覆盖用户纠正后的事实。 */
|
||||
export function selectMemories<T extends { kind: string; content: string }>(
|
||||
items: T[],
|
||||
query: string,
|
||||
budget = 2200,
|
||||
) {
|
||||
const terms = [
|
||||
...new Set(query.toLocaleLowerCase().match(/[\p{L}\p{N}]{2,12}/gu) ?? []),
|
||||
];
|
||||
const score = (m: T) =>
|
||||
(m.kind === "manual" ? 100 : m.kind === "fact" ? 40 : 0) +
|
||||
terms.filter((t) => m.content.toLocaleLowerCase().includes(t)).length;
|
||||
let used = 0;
|
||||
return [...items]
|
||||
.sort((a, b) => score(b) - score(a))
|
||||
.filter((m) => {
|
||||
if (used + m.content.length > budget) return false;
|
||||
used += m.content.length;
|
||||
return true;
|
||||
});
|
||||
}
|
||||
/** 漏斗以服务端时间先后顺序计算,跳过中间阶段的账号不能计为完整转化。 */
|
||||
export function orderedFunnel(
|
||||
events: { account: string; event: string; at: number }[],
|
||||
stages: string[],
|
||||
) {
|
||||
const progress = new Map<string, { step: number; at: number }>();
|
||||
const counts = stages.map(() => 0);
|
||||
for (const e of [...events].sort((a, b) => a.at - b.at)) {
|
||||
const p = progress.get(e.account) ?? { step: 0, at: -Infinity };
|
||||
if (stages[p.step] === e.event && e.at >= p.at) {
|
||||
counts[p.step]++;
|
||||
progress.set(e.account, { step: p.step + 1, at: e.at });
|
||||
}
|
||||
}
|
||||
return stages.map((stage, i) => ({ stage, users: counts[i] }));
|
||||
}
|
||||
|
||||
/** 基于Hoeffding界检查50/50分配异常;小样本只显示不足,不把业务差异当作显著提升。 */
|
||||
export function allocationHealth(
|
||||
groups: { revision: number; variant: string; assignedUsers: number }[],
|
||||
) {
|
||||
const revisions = [
|
||||
...new Set(
|
||||
groups.filter((g) => g.variant !== "off").map((g) => g.revision),
|
||||
),
|
||||
];
|
||||
return revisions.map((revision) => {
|
||||
const rows = groups.filter((g) => g.revision === revision),
|
||||
a = Number(rows.find((g) => g.variant === "popular")?.assignedUsers ?? 0),
|
||||
b = Number(
|
||||
rows.find((g) => g.variant === "personalized")?.assignedUsers ?? 0,
|
||||
),
|
||||
n = a + b;
|
||||
const bound = n
|
||||
? Math.min(1, 2 * Math.exp(-2 * n * (a / n - 0.5) ** 2))
|
||||
: 1;
|
||||
return {
|
||||
revision,
|
||||
assigned: n,
|
||||
imbalanceUpperBound: bound,
|
||||
status:
|
||||
n < 200
|
||||
? "样本不足"
|
||||
: bound < 0.01
|
||||
? "分配比例异常,暂停解读"
|
||||
: "暂未发现明显分配异常",
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
/** 活动使用北京时间,拒绝不存在的日历日期和超过30天的窗口。 */
|
||||
export function validCampaignWindow(start: string, end: string) {
|
||||
const parse = (s: string) => Date.parse(s.replace(" ", "T") + "+08:00");
|
||||
const a = parse(start),
|
||||
b = parse(end);
|
||||
const same = (s: string, n: number) =>
|
||||
Number.isFinite(n) &&
|
||||
new Date(n + 8 * 3600000).toISOString().slice(0, 19).replace("T", " ") ===
|
||||
s;
|
||||
return same(start, a) && same(end, b) && b > a && b - a <= 30 * 86400000;
|
||||
}
|
||||
@@ -0,0 +1,224 @@
|
||||
/** 回复次数预占与结算、全站字符预算及过期回收,账本与聊天写入共用事务。 */
|
||||
import type { PoolConnection } from "mysql2/promise";
|
||||
import { rows, write, transaction } from "../digital.repository";
|
||||
import { HttpError, conflict } from "../../../shared/http-error";
|
||||
import {
|
||||
growthConfig,
|
||||
identity,
|
||||
takeLimit,
|
||||
growthEvent,
|
||||
} from "./growth.repository";
|
||||
/** 查询权益只读现有用量,不通过打开页面赠送额度。 */
|
||||
export async function entitlement(account: string) {
|
||||
const [config, user] = await Promise.all([growthConfig(), identity(account)]);
|
||||
const [date] = await rows<{ day: string; isMember: number }>(
|
||||
"SELECT DATE_FORMAT(CURDATE(),'%Y-%m-%d') day, (? IS NOT NULL AND ?>NOW(3)) AS isMember",
|
||||
[user.member_until, user.member_until],
|
||||
);
|
||||
const guest = account.startsWith("guest:"),
|
||||
limit = guest
|
||||
? config.guestLifetime
|
||||
: date.isMember
|
||||
? config.memberDaily
|
||||
: config.freeDaily,
|
||||
period = guest ? "1970-01-01" : date.day;
|
||||
const [usage] = await rows<{ used: number; reserved: number }>(
|
||||
"SELECT used,reserved FROM dh_growth_quota WHERE account=? AND period=?",
|
||||
[account, period],
|
||||
);
|
||||
return {
|
||||
tier: guest ? "guest" : date.isMember ? "member" : "free",
|
||||
limit,
|
||||
used: usage?.used ?? 0,
|
||||
reserved: usage?.reserved ?? 0,
|
||||
remaining: Math.max(0, limit - (usage?.used ?? 0) - (usage?.reserved ?? 0)),
|
||||
period,
|
||||
day: date.day,
|
||||
memberUntil: user.member_until,
|
||||
config,
|
||||
};
|
||||
}
|
||||
/** 在既有会话租约事务中执行,重试不能重复预占,空失败释放、部分回复消耗一次。 */
|
||||
export async function reserveReply(
|
||||
account: string,
|
||||
conversation: string,
|
||||
requestId: string,
|
||||
estimate: number,
|
||||
rights: Awaited<ReturnType<typeof entitlement>>,
|
||||
c: PoolConnection,
|
||||
purpose: "send" | "continue" | "regenerate" | "suggestion" = "send",
|
||||
) {
|
||||
if (!rights.config.generationEnabled)
|
||||
throw new HttpError(503, "GENERATION_PAUSED", "回复服务暂时维护中");
|
||||
await takeLimit(
|
||||
`generation:${account}:${Math.floor(Date.now() / 60000)}`,
|
||||
12,
|
||||
180,
|
||||
c,
|
||||
);
|
||||
const duplicate = await rows(
|
||||
"SELECT request_id FROM dh_growth_requests WHERE account=? AND request_id=?",
|
||||
[account, requestId],
|
||||
c,
|
||||
);
|
||||
if (duplicate.length) throw conflict("此请求已受理,请同步聊天记录");
|
||||
await write(
|
||||
"INSERT INTO dh_growth_quota(account,period) VALUES (?,?) ON DUPLICATE KEY UPDATE account=VALUES(account)",
|
||||
[account, rights.period],
|
||||
c,
|
||||
);
|
||||
const quota = await write(
|
||||
"UPDATE dh_growth_quota SET reserved=reserved+1 WHERE account=? AND period=? AND used+reserved<?",
|
||||
[account, rights.period, rights.limit],
|
||||
c,
|
||||
);
|
||||
if (!quota.affectedRows)
|
||||
throw new HttpError(
|
||||
429,
|
||||
"QUOTA_EXHAUSTED",
|
||||
rights.tier === "guest"
|
||||
? "游客体验次数已用完,登录后继续原故事"
|
||||
: "今日回复额度已用完,请明日再来",
|
||||
);
|
||||
// 同账号并行会话也共享数据库并发上限,避免绕过单会话租约。
|
||||
const [active] = await rows<{ reserved: number }>(
|
||||
"SELECT reserved FROM dh_growth_quota WHERE account=? AND period=? FOR UPDATE",
|
||||
[account, rights.period],
|
||||
c,
|
||||
);
|
||||
if (Number(active.reserved) > (rights.tier === "member" ? 2 : 1))
|
||||
throw new HttpError(
|
||||
429,
|
||||
"ACCOUNT_BUSY",
|
||||
"其他故事仍在回复,请先停止或等待完成",
|
||||
);
|
||||
const capacity = await write(
|
||||
"UPDATE dh_growth_capacity SET in_flight=in_flight+1 WHERE id=1 AND in_flight<4",
|
||||
[],
|
||||
c,
|
||||
);
|
||||
if (!capacity.affectedRows)
|
||||
throw new HttpError(429, "MODEL_BUSY", "当前回复较多,请稍后重试");
|
||||
await write(
|
||||
"INSERT INTO dh_growth_budget(period) VALUES (?) ON DUPLICATE KEY UPDATE period=VALUES(period)",
|
||||
[rights.day],
|
||||
c,
|
||||
);
|
||||
const budget = await write(
|
||||
"UPDATE dh_growth_budget SET reserved=reserved+? WHERE period=? AND used+reserved+?<=?",
|
||||
[estimate, rights.day, estimate, rights.config.dailyCharacterBudget],
|
||||
c,
|
||||
);
|
||||
if (!budget.affectedRows)
|
||||
throw new HttpError(
|
||||
503,
|
||||
"BUDGET_EXHAUSTED",
|
||||
"今日服务容量已达上限,请稍后再来",
|
||||
);
|
||||
await write(
|
||||
"INSERT INTO dh_growth_requests(account,request_id,conversation_id,period,budget_period,estimate_reserved,purpose,model,prompt_version,expires_at) VALUES (?,?,?,?,?,?,?,'deepseek-flash','growth-context-v1',DATE_ADD(NOW(3),INTERVAL 180 SECOND))",
|
||||
[
|
||||
account,
|
||||
requestId,
|
||||
conversation,
|
||||
rights.period,
|
||||
rights.day,
|
||||
estimate,
|
||||
purpose,
|
||||
],
|
||||
c,
|
||||
);
|
||||
if (purpose !== "suggestion")
|
||||
await growthEvent(
|
||||
account,
|
||||
"chat_requested",
|
||||
conversation,
|
||||
`request:${requestId}`,
|
||||
undefined,
|
||||
c,
|
||||
);
|
||||
}
|
||||
/** 条件状态转换保证结算、重试与回收之间最多记账一次。 */
|
||||
export async function settleReply(
|
||||
account: string,
|
||||
requestId: string,
|
||||
outcome: string,
|
||||
characters: number,
|
||||
hasOutput: boolean,
|
||||
firstTokenMs: number | null,
|
||||
durationMs: number,
|
||||
c: PoolConnection,
|
||||
) {
|
||||
const [request] = await rows<{
|
||||
state: string;
|
||||
period: string;
|
||||
budget_period: string;
|
||||
estimate_reserved: number;
|
||||
}>(
|
||||
"SELECT state,DATE_FORMAT(period,'%Y-%m-%d') period,DATE_FORMAT(budget_period,'%Y-%m-%d') budget_period,estimate_reserved FROM dh_growth_requests WHERE account=? AND request_id=? FOR UPDATE",
|
||||
[account, requestId],
|
||||
c,
|
||||
);
|
||||
if (!request || request.state !== "reserved") return;
|
||||
const cost = Math.min(
|
||||
Math.max(0, Math.ceil(characters)),
|
||||
request.estimate_reserved,
|
||||
);
|
||||
await write(
|
||||
"UPDATE dh_growth_quota SET reserved=GREATEST(0,reserved-1),used=used+? WHERE account=? AND period=?",
|
||||
[hasOutput ? 1 : 0, account, request.period],
|
||||
c,
|
||||
);
|
||||
await write(
|
||||
"UPDATE dh_growth_capacity SET in_flight=GREATEST(0,in_flight-1) WHERE id=1",
|
||||
[],
|
||||
c,
|
||||
);
|
||||
await write(
|
||||
"UPDATE dh_growth_budget SET reserved=GREATEST(0,reserved-?),used=used+? WHERE period=?",
|
||||
[request.estimate_reserved, cost, request.budget_period],
|
||||
c,
|
||||
);
|
||||
await write(
|
||||
"UPDATE dh_growth_requests SET state=?,estimate_used=?,outcome=?,first_token_ms=?,duration_ms=? WHERE account=? AND request_id=?",
|
||||
[
|
||||
hasOutput ? "consumed" : "released",
|
||||
cost,
|
||||
outcome,
|
||||
firstTokenMs,
|
||||
durationMs,
|
||||
account,
|
||||
requestId,
|
||||
],
|
||||
c,
|
||||
);
|
||||
}
|
||||
/** 进程重启后回收超时预占;已有持久化的部分回复仍计一次,避免通过断线刷额度。 */
|
||||
export async function recoverExpiredReservations() {
|
||||
const stale = await rows<{
|
||||
account: string;
|
||||
request_id: string;
|
||||
estimate_reserved: number;
|
||||
}>(
|
||||
"SELECT account,request_id,estimate_reserved FROM dh_growth_requests WHERE state='reserved' AND expires_at<NOW(3) LIMIT 100",
|
||||
);
|
||||
for (const r of stale)
|
||||
await transaction(async (c) => {
|
||||
const [saved] = await rows<{ n: number }>(
|
||||
"SELECT COALESCE(MAX(CHAR_LENGTH(m.content)),0) n FROM dh_messages m JOIN dh_conversations d ON d.id=m.conversation_id WHERE d.account=? AND m.request_id=? AND m.role='assistant'",
|
||||
[r.account, r.request_id],
|
||||
c,
|
||||
);
|
||||
await settleReply(
|
||||
r.account,
|
||||
r.request_id,
|
||||
"expired",
|
||||
r.estimate_reserved,
|
||||
!!saved?.n,
|
||||
null,
|
||||
180000,
|
||||
c,
|
||||
);
|
||||
});
|
||||
await write("DELETE FROM dh_growth_limits WHERE expires_at<NOW(3) LIMIT 500");
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
@@ -0,0 +1,260 @@
|
||||
/** 增长配置、匿名身份和事件写入;所有账号来源均为已校验令牌。 */
|
||||
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,
|
||||
);
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,476 @@
|
||||
/** 已鉴权增长路由:运营指标与配置仅后台可见,前台只管理本人权益、记忆和反馈。 */
|
||||
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",
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
Reference in New Issue
Block a user