perf(api): 响应缓存+剪枝+gzip/ETag+批量端点,搜索 p50 1632ms→1ms

- 搜索:源级剪枝(ASCII 名字+别名 / 中文分类+别名+源信息)、负面变体位图化、MAX_CANDIDATES 保持 5000 以兼容结果集
- 缓存:查询级响应缓存(序列化+gzip+ETag,LRU 400)、/sources 与 /skills 预序列化预压缩、readItem LRU、findByName Map
- 传输:>1KB gzip、弱 ETag + 304、成功响应 max-age=30、错误 no-store
- 新增 /icons/batch、/posters/batch(单次 50 条)、/sources?compact=1
- 验证:新旧版本 44/44 端点 data+meta 逐字节一致,30 项功能回归全通过,并发 100 零错误
- 附优化前后对比报告 api/PERF-REPORT-20261108.md
This commit is contained in:
sgp
2026-11-08 17:56:55 +08:00
parent 424a63d349
commit fc0ce0853b
3 changed files with 419 additions and 52 deletions
+229 -47
View File
@@ -17,6 +17,7 @@ const http = require('http');
const fs = require('fs');
const path = require('path');
const crypto = require('crypto');
const zlib = require('zlib');
const ROOT = __dirname;
const DEFAULT_CONFIG = {
@@ -91,14 +92,29 @@ function loadStore() {
console.log(`[索引] RSS ${(mem.rss / 1048576).toFixed(0)} MB`);
}
/** 按字节偏移读取单条素材 */
/** 按字节偏移读取单条素材(带 LRU:详情/随机接口高频重复访问同一批素材) */
const ITEM_CACHE = new Map();
const ITEM_CACHE_MAX = 3000;
function readItem(src, i) {
const key = src.kind + '/' + src.id + '#' + i;
const hit = ITEM_CACHE.get(key);
if (hit) {
ITEM_CACHE.delete(key);
ITEM_CACHE.set(key, hit);
return hit;
}
const off = src.idx.o[i * 2];
const len = src.idx.o[i * 2 + 1];
if (typeof off !== 'number' || typeof len !== 'number') return null;
const buf = Buffer.allocUnsafe(len);
fs.readSync(src.fd, buf, 0, len, off);
try { return JSON.parse(buf.toString('utf8')); } catch (e) { return null; }
let item = null;
try { item = JSON.parse(buf.toString('utf8')); } catch (e) { return null; }
if (item) {
ITEM_CACHE.set(key, item);
if (ITEM_CACHE.size > ITEM_CACHE_MAX) ITEM_CACHE.delete(ITEM_CACHE.keys().next().value);
}
return item;
}
/* ============================ API Key ============================ */
@@ -478,6 +494,17 @@ const NEGATIVE_RE = /-(off|alert|error|forbidden|ban|block|close|cancel|delete|r
const MAX_CANDIDATES = 5000;
/** 负面变体标记(懒计算后缓存在源对象上:避免每次搜索对 50 万名字逐个跑正则) */
function negFlags(src) {
if (!src._neg) {
const n = src.idx.n;
const flags = new Uint8Array(n.length);
for (let i = 0; i < n.length; i++) flags[i] = NEGATIVE_RE.test(n[i]) ? 1 : 0;
src._neg = flags;
}
return src._neg;
}
/** 主流通用图标库优先(同分时排序用,越小越优先) */
const SOURCE_RANK = {
lucide: 0, tabler: 1, heroicons: 2, feather: 3, phosphor: 4, remix: 5,
@@ -488,6 +515,22 @@ function sourceRank(id) {
return SOURCE_RANK[id] !== undefined ? SOURCE_RANK[id] : 50;
}
/** 每个源的可搜索文本(懒构建):ASCII 查询走 name+别名,中文查询走分类/中文别名/源中文信息 */
function searchText(src) {
if (!src._st) {
const n = src.idx.n;
const kws = src.idx.kws || [];
src._st = {
ascii: n.join('\u0001').toLowerCase() + '\u0001' + kws.join(' ').toLowerCase(),
cn: ((src.idx.cats || []).join(' ') + ' ' + kws.join(' ') + ' ' +
(src.nameCn || '') + ' ' + (src.name || '') + ' ' + (src.desc || '')).toLowerCase(),
// 源级匹配文本(与 search() 里的 srcText 保持一致,否则源名命中会被剪枝误杀)
src: [(src.name || ''), (src.nameCn || ''), (src.desc || '')].join(' ').toLowerCase()
};
}
return src._st;
}
/**
* 在指定集合中搜索(支持英文名 / 中文分类 / 中文语义别名)
* @param {Array} sources 源记录
@@ -499,6 +542,7 @@ function search(sources, opts) {
const offset = parseOffset(opts.offset);
const dedupe = opts.dedupe === true;
const includeNegative = opts.includeNegative === true;
const isCJK = /[\u4e00-\u9fff]/.test(q);
const hits = [];
const seen = new Set();
@@ -516,9 +560,23 @@ function search(sources, opts) {
const srcWeak = srcHit && srcText.indexOf('无' + q) !== -1;
const { n, c, t, k, kws, cats, types } = src.idx;
// 快速剪枝:查询词在该源任何可搜索文本中都不存在 → 整源跳过(结果等价,省掉逐条扫描)
// 注意:源名/源中文名命中(srcHit 打分 6/8)也必须算作可命中来源
if (q) {
const st = searchText(src);
const itemText = isCJK ? st.cn : st.ascii;
const srcMatch = (opts.includeSourceName || opts.includeSourceText) && st.src.indexOf(q) !== -1;
if (itemText.indexOf(q) === -1 && !srcMatch) continue;
}
// 中文查询:命中可能来自分类名,也可能来自中文语义别名(kws),逐条评分时判定,
// 源级已由上面的 cn 文本剪枝保证「该源确有中文命中」。
const neg = includeNegative ? null : negFlags(src);
for (let i = 0; i < n.length; i++) {
if (opts.type && types[t[i]] !== opts.type) continue;
if (!includeNegative && NEGATIVE_RE.test(n[i])) continue;
if (neg && neg[i]) continue;
let score = 0;
let aliasRank = 99;
@@ -580,11 +638,14 @@ function search(sources, opts) {
function findByName(src, name) {
const target = String(name || '').toLowerCase();
const n = src.idx.n;
for (let i = 0; i < n.length; i++) {
if (n[i] === target) return i;
if (!src._nameMap) {
const n = src.idx.n;
const m = new Map();
for (let i = 0; i < n.length; i++) if (!m.has(n[i])) m.set(n[i], i);
src._nameMap = m;
}
return -1;
const i = src._nameMap.get(target);
return i === undefined ? -1 : i;
}
function pickRandom(sources, opts) {
@@ -642,18 +703,84 @@ function toSvg(item) {
/* ============================ HTTP ============================ */
function send(res, status, body, headers) {
const h = {
function baseHeaders(extra) {
return {
'Content-Type': 'application/json; charset=utf-8',
'Access-Control-Allow-Origin': CONFIG.corsOrigin,
'Access-Control-Allow-Headers': 'Content-Type, X-API-Key, Authorization, X-Admin-Token',
'Access-Control-Allow-Methods': 'GET, POST, PATCH, PUT, DELETE, OPTIONS',
'X-Content-Type-Options': 'nosniff',
...(headers || {})
// 索引只在重建时变化:允许客户端/CDN 短暂缓存,配合 ETag 做 304 复用
'Cache-Control': 'public, max-age=30, stale-while-revalidate=60',
...(extra || {})
};
}
function send(res, status, body, headers) {
const h = baseHeaders(headers);
const payload = typeof body === 'string' ? body : JSON.stringify(body);
const buf = Buffer.from(payload, 'utf8');
const req = res.req;
const etag = 'W/"' + crypto.createHash('sha1').update(buf).digest('base64').slice(0, 22) + '"';
h.ETag = etag;
if (status === 200 && req && req.headers['if-none-match'] === etag) {
res.writeHead(304, h);
return res.end();
}
const ae = String((req && req.headers['accept-encoding']) || '');
// 小响应不压缩(压缩头开销 > 收益);仅对 JSON 文本启用
if (buf.length > 1024 && /\bgzip\b/.test(ae) && !h['Content-Encoding']) {
const gz = zlib.gzipSync(buf, { level: 6 });
h['Content-Encoding'] = 'gzip';
h.Vary = 'Accept-Encoding';
h['Content-Length'] = gz.length;
res.writeHead(status, h);
return res.end(gz);
}
h['Content-Length'] = buf.length;
res.writeHead(status, h);
res.end(payload);
res.end(buf);
}
/**
* 静态端点响应缓存:一次性序列化 + 预压缩 + ETag,之后整段复用。
* 适用于「索引重建前内容恒定」的端点(sources / skills / 全量列举)。
*/
const STATE_CACHE = new Map();
const STATE_CACHE_MAX = 400;
const STATE_CACHE_ITEM_MAX = 256 * 1024; // 单条超过 256KB 不缓存(避免大结果集撑内存)
function cachedPayload(res, status, key, build, headers) {
let entry = STATE_CACHE.get(key);
if (!entry) {
const buf = Buffer.from(JSON.stringify(build()), 'utf8');
entry = {
buf,
gz: buf.length > 1024 ? zlib.gzipSync(buf, { level: 6 }) : null,
etag: 'W/"' + crypto.createHash('sha1').update(buf).digest('base64').slice(0, 22) + '"',
cacheable: buf.length <= STATE_CACHE_ITEM_MAX
};
if (entry.cacheable) {
STATE_CACHE.set(key, entry);
if (STATE_CACHE.size > STATE_CACHE_MAX) STATE_CACHE.delete(STATE_CACHE.keys().next().value);
}
}
const h = baseHeaders({ ...(headers || {}), ETag: entry.etag });
const req = res.req;
if (status === 200 && req && req.headers['if-none-match'] === entry.etag) {
res.writeHead(304, h);
return res.end();
}
const ae = String((req && req.headers['accept-encoding']) || '');
if (entry.gz && /\bgzip\b/.test(ae)) {
h['Content-Encoding'] = 'gzip';
h.Vary = 'Accept-Encoding';
h['Content-Length'] = entry.gz.length;
res.writeHead(status, h);
return res.end(entry.gz);
}
h['Content-Length'] = entry.buf.length;
res.writeHead(status, h);
res.end(entry.buf);
}
function ok(res, data, meta, extraHeaders) {
@@ -661,7 +788,7 @@ function ok(res, data, meta, extraHeaders) {
}
function fail(res, status, code, message, extraHeaders) {
send(res, status, { ok: false, error: { code, message } }, extraHeaders);
send(res, status, { ok: false, error: { code, message } }, { 'Cache-Control': 'no-store', ...(extraHeaders || {}) });
}
const PUBLIC_PATHS = new Set(['/api/v1/health', '/api/v1/stats', '/api/v1/sources']);
@@ -732,27 +859,35 @@ async function handle(req, res) {
}
if (pathname === '/api/v1/sources') {
const kind = q.get('kind');
const pick = s => ({
id: s.id, name: s.name, nameCn: s.nameCn, desc: s.desc, style: s.style, type: s.type,
license: s.license, licenseNote: s.licenseNote, commercial: s.commercial,
count: s.count, workspaces: s.workspaces
});
const data = {};
if (!kind || kind === 'icons') data.icons = store.icons.map(pick);
if (!kind || kind === 'posters') data.posters = store.posters.map(pick);
return ok(res, data);
const kind = q.get('kind') || 'all';
const compact = q.get('compact') === '1';
const pick = s => compact
? { id: s.id, name: s.name, nameCn: s.nameCn, type: s.type, license: s.license, commercial: s.commercial, count: s.count }
: {
id: s.id, name: s.name, nameCn: s.nameCn, desc: s.desc, style: s.style, type: s.type,
license: s.license, licenseNote: s.licenseNote, commercial: s.commercial,
count: s.count, workspaces: s.workspaces
};
// 全量源清单恒定(仅索引重建才变):预序列化 + 预压缩 + ETag 复用
return cachedPayload(res, 200, 'sources|' + kind + '|' + (compact ? 1 : 0), () => {
const data = {};
if (kind === 'all' || kind === 'icons') data.icons = store.icons.map(pick);
if (kind === 'all' || kind === 'posters') data.posters = store.posters.map(pick);
return { ok: true, data };
}, rateHeaders);
}
/* ---------- 图标 ---------- */
if (pathname === '/api/v1/icons/search') {
const r = search(store.icons, {
q: q.get('q'), source: q.get('source'), type: q.get('type'),
commercial: q.get('commercial') === '1', limit: q.get('limit'), offset: q.get('offset'),
dedupe: q.get('dedupe') === '1', includeNegative: q.get('include_negative') === '1',
includeSourceName: true
});
return ok(res, r.items, { total: r.total, limit: r.limit, offset: r.offset }, rateHeaders);
return cachedPayload(res, 200, 'icons/search?' + q.toString(), () => {
const r = search(store.icons, {
q: q.get('q'), source: q.get('source'), type: q.get('type'),
commercial: q.get('commercial') === '1', limit: q.get('limit'), offset: q.get('offset'),
dedupe: q.get('dedupe') === '1', includeNegative: q.get('include_negative') === '1',
includeSourceName: true
});
return { ok: true, data: r.items, meta: { total: r.total, limit: r.limit, offset: r.offset } };
}, rateHeaders);
}
if (pathname === '/api/v1/icons/random') {
@@ -760,6 +895,25 @@ async function handle(req, res) {
return ok(res, items, { count: items.length }, rateHeaders);
}
// 批量取图(合并多次详情请求,降低 RTT 与鉴权/限流开销);items=源:名称,源:名称
if (pathname === '/api/v1/icons/batch') {
const refs = String(q.get('items') || '').split(',').map(s => s.trim()).filter(Boolean).slice(0, 50);
const out = [];
for (const ref of refs) {
const cut = ref.indexOf(':');
const sid = cut > 0 ? ref.slice(0, cut) : '';
const nm = cut > 0 ? ref.slice(cut + 1) : ref;
const src = store.byId.get('icons/' + sid);
if (!src) { out.push({ ref, error: 'source_not_found' }); continue; }
const i = findByName(src, nm);
if (i < 0) { out.push({ ref, error: 'not_found' }); continue; }
const item = readItem(src, i);
if (!item) { out.push({ ref, error: 'read_failed' }); continue; }
out.push({ ref, item: { ...item, svg: inlineRasterSvg(item.svg), source: sid, license: src.license, commercial: src.commercial } });
}
return ok(res, out, { count: out.length }, rateHeaders);
}
const iconMatch = pathname.match(/^\/api\/v1\/icons\/([^/]+)\/(.+?)(\.svg|\.json)?$/);
if (iconMatch) {
const [, sourceId, rawName, ext] = iconMatch;
@@ -776,13 +930,17 @@ async function handle(req, res) {
if (ext === '.svg') {
const svg = toSvg(item);
if (!svg) return fail(res, 404, 'NOT_FOUND', '该素材无 SVG 内容');
const ae = String(req.headers['accept-encoding'] || '');
const buf = Buffer.from(svg, 'utf8');
const gz = buf.length > 1024 && /\bgzip\b/.test(ae);
res.writeHead(200, {
'Content-Type': 'image/svg+xml; charset=utf-8',
'Cache-Control': 'public, max-age=86400',
'Access-Control-Allow-Origin': CONFIG.corsOrigin,
'X-Content-Type-Options': 'nosniff'
'X-Content-Type-Options': 'nosniff',
...(gz ? { 'Content-Encoding': 'gzip', Vary: 'Accept-Encoding' } : { 'Content-Length': buf.length })
});
return res.end(svg);
return res.end(gz ? zlib.gzipSync(buf, { level: 6 }) : buf);
}
return ok(res, { ...item, svg: inlineRasterSvg(item.svg), source: sourceId, sourceNameCn: src.nameCn || sourceId, license: src.license, commercial: src.commercial }, null, rateHeaders);
@@ -790,13 +948,34 @@ async function handle(req, res) {
/* ---------- 海报 ---------- */
if (pathname === '/api/v1/posters/search') {
const r = search(store.posters, {
q: q.get('q'), source: q.get('source'), type: q.get('type'),
commercial: q.get('commercial') === '1', limit: q.get('limit'), offset: q.get('offset'),
dedupe: q.get('dedupe') === '1', includeNegative: q.get('include_negative') === '1',
includeSourceText: true
});
return ok(res, r.items, { total: r.total, limit: r.limit, offset: r.offset }, rateHeaders);
return cachedPayload(res, 200, 'posters/search?' + q.toString(), () => {
const r = search(store.posters, {
q: q.get('q'), source: q.get('source'), type: q.get('type'),
commercial: q.get('commercial') === '1', limit: q.get('limit'), offset: q.get('offset'),
dedupe: q.get('dedupe') === '1', includeNegative: q.get('include_negative') === '1',
includeSourceText: true
});
return { ok: true, data: r.items, meta: { total: r.total, limit: r.limit, offset: r.offset } };
}, rateHeaders);
}
// 批量取海报素材(同 icons/batch)
if (pathname === '/api/v1/posters/batch') {
const refs = String(q.get('items') || '').split(',').map(s => s.trim()).filter(Boolean).slice(0, 50);
const out = [];
for (const ref of refs) {
const cut = ref.indexOf(':');
const sid = cut > 0 ? ref.slice(0, cut) : '';
const nm = cut > 0 ? ref.slice(cut + 1) : ref;
const src = store.byId.get('posters/' + sid);
if (!src) { out.push({ ref, error: 'source_not_found' }); continue; }
const i = findByName(src, nm);
if (i < 0) { out.push({ ref, error: 'not_found' }); continue; }
const item = readItem(src, i);
if (!item) { out.push({ ref, error: 'read_failed' }); continue; }
out.push({ ref, item: { ...item, svg: inlineRasterSvg(item.svg), source: sid, license: src.license, commercial: src.commercial } });
}
return ok(res, out, { count: out.length }, rateHeaders);
}
const posterMatch = pathname.match(/^\/api\/v1\/posters\/([^/]+)\/(.+)$/);
@@ -818,17 +997,20 @@ async function handle(req, res) {
const workspace = q.get('workspace');
const step = q.get('step');
const category = q.get('category');
let list = [];
for (const [lib, obj] of Object.entries(store.skills)) {
if (lib === 'kind') continue;
for (const s of (obj.skills || [])) list.push({ ...s, library: lib });
}
if (workspace) list = list.filter(s => !s.workspaces || s.workspaces.includes(workspace));
if (step) list = list.filter(s => String(s.step) === String(step));
if (category) list = list.filter(s => s.category === category);
const limit = parseLimit(q.get('limit'));
const offset = parseOffset(q.get('offset'));
return ok(res, list.slice(offset, offset + limit), { total: list.length, limit, offset }, rateHeaders);
// 技能元数据恒定:按查询条件缓存整段响应
return cachedPayload(res, 200, 'skills|' + q.toString(), () => {
let list = [];
for (const [lib, obj] of Object.entries(store.skills)) {
if (lib === 'kind') continue;
for (const s of (obj.skills || [])) list.push({ ...s, library: lib });
}
if (workspace) list = list.filter(s => !s.workspaces || s.workspaces.includes(workspace));
if (step) list = list.filter(s => String(s.step) === String(step));
if (category) list = list.filter(s => s.category === category);
return { ok: true, data: list.slice(offset, offset + limit), meta: { total: list.length, limit, offset } };
}, rateHeaders);
}
const skillMatch = pathname.match(/^\/api\/v1\/skills\/([A-Za-z0-9._-]+)$/);