From 69ce61a9321fdbe2cb7f6263fa5bb14a02b5ce0f Mon Sep 17 00:00:00 2001 From: hoelee Date: Tue, 27 Oct 2026 06:15:27 +0800 Subject: [PATCH] docs(review): apply batch-01 consultant fixes and update review status --- docs/consultant-review/AUDIT-TRACKER.md | 2 +- docs/consultant-review/batches/batch-01.md | 4133 ----------------- docs/consultant-review/batches/batch-02.md | 3818 --------------- .../reports/report-batch-01.md | 22 + ...-english-mode-to-a-chinese-only-web-app.md | 6 +- .../posts/debugging-remotion-video-jitter.md | 26 +- ...onts-so-a-pdf-looks-the-same-everywhere.md | 9 +- .../posts/jpa-version-field-lost-update.md | 22 +- ...rating-codeigniter-iis-to-openlitespeed.md | 4 +- ...walled-marketplace-warm-browser-session.md | 3 +- ...cript-file-stops-working-and-looks-fine.md | 7 +- .../why-your-cdp-clicks-silently-fail.md | 2 +- ...hy-your-grafana-dashboard-shows-no-data.md | 9 +- .../posts/your-disk-full-alert-is-lying.md | 10 +- ...-english-mode-to-a-chinese-only-web-app.md | 6 +- .../zh/debugging-remotion-video-jitter.md | 26 +- ...onts-so-a-pdf-looks-the-same-everywhere.md | 8 +- .../posts/zh/jpa-version-field-lost-update.md | 22 +- ...rating-codeigniter-iis-to-openlitespeed.md | 6 +- ...walled-marketplace-warm-browser-session.md | 3 +- ...cript-file-stops-working-and-looks-fine.md | 8 +- .../zh/why-your-cdp-clicks-silently-fail.md | 2 +- ...hy-your-grafana-dashboard-shows-no-data.md | 6 +- .../posts/zh/your-disk-full-alert-is-lying.md | 8 +- 24 files changed, 119 insertions(+), 8049 deletions(-) delete mode 100644 docs/consultant-review/batches/batch-01.md delete mode 100644 docs/consultant-review/batches/batch-02.md create mode 100644 docs/consultant-review/reports/report-batch-01.md diff --git a/docs/consultant-review/AUDIT-TRACKER.md b/docs/consultant-review/AUDIT-TRACKER.md index ee10f27..05689f9 100644 --- a/docs/consultant-review/AUDIT-TRACKER.md +++ b/docs/consultant-review/AUDIT-TRACKER.md @@ -1,6 +1,6 @@ # 全站文章顾问审阅状态总控台 (Audit Tracker) -> **最后同步时间**:2026-10-27 06:11:29 +> **最后同步时间**:2026-10-27 06:14:26 > **全站总文章数**:91 篇 | **已审批完成**:91 篇 (100.0%) | **待审阅**:0 篇 ## 一、操作命令速查 diff --git a/docs/consultant-review/batches/batch-01.md b/docs/consultant-review/batches/batch-01.md deleted file mode 100644 index ad58406..0000000 --- a/docs/consultant-review/batches/batch-01.md +++ /dev/null @@ -1,4133 +0,0 @@ -# 博客文章顾问审阅资料包 — Batch-01 - -> **批次编号**:`Batch-01` -> **包含文章数**:11 篇 -> **本批次总字符量**:170,149 字(严格限制 < 200,000 字) -> **模式**:BILINGUAL -> **生成时间**:2026-10-27 06:05:52 - -# 外部顾问审阅前置须知与工程背景规范 - -> **本文档目标**:本批次包含 `blog.hoelee.com` 的待审阅技术文章全文。请外部顾问在审阅正文与技术主张时,以此规范为最高评估准则。 - -## 1. 站点定位与双重业务目的 -- **受众 A(技术招聘官 / 资深技术主管)**:寻找具备 Senior 全栈 + DevOps + AI 智能体闭环能力的架构工程师。文章定位为**“不可伪造的工程实操交付证据(Proof of Expertise)”**,要求代码真实、日志可查、有架构权衡与技术深度。 -- **受众 B(中小企业主 SME / 商业客户)**:寻找能提供系统研发、私有化部署、24/7 AI 获客系统、高可用基础设施的技术顾问。文章需清晰阐述业务痛点、商业 ROI、上线效率与交付保障。 - -## 2. 核心人设铁律与工程硬约束(必须严格遵守) -1. **彻底杜绝业余爱好者/玩具口吻**: - - ❌ **绝对禁用词**:`homelab`, `home lab`, `家用`, `小主机`, `玩具`, `折腾`。 - - ✅ **标准替代词**:`the infrastructure I manage`(我管理的私有基础设施)、`self-hosted production node`(自托管生产节点)、`on-premise host`(私有化服务器)。 -2. **严禁捏造虚假指标与性能数字**: - - 所有 benchmark 数据必须有明确的测试基准与单设备限制。 - - 严格区分“耗时减少比例”与“吞吐加速倍数”(例如耗时从 352s 降至 218s 是耗时减少 38.0%,吞吐提升 1.61×,严禁偷换概念混淆)。 - - 时间戳精度与物理帧对齐:视频帧率上限(如 30 fps 单帧 33.3ms)不可妄称“微秒级精确”。 -3. **去模板化叙事与真实物理锚点**: - - 拒绝千篇一律的 AI 模板味。文章采用三大叙事架构:① 故障排查谜案(Symptom → False Lead → Kernel Evidence → Fix);② 商业交付复盘(Client Bottleneck → Trade-offs → State Machine → ROI);③ 架构演进对比(V1 Naive → Concurrency Crash → V2 Redesign)。 - - 每篇文章必须包含至少一个物理真实世界锚点(主机真实硬件规格、生产维护窗口、真实业务场景)。 -4. **代码与配置展示规范**: - - 超过 20 行的配置或日志采用 HTML `
` 原生折叠,`` 必须精准标注文档名与行数。 - -## 3. 顾问重点开刀维度 -- [ ] **事实与数字可核性**:技术判断与性能数据是否自洽?有无过度夸大? -- [ ] **人设与语调纯洁性**:有无遗漏的 hobbyist/homelab 口吻? -- [ ] **双轨转化引导有效性**:是否有清晰的业务价值提炼与行动召唤(CTA)? -- [ ] **代码与生产安全性**:有无未脱敏的凭据、绝对内部私密路径或不安全的权限配置? - - ---- - -## 本批次文章目录索引 - -1. [devops] **为什么你的 CDP 点击会静默失效:平滑滚动、最小化窗口与 JS 派发事件** (`why-your-cdp-clicks-silently-fail`) — ~12,590 字符 -2. [devops] **Prometheus 明明有数据,Grafana 面板却全是 No data 的原因** (`why-your-grafana-dashboard-shows-no-data`) — ~11,375 字符 -3. [devops] **你的“磁盘将满”告警在说谎:别再按百分比告警** (`your-disk-full-alert-is-lying`) — ~9,229 字符 -4. [engineering] **浏览器翻译没有 API:我给一个纯中文网页应用加上了英文模式** (`adding-english-mode-to-a-chinese-only-web-app`) — ~18,167 字符 -5. [engineering] **排查 Remotion 视频抽搐:为什么在背景图挂载音频低频 Scale 会毁了转场** (`debugging-remotion-video-jitter`) — ~15,489 字符 -6. [engineering] **把字体嵌进 PDF,让它在任何机器上都长一样** (`embedding-fonts-so-a-pdf-looks-the-same-everywhere`) — ~12,338 字符 -7. [engineering] **那个把静默丢失更新变成 409 的 JPA 字段:@Version 乐观锁** (`jpa-version-field-lost-update`) — ~20,042 字符 -8. [engineering] **把 CodeIgniter 4 应用从 IIS 迁移到 OpenLiteSpeed** (`migrating-codeigniter-iis-to-openlitespeed`) — ~23,368 字符 -9. [engineering] **用「热浏览器会话」爬取有反爬墙的电商网站** (`scraping-bot-walled-marketplace-warm-browser-session`) — ~17,047 字符 -10. [engineering] **JavaScript 文件静默失效的两种方式:而页面看上去一切正常** (`two-ways-a-javascript-file-stops-working-and-looks-fine`) — ~11,294 字符 -11. [engineering] **逐页验证一份 19 页的 PDF 报告** (`verifying-a-pdf-report-page-by-page`) — ~19,210 字符 - ---- - -## 文章 01 / 11:为什么你的 CDP 点击会静默失效:平滑滚动、最小化窗口与 JS 派发事件 -- **Slug**: `why-your-cdp-clicks-silently-fail` -- **英文标题**: Why Your CDP Clicks Silently Fail: Smooth Scroll, Minimised Windows, and JS-Dispatched Events -- **分类**: `devops` | **发布日期**: 2025-03-19 -- **线上地址**: https://blog.hoelee.com/posts/why-your-cdp-clicks-silently-fail/ (EN) | https://blog.hoelee.com/posts/zh/why-your-cdp-clicks-silently-fail/ (ZH) -- **本篇审核状态**: ⏳ 待审核 (Pending) - -### ✍️ 顾问审阅意见区 (Review Feedback) -```text -【审阅结论】:[ ] 通过 [ ] 需微调 [ ] 需重构 -【事实与数字核对】: -【人设与用词卫生】: -【CRO与转化建议】: -``` - -### 🇨🇳 中文版原文 (Chinese Markdown Twin) -````markdown ---- -title: "为什么你的 CDP 点击会静默失效:平滑滚动、最小化窗口与 JS 派发事件" -description: "Chrome DevTools Protocol 点击报告成功却毫无反应的三个原因:平滑滚动导致的过期坐标、最小化窗口被丢弃的坐标输入、以及页面收到了点击但拒绝了它。" -pubDate: 2025-03-19 -updatedDate: 2026-09-29 -category: devops -tags: [cdp, chrome, react, browser-automation, debugging, python] -ogImage: /og/zh-why-your-cdp-clicks-silently-fail.jpg -banner: /banners/why-your-cdp-clicks-silently-fail.jpg -draft: false ---- - -如果你用 Chrome DevTools Protocol 驱动网页应用,你一定见过这个失败:脚本报告 `clicked @591,361`,元素明明在,点击也确实发出去了 —— 然后什么都没发生。没有异常,没有控制台报错,页面毫无变化。 - -我在自动化某平台卖家后台时整整耗了一个晚上在这上面。找到的三个原因值得写下来,因为**它们对「报告点击成功」的那段代码全都是隐形的**。 - -## 原因一:坐标过期,因为页面是平滑滚动的 - -最直观的点击辅助函数大概长这样: - -```python -r = self.ev("""(()=>{const e=%s; e.scrollIntoView({block:'center'}); - const b=e.getBoundingClientRect(); - return JSON.stringify({x:b.left+b.width/2, y:b.top+b.height/2});})()""") -self.click_xy(json.loads(r)["x"], json.loads(r)["y"]) -``` - -滚动到可视区、读取元素矩形、点它的中心。逻辑没错 —— 除非页面有 `scroll-behavior: smooth`(现代 UI 组件库里非常常见)。那时 `scrollIntoView()` 启动的是**动画**,而同一个 tick 里的 `getBoundingClientRect()` 返回的是元素**即将离开**的位置。你的点击落在元素**原来**的地方,落在当时在那儿的别的东西上,而日志忠实地告诉你:它点击了你要求的坐标。 - -修法是两行 —— 关掉平滑滚动,然后重新读矩形: - -```python -self.ev("""(()=>{document.documentElement.style.scrollBehavior='auto'; - if(document.body) document.body.style.scrollBehavior='auto'; return 'ok';})()""") -moved = self.ev("""(()=>{const e=%s; if(!e) return 'no'; - e.scrollIntoView({block:'center', behavior:'instant'}); return 'ok';})()""" % sel) -time.sleep(0.35) # 等布局稳定 -# 然后再读矩形(元素晚一帧才渲染的话,外面再套一层重试) -``` - -两个细节很关键:`scrollIntoView` 上的 `behavior:'instant'` 会覆盖 CSS;而读取前那一小段等待,才是让坐标可信的原因。没有重试循环的话,这个辅助函数在晚一帧渲染的元素上仍会偶发失败 —— **偶发失败是最糟的一类,因为它会让你怀疑自己的判断。** - -## 原因二:窗口最小化时,坐标点击被丢弃 - -修好之后,我的点击辅助函数在一次性探针里能用,一放进真正的脚本就再也没成功过。同样的选择器、同样的坐标、同样的页面。差别最后落在可见性上: - -``` -document.visibilityState → "hidden" -document.hasFocus() → true -``` - -当目标标签页不是可见窗口的活动标签页时,CDP 合成的坐标级鼠标事件是不可靠的 —— 浏览器可能接受、可能限流、也可能直接不往任何地方送。注意 `hasFocus()` **在文档隐藏时依然返回 `true`**,所以它不是有效的判断依据;要看的是 `document.hidden` / `visibilityState`。 - -两个修法,我都用: - -```python -def activate(self): # 把标签页提到窗口最前 - self.cdp("Page.bringToFront") - time.sleep(0.2) - -def click_js(self, sel): # 在页面内部派发事件来点击 - return self.ev("""(()=>{const e=%s; if(!e) return 'no'; - ['mousedown','mouseup','click'].forEach(k=> - e.dispatchEvent(new MouseEvent(k,{bubbles:true,cancelable:true,view:window}))); - return 'js-clicked';})()""" % sel) -``` - -`Page.bringToFront` 解决了常见情况。但真正从不出错的是 JS 派发的点击:它不依赖窗口是否可见,而且 React 挂在根节点上的事件监听器会收到它,和收到真实点击的方式完全一样 —— 因为事件冒泡到的是同一个根。一个用坐标点击五次才能打开一次的日期选择器,用这种方式**每次都开**。 - -需要知道的取舍:派发事件会跳过 hit-testing,所以它也会「点到」用户根本够不到的元素(被遮住、滚出屏幕、透明度为零)。在这里这是优点 —— 如果你用它去掩盖布局 bug,那就是坑 —— 所以凡是可视化的东西我都用坐标点击,而遇到自定义控件时才伸手去拿 `click_js`。 - -## 原因三:页面收到了点击,然后拒绝了它 - -这个最浪费时间,因为它的症状和前两个一模一样:点击发出去了,什么都没变。 - -区分它们只需要注入一个监听器: - -```js -window.__ev = []; -['mousedown','mouseup','click'].forEach(k => - document.addEventListener(k, e => window.__ev.push(k + ':' + e.target.tagName), true)); -``` - -- 有事件记录 → 输入链路是通的,问题在应用侧(原因三),或者在你读取结果的方式上(见下)。 -- 一条都没有 → 是原因一或原因二。 - -挂上监听器后我点了一次 `Confirm`,缓冲区满了 —— 说明点击没问题,是应用在说「不」。理由在一段我从没想过要看的文字里: - -> “Please create a new shop welcome voucher after the existing one is expired.” - -表单拒绝创建同类型的第二张券。没有字段级红字、头 500 毫秒里没有提示条、URL 也没变。**拒绝是真的,点击是无辜的。** - -这一类 bug 还有两个工具: - -```js -document.elementFromPoint(x, y) // 那个坐标上到底是什么? -document.querySelectorAll('button').length // 你的选择器到底命中了几个? -``` - -第二个抓到过一处很细的问题:门户页面在 DOM 里留了一个**隐藏的** `Confirm` 按钮(来自收起状态的日期面板),于是 `.pop()` 返回的是那个看不见的副本,点击自然落到了无人的地方。按可见性和尺寸一起过滤: - -```python -"[...document.querySelectorAll('button')].filter(b=>/^Confirm$/.test(b.innerText.trim())" -" && b.offsetParent!==null && b.getBoundingClientRect().width>0).pop()" -``` - -## 第四种「失败」,只有回读才发现 - -还有一类「失败」其实不是失败:**写入成功了,而你的读取是旧的。** 我因为列表页没有立刻显示,就断定创建被静默拒绝,又点了一次;后来才发现那张券一直都存在 —— 列表只是延迟了大约十分钟。这个教训可以推广:一次写入之后,唯一可信的结论是在**等待足够时间之后**回读得到的,而「看不到变化」意味着**未知**,不是失败。 - -## 检查清单 - -1. 关掉平滑滚动;用 `behavior:'instant'` 滚动;等一会儿再读矩形。 -2. 点击前调用 `Page.bringToFront`;判断依据用 `document.hidden`,不是 `hasFocus()`。 -3. 自定义控件用 JS 派发 `mousedown`/`mouseup`/`click`,别点坐标。 -4. 先挂事件监听器,证明输入是否到达,再去怪应用。 -5. 数一数选择器命中几个 —— 组件库里隐藏的重复元素很常见。 -6. 写入之后先等待再回读;永远不要重复点击一个还没验证过的提交按钮。 - -这些都不算冷门知识,但它们中的每一条,在一行 `clicked @591,361` 面前都是隐形的。如果你正在对着一个自己无法控制的后台做自动化:点击是整条链路里最不可靠的一环 —— 也是最容易被最后才怀疑的一环。 - -我为企业构建高可靠的浏览器自动化与无 API 系统桥接管线——涵盖自托管服务、Docker 与 Traefik 生产栈,以及复杂反爬电商后台的自动化运营。如果你的业务工作流总因为「第三方 UI 频繁变动」而中断,欢迎联系我:[WhatsApp +60 12-797 2969](https://wa.me/60127972969) · [me@hoelee.com](mailto:me@hoelee.com?subject=Browser%20automation%20debugging) · [hoelee.com](https://hoelee.com)。 -```` - -### 🇬🇧 英文版原文 (English Markdown Primary) -````markdown ---- -title: "Why Your CDP Clicks Silently Fail: Smooth Scroll, Minimised Windows, and JS-Dispatched Events" -description: "Three reasons a Chrome DevTools Protocol click reports success and does nothing: a stale rect from smooth scrolling, a minimised window that drops coordinate input, and a page that received the click but rejected it." -pubDate: 2025-03-19 -updatedDate: 2026-09-29 -category: devops -tags: [cdp, chrome, react, browser-automation, debugging, python] -ogImage: /og/why-your-cdp-clicks-silently-fail.jpg -banner: /banners/why-your-cdp-clicks-silently-fail.jpg -draft: false ---- - -If you drive a web app with the Chrome DevTools Protocol, you have met this failure: your script reports `clicked @591,361`, the element is there, the click landed — and nothing happens. No exception, no console error, no change on the page. - -I spent an evening on exactly this while automating a marketplace's seller admin panel, and the three causes I found are worth writing down, because they are all invisible to the code that reports the click. - -## Cause 1: a stale rect, because the page scrolls smoothly - -The obvious click helper looks like this: - -```python -r = self.ev("""(()=>{const e=%s; e.scrollIntoView({block:'center'}); - const b=e.getBoundingClientRect(); - return JSON.stringify({x:b.left+b.width/2, y:b.top+b.height/2});})()""") -self.click_xy(json.loads(r)["x"], json.loads(r)["y"]) -``` - -Scroll into view, read the element's rectangle, click its centre. Correct — unless the page has `scroll-behavior: smooth` (very common in modern UI kits). Then `scrollIntoView()` starts an **animation**, and `getBoundingClientRect()` in the same tick returns the position the element is *about to leave*. Your click goes to where the element was, lands on whatever is there, and the log tells you it clicked the coordinates you asked for. - -The fix is two lines — turn smooth scrolling off, then re-read the rect: - -```python -self.ev("""(()=>{document.documentElement.style.scrollBehavior='auto'; - if(document.body) document.body.style.scrollBehavior='auto'; return 'ok';})()""") -moved = self.ev("""(()=>{const e=%s; if(!e) return 'no'; - e.scrollIntoView({block:'center', behavior:'instant'}); return 'ok';})()""" % sel) -time.sleep(0.35) # let layout settle -# then read the rect (and retry a couple of times if the element is not there yet) -``` - -Two details matter. `behavior:'instant'` on `scrollIntoView` overrides the CSS; and the small wait before reading is what makes the rect trustworthy. Without the retry loop the helper still fails intermittently on elements that render a frame late — intermittent failures are the worst kind, because they make you doubt your own diagnosis. - -## Cause 2: the window is minimised, and coordinate clicks are dropped - -After the fix, my click helper worked in a one-off probe and then never again inside the real script. Same selector, same coordinates, same page. The difference turned out to be visibility: - -``` -document.visibilityState → "hidden" -document.hasFocus() → true -``` - -CDP-synthesised mouse events at coordinates are unreliable when the target tab is not the active tab of a visible window — the browser may accept them, throttle them, or route them nowhere. Note that `hasFocus()` returns `true` even when the document is hidden, so it is not a useful check; `document.hidden`/`visibilityState` is. - -Two fixes, and I use both: - -```python -def activate(self): # bring the tab to the front of its window - self.cdp("Page.bringToFront") - time.sleep(0.2) - -def click_js(self, sel): # click by dispatching events from inside the page - return self.ev("""(()=>{const e=%s; if(!e) return 'no'; - ['mousedown','mouseup','click'].forEach(k=> - e.dispatchEvent(new MouseEvent(k,{bubbles:true,cancelable:true,view:window}))); - return 'js-clicked';})()""" % sel) -``` - -`Page.bringToFront` fixes the common case. But the JS-dispatched click is the one that never fails: it does not depend on the window being visible, and React's root-level event listener receives it exactly as it receives a real click, because the events bubble to the same root. A date-picker input that opened maybe one time in five with coordinate clicks opens **every** time this way. - -The trade-off to know: dispatching events skips hit-testing, so it will also “click” an element a user could not reach (covered, scrolled off, zero-opacity). That is a feature here — and a trap if you use it to paper over a layout bug — so I keep coordinate clicking for anything visual and reach for `click_js` when the widget is a custom control. - -## Cause 3: the page received the click and rejected it - -This is the one that wasted the most time, because the symptom is identical to causes 1 and 2: click fires, nothing changes. - -Distinguishing them takes one injected listener: - -```js -window.__ev = []; -['mousedown','mouseup','click'].forEach(k => - document.addEventListener(k, e => window.__ev.push(k + ':' + e.target.tagName), true)); -``` - -- Events recorded → the input path works. The problem is in the app (cause 3), or in how you read the result (see below). -- Nothing recorded → causes 1 or 2. - -With the listener armed I clicked `Confirm` and the buffer filled up — so the click was fine, and the app was saying no. The reason was in text I had not thought to look at: - -> “Please create a new shop welcome voucher after the existing one is expired.” - -The form refuses a second voucher of that type. No field-level red text, no toast in the first 500 ms, the URL unchanged. **The rejection was real and the click was innocent.** - -Two more tools for this class of bug: - -```js -document.elementFromPoint(x, y) // what is actually on top at that coordinate? -document.querySelectorAll('button').length // how many match your selector? -``` - -The second one caught a subtle one: the portal leaves a **hidden** `Confirm` button in the DOM from the collapsed date-panel, so `.pop()` returned the invisible duplicate and the click went nowhere visible. Filter by visibility *and* size: - -```python -"[...document.querySelectorAll('button')].filter(b=>/^Confirm$/.test(b.innerText.trim())" -" && b.offsetParent!==null && b.getBoundingClientRect().width>0).pop()" -``` - -## And the fourth failure I only found by re-reading - -There is a class of “failure” that is not one: **the write succeeded and your read is stale.** I concluded a create had been silently refused because the list page did not show it immediately, clicked again, and later discovered the voucher had existed the whole time — the list just lagged about ten minutes. The lesson generalises: after a write, the only trustworthy verdict is a read-back *after* a real waiting period, and “no visible change” means *unknown*, not *failed*. - -## The checklist - -1. Turn off smooth scrolling; scroll with `behavior:'instant'`; wait, then read the rect. -2. Call `Page.bringToFront` before clicking; treat `document.hidden` as the signal, not `hasFocus()`. -3. For custom widgets, dispatch `mousedown`/`mouseup`/`click` from JS rather than clicking coordinates. -4. Arm an event listener to prove whether input arrived before you blame the app. -5. Count your selectors — hidden duplicates are common in component libraries. -6. After a write, wait and re-read; never re-click a submit you have not verified. - -None of this is exotic, but every item is invisible in a log line that says `clicked @591,361`. If you are building automation against an admin panel you do not control, the click is the least reliable part of the pipeline — and the one most likely to be blamed last. - -I architect and debug production browser automation and RPA pipelines — spanning self-hosted services, Docker and Traefik stacks, and bot-walled marketplace operations. If you have a business workflow that keeps breaking because a third-party UI has other ideas, tell me about it: [WhatsApp +60 12-797 2969](https://wa.me/60127972969) · [me@hoelee.com](mailto:me@hoelee.com?subject=Browser%20automation%20debugging) · [hoelee.com](https://hoelee.com). -```` - ---- - -## 文章 02 / 11:Prometheus 明明有数据,Grafana 面板却全是 No data 的原因 -- **Slug**: `why-your-grafana-dashboard-shows-no-data` -- **英文标题**: Why Your Grafana Dashboard Shows No Data (When Prometheus Is Fine) -- **分类**: `devops` | **发布日期**: 2026-05-17 -- **线上地址**: https://blog.hoelee.com/posts/why-your-grafana-dashboard-shows-no-data/ (EN) | https://blog.hoelee.com/posts/zh/why-your-grafana-dashboard-shows-no-data/ (ZH) -- **本篇审核状态**: ⏳ 待审核 (Pending) - -### ✍️ 顾问审阅意见区 (Review Feedback) -```text -【审阅结论】:[ ] 通过 [ ] 需微调 [ ] 需重构 -【事实与数字核对】: -【人设与用词卫生】: -【CRO与转化建议】: -``` - -### 🇨🇳 中文版原文 (Chinese Markdown Twin) -````markdown ---- -title: "Prometheus 明明有数据,Grafana 面板却全是 No data 的原因" -description: "所有 target 都是 up、数据就在 Prometheus 里、面板表达式也没错——41 个面板却全部 No data。原因是 Grafana 变量过滤了自己,而我的验证方式恰好掩盖了它。" -pubDate: 2026-05-17 -updatedDate: 2026-09-29 -category: devops -blueprint: self-hosted-infrastructure -blueprintLayer: L3-observability-self-healing -tags: [grafana, prometheus, dashboards, monitoring, promql, observability] -ogImage: /og/zh-why-your-grafana-dashboard-shows-no-data.jpg -banner: /banners/why-your-grafana-dashboard-shows-no-data.jpg -draft: false ---- - -打开每天在看的面板,结果是空的。不是\"某一格坏了\",而是**从上到下每一格**都写着 *No data*。去查 Prometheus,一切健康。这篇讲我踩到的那个具体且不直观的原因,以及为什么我自己的验证会同时告诉我\"面板没问题\"。 - -## 最省时间的排查顺序 - -常见原因(数据源选错、时间范围不对、`rate()` 用在会重置的计数器上、target 没被抓取)都不适用。真正有效的检查顺序是: - -```bash -# 1. target 真被抓取了吗? -curl -s http://prometheus:9090/api/v1/targets | jq '.data.activeTargets[] | {job:.labels.job, health}' - -# 2. 指标现在存在吗?(完全绕过 Grafana) -curl -s -G http://prometheus:9090/api/v1/query \ - --data-urlencode 'query=node_uname_info{job="unraid-host"}' | jq '.data.result[0].metric' - -# 3. 面板表达式本身对吗? -curl -s -G http://prometheus:9090/api/v1/query \ - --data-urlencode 'query=count(node_cpu_seconds_total{mode="idle",job="unraid-host"})' -``` - -三项都过了:7 个 target `up`、2.5 万条序列在采集、手动跑面板表达式也有数据。所以问题不在指标、不在抓取、也不在 PromQL——而在**它们之间的变量层**。 - -## 真正的原因:变量过滤了自己 - -面板上有一个主机选择器,两个变量串联:`$nodename`(哪台机器)和 `$node`(它的 `instance` 标签)。第一个的定义是: - -```promql -# BROKEN — 变量用自身的值来过滤自己 -label_values(node_uname_info{job="unraid-host", nodename=~"$nodename"}, nodename) -``` - -首次加载时 `$nodename` 还没有值,选择器就变成 `nodename=~""`——**什么都匹配不到**。查询返回零行的变量没有任何选项,于是它保持空;而 `$node` 又是基于 `$nodename` 定义的: - -```promql -label_values(node_uname_info{job="unraid-host", nodename="$nodename"}, instance) -``` - -于是 `$node` 也是空,所有以 `$node` 为过滤条件的面板自然匹配不到序列。Grafana 说 *No data* 并没有骗人:面板查询真的没有数据,因为给它限定范围的变量解析成了空。 - -修法是去掉自引用,并给每个变量存一个明确的默认值: - -```promql -# FIXED — 不自引用,每个变量只跳一层 -# $nodename -label_values(node_uname_info{job="unraid-host"}, nodename) -# $node -label_values(node_uname_info{job="unraid-host", nodename="$nodename"}, instance) -``` - -## 为什么我的验证没抓到 - -这才是值得抄的部分。我\"验证\"面板的方式是:**手动**把每个面板表达式里的变量替换成我知道正确的值(`$nodename=unRaid`、`$node=host.docker.internal:9100`),然后断言查询有数据点。13 项检查全部通过——面板依然是空的,因为 bug 在被替换的那个值**上游**:Grafana 自己对变量的解析是空的。 - -**一个替换掉\"可疑值\"的验证,永远发现不了那个值解析失败。** 要抓它,得读 Grafana 真实存下来的值: - -```bash -curl -s -u admin:"$PW" http://grafana:4010/api/dashboards/uid/rYdddlPWk \ - | jq '.dashboard.templating.list[] | {name, current: .current.value}' -``` - -更直接的检查对象是变量查询本身——跑 Grafana 会跑的那条: - -```bash -# $nodename 的 label_values() 到底返回什么? -curl -s -G http://prometheus:9090/api/v1/query \ - --data-urlencode 'query=count by (nodename) (node_uname_info{job="unraid-host"})' | jq '.data.result' -``` - -那里是空,面板就不可能渲染出来,无论数据多健康。 - -## 第二个坑:`$__all` 不是 `.*` - -做自动化面板检查时,值为\"All\"的变量,其 current 是哨兵字符串 `$__all`——不是正则。把 `name=~"$__all"` 原样展开会匹配不到任何东西,于是完全健康的容器面板\"全军覆没\"。展开前要把 `$__all` 解析成该变量的 `allValue`(通常是 `.*`),否则你追的是一个只存在于自己检查脚本里的 bug。 - -## 不是每个空面板都是 bug - -修完之后,41 个总面板(含分组行与状态块)中,**25 个核心指标图表里有 21 个成功出数**,剩下 4 个是**设计上就不可能**在该节点上有数据的,最好在面板说明里写清楚: - -- **PSI 面板**需要 `/proc/pressure`,而这台私有存储节点(NAS)的内核不暴露它——指标在这台机器上无法存在;同样的面板在会导出 `node_pressure_*` 的主机上正常显示。 -- **根文件系统面板**的表达式带 `fstype!="rootfs"`,而某台主机的 `/` 是**内存盘**(unRaid 就是),所以永远匹配不到。 - -区分\"因为 bug 空\"和\"因为这台机器不可能有这个指标而空\",是真修好和瞎忙一下午的分界线。 - -## 我下次会怎么做 - -- **永远不要定义过滤自己的模板变量。** 一个变量只跳一层。 -- **给面板依赖的变量存明确的 `current` 值**,别让全新加载依赖下拉框被选中。 -- **用 Grafana 存下来的值做验证**,而不是我以为的值。 -- **故意留空的缺口写进面板说明**,否则未来的你会花一个下午去\"修\"一个本来就没打算工作的面板。 - -## 结果 - -三台主机现在跑同一套布局——每台一个 41 面板的主机总览(25 个核心指标图表中分别有 21/23/25 个成功出数)+ 一个 10 面板的容器面板,两类结构性空缺写在面板说明里,而不是留给下一个打开它的人去猜。 - -## 需要为你的业务做这个吗? - -如果你有一堆没人信任的 Grafana 面板,或者服务器和 NAS 完全没有监控,我可以帮你搭自托管的 Prometheus + Grafana(主机与容器指标、合理的告警规则、通知推到 Telegram 和邮件),也会把你那些悄悄\"不出数\"的面板修好。 - -**WhatsApp:[+60 12-797 2969](https://wa.me/60127972969)** · **邮箱:[me@hoelee.com](mailto:me@hoelee.com?subject=Grafana%20monitoring)** · **[hoelee.com](https://hoelee.com)** - -网站设计与开发是我的主业;服务器加固与自托管基础设施是它的另一半。 -```` - -### 🇬🇧 英文版原文 (English Markdown Primary) -````markdown ---- -title: "Why Your Grafana Dashboard Shows No Data (When Prometheus Is Fine)" -description: "Every target up, data in Prometheus, panel expressions correct — and all 41 panels reading No data. The culprit was a Grafana variable filtering on itself, plus the verification habit that hid it." -pubDate: 2026-05-17 -updatedDate: 2026-09-29 -category: devops -blueprint: self-hosted-infrastructure -blueprintLayer: L3-observability-self-healing -tags: [grafana, prometheus, dashboards, monitoring, promql, observability] -ogImage: /og/why-your-grafana-dashboard-shows-no-data.jpg -banner: /banners/why-your-grafana-dashboard-shows-no-data.jpg -draft: false ---- - -You open the dashboard you use every day and it's empty. Not "one panel broke" empty — -**every panel**, top to bottom, says *No data*. You check Prometheus and everything is -healthy. This post is the specific, non-obvious cause I hit, and the way my own -verification convinced me the dashboard was fine while it wasn't. - -## The searchable question - -*My Grafana panels show No data but the data is in Prometheus — why?* - -The usual answers (wrong datasource, wrong time range, `rate()` on a counter that -resets, missing scrape target) did not apply. Here is the checklist that narrowed it -down, in the order that costs the least time: - -```bash -# 1. is the target actually being scraped? -curl -s http://prometheus:9090/api/v1/targets | jq '.data.activeTargets[] | {job:.labels.job, health}' - -# 2. does the metric exist right now? (bypasses Grafana entirely) -curl -s -G http://prometheus:9090/api/v1/query \ - --data-urlencode 'query=node_uname_info{job="unraid-host"}' | jq '.data.result[0].metric' - -# 3. is the panel's expression sound? -curl -s -G http://prometheus:9090/api/v1/query \ - --data-urlencode 'query=count(node_cpu_seconds_total{mode="idle",job="unraid-host"})' -``` - -All three were green: 7 targets `up`, 25k series ingested, and the panel's raw -expression returned data when I ran it by hand. So the problem was not the metrics, -the scrape, or the PromQL — it was **the variable layer between them**. - -## The actual cause: a variable that filtered on itself - -The dashboard had a host picker. Two variables chained: `$nodename` (which machine) -and `$node` (its `instance` label). The definition of the first one was: - -```promql -# BROKEN — the variable filters on its own value -label_values(node_uname_info{job="unraid-host", nodename=~"$nodename"}, nodename) -``` - -On first load `$nodename` has no value, so the selector becomes -`nodename=~""` — which matches **nothing**. A variable whose query returns no rows has -no options, so it stays empty. `$node` is then defined against `$nodename`: - -```promql -label_values(node_uname_info{job="unraid-host", nodename="$nodename"}, instance) -``` - -…which is also empty, so every panel filtering on `$node` matches no series. Grafana -isn't lying when it says *No data*: the panel query genuinely has no data, because the -variable that scopes it resolved to nothing. - -The fix is to stop the self-reference and give each variable an explicit saved default: - -```promql -# FIXED — no self-reference, one hop per variable -# $nodename -label_values(node_uname_info{job="unraid-host"}, nodename) -# $node -label_values(node_uname_info{job="unraid-host", nodename="$nodename"}, instance) -``` - -Then save `current` values for both so the dashboard opens populated instead of -depending on a click. (This is also why the same 41-panel layout can be cloned to -three hosts and just work.) - -## Why my verification missed it - -This is the part worth stealing. I "verified" the dashboard by expanding each panel's -expression **by hand**, substituting the variable values I knew were correct -(`$nodename=unRaid`, `$node=host.docker.internal:9100`), and asserting the query -returned points. Thirteen of those checks passed. The dashboard was still blank, -because the bug was upstream of the substitution: Grafana's *own* resolution of the -variables was empty. - -**A verification that substitutes the very value under suspicion cannot detect that -value failing to resolve.** To catch it, read the values Grafana actually saved and -expand with those: - -```bash -curl -s -u admin:"$PW" http://grafana:4010/api/dashboards/uid/rYdddlPWk \ - | jq '.dashboard.templating.list[] | {name, current: .current.value}' -``` - -The correct check is on the variable query itself — run what Grafana runs: - -```bash -# what does $nodename's label_values() actually return? -curl -s -G http://prometheus:9090/api/v1/query \ - --data-urlencode 'query=count by (nodename) (node_uname_info{job="unraid-host"})' | jq '.data.result' -``` - -Empty there means the dashboard cannot possibly render, no matter how healthy the data is. - -## The second trap: `$__all` is not `.*` - -While automating panel checks, a variable set to *All* reports its current value as the -sentinel string `$__all` — not a regex. Expanding panel expressions naively turns -`name=~"$__all"` into a literal that matches nothing, so a perfectly healthy -container dashboard "fails" every panel. Resolve `$__all` to the variable's `allValue` -(usually `.*`) before expanding, or you'll chase a bug that only exists in your checker. - -## Not every empty panel is a bug - -After the fix, out of the 41 total layout panels, **21 of the 25 core metric panels** returned data. The remaining four were empty **by design** and -worth naming honestly in the panel description: - -- **PSI panels** (`Pressure`, `Pressure Stall Information`) need `/proc/pressure`, which - the on-premise NAS storage node's kernel doesn't expose. The metric cannot exist there — the same panels on a - host that *does* export `node_pressure_*` render fine. -- **Root filesystem panels** whose expression carries `fstype!="rootfs"` can never match - on a host whose `/` is a **ramdisk**, which is what unRaid's root is. - -Distinguishing "broken because of a bug" from "empty because the metric cannot exist on -this host" is the difference between a real fix and a wild goose chase. - -## What I'd do differently - -- **Never define a template variable that filters on itself.** One hop per variable. -- **Always save explicit `current` values** for variables a dashboard depends on, so a - fresh load doesn't rely on a populated dropdown. -- **Verify with Grafana's saved values, not my idea of them.** The masking is invisible - in the test result and obvious in the UI. -- **Describe intentional gaps in the panel description.** Future-you will otherwise - spend an afternoon "fixing" a panel that was never meant to work there. - -## The result - -All three hosts now run the same instrumented layout — a 41-panel host dashboard (with 21/23/25 of the 25 core metric panels returning data respectively) and a -10-panel container dashboard each — and the two structurally-empty classes documented in place instead of silently -confusing whoever opens them next. - -## Want this for your business? - -If you have Grafana dashboards that nobody trusts — or servers and a NAS with no -monitoring at all — I build self-hosted Prometheus + Grafana stacks (host and container -metrics, sensible alert rules, alerts to Telegram and email) and I'll fix the ones that -have quietly stopped showing data. - -**WhatsApp: [+60 12-797 2969](https://wa.me/60127972969)** · **Email: [me@hoelee.com](mailto:me@hoelee.com?subject=Grafana%20monitoring)** · **[hoelee.com](https://hoelee.com)** - -Website design and development is my main line of work; server hardening and -self-hosted infrastructure is the other half of it. -```` - ---- - -## 文章 03 / 11:你的“磁盘将满”告警在说谎:别再按百分比告警 -- **Slug**: `your-disk-full-alert-is-lying` -- **英文标题**: Your Disk-Full Alert Is Lying: Stop Alerting on Percentages -- **分类**: `devops` | **发布日期**: 2026-06-24 -- **线上地址**: https://blog.hoelee.com/posts/your-disk-full-alert-is-lying/ (EN) | https://blog.hoelee.com/posts/zh/your-disk-full-alert-is-lying/ (ZH) -- **本篇审核状态**: ⏳ 待审核 (Pending) - -### ✍️ 顾问审阅意见区 (Review Feedback) -```text -【审阅结论】:[ ] 通过 [ ] 需微调 [ ] 需重构 -【事实与数字核对】: -【人设与用词卫生】: -【CRO与转化建议】: -``` - -### 🇨🇳 中文版原文 (Chinese Markdown Twin) -````markdown ---- -title: "你的“磁盘将满”告警在说谎:别再按百分比告警" -description: "\"剩余 3%\"听着像紧急事故,直到你发现那是 500 GB。在多 TB 的卷上,百分比阈值会在没事的时候乱叫,也会在真出事的时候沉默。" -pubDate: 2026-06-24 -updatedDate: 2026-09-29 -category: devops -blueprint: self-hosted-infrastructure -blueprintLayer: L3-observability-self-healing -tags: [monitoring, alerting, prometheus, grafana, storage, capacity, observability] -ogImage: /og/zh-your-disk-full-alert-is-lying.jpg -banner: /banners/your-disk-full-alert-is-lying.jpg -draft: false ---- - -我搭好监控、写了一套看着合理的规则,然后用一个下午删掉了其中大半阈值。它们全是百分比,而且都以同一种方式错了。 - -## 三个教我道理的告警 - -**1.「文件系统使用率超过 90%」**——它在一个还剩约 500 GB 的 17 TB 卷上触发。没事发生,也不会马上有事发生。这种体量的卷,一次大备份就能让百分比摆动几个点:比例是噪声,而\"还有 500 GB 可用\"才是世界的真实状态。 - -**2.「内存使用率超过 90%」**——在一台**可用**内存 4.8 GB 的主机上反复触发。Linux 会用空闲内存做 page cache,需要时立刻归还;`MemTotal - MemFree` 描述的是文件缓存,不是你的风险。真正预示 OOM 的是 `MemAvailable`。(即便改用 `MemAvailable` 按 90% 告警,在 64 GB 内存的节点上依然会在还剩 4.8 GB 可用内存时误报。) - -**3.「CPU steal 超过 25%」**——一台把邮件栈跑得完全正常的 VPS,steal 长期在 41%。steal 说明宿主机忙,它是**容量**信号而不是**故障**信号;7 vCPU 的机器 41% steal 就是这台机器的成本。这条规则产生的告警永远为真、也永远无用。 - -共同点:**我在对比例告警,而比例不知道东西有多大。** - -## 对\"后果\"告警,而不是对比例 - -我现在对每个阈值都问一句:*如果这个状态持续下去,实际会发生什么?* 答案几乎总能用绝对单位表达。 - -| 不要这样 | 改成 | 原因 | -|---|---|---| -| 文件系统 > 90% | 剩余空间 < N GB | \"我还能不能写进去\"才是问题 | -| 内存使用 > 90% | `MemAvailable` < 512 MB | 逼近 OOM,而不是\"缓存很暖和\" | -| CPU steal > 25% | steal > 50% | 容量成本 vs 真的被饿死 | -| 负载 > N | `load1 / 核数 > 2` | 不谈核数的负载没有意义 | - -PromQL 的前后对比: - -```promql -# BEFORE — 17 TB 卷的百分比;还剩半 TB 就开叫 -(1 - node_filesystem_avail_bytes / node_filesystem_size_bytes) * 100 > 90 - -# AFTER — 真正装数据的卷上,还剩多少容量 -min by (instance, mountpoint) ( - node_filesystem_avail_bytes{mountpoint=~"/volume[0-9]+|/mnt/ssd|/mnt/disk[0-9]+"} -) < 25e9 -``` - -```promql -# BEFORE — 把可回收的 page cache 也当成了内存压力(误用 MemFree) -(1 - node_memory_MemFree_bytes / node_memory_MemTotal_bytes) * 100 > 90 - -# AFTER — 基于内核可分配内存(MemAvailable)的真实 OOM 绝对值前兆 -node_memory_MemAvailable_bytes < 512 * 1024 * 1024 -``` - -两个让规则能活下来的细节: - -**把比较放进阈值条件里,不要塞进表达式。** 查询就写 `min by (mountpoint) (node_filesystem_avail_bytes{...})`,让告警规则去和 `25000000000` 比。若你在 PromQL 里写死 `< 25e9`、规则里又留着继承来的 `> 90`,规则照样会评估——但界面显示的阈值是错的,下一个读它的人得从两个互相矛盾的条件下反推你的意图。 - -**排除那些\"只是另一个挂载点的视图\"。** 一条\"剩余空间\"规则有多诚实,取决于它的选择器。在我自己的环境里,同一个 NAS 卷出现三次(`/volume1`、`/opt`、以及在另一台主机上以 CIFS 再次挂载),而 unRaid 的 shfs 联合挂载报告 `avail=0`——不加排除的规则不是永远误报,就是把容量算成两倍。一个写明白的选择器胜过聪明的通用写法。 - -## 噪声不是无害的 - -坏阈值的代价不在告警本身,而在**训练**:每条\"没事乱叫\"的告警都在教你先扫一眼、然后忽略;等你真正该看的那条到来时,它出现在一个你早已不再读的频道里。我的规则总数**减少了**,覆盖率却上升了——更少,但每条都对应一个明确的后果。 - -## 阈值是私人的,形状是通用的 - -上面的数字是我的:NAS 卷剩不到 25 GB 我会在意、可用内存低于 512 MB 我才管、VPS steal 超过 50% 才算被饿。你的数字随硬件和容忍度而变。 - -能通用的是形状: - -- 用绝对单位而非比例; -- 把后果写进告警的摘要里; -- 选择器明确声明它在替哪些挂载点说话; -- 规则数量少到你还能读完每一条。 - -## 结果 - -同一套栈,从\"三条永久无用报警\"变成 16 条在机房健康时保持安静的规则——其中一条立刻暴露了一个只剩 21 GB 的 NAS 卷,而那正是百分比规则一直藏在\"99% 满的巨物\"背后、被你学会忽略的东西。 - -## 需要为你的业务做这个吗? - -如果你的监控在发你已经学会忽略的告警,或者你根本没有监控、宁愿从一条规则而不是从一次失败的备份里得知磁盘满了,我可以帮你搭自托管的监控与告警(Prometheus + Grafana,通知推 Telegram 和邮件),阈值按\"什么会真的坏\"来定。 - -**WhatsApp:[+60 12-797 2969](https://wa.me/60127972969)** · **邮箱:[me@hoelee.com](mailto:me@hoelee.com?subject=Monitoring%20and%20alerting)** · **[hoelee.com](https://hoelee.com)** - -网站设计与开发是我的主业;服务器加固与自托管基础设施是它的另一半。 -```` - -### 🇬🇧 英文版原文 (English Markdown Primary) -````markdown ---- -title: "Your Disk-Full Alert Is Lying: Stop Alerting on Percentages" -description: "3% free sounds like an emergency until you notice it is 500 GB. On multi-terabyte volumes, percentage thresholds fire when nothing is wrong — and miss when something is." -pubDate: 2026-06-24 -updatedDate: 2026-09-29 -category: devops -blueprint: self-hosted-infrastructure -blueprintLayer: L3-observability-self-healing -tags: [monitoring, alerting, prometheus, grafana, storage, capacity, observability] -ogImage: /og/your-disk-full-alert-is-lying.jpg -banner: /banners/your-disk-full-alert-is-lying.jpg -draft: false ---- - -I built a monitoring stack, wrote a reasonable set of rules, and then spent an -afternoon deleting most of my own thresholds. Every one of them was a percentage, and -every one of them was wrong in the same specific way. - -## The three alerts that taught me - -**1. "Filesystem above 90% used."** It fired on a 17 TB volume that had ~500 GB free. -Nothing was wrong. Nothing was *about* to be wrong. On a volume that size, a single -large backup can swing the percentage by several points — the ratio is noise, and the -fact that 500 GB is still available is the actual state of the world. - -**2. "Memory above 90% used."** Fired constantly on a host with 4.8 GB *available*. -Linux uses free RAM for page cache and gives it back on demand; `MemTotal - MemFree` -describes your filesystem cache, not your risk. The number that predicts an OOM is -`MemAvailable`. (Even if one alerts on `MemAvailable` exceeding 90% capacity, on a 64 GB host it still fires an alert when 4.8 GB of usable headroom remains.) - -**3. "CPU steal above 25%."** Fired on a VPS that had been running its mail stack -perfectly at 41% steal. Steal means the hypervisor is busy — it is a *capacity* signal, -not a *failure* signal, and 41% steal on a 7-vCPU box was simply what that host costs. -The rule produced alerts that were always true and never actionable. - -The common thread: **I was alerting on a ratio, and the ratio doesn't know how big the -thing is.** - -## Alert on the consequence, not the ratio - -The test I now apply to every threshold: *if this condition persists, what will actually -happen?* That answer is almost always expressible in absolute units. - -| Instead of | Alert on | Because | -|---|---|---| -| Filesystem > 90% | Free space < N GB | "Can I still write?" is the question | -| Memory > 90% used | `MemAvailable` < 512 MB | about to OOM, not "cache is warm" | -| CPU steal > 25% | Steal > 50% | capacity cost vs. starvation | -| Load average > N | `load1 / cores > 2` | load is meaningless without core count | - -In PromQL, before and after: - -```promql -# BEFORE — percentage of a 17 TB pool; fires with half a terabyte still free -(1 - node_filesystem_avail_bytes / node_filesystem_size_bytes) * 100 > 90 - -# AFTER — capacity left, on the volumes that hold data -min by (instance, mountpoint) ( - node_filesystem_avail_bytes{mountpoint=~"/volume[0-9]+|/mnt/ssd|/mnt/disk[0-9]+"} -) < 25e9 -``` - -```promql -# BEFORE — page cache counted as "pressure" (misusing MemFree) -(1 - node_memory_MemFree_bytes / node_memory_MemTotal_bytes) * 100 > 90 - -# AFTER — the actual OOM precursor based on kernel-reclaimable MemAvailable -node_memory_MemAvailable_bytes < 512 * 1024 * 1024 -``` - -Two details that make these rules survive contact with a real dashboard: - -**Keep the comparison in the threshold condition, not inside the expression.** Query -`min by (mountpoint) (node_filesystem_avail_bytes{...})`, then let the alert rule -compare it to `25000000000`. If you bake `< 25e9` into the PromQL *and* leave an -inherited `> 90` in the rule, the rule still evaluates — but it displays a nonsense -threshold, and the next person to read it has to reconstruct your intent from two -contradictory conditions. - -**Exclude the mounts that are views of other mounts.** A "free space" rule is only as -honest as its selector. On my own setup, one NAS volume appears three times (as -`/volume1`, as `/opt`, and again on another host as a CIFS re-mount), and unRaid's shfs -union mount reports `avail=0` — a rule without exclusions would either fire forever or -double-count capacity. One explicit selector beats a clever generic one: - -```promql -node_filesystem_avail_bytes{mountpoint=~"/volume[0-9]+|/mnt/ssd|/mnt/disk[0-9]+"} -``` - -## Noise is not harmless - -The cost of a bad threshold isn't the alert itself — it's the *training*. Every alert -that fires while nothing is wrong teaches you to skim, then to ignore, and then the one -that matters arrives in a channel you've stopped reading. My rule count went **down** -while coverage went up: fewer, each tied to a named consequence. - -## Thresholds are personal, shapes are not - -The specific numbers above are mine — 25 GB free before a NAS volume bothers me, 512 MB -available before I care about memory, 50% steal before a VPS is being starved. Yours -will differ with your hardware and your tolerance. - -What transfers is the shape: - -- absolute units over ratios, -- the consequence written into the alert's summary, -- a selector that states exactly which mounts it speaks for, -- and a rule count small enough that you still read every message. - -## The result - -The same stack that was producing three permanent, uninformative warnings now runs 16 -rules that stay silent when the infrastructure is healthy — and one of them immediately surfaced a -NAS volume sitting at 21 GB free, which is the kind of thing a percentage rule had been -hiding behind a 99%-full giant that I'd learned to ignore. - -## Want this for your business? - -If your monitoring sends you alerts you've learned to ignore, or you have none and would -rather find out about a full disk from a rule than from a failed backup, I set up -self-hosted monitoring and alerting (Prometheus + Grafana, alerts to Telegram and email) -with thresholds tied to what actually breaks. - -**WhatsApp: [+60 12-797 2969](https://wa.me/60127972969)** · **Email: [me@hoelee.com](mailto:me@hoelee.com?subject=Monitoring%20and%20alerting)** · **[hoelee.com](https://hoelee.com)** - -Website design and development is my main line of work; server hardening and -self-hosted infrastructure is the other half of it. -```` - ---- - -## 文章 04 / 11:浏览器翻译没有 API:我给一个纯中文网页应用加上了英文模式 -- **Slug**: `adding-english-mode-to-a-chinese-only-web-app` -- **英文标题**: No API for Browser Translation: Adding an English Mode to a Chinese-Only Web App -- **分类**: `engineering` | **发布日期**: 2025-06-11 -- **线上地址**: https://blog.hoelee.com/posts/adding-english-mode-to-a-chinese-only-web-app/ (EN) | https://blog.hoelee.com/posts/zh/adding-english-mode-to-a-chinese-only-web-app/ (ZH) -- **本篇审核状态**: ⏳ 待审核 (Pending) - -### ✍️ 顾问审阅意见区 (Review Feedback) -```text -【审阅结论】:[ ] 通过 [ ] 需微调 [ ] 需重构 -【事实与数字核对】: -【人设与用词卫生】: -【CRO与转化建议】: -``` - -### 🇨🇳 中文版原文 (Chinese Markdown Twin) -````markdown ---- -title: "浏览器翻译没有 API:我给一个纯中文网页应用加上了英文模式" -description: "浏览器不提供触发翻译的 JavaScript API,而我的应用明明是中文却声明自己是英文。于是我改用反向代理,把一个英文模式注入进去。" -pubDate: 2025-06-11 -updatedDate: 2026-09-29 -category: engineering -blueprint: sme-digital-suite -blueprintLayer: L1-high-conversion-web -tags: ["i18n", "nginx", "vue", "javascript", "self-hosting"] -ogImage: "/og/zh-adding-english-mode-to-a-chinese-only-web-app.jpg" -banner: "/banners/adding-english-mode-to-a-chinese-only-web-app.jpg" -draft: false ---- - -「能不能用 JavaScript 触发浏览器自带的翻译?」答案是**不能**。接受这一点花了我一个下午 —— 但更有意思的发现出现在前面:我的应用其实一直在破坏浏览器的翻译功能,而且只用一个属性就做到了。 - -## 我在做什么 - -我维护着一个私人的邀请制阅读平台 `book.hoelee.com`:自建的阅读器(Kotlin/Spring 后端 + Vue 单页应用),装着我自己的藏书,并给受邀读者开了账号。界面是纯中文 —— 不是「以中文为主」,而是**只有中文**。我在相信这一点之前把每个前端 bundle 都翻了一遍:没有 i18n 库、没有语言包、没有语言切换,只有一个简繁转换表和一堆英文 TTS 语音名。 - -后来我开始把邀请卡发给只说英文的读者。他们能注册,然后迎面撞上:书架、浏览书仓、确定、设置 —— 每一个控件都在他们读不懂的语言里。这不是「体验不够精致」的问题。对我邀请的一半人来说,这个产品是不可用的。 - -有一条约束决定了后面所有做法:**我不改这个应用。** 它的上游仓库已经归档,界面是压缩过的 Vue bundle —— 任何我打进镜像里的补丁,都会在下一次换镜像时消失。所以我做的东西必须待在**外面一层**:我已经架在应用前面的那个 nginx 网关。 - -## 发现一:应用声明了自己错误的语言,而这会关掉翻译 - -写代码之前,我先看看浏览器到底看到了什么: - -```bash -$ curl -s https://book.hoelee.com/index.html | grep -o ']*>' - -``` - -外壳声明英文,界面 100% 中文。 - -这件事比看上去严重。Chrome、Edge、Safari 决定「要不要**主动提示**翻译」,很大程度取决于页面声明的语言。一个声明自己是英文、却渲染中文内容的页面,不会得到那个「要翻译此页面吗?」的提示 —— 对我的新读者来说最有用的一项无障碍功能,就这么被悄悄关掉了;而「右键 → 翻译成中文/英文」是大多数人从来不知道的操作。 - -修复只要一行,而且是作用在**响应出站时**,不是打进应用里: - -```nginx -location = /index.html { - # sub_filter 不能改写 gzip 后的内容 -> 让上游返回未压缩的 HTML - proxy_set_header Accept-Encoding ""; - sub_filter_once on; - # 应用声明 lang="en" 而界面是中文 -> 浏览器因此永远不提示中译英。 - # 说出事实。 - sub_filter '' ''; - proxy_pass http://hectorqin-reader:8080; -} -``` - -用发现它的方式验证:`curl -s https://book.hoelee.com/index.html | grep -o '' ''; - proxy_pass http://hectorqin-reader:8080; -} -``` - -整个部署就是这样:一个 40 KB 的脚本,只在 `/index.html` 加载,所以按钮只存在于应用内,别处都没有。脚本做三件事。 - -### 1. 从应用自己的 bundle 里「收割」词汇表 - -界面文案本来就在压缩后的 JavaScript 里,以字符串字面量的形式存在。把所有含中日韩字符的字符串抓出来并计数: - -```python -import re, collections -CJK = re.compile(r'[\u4e00-\u9fff]') -count = collections.Counter() -for bundle in bundles: - for m in re.finditer(r'"([^"\\\n]{2,40})"', bundle): - if CJK.search(m.group(1)): - count[m.group(1)] += 1 -print(len(count)) # 840 条唯一字符串,按出现频率排序 -``` - -跑出 840 条唯一字符串:菜单(书架、书源管理)、确认框(确认要删除所选择的书籍吗?)、设置项(段落行距)、错误信息(本地书籍源文件不存在)。词典最终是 **871 条** —— 收割来的,加上我在英文模式下实际使用应用、看还有什么没翻而补上的。 - -### 2. 按 DOM 的真实样子匹配,而不是你希望的样子 - -朴素的子串替换会毁掉中文词组:书架 就藏在 加入书架 里面,单字更糟(页 藏在 页面 里)。三条规则解决了它: - -- **先做整标签匹配,基于去掉空白后的文本。** 应用里的标签是 `" 书架 "` 这种带空格的,所以词典里的 `设置` 必须能匹配 DOM 里的 `" 设置 "`。 -- **然后是最长优先的子串替换**,只允许长度 ≥ 2 的键参与。 -- **单字键只做整标签匹配**(章、页、条),这样它们永远不可能破坏更长的词。 - -```js -function tr(s) { - if (!s || !CJK.test(s)) return s; - var hit = EXACT[s.replace(/[\s\u3000]/g, '')]; // 整标签匹配,空白归一化 - if (hit) return keepWS(s, hit); - var t = s; - for (var i = 0; i < KEYS.length; i++) { // KEYS:最长优先,长度 >= 2 - if (t.indexOf(KEYS[i]) >= 0) t = t.split(KEYS[i]).join(DICT[KEYS[i]]); - } - // 收拾数量短语:共58个可用书源 -> "58 usable sources" - return t.replace(/共\s*(\d+)/g, '$1').replace(/(\d+)\s*个/g, '$1').replace(/(\d)([A-Za-z])/g, '$1 $2'); -} -``` - -### 3. 跟上框架的重绘 - -它是 Vue 应用,DOM 一直在被重写 —— 只跑一次的翻译,一秒后就有一半是错的。一个带 150 ms 防抖的 `MutationObserver`,在任何变化之后重跑一遍遍历。 - -这一遍是幂等的:标签一旦变成英文就不再含中日韩字符,于是不会被再写一次,也不会形成写入循环。文本节点之外,`placeholder`、`title`、`aria-label`、`alt` 和输入框的 `value` 也会翻译 —— 所以提示气泡和搜索框也一起变英文了。 - -UI 是右下角的一个小胶囊:关闭时显示 `EN`,开启后显示 `中文`,选择记在 `localStorage`,还提供「隐藏此按钮」给更愿意用自己翻译器的读者。 - -## 它**刻意**不翻译什么 - -**书籍正文。** 阅读器把 EPUB 内容渲染在 iframe 里,我的遍历器按设计跳过 iframe —— 而且我无论如何也不会去机器替换一本小说的正文。 - -同样保持原样的还有:书名与作者、书源名称、我自己建的分组名(技术、历史、传记),以及应用那句诗。这些是**数据**,不是界面。翻译界面是一种体贴;悄悄改写用户自己的内容是另一回事,而且糟糕得多。 - -书籍正文仍然交给浏览器自带的翻译 —— 而且因为「发现一」,它现在真的会被提示出来。按钮的弹窗里就是这么写的。 - -## 要量,不要用眼睛看 - -「截图看起来基本是英文了」不算结果。我在开关按钮的前后,数了实时 DOM 里含中日韩字符的文本节点: - -```js -let cjk = 0, total = 0; // 遍历器跳过注入的 UI 与 script/style -while ((n = walker.nextNode())) { - const t = n.nodeValue.trim(); - if (!t) continue; - total++; - if (/[\u4e00-\u9fff]/.test(t)) cjk++; -} -``` - -| 界面 | 之前 | 之后 | 已翻译 | -|---|---|---|---| -| 登录 / 注册对话框 | 80 | 12 | 85% | -| 书架 + 设置 | 259 | 60 | 77% | -| 阅读页界面 | 214 | 31 | 86% | - -那些界面里仍被计为中文的,全部是数据 —— 书名、作者、书源名、我自己的分组名、那句诗 —— 正是应该保持中文的部分。 - -## 我会怎么做得不一样 - -**不要用手工重写一份 871 条的词典。** 我重构过一次,静默丢了 25 个键。症状看起来像逻辑 bug:设置 还是中文,而它的每个兄弟标签都翻译正常。匹配器没问题 —— 是**条目**不见了。在你相信一次重写之前,用程序对比键集合: - -```bash -python -c "print(sorted(set(old_keys) - set(new_keys)))" -``` - -**自动化 UI 检查要写短。** 我的无头运行器每次调用硬超时 60 秒。一个遍历六本书的循环返回 HTTP 408 和空 body,而我的 JSON 解析器报的是「解析错误」而不是「超时」—— 我一度在查错的东西。 - -**调试之前先搞清楚 SPA 的真实路由。** `#/reader/1` 会渲染出一个空白外壳,让人以为应用坏了;真正的路由是 `#/reader?bookUrl=`。 - -**注意你自己的跳转逻辑。** 我的网关会把任何刷新送回前台页,除非设置了 `sessionStorage` 的通行标记。把界面切**回**中文会重载页面 —— 所以按钮会先设好同一个标记,否则读者会因为改了个语言设置被踢出应用。 - -## 结果 - -一个只懂英文的读者,现在打开平台、点一下按钮,就能用英文读界面。应用本身没有被改动:整个功能只是一个由 sidecar nginx 容器提供的 40 KB 脚本,所以下一次换镜像不可能弄坏它;而浏览器自带的翻译,终于有一个会声明自己真实语言的页面可以配合。 - -我留下的经验:**当平台不给你 API 时,往外看一层。** 反向代理是添加「应用里加不了的行为」的正当位置 —— 而且通常是唯一能在升级中存活的位置。 - ---- - -*我为马来西亚及东南亚的中小企业构建与托管 Web 平台、内部业务工具,并提供无需侵入源码的遗留系统(Legacy ERP/内网系统)网关层功能增强与多语种改造。有需要可以找我:[WhatsApp +60 12-797 2969](https://wa.me/60127972969)、[me@hoelee.com](mailto:me@hoelee.com?subject=Self-hosted%20platform),或访问 [hoelee.com](https://www.hoelee.com)。* -```` - -### 🇬🇧 英文版原文 (English Markdown Primary) -````markdown ---- -title: "No API for Browser Translation: Adding an English Mode to a Chinese-Only Web App" -description: "Browsers expose no JavaScript API to trigger translation — and my app declared English while being Chinese. How I injected an English mode at the reverse proxy." -pubDate: 2025-06-11 -updatedDate: 2026-09-29 -category: engineering -blueprint: sme-digital-suite -blueprintLayer: L1-high-conversion-web -tags: ["i18n", "nginx", "vue", "javascript", "self-hosting"] -ogImage: "/og/adding-english-mode-to-a-chinese-only-web-app.jpg" -banner: "/banners/adding-english-mode-to-a-chinese-only-web-app.jpg" -draft: false ---- - -Can I trigger the browser's translate feature from JavaScript? No. That answer cost me an afternoon to accept — but the more interesting discovery came first: my app was already sabotaging the browser's translation, and it did it with a single attribute. - -## What I was working on - -I run a private, invite-only reading platform at `book.hoelee.com`: a self-hosted reader (Kotlin/Spring backend, Vue single-page app) holding my library, with accounts for invited readers. The interface is Chinese-only. Not "Chinese-first" — *only*. I grepped every served bundle before believing it: no i18n library, no locale files, no language switcher. Just a Simplified/Traditional character converter and a list of English TTS voice names. - -Then I started handing out invite cards to English-speaking readers. They could register, and then they met 书架, 浏览书仓, 确定, 设置 — every control in a language they don't read. That isn't a polish problem. For half the people I invited, the product was unusable. - -One constraint shaped everything that follows: **I don't modify the app.** Its upstream repository is archived and the UI is a minified Vue bundle, so anything I patch inside the image dies the next time I swap the image. Whatever I build has to live one layer out — in the nginx gateway I already run in front of the app. - -## Finding 1: the app declares the wrong language, and that disables translation - -Before writing a single line of code, I looked at what the browser sees: - -```bash -$ curl -s https://book.hoelee.com/index.html | grep -o ']*>' - -``` - -The shell says English. The interface is 100% Chinese. - -That matters more than it looks. Chrome, Edge and Safari decide whether to *offer* translation largely from the page's declared language. A page that declares English while rendering Chinese text doesn't get the "Translate this page?" prompt — the single most useful accessibility feature for my new readers was silently switched off, and right-click → *Translate to English* is a ritual most people never learn. - -The fix is one line, applied to the response on the way out instead of inside the app: - -```nginx -location = /index.html { - # sub_filter cannot rewrite a gzipped body -> ask upstream for plain HTML - proxy_set_header Accept-Encoding ""; - sub_filter_once on; - # the app declares lang="en" while its UI is Chinese -> browsers then never - # offer Chinese -> English translation. Declare the truth. - sub_filter '' ''; - proxy_pass http://hectorqin-reader:8080; -} -``` - -Verify the same way you found it: `curl -s https://book.hoelee.com/index.html | grep -o '' ''; - proxy_pass http://hectorqin-reader:8080; -} -``` - -That's the whole deployment: a 40 KB script, loaded only on `/index.html`, so the button exists inside the app and nowhere else. The script does three things. - -### 1. Harvest the vocabulary from the app's own bundles - -The UI strings are already in the minified JavaScript as quoted literals. Extract every one that contains a CJK character and count them: - -```python -import re, collections -CJK = re.compile(r'[\u4e00-\u9fff]') -count = collections.Counter() -for bundle in bundles: - for m in re.finditer(r'"([^"\\\n]{2,40})"', bundle): - if CJK.search(m.group(1)): - count[m.group(1)] += 1 -print(len(count)) # 840 unique strings, most frequent first -``` - -840 unique strings came out: menus (书架, 书源管理), confirmations (确认要删除所选择的书籍吗?), settings labels (段落行距), error messages (本地书籍源文件不存在). The dictionary ended up at **871 entries** — the harvest plus everything I found by running the app in English mode and watching what stayed Chinese. - -### 2. Match like the DOM actually is, not like you wish it were - -Naive substring replacement mangles Chinese compounds: 书架 sits inside 加入书架, and single characters are worse (页 inside 页面). Three rules fixed it: - -- **Whole-label match first, on whitespace-stripped text.** The app stores labels like `" 书架 "` with padding, so a dictionary key of `设置` has to match `" 设置 "` in the DOM. -- **Then longest-first substring replacement**, restricted to keys of two or more characters. -- **One-character keys are whole-label only** (章, 页, 条), so they can never corrupt a longer word. - -```js -function tr(s) { - if (!s || !CJK.test(s)) return s; - var hit = EXACT[s.replace(/[\s\u3000]/g, '')]; // whole label, whitespace-normalised - if (hit) return keepWS(s, hit); - var t = s; - for (var i = 0; i < KEYS.length; i++) { // KEYS: longest-first, length >= 2 - if (t.indexOf(KEYS[i]) >= 0) t = t.split(KEYS[i]).join(DICT[KEYS[i]]); - } - // tidy count phrases: 共58个可用书源 -> "58 usable sources" - return t.replace(/共\s*(\d+)/g, '$1').replace(/(\d+)\s*个/g, '$1').replace(/(\d)([A-Za-z])/g, '$1 $2'); -} -``` - -### 3. Keep up with the framework - -It's a Vue app, so the DOM is rewritten constantly — a translation pass that runs once is a translation pass that's half wrong a second later. A `MutationObserver` with a 150 ms debounce re-runs the walk after any change. - -The pass is idempotent: once a label is English it contains no CJK, so nothing is rewritten and there is no write loop. Text nodes plus `placeholder`, `title`, `aria-label`, `alt` and input `value` attributes all get translated, which is why tooltips and the search box come along too. - -The UI is a small pill in the bottom-right corner: `EN` when off, `中文` when on, remembered in `localStorage`, with a "Hide this button" link for readers who prefer their own translator. - -## What it deliberately does not translate - -**Book text.** The reader renders EPUB content inside an iframe; my walker skips iframes by design, and I would never machine-swap a novel's prose anyway. - -Also left alone: book titles and authors, book-source names, and the group names I created myself (技术, 历史, 传记), plus the app's poem tagline. Those are *data*, not interface. Translating the chrome is a courtesy; silently rewriting a user's own content is a different and much worse idea. - -For book text the browser's own translation is still the right tool — and it now actually gets offered, thanks to Finding 1. The button's popup says exactly that. - -## Measure it, don't eyeball it - -"Screenshots look mostly English" is not a result. I counted CJK-containing text nodes in the live DOM before and after toggling the button: - -```js -let cjk = 0, total = 0; // walker skips the injected UI + script/style -while ((n = walker.nextNode())) { - const t = n.nodeValue.trim(); - if (!t) continue; - total++; - if (/[\u4e00-\u9fff]/.test(t)) cjk++; -} -``` - -| Screen | Before | After | Translated | -|---|---|---|---| -| Login / register dialog | 80 | 12 | 85% | -| Bookshelf + settings | 259 | 60 | 77% | -| Reading page chrome | 214 | 31 | 86% | - -Everything still counted as Chinese on those screens is data — titles, authors, source names, my own group names, the tagline — which is exactly what should stay Chinese. - -## What I'd do differently - -**Don't rewrite an 871-entry dictionary by hand.** I restructured mine once and silently dropped 25 keys. The symptom looked like a logic bug: 设置 stayed Chinese while every sibling label translated correctly. The matcher was fine — the *entry* was gone. Diff the key sets programmatically before you trust a rewrite: - -```bash -python -c "print(sorted(set(old_keys) - set(new_keys)))" -``` - -**Keep automated UI checks short.** My headless runner hard-times-out at 60 seconds per call. A six-book loop came back HTTP 408 with an empty body, and my JSON parser reported a parse error rather than a timeout — I debugged the wrong thing for a while. - -**Learn the SPA's real routes before debugging it.** `#/reader/1` renders a blank shell and makes you think the app is broken; the actual route is `#/reader?bookUrl=`. - -**Mind your own bounce logic.** My gateway sends any reload back to the front page unless a `sessionStorage` pass flag is set. Switching the interface *back* to Chinese reloads the page — so the button sets that same flag first, or the reader gets thrown out of the app for changing a language setting. - -## Result - -An English-only reader now opens the platform, taps one button, and reads the interface in English. The app itself is untouched: the whole feature is a 40 KB script served by a sidecar nginx container, so the next image update cannot break it, and the browser's own translation has a page that declares its real language to work with. - -The lesson I'm keeping: **when the platform won't give you an API, look one layer out.** A reverse proxy is a legitimate place to add behaviour you can't add in the app — and it's usually the only place that survives upgrades. - ---- - -*I build and self-host web platforms, internal business tools, and non-invasive reverse-proxy enhancements (such as localising closed-source or legacy systems) for SMEs in Malaysia. If you need something similar: [WhatsApp +60 12-797 2969](https://wa.me/60127972969), [me@hoelee.com](mailto:me@hoelee.com?subject=Self-hosted%20platform), or [hoelee.com](https://www.hoelee.com).* -```` - ---- - -## 文章 05 / 11:排查 Remotion 视频抽搐:为什么在背景图挂载音频低频 Scale 会毁了转场 -- **Slug**: `debugging-remotion-video-jitter` -- **英文标题**: Debugging Remotion Video Jitter: Why Bass Scaling Ruins Background Transitions -- **分类**: `engineering` | **发布日期**: 2025-11-26 -- **线上地址**: https://blog.hoelee.com/posts/debugging-remotion-video-jitter/ (EN) | https://blog.hoelee.com/posts/zh/debugging-remotion-video-jitter/ (ZH) -- **本篇审核状态**: ⏳ 待审核 (Pending) - -### ✍️ 顾问审阅意见区 (Review Feedback) -```text -【审阅结论】:[ ] 通过 [ ] 需微调 [ ] 需重构 -【事实与数字核对】: -【人设与用词卫生】: -【CRO与转化建议】: -``` - -### 🇨🇳 中文版原文 (Chinese Markdown Twin) -````markdown ---- -title: "排查 Remotion 视频抽搐:为什么在背景图挂载音频低频 Scale 会毁了转场" -description: "深入排查 Remotion 音频可视化中背景画面剧烈抽搐与切镜暗闪的根本原因:解耦 HUD 与背景图层,以及纯净单向叠化与硬件基准实测对比。" -pubDate: 2025-11-26 -updatedDate: 2026-10-22 -category: engineering -stream: creative-lab -tags: ["remotion", "react", "audio-visualizer", "css-animation", "debugging"] -ogImage: "/og/zh-debugging-remotion-video-jitter.jpg" -banner: "/banners/debugging-remotion-video-jitter.jpg" -draft: false ---- - -使用 React 和 Remotion 编写自动化视频赋予了开发者对每一帧画面的极致掌控。你可以直接将 Web Audio 的频域分析数据映射到 SVG 属性、CSS 变换矩阵以及排版样式上,这种灵活性是传统非线性剪辑软件很难比拟的。 - -然而,将视频帧当作常规网页来渲染时,极易踩入微妙的视觉陷阱。在我们的自动化音乐视频生成管线中,一个在开发组件预览时看似完全正常的设计,在全量导出为 1080P 30fps 视频后,却出现了极其刺眼、让人目眩的“地震式剧烈抽搐”。 - -本文记录这次视觉 BUG 的深度排查过程:为什么对音频动效的朴素直觉会毁了整部视频,以及如何重构 React 视频图层架构以实现丝滑稳定的影视级转场。 - -> **线上成品验证**:修复后的渲染流水线已正式交付并发布至 YouTube:[《糖画小仙》1080p 官方 MV](https://youtu.be/vZbyKeCCSRA),全片背景稳固、转场平滑。 - -> **TL;DR** —— 让整幅背景图跟着低频段缩放,等于每一帧都重新做图像插值采样,肉眼读到的就是剧烈抖动与震颤;再加上两层半透明图层对称交叉淡化,在时间中点必然透出底层的黑色容器。修复方案:背景画面绝对静态,将所有音频动效彻底隔离在顶层 HUD 频谱层,转场采用「100% 实体底图 + 顶层单向淡入」。渲染耗时实测**缩短 38.0%(从 352 秒降至 218 秒,吞吐速度提升 1.61 倍)**。这一篇是 [全自动 MV 生成流水线](/posts/zh/how-i-built-an-automated-music-video-pipeline/) 的渲染篇;文件落盘与发布那一半见 [Docker 容器大文件上传](/posts/zh/uploading-large-videos-to-youtube-via-cdp/)。 - ---- - -## 1. 故障现象:全画面的“高频地震” - -该视频合成组件最初的视觉设想非常清晰: -1. 底层是一组 1080P 高清插画分镜,在不同章节间慢速淡入淡出(Crossfade); -2. 画面上方浮动一个跟随音乐重音律动的环形音频频谱仪; -3. 三行书法歌词居中显示在音频环内,并根据每张插画的主体位置在画面左右两侧平滑滑移避让。 - -在开发工具里单帧点按检查时,画面一切正常。但在以 30fps 正常播放渲染出的成片时,肉眼观感极度难受:每当强烈的电子重音鼓点响起,整张背景图每秒剧烈颤抖震荡数十次;不仅如此,在两张图片交替切镜的 1.8 秒窗口内,画面中央还会突然闪现明显的“暗黑闪烁”,亮度瞬间下沉。 - ---- - -## 2. 根因分析一:低频 Scale 能量污染背景图 - -翻阅最初的 `BackgroundSlideshow.tsx` 组件,我们发现了一段看似合情合理的动效代码: - -```tsx -// 埋下灾难的罪魁祸首代码 -const bassScale = interpolate(bassLevel, [0, 1], [1.0, 1.025], { - extrapolateRight: 'clamp', -}); - -// 应用在全屏背景图片上: - -``` - -在直觉中,重低音响起时让背景图随着节奏轻微放大 2.5%,听起来像是在模拟动感的镜头呼吸感。然而在真实物理渲染中: -- **电音鼓点的瞬态脉冲只有 30~60 毫秒**:低频能量在连续 2 到 3 帧之内瞬间从零冲上顶峰,又在下一帧骤跌回原点; -- **1920x1080 的巨幅背景图放大 2.5%,边缘物理像素瞬间位移多达 25 到 30 像素**; -- 这种在相邻帧之间急剧拉扯的剧烈像素位移,人眼接收到的根本不是“音乐律动”,而是被视网膜本能判定为**强烈的镜头颠簸、抽动与丢帧残影**; -- 更致命的是,在 1.8 秒的交叉淡入淡出期间,两张重叠的图片各自具有不同的锚点和缩放系数,两层图像以不同的相位同时高频抖动,产生了极其混乱的重影眩晕感。 - ---- - -## 3. 根因分析二:对称线性透明度重叠时的“黑闪”陷阱 - -第二个问题是切镜时的亮度下陷黑闪。在传统 Web CSS 中,人们通常很自然地写出: - -```css -/* 常见的渐变叠化陷阱 */ -.current-slide { opacity: 1 -> 0; } -.next-slide { opacity: 0 -> 1; } -``` - -当两张图片都以线性渐变进行透明度变换时,在正中间那颗时间点($t = 0.5$): -- 当前图片透明度 = 0.5 -- 下一张图片透明度 = 0.5 - -来看浏览器和 Remotion 的合成器是如何将这几层叠在底层的纯黑容器之上的: - -``` -┌─────────────────────────────────────────────────────────────┐ -│ Layer 2: 下一张图片(Next Slide,透明度 = 0.5) │ -├─────────────────────────────────────────────────────────────┤ -│ Layer 1: 当前图片(Current Slide,透明度 = 0.5) │ -├─────────────────────────────────────────────────────────────┤ -│ Layer 0: 根容器底色(Root Container,背景色 = #000000 纯黑) │ -└─────────────────────────────────────────────────────────────┘ -``` - -由于多层半透明通道是依次向下进行乘法 Alpha 混合: -$$\text{有效综合不透明度} = 1 - (1 - 0.5) \times (1 - 0.5) = 1 - 0.25 = 0.75$$ - -合成后的总有效透明度只有 **0.75**,这意味着多达 **25% 的底层纯黑背景**被暴露了出来!这不是错觉,而是纯粹的数学光度衰减。每一次转场切镜,画面整体照度都会凭空跌掉四分之一,造成非常明显的瞬间暗淡闪烁。 - ---- - -## 4. 重构方案:稳固基座 + 纯净单向叠化 - -找到症结后,我们对组件进行了彻底重构: - -### 1. 彻底剥离背景图层的所有音频缩放 -背景插画必须稳如磐石。所有的音频跳动、瞬态光斑与能量爆发,**只能且必须限定在顶层的 HUD 频谱仪中**。背景层坚决不承载任何高频振荡属性。 - -### 2. 底层 100% 实体 + 顶层单向平滑淡入 -坚决不要让底图淡出。**当前图片始终保持 100% 不透明**,下一张图片直接覆盖在其上方,慢速执行 `0 -> 1.0` 的单向淡入: - -```tsx -const fullBleed = { position: 'absolute', width: '100%', height: '100%', objectFit: 'cover' }; - -return ( -
- {/* 1. 底层图片:坚固不透明,彻底消除暗黑闪烁 */} - - - {/* 2. 顶层图片:在 1.8 秒内平滑淡入 (0 -> 1.0) */} - {isTransitioning && ( - - )} -
-); -``` - -### 3. HUD 与背景物理层级绝对隔离 -歌词弹幕与音频环容器设置在独立的顶层图层中,并赋予 `pointerEvents: 'none'`。歌词在留白侧之间的横向位移完全根据当前时间戳自主计算,与底层的图片渐变完全物理隔离,互不干涉。 - ---- - -## 5. 改造后的成效与基准复现 - -重构落地后,对比极其显著: - -1. **彻底消除画面抖动**:无论音乐鼓点多么狂暴密集,背景画面在所有测试分镜中纹丝不动,人物与细节清晰稳定; -2. **转场不再发生黑闪**:1.8 秒的单向贝塞尔叠化始终保持 100% 连续亮度,杜绝了中间态透出底层黑色的缺陷; -3. **渲染吞吐速度大幅提升**:移除了对超大尺寸背景图的高频矩阵重算后,渲染性能获得了实测提升。 - -### 基准实测与硬件复现条件 - -| 评估指标 | 优化前版本 | 优化后版本 | 变化幅度与提升 | -|---|---|---|---| -| **渲染总耗时** | 352.0 秒 | 218.3 秒 | **耗时减少 38.0% (-133.7s)** | -| **平均渲染帧率** | 22.24 fps | 35.87 fps | **吞吐速度提升 1.61 倍** | -| **总计处理帧数** | 7,830 帧 | 7,830 帧 | 完全一致(261 秒 / 4 分 21 秒) | -| **输出视频规格** | 1920 × 1080 (1080p @ 30fps) | 1920 × 1080 (1080p @ 30fps) | 完全一致 | -| **编码器设置** | H.264 (CRF 18, preset medium) | H.264 (CRF 18, preset medium) | 完全一致 | - -**基准测试宿主环境:** -- **CPU**:Intel Core i9-13900K(24 核 / 32 线程,最高睿频 5.8 GHz) -- **GPU**:NVIDIA GeForce RTX 3060(12GB GDDR6 显存,驱动版本 551.xx) -- **内存**:64GB DDR5 5600 MHz -- **系统**:Windows 11 专业版 64 位 -- **软件栈**:Node.js v20.x,Remotion v4.0.x,开启 Chromium 无头 GPU 加速 - -两次基准测试均在同一工作站、连续以完全相同的音频频谱输入和插画素材进行。渲染耗时缩短 38.0%,即吞吐速度达到优化前的 **1.61 倍**,使原本慢于真实播放时长的渲染变为高于实时帧率的高效输出。 - ---- - -## 本专题关联阅读 -- **系统总架构篇**:[我是如何用 Remotion 与 Docker CDP 打造全自动 MV 生成与多语种油管发布流的](/posts/zh/how-i-built-an-automated-music-video-pipeline/) -- **大文件上传篇**:[借助 Docker Archive API 模式通过 CDP 自动化上传 100MB+ 视频到 YouTube](/posts/zh/uploading-large-videos-to-youtube-via-cdp/) -- **线上实成片**:[前往 YouTube 观看《糖画小仙》1080P 官方完整成片](https://youtu.be/vZbyKeCCSRA) - ---- - -**需要构建自动化音视频渲染或高吞吐媒体处理管线?** 我为企业与内容团队定制基于 Remotion、Node.js 与 Docker 的全自动视频合成、渲染性能优化与多平台无人值守分发系统。欢迎联系交流:[WhatsApp +60 12-797 2969](https://wa.me/60127972969) · [me@hoelee.com](mailto:me@hoelee.com?subject=Automated%20Video%20Pipeline) · [hoelee.com](https://hoelee.com)。 -```` - -### 🇬🇧 英文版原文 (English Markdown Primary) -````markdown ---- -title: "Debugging Remotion Video Jitter: Why Bass Scaling Ruins Background Transitions" -description: "Diagnose audio-reactive background jitter and crossfade flicker in Remotion. See how separating the HUD from background layers can improve visual stability and rendering performance." -pubDate: 2025-11-26 -updatedDate: 2026-10-22 -category: engineering -stream: creative-lab -tags: ["remotion", "react", "audio-visualizer", "css-animation", "debugging"] -ogImage: "/og/debugging-remotion-video-jitter.jpg" -banner: "/banners/debugging-remotion-video-jitter.jpg" -draft: false ---- - -Building programmatic videos with React and Remotion gives you complete DOM control over every frame. You can map web audio frequencies directly to SVG attributes, CSS transforms, and typography in ways standard video editors can barely touch. - -However, treating video frames like standard web pages introduces subtle visual bugs. In our automated music video pipeline, an export that looked plausible in unit tests developed a jarring, violent shudder when rendered into a 1080p MP4. - -Here is what went wrong, why our initial intuition about audio reactivity failed, and how to structure React video layers so audio-driven HUDs never pollute background transitions. - -> **Live Reference**: The repaired rendering pipeline produced the final production MV for [《糖画小仙》 (Sugar Art Fairy) on YouTube](https://youtu.be/vZbyKeCCSRA), running rock-solid at 1080p 30fps. - -> **TL;DR** — Scaling a full-bleed background image with the bass band forces an interpolation resampling on every frame, which the human eye perceives as violent shudder. Furthermore, two stacked semi-transparent layers crossfading symmetrically dip through the black root container at the midpoint. Fixes: keep the background canvas completely static, decouple all audio-reactive pulsing into isolated foreground HUD layers, and fade in the incoming slide on top of a 100% solid base. Render time dropped by **38.0% (from 352s to 218s, a 1.61× throughput speedup)**. This is the rendering chapter of our [music-video pipeline](/posts/how-i-built-an-automated-music-video-pipeline/); the file-staging half is covered in [uploading large videos via CDP](/posts/uploading-large-videos-to-youtube-via-cdp/). - ---- - -## 1. The Symptom: A Whole-Frame Earthquake - -The visual effect was supposed to be simple: -1. An illustrated 1080p background slowly crossfading between slides. -2. A pulsing circular spectrum visualizer in the foreground. -3. Three lines of Chinese calligraphy lyrics that slide between left and right depending on where the character in the artwork is standing. - -In preview scrubbing, everything looked acceptable. But during full-speed 30fps playback of the rendered 1080p file, the viewer felt instant visual fatigue. Every time the electronic drum pattern kicked in, the entire scene appeared to vibrate violently up to 30 times per second. Furthermore, during slide transitions, the screen experienced micro-flashes where the background brightness suddenly dipped. - ---- - -## 2. Root Cause 1: Low-Frequency Scale Pollution - -Looking at the initial `BackgroundSlideshow.tsx`, we had attached an audio reactivity hook: - -```tsx -// The culprit in BackgroundSlideshow.tsx -const bassScale = interpolate(bassLevel, [0, 1], [1.0, 1.025], { - extrapolateRight: 'clamp', -}); - -// Applied to the background image: - -``` - -On paper, expanding the image by 2.5% on bass hits sounds like an engaging dynamic pulse. In reality: -- **Electronic audio beats hit in 30–60ms bursts**: The bass amplitude oscillates rapidly between zero and peak within 2 to 3 consecutive frames. -- **A 1920x1080 image scaling by 2.5% shifts edge pixels by nearly 25 to 30 physical pixels in a single frame**. -- When that sudden displacement reverses on the very next frame, the human eye interprets it not as a musical pulse, but as **severe camera shake / stutter**. -- To make matters worse, during the 1.8-second slide transition, two overlapping images with different transform origins were simultaneously vibrating at conflicting scales, creating a hallucinatory double-vision jitter. - ---- - -## 3. Root Cause 2: Symmetrical Opacity Crossfade DIP - -The second issue was the crossfade flash. In standard web CSS, people often do: - -```css -/* Web crossfade trap */ -.current-slide { opacity: 1 -> 0; } -.next-slide { opacity: 0 -> 1; } -``` - -When two images crossfade with linear opacity, consider what happens at the exact midpoint ($t = 0.5$): -- $\text{Current Slide Opacity} = 0.5$ -- $\text{Next Slide Opacity} = 0.5$ - -Here is how the browser/Remotion compositing pipeline stacks these layers against the root black container: - -``` -┌─────────────────────────────────────────────────────────────┐ -│ Layer 2: Next Slide (opacity = 0.5) │ -├─────────────────────────────────────────────────────────────┤ -│ Layer 1: Current Slide (opacity = 0.5) │ -├─────────────────────────────────────────────────────────────┤ -│ Layer 0: Root Container (background = #000000 black) │ -└─────────────────────────────────────────────────────────────┘ -``` - -Because alpha blending operates multiplicatively down the stack: -$$\text{Composite Alpha} = 1 - (1 - 0.5) \times (1 - 0.5) = 1 - 0.25 = 0.75$$ - -The total combined alpha drops to **0.75**, exposing **25% of the black background**! This is not an optical illusion; it is mathematical light loss. Every time a transition peaked, the frame darkened by a quarter of its luminance, creating an unmistakable flicker. - ---- - -## 4. The Solution: Rock-Solid Base + Pure Single-Direction Opacity - -To fix both issues permanently: - -### 1. Remove All Scaling from Backgrounds -Background artwork must remain rock-solid. All audio reactivity belongs exclusively in the HUD layer (the radial spectrum bars and glowing rings). The background canvas should only ever receive smooth, non-oscillating transformations. - -### 2. Base Solid + Top Layer Fade-In -Instead of fading out the current image, **keep the current image at solid 100% opacity**. Only animate the incoming image on top: - -```tsx -const fullBleed = { position: 'absolute', width: '100%', height: '100%', objectFit: 'cover' }; - -return ( -
- {/* Base Slide: Stays 100% solid, eliminating any drop to black */} - - - {/* Next Slide: Smoothly fades in on top over 1.8s */} - {isTransitioning && ( - - )} -
-); -``` - -### 3. Physical Decoupling of HUD and Canvas -The lyric box and circular spectrum are mounted inside a completely separate container layer with `pointerEvents: 'none'`. As the HUD glides across the canvas from `centerX: 540` to `centerX: 1380`, it calculates its position strictly from the timeline clock. It has zero knowledge of and zero impact on the background's opacity crossfade. - ---- - -## 5. The Outcome & Benchmark Reproduction - -After removing the background `bassScale` and switching to one-way opacity stacking: - -1. **Eliminated visible jitter**: Background illustrations remain crisp and visually anchored through rapid 140 BPM electronic drum drops across all test sequences. -2. **Eliminated transition light dips**: The 1.8s Bezier crossfade maintains 100% luminance continuity without dipping through the dark container base. -3. **Significant throughput speedup**: Removing per-frame matrix interpolation and scaling calculations on high-resolution background assets delivered a measurable performance boost. - -### Reproduction Benchmark - -| Metric | Before Optimization | After Optimization | Delta | -|---|---|---|---| -| **Render Duration** | 352.0 seconds | 218.3 seconds | **-38.0% (-133.7s)** | -| **Render Throughput** | 22.24 fps | 35.87 fps | **+1.61× speedup** | -| **Total Frames** | 7,830 frames | 7,830 frames | Identical (261s / 4m 21s) | -| **Output Resolution** | 1920 × 1080 (1080p @ 30fps) | 1920 × 1080 (1080p @ 30fps) | Identical | -| **Codec & Settings** | H.264 (CRF 18, preset medium) | H.264 (CRF 18, preset medium) | Identical | - -**Test Environment Specifications:** -- **CPU**: Intel Core i9-13900K (24 cores / 32 threads, boost up to 5.8 GHz) -- **GPU**: NVIDIA GeForce RTX 3060 (12GB GDDR6 VRAM, Driver 551.xx) -- **RAM**: 64GB DDR5 5600 MHz -- **OS**: Windows 11 Pro 64-bit -- **Software**: Node.js v20.x, Remotion v4.0.x with Chromium headless GPU rendering enabled - -Both benchmark runs were executed consecutively using identical media assets, audio spectrogram inputs, and composition parameters. The 38.0% reduction in render time directly translates to a **1.61× throughput speedup**, turning a process that was previously slower than realtime into an accelerated 35.8 fps export. - ---- - -## Related Guides in this Series -- **Pipeline Architecture**: [How I Built an Automated Music Video Pipeline with Remotion and Docker](/posts/how-i-built-an-automated-music-video-pipeline/) -- **Remote Publishing**: [Uploading 100MB+ Videos to YouTube via CDP: The Docker Archive Pattern](/posts/uploading-large-videos-to-youtube-via-cdp/) -- **Live Output**: [Watch the finished MV on YouTube](https://youtu.be/vZbyKeCCSRA) - ---- - -**Need an automated media rendering or publishing pipeline?** I build programmatic video generation systems, high-throughput Remotion/Node.js rendering pipelines, and unattended multi-platform publishing workflows. Get in touch: [WhatsApp +60 12-797 2969](https://wa.me/60127972969) · [me@hoelee.com](mailto:me@hoelee.com?subject=Automated%20Video%20Pipeline) · [hoelee.com](https://hoelee.com). -```` - ---- - -## 文章 06 / 11:把字体嵌进 PDF,让它在任何机器上都长一样 -- **Slug**: `embedding-fonts-so-a-pdf-looks-the-same-everywhere` -- **英文标题**: Embedding Fonts So a PDF Looks the Same on Every Machine -- **分类**: `engineering` | **发布日期**: 2026-10-15 -- **线上地址**: https://blog.hoelee.com/posts/embedding-fonts-so-a-pdf-looks-the-same-everywhere/ (EN) | https://blog.hoelee.com/posts/zh/embedding-fonts-so-a-pdf-looks-the-same-everywhere/ (ZH) -- **本篇审核状态**: ⏳ 待审核 (Pending) - -### ✍️ 顾问审阅意见区 (Review Feedback) -```text -【审阅结论】:[ ] 通过 [ ] 需微调 [ ] 需重构 -【事实与数字核对】: -【人设与用词卫生】: -【CRO与转化建议】: -``` - -### 🇨🇳 中文版原文 (Chinese Markdown Twin) -````markdown ---- -title: "把字体嵌进 PDF,让它在任何机器上都长一样" -description: "四个字族、八个字面、两个渲染引擎,外加一条 CSS 怪癖:为了不让生成的报告依赖服务器上恰好装了什么字体,我做了什么。" -pubDate: 2026-10-15 -updatedDate: 2026-10-16 -category: engineering -tags: ["pdf", "fonts", "mpdf", "typography", "php"] -ogImage: /og/zh-embedding-fonts-so-a-pdf-looks-the-same-everywhere.jpg -banner: /banners/embedding-fonts-so-a-pdf-looks-the-same-everywhere.jpg -draft: false ---- - -## 需求只有一句话 - -一个报告生成器必须产出在任何地方都长得一样的文档:中文标题用宋体、中文正文用黑体、英文标题与封面数字用一款展示衬线体、英文正文和表格用 Inter。字重也要对——强调用 medium、标题用 semibold——而且是三语、两个 PDF 渲染引擎都要对。 - -同时,**字体必须跟着文档走**。不是「服务器装过」,也不是「读者大概有」,而是**嵌进文件里**,这样另一个国家的印厂看到的页面是一样的。 - -老管线在最后这句上栽得很隐蔽:它依赖服务器上用包管理器装过的字体,而且**只嵌入了一款中文字体**。第二档字重根本不存在,于是「粗体」是渲染器的合成近似;而想发现这件事,唯一的办法是打开 PDF 去看里面到底装了什么。 - -## 规则一:从成品 PDF 里把字体读回来 - -「已嵌入」是一个关于**输出**的断言,所以我量的是输出。同一份文档,改前与改后: - -| | 改前 | 改后 | -|---|---|---| -| zh 页数 | 23 | **23** | -| en 页数 | 28 | **29** | -| bm 页数 | 30 | **30** | -| 真正嵌进去的字体 | 一款中文字体 + Roboto | 思源宋 Medium + SemiBold · 思源黑 Regular + Medium · Cormorant Garamond Medium + SemiBold · Inter Regular + SemiBold + Medium · 拉丁报告里的汉字走思源黑 | -| 渲染时间 / 峰值内存 | 基线 | 同一量级(±10%,属噪声) | -| 文件体积 | 基线 | 约 +3% | - -每个字面的字形数是收据:中文报告里 15,988 个字形落在正文黑体、2,247 个落在它的 medium 档、634 个落在标题宋体的 medium、222 个落在它的 semibold。这就是「字体在服务器上」与「字体在文件里」的区别——另一个国家的读者看到的是同样四个字面,而代价是某一种语言正好多一页(拉丁字体的度量比它替换掉的那个更宽)。 - -## 规则二:只出静态实例,理由写在解析器里 - -现代做法看起来该是「每个字族发一个可变字体」,但在这里是错的,有两个实测理由: - -1. **PDF 引擎的字体解析器只读 `glyf`/`loca`。** 喂它一个 PostScript/CFF 轮廓的 OpenType 文件,它直接拒绝:`Fonts with postscript outlines are not supported`。问题不是「可变」,是 CFF 轮廓。 -2. **它完全不读 `fvar` 表**,所以可变字体会**静默地**解析成它的**默认实例**——而中文字族的默认实例恰恰是最细的那一档(`name` 表里写得清清楚楚:Thin 100 与 ExtraLight 200)。整份报告会变成发丝体,而整条管线里不会报任何一个错。 - -所以构建步骤拿上游的可变字体**实例化成静态切面**:跑实例化器,然后把 `name`、`OS/2.usWeightClass` 和 `head.macStyle` 改写成它现在真实的字重(源文件的名字里还写着 Thin)。产物旁边有一份 manifest,逐文件记下 family、字重、sha256、字形数与码位数;许可证也随文件一起进仓库。 - -## 规则三:引擎只会说两种字重,那就映射到两个槽位 - -渲染引擎的 CSS 只认 `normal` 和 `bold`——它的源码自己就这么写("Does not support: bolder, lighter, 100..900")。所以数字字重对它毫无意义;而同一条管线里的无头 Chromium 又完全认它们。 - -可用的映射是:每个字族声明一个 **R 槽**和一个 **B 槽**(常规一档、更重一档),`font-weight: 500` 落到目标字族的 R 槽,`600` **只在 PDF 那一侧被改写成 `bold`**,落到 B 槽。Chromium 侧照写 `600`。两条测试钉住它:B 槽必须比 R 槽重(读 `usWeightClass`,不是假设),且 `font-weight: 600` 绝不允许出现在交给 PDF 引擎的样式表里。 - -有一处细节值得单写一段:在这个管线里,**medium 不是强调手段,而是一个字族成员**。中文标题用宋体的 medium 当常规、用 semibold 做强调;英文标题用展示衬线体做同样的事。这里搞错,屏幕上完全看不出来,而印出来一目了然。 - -## 规则四:不要按你控制不了输入的字集做子集化 - -第一版把中文字体按两个国家字集的并集做了子集,产物从约 50 MB 降到约 29 MB。然后我跑了姓名探针,发现这些字被裁掉了: - -```text -犇 骉 頔 祎 廸 玧 祾 赟 堃 -``` - -每一个都是真实的人名用字。报告会把客户姓名印在封面上,而姓名是自由输入——所以一套基于子集的构建,迟早会在产品最醒目的那一页上放一个豆腐块。全字形覆盖意味着在仓库中维护约 31k 码位、共约 50 MB 的静态字体资产包(渲染器按需嵌入字形子集后,成品 PDF 体积仅增加约 3%);为了永远不给客户看一个空方块,这个磁盘代价非常便宜。 - -## 规则五:把「缺字」变成构建失败,而不是惊喜 - -闸门跑三项检查,任何一项不过就非零退出: - -- manifest 里声明的每个字体文件都在,且 sha256 与磁盘上的文件一致; -- 内容库(三语全部)+ 品牌字面 + 各类探针(简体、繁体、CJK 标点、全角、中英混排、数字、拉丁扩展、符号)+ 姓名用字,**每一个字在「它实际会被哪一档字体印出来」的那一档里都有字形**; -- 查字形用的是 PDF 引擎自己的解析器,而不是第三方库,所以这条检查不可能和渲染器互相矛盾。 - -已知边界写在明处,不藏起来:✅ ✔ 这类符号在这几款正文字体里都没有字形,而引擎也画不了彩色 emoji,所以它们不出现在报告正文;拉丁标题那款展示衬线体只有 974 个字形,不画 ① ★ ℃,这也是为什么内容库的检查覆盖**所有**槽位而不只是正文;而拉丁报告里的汉字必须走专门的 CJK 槽位——两条测试防止两个渲染器在这点上产生分歧。 - -## 如果重来一次 - -1. **在动样式之前先定字族与字重。** 版式做完之后再去加第二档字重,意味着每一页页数都要手工复核一遍。 -2. **选字体格式之前先读渲染器的源码。** 可变字体看着是审美问题,实际上是解析器问题——两个文件、十分钟就定了。 -3. **把要嵌进文档的一切当作许可证产物。** 字体文件连同许可证一起进仓库,否则就得进别人的法务审查。 -4. **量「到底嵌进去了什么」。** 页数、每个字面的字形数、文件体积、渲染时间:四项都动了,其中三项的方向和我猜的相反。 - -## 结果 - -改前:一款中文字体加一款界面字体、靠合成粗体、还取决于服务器装过什么。改后:四个字族、八个静态字面真正嵌在文件里,字重是各个字族真实的成员,页数与上一版相差不超过一页,而且有一条 lint 闸门:某个字没有字形时直接让构建失败——于是失败形态从「客户看到一个方块」变成了「CI 拒绝发版」。这跟这条管线里其它地方的取舍是同一个:**让错误发不出去,而不是让错误容易被看见。** - ---- - -我为企业构建高可靠的文档自动化与多语种 PDF 出版管线——从排版引擎定制、字体合规内嵌到自动化 CI 视觉回归校验。如果你的业务报表、合同或交付报告需要在任何设备上保持印刷级一致,欢迎联系我:[WhatsApp +60 12-797 2969](https://wa.me/60127972969) · [me@hoelee.com](mailto:me@hoelee.com?subject=PDF%20Typography%20Pipeline) · [hoelee.com](https://hoelee.com)。 -```` - -### 🇬🇧 英文版原文 (English Markdown Primary) -````markdown ---- -title: "Embedding Fonts So a PDF Looks the Same on Every Machine" -description: "Four families, eight faces, two renderers and one CSS quirk: what it took to stop a generated report depending on whatever fonts the server happened to have." -pubDate: 2026-10-15 -updatedDate: 2026-10-16 -category: engineering -tags: ["pdf", "fonts", "mpdf", "typography", "php"] -ogImage: /og/embedding-fonts-so-a-pdf-looks-the-same-everywhere.jpg -banner: /banners/embedding-fonts-so-a-pdf-looks-the-same-everywhere.jpg -draft: false ---- - -## The requirement was one sentence - -A report generator has to produce a document that looks the same everywhere: -Chinese headings in a serif, Chinese body text in a sans, Latin headings and -cover numerals in a display serif, Latin body text and tables in Inter. -Weights matter — medium for emphasis, semibold for headings — across three -languages and two PDF renderers. - -And the fonts must travel with the document. Not "the server has them -installed", not "the reader probably has them" — **embedded**, so a print -shop in another country sees the same pages. - -The old pipeline failed on the last clause in a way that was invisible: it -depended on fonts installed on the server by a package manager, and it only -ever embedded a single CJK face. The second weight did not exist, so "bold" -was the renderer's synthetic approximation, and the only way to notice was -to open the PDF and look at what was actually inside it. - -## Rule one: read the fonts back out of the finished PDF - -"Embedded" is a claim about the output, so I measured the output. The same -document, rendered before and after: - -| | before | after | -|---|---|---| -| zh page count | 23 | **23** | -| en page count | 28 | **29** | -| bm page count | 30 | **30** | -| fonts actually embedded | one CJK face + Roboto | Source Han Serif Medium + SemiBold · Source Han Sans Regular + Medium · Cormorant Garamond Medium + SemiBold · Inter Regular + SemiBold + Medium · Source Han Sans for the CJK runs inside Latin reports | -| render time / peak memory | baseline | same order (±10%, noise) | -| file size | baseline | roughly +3% | - -The glyph counts per face are the receipt: in the Chinese report, 15,988 -glyphs land in the body sans, 2,247 in its medium weight, 634 in the heading -serif medium, 222 in its semibold. That is the difference between "the font -is on the server" and "the font is in the file" — a reader in another -country sees the same four faces, and a page count that moved by exactly one -page in one language (the Latin metrics are wider than what they replaced) -is the honest cost. - -## Rule two: static instances only, and the reason is in the parser - -The obvious modern choice — ship one variable font per family — is wrong -here, for two measured reasons: - -1. **The PDF engine's font parser reads `glyf`/`loca` only.** Feed it an - OpenType file with PostScript/CFF outlines and it refuses: - `Fonts with postscript outlines are not supported`. A variable font is - not the problem; CFF outlines are. -2. **It does not read the `fvar` table at all**, so a variable font silently - resolves to its *default instance* — and the default instances of the CJK - families are the thinnest ones (Thin 100 and ExtraLight 200, visible in - the `name` table). Every page would render in a hairline weight, with no - error anywhere in the pipeline. - -So the build step takes the upstream variable fonts and **instantiates -static cuts**: it runs the instancer, then rewrites `name`, -`OS/2.usWeightClass` and `head.macStyle` so the file identifies itself as -the weight it now is (the source's own name still says "Thin"). A manifest -records family, weight class, sha256, glyph count and code-point count for -every file, and the licence files ship next to them. - -## Rule three: the engine speaks two weights, so map onto two slots - -The renderer's CSS handling honours exactly `normal` and `bold` — its source -says so in as many words ("Does not support: bolder, lighter, 100..900"). -Numeric weights are therefore meaningless to it, while the headless-Chromium -renderer in the same pipeline honours them properly. - -The mapping that works: each family declares an **R slot** and a **B slot** -(regular-ish and heavier), `font-weight: 500` lands on the R slot of the -intended family, and `600` is **rewritten to `bold`** on the PDF side only, -which lands on the B slot. Chromium keeps `600` as written. Two tests pin -it: the B slot must be heavier than the R slot (read from `usWeightClass`, -not assumed), and `font-weight: 600` must never appear in the stylesheet -handed to the PDF engine. - -One subtlety worth the paragraph: a "medium" weight is not an emphasis -mechanism in this pipeline, it is a *family member*. Chinese headings use -the serif's medium as their regular and its semibold for emphasis; Latin -headings do the same with the display serif. Getting that wrong is invisible -on a screen and obvious in print. - -## Rule four: do not subset against a character set you do not control - -The first attempt subset the CJK fonts to the union of two national -character sets and produced a ~29 MB bundle instead of ~50 MB. Then I ran -the name probe and found these were cut: - -```text -犇 骉 頔 祎 廸 玧 祾 赟 堃 -``` - -Every one of them is a real given name character. The report prints a -customer's name on the cover, and the name is free input — so a subset-based -build will eventually put a tofu box on the most prominent page of the -product. Full coverage means keeping ~31k code points — roughly 50 MB of static font assets in the repository (adding only ~3% to each finished PDF after engine subsetting); that is a fine price for never showing a customer an empty rectangle. - -## Rule five: make missing glyphs a build failure, not a surprise - -The gate runs three checks and exits non-zero on any of them: - -- every font file declared in the manifest is present, and its sha256 - matches the file on disk; -- every character in the content library (all three languages) plus the - brand strings, plus probe classes — simplified, traditional, CJK - punctuation, full-width forms, mixed-script, digits, Latin extended, - symbols — plus the name characters, has a glyph **in the face that will - actually print it**; -- the lookup uses the PDF engine's own font parser rather than a third-party - library, so the check cannot disagree with the renderer. - -The known edges are written down instead of hidden. Dingbats and emoji (✅ ✔) -exist in none of these text fonts and the engine cannot draw colour emoji, -so they are kept out of the report body. The display serif has only 974 -glyphs and does not draw symbols like ① ★ ℃, which is why the -content-library check covers *all* slots rather than just the body. And CJK -characters inside a Latin report must go through the dedicated CJK slot — -two tests keep the renderers from disagreeing about that. - -## What I would do differently - -1. **Choose faces and weights before styling anything.** Retrofitting a - second weight after the layout exists means re-checking every page count - by hand. -2. **Read the renderer's source before choosing a font format.** The - variable-font decision looked like a taste question and was actually a - parser question — two files settled it in ten minutes. -3. **Treat everything you ship inside a document as a licence artifact.** - Font files enter the repo with their licences, or they enter someone - else's legal review. -4. **Measure what got embedded.** Page count, glyph-per-face counts, file - size, render time: all four moved, and three of them moved in ways I - would have guessed wrong. - -## The result - -Before: one CJK face and a UI font, with synthetic bold, depending on what -the server had installed. After: four families and eight static faces -embedded in the file, weights that are real members of their families, page -counts within one page of the previous layout, and a lint gate that fails -the build when a character has no glyph — so the failure mode moved from "a -customer sees a box" to "CI refuses the release". Which is the same trade as -everywhere else in this pipeline: make the mistake impossible to ship rather -than easy to notice. - ---- - -I build automated document generation and multi-lingual PDF publishing pipelines — from layout engine customisation and compliant font embedding to CI visual verification gates. If your business reports, invoices, or client deliverables need to look identical on every machine, get in touch: [WhatsApp +60 12-797 2969](https://wa.me/60127972969) · [me@hoelee.com](mailto:me@hoelee.com?subject=PDF%20Typography%20Pipeline) · [hoelee.com](https://hoelee.com). -```` - ---- - -## 文章 07 / 11:那个把静默丢失更新变成 409 的 JPA 字段:@Version 乐观锁 -- **Slug**: `jpa-version-field-lost-update` -- **英文标题**: The JPA Field That Turns a Silent Lost Update Into a 409 -- **分类**: `engineering` | **发布日期**: 2026-08-19 -- **线上地址**: https://blog.hoelee.com/posts/jpa-version-field-lost-update/ (EN) | https://blog.hoelee.com/posts/zh/jpa-version-field-lost-update/ (ZH) -- **本篇审核状态**: ⏳ 待审核 (Pending) - -### ✍️ 顾问审阅意见区 (Review Feedback) -```text -【审阅结论】:[ ] 通过 [ ] 需微调 [ ] 需重构 -【事实与数字核对】: -【人设与用词卫生】: -【CRO与转化建议】: -``` - -### 🇨🇳 中文版原文 (Chinese Markdown Twin) -````markdown ---- -title: "那个把静默丢失更新变成 409 的 JPA 字段:@Version 乐观锁" -description: "在 REST + JPA 的读-改-写流程里,两个编辑同时保存同一条记录时,后保存者会静默覆盖先保存者的修改,而 API 两次都返回成功——JPA 的 @Version 乐观锁把这个静默丢失更新变成 HTTP 409 冲突:请求携带期望版本号,版本不符就拒绝写入,并提示客户端重新读取再试。" -pubDate: 2026-08-19 -category: engineering -tags: [java, spring, jpa, hibernate, rest, testing] -ogImage: /og/zh-jpa-version-field-lost-update.jpg -banner: /banners/jpa-version-field-lost-update.jpg -draft: false ---- - -两个人同时打开同一篇文章,两个人都改了,两个人都保存。其中一次 -保存悄无声息地消失了——没有报错,没有警告,而且 API 对两次请求 -都返回了 HTTP 200。 - -这就是丢失更新(lost update)问题,是读-改-写(read-modify-write) -API 里最安静的数据丢失 bug。我在做 Spring Boot 作品集 demo 时撞上 -了它——这是一个 Spring Boot 3.5.16(Java 21)的 REST API,编辑器 -从浏览器页面创建和更新文章。修法最终落在三处:JPA 实体上的一个 -`@Version` 字段、请求契约里的一个字段、以及 API 层把它映射成 -HTTP 409 Conflict 的一个异常。这篇文章就沿着真实代码走一遍这条路。 - -## 问题:一条编辑消失了,却谁都怪不上 - -为什么两个人保存同一条记录时,其中一个人的修改会消失? - -跟着时间线走。编辑器 A 和编辑器 B 都拉取了同一篇文章。A 先保存: -行被更新,API 返回 200。B 稍后保存:行被*再次*更新,这次覆盖了 -A 的文字,API 又返回 200。每个请求都成功;每个响应都告诉它的调用 -方「你的保存就是这条记录的当前状态」——对其中一个人来说这是假话。 -A 的编辑就这么没了,两个客户端都没有任何办法知道。 - -失败是静默的,因为它就是读-改-写流程的正常行为,不是异常。这正是 -它在真实系统里存活的理由,也是为什么在要展示工程判断力的东西里, -值得把它修得干净。 - -## 我先试的方案:不带版本号的读-改-写,以及它为什么失败 - -我对更新流程的第一版草图是最直白的那种:`GET` 记录、编辑、 -`PUT` 回去,只带新的标题和正文,什么都不带。 - -```text -GET /api/posts/{id} # 读取记录 -PUT /api/posts/{id} # 写回新的标题和正文 -``` - -服务端加载行、套用更新、返回 200。它无从知道在这一行数据上,客户端 -在 `GET` 和 `PUT` 之间已经被别人动过——读取和写入是两个互不相干的 -请求,契约里没有任何东西把它们连起来。最后写入的人赢,而两个写入 -者都被告知成功。 - -在这里,200 比报错更糟。报错至少告诉输掉的那个客户端「出事了」, -给他们一个去查的理由。200 则告诉两个客户端「你们的保存就是记录 -当前的状态」——对其中一个是撒谎。输掉的那次编辑现在哪儿都不存在: -屏幕上没有,数据库里也没有;而因为客户端相信自己保存成功了, -没有人会去找这份数据。 - -## 修法:一个 @Version 字段、一份契约、一个冲突 - -修法一共五小步,全部都在该参考服务的源码里。 - -### 1. 实体随身携带一个版本列 - -```java -@Entity -@Table(name = "posts", indexes = @Index(name = "idx_posts_title", columnList = "title")) -@EntityListeners(AuditingEntityListener.class) -public class Post { - - @Id - @GeneratedValue - @UuidGenerator - private UUID id; - - @Column(nullable = false, length = 160) - private String title; - - @Column(nullable = false, length = 10_000) - private String body; - - @Version - private long version; - // ... -} -``` - -`@Version` 告诉 Hibernate 把 `version` 当作乐观锁。它生成的每一条 -`UPDATE` 都变成有条件的: - -```sql -UPDATE posts -SET title = ?, body = ?, version = version + 1, ... -WHERE id = ? AND version = ? -``` - -如果这行数据的版本号已经和语句构造时的不一致,受影响行数为零, -Hibernate 就会拒绝这次 flush,而不是悄悄覆盖。实体从不用手自增 -计数器——更新方法只碰 `title` 和 `body`;版本号跟着写入一起走。 - -### 2. 版本号进入 API 契约 - -锁如果客户端无法参与,就没有用,所以版本号在两个方向上都穿过 -API。响应的 record 暴露它: - -```java -public record PostResponse(UUID id, long authorId, String title, String body, - long version, Instant createdAt, Instant updatedAt) { -} -``` - -更新请求则要求把它带回来: - -```java -public record UpdatePostRequest( - @NotBlank @Size(max = 160) String title, - @NotBlank @Size(max = 10_000) String body, - @NotNull @Min(0) Long version) { -} -``` - -`UpdatePostRequest` 旁边的学习注记说得很直白: -「the expected version is part of the update -contract, making optimistic locking visible to clients.」 -(期望的版本号是更新契约的一部分,让乐观锁对客户端可见。) - -### 3. 在拥有写事务的 service 里检查版本 - -```java -@CachePut(cacheNames = "posts", key = "#postId") -@Transactional -public PostResponse updatePost(UUID postId, UpdatePostRequest request) { - Post post = postRepository.findById(postId) - .orElseThrow(() -> new PostNotFoundException(postId)); - if (post.getVersion() != request.version()) { - throw new PostVersionConflictException(postId); - } - post.update(request.title().trim(), request.body().trim()); - return PostResponse.from(postRepository.saveAndFlush(post)); -} -``` - -读取、比较、保存全部发生在一个 `@Transactional` 方法里——这正是让 -检查诚实的那部分:版本号是和*写入那一刻*的行状态比较,而不是和 -早前某个请求留下的快照比较。如果读取和写入分属不同事务,检查到的 -就是这行数据已经离开的旧版本,整套机制就成了表演。`PostService` -的学习注记点名了这条规则:「service methods -centralize transaction boundaries, cache coherence, and -optimistic-locking rules.」(service 方法集中管理事务边界、缓存 -一致性与乐观锁规则。)服务还开着 -`spring.jpa.open-in-view: false`,所以不会有残留的会话跨请求地 -供给过期实体——行是在写入事务内部重新读取的。 - -显式的检查会确定性地挡掉过期请求。`@Version` 列在底层仍然有意义: -如果检查与 flush 之间恰好插进一次别的提交,那条有条件的 `UPDATE` -影响零行,Hibernate 照样拒绝这次写入。 - -### 4. 异常处理器把它映射成 409 - -异常本身带着客户端能直接照做的信息: - -```java -public class PostVersionConflictException extends RuntimeException { - - public PostVersionConflictException(UUID postId) { - super("Post %s has changed; fetch it again before retrying".formatted(postId)); - } -} -``` - -错误边界把它转成正确的 HTTP 应答: - -```java -@ExceptionHandler({PostVersionConflictException.class, ObjectOptimisticLockingFailureException.class}) -ProblemDetail handleConflict(RuntimeException exception) { - return problem(HttpStatus.CONFLICT, "POST_VERSION_CONFLICT", exception.getMessage()); -} -``` - -`HttpStatus.CONFLICT` 就是 HTTP 409,响应是一份 problem -document——一个 `type` URI、一个稳定的机器码 -(`POST_VERSION_CONFLICT`)和一段人类可读的说明。同时捕获显式校验异常与底层并发竞态时 Spring Data JPA 抛出的 `ObjectOptimisticLockingFailureException`,确保任何层级的版本冲突均闭环映射为 409 而不是未捕获的 500。demo 在配置里 -开启了框架的 problem-details 支持 -(`spring.mvc.problemdetails.enabled: true`),所以校验错误和所有 -其他错误都共用同一种响应形状。 - -### 5. 整条链路,从头到尾 - -```text -过期的 PUT /api/posts/{id} - -> PostService.updatePost 在事务内部重新读取这一行 - -> post.getVersion() != request.version() - -> PostVersionConflictException: "fetch it again before retrying" - -> ApiExceptionHandler.handleConflict - -> HTTP 409, ProblemDetail with code POST_VERSION_CONFLICT - -> 客户端知道自己的前提过期了 -``` - -一个 `@Version` 字段、请求契约里的一个 `version`、一个异常、一个 -handler 方法。Controller 什么都没改——`updatePost` 看起来还是普通 -的 `PUT`。 - -## 为什么答案是冲突,而不是重试 - -当两个编辑器产出同一份记录的两种不同版本时,服务端无法知道哪一方 -的意图才是被需要的。从各自作者的角度看,两次保存都正当;重放那条 -过期的写入,只是重放同一次数据丢失。 - -诚实的结论就是 HTTP 对 409 的定义:请求与资源的当前状态冲突, -并且客户端被明确告知如何解决——「fetch it again before retrying」 -(重新取一次再试)。输掉的客户端重新读取记录,看到另一位作者的 -修改,由人来决定保留什么。静默覆盖变成了一处看得见的决策点——这 -正是这件事的全部意义。 - -## 这个参考架构服务的其余部分证明了什么 - -版本字段只是一个小系统里的一层,而其余部分都能用同样的方式核实 -——下面每一行都是仓库里的一个类或配置文件,不是一句口号: - -| 层 | 做了什么 | 在哪 | -|---|---|---| -| 缓存 | 单篇文章读取使用有界 Caffeine 缓存(上限 500,TTL 10 分钟,都来自配置);读取用 `@Cacheable`、更新用 `@CachePut`、删除用 `@CacheEvict`;`GET /api/showcase/cache` 暴露请求数、命中数、未命中数和命中率 | `CacheConfig`、`CacheProperties`、`ShowcaseMetricsController` | -| 安全 | 无状态 HTTP Basic + BCrypt;页面与读 API 公开,所有写操作需要 `EDITOR` 角色;本地默认是专用的非机密 `demo-editor`/`changeit` 账户,可用环境变量覆盖 | `SecurityConfig`、`application.yml` | -| 错误 | 请求 record 在边界处校验;一个 `@RestControllerAdvice` 返回一致的 problem document 和机器码——`POST_NOT_FOUND`(404)、`POST_VERSION_CONFLICT`(409)、带字段错误表的 `VALIDATION_FAILED`(400) | `CreatePostRequest`、`UpdatePostRequest`、`ApiExceptionHandler` | -| 配置 | 本地 profile 使用内存 H2 数据库(PostgreSQL 模式),`ddl-auto: update` 并预置示例文章;`prod` 选择 PostgreSQL,所有凭据来自 `APP_*` 环境变量,`ddl-auto: validate` | `application.yml`、`application-prod.yml` | -| 测试 | 一个 `@SpringBootTest` 套件断言:渲染的 Thymeleaf 页面、未认证 401 对编辑器 201、`VALIDATION_FAILED` 问题响应、公开搜索,以及重复读取后的缓存命中 | `DemoApplicationIntegrationTest` | - -## 从参考架构到生产环境落地的加固项 - -一旦从单机验证走向生产环境落地,有两件事立刻要变。项目 README 里两件都写了, -值得作为我自己的判断再重复一遍。 - -第一,schema 管理。我会在任何时候把 `ddl-auto` 设为 `validate` 之前, -先加 Flyway 或 Liquibase 迁移。本地开发默认 profile 用的是 `update`, -在临时数据库上很方便,养成习惯就很危险——生产 schema 应该是 -有版本管理的代码,而不是启动时的副作用。 - -第二,密钥。本地开发测试账户是刻意的非机密账户,带默认凭据。 -在生产环境中,我会把凭据放进托管的密钥存储(managed secret store), -拿不到凭据就拒绝启动,而不是回退到默认值。`prod` profile 已经做到 -所有凭据来自环境变量、不提交任何密钥——这正是我想要的形态, -只是不要那些回退值。 - -## 结果 - -过期的更新现在返回 HTTP 409,机器码 `POST_VERSION_CONFLICT`,而不是 -一个静静丢掉另一位作者修改的 200。丢失不再可能悄悄发生:失败是 -响亮的、可操作的——「fetch it again before retrying」——并且集成 -测试套件端到端地断言了访问与校验行为。 - -整个修法就是一个字段上的一个注解,加上让版本号成为契约一部分的 -管道代码。如果一条记录可能同时被两个人读取,这个字段就是「编辑 -丢失」与「双方都看得见的冲突」之间的分界线。 - -我平时就做 Java/Spring 后端和全栈 Web 应用——从浏览器页面到数据库 -的 REST API:JPA、乐观锁、缓存、校验和一整套集成测试。如果你的表单 -或字段里也有「编辑悄悄消失」的问题,跟我说说: -[WhatsApp](https://wa.me/60127972969) · -[me@hoelee.com](mailto:me@hoelee.com?subject=Spring%20Boot%20help) · -[hoelee.com](https://hoelee.com)。 -```` - -### 🇬🇧 英文版原文 (English Markdown Primary) -````markdown ---- -title: "The JPA Field That Turns a Silent Lost Update Into a 409" -description: "How a JPA @Version field turns a silent lost update into a 409 conflict — optimistic locking makes a stale REST write fail loudly instead of overwriting." -pubDate: 2026-08-19 -category: engineering -tags: [java, spring, jpa, hibernate, rest, testing] -ogImage: /og/jpa-version-field-lost-update.jpg -banner: /banners/jpa-version-field-lost-update.jpg -draft: false ---- - -Two people open the same post. Both edit it. Both save. One of the saves -disappears without a trace — no error, no warning, and the API answered -HTTP 200 for both of them. - -That is the lost update problem, and it is the quietest data-loss bug in -read-modify-write APIs. I hit it while building my Spring Boot reference -service — a Spring Boot 3.5.16 (Java 21) REST API where editors create and -update posts from a browser page. The fix turned out to be one `@Version` -field on the JPA entity, one field on the request contract, and one -exception that the API layer maps to HTTP 409 Conflict. This post traces -that path through the actual code. - -## The problem: an edit that vanishes with no one to blame - -Why does one editor's change disappear when two people save the same -record? - -Follow the timeline. Editor A and editor B both fetch the same post. -A saves first: the row is updated and the API answers 200. B saves a -moment later: the row is updated *again*, this time over A's text, and -the API answers 200 again. Every request succeeded; every response told -its caller that their save is the state of the record. A's edit is -simply gone, and neither client has any way to know. - -The failure is silent because it is normal read-modify-write behaviour, -not an anomaly. That is exactly why the bug survives in real systems, and -why it is worth fixing properly in something meant to demonstrate -engineering judgement. - -## What I tried first, and why it failed - -My first sketch of the update flow was the obvious one: `GET` the record, -edit it, `PUT` it back with the new title and body and nothing else. - -```text -GET /api/posts/{id} # read the record -PUT /api/posts/{id} # write it back with a new title and body -``` - -The server loads the row, applies the update, and returns 200. It has no -way to notice that the row moved underneath the client between the `GET` -and the `PUT` — the read and the write are two unrelated requests, and -nothing in the contract connects them. The last write wins, and both -writers are told they succeeded. - -A 200 is worse than an error here. An error at least tells the losing -client that something happened and gives them a reason to look. A 200 -tells both clients that their save is the current state of the record, -which is a lie for one of them. The losing edit now exists nowhere — not -on screen, not in the database — and because the client believes it -saved, nobody goes looking for the data. - -## The fix: a @Version field, a contract, and a conflict - -The fix is five small parts, all of them in the reference service's source. - -### 1. The entity carries a version column - -```java -@Entity -@Table(name = "posts", indexes = @Index(name = "idx_posts_title", columnList = "title")) -@EntityListeners(AuditingEntityListener.class) -public class Post { - - @Id - @GeneratedValue - @UuidGenerator - private UUID id; - - @Column(nullable = false, length = 160) - private String title; - - @Column(nullable = false, length = 10_000) - private String body; - - @Version - private long version; - // ... -} -``` - -`@Version` tells Hibernate to treat `version` as an optimistic lock. Every -`UPDATE` it generates becomes conditional: - -```sql -UPDATE posts -SET title = ?, body = ?, version = version + 1, ... -WHERE id = ? AND version = ? -``` - -If the row's version no longer matches the value the statement was built -with, zero rows change and Hibernate rejects the flush instead of quietly -overwriting. The entity never bumps the counter by hand — the update -method only touches `title` and `body`; the version moves with the write -itself. - -### 2. The version is part of the API contract - -A lock is useless if the client cannot take part in it, so the version -travels through the API in both directions. The response record exposes -it: - -```java -public record PostResponse(UUID id, long authorId, String title, String body, - long version, Instant createdAt, Instant updatedAt) { -} -``` - -and the update request requires it back: - -```java -public record UpdatePostRequest( - @NotBlank @Size(max = 160) String title, - @NotBlank @Size(max = 10_000) String body, - @NotNull @Min(0) Long version) { -} -``` - -The learning note next to `UpdatePostRequest` says it plainly: "the -expected version is part of the update contract, making optimistic -locking visible to clients." - -### 3. The service checks it inside the transaction that owns the write - -```java -@CachePut(cacheNames = "posts", key = "#postId") -@Transactional -public PostResponse updatePost(UUID postId, UpdatePostRequest request) { - Post post = postRepository.findById(postId) - .orElseThrow(() -> new PostNotFoundException(postId)); - if (post.getVersion() != request.version()) { - throw new PostVersionConflictException(postId); - } - post.update(request.title().trim(), request.body().trim()); - return PostResponse.from(postRepository.saveAndFlush(post)); -} -``` - -The load, the comparison and the save all happen inside one -`@Transactional` method, and that is the part that makes the check -honest: the version is compared against the row as it stands *at write -time*, not against a snapshot from an earlier request. If the read and -the write lived in different transactions, the check would compare -against a version the row has already left behind, and the whole scheme -would be theatre. The learning note on `PostService` names the rule: -"service methods centralize transaction boundaries, cache coherence, and -optimistic-locking rules." The service also runs with -`spring.jpa.open-in-view: false`, so no lingering session serves a stale -entity across requests — the row is re-read inside the writing -transaction. - -The explicit check catches stale requests deterministically. The -`@Version` column still matters underneath: if another commit slips in -between the check and the flush, the conditional `UPDATE` affects zero -rows and Hibernate refuses the write anyway. - -### 4. The handler maps the exception to a 409 - -The exception itself carries the message a client can act on: - -```java -public class PostVersionConflictException extends RuntimeException { - - public PostVersionConflictException(UUID postId) { - super("Post %s has changed; fetch it again before retrying".formatted(postId)); - } -} -``` - -and the error boundary turns it into the right HTTP answer: - -```java -@ExceptionHandler({PostVersionConflictException.class, ObjectOptimisticLockingFailureException.class}) -ProblemDetail handleConflict(RuntimeException exception) { - return problem(HttpStatus.CONFLICT, "POST_VERSION_CONFLICT", exception.getMessage()); -} -``` - -`HttpStatus.CONFLICT` is HTTP 409, and the response is a problem document -— a `type` URI, a stable machine code (`POST_VERSION_CONFLICT`) and a -human-readable detail. Mapping both our explicit exception and Spring Data JPA's `ObjectOptimisticLockingFailureException` (thrown when Hibernate detects a race condition) guarantees that concurrent write collisions always return 409 rather than an unhandled 500. The service enables the framework's problem-details -support in its configuration (`spring.mvc.problemdetails.enabled: true`), -so validation and every other error ride the same shape. - -### 5. The whole path, end to end - -```text -stale PUT /api/posts/{id} - -> PostService.updatePost re-reads the row inside its transaction - -> post.getVersion() != request.version() - -> PostVersionConflictException: "fetch it again before retrying" - -> ApiExceptionHandler.handleConflict - -> HTTP 409, ProblemDetail with code POST_VERSION_CONFLICT - -> the client knows its premise was stale -``` - -One `@Version` field, one `version` in the request contract, one -exception, one handler method. Nothing on the controller changed — -`updatePost` still looks like an ordinary `PUT`. - -## Why a conflict is the correct answer, not a retry - -When two editors produce two different versions of the same record, the -server cannot know which intent is the one meant. Both saves are -legitimate from their authors' point of view, and replaying the stale -write just replays the same data loss. - -The honest verdict is HTTP's own definition of 409: the request conflicts -with the current state of the resource, and the client is told exactly -how to resolve it — "fetch it again before retrying". The losing client -re-reads the record, sees the other writer's change, and a human decides -what to keep. The silent overwrite becomes a visible decision point, -which is the entire purpose of the exercise. - -## What the rest of the reference service proves - -The version field is one layer of a small system, and the rest of it is -verifiable the same way — every row below is a class or a config file in -the repository, not a claim: - -| Layer | What it does | Where it lives | -|---|---|---| -| Caching | Bounded Caffeine cache on single-post reads (max 500, TTL 10 min, both from config); `@Cacheable` on read, `@CachePut` on update, `@CacheEvict` on delete; `GET /api/showcase/cache` exposes requests, hits, misses and hit rate | `CacheConfig`, `CacheProperties`, `ShowcaseMetricsController` | -| Security | Stateless HTTP Basic with BCrypt; pages and read APIs are public, every mutation needs the `EDITOR` role; local defaults are a throwaway `demo-editor`/`changeit` account overridable via env vars | `SecurityConfig`, `application.yml` | -| Errors | Request records validate at the boundary; one `@RestControllerAdvice` returns consistent problem documents with machine codes — `POST_NOT_FOUND` (404), `POST_VERSION_CONFLICT` (409), `VALIDATION_FAILED` (400) with a field-error map | `CreatePostRequest`, `UpdatePostRequest`, `ApiExceptionHandler` | -| Configuration | Local profile runs an in-memory H2 database in PostgreSQL mode with `ddl-auto: update` and seeded sample posts; `prod` selects PostgreSQL, takes every credential from `APP_*` env vars and sets `ddl-auto: validate` | `application.yml`, `application-prod.yml` | -| Tests | One `@SpringBootTest` suite asserts the rendered Thymeleaf pages, unauthenticated 401s versus editor 201s, the `VALIDATION_FAILED` problem response, public search, and cache hits after repeated reads | `DemoApplicationIntegrationTest` | - -## Hardening This Pattern for Production Rollout - -Two things change the moment this pattern moves to production. The project -README says both, and they are worth repeating as my own judgement. - -First, schema management. I would add Flyway or Liquibase migrations -before ever setting `ddl-auto` to `validate`. The local development profile -uses `update`, which is convenient on a scratch database and dangerous as -a habit — production schema should be versioned code, not a side effect -of startup. - -Second, secrets. The local editor account is intentionally a non-secret -demo account with default credentials. For anything real, I would keep -credentials in a managed secret store and refuse to boot without them, -instead of falling back to a default. The `prod` profile already takes -every credential from environment variables with no committed secrets — -that is the shape I would keep, minus the fallbacks. - -## The result - -A stale update now returns HTTP 409 with code `POST_VERSION_CONFLICT` -instead of a 200 that silently discards the other writer's change. The -loss can no longer happen quietly: the failure is loud, actionable — -"fetch it again before retrying" — and the integration test suite asserts -the access and validation behaviour end to end. - -The whole fix is one annotation on one field, plus plumbing that makes -the version part of the contract. If a record can be read by two people -at the same time, that field is the difference between a lost edit and a -conflict both clients can see. - -I build Java/Spring back ends and full-stack web applications — REST APIs -with JPA, optimistic locking, caching, validation and integration tests, -from the browser page down to the database. If you have a form or a field -where edits keep quietly disappearing, tell me about it: -[WhatsApp](https://wa.me/60127972969) · -[me@hoelee.com](mailto:me@hoelee.com?subject=Spring%20Boot%20help) · -[hoelee.com](https://hoelee.com). -```` - ---- - -## 文章 08 / 11:把 CodeIgniter 4 应用从 IIS 迁移到 OpenLiteSpeed -- **Slug**: `migrating-codeigniter-iis-to-openlitespeed` -- **英文标题**: Migrating a CodeIgniter 4 App From IIS to OpenLiteSpeed -- **分类**: `engineering` | **发布日期**: 2026-09-27 -- **线上地址**: https://blog.hoelee.com/posts/migrating-codeigniter-iis-to-openlitespeed/ (EN) | https://blog.hoelee.com/posts/zh/migrating-codeigniter-iis-to-openlitespeed/ (ZH) -- **本篇审核状态**: ⏳ 待审核 (Pending) - -### ✍️ 顾问审阅意见区 (Review Feedback) -```text -【审阅结论】:[ ] 通过 [ ] 需微调 [ ] 需重构 -【事实与数字核对】: -【人设与用词卫生】: -【CRO与转化建议】: -``` - -### 🇨🇳 中文版原文 (Chinese Markdown Twin) -````markdown ---- -title: "把 CodeIgniter 4 应用从 IIS 迁移到 OpenLiteSpeed" -description: "我把一个 17,000 行的 CodeIgniter 4 应用从 Windows IIS 搬到了 CyberPanel 上的 OpenLiteSpeed。迁移后冒出两个致命错误——而 IIS 一直靠 SSO 把它们藏着。" -pubDate: 2026-09-27 -category: engineering -blueprint: sme-digital-suite -blueprintLayer: L1-high-conversion-web -tags: [codeigniter, php, openlitespeed, cyberpanel, iis, migration, litespeed, linux] -ogImage: /og/zh-migrating-codeigniter-iis-to-openlitespeed.jpg -banner: /banners/migrating-codeigniter-iis-to-openlitespeed.jpg -draft: false ---- - -我维护着一个数字命理报告生成器:一个 CodeIgniter 4 应用,接收出生日期和姓名,跑一遍命理引擎,渲染出 19 页 A4 报告。它在 Windows Server + IIS 上跑了很多年。2026 年 9 月,我把它迁到 CyberPanel 上的 OpenLiteSpeed,跑在 Linux 上,换了个域名。 - -迁移本身没什么好说的——拷文件、把 docroot 指向 `public/`、装依赖。真正值得写下来的是:**新主机上第一个未认证请求,就在两条路由上直接致命崩溃——而这两条路由在 IIS 上"一直好好的"。** - -两个 bug 都是真的。两个从一开始就存在于 IIS 上。两个都看不见,因为 IIS 在出问题的路由前面恰好挡了一层 authentik SSO。 - -## 为什么这件事重要 - -如果你的自托管应用前面挂了一层认证网关,那这层网关做的事不止是保护数据——它同时**在帮你藏 bug**。任何"只对未认证用户出错"的东西永远不会以未认证身份运行,所以永远不会报错。而它会在最糟的时刻暴露:你迁移的时候、你拆掉网关的时候、你把路由暴露到公网的时候。 - -我这个应用,就"健康"了整整几年。我把新域名指过去的那一刻,两条路由返 HTTP 500。代码一行没改。唯一变的是网关没了。 - -两个修复加起来大概二十分钟。找到它们花了两个小时——因为真正的错误信息被 CodeIgniter 的 CLI 错误渲染器挡在了后面。 - -## 环境 - -这是一个相当普通的 CI4 项目,但有一个不太常见的架构细节:报告引擎不是库,而是**同一台主机上的 HTTP 端点**。控制器拼一个请求,`curl` 回自己域名的 `/api/single`,引擎返回算好的 JSON 数值,控制器再把它渲染成可打印的报告。 - -正是这个"自调用"设计,让 IIS 上必须有 `CONST_IIS_INTERNAL_BASE`。这点我后面会回来说——它才是真正有意思的部分。 - -| | 迁移前 | 迁移后 | -|---|---|---| -| 操作系统 | Windows Server | Ubuntu (CyberPanel) | -| Web 服务器 | IIS | OpenLiteSpeed 1.9.0 | -| PHP | 8.4 (Windows 版) | 8.4.25 (lsphp84) | -| Docroot | `C:\inetpub\calc.hoelee.com` | `/home/<域名>/public_html/public` | -| 认证网关 | authentik SSO 挡 `/lifecode`、`/api/*` | 无 | - -## 第一步:docroot 指向 `public/`,不是项目根目录 - -CI4 是两段式目录结构。`app/`、`vendor/`、`writable/` 和 `.env` 都在项目根目录,只有 `public/` 本该对 Web 可见。 - -CyberPanel 建的站点根目录叫 `public_html`。我的第一反应是把整个项目解压进 `public_html`,docroot 不动。 - -**那样会把 `app/`、`vendor/`、`.env` 文件和 `writable/` 的 session 数据全部暴露在 HTTP 之下。** 这个项目的 `.env` 里有一个 webhook 凭证。任何人猜到 `/../.env`——或者干脆直接请求 `/.env`,因为这文件就躺在被服务的目录下面——就拿到了。 - -正确做法是解压进 `public_html`,然后把 vhost 的 docroot 往下一层,改成 `public_html/public`: - -```bash -# 解压成 app/、vendor/、.env 位于 public_html 之下 -cd /home/<域名>/public_html -tar -xzf /tmp/deploy.tar.gz - -# docroot 必须是 public_html/public,不是 public_html -sudo sed -i 's#/home/<域名>/public_html$#/home/<域名>/public_html/public#' \ - /usr/local/lsws/conf/vhosts/<域名>/vhost.conf - -sudo /usr/local/lsws/bin/lshttpd -t -sudo systemctl restart lsws -``` - -这是整个迁移里最重要的一步,也是大多数教程跳过的一步。其他什么都不做,这一步也得做。 - -## 第二步:IIS 藏起来的两个致命错误 - -### 致命错误一 —— `env()` 调用得太早 - -第一个 500 完全没有响应体。这不太寻常——CI4 正常会渲染点东西出来。一个空白的 500 通常意味着 PHP 在框架的错误处理器装上之前就死了。 - -CI4 的启动流程会在 `Boot::bootWeb()` 里很早加载 `app/Config/Constants.php`(通过 `Boot::loadConstants()`)。而这件事发生在 **`Common.php` 助手文件加载之前**——`env()` 就定义在那个文件里。 - -所以这一行: - -```php -// app/Config/Constants.php —— 错误写法 -define('CONST_fullBase', env('hoelee.fullBase')); -``` - -会失败于: - -``` -Fatal error: Uncaught Error: Call to undefined function env() -in app/Config/Constants.php:96 -``` - -规则是绝对的:**`Constants.php` 里只能放普通常量。** 不能有 `env()`、不能有 `getenv()`、不能有配置助手。如果你真需要依赖环境的值,就定义到启动流程更靠后的位置——或者把这个常量降级成 fallback,真正的值后面再读。 - -我做的正是后者。`CONST_fullBase` 变回普通字符串,消费它的助手函数改为**先**查框架自己的 `app.baseURL`(那个才是 `.env` 驱动的): - -```php -// app/Helpers/hoelee_helper.php -function getFullBase(bool $selfCall = false): string -{ - // .env 驱动的 baseURL 优先;CONST_fullBase 只是 fallback - if ($selfCall && defined('CONST_IIS_INTERNAL_BASE') && CONST_IIS_INTERNAL_BASE) { - return rtrim(CONST_IIS_INTERNAL_BASE, '/'); - } - $appBase = config('App')->baseURL; - if ($appBase) return rtrim($appBase, '/'); - if (defined('CONST_fullBase') && CONST_fullBase) return rtrim(CONST_fullBase, '/'); - return ''; -} -``` - -**这个是我自己搞出来的。** 同一周做凭证清理重构时引入的——我把一个硬编码 URL 挪进 `.env`,然后在 `Constants.php` 里用 `env()` 读它。在我机器上是通的,因为本地 `.env` 走的是另一条路径被读到。干净启动下它从来没通过。我是在**部署测试**后一小时内抓到的;如果只是代码审查,很可能就这么放过去了。 - -### 致命错误二 —— CI4 控制器里的 `parent::__construct()` - -第二个失败在 `/lifecode`。这个是应用里**原本就存在**的 bug,不是我引入的。 - -绕过 CLI 渲染器之后,真正的报错是: - -``` -Error: Cannot call constructor -``` - -CI4 的基础类 `CodeIgniter\Controller` **根本没有构造函数**。它实现的是 `initController()`,由框架把 request、response、logger 三个对象传进去。标准写法是: - -```php -// CI4 的正确写法 -public function initController( - RequestInterface $request, - ResponseInterface $response, - LoggerInterface $logger -) { - parent::initController($request, $response, $logger); - // 你的初始化代码 -} -``` - -但 `Lifecode.php` 和 `ApiEn.php` 用的是传统构造函数,还在调 `parent::__construct()`: - -```php -// 错误 —— CodeIgniter\Controller 没有 __construct() -public function __construct() -{ - parent::__construct(); - // ... -} -``` - -对一个没有定义 `__construct()` 的父类调 `parent::__construct()`,在 PHP 8 里是致命错误。把两个控制器改成 `initController()` 就修好了——同时要为新签名补上三个 interface 的 `use` 语句。 - -我没有盲信报错信息,而是先确认父类**确实**没有构造函数: - -```bash -grep -n 'function __construct\|function initController' \ - vendor/codeigniter4/framework/system/Controller.php -``` - -只出来 `initController()`。这一步值得做——"Cannot call constructor" 在父类**有**构造函数但内部报错时也会出现,重写签名之前你得先搞清楚自己是哪种情况。 - -## 为什么这两个 bug 在 IIS 上都不出现 - -这是让我改变部署观念的部分。 - -在 IIS 主机上,`/lifecode` 和 `/api/*` 挡在 authentik SSO 后面。对这两条路由的未认证请求返回 **HTTP 302 跳转到 `auth.hoelee.com`**——压根不会碰到控制器。那个坏掉的构造函数从来没被执行过。这条路由大概从写出来那天就是坏的,而它从来没被要求真正处理过一次请求。 - -我直接对比了两台主机来确认: - -```bash -curl -sI https://calc.hoelee.com/lifecode | head -1 -# HTTP/2 302 <- authentik 跳转;控制器根本没运行 - -curl -sI http://<新主机>/lifecode | head -1 -# HTTP/1.1 500 <- 没有网关;控制器运行并致命崩溃 -``` - -那个 302 就是这个 bug 活下来的原因。应用看起来健康,只是因为它不健康的部分根本触不到。 - -**教训说白了就是:一条路由前面挂了认证网关,就意味着这条路由自己的代码没有任何有效的测试覆盖。** 如果你要迁移或者拆网关,请专门留出时间,用未认证身份把每一条曾被网关挡着的路由都打一遍,再宣布迁移完成。小应用上这只是十行 `curl` 循环。在我这里,它本来几秒钟就能找出这两个 bug,而不是两个小时: - -```bash -for p in / /read/single /read/partner /lifecode /api/date /api/single; do - printf '%-16s %s\n' "$p" "$(curl -s -o /dev/null -w '%{http_code}' https://<主机>$p)" -done -``` - -## 第三步:那个不再是 loopback 的自调用 - -现在是这个架构里真正有意思的后果。 - -报告引擎是靠控制器 `curl` 自己的主机来调用的。在 IIS 上,`CONST_IIS_INTERNAL_BASE` 把这个调用指向 `http://localhost:7296`——loopback 接口,请求不出机器,也不碰 DNS 和 TLS。 - -在 LiteSpeed 上这个常量被**故意不定义**,于是 `getFullBase()` 落到 `app.baseURL`。这意味着每一次生成报告,现在都是**一个真实的对外 HTTPS 请求,打到应用自己的公网 URL,再从 Cloudflare 绕回来**。 - -那问题就来了:这到底能不能跑? - -答案是能,但值得专门测一次,因为它的失败模式很容易误导人。这是确切的测法——**在服务器上跑**,不是在你的笔记本上: - -```bash -curl -s -o /dev/null -w 'HTTPS self-call: %{http_code}\n' \ - -X POST 'https://<域名>/api/single' -d 'nameCn=test&dob=1990-01-01' -``` - -两个要注意的地方: - -- **在服务器上跑。** 我从 Windows 机器上打同一个 URL,拿到的是 404 和 500——那是我这台机器 DNS 解析和 Cloudflare 机器人防护的产物,不是服务器的问题。在错误的主机上测试,会得出很有把握的错误结论。 -- **看 JSON,不只看状态码。** 一个 200 配一个被截断的 body,比干脆失败更糟。我在信任之前先确认了响应能被解析。 - -这里藏着一个真实的取舍,我还没完全解决:走公网 URL 的自调用意味着生成报告依赖 Cloudflare 在线、每次报告多一次 TLS 握手、并且在整个过程中占用两个 PHP worker。在 LiteSpeed 上 worker 池不大的情况下,并发报告一多就可能死锁——每个请求都在等另一个请求,而后者拿不到空闲 worker。以目前的流量没问题。但在规模上去之前,这个自调用应该换成绕过 CDN 的内部路径。 - -## 第四步:验证真实产出,不是状态码 - -`/` 返 200 只证明落地页能渲染。它不证明报告引擎能用,而引擎才是整个产品。所以最后一步是端到端生成一份真报告: - -```bash -curl -s -X POST 'https://<域名>/read/single' \ - -d 'nameCn=test&dob=1990-01-01&gender=m' \ - -o report.html -w 'HTTP:%{http_code} bytes:%{size_download}\n' -``` - -结果:**HTTP 200、99,189 字节、19 页 A4。** 我又用中文字符输入跑了一遍,把引擎的 UTF-8 路径也走通——HTTP 200、99,205 字节、19 页、姓名渲染正常、输出里零 PHP 警告。 - -真正有意义的检查,是新旧主机之间页数可比。它证明字体、DPI 和分页逻辑都完整地熬过了这次搬迁。 - -关于那个 UTF-8 测试的插曲:我第一次跑的时候返回了 500,差点就一头扎进去查 bug。原因是我自己的 shell——中文字符在进 `curl` 的路上被终端编码搞坏了,应用收到的是非法字节。把同一个请求写成服务器上的脚本再跑,编码在我控制之内,就返回了 200。**在你调试编码故障之前,先确认服务器真正收到的字节就是你打算发出去的字节。** - -## 如果重来一次,我会怎么改 - -**迁移前就测未认证路由,而不是迁移后。** 那两个小时的排查,用一个遍历路由列表的 `curl` 循环就能完全避免。我现在把"列出所有路由、以未认证身份逐个请求、记录状态码"当成任何迁移的第零步。 - -**不要在 `Constants.php` 里调 `env()`。** 我在文件里留了注释专门写这件事,因为下一个人——多半是六个月后的我自己——一定会想这么干。 - -**迁移前先查框架版本对应的 project-space 配置。** 同一周我把 CI4 从 4.6.3 升到 4.7.4,它在两个升级指南里根本没提的属性上致命崩溃了两次:`Config\App::$permittedURIChars`(4.7 的 Router 要求)和 `Config\Format::$jsonEncodeDepth`(JSONFormatter 要求,而第二个正好打断了引擎的 JSON 自调用)。Composer 会更新 `vendor/`,但**永远**不会合并 `app/Config/*.php`,因为那些属于 project-space。我最后往 14 个配置文件里手工合并了新属性。那是另一篇文章,但迁移的教训是同一个形状:**框架会告诉你 `vendor/` 里改了什么;没有任何东西会告诉你 `app/` 里改了什么。** - -**先确认 docroot,再动别的。** 如果我解压进 `public_html` 就收手,应用是能跑的——同时静静地把 `.env` 通过 HTTP 服务出去。能跑的迁移,不等于安全的迁移。 - -## 结果 - -一个晚上。六条路由全部验证 200,中英文输入的报告产出在字节层面可比,零 PHP 警告,另外还从代码库里清掉了两个长期潜伏的 bug——而这两个 bug 一直被 IIS 的认证网关遮着。 - -应用现在跑在 OpenLiteSpeed 上,docroot 正确分离,主机可自动化管理,凭证放在 `.env` 而不是写死在常量里。 - ---- - -**想让你的应用也做这套迁移?** 我可以在 IIS、Apache、nginx 和 LiteSpeed 之间迁移 PHP 应用——包括那些麻烦的部分:自调用架构、藏 bug 的 SSO 网关,以及会碰到 project-space 配置的框架升级。 - -[WhatsApp +60 12-797 2969](https://wa.me/60127972969) · [me@hoelee.com](mailto:me@hoelee.com?subject=CodeIgniter%20migration) · [hoelee.com](https://hoelee.com) -```` - -### 🇬🇧 英文版原文 (English Markdown Primary) -````markdown ---- -title: "Migrating a CodeIgniter 4 App From IIS to OpenLiteSpeed" -description: "I moved a 17,000-line CodeIgniter 4 app from Windows IIS to OpenLiteSpeed on CyberPanel. Two fatal errors appeared that IIS had been hiding behind SSO." -pubDate: 2026-09-27 -category: engineering -blueprint: sme-digital-suite -blueprintLayer: L1-high-conversion-web -tags: [codeigniter, php, openlitespeed, cyberpanel, iis, migration, litespeed, linux] -ogImage: /og/migrating-codeigniter-iis-to-openlitespeed.jpg -banner: /banners/migrating-codeigniter-iis-to-openlitespeed.jpg -draft: false ---- - -I maintain a numerology report generator: a CodeIgniter 4 application that takes a birth date and a name, runs them through a numerology engine, and renders a 19-page A4 report. It had run on Windows Server with IIS for years. In September 2026 I moved it to OpenLiteSpeed on CyberPanel, on Linux, on a different domain. - -The migration itself was unremarkable — copy the files, point the docroot at `public/`, install dependencies. What made it worth writing about is that **the first unauthenticated request to the new host fatally crashed on two routes that had been working fine on IIS for years.** - -Both bugs were real. Both were present on IIS the whole time. Neither was visible, because IIS had an authentik SSO gate in front of the exact routes that were broken. - -## Why this matters - -If you run a self-hosted app behind an authentication gateway, your auth layer is doing more than protecting data — it is also **hiding your bugs**. Anything that only breaks for unauthenticated users never runs unauthenticated, so it never fails. The failure surfaces at the worst possible moment: when you migrate, remove the gate, or expose the route to the public internet. - -In my case the app had been reporting "healthy" for as long as I'd owned it. The moment I pointed a new domain at it, two routes returned HTTP 500. Nothing had changed in the code. The only thing that changed was that the gate was gone. - -The fix for both took about twenty minutes. Finding them took two hours, because the actual error messages were hidden behind CodeIgniter's CLI error renderer. - -## The setup - -The app is a fairly ordinary CI4 project with an unusual architecture detail: the report engine is not a library, it is a **set of HTTP endpoints on the same host**. The controllers generate a request, `curl` it back to `/api/single` on their own domain, and the engine returns JSON with the computed numbers. The controller then renders that into the printable report view. - -That self-call design is what made `CONST_IIS_INTERNAL_BASE` necessary on IIS. Let me come back to it — it turns out to be the interesting part. - -| | Before | After | -|---|---|---| -| OS | Windows Server | Ubuntu (CyberPanel) | -| Web server | IIS | OpenLiteSpeed 1.9.0 | -| PHP | 8.4 (Windows build) | 8.4.25 (lsphp84) | -| Docroot | `C:\inetpub\calc.hoelee.com` | `/home//public_html/public` | -| Auth gate | authentik SSO on `/lifecode`, `/api/*` | none | - -## Step 1: Point the docroot at `public/`, not the project root - -CI4 ships with a two-folder layout. `app/`, `vendor/`, `writable/` and `.env` live in the project root. Only `public/` is meant to be web-accessible. - -CyberPanel creates the document root as `public_html`. My first instinct was to extract the whole project into `public_html` and leave the docroot alone. - -**That would have exposed `app/`, `vendor/`, the `.env` file, and `writable/` session data over HTTP.** The `.env` in this project contains a webhook credential. Anyone who guessed `/../.env` — or just fetched `/.env`, since the file sits directly under a served directory — gets it. - -The correct layout is to extract into `public_html` and then repoint the vhost docroot one level deeper, at `public_html/public`: - -```bash -# extract the project so that app/, vendor/ and .env sit UNDER public_html -cd /home//public_html -tar -xzf /tmp/deploy.tar.gz - -# the docroot must be public_html/public, NOT public_html -sudo sed -i 's#/home//public_html$#/home//public_html/public#' \ - /usr/local/lsws/conf/vhosts//vhost.conf - -sudo /usr/local/lsws/bin/lshttpd -t -sudo systemctl restart lsws -``` - -This is the single most important step in the migration, and it is the one most guides skip. If you do nothing else, do this. - -## Step 2: The two fatals IIS was hiding - -### Fatal 1 — `env()` called too early - -The first 500 had no body at all. That is unusual — CI4 normally renders something. An empty 500 usually means PHP died before the framework's error handler was installed. - -CI4's bootstrap loads `app/Config/Constants.php` very early in `Boot::bootWeb()`, via `Boot::loadConstants()`. That happens **before** the `Common.php` helper file is loaded, which is where `env()` is defined. - -So this line: - -```php -// app/Config/Constants.php — BROKEN -define('CONST_fullBase', env('hoelee.fullBase')); -``` - -fails with: - -``` -Fatal error: Uncaught Error: Call to undefined function env() -in app/Config/Constants.php:96 -``` - -The rule is absolute: **`Constants.php` may only contain plain constants.** No `env()`, no `getenv()`, no config helper. If you need environment-dependent values there, define them further along the bootstrap — or make the constant a fallback and read the real value later. - -That is exactly what I did. `CONST_fullBase` became a plain string, and the helper that consumes it checks the framework's own `app.baseURL` (which *is* `.env`-driven) first: - -```php -// app/Helpers/hoelee_helper.php -function getFullBase(bool $selfCall = false): string -{ - // the .env-driven baseURL wins; CONST_fullBase is only a fallback - if ($selfCall && defined('CONST_IIS_INTERNAL_BASE') && CONST_IIS_INTERNAL_BASE) { - return rtrim(CONST_IIS_INTERNAL_BASE, '/'); - } - $appBase = config('App')->baseURL; - if ($appBase) return rtrim($appBase, '/'); - if (defined('CONST_fullBase') && CONST_fullBase) return rtrim(CONST_fullBase, '/'); - return ''; -} -``` - -**This one was my own doing.** I had introduced it during a secrets-cleanup refactor in the same week — I moved a hardcoded URL into `.env` and called `env()` in `Constants.php` to read it. It worked on my machine because the local `.env` was being read through a different path. It never worked on a clean boot. I caught it within an hour *only because* I deployed and tested; a code review would plausibly have waved it through. - -### Fatal 2 — `parent::__construct()` in a CI4 controller - -The second failure was on `/lifecode`, and this one is a genuine pre-existing bug in the application — not something I introduced. - -The error, once I got past the CLI renderer, was: - -``` -Error: Cannot call constructor -``` - -CI4's base `CodeIgniter\Controller` class **has no constructor**. It implements `initController()`, which the framework calls with the request, response, and logger objects. The standard pattern is: - -```php -// correct CI4 pattern -public function initController( - RequestInterface $request, - ResponseInterface $response, - LoggerInterface $logger -) { - parent::initController($request, $response, $logger); - // your setup here -} -``` - -But `Lifecode.php` and `ApiEn.php` declared a classic constructor and called `parent::__construct()`: - -```php -// BROKEN — CodeIgniter\Controller has no __construct() -public function __construct() -{ - parent::__construct(); - // ... -} -``` - -`parent::__construct()` on a parent class that does not define `__construct()` is a fatal in PHP 8. Converting both controllers to `initController()` fixed it — and required adding the three `use` statements for the interface types in the new signature. - -I checked whether the base class *really* had no constructor rather than trusting the error message: - -```bash -grep -n 'function __construct\|function initController' \ - vendor/codeigniter4/framework/system/Controller.php -``` - -Only `initController()` came back. Worth doing — "Cannot call constructor" also fires when a parent *has* a constructor that errors internally, and you want to know which case you are in before you rewrite the signature. - -## Why neither bug showed up on IIS - -This is the part that changed how I think about the deployment. - -On the IIS host, `/lifecode` and `/api/*` sat behind authentik SSO. An unauthenticated request to either returned **HTTP 302 to `auth.hoelee.com`** — it never reached the controller at all. The broken constructor was never executed. The route had presumably been broken since it was written, and it had never once been asked to serve a request. - -I confirmed this by comparing the two hosts directly: - -```bash -curl -sI https://calc.hoelee.com/lifecode | head -1 -# HTTP/2 302 <- authentik redirect; controller never runs - -curl -sI http:///lifecode | head -1 -# HTTP/1.1 500 <- no gate; controller runs and fatals -``` - -The 302 is why the bug survived. The app looked healthy because the unhealthy parts were unreachable. - -**The lesson, stated plainly: an auth gate in front of a route means that route has no working test coverage for its own code.** If you migrate or remove the gate, budget time to hit every previously-gated route unauthenticated before you call the migration done. On a small app that is a ten-line `curl` loop. Here it would have found both bugs in seconds instead of two hours: - -```bash -for p in / /read/single /read/partner /lifecode /api/date /api/single; do - printf '%-16s %s\n' "$p" "$(curl -s -o /dev/null -w '%{http_code}' https://$p)" -done -``` - -## Step 3: The self-call that stops being a loopback - -Now the interesting architectural consequence. - -The report engine is reached by the controller `curl`-ing its own host. On IIS, `CONST_IIS_INTERNAL_BASE` pointed that call at `http://localhost:7296` — the loopback interface — so the request never left the machine and never touched TLS or DNS. - -On LiteSpeed that constant is deliberately left **undefined**, so `getFullBase()` falls through to `app.baseURL`. Which means every report generation now makes a **real outbound HTTPS request to the app's own public URL** and comes back in through Cloudflare. - -Which raises the obvious question: does that work at all? - -The answer is yes, but it is worth testing explicitly, because the failure mode is confusing. Here is the exact test — run it **on the server**, not from your laptop: - -```bash -curl -s -o /dev/null -w 'HTTPS self-call: %{http_code}\n' \ - -X POST 'https:///api/single' -d 'nameCn=test&dob=1990-01-01' -``` - -Two things to watch for: - -- **Run it from the server.** From my Windows machine the same URL returned 404 and 500 — an artefact of DNS resolution and Cloudflare bot protection on my caller, not a server problem. Testing from the wrong host produces confident, wrong conclusions. -- **Watch the JSON, not just the status code.** A 200 with a truncated body is worse than a clean failure. I checked the response was parseable before trusting it. - -There is a real trade-off hiding here, and I have not fully resolved it: a public-URL self-call means report generation depends on Cloudflare being up, costs a TLS handshake per report, and occupies two PHP workers for the duration. On LiteSpeed with a small worker pool, a burst of concurrent reports could deadlock — each request waiting on another request that has no free worker. For the current traffic level it is fine. Before this scales, the self-call should move to an internal path that bypasses the CDN. - -## Step 4: Verify the actual output, not the status code - -A 200 on `/` proves the landing page renders. It does not prove the report engine works, and the engine is the entire product. So the last step was generating a real report end to end: - -```bash -curl -s -X POST 'https:///read/single' \ - -d 'nameCn=test&dob=1990-01-01&gender=m' \ - -o report.html -w 'HTTP:%{http_code} bytes:%{size_download}\n' -``` - -The result: **HTTP 200, 99,189 bytes, 19 A4 pages.** I ran it again with Chinese-character input to exercise the UTF-8 path through the engine — HTTP 200, 99,205 bytes, 19 pages, name rendering correctly, zero PHP warnings in the output. - -Byte-comparable page counts between the old and new host is the check that matters. It proves the fonts, the DPI, and the pagination logic all survived the move. - -A side note on the UTF-8 test: my first attempt at it returned a 500 and I nearly went bug-hunting. The cause was my own shell — the Chinese characters were being mangled by the terminal encoding on the way into `curl`, so the app received invalid bytes. Running the same request from a script on the server, where the encoding is under my control, returned 200. **Before you debug an encoding failure, confirm the bytes actually arriving at the server are the bytes you meant to send.** - -## What I'd do differently - -**Test unauthenticated routes before migrating, not after.** The whole two-hour debugging session was avoidable with a `curl` loop over the route list. I now treat "list every route, hit it unauthenticated, record the status" as step zero of any migration. - -**Do not call `env()` in `Constants.php`.** I have left a comment in the file itself saying so, because the next person — probably me in six months — will be tempted. - -**Check the framework version's project-space config before the move.** The same week, I upgraded CI4 from 4.6.3 to 4.7.4, and it fataled twice on properties the upgrade guide did not mention: `Config\App::$permittedURIChars`, required by the 4.7 Router, and `Config\Format::$jsonEncodeDepth`, required by the JSONFormatter — the second of which broke the engine's JSON self-call specifically. Composer updates `vendor/` but never merges `app/Config/*.php`, because those are project-space files. I ended up merging new properties into 14 config files. That is a separate post, but the migration lesson is the same shape: **the framework tells you what changed in `vendor/`; nothing tells you what changed in `app/`.** - -**Confirm the docroot before anything else.** If I had extracted into `public_html` and stopped, the app would have worked — and quietly served `.env` over HTTP. A migration that works is not the same as a migration that is safe. - -## The result - -One evening. Six routes verified 200, byte-comparable report output on both Chinese and ASCII input, zero PHP warnings, and two long-standing latent bugs removed from the codebase that IIS had been concealing behind an auth gate. - -The app is now running on OpenLiteSpeed with a properly separated docroot, on a host I can automate, with the credential in `.env` rather than a constant. - ---- - -**Want this done for your own application?** I migrate PHP applications between IIS, Apache, nginx and LiteSpeed — including the awkward parts: self-calling architectures, SSO gates that hide bugs, and framework upgrades that touch project-space config. - -[WhatsApp +60 12-797 2969](https://wa.me/60127972969) · [me@hoelee.com](mailto:me@hoelee.com?subject=CodeIgniter%20migration) · [hoelee.com](https://hoelee.com) -```` - ---- - -## 文章 09 / 11:用「热浏览器会话」爬取有反爬墙的电商网站 -- **Slug**: `scraping-bot-walled-marketplace-warm-browser-session` -- **英文标题**: Scraping a Bot-Walled Marketplace With a Warm Browser Session -- **分类**: `engineering` | **发布日期**: 2026-09-13 -- **线上地址**: https://blog.hoelee.com/posts/scraping-bot-walled-marketplace-warm-browser-session/ (EN) | https://blog.hoelee.com/posts/zh/scraping-bot-walled-marketplace-warm-browser-session/ (ZH) -- **本篇审核状态**: ⏳ 待审核 (Pending) - -### ✍️ 顾问审阅意见区 (Review Feedback) -```text -【审阅结论】:[ ] 通过 [ ] 需微调 [ ] 需重构 -【事实与数字核对】: -【人设与用词卫生】: -【CRO与转化建议】: -``` - -### 🇨🇳 中文版原文 (Chinese Markdown Twin) -````markdown ---- -title: "用「热浏览器会话」爬取有反爬墙的电商网站" -description: "为一位做二手手机生意的客户:爬取有反爬墙的电商商品列表——热 CDP 会话、失败即止的健康检查、分段等待渲染。" -pubDate: 2026-09-13 -category: engineering -tags: ["scraping", "cdp", "headless-chrome", "anti-bot", "shopee", "python"] -ogImage: "/og/zh-scraping-bot-walled-marketplace-warm-browser-session.jpg" -banner: "/banners/scraping-bot-walled-marketplace-warm-browser-session.jpg" -draft: false ---- - -一位客户请我做一个听起来很简单的东西:每天把一个大电商平台上的二手手机列出来,按价格排序,好让他的进货决策靠数据而不是靠感觉。这位客户靠倒卖二手电子产品吃饭——一台手机差几百马币就是他的利润。 - -结果完全不是一段干净的 `requests` + BeautifulSoup 脚本。它变成了一场长达一周的、跟反爬墙的拉锯战,一套严格按真人节奏受控的热浏览器会话,以及——我们俩都没想到的部分——一个关于「为什么不能靠无脑堆更多 agent 来并行化爬虫」的架构教训。 - -这就是那个故事,按照我经历的顺序来讲:问题、我试过却失败的每一件事、最终奏效的办法,以及下次我会怎么做。 - -## 问题,用别人真正会搜索的方式表述 - -> "如何从一个拦截无头浏览器的网站爬取商品列表?" - -或者更诚实地说:**当一个电商网站已经把「防爬」当成它唯一的本职工作,你要怎么爬它?** Shopee 不会礼貌地把 HTML 喂给 `curl`。它会检测自动化、抛出一个 `/verify` 验证码,然后静默地给你一个「看起来正常但里面什么都没有」的页面。 - -客户的需求清单很短: - -- 搜索二手手机,只筛选「二手」成色,存储 128 GB 及以上。 -- 提取每个商品的所有存储规格和价格。 -- 按价格升序排序。 -- 不搞一百个 headless 实例的 `chromedriver` 农场——倒卖的利润养不起一百个住宅 IP,我的也一样。 - -从这里开始,全部都是调试故事。 - -## 我试过的,以及为什么失败 - -### 尝试 1:通过 CDP 用冷的无头 Chrome——「直接把 Chrome 远程调试开起来」 - -我用 `--headless --remote-debugging-port=9222` 启动了 Chrome,用 Chrome DevTools Protocol 连上去,然后导航到搜索 URL。大约十秒钟里我觉得自己很聪明。 - -**失败:** 页面加载了,但每个商品卡片都是空的。DOM 是个空壳。Shopee 指纹识别了这个无头浏览器(没有真正的 GPU、user-agent 指纹不一致、`navigator.webdriver` 标志),把我重定向进了一个我永远过不去的 `/verify` 验证码循环。冷的无头 profile 一上来就撞墙。 - -教训很无聊但很重要:**如果你的浏览器本身在「身份」上撒谎,选择器写得再好也没用。** - -### 尝试 2:并行子 agent——「直接开 N 个 worker」 - -这是我最想让它成功的方案。我有一套多 agent 的架构。本能反应就是:开五个 agent,每个爬一个不同的搜索词,收集结果,合并。 - -**失败:** 它们全都连到**同一个**浏览器会话上。它们不会各自拿到一个浏览器——只会各自拿到共享 Chrome 实例里的一个标签页,或者更糟:全都挤在同一个标签页上。每一次 `Page.navigate` 都会把上一个 agent 的上下文抹掉。而且关键在于: - -1. **热会话是共享资源。** 只有一个没被标记的 Canary profile。五个 agent 交错访问同一个标签页,在 Shopee 眼里,跟一个浏览器疯狂快速导航没有区别。而这恰恰是**触发**反爬墙的行为。 -2. **反爬的「节奏」是累积的。** 我的可用方案依赖导航之间约 7 秒的间隔来显得像真人。五个 agent 并发导航,就等于五个导航以零间隔打向同一个会话。 - -所以「横向扩展」的本能——加更多 worker——对我赖以存活的那件事(看起来像真人)是有害的。这里的并发上限不是 CPU 也不是内存,而是**一个热浏览器,一次一个标签页。** - -### 尝试 3:靠「Buy With Voucher」按钮来拿价格 - -一旦列表能渲染出来了,我假设购买按钮的文案里带着价格。大多数电商网站确实如此。但这个渲染出来的按钮写的是 `Add To Cart` / `Buy Now`。我用来匹配「Buy With Voucher … RM…」的正则什么都匹配不到,我在原地打转了好一会儿,才真正去读了 DOM。 - -**失败:** Shopee 商品页的价格不在按钮里。它被渲染成**拆分的 span**——`RM` 在一个元素里、`850` 在另一个里、`00` 又在另一个里——所以朴素的叶子文本匹配只会抓到碎片,或者当商品有多个规格时,抓到一个**区间**(`RM850.00 - RM1150.00`)。 - -### 尝试 4:点击规格选项来拿精确价格 - -对于单轴规格选择器(比如一个存储下拉:128GB / 256GB / 512GB),点击一个选项会把价格收敛成单个值,我的提取方法能正常工作。 - -**失败:** 对于**双轴**选择器(品牌 × 存储),点击第一个轴(某个品牌)会锁定一个价格,但加上第二个轴(某个存储规格)又把它**解散**回商品全区间。这个面板渲染的是「所有可购买组合」的区间,而不是我选中的那个具体组合;而且「已选中」状态是用一个「同时匹配其他所有选项框」的 class 来标记的。我没法可靠地知道我到底锁定了哪个组合。 - -我在这个上面花了实打实的时间,最后才接受这个诚实的答案:**对于真正的双轴商品,正确的数据是价格区间,而不是一个瞎猜的「每个组合」数字。** 发布一个「有时候能用」的脆弱覆盖方案,比老实报告一个区间更糟糕。 - -## 修复——真正奏效的东西 - -三块,都很小,都是吃了亏才学会的。 - -### 1. 热的人性化节奏的浏览器会话(地基) - -别跟墙硬刚。用一个已经登录过、正常浏览过的浏览器 profile——一个「热」profile。用真实的 7 秒间隔来导航。它更慢,但它是唯一能稳定活下来的方式。 - -```python -# 不是真正的代码——是它的「形状」。先导航,然后像真人一样等待。 -goto_url(target) -time.sleep(7) # 真人节奏,不可妥协 -wait_for_selector(".shopee-search-item-result__item") -``` - -### 2. 失败即止,别傻等超时 - -在任何爬取之前,先打 CDP 的 HTTP 端点,检查会话状态。如果 Canary 挂掉了、或标签页停在 `/verify` 上,就在约 1 秒内中止,而不是在「怎么还不渲染」的超时里浪费 40 秒。 - -```python -import json, urllib.request - -def session_healthy(): - try: - tabs = json.load(urllib.request.urlopen("http://127.0.0.1:9222/json")) - except Exception: - return False - for t in tabs: - if t.get("type") == "page" and "/verify" in t.get("url", ""): - return False # 撞到验证码墙——重新热会话,别爬了 - return True -``` - -就这么一个改动,把「静默的 40 秒死胡同」变成了「即时、可执行的失败」。 - -### 3. 正确的价格选择器:最深的纯 RM 节点 - -购买按钮是个谎言。价格是**那个文本内容纯粹是一个 RM 值的、最深的元素**——在选中规格之前是一个区间(`RM850.00 - RM1150.00`),之后是单个值(`RM850.00`)。遍历 DOM,取文本能匹配上的最深元素: - -```python -import re - -RM = re.compile(r"^RM\s?[\d,.]+(\s?[-–]\s?RM\s?[\d,.]+)?$") - -# DOM 树遍历逻辑(通过 CDP Runtime.evaluate 或 DOM 包装器执行) -def find_price(root): - best, depth = None, -1 - for el in root.querySelectorAll("*"): - txt = (el.textContent or "").strip() - if txt and RM.match(txt) and " " not in txt.split("RM")[0]: - d = depth_of(el) - if d > depth: - best, depth = el, d - return best.textContent.strip() if best else None -``` - -这就是全部的诀窍。没有脆弱的 class 名。没有瞎猜。一个「整个文本就是一个价格」的节点,就是价格本身。 - -## 结果——一个可量化的成果 - -从单个热会话、一次串行遍历中,我提取了 **20+ 个二手手机商品及其各规格价格**,筛选到 128 GB 及以上,按价格升序排序。最便宜的真实目标——一台 128GB 机型——以 **RM299** 的价格浮出水面,另外还有几台 128/256GB 的选项在 RM450–880 区间。现在一条命令(`sweep.py ...`)就能重新检查整份候选清单并输出 JSONLines;客户每天进货前跑一次。 - -但我最庆幸的数字是这个:**零验证码。** 「热会话 + 人性化节奏 + 失败即止」这套组合,在整次遍历中一次都没触发过 `/verify`。 - -## 下次我会怎么做 - -1. **我会一开始就写「失败即止」的健康检查**,在任何爬取代码之前。三十秒的活,换来未来每次失败省四十秒。 -2. **我会从第一天就抵抗并行化的冲动。** 「爬虫太慢」的答案是把更多工作打包进一次串行遍历(批量搜索、对多个 URL 跑 `sweep.py`),而不是「再加 worker」。共享的浏览器状态让并发变得更糟,而不是更好。 -3. **我会立刻接受双轴的限制**,老实报告区间,而不是在一个根本没法可靠化的选择器上烧一个下午。 -4. **我会别再猜 DOM 结构,先去探测它。** 几乎每一个错误假设(URL 路径里 `/i.` vs `-i.`、把 `Buy With Voucher` 当价格锚点、「过滤器是个真正的 `` 复选框」)都来自**没有先读真实的 DOM**。 - -## 可复用的部分 - -所有这一切被做成了一个小的独立工具集——每个脚本都是一次自包含的 `python x.py ...` 调用: - -| 脚本 | 作用 | -|---|---| -| `search.py` | 粗粒度搜索 → 商品卡片 | -| `used_search.py` | 点击「二手」条件复选框,校验 URL 里的 `USED_ITEM`,再提取 | -| `detail.py` | 从商品页提取各规格价格(最深 RM 节点法 + 分段等待) | -| `sweep.py` | 一次会话内对 N 个 URL 做批量详情提取,按 item-id 去重,写 JSONLines,打印表格 | -| `cdp_common.py` | 共享的健康检查 + 导航辅助 | - -真正可复用的教训不是那些 Shopee 专属的选择器——而是**姿态**:**假设页面在 DOM 上撒谎,失败即止,用批量化而不是并行 worker 来扩展。** - ---- - -*这是一次真实的调试过程,不是事后补写的教程。这个爬虫工具集、以及这里的每一次失败,都发生在为一个做二手电子产品倒卖的客户构建它的过程中——我保留了能泛化的部分,砍掉了那些只对某个马来西亚电商网站、某个时间点有效的部分。* - ---- - -## 想为你的业务做这个吗? - -我做定制爬虫和数据提取管道——热会话 CDP 爬虫、反爬墙感知的采集器、批量价格监控扫描——也做全栈 Web 应用(PHP/CodeIgniter、Java/Spring、React/TypeScript)和自托管自动化(n8n、Telegram 机器人、NAS 上的 Docker)。 - -如果你需要从某个「会反抗」的网站拿商品或价格数据,直接点进来,告诉我你想提取什么: - -- 💬 [WhatsApp](https://wa.me/60127972969) — 直接私信我 -- ✉️ [Email](mailto:me@hoelee.com?subject=Custom%20scraping%20pipeline) — 告诉我网站和数据 -- 🌐 [hoelee.com](https://hoelee.com) — 看看我还做了些什么 -```` - -### 🇬🇧 英文版原文 (English Markdown Primary) -````markdown ---- -title: "Scraping a Bot-Walled Marketplace With a Warm Browser Session" -description: "Scraping bot-walled marketplace listings for a client's used-electronics business: warm CDP session, fail-fast health checks, split-wait rendering." -pubDate: 2026-09-13 -category: engineering -tags: ["scraping", "cdp", "headless-chrome", "anti-bot", "shopee", "python"] -ogImage: "/og/scraping-bot-walled-marketplace-warm-browser-session.jpg" -banner: "/banners/scraping-bot-walled-marketplace-warm-browser-session.jpg" -draft: false ---- - -A client asked me to build something that sounds simple: every day, list the second-hand phones on a big marketplace, sorted by price, so their restocking decisions come from data instead of gut feel. The client resells used electronics for a living — a few hundred ringgit either way on a phone is the whole margin. - -The result was nothing like a clean `requests` + BeautifulSoup script. It was a week-long fight against an anti-bot wall, a carefully paced warm browser session, and — the part neither of us saw coming — a hard architectural lesson about why you cannot just "parallelize" a scraper by throwing more agents at it. - -This is that story, told in the order I lived it: the problem, everything I tried that failed, the thing that finally worked, and what I'd do differently. - -## The problem, phrased the way someone would actually search it - -> "How do I scrape product listings from a site that blocks headless browsers?" - -Or, more honestly: **how do you scrape a marketplace that has already made scraping its sole job description?** Shopee doesn't politely serve HTML to `curl`. It detects automation, throws a `/verify` captcha, and silently serves you a page that looks fine but contains nothing. - -The client's requirement list was small: - -- Search for used phones, filter to "used condition only", storage 128 GB and up. -- Extract every listing's storage variants and prices. -- Sort by price ascending. -- Do it without a `chromedriver` farm of a hundred headless instances — a reseller's margins don't pay for a hundred residential IPs, and neither do mine. - -Everything after this point is the debugging story. - -## What I tried, and why it failed - -### Attempt 1: cold headless Chrome via CDP — "just point Chrome's remote debugger at it" - -I launched Chrome with `--headless --remote-debugging-port=9222`, connected with the Chrome DevTools Protocol, and navigated to a search URL. It felt clever for about ten seconds. - -**Failure:** the page loaded, but every product card was empty. The DOM was a shell. Shopee had fingerprinted the headless browser (no real GPU, no real user-agent fingerprint consistency, `navigator.webdriver` flag) and redirected me into a `/verify` captcha loop I never got past. Cold headless profiles hit the wall immediately. - -The lesson is boring but important: **anti-bot systems don't care how good your selectors are if the browser itself is lying about what it is.** - -### Attempt 2: parallel subagents — "just spawn N workers" - -This was the one I really wanted to work. I have a multi-agent setup. The natural instinct is: spawn five agents, each scraping a different search query, gather the results, merge. - -**Failure:** all of them attach to the *same* browser session. They don't get their own browser — they get their own *tab* in one shared Chrome instance, or worse, they all fight over the same single tab. Every `Page.navigate` un-does the previous agent's context. And critically: - -1. **The warm session is a shared resource.** There is one Canary profile that isn't flagged. Five agents navigated the same tab in an interleaved order, which is indistinguishable — to Shopee — from one browser doing rapid-fire navigation. That's exactly the behavior that *triggers* the wall. -2. **Anti-bot pacing is cumulative.** My working setup depends on ~7-second gaps between navigations to look human. Five agents navigating concurrently means five navigations hitting the same session with effectively zero gap. - -So the "horizontal scaling" instinct — more workers — is actively hostile to the one thing keeping me alive: looking human. The concurrency ceiling here isn't CPU or memory. It's **one warm browser, one tab at a time.** - -### Attempt 3: trusting the "Buy With Voucher" button for the price - -Once I had listings rendering, I assumed the buy button's label contained the price. On most marketplaces it does. On this render, the button said `Add To Cart` / `Buy Now`. My regex for "Buy With Voucher … RM…" matched nothing, and I went around in circles for a while before actually reading the DOM. - -**Failure:** the price on Shopee product pages isn't in the button. It's rendered as **split spans** — `RM` in one element, `850` in another, `00` in a third — so a naive leaf-text match returns fragments, or a **range** (`RM850.00 - RM1150.00`) when the listing has multiple variants. - -### Attempt 4: clicking variant options to get an exact price - -For a single-axis variant selector (e.g. one dropdown of storage options — 128GB / 256GB / 512GB), clicking one option collapses the price to a single value, and my extraction worked. - -**Failure:** for a **two-axis** selector (brand × storage), clicking the first axis (a brand) locks a price, but adding the second axis (a storage size) *un-collapses* it back to the product-wide range. The panel renders the range of all purchasable combinations, not the exact combination I selected, and the "selected" state is marked by a class that also matches every other option box. There is no reliable way to know which combination I actually locked. - -I spent real time on this before accepting the honest answer: **for genuinely two-axis listings, the correct data is the price range, not a guessed per-combination number.** Shipping a fragile override that "sometimes works" would be worse than reporting an honest range. - -## The fix — what actually worked - -Three pieces, all small, all learned the hard way. - -### 1. A warm, human-paced browser session (the foundation) - -Don't fight the wall. Use a browser profile that has already logged in and browsed normally — a "warm" profile. Navigate with real 7-second gaps. It is slower and it is the only thing that reliably survives. - -```python -# not real code — the *shape* of it. Navigate, then wait like a human. -goto_url(target) -time.sleep(7) # human pacing, non-negotiable -wait_for_selector(".shopee-search-item-result__item") -``` - -### 2. Fail fast, don't time out - -Before any scrape, hit the CDP HTTP endpoint and check the session state. If Canary is down or the tab is sitting on `/verify`, abort in ~1 second instead of wasting 40 seconds on a "did not render" timeout. - -```python -import json, urllib.request - -def session_healthy(): - try: - tabs = json.load(urllib.request.urlopen("http://127.0.0.1:9222/json")) - except Exception: - return False - for t in tabs: - if t.get("type") == "page" and "/verify" in t.get("url", ""): - return False # captcha wall — re-warm the session, don't scrape - return True -``` - -This one change turned "silent 40-second dead-ends" into "instant, actionable failure." - -### 3. The right price selector: deepest pure-RM node - -The buy button is a lie. The price is the **deepest element whose text is a pure RM value** — a range (`RM850.00 - RM1150.00`) before a variant is selected, a single value (`RM850.00`) after. Walk the DOM and take the deepest element whose text matches: - -```python -import re - -RM = re.compile(r"^RM\s?[\d,.]+(\s?[-–]\s?RM\s?[\d,.]+)?$") - -# DOM walk logic (executed via CDP DOM wrapper / Runtime.evaluate) -def find_price(root): - best, depth = None, -1 - for el in root.querySelectorAll("*"): - txt = (el.textContent or "").strip() - if txt and RM.match(txt) and " " not in txt.split("RM")[0]: - d = depth_of(el) - if d > depth: - best, depth = el, d - return best.textContent.strip() if best else None -``` - -That's the whole trick. No brittle class names. No guessing. A node whose entire text *is* a price is the price. - -## The result — one quantified outcome - -From a single warm session, in one serial pass, I extracted **20+ used-phone listings with per-variant prices**, filtered to 128 GB and up, sorted by price. The cheapest real target — a 128GB model — surfaced at **RM299**, alongside several 128/256GB options in the RM450–880 range. One command (`sweep.py ...`) now re-checks the whole shortlist and dumps JSONLines; the client runs it once a day before restocking. - -But the number I'm most glad about is this: **zero captchas.** The warm-session + human-pacing + fail-fast combo survived the entire sweep without tripping `/verify` once. - -## What I'd do differently - -1. **I'd write the fail-fast health check first**, before a single scraping line. It's thirty seconds of work that saves forty seconds per future failure. -2. **I'd resist the parallelization instinct day one.** The answer to "the scraper is slow" is "bundle more work into one serial pass" (batch search, `sweep.py` over many URLs), not "more workers." Shared browser state makes concurrency worse, not better. -3. **I'd accept the two-axis limitation immediately** and report ranges, instead of burning an afternoon on a selector that can't be made reliable. -4. **I'd stop guessing DOM structure and probe it.** Almost every mistaken assumption (`/i.` vs `-i.` in the URL path, `Buy With Voucher` as the price anchor, "the filter is a real `` checkbox") came from *not reading the actual DOM first*. - -## The reusable pieces - -All of this became a small, standalone toolkit — each script is one self-contained `python x.py ...` call: - -| Script | What it does | -|---|---| -| `search.py` | Coarse search → listing cards | -| `used_search.py` | Clicks the "Used" condition checkbox, verifies `USED_ITEM` in the URL, extracts | -| `detail.py` | Pulls per-variant prices from a product page (deepest-RM-node method + split-wait) | -| `sweep.py` | Batch detail over N URLs in one session, dedupes by item-id, writes JSONLines, prints a table | -| `cdp_common.py` | Shared health check + navigation helpers | - -The genuinely reusable lesson isn't the Shopee-specific selectors — it's the *posture*: **assume the page is lying about its DOM, fail fast, and scale by batching, not by parallel workers.** - ---- - -*This is a real debugging session, not a tutorial written after the fact. The scraping toolkit and every one of these failures happened while building it for a client who resells used electronics — I kept the parts that generalize and cut the parts that only matter to one Malaysian marketplace at one point in time.* - ---- - -## Want this for your business? - -I build custom scraping and data-extraction pipelines — warm-session CDP scrapers, bot-wall-aware crawlers, and batch price-monitoring sweeps — as well as full-stack web apps (PHP/CodeIgniter, Java/Spring, React/TypeScript) and self-hosted automation (n8n, Telegram bots, Docker on NAS). - -If you need product or price data off a site that fights back, tap through and tell me what you're trying to extract: - -- 💬 [WhatsApp](https://wa.me/60127972969) — message me directly -- ✉️ [Email](mailto:me@hoelee.com?subject=Custom%20scraping%20pipeline) — tell me the site + the data -- 🌐 [hoelee.com](https://hoelee.com) — see what else I build -```` - ---- - -## 文章 10 / 11:JavaScript 文件静默失效的两种方式:而页面看上去一切正常 -- **Slug**: `two-ways-a-javascript-file-stops-working-and-looks-fine` -- **英文标题**: Two Ways a JavaScript File Stops Working and Looks Fine -- **分类**: `engineering` | **发布日期**: 2025-02-20 -- **线上地址**: https://blog.hoelee.com/posts/two-ways-a-javascript-file-stops-working-and-looks-fine/ (EN) | https://blog.hoelee.com/posts/zh/two-ways-a-javascript-file-stops-working-and-looks-fine/ (ZH) -- **本篇审核状态**: ⏳ 待审核 (Pending) - -### ✍️ 顾问审阅意见区 (Review Feedback) -```text -【审阅结论】:[ ] 通过 [ ] 需微调 [ ] 需重构 -【事实与数字核对】: -【人设与用词卫生】: -【CRO与转化建议】: -``` - -### 🇨🇳 中文版原文 (Chinese Markdown Twin) -````markdown ---- -title: "JavaScript 文件静默失效的两种方式:而页面看上去一切正常" -description: "一个被参数名遮住的函数名,加一个声明在首次调用之后的 let,让整段脚本停摆——而页面渲染得完美好看,因为屏幕上什么都没变。" -pubDate: 2025-02-20 -updatedDate: 2026-10-16 -category: engineering -tags: ["javascript", "i18n", "debugging", "frontend"] -ogImage: /og/zh-two-ways-a-javascript-file-stops-working-and-looks-fine.jpg -banner: /banners/two-ways-a-javascript-file-stops-working-and-looks-fine.jpg -draft: false ---- - -## 一次「什么都没发生」的改动 - -我给一个自己用的媒体转码队列看板加了语言切换:三份语言包、一个 `t(key, vars)` 函数、界面 chrome 上的 `data-i18n`、顶栏一个 `` in the top bar. - -After deploying it, the page looked exactly as it had before. Not broken — -*unchanged*. Same layout, same Chinese labels, no missing panels, no error -card, no console banner. The switcher was simply not there, and neither was -anything else the new code was supposed to do. - -That is the shape of bug I want to write down, because the page was not -"mostly working". **The script had stopped executing partway through — -twice, for two unrelated one-line reasons — and the page rendered perfectly -anyway.** - -## Why nothing looked broken - -Two design decisions I would make again, and both of them hid the failure. - -The first is that the default language lives in the markup. The Chinese text -is written inside the elements; `data-i18n` is only a hook that *overrides* -it when you switch. That is deliberate — the page needs no fetch to render, -and if a language pack goes missing you get Chinese instead of a row of -`top.theme_to_dark` keys. It also means a completely dead i18n layer -produces a page that is, visually, correct. - -The second is that the buttons are wired with inline handlers -(`onclick="rtFoo()"`), which after a script abort point at functions that -were never defined. Nothing warns you. The page only reveals the truth when -a human clicks something. - -So the symptom was "my change had no effect", which is the least informative -symptom a web page can give you. - -## Failure one: a parameter that swallowed a function - -The file has a theme block and an i18n block. The theme block had this -signature: - -```js -function applyTheme(t) { // t = the theme - label.textContent = t('top.theme_to_dark'); // TypeError: t is not a function -} -``` - -`applyTheme` was written before the i18n layer existed, and `t` was a -perfectly reasonable name for "theme". When the i18n layer arrived, `t` in -that scope stopped meaning the theme and started meaning *the function I -wanted to call* — except the parameter shadows it, so the call became -"invoke a string". - -A `TypeError` at the top level of a classic script does not just fail one -line. Everything after it never runs: the language-pack loader, the -`data-i18n` sweep, the switcher rendering. One wrong letter removed an -entire feature, silently. - -The fix is one character — rename the parameter to `th` — plus a comment -where the next person will look: - -```js -function applyTheme(th) { // NOT `t`: t() is the i18n function in this file -``` - -## Failure two: a declaration that arrived too late - -The second cause was in the same file, and it is a JavaScript rule people -know and still trip over. The theme block runs at load and calls `t('…')`. -The i18n block, further down the file, began with: - -```js -let LANG = localStorage.getItem('rt_lang') || 'zh-CN'; -``` - -`let` and `const` are hoisted but **not initialised**: between the start of -the scope and that line they live in the temporal dead zone, and any access -throws `Cannot access 'LANG' before initialization`. Because the theme block -sits *above* the i18n block, the failure was not a race — it was guaranteed -on every single load. - -Note the distinction from `var`, which would have quietly given me -`undefined` and a working page. The TDZ is the language protecting me from -exactly the bug I was about to write; the only reason it looked like -"nothing happened" is the markup fallback again. - -The fix is ordering, and ordering here is a *dependency*, not a style -choice: if a block calls `t()`, the i18n declarations have to be above it. -The file had been organised by topic ("theme, then i18n") because that is -how it grew. - -## Why my checks did not catch either one - -I had tests. They checked intent, not effect: - -- the three language packs exist and parse; -- every key used in the markup exists in every pack; -- no pack contains a dead key (a typo detector); -- the `{var}` placeholder sets in the three packs match. - -All true. All green. None of them executes the page, so none of them can see -a script that aborts on line 12 of 900. Static checks are structurally -unable to catch "the file is valid and the program is dead". - -## Assert on effects, in a browser - -What found both bugs was asking the live page questions that only a running -program can answer: - -```js -typeof t === 'function' // is the entry point still callable? -document.querySelectorAll('[data-i18n]').length // hooks present -rtCheckHandlers() // do the inline handlers still resolve? -``` - -That last one is worth more than it looks. The page carries **219 inline -`onclick` attributes naming 217 distinct functions**; the check enumerates -them and asserts each name is defined on `window`. It turns a hand-clicked -smoke test into a two-second automated one, and it is the check that turns -"the page looks right" into a measurable property. - -The second tool is cheaper and nastier: a **pseudo-language**. -`?lang=pseudo` takes every string in the pack, prefixes it with `[~~` and -stretches it 1.6×. Then assert two things — no horizontal overflow at -1440px, and no element in the nav still lacks the `[~~` prefix. The first -catches layout that only breaks in a longer language; the second catches -nodes that never got a translation hook at all. It found a real one in the -same run. - -Honest scope note: a pseudo-locale does not prove your Malay translation is -*good*. It proves the *plumbing* is complete — every string flows through -the mechanism, and the layout survives length. Judgement about the words -stays with a human. - -## What I would do differently - -1. **Load the page in a real browser and assert `typeof` on the entry points - before believing a client-side refactor worked.** A dead script is - invisible to every static check you own. -2. **Never let a parameter name shadow a function the same file calls.** One - letter bought me an entire afternoon; the comment is the part that stops - it recurring. -3. **Treat declaration order as a dependency, not aesthetics.** If a block - calls a function or reads a constant, that declaration goes above it — - especially in one long script. -4. **Generate the language packs from one table.** Then "the keys match" is - a test rather than a hope, and drift cannot be merged. -5. **When a change does nothing, suspect the script before the change.** - "Nothing happened" is the default failure mode of a rendered page, not - evidence that your code was inert. - -## The result - -Two one-line causes, both in the same file, both found by browser-side -assertions rather than by reading code again. The dashboard switches -language at runtime now, the default render is byte-for-byte what it was -before the change, and the three packs come from a single generated table — -so a missing key shows up as a red test instead of as a word that quietly -stays Chinese. - -The generalisation is the part I keep: **a crash tells you where to look. A -silent stop tells you nothing, and looks like success.** If a feature can -fail without moving a single pixel, then "the page still looks right" is not -a check. -```` - ---- - -## 文章 11 / 11:逐页验证一份 19 页的 PDF 报告 -- **Slug**: `verifying-a-pdf-report-page-by-page` -- **英文标题**: Verifying a 19-Page PDF Report Page by Page -- **分类**: `engineering` | **发布日期**: 2026-09-28 -- **线上地址**: https://blog.hoelee.com/posts/verifying-a-pdf-report-page-by-page/ (EN) | https://blog.hoelee.com/posts/zh/verifying-a-pdf-report-page-by-page/ (ZH) -- **本篇审核状态**: ⏳ 待审核 (Pending) - -### ✍️ 顾问审阅意见区 (Review Feedback) -```text -【审阅结论】:[ ] 通过 [ ] 需微调 [ ] 需重构 -【事实与数字核对】: -【人设与用词卫生】: -【CRO与转化建议】: -``` - -### 🇨🇳 中文版原文 (Chinese Markdown Twin) -````markdown ---- -title: "逐页验证一份 19 页的 PDF 报告" -description: "如何逐页验证生成的 PDF 报告:用浏览器打印同一份 HTML 作基线,逐页比对几何尺寸,把每一处偏差都压到 2pt 以内。" -pubDate: 2026-09-28 -updatedDate: 2026-09-29 -category: engineering -blueprint: sme-digital-suite -blueprintLayer: L4-managed-ops-handover -tags: [php, codeigniter, pdf, css, print, testing] -ogImage: /og/zh-verifying-a-pdf-report-page-by-page.jpg -banner: /banners/verifying-a-pdf-report-page-by-page.jpg -draft: false ---- - -你怎么知道一份生成出来的 PDF 每一页都真的正确——不只是第一页? -我维护着一个 CodeIgniter 4 应用:输入一个人的出生信息,生成一份 -中文命理/生命密码报告——十九张密排的 A4 sheet,封面、数字图表、 -方向九宫格、「一到九」的个人特征页。以前这份报告按网站原本的设计 -交付:操作员在浏览器里按 Ctrl+P,手工另存成 PDF。我把它换成了 -服务端渲染(mPDF),一夜之间,产品的质量取决于一个我看不见 -如何排版的引擎。 - -这就是这个问题可被搜索的版本:如何把一份多页 PDF 报告逐页地、 -用数字而不是肉眼,去和浏览器自己的打印输出对版?这个过程抓到 -了真实的 bug——包括一行被渲染成 2.5pt、从第二页起几乎看不见的 -页眉——最后全部十九页与浏览器基线的偏差都压进了 2pt。 - -## 为什么「看起来没问题」不算测试 - -没有人能用肉眼验证一份 19 页的报告。过去的流程是:打开 PDF, -扫一眼封面,交付。第 17 页标题漂移、页脚插图压住版权行、页眉 -小到读不出来——快速翻一遍永远发现不了,而花钱买报告的顾客 -看到的是全尺寸。 - -天真的做法会失败,是结构性的原因。服务端 PDF 渲染器不会像 -浏览器那样排你的 HTML:分页、页边距、基线、字距全都会漂移—— -而且不存在一个「看起来没问题」的测试,能让你在下周有人改了 -CSS 之后再跑一次。我第一次单趟渲染出来是 27 页,而设计预期 -是 19 页:mPDF 没有 CSS 裁剪,而 sheet 靠 `overflow: hidden` -藏住溢出。报告的 `@page` 规则更糟:mPDF 为这条规则本身 -翻了一页,19 张 sheet 炸成 12,789 页。页数都不稳定,所以 -「扫一眼第一页」不是验证——是碰运气。 - -## 基线:让浏览器去打印你的 HTML - -操作员的 Ctrl+P,就是 Chrome 用打印 CSS 打印报告自己的 HTML。 -所以参照标准不是「我觉得它应该长什么样」,而是浏览器自己的 -打印输出——在同一台机器、同一套网页字体下生成。做法:把报告 -目录用本地静态服务起起来(字体必须同源,否则 webfont 拒绝 -加载),再用 headless Chrome 打印。报告 CSS 声明了 -`@page { margin: 0 }`,所以浏览器输出是无边距满幅,再配合 -`-webkit-print-color-adjust: exact` 保住背景图——等价于操作员 -勾选「背景图形」: - -```bash -python -m http.server 8123 --bind 127.0.0.1 --directory - -"C:\Program Files\Google\Chrome\Application\chrome.exe" --headless=new --disable-gpu \ - --no-pdf-header-footer --user-data-dir=%TEMP%\chromeprofile --virtual-time-budget=30000 \ - --print-to-pdf=chrome-win.pdf "http://127.0.0.1:8123/report-local.html" -``` - -然后在 VM 上,用同一份 HTML 出服务端版本: - -```bash -php tools/pdf-render.php /tmp/report-v10.html /tmp/mpdf.pdf -``` - -## 逐页比对,而不是整体对比 - -以浏览器的 PDF 为基准,我在 Windows 这边用 -`uv run --with pymupdf` 逐页对比两份文档:页面尺寸、文字条数、 -图片包围盒(x0/y0/宽/高)、附图说明文字的 y 坐标。判定阈值: -**偏差 ≤2pt(0.7mm)算对齐**;超过 5pt 就要查根因。而且只比 -「同一元素在两份 PDF 里的差」——永远不要比绝对页数,因为页数 -一致是前提,不是测试本身。 - -## 逐页比对抓到了什么 - -下面每个 bug 都有可测量的前后数字,而且都修在库或模板里—— -不是用管道糊过去。 - -**看不见的页眉行。** 从第二页起每页顶部有一行小字,用户直接 -反馈说小到读不出来。页眉是一个 `font-size: 10px` 的 div, -里面套一张 auto 宽的 table,第一格写着 `width: 100%`。mPDF -把这解读成「表格超宽」,于是连同字号一起把整行缩到三分之一: -**2.5pt,而 Chrome 是 7.5pt**。修法(`fixPageHeaderTables()`): -给表格显式宽度 + 显式字号(px→pt),并去掉第一格的 -`width: 100%`: - -```php -$pt = round((float) $m[2] * 0.75, 2); // 10px = 7.5pt -``` - -**匹配过宽的外边距规则。** `.sheet { margin: 5mm auto }` 是为 -屏幕预览准备的(sheet 之间的阴影缝隙)。mPDF 当真了,把 -296mm 的 sheet 推到 301mm——越过 297mm 的页面——于是 sheet -在页边被切开,auto-fit 把整页缩小 3%,带白边。最直观的修法、 -在样式表末尾追加一条 `.sheet { margin: 0; }`,完全没用:mPDF -对同名选择器的两条规则只认「先出现的赢」。所以库要原地改写 -这条规则(`stripSheetMargins()`),而匹配器必须小心什么才算 -「sheet 规则」。护栏是一个负向回顾断言: - -```php -'~(?` 标签 -居中,而 mPDF 8 的 `Center` 标签处理器是空类——标签整个被 -丢弃,所有居中的标题和表格全部左对齐(「前言」实测 x=30, -Chrome 是 x=280)。`expandCenterTags()` 把 `
` 改写成 -`
`,并给居中块里的表格补上 -`align="center"`——因为父级的 `text-align` 传不到表格。 -修复后:x=281,Chrome 280。 - -**行距比浏览器高 15%。** 模板的 normalize.css 声明了 -`html { line-height: 1.15 }`;mPDF 不继承它,退回自己的字体 -度量(1.33)。这累积成每页下半部 20–40pt 的漂移——sheet 3 -甚至溢出到第二页,触发整页缩小。把 `useFixedNormalLineHeight` -设成模板自己的值之后,正文行距 15.5pt,Chrome 是 15.7。 -表格还要显式加 `td, th { padding: 1px }`——mPDF 默认的 -单元格内边距比浏览器大 2px。 - -**字体是错的。** mPDF 读不了网页用的 `.woff`,文字回退到 -自带的 Sun-ExtA;而正文栈里的「微软雅黑」在 Linux 服务器上 -根本不存在。我注册了三套真 TTF——标题手写体 MaShanZheng、 -拉丁与数字 Roboto、正文 CJK 用 wqy-microhei——并把模板的 -字体栈映射过去。一个坑:必须关掉 mPDF 的自动按脚本选字, -否则它挑「第一个支持中文的已注册字体」——整页正文都变成 -手写体。 - -**还有一个与 mPDF 无关的 bug。** 第 7 页的主插图在**两份** -PDF 里都是破图——比对显示 Chrome 和 mPDF 里是同一个破损 -占位块。模板硬编码了 `https://cdn.hoelee.com/...`,这个域名 -已经不再解析(NXDOMAIN),所以每个引擎都抓不到图。把模板 -改回应用自己的 base URL,并让 `localiseAssets()` 把任何 -host 的 `/static/` 路径都映射到本地文件,两个引擎里的插图 -都恢复了。只有并排比对才能暴露这一类 bug——单独看哪个引擎 -都「正常」。 - -## 一张 sheet,一页 - -渲染器这么设计是有意的:库把 HTML 按 `
` -切开,每张 sheet 单独渲染成一份单页文档,合并时只取第 1 页—— -物理上保证「一张 sheet = 正好一页 A4」,永远不会跨页断裂。 -mPDF 量中文宽度和 Chrome 略有不同,个别 sheet 会高出几毫米。 -与其丢内容,库按一把缩放梯子——1.0, 1.005, 1.01, 1.02, 1.03, -1.06, 1.10, 1.15, 1.22——取第一个能落进一页的比例,缩小整张 -sheet 而不是裁内容。隐藏溢出是浏览器打印做的事 -(`overflow: hidden`);一份收费产品如果 PDF 里静默丢了页内 -内容,就是无声的交付事故,所以设计选择是绝不丢内容。sheet 3 -现在需要 x1.005——0.5%,肉眼不可见——以前是 x1.03。 - -**「19/7 页」是什么意思。** 报告模板永远按固定顺序渲染十九张 -sheet;「版本」是这些 sheet 上的一个过滤器,不是第二份模板。 -完整版是 **19 页**;RM49 的精华版是**这 19 张里的 7 张**, -页码重编,每张入选的 sheet 都登记了一个文字标记——模板被 -改动/重排导致取错页时会大声失败,而不是把错误的章节交给 -顾客。两个版本走同一条管线,也用同一种方式验收: -`tools/pdf-verify.php --expect=19` 和 -`--expect=7` 双双 PASS -——页数加逐页 ink 检查(ghostscript 50dpi)证明没有任何 -空白页。 - -## 为什么收据是独立文档 - -收据不是报告裁剪出来的。它是自己的一份单页 A4 文档:真 -16mm 页边距(报告刻意做满幅无边距)、三语、单趟渲染—— -因为里面没有 sheet。它在发「已收款」邮件时才懒生成:付款 -回调必须毫秒级应答,0.3–1 秒的 PDF 渲染不属于回调。它落进 -同一个交付存储,文件名带 `-receipt` 后缀,永远不会和报告 -文件撞名,而且幂等:重试、重寄、顾客自己来拿,拿到的都是 -同一份。做它的过程从另一个方向印证了同一个论点——连单页 -文档都和浏览器不一样:`` 上的 `display: block` -不生效,左右并排的两张表把右列的数值裁出页面右边界, -合计行必须写在明细表内部,否则标签会浮在半空。 - -## 我会怎么做不一样 - -对版方法现在躺在项目笔记里,是一份文档化的流程,不是仓库 -里的脚本——这就是差距。仓库里自动化的验收工具只证明页数和 -逐页 ink,永远抓不到 2.5pt 的页眉或 15% 的行距漂移。我会把 -浏览器基线比对做成仓库验证工具链里的一个脚本:用同一份 -HTML 分别喂 Chrome 和库,diff 几何,任何超过 5pt 的偏差 -直接失败。这样,一次让打印布局悄悄回退的 CSS 改动会在构建 -时炸掉,而不是送到顾客手里。 - -我还会在写任何 mPDF 补偿代码之前就先出 Chrome 基线。 -「用操作员用的同一个引擎打印,然后测量」才是解锁点;之后 -每个修复都是机械活。还有两件诚实的遗留工作:伴侣合盘与 -家庭套餐还没跑过这套逐页对版,19 页的 PDF(背景图加嵌入 -字体约 20 MB)也还需要在交付前压缩。 - -## 结果 - -修复后的完整版验收: - -```text -$ php tools/pdf-verify.php /tmp/report-v10.html --expect=19 -out : 20,225,818 bytes, 19 pages, 10.4s, peak 188 MB -per-page ink check: all pages have content | report pages=19 -expected 19 pages => MATCH -RESULT: PASS -``` - -- **19 页 vs Chrome 基线的 19 页 — MATCH**,一张 sheet 一页, - 无跨页断裂。 -- 每一项实测偏差都**在 2pt(0.7mm)以内**:第 6 页偏了 - 213.5pt 的页脚插图、从 2.5pt 恢复到浏览器同款 7.5pt 的 - 页眉、归位的居中标题、15.5pt vs Chrome 15.7 的正文行距、 - 与网页字体一致的嵌入字体。 -- ink 检查确认**没有任何空白页**,PDF 文字可提取——封面能 - 读出真实文字,这对一份顾客要复制内容的报告很重要。 -- 精华版:**7 页 PASS**,4.99 MB,2.8 秒。 - -这就是「第一页看起来没问题」和「全部十九页都在浏览器两个点 -以内」的区别。前者是肉眼扫一遍就交付的结果;后者是拿浏览器 -自己当测试得到的结果。 - ---- - -我平时就做这类 Web 应用与打印/PDF 报告管线,也做网站设计与 -开发。如果你有一份服务器渲染的文档——报告、收据、发票—— -想在它送到顾客手里之前确认每一页都正确,跟我说说: -[WhatsApp](https://wa.me/60127972969) · [me@hoelee.com](mailto:me@hoelee.com?subject=PDF%20report%20pipeline) · -[hoelee.com](https://hoelee.com)。 -```` - -### 🇬🇧 英文版原文 (English Markdown Primary) -````markdown ---- -title: "Verifying a 19-Page PDF Report Page by Page" -description: "Verify a PDF report page by page: print the same HTML from your browser as a baseline, compare the per-page geometry, and keep every deviation under 2pt." -pubDate: 2026-09-28 -updatedDate: 2026-09-29 -category: engineering -blueprint: sme-digital-suite -blueprintLayer: L4-managed-ops-handover -tags: [php, codeigniter, pdf, css, print, testing] -ogImage: /og/verifying-a-pdf-report-page-by-page.jpg -banner: /banners/verifying-a-pdf-report-page-by-page.jpg -draft: false ---- - -How do you know a generated PDF actually looks right on every page — not just -page one? I maintain a CodeIgniter 4 app that turns birth details into a -Chinese numerology report. Until recently the operator printed it with Ctrl+P -and saved a PDF by hand. I replaced it with a server-side renderer (mPDF), and -overnight the product's quality depended on a layout engine I could not see. - -This post is the searchable version of that problem: verifying a multi-page -PDF report page by page against the browser's own print output, with numbers -instead of eyeballs. It caught real bugs — a header line rendered at 2.5pt, -effectively invisible on every page after the first — and ended with all -nineteen pages within 2pt of the browser. - -## Why "looks fine" is not a test - -Nobody can verify a 19-page report by eye. The old ritual was: open the PDF, -skim the cover, ship it. A drifting heading on page 17, a footer illustration -over the copyright line, an unreadable header — a quick flick never catches -those, and the customer who paid sees them at full size. - -Naive approaches fail structurally. A server-side PDF renderer does not lay -out HTML the way a browser does, so page breaks, margins, baselines and -spacing all drift — and there is no "looks fine" test you can re-run after -someone edits the CSS. My first single-pass render came out as 27 pages where -the design expects 19 — mPDF has no CSS clipping and the sheets hide overflow -with `overflow: hidden`. The report's own `@page` rule was worse: mPDF emitted -a page break for the rule itself, and 19 sheets exploded into 12,789 pages. -Page counts were not even stable, so eyeballing page one was not verification; -it was hope. - -## The baseline: make the browser print your HTML - -The operator's Ctrl+P is Chrome printing the report's own HTML with its print -CSS — same machine, same web fonts. So the reference is not "what I think it -should look like"; it is the browser's own print output. I served the report -directory locally (fonts must be same-origin or webfonts refuse to load) and -printed with headless Chrome. The report CSS declares `@page { margin: 0 }`, -so the output is borderless full-bleed, and `-webkit-print-color-adjust: -exact` keeps the background graphics the operator ticks: - -```bash -python -m http.server 8123 --bind 127.0.0.1 --directory - -"C:\Program Files\Google\Chrome\Application\chrome.exe" --headless=new --disable-gpu \ - --no-pdf-header-footer --user-data-dir=%TEMP%\chromeprofile --virtual-time-budget=30000 \ - --print-to-pdf=chrome-win.pdf "http://127.0.0.1:8123/report-local.html" -``` - -Then the server-side output, from the same HTML, on the VM: - -```bash -php tools/pdf-render.php /tmp/report-v10.html /tmp/mpdf.pdf -``` - -## Compare page by page, not overall - -I compared the two PDFs page by page with `uv run --with pymupdf`: page size, -text-block count, image bounding boxes (x0/y0/width/height), and caption text -y. Threshold: **within 2pt (0.7mm) counts as aligned**; over 5pt gets a root -cause. Compare the same element across the two PDFs — never absolute page -counts; page parity is the prerequisite, not the test. - -## What the comparison caught - -Each bug below had a measurable before/after and a fix in the library or -template. - -**The invisible header line.** A user reported the small header line, present -on every page after the cover, was unreadable. It is a `font-size: 10px` div -wrapping an auto-width table whose first cell declares `width: 100%` — mPDF -read that as "table too wide" and scaled the whole line, font included, to a -third of its size: **2.5pt vs Chrome's 7.5pt**. `fixPageHeaderTables()` gives -the table an explicit width and font size in points (px → pt) and drops the -offending cell: - -```php -$pt = round((float) $m[2] * 0.75, 2); // 10px = 7.5pt -``` - -**The margin rule that matched too much.** `.sheet { margin: 5mm auto }` -spaces the sheets on screen. mPDF took it literally and pushed the 296mm sheet -to 301mm — past the 297mm page — so the sheet was cut at the page edge and -auto-fit shrank the whole page by 3%, white border included. Appending `.sheet -{ margin: 0; }` does nothing — mPDF honours the *first* rule for a duplicated -selector. So the library rewrites the rule in place (`stripSheetMargins()`), -and the matcher must not over-match — the guard is a negative lookbehind: - -```php -'~(?` tag; mPDF 8's `Center` handler is an empty class, so the tag is -dropped and every centred heading and table came out left-aligned (the preface -heading measured x=30 against Chrome's x=280). `expandCenterTags()` rewrites -`
` to `
` and adds `align="center"` to -tables inside centred blocks, because parent `text-align` does not reach -tables. After the fix: x=281, Chrome 280. - -**Line spacing 15% taller than the browser's.** The template's normalize.css -declares `html { line-height: 1.15 }`; mPDF does not inherit it and fell back -to its own font metrics (1.33) — 20–40pt of drift accumulated on the lower -half of every page, and sheet 3 overflowed onto a second page, triggering a -whole-page shrink. Setting `useFixedNormalLineHeight` to the template's own -value brought body leading to 15.5pt against Chrome's 15.7. Tables needed `td, -th { padding: 1px }` — mPDF's default cell padding is 2px larger than a -browser's. - -**The fonts were wrong.** mPDF cannot read the `.woff` files the web views -use, so text fell back to its built-in Sun-ExtA, and "Microsoft YaHei" does -not exist on the Linux server. I registered the real TTFs — MaShanZheng for -headings, Roboto for Latin, wqy-microhei for CJK — and mapped the template's -stacks onto them. One trap: mPDF's automatic script-to-font selection must be -off, or it picks the first registered font that supports Chinese — the entire -body came out in handwriting. - -**And one bug that had nothing to do with mPDF.** Page 7's main illustration -was broken in *both* PDFs — the same broken stub in Chrome and mPDF. The -template hardcoded `https://cdn.hoelee.com/...`, a domain that no longer -resolves (NXDOMAIN), so every engine fetched nothing. Fixing the template to -use the app's own base URL and mapping any host's `/static/` path to local -files restored it in both engines. Only a side-by-side comparison surfaces -this — each engine alone looks "fine". - -## One sheet, one page - -The library splits the HTML into its `
` blocks and -renders each sheet as its own one-page document, importing page 1 and merging -— a physical guarantee that one sheet is exactly one A4 page, never split -across pages. mPDF measures CJK text widths slightly differently from Chrome, -so some sheets come out a few millimetres too tall. Rather than lose content, -the library re-renders the sheet at the smallest scale factor from a ladder — -1.0, 1.005, 1.01, 1.02, 1.03, 1.06, 1.10, 1.15, 1.22 — that fits, shrinking -the whole sheet instead of clipping. The browser's print clips with `overflow: -hidden`; a PDF that silently dropped in-sheet content would be a delivery -accident, so the design never drops content. Sheet 3 needs x1.005 today (0.5%, -invisible) where it used to need x1.03. - -**What "19/7 pages" means.** The report template always renders nineteen -sheets in a fixed order; the "edition" is a filter over those sheets, not a -second template. The full report is **19 pages**; the RM49 essence edition is -**7 of those 19 sheets**, renumbered, each selected sheet carrying a marker so -a rearranged template fails loudly instead of shipping the wrong chapters. -Both editions run the same pipeline and verify the same way: -`tools/pdf-verify.php --expect=19` and `--expect=7` both PASS — page count -plus a per-page ink check (ghostscript at 50dpi) proving no blank pages. - -## Why the invoice is a separate document - -The receipt is not a cut-down report. It is its own one-page A4 document: real -16mm page margins (the report is deliberately full-bleed), three languages, -and a single-pass render because there are no sheets. It is generated lazily -at email time — the payment callback must answer in milliseconds, and a 0.3–1s -render does not belong in it. It lands in the same delivery store under a -`-receipt` filename, never colliding with the report file, and it is -idempotent: retries get the same file. Even one page differed from the -browser: `display: block` on `` was ignored, side-by-side tables -clipped the right column's values off the page edge, and the total row had to -live inside the items table or its label floated in mid-air. - -## What I'd do differently - -The method lives in the project notes as a documented ritual, not a committed -script — that is the gap. The repo's automated acceptance tool proves page -count and per-page ink, which would never catch a 2.5pt header or a 15% -leading drift. I would turn the browser-baseline comparison into a script in -the repo's verification tooling: render the same HTML in Chrome and in the -library, diff the geometry, fail on any deviation over 5pt. Then a CSS change -that silently regresses the print layout fails the build instead of reaching a -customer. - -I would also have generated the Chrome baseline before writing any mPDF -compensation code — "print with the same engine the operator uses, then -measure" was the unlock. Two honest items remain: the partner and family -reports have not had this page-by-page pass yet, and the 19-page PDF (20 MB -with backgrounds and embedded fonts) still needs compression before delivery. - -## The result - -Full report verification, after the fixes: - -```text -$ php tools/pdf-verify.php /tmp/report-v10.html --expect=19 -out : 20,225,818 bytes, 19 pages, 10.4s, peak 188 MB -per-page ink check: all pages have content | report pages=19 -expected 19 pages => MATCH -RESULT: PASS -``` - -- **19 pages vs the Chrome baseline's 19 — MATCH**, one A4 page per sheet, - no splits. -- Every measured deviation is **within 2pt (0.7mm)** of the browser's print - output: footer art 213.5pt off on page 6 aligned, header restored to the - browser's 7.5pt, centred headings back, leading 15.5pt vs 15.7, embedded - fonts matching the web fonts. -- The ink check confirms **no blank pages**, and the PDF text is extractable — - the cover reads back as real text, which matters for a report customers - copy from. -- Essence edition: **7 pages PASS**, 4.99 MB, 2.8 seconds. - -That is the difference between "the first page looks fine" and "all nineteen -pages within two points of the browser": the first ships when you eyeball a -PDF; the second is what you get when the browser itself is the test. - ---- - -I build web applications and print/PDF report pipelines like this one, and I -do website design and development. If you have a document your server renders -— a report, a receipt, an invoice — and you want to be sure it is right on -every page before it reaches a customer, tell me about it: -[WhatsApp](https://wa.me/60127972969) · -[me@hoelee.com](mailto:me@hoelee.com?subject=PDF%20report%20pipeline) · -[hoelee.com](https://hoelee.com). -```` - ---- - diff --git a/docs/consultant-review/batches/batch-02.md b/docs/consultant-review/batches/batch-02.md deleted file mode 100644 index 4f5466c..0000000 --- a/docs/consultant-review/batches/batch-02.md +++ /dev/null @@ -1,3818 +0,0 @@ -# 博客文章顾问审阅资料包 — Batch-02 - -> **批次编号**:`Batch-02` -> **包含文章数**:5 篇 -> **本批次总字符量**:166,484 字(严格限制 < 200,000 字) -> **模式**:BILINGUAL -> **生成时间**:2026-10-27 06:05:52 - -# 外部顾问审阅前置须知与工程背景规范 - -> **本文档目标**:本批次包含 `blog.hoelee.com` 的待审阅技术文章全文。请外部顾问在审阅正文与技术主张时,以此规范为最高评估准则。 - -## 1. 站点定位与双重业务目的 -- **受众 A(技术招聘官 / 资深技术主管)**:寻找具备 Senior 全栈 + DevOps + AI 智能体闭环能力的架构工程师。文章定位为**“不可伪造的工程实操交付证据(Proof of Expertise)”**,要求代码真实、日志可查、有架构权衡与技术深度。 -- **受众 B(中小企业主 SME / 商业客户)**:寻找能提供系统研发、私有化部署、24/7 AI 获客系统、高可用基础设施的技术顾问。文章需清晰阐述业务痛点、商业 ROI、上线效率与交付保障。 - -## 2. 核心人设铁律与工程硬约束(必须严格遵守) -1. **彻底杜绝业余爱好者/玩具口吻**: - - ❌ **绝对禁用词**:`homelab`, `home lab`, `家用`, `小主机`, `玩具`, `折腾`。 - - ✅ **标准替代词**:`the infrastructure I manage`(我管理的私有基础设施)、`self-hosted production node`(自托管生产节点)、`on-premise host`(私有化服务器)。 -2. **严禁捏造虚假指标与性能数字**: - - 所有 benchmark 数据必须有明确的测试基准与单设备限制。 - - 严格区分“耗时减少比例”与“吞吐加速倍数”(例如耗时从 352s 降至 218s 是耗时减少 38.0%,吞吐提升 1.61×,严禁偷换概念混淆)。 - - 时间戳精度与物理帧对齐:视频帧率上限(如 30 fps 单帧 33.3ms)不可妄称“微秒级精确”。 -3. **去模板化叙事与真实物理锚点**: - - 拒绝千篇一律的 AI 模板味。文章采用三大叙事架构:① 故障排查谜案(Symptom → False Lead → Kernel Evidence → Fix);② 商业交付复盘(Client Bottleneck → Trade-offs → State Machine → ROI);③ 架构演进对比(V1 Naive → Concurrency Crash → V2 Redesign)。 - - 每篇文章必须包含至少一个物理真实世界锚点(主机真实硬件规格、生产维护窗口、真实业务场景)。 -4. **代码与配置展示规范**: - - 超过 20 行的配置或日志采用 HTML `
` 原生折叠,`` 必须精准标注文档名与行数。 - -## 3. 顾问重点开刀维度 -- [ ] **事实与数字可核性**:技术判断与性能数据是否自洽?有无过度夸大? -- [ ] **人设与语调纯洁性**:有无遗漏的 hobbyist/homelab 口吻? -- [ ] **双轨转化引导有效性**:是否有清晰的业务价值提炼与行动召唤(CTA)? -- [ ] **代码与生产安全性**:有无未脱敏的凭据、绝对内部私密路径或不安全的权限配置? - - ---- - -## 本批次文章目录索引 - -1. [tutorials] **给没有时间戳的歌曲自动生成字幕** (`generating-subtitles-for-songs-without-timestamps`) — ~90,113 字符 -2. [tutorials] **购买主机前,如何核实一家服务商的真实情况** (`how-to-verify-a-hosting-provider-before-you-buy`) — ~10,918 字符 -3. [web3] **一个基于 Chainlink VRF v2.5 与 Automation 的自动化彩票合约** (`chainlink-vrf-v2-lottery-contract`) — ~25,959 字符 -4. [web3] **全链上 SVG NFT:把艺术作品放进合约里** (`fully-on-chain-svg-nfts`) — ~26,486 字符 -5. [web3] **为什么在 Windows 上克隆后,我的链上 NFT 图像变了** (`why-my-on-chain-nft-art-changed-on-windows`) — ~13,008 字符 - ---- - -## 文章 01 / 05:给没有时间戳的歌曲自动生成字幕 -- **Slug**: `generating-subtitles-for-songs-without-timestamps` -- **英文标题**: Generating Subtitles for Songs That Ship Without Timestamps -- **分类**: `tutorials` | **发布日期**: 2026-10-20 -- **线上地址**: https://blog.hoelee.com/posts/generating-subtitles-for-songs-without-timestamps/ (EN) | https://blog.hoelee.com/posts/zh/generating-subtitles-for-songs-without-timestamps/ (ZH) -- **本篇审核状态**: ⏳ 待审核 (Pending) - -### ✍️ 顾问审阅意见区 (Review Feedback) -```text -【审阅结论】:[ ] 通过 [ ] 需微调 [ ] 需重构 -【事实与数字核对】: -【人设与用词卫生】: -【CRO与转化建议】: -``` - -### 🇨🇳 中文版原文 (Chinese Markdown Twin) -````markdown ---- -title: "给没有时间戳的歌曲自动生成字幕" -description: "AI 音乐工具只给你音频 —— 没有逐行时间,没有卡拉 OK。这是我给 18 首歌生成 LRC 与 SRT 字幕的完整流程,为什么单纯转写不行,以及让歌词框滚到底的两个 bug。" -pubDate: 2026-10-20 -category: tutorials -blueprint: ai-agent-automation -blueprintLayer: L3-local-gpu-inference -stream: creative-lab -tags: ["subtitles", "lrc", "srt", "whisper", "forced-alignment", "ai-music", "python"] -ogImage: "/og/zh-generating-subtitles-for-songs-without-timestamps.jpg" -banner: "/banners/generating-subtitles-for-songs-without-timestamps.jpg" -dynamicCta: true -draft: false ---- -我试过的每一个 AI 音乐工具,交出来的东西形状都一样:一个音频文件。没有一个会告诉你**每一句是什么时候唱的**。只想听的话没问题,但只要你想把歌词放到屏幕上 —— 卡拉 OK 的那一行、视频字幕、播放器下面的滚动框 —— 就完全不够用。 - -时间轴才是全部难点。音频反而是简单的部分。 - -这是我最后跑通的一套流程,用在本地生成的 18 首英文歌上,外加它在浏览器里崩掉的两个地方。下面全部可复现:它唯一需要你提供的东西,是**你已经写好的歌词**。 - -## 你真正需要的两样东西 - -两种字幕格式,共用同一份数据结构: - -| 格式 | 用在哪 | 长什么样 | -|---|---|---| -| **LRC** | 音乐播放器、卡拉 OK 块、`