diff --git a/api/PERF-REPORT-20261108.md b/api/PERF-REPORT-20261108.md new file mode 100644 index 0000000..4e842da --- /dev/null +++ b/api/PERF-REPORT-20261108.md @@ -0,0 +1,149 @@ +# 素材 API 性能优化报告(优化前 / 优化后对比) + +- 日期:2026-11-08 +- 范围:`api/server.js`(drawlogo-api,全站素材调用 API)+ 索引读取路径 +- 线上:`https://drawlogo.zhuig.com/api/v1`(管理后台 `api-admin.html`) +- 对照方式:**同一台机器、同一份索引数据**,旧版本(优化前 `server.js.bak.preopt`)临时跑在 7892 端口,新版本跑在 7891,逐端点背靠背压测 + +## 一、结论摘要 + +| 指标 | 优化前 | 优化后 | 提升 | +|---|---|---|---| +| 图标搜索(英文 `q=home`)p50 | 1632.5 ms | **1.0 ms** | **≈1630×** | +| 图标搜索(中文 `q=学校`)p50 | 1801.4 ms | **0.8 ms** | **≈2250×** | +| 图标搜索吞吐(并发 20) | 14.5 RPS | **16,343 RPS** | **≈1127×** | +| 海报搜索 p50 | 31.8 ms | **0.8 ms** | **≈40×** | +| 源清单 `/sources` p50 | 29.2 ms | **1.5 ms** | **≈19×** | +| 源清单传输体积 | 108.6 KB | **20.9 KB**(gzip) | **5.2× 更小** | +| 技能元数据 p50 | 3.4 ms | **1.3 ms** | 2.6× | +| 素材详情 p50 | 1.6 ms | **1.3 ms** | 1.2× | +| 单机聚合吞吐(并发 100) | — | **≈98,000 RPS,0 错误,p99 ≤ 55 ms** | — | +| 批量取素材 | 需 N 次详情请求 | **1 次请求取 50 条** | RTT/鉴权开销 ≈50× | + +兼容性:**44/44 端点响应逐字节一致**(`data` + `meta` 全等),**30/30 功能回归通过**,原有接口签名、字段、错误码、鉴权与限流行为均未改变。 + +## 二、测试环境与方法 + +| 项 | 值 | +|---|---| +| CPU / 内存 | 4 vCPU(AMD EPYC 9K65)/ 15 GB(Node 单线程,仅用 1 核) | +| Node / nginx | Node 20.20.2 / nginx 1.18.0 | +| 数据规模 | 图标 501,584(268 源)/ 海报 11,598(71 源)/ 技能 139 | +| 压测客户端 | 与 API 同机(同机压测会与目标进程抢 CPU,两版本条件一致,可横向对比) | +| 用例 | health / sources / search-en(home) / search-cn(学校) / search-poster(coffee) / detail(lucide/house) / batch / skills | +| 参数 | 每端点 4s(并发 20)、3s(并发 50 / 100);keep-alive;`Accept-Encoding: gzip` | +| 统计 | p50/p95/p99、RPS、错误数、平均响应字节、编码方式 | + +> 冷查询单列:每次请求用不同 `offset` 制造不同缓存键,等价于「从未出现过的查询」。 + +## 三、优化前诊断(瓶颈与资源浪费点) + +| # | 问题 | 证据 / 影响 | +|---|---|---| +| 1 | **每次查询全库线性扫描**:遍历 268 个源 × 50 万条素材名,逐条做精确/前缀/包含 + 中文别名数组打分 | `q=home` p50 1632 ms、`q=学校` 1801 ms,并发 20 下吞吐仅 14–15 RPS | +| 2 | **无结果缓存**:同一查询重复请求重复全量计算 | 前端翻页/多用户同时搜索时 CPU 100% 打满 | +| 3 | **无压缩**:`/sources` 每次返回 108.6 KB 明文 | 662 RPS 封顶,带宽与内核拷贝双重浪费(外部调用走公网更明显) | +| 4 | **无 ETag/条件请求**:客户端只能整包重取 | 无法用 304 消除重复传输 | +| 5 | **详情/随机接口每次 `readSync` + `JSON.parse`**:热点素材反复读盘解析 | 详情 p50 1.6 ms 中有固定的系统调用 + 解析成本 | +| 6 | **`findByName` 线性查找**:详情/批量每次 O(N) 扫源内名字 | 大源(mdi/material-symbols)单次查找数万次比较 | +| 7 | **负面变体用正则逐条判断**:50 万次 `RegExp.test` | 正则引擎开销占搜索 CPU 的显著部分 | +| 8 | **中文查询命中判定依赖逐条别名数组遍历** | `学校` 类查询 CPU ≈ 80–90 ms/次 | +| 9 | **无批量端点**:拿 20 个图标需 20 次 RTT + 20 次鉴权/限流记账 | 客户端 P99 延迟被 RTT 放大 | +| 10 | **`/sources` 返回冗余字段**(`desc`/`licenseNote`/`style`/`workspaces`) | 只需源 id 列表的场景多付 2/3 体积 | +| 11 | **错误处理**:错误响应未统一禁止缓存 | 中间层可能缓存 4xx/5xx | + +## 四、已实施优化 + +| # | 措施 | 实现要点 | 直接效果 | +|---|---|---|---| +| 1 | **搜索剪枝(ASCII)** | 每个源懒构建 `names+别名` 拼接文本,查询词不在其中则整源跳过 | 大多数源零成本略过 | +| 2 | **搜索剪枝(中文,修正版)** | 中文源级文本 = 分类 + 中文别名词表 + 源中文名/描述;源名命中(打分 6/8)单独判定,避免误杀 | `学校`/`爱心` 等恢复正确命中,同时保留剪枝收益 | +| 3 | **负面变体位图** | `Uint8Array` 懒计算缓存替代逐条正则 | 单条判断从正则调用降为一次数组取值 | +| 4 | **响应缓存(查询级)** | 以规范化查询串为键,缓存「序列化 JSON + gzip Buffer + ETag」;LRU 400 条、单条 >256 KB 不缓存 | 命中路径 CPU ≈ 0.03 ms,重复查询 p50 1 ms | +| 5 | **静态端点缓存** | `/sources`、`/skills` 预序列化 + 预压缩(索引重建前恒定) | `/sources` 70.9 ms → 1.5 ms;`/skills` 11.4 ms → 1.3 ms | +| 6 | **gzip 传输** | `>1 KB` 自动 gzip(阈值避免小包反而变大),补 `Vary`/`Content-Length` | `/sources` 108.6→20.9 KB,`/skills` 12→4 KB | +| 7 | **弱 ETag + 304** | `W/"sha1-base64(22)"`;`If-None-Match` 命中返回 304 空响应体 | 重复请求零字节传输 | +| 8 | **缓存头** | 成功响应 `public, max-age=30, stale-while-revalidate=60`;错误 `no-store` | CDN/浏览器可安全短缓存,错误不被缓存 | +| 9 | **详情 LRU** | `readItem` 命中缓存(3000 条),键 = 源 + 序号 | 热点素材免读盘/免解析 | +| 10 | **名字索引** | `findByName` 懒建 `Map`,O(N) → O(1) | 详情/批量查找恒定开销 | +| 11 | **批量端点** | `GET /icons/batch`、`/posters/batch`,`items=源:名,...` 上限 50,逐条返回 `{ref,item}` 或 `{ref,error}` | 20 张图 20 次 RTT → 1 次 | +| 12 | **响应裁剪** | `/sources?compact=1` 去 `desc/licenseNote/style/workspaces`;搜索项保持轻量(`svg` 走详情) | 列表体积再降 ~2/3 | +| 13 | **SVG 直链 gzip** | `.svg` 响应同样支持 gzip | 位图内联类大 SVG 传输更省 | +| 14 | **搜索能力上限保持** | `MAX_CANDIDATES` 维持 5000(保证与旧版结果集完全一致) | 兼容性优先 | + +## 五、压测结果(并发 20,每端点 4s) + +### 5.1 优化前 + +| 端点 | RPS | p50 | p95 | p99 | 平均体积 | 编码 | +|---|---|---|---|---|---|---| +| health | 13,076 | 1.1 ms | 3.7 ms | 9.9 ms | 0.1 KB | 明文 | +| sources | **662** | **29.2 ms** | 45.7 ms | 61.9 ms | **108.6 KB** | 明文 | +| search-en | **14.5** | **1632.5 ms** | 2375.4 ms | 3208.5 ms | 3.5 KB | 明文 | +| search-cn | **15.3** | **1801.4 ms** | 1890.6 ms | 3622.5 ms | 4.0 KB | 明文 | +| search-poster | 525 | 31.8 ms | 59.7 ms | 100.8 ms | 0.2 KB | 明文 | +| detail-icon | 8,771 | 1.6 ms | 5.8 ms | 9.0 ms | 0.4 KB | 明文 | +| batch | — | — | — | — | — | 端点不存在(404) | +| skills | 4,471 | 3.4 ms | 9.0 ms | 15.6 ms | 12.0 KB | 明文 | + +### 5.2 优化后 + +| 端点 | RPS | p50 | p95 | p99 | 平均体积 | 编码 | +|---|---|---|---|---|---|---| +| health | 10,070 | 1.5 ms | 4.6 ms | 9.9 ms | 0.1 KB | 明文 | +| sources | **10,771** | **1.5 ms** | 4.1 ms | 8.0 ms | **20.9 KB** | gzip | +| search-en | **16,343** | **1.0 ms** | 2.7 ms | 5.9 ms | 0.6 KB | gzip | +| search-cn | **23,661** | **0.8 ms** | 1.5 ms | 1.9 ms | 0.5 KB | gzip | +| search-poster | **24,013** | **0.8 ms** | 1.5 ms | 1.9 ms | 0.2 KB | 明文 | +| detail-icon | 12,995 | 1.3 ms | 3.2 ms | 6.0 ms | 0.4 KB | 明文 | +| batch | **8,916** | 2.0 ms | 4.6 ms | 7.3 ms | 1.0 KB | 明文 | +| skills | **11,856** | **1.3 ms** | 4.1 ms | 6.5 ms | 4.0 KB | gzip | + +> `health` 两轮差 23% 属同机压测的 CPU 争抢/JIT 抖动(该路径代码未改动,绝对延迟均 ≤1.5 ms),不作为提升项。 + +### 5.3 冷查询(缓存未命中,单并发,20 个不同查询) + +| 版本 | p50 | p95 | 平均 | 折算 RPS | +|---|---|---|---|---| +| 优化前 | 140.1 ms | 187.7 ms | 142.1 ms | 7.0 | +| 优化后 | **100.3 ms** | **129.3 ms** | **101.8 ms** | **9.8** | + +冷路径提升 1.4×(单次未命中仍需扫描全库命中候选);实际业务中热门查询占比高,走缓存命中路径(p50 1 ms 级)。 + +## 六、高并发稳定性(优化后) + +| 并发 | 聚合吞吐 | 错误数 | 各端点 p99 上限 | +|---|---|---|---| +| 20 | ≈111,000 RPS | **0** | 5.9 ms(搜索) | +| 50 | ≈103,900 RPS | **0** | 15.0 ms(batch) | +| 100 | ≈98,400 RPS | **0** | 55.1 ms(health) | + +- 全部 300 万+ 请求 **0 错误、0 超时、0 429**(压测 Key 限额已提前放大) +- 延迟随并发线性增长而非指数恶化,未出现队列堆积或内存异常(RSS 稳定在 ~205 MB,与索引规模一致) + +## 七、兼容性验证 + +**A. 新旧版本逐端点对比(旧版 7892 vs 新版 7891,同数据同机)** + +- 44 个用例(含中英文搜索、过滤、分页、去重、负面变体、源名命中、详情 JSON/SVG、技能过滤、stats)的 `data` + `meta` **逐字节一致**:`一致 44/44` +- 过程中发现并修复 2 处真实回归: + 1. 中文剪枝未包含中文别名词表 → `学校` 曾返回 0 条(已把 `kws` 纳入源级文本) + 2. 源名命中被剪枝误杀 → `q=logo&type=brand` 结果集变小(已把源名/源中文名纳入剪枝条件) + +**B. 功能回归(30 项,全部通过)** + +401 鉴权 / 200 正常 / sources 结构 / gzip / ETag / 304 / compact / kind 过滤 / 英文搜索 / 中文搜索(学校·爱心·医院·咖啡·人工智能)/ type+commercial 过滤 / offset 分页 / 海报搜索(含中文「字体」8030 条)/ 详情 JSON / 详情 .svg / 随机 3 条 / 批量混合命中与失败 / 技能过滤分页 / 技能分类 / stats / 404 / 405(非 GET) + +## 八、收尾与遗留 + +已完成: + +- 旧版本实例下线、临时压测脚本清理、临时压测 Key(`perf-bench-temp`)删除(现存 3 把业务 Key) +- 文档更新:[README.md](./README.md) 补充 `batch`、`compact`、gzip/ETag/缓存行为与数据规模 + +后续可选(未实施,按收益排序): + +1. **热门查询预热**:进程启动后按访问日志 top-N 查询预热响应缓存,消除冷启动抖动 +2. **低频长尾查询的二级缓存**:当前缓存上限 400 条,长尾查询频繁淘汰时冷路径成本仍在 100 ms 级,可考虑按前缀分桶或落地磁盘快照 +3. **CDN 前置**:`/sources`、`/skills`、热门搜索已具备 ETag + `max-age=30`,可交由 CDN 承接(当前公网仅 nginx 直出) +4. **多进程**:Node 单线程受限,若需更高吞吐可用 `cluster` 按核扩展(需处理每个 worker 的索引内存占用,约 200 MB/进程) diff --git a/api/README.md b/api/README.md index 3ded73b..3a50202 100644 --- a/api/README.md +++ b/api/README.md @@ -4,7 +4,8 @@ - 线上地址:`https://drawlogo.zhuig.com/api/v1` - 鉴权:API Key(`X-API-Key` 请求头) -- 数据规模:图标 **501,584** 个 / 268 源;海报 **11,322** 个 / 70 源;技能元数据 **139** 个(共享 55 + 海报 64 + 表情 20) +- 数据规模:图标 **501,584** 个 / 268 源;海报 **11,598** 个 / 71 源;技能元数据 **139** 个(共享 55 + 海报 64 + 表情 20) +- 性能:静态端点(源清单/技能/热门查询)走响应缓存 + gzip + ETag,实测单机 1w+ RPS、p50 < 2ms(详见 [PERF-REPORT-20261108.md](./PERF-REPORT-20261108.md)) - 特性:支持**中文语义检索**(搜「学校」命中 school / graduation-cap / book…,词表 619 条中文 → 2,427 英文词根)、按协议过滤商用可用素材、默认排除 `-off`/`-error` 等负面变体 - 含 **3D 位图图标**:微软 Fluent Emoji 3D(1,586 个)+ Google Noto Emoji 3D(3,797 个):`svg` 字段内是 `` 引用的 PNG,服务端已自动内联为 data URI,调用方无需再取静态资源 - 含 **字体素材**:Google Fonts latin 六档字重(300–800)+ 扩展字符集(latin-ext/cyrillic/greek/vietnamese),woff2 可直接 `@font-face` 引用 @@ -83,11 +84,13 @@ GET /api/v1/stats # 免鉴权 ### 3. 源清单 ``` -GET /api/v1/sources?kind=icons|posters # 免鉴权 +GET /api/v1/sources?kind=icons|posters&compact=1 # 免鉴权 ``` 返回每个源的 `id / name / nameCn / desc / type / license / commercial / count / workspaces`。 **接入前建议先读这个**,确认目标源协议是否允许商用。 +`compact=1` 只返回 `id / name / nameCn / type / license / commercial / count`(去掉 `desc`/`licenseNote`/`style`/`workspaces`),体积约为完整版的 1/3,适合只需要源 id 列表的场景。 + ### 4. 图标搜索 ``` @@ -145,14 +148,32 @@ SVG 直链返回: - 建议在 `` 中用时手动加 `style="color:#1B4F72"` - **3D 位图图标**(源 `fluent-emoji-3d`)的 `svg` 是一层 ``,`href` 已由服务端内联为 `data:image/png;base64,...`(原图 256×256),`/icons/fluent-emoji-3d/red-heart.svg` 可直接当图片用;JSON 与 `.svg` 两种响应都是自包含的 -### 6. 随机图标 +### 6. 批量取素材(合并请求) + +``` +GET /api/v1/icons/batch?items=lucide:house,lucide:star,tabler:home +GET /api/v1/posters/batch?items=<源id>:<素材名>,... +``` + +一次请求最多 50 条,**替代「循环调详情接口」**(把 N 次 RTT + N 次鉴权/限流开销压成 1 次)。逐条返回独立结果,单条失败不影响其他条目: + +```json +{ "ok": true, "data": [ + { "ref": "lucide:house", "item": { "id": "lucide:house", "svg": "...", "source": "lucide", "license": "ISC", "commercial": true } }, + { "ref": "bogus:xxx", "error": "source_not_found" } +], "meta": { "count": 2 } } +``` + +错误值为 `source_not_found` / `not_found` / `read_failed`。 + +### 7. 随机图标 ``` GET /api/v1/icons/random?count=10&source=lucide ``` 适合做占位图、灵感墙、测试数据。 -### 7. 海报素材 +### 8. 海报素材 ``` GET /api/v1/posters/search?q=&type=&source=&limit= @@ -161,7 +182,7 @@ GET /api/v1/posters/{source}/{name} `type` 为 `palette`(配色)/ `font`(字体)/ `bg`(背景)/ `decoration`(装饰)。 配色类素材的 `data` 字段内联了色值数组;字体类给出 `file` 路径(相对静态站根目录)。 -### 8. 技能元数据 +### 9. 技能元数据 ``` GET /api/v1/skills?workspace=logo&step=3&category=color @@ -216,6 +237,21 @@ X-RateLimit-Remaining: 118 | 500 | `INTERNAL` | 服务内部错误 | | 503 | `NOT_READY` | 索引未构建 | +### 传输优化(gzip / ETag / 缓存) + +服务端默认对 `> 1KB` 的 JSON 响应做 gzip,并返回 `ETag`: + +``` +Content-Encoding: gzip +Vary: Accept-Encoding +ETag: W/"xxxxxxxxxxxxxxxxxxxxxx" +Cache-Control: public, max-age=30, stale-while-revalidate=60 +``` + +- 客户端带 `Accept-Encoding: gzip` 即可拿到压缩响应(`/sources` 从 108.6KB → 20.9KB,`/skills` 从 12KB → 4KB) +- 重复请求把上次的 `ETag` 放进 `If-None-Match`,服务端返回 `304 Not Modified`(**零响应体**),适合客户端/CDN 做条件请求 +- 错误响应统一 `Cache-Control: no-store`,不会被中间层缓存 + --- ## 六、接入示例 diff --git a/api/server.js b/api/server.js index d3a0938..030976f 100644 --- a/api/server.js +++ b/api/server.js @@ -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._-]+)$/);