mirror of
https://github.com/margrop/wrong-notebook.git
synced 2026-12-07 03:57:32 +08:00
- 批量编辑、移动、删除按每批 100 条提交,返回逐条结果;界面显示进度,可取消并重试失败项 - 批量编辑支持统一替换知识点标签,逐题事务写入,单题失败不影响其他条目 - 多选栏新增「全选筛选结果」,跨页选中最多 2000 道错题;列表新增只读 id 的全选接口 - 备份与题目导出按批读取,千级数据不一次性载入全部原图等大字段 - 新增千级批量基准脚本与文档,补充单元、集成测试 Refs: https://github.com/margrop/wrong-notebook/issues/66
206 lines
7.6 KiB
JavaScript
206 lines
7.6 KiB
JavaScript
/**
|
|
* 千级批量操作基准:在临时 SQLite 库中按当前 schema 建库并写入合成错题,
|
|
* 测量「全选 id、批量改来源/移动/删除、按批导出、薄弱知识点按批读取」的服务端等价耗时。
|
|
*
|
|
* 用法:node scripts/bench-bulk-ops.mjs [--rounds 10] [--count 1000]
|
|
* 临时库在系统临时目录,结束后删除,不写入仓库。
|
|
*/
|
|
import { execFileSync } from 'node:child_process';
|
|
import { cpSync, mkdtempSync, rmSync } from 'node:fs';
|
|
import { tmpdir } from 'node:os';
|
|
import { join, resolve } from 'node:path';
|
|
import { PrismaClient } from '@prisma/client';
|
|
|
|
const PRISMA_CLI = resolve('node_modules/prisma/build/index.js');
|
|
const SCHEMA = resolve('prisma/schema.prisma');
|
|
const BATCH = 100;
|
|
const SEED_CHUNK = 500;
|
|
const STATS_BATCH = 500;
|
|
|
|
function parseArgs() {
|
|
const args = process.argv.slice(2);
|
|
const rounds = Number(args[args.indexOf('--rounds') + 1] || 10);
|
|
const count = Number(args[args.indexOf('--count') + 1] || 1000);
|
|
return {
|
|
rounds: Number.isFinite(rounds) && rounds > 0 ? rounds : 10,
|
|
count: Number.isFinite(count) && count > 0 ? count : 1000,
|
|
};
|
|
}
|
|
|
|
function createDatabase(directory) {
|
|
const databasePath = join(directory, 'bench.db');
|
|
const schemaPath = join(directory, 'schema.prisma');
|
|
cpSync(SCHEMA, schemaPath);
|
|
execFileSync(process.execPath, [PRISMA_CLI, 'db', 'push', '--schema', schemaPath, '--skip-generate'], {
|
|
env: { ...process.env, DATABASE_URL: 'file:' + databasePath },
|
|
encoding: 'utf8',
|
|
stdio: 'pipe',
|
|
timeout: 120_000,
|
|
});
|
|
return databasePath;
|
|
}
|
|
|
|
function percentile(values, ratio) {
|
|
const sorted = [...values].sort((left, right) => left - right);
|
|
const index = Math.min(sorted.length - 1, Math.max(0, Math.ceil(sorted.length * ratio) - 1));
|
|
return sorted[index];
|
|
}
|
|
|
|
async function seed(prisma, total) {
|
|
const data = [];
|
|
const base = Date.parse('2026-01-01T00:00:00Z');
|
|
for (let index = 0; index < total; index++) {
|
|
data.push({
|
|
id: `bulk-item-${index}`,
|
|
userId: 'bulk-user',
|
|
subjectId: 'bulk-subject',
|
|
originalImageUrl: 'bench-image',
|
|
questionText: `批量题目 ${index}`,
|
|
createdAt: new Date(base + index * 60_000),
|
|
});
|
|
}
|
|
for (let start = 0; start < data.length; start += SEED_CHUNK) {
|
|
await prisma.errorItem.createMany({ data: data.slice(start, start + SEED_CHUNK) });
|
|
}
|
|
}
|
|
|
|
/** 与接口等价的按批 id 列表 */
|
|
async function allIds(prisma) {
|
|
return (await prisma.errorItem.findMany({
|
|
where: { userId: 'bulk-user' },
|
|
orderBy: { id: 'asc' },
|
|
select: { id: true },
|
|
})).map((row) => row.id);
|
|
}
|
|
|
|
function chunks(ids) {
|
|
const result = [];
|
|
for (let start = 0; start < ids.length; start += BATCH) result.push(ids.slice(start, start + BATCH));
|
|
return result;
|
|
}
|
|
|
|
async function measure(prisma, ids, rounds) {
|
|
const timings = {};
|
|
const record = (name, startedAt) => {
|
|
(timings[name] ??= []).push(Number(process.hrtime.bigint() - startedAt) / 1e6);
|
|
};
|
|
|
|
for (let round = 0; round < rounds; round++) {
|
|
let startedAt = process.hrtime.bigint();
|
|
await prisma.errorItem.findMany({
|
|
where: { userId: 'bulk-user' },
|
|
orderBy: { id: 'asc' },
|
|
select: { id: true },
|
|
});
|
|
record('selectAllIds', startedAt);
|
|
|
|
startedAt = process.hrtime.bigint();
|
|
for (const chunk of chunks(ids)) {
|
|
await prisma.errorItem.updateMany({
|
|
where: { id: { in: chunk }, userId: 'bulk-user' },
|
|
data: { source: `批量来源 ${round}` },
|
|
});
|
|
}
|
|
record('batchUpdateSource', startedAt);
|
|
|
|
startedAt = process.hrtime.bigint();
|
|
for (const chunk of chunks(ids)) {
|
|
await prisma.errorItem.updateMany({
|
|
where: { id: { in: chunk }, userId: 'bulk-user' },
|
|
data: { subjectId: 'bulk-subject' },
|
|
});
|
|
}
|
|
record('batchMove', startedAt);
|
|
|
|
startedAt = process.hrtime.bigint();
|
|
for (const chunk of chunks(ids)) {
|
|
await prisma.errorItem.findMany({
|
|
where: { id: { in: chunk }, userId: 'bulk-user' },
|
|
select: {
|
|
id: true,
|
|
questionText: true,
|
|
answerText: true,
|
|
analysis: true,
|
|
wrongAnswerText: true,
|
|
figureSvg: true,
|
|
originalImageUrl: true,
|
|
},
|
|
});
|
|
}
|
|
record('exportQuestionsRead', startedAt);
|
|
|
|
startedAt = process.hrtime.bigint();
|
|
for (let start = 0; start < ids.length; start += STATS_BATCH) {
|
|
await prisma.errorItem.findMany({
|
|
where: { userId: 'bulk-user' },
|
|
orderBy: [{ createdAt: 'asc' }, { id: 'asc' }],
|
|
skip: start,
|
|
take: STATS_BATCH,
|
|
select: {
|
|
id: true,
|
|
subjectId: true,
|
|
masteryProbability: true,
|
|
tags: { select: { name: true, tagSet: true } },
|
|
_count: { select: { practiceRecords: { where: { result: { not: null } } } } },
|
|
},
|
|
});
|
|
}
|
|
record('weakTagsRead', startedAt);
|
|
}
|
|
|
|
return Object.fromEntries(Object.entries(timings).map(([name, values]) => [
|
|
name,
|
|
{
|
|
p50: percentile(values, 0.5),
|
|
p75: percentile(values, 0.75),
|
|
p95: percentile(values, 0.95),
|
|
},
|
|
]));
|
|
}
|
|
|
|
async function main() {
|
|
const { rounds, count } = parseArgs();
|
|
const directory = mkdtempSync(join(tmpdir(), 'wrong-notebook-bulk-bench-'));
|
|
const databasePath = createDatabase(directory);
|
|
const prisma = new PrismaClient({ datasources: { db: { url: 'file:' + databasePath } } });
|
|
try {
|
|
await prisma.user.create({ data: { id: 'bulk-user', email: 'bulk@example.com', password: 'bench-only' } });
|
|
await prisma.subject.create({
|
|
data: { id: 'bulk-subject', name: '基准数学', userId: 'bulk-user', subjectKey: 'math' },
|
|
});
|
|
await seed(prisma, count);
|
|
const ids = await allIds(prisma);
|
|
const result = await measure(prisma, ids, rounds);
|
|
|
|
console.log(`批量操作基准:${count} 道,${rounds} 轮,每批 ${BATCH} 条`);
|
|
console.log('| 场景 | p50 | p75 | p95 |');
|
|
console.log('|---|---:|---:|---:|');
|
|
const labels = {
|
|
selectAllIds: '全选筛选 id(一次只读 id)',
|
|
batchUpdateSource: '按批改来源(10 批)',
|
|
batchMove: '按批移动(10 批)',
|
|
exportQuestionsRead: '按批读取导出字段(10 批)',
|
|
weakTagsRead: '薄弱知识点按批读取',
|
|
};
|
|
for (const [name, value] of Object.entries(result)) {
|
|
console.log(`| ${labels[name]} | ${value.p50.toFixed(2)} | ${value.p75.toFixed(2)} | ${value.p95.toFixed(2)} |`);
|
|
}
|
|
|
|
// 最后按批删除,验证千级删除路径
|
|
const deleteStartedAt = process.hrtime.bigint();
|
|
for (const chunk of chunks(ids)) {
|
|
await prisma.errorItem.deleteMany({ where: { id: { in: chunk }, userId: 'bulk-user' } });
|
|
}
|
|
const deleteMs = Number(process.hrtime.bigint() - deleteStartedAt) / 1e6;
|
|
console.log(`按批删除全部 ${ids.length} 道:${deleteMs.toFixed(2)} ms`);
|
|
} finally {
|
|
await prisma.$disconnect();
|
|
rmSync(directory, { recursive: true, force: true });
|
|
}
|
|
}
|
|
|
|
main().catch((error) => {
|
|
console.error(error);
|
|
process.exit(1);
|
|
});
|