feat(growth): 建立C端增长与权益服务闭环
- growth模块:新增游客承接、行为漏斗、推荐实验和站内生命周期运营 - 额度账本:事务预占、幂等结算、全站并发与字符预算保护 - 聊天与记忆:接入回答反馈、可控记忆和持久化异步提取 - 迁移020与回归:覆盖账号隔离、计数器死锁和真实MySQL并发场景
This commit is contained in:
@@ -0,0 +1,390 @@
|
||||
/** 显式选择的一次性本地MySQL集成回归:禁止远端地址,数据库名称必须带codex_growth_前缀。 */
|
||||
import test from "node:test";
|
||||
import assert from "node:assert/strict";
|
||||
import { randomUUID } from "node:crypto";
|
||||
import { readFile } from "node:fs/promises";
|
||||
import { createConnection } from "mysql2/promise";
|
||||
import type { RowDataPacket } from "mysql2/promise";
|
||||
|
||||
test(
|
||||
"MySQL8事务:最后一次额度并发、幂等结算、游客承接、记忆删除和分析SQL",
|
||||
{ skip: !process.env.GROWTH_MYSQL_URL },
|
||||
async (t) => {
|
||||
const url = new URL(process.env.GROWTH_MYSQL_URL!);
|
||||
assert.ok(
|
||||
["127.0.0.1", "localhost"].includes(url.hostname),
|
||||
"集成测试仅允许本机数据库",
|
||||
);
|
||||
const database = url.pathname.slice(1);
|
||||
assert.match(database, /^codex_growth_[a-z0-9_]+$/);
|
||||
const connection = await createConnection({
|
||||
host: url.hostname,
|
||||
port: Number(url.port || 3306),
|
||||
user: decodeURIComponent(url.username),
|
||||
password: decodeURIComponent(url.password),
|
||||
multipleStatements: true,
|
||||
});
|
||||
const [existing] = await connection.query(
|
||||
"SELECT SCHEMA_NAME FROM information_schema.SCHEMATA WHERE SCHEMA_NAME=?",
|
||||
[database],
|
||||
);
|
||||
assert.equal(
|
||||
(existing as unknown[]).length,
|
||||
0,
|
||||
"测试必须新建自己的数据库,不能复用已有库",
|
||||
);
|
||||
await connection.query(
|
||||
`CREATE DATABASE \`${database}\` CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci`,
|
||||
);
|
||||
t.after(async () => {
|
||||
await connection.query(`DROP DATABASE \`${database}\``);
|
||||
await connection.end();
|
||||
});
|
||||
await connection.query(`USE \`${database}\``);
|
||||
for (const file of [
|
||||
"009_digital_humans.sql",
|
||||
"018_digital_conversation_soft_delete.sql",
|
||||
"019_conversation_management.sql",
|
||||
"020_digital_growth.sql",
|
||||
])
|
||||
await connection.query(
|
||||
await readFile(
|
||||
new URL(`../migrations/${file}`, import.meta.url),
|
||||
"utf8",
|
||||
),
|
||||
);
|
||||
await connection.query(
|
||||
"CREATE TABLE dh_users(id BIGINT PRIMARY KEY,created_at DATETIME(3) DEFAULT CURRENT_TIMESTAMP(3)); INSERT INTO dh_users(id) VALUES (7),(8),(9),(10),(11),(12),(13),(14),(15)",
|
||||
);
|
||||
Object.assign(process.env, {
|
||||
DB_HOST: url.hostname,
|
||||
DB_PORT: String(url.port || 3306),
|
||||
DB_USER: decodeURIComponent(url.username),
|
||||
DB_PASSWORD: decodeURIComponent(url.password),
|
||||
DB_NAME: database,
|
||||
JWT_SECRET: "growth-local-integration-only-not-for-production",
|
||||
});
|
||||
const { pool } = await import("../src/db/pool");
|
||||
t.after(() => pool.end());
|
||||
const { transaction } = await import(
|
||||
"../src/modules/digital/digital.repository"
|
||||
);
|
||||
const {
|
||||
entitlement,
|
||||
reserveReply,
|
||||
settleReply,
|
||||
recoverExpiredReservations,
|
||||
} = await import("../src/modules/digital/growth/growth.quota");
|
||||
const { createGuest, mergeGuest, identity } = await import(
|
||||
"../src/modules/digital/growth/growth.repository"
|
||||
);
|
||||
const { scheduleMemory, processMemoryJobs, contextMemories } = await import(
|
||||
"../src/modules/digital/growth/growth.memory"
|
||||
);
|
||||
const { recommend } = await import(
|
||||
"../src/modules/digital/growth/growth.recommendations"
|
||||
);
|
||||
const { growthOverview } = await import(
|
||||
"../src/modules/digital/growth/growth.analytics"
|
||||
);
|
||||
const { campaignInbox } = await import(
|
||||
"../src/modules/digital/growth/growth.campaigns"
|
||||
);
|
||||
await connection.query("UPDATE dh_growth_config SET body=? WHERE id=1", [
|
||||
JSON.stringify({ freeDaily: 1, guestLifetime: 2 }),
|
||||
]);
|
||||
await t.test(
|
||||
"两个并发请求争抢最后一次额度只能成功一个,失败事务不占容量",
|
||||
async () => {
|
||||
const rights = await entitlement("user:7"),
|
||||
ids = [randomUUID(), randomUUID()];
|
||||
const result = await Promise.allSettled(
|
||||
ids.map((id) =>
|
||||
transaction((c) =>
|
||||
reserveReply("user:7", "story", id, 30000, rights, c),
|
||||
),
|
||||
),
|
||||
);
|
||||
assert.equal(result.filter((r) => r.status === "fulfilled").length, 1);
|
||||
const [quota] = await connection.query<RowDataPacket[]>(
|
||||
"SELECT used,reserved FROM dh_growth_quota WHERE account=?",
|
||||
["user:7"],
|
||||
);
|
||||
assert.equal(quota[0].reserved, 1);
|
||||
const winner = ids[result.findIndex((r) => r.status === "fulfilled")];
|
||||
for (let i = 0; i < 2; i++)
|
||||
await transaction((c) =>
|
||||
settleReply("user:7", winner, "failed", 100, false, null, 10, c),
|
||||
);
|
||||
assert.equal((await entitlement("user:7")).remaining, 1);
|
||||
const next = randomUUID(),
|
||||
freshRights = await entitlement("user:7");
|
||||
await transaction((c) =>
|
||||
reserveReply("user:7", "story", next, 30000, freshRights, c),
|
||||
);
|
||||
for (let i = 0; i < 2; i++)
|
||||
await transaction((c) =>
|
||||
settleReply("user:7", next, "stopped", 300, true, 20, 100, c),
|
||||
);
|
||||
assert.equal((await entitlement("user:7")).remaining, 0);
|
||||
},
|
||||
);
|
||||
// 后续使用更新后的真实权益,不能在事务回调内偷偷使用过期快照。
|
||||
await t.test("部分回复计次,重复结算不多扣,超时预占可回收", async () => {
|
||||
const request = randomUUID(),
|
||||
freshRights = await entitlement("user:8");
|
||||
await transaction((c) =>
|
||||
reserveReply("user:8", "empty-story", request, 30000, freshRights, c),
|
||||
);
|
||||
await connection.query(
|
||||
"UPDATE dh_growth_requests SET expires_at=DATE_SUB(NOW(3),INTERVAL 1 SECOND) WHERE account=? AND request_id=?",
|
||||
["user:8", request],
|
||||
);
|
||||
await recoverExpiredReservations();
|
||||
assert.equal((await entitlement("user:8")).remaining, 1);
|
||||
});
|
||||
await t.test(
|
||||
"游客登录承接故事、用量与稳定推荐身份,重复承接不重复累计",
|
||||
async () => {
|
||||
const guest = await createGuest(),
|
||||
subject = (await identity(guest)).subject,
|
||||
conversation = randomUUID(),
|
||||
request = randomUUID();
|
||||
await connection.query(
|
||||
"INSERT INTO dh_conversations(id,account,character_id,title,settings) VALUES (?,?,?,'体验故事',JSON_OBJECT())",
|
||||
[conversation, guest, "card"],
|
||||
);
|
||||
const rights = await entitlement(guest);
|
||||
await transaction((c) =>
|
||||
reserveReply(guest, conversation, request, 30000, rights, c),
|
||||
);
|
||||
await transaction((c) =>
|
||||
settleReply(guest, request, "stopped", 500, true, 20, 200, c),
|
||||
);
|
||||
await mergeGuest(guest, "user:9");
|
||||
await mergeGuest(guest, "user:9");
|
||||
assert.equal((await identity("user:9")).subject, subject);
|
||||
await assert.rejects(identity(guest));
|
||||
assert.equal((await entitlement("user:9")).used, 1);
|
||||
const [chats] = await connection.query<RowDataPacket[]>(
|
||||
"SELECT account FROM dh_conversations WHERE id=?",
|
||||
[conversation],
|
||||
);
|
||||
assert.equal(chats[0].account, "user:9");
|
||||
},
|
||||
);
|
||||
await t.test("自动提取后删除的来源事实不会被后续任务重新创建", async () => {
|
||||
const story = randomUUID(),
|
||||
userMessage = randomUUID(),
|
||||
assistant = randomUUID();
|
||||
await connection.query(
|
||||
"UPDATE dh_growth_identities SET auto_memory=TRUE WHERE account='user:9'",
|
||||
);
|
||||
await connection.query(
|
||||
"INSERT INTO dh_conversations(id,account,character_id,title,settings) VALUES (?,'user:9','card','记忆测试',JSON_OBJECT())",
|
||||
[story],
|
||||
);
|
||||
await connection.query(
|
||||
"INSERT INTO dh_messages(id,conversation_id,role,content) VALUES (?,?,'user','请记住:周六一起看灯塔'),(?,?,'assistant','约好了')",
|
||||
[userMessage, story, assistant, story],
|
||||
);
|
||||
await scheduleMemory("user:9", story, assistant);
|
||||
await processMemoryJobs();
|
||||
assert.match(await contextMemories("user:9", story, "灯塔"), /周六/);
|
||||
await connection.query(
|
||||
"UPDATE dh_growth_memories SET deleted_at=NOW(3) WHERE account='user:9' AND conversation_id=?",
|
||||
[story],
|
||||
);
|
||||
const next = randomUUID();
|
||||
await connection.query(
|
||||
"INSERT INTO dh_messages(id,conversation_id,role,content) VALUES (?,?,'assistant','继续故事')",
|
||||
[next, story],
|
||||
);
|
||||
await scheduleMemory("user:9", story, next);
|
||||
await processMemoryJobs();
|
||||
assert.equal(await contextMemories("user:9", story, "灯塔"), "");
|
||||
});
|
||||
|
||||
await t.test(
|
||||
"不同账号并发争抢全站4个容量,拒绝必须来自业务保护",
|
||||
async () => {
|
||||
const accounts = [
|
||||
"user:10",
|
||||
"user:11",
|
||||
"user:12",
|
||||
"user:13",
|
||||
"user:14",
|
||||
];
|
||||
const rights = await Promise.all(accounts.map(entitlement)),
|
||||
ids = accounts.map(() => randomUUID());
|
||||
const result = await Promise.allSettled(
|
||||
accounts.map((account, i) =>
|
||||
transaction((c) =>
|
||||
reserveReply(account, "parallel", ids[i], 30000, rights[i], c),
|
||||
),
|
||||
),
|
||||
);
|
||||
assert.equal(result.filter((r) => r.status === "fulfilled").length, 4);
|
||||
for (const r of result)
|
||||
if (r.status === "rejected")
|
||||
assert.equal(r.reason.code, "MODEL_BUSY");
|
||||
for (let i = 0; i < result.length; i++)
|
||||
if (result[i].status === "fulfilled")
|
||||
await transaction((c) =>
|
||||
settleReply(accounts[i], ids[i], "failed", 0, false, null, 0, c),
|
||||
);
|
||||
},
|
||||
);
|
||||
await t.test("会员并发2次上限,三请求争抢不能以死锁冒充限流", async () => {
|
||||
await identity("user:15");
|
||||
await connection.query(
|
||||
"UPDATE dh_growth_identities SET member_until=DATE_ADD(NOW(3),INTERVAL 1 DAY) WHERE account='user:15'",
|
||||
);
|
||||
for (let round = 0; round < 3; round++) {
|
||||
const rights = await entitlement("user:15");
|
||||
assert.equal(rights.tier, "member");
|
||||
const ids = Array.from({ length: 3 }, () => randomUUID());
|
||||
const result = await Promise.allSettled(
|
||||
ids.map((id) =>
|
||||
transaction((c) =>
|
||||
reserveReply("user:15", "parallel", id, 30000, rights, c),
|
||||
),
|
||||
),
|
||||
);
|
||||
assert.equal(result.filter((r) => r.status === "fulfilled").length, 2);
|
||||
for (const r of result)
|
||||
if (r.status === "rejected")
|
||||
assert.equal(r.reason.code, "ACCOUNT_BUSY");
|
||||
for (let i = 0; i < result.length; i++)
|
||||
if (result[i].status === "fulfilled")
|
||||
await transaction((c) =>
|
||||
settleReply("user:15", ids[i], "failed", 0, false, null, 0, c),
|
||||
);
|
||||
}
|
||||
});
|
||||
await t.test("真实推荐与分析SQL可执行,活动频控不重复分配", async () => {
|
||||
await connection.query(
|
||||
"INSERT INTO dh_content(id,kind,name,status,body) VALUES ('card','character','角色','published',?)",
|
||||
[JSON.stringify({ tags: ["科幻"] })],
|
||||
);
|
||||
assert.equal((await recommend("user:9")).items[0].id, "card");
|
||||
const campaign = randomUUID();
|
||||
await connection.query(
|
||||
"INSERT INTO dh_growth_campaigns(id,title,content,segment,enabled,holdout_percent,starts_at,ends_at) VALUES (?,'欢迎','继续故事','new',TRUE,0,DATE_SUB(NOW(3),INTERVAL 1 DAY),DATE_ADD(NOW(3),INTERVAL 1 DAY))",
|
||||
[campaign],
|
||||
);
|
||||
assert.equal((await campaignInbox("user:9")).length, 1);
|
||||
assert.equal((await campaignInbox("user:9")).length, 1);
|
||||
const [deliveries] = await connection.query<RowDataPacket[]>(
|
||||
"SELECT COUNT(*) n FROM dh_growth_deliveries WHERE account='user:9'",
|
||||
);
|
||||
assert.equal(deliveries[0].n, 1);
|
||||
assert.equal((await growthOverview(14)).days, 14);
|
||||
});
|
||||
await t.test(
|
||||
"真实路由并发赠送只生效一次,事件补报去重并保存发生时间",
|
||||
async (sub) => {
|
||||
const { createApp } = await import("../src/app");
|
||||
const { authService } = await import(
|
||||
"../src/modules/auth/auth.service"
|
||||
);
|
||||
sub.mock.method(
|
||||
authService,
|
||||
"getCurrentUser",
|
||||
async (payload: { accountType: string }) => ({
|
||||
accountType: payload.accountType,
|
||||
permissions: [],
|
||||
}),
|
||||
);
|
||||
const app = createApp();
|
||||
await app.ready();
|
||||
try {
|
||||
await connection.query("INSERT INTO dh_users(id) VALUES (16)");
|
||||
const adminToken = app.jwt.sign({
|
||||
sub: "super_admin:1",
|
||||
accountType: "SUPER_ADMIN",
|
||||
scene: "MANAGEMENT",
|
||||
}),
|
||||
headers = { authorization: `Bearer ${adminToken}` },
|
||||
requestId = randomUUID();
|
||||
const payload = {
|
||||
userId: 16,
|
||||
requestId,
|
||||
days: 30,
|
||||
reason: "本地集成测试赠送",
|
||||
};
|
||||
const results = await Promise.all(
|
||||
Array.from({ length: 3 }, () =>
|
||||
app.inject({
|
||||
method: "POST",
|
||||
url: "/api/digital-admin/growth/entitlements",
|
||||
headers,
|
||||
payload,
|
||||
}),
|
||||
),
|
||||
);
|
||||
for (const response of results)
|
||||
assert.equal(response.statusCode, 200, response.body);
|
||||
const [audit] = await connection.query<RowDataPacket[]>(
|
||||
"SELECT COUNT(*) n FROM dh_audits WHERE action='growth.entitlement' AND target=?",
|
||||
[requestId],
|
||||
);
|
||||
assert.equal(audit[0].n, 1);
|
||||
const [user] = await connection.query<RowDataPacket[]>(
|
||||
"SELECT TIMESTAMPDIFF(DAY,NOW(3),member_until) days FROM dh_growth_identities WHERE account='user:16'",
|
||||
);
|
||||
assert.ok(Number(user[0].days) >= 29 && Number(user[0].days) <= 30);
|
||||
assert.equal(
|
||||
(
|
||||
await app.inject({
|
||||
method: "POST",
|
||||
url: "/api/digital-admin/growth/entitlements",
|
||||
headers,
|
||||
payload: { ...payload, days: 31 },
|
||||
})
|
||||
).statusCode,
|
||||
409,
|
||||
);
|
||||
const token = app.jwt.sign({
|
||||
sub: "user:16",
|
||||
accountType: "DIGITAL_USER",
|
||||
scene: "DIGITAL_APP",
|
||||
}),
|
||||
eventId = randomUUID(),
|
||||
occurredAt = Date.now() - 5000;
|
||||
const batch = {
|
||||
account: "user:16",
|
||||
events: [
|
||||
{
|
||||
id: eventId,
|
||||
event: "page_view",
|
||||
entity: "discover",
|
||||
occurredAt,
|
||||
},
|
||||
],
|
||||
};
|
||||
for (let n = 0; n < 2; n++)
|
||||
assert.equal(
|
||||
(
|
||||
await app.inject({
|
||||
method: "POST",
|
||||
url: "/api/digital/growth/events",
|
||||
headers: { authorization: `Bearer ${token}` },
|
||||
payload: batch,
|
||||
})
|
||||
).statusCode,
|
||||
200,
|
||||
);
|
||||
const [events] = await connection.query<RowDataPacket[]>(
|
||||
"SELECT UNIX_TIMESTAMP(occurred_at)*1000 happenedAt FROM dh_growth_events WHERE id=?",
|
||||
[eventId],
|
||||
);
|
||||
assert.equal(events.length, 1);
|
||||
assert.ok(Math.abs(Number(events[0].happenedAt) - occurredAt) < 2);
|
||||
} finally {
|
||||
await app.close();
|
||||
}
|
||||
},
|
||||
);
|
||||
},
|
||||
);
|
||||
Reference in New Issue
Block a user