init: SRE 学习路径站点(阶段 0-3 详解)与项目资料

站点
- knowledge/sre-learning-path/:离线静态站,无外部依赖、无需构建
- 目录页 index.html 按 7 个阶段组织,阶段 0-3 共 15 个模块已上线详解
- 阶段 0 Linux/网络/编程 3 模块、阶段 1 Nginx/部署/容器/CI-CD 4 模块
- 阶段 2 指标/日志/链路/看板 4 模块、阶段 3 SLO/高可用/容量/混沌 4 模块
- 共 203 个页面(105 章 / 317 小节),每章含场景推演与可复制实操

结构
- 模块目录 modules/<dir>/index.html + NN-<slug>.html 章节页
- 共享资源 assets/doc.css、doc.js(目录滚动高亮、代码块增强、主题切换)
- 静态侧边导航由 tools/build-nav.js 生成,tools/check-pages.js 全站校验

内容生成器 .sre-s23/(站点外,供阶段 4-6 复用)
- SPEC.md 撰写规范、README.md 流程说明
- gen.js 由 content/*.js 生成页面骨架,保证各模块样式一致
- check-pre.js / verify-template.js / fix-esc.js / coverage.js 校验工具

其它
- project/:AI Agent 面试题库、场景题集
- 增加 .gitattributes 统一 LF 行尾,忽略沙箱诊断产物
This commit is contained in:
2026-10-08 16:48:05 +08:00
commit 1eea6f4687
234 changed files with 64653 additions and 0 deletions

55
.sre-s23/README.md Normal file
View File

@@ -0,0 +1,55 @@
# 阶段 2 / 3 内容生产脚手架
这个目录是**构建工具**,不是站点的一部分。站点(`knowledge/sre-learning-path/`)仍然是纯静态 HTML,
不依赖这里的任何文件即可打开。留着它是为了让阶段 4–6 的模块能用同一套模板快速产出。
## 内容清单
| 文件 | 作用 |
|---|---|
| `SPEC.md` | 内容编写规范:数据文件格式、可用 HTML 片段、写作要求、自查清单 |
| `gen.js` | 生成器:读 `content/*.js`,产出 `modules/<dir>/index.html` 与 `NN-*.html` |
| `content/*.js` | 8 个模块的内容源(阶段 2 的 4 个 + 阶段 3 的 4 个) |
| `fix-esc.js` | 查/修 JS 模板字面量导致的两类静默损坏(见下) |
| `check-pre.js` | 体检生成后的代码块:`data-lang="json"` 的块能否 `JSON.parse` |
| `verify-template.js` | 样式一致性:新页面是否只用阶段 0/1 已有的 class |
| `coverage.js` | 知识点覆盖:目录页要求的知识点是否都落到页面里 |
## 常用命令
```bash
node .sre-s23/gen.js # 生成全部模块
node .sre-s23/gen.js --only s2-01-metrics # 只生成一个
node .sre-s23/gen.js --check s2-01-metrics # 只校验内容源,不写盘
cd knowledge/sre-learning-path
node tools/build-nav.js # 重建侧栏目录树(生成后必须跑)
node tools/check-pages.js # 链接 / 锚点 / 结构 / 目录树一致性
node D:/code/materials/.sre-s23/check-pre.js
node D:/code/materials/.sre-s23/verify-template.js
node D:/code/materials/.sre-s23/coverage.js
```
## 注意:模板字面量的三个陷阱
`content/*.js` 的正文写在 `html: \`...\`` 里,JS 会先解释一遍,三类内容会被静默吃掉
(HTML 校验查不出来,必须靠 `fix-esc.js`):
| 源码 | 会被解释成 | 正确写法 |
|---|---|---|
| `\"` | `"`(反斜杠丢失) | `\\"` |
| 行尾 `\` | 吞掉换行,命令粘成一行 | 行尾 `\\` |
| `${x}` | 当 JS 表达式求值(报 `x is not defined`) | `\${x}` |
`fix-esc.js <dir>` 报告前两类,`--write` 可自动修复;第三类会直接让 `gen.js` 加载失败,容易发现。
## 新增一个模块的流程
1. 按 `SPEC.md` 写 `content/<dir>.js`
2. `node .sre-s23/gen.js --check <dir>` 直到 `OK 校验通过`
3. `node .sre-s23/gen.js --only <dir>`
4. `cd knowledge/sre-learning-path && node tools/build-nav.js && node tools/check-pages.js`
5. 在站点 `index.html` 的 `PAGES` 表里登记路由;`gen.js` 顶部的 `CHAIN` 决定「上一/下一模块」
新增章节或调整顺序后,只要重跑第 3–4 步。

204
.sre-s23/SPEC.md Normal file
View File

@@ -0,0 +1,204 @@
# 阶段 2 / 3 内容编写规范(SPEC)
你只负责**写内容数据文件**,不要碰站点的 HTML、`index.html`、`assets/`、`tools/`。
页面 HTML(页头、面包屑、侧栏容器、章节定位条、上一/下一章)由生成器统一产出,
所以**格式正确性由生成器 + `tools/check-pages.js` 双重把关**,你的任务是把技术内容写扎实。
---
## 1. 交付物
一个 CommonJS 文件:`D:\code\materials\.sre-s23\content\<dir>.js`
```js
module.exports = {
dir: "s2-01-metrics", // 必须与文件名一致,格式 sN-NN-slug
title: "指标与 Prometheus", // 模块标题
sub: "阶段 2 · 可观测性三支柱 · 时序模型、PromQL、告警设计", // 模块目录页副标题
stage: { num: 2, title: "看得见" }, // 所属阶段
no: 1, // 本模块在阶段内的序号
total: 4, // 本阶段模块总数
// 模块目录页的导语,HTML 片段。必须包含「模块定位 / 学完之后你应该能 / 前置 / 建议投入」四段
lead: `
<b>模块定位:</b>……
<br><br>
<b>学完之后你应该能:</b>……
<br><br>
<b>前置:</b>阶段 1 的 <a href="../s1-01-nginx/index.html">Nginx 与流量入口</a>……
<br><br>
<b>建议投入:</b>16–20 小时,其中至少 6 小时要在真实环境里动手。
`,
chapters: [
{
file: "01-why", // 生成 01-why.html,序号必须从 01 连续递增
id: "why", // 该章 <h2 id="why">
title: "为什么指标是可观测性的第一支柱", // 章节标题(不要自己加序号)
html: `
<p>……</p>
<h3 id="sec-1-1">1.1 指标能回答而日志回答不了的问题</h3>
<p>……</p>
<pre data-lang="promql" data-name="查询:接口错误率">sum(rate(http_requests_total{job="api",status=~"5.."}[5m]))
/
sum(rate(http_requests_total{job="api"}[5m]))</pre>
`
}
// …… 更多章
]
};
```
### 校验命令
```
node D:\code\materials\.sre-s23\gen.js --check <dir>
```
必须先跑通(输出 `OK 校验通过`)再结束。生成器会检查:
- `file` 序号连续、`id` 唯一且为小写连字符
- 每章正文 ≥ 600 字,全模块 ≥ 11000 字(**实际要求 ≥ 15000 字**)
- 每个 `<pre>` 有 `data-lang`,且块内 `<` 已转义
- `div/section/details/table/ul/ol/li/p/span` 开合配对
- 所有 `<h3>` 都带 `id`
- 中文正文里不出现 ASCII 单引号 `'`(引号一律用 `「」`)
- 最后一章文件名/标题含「自测」或 `checklist`
---
## 2. 可用的 HTML 片段(只有这些样式,别自创)
### 提示框(七种,按语义选)
```html
<div class="box note"><span class="bt">标题</span><p>正文</p></div>
<div class="box tip"><span class="bt">…</span><p>…</p></div>
<div class="box warn"><span class="bt">…</span><p>…</p></div>
<div class="box danger"><span class="bt">…</span><p>…</p></div>
<div class="box ok"><span class="bt">…</span><p>…</p></div>
<div class="box case"><span class="bt">…</span><p>…</p></div>
<div class="box lab"><span class="bt">…</span><p>…</p></div>
```
语义:`note` 概念澄清 · `tip` 经验/技巧 · `warn` 风险 · `danger` 会导致故障 ·
`ok` 结论/验收 · `case` **真实故障案例**(课后最有价值的部分,每章尽量有)·
`lab` **动手实操**(命令 + 预期输出)。
正文里可继续用 `<p>` `<ul>/<ol>` `<li>` `<b>` `<code>` `<a>`,提示框内也可以。
### 代码块
```html
<pre data-lang="bash" data-name="查看标签基数最高的指标">curl -s localhost:9090/api/v1/label/__name__/values | jq -r '.data[]' | head</pre>
```
- `data-lang`:`bash` `yaml` `json` `promql` `logql` `nginx` `dockerfile` `ini` `toml` `text` `sql` `go` `python` `javascript` 等,写成语言名即可
- `data-name`:文件名或一句说明,可选但**建议每块都写**
- **块内 `<` `>` `&` 必须写成 `&lt;` `&gt;` `&amp;`**,否则生成器报错
### 表格
```html
<div class="tablewrap">
<table>
<thead><tr><th>参数</th><th>默认</th><th>含义</th><th>踩坑后果</th></tr></thead>
<tbody>
<tr><td><code>scrape_interval</code></td><td>1m</td><td>抓取间隔</td><td>太短→目标压力大;太长→告警迟钝</td></tr>
</tbody>
</table>
</div>
```
### 步骤
```html
<ol class="steps">
<li><b>先定位</b>:<code>docker stats</code> 看内存是否贴着 limit。</li>
<li><b>再验证</b>:……</li>
</ol>
```
### 卡片(用于并列对比,2–4 张)
```html
<div class="cards">
<div class="card"><h4>方案 A</h4><ul><li><b>优点</b>:…</li><li><b>代价</b>:…</li></ul></div>
<div class="card"><h4>方案 B</h4><ul><li><b>优点</b>:…</li><li><b>代价</b>:…</li></ul></div>
</div>
```
### 自测题(只在最后一章用)
```html
<details>
<summary><b>Q1:为什么 histogram 不能做算术平均?</b></summary>
<p>因为桶计数只保留了分布信息……</p>
</details>
```
---
## 3. 写作要求(这是重点,格式只是及格线)
**定位**:面向「已经会 Linux、Nginx、Docker、CI/CD,正在往成熟 SRE 走」的读者。
不要解释什么是 Linux、什么是 HTTP。默认读者懂基础命令行。
**每章必须包含**:
1. **开场 2–4 句点出问题的本质**:不是「本章介绍 X」,而是「X 出错时你会看到什么现象、为什么值得花时间」。
2. **核心知识**:参数/概念/公式讲清楚,配表格或多方案对比。
3. **至少一个生产场景**:用 `box case` 写一次真实故障或线上判断过程,要具体——具体指标名、具体数值、具体报错、具体结论。不要写「某公司曾发生」这种空话。
4. **至少一个动手实操**:用 `box lab`,给**能直接粘进终端跑**的命令与预期输出。写清前置条件(需要装什么)。
5. **坑与反模式**:`box warn` / `box danger`,说清「错在哪、为什么会错、怎么发现」。
**硬性要求**:
- 严禁空话套话。不写「总而言之」「随着业务发展」「本文档将介绍」「需要注意的是」这类填充。
- 不写「某公司」「某大型互联网企业」;用「我们的订单服务」「一个 8 核 16G 的实例」这类具体设定。
- 数字要给具体值:`p99 从 120ms 涨到 2.3s`,不要写「明显变慢」。
- 命令要真实:`rate(http_requests_total[5m])`、`kubectl top pod`、`logcli query '{app="api"} |= "timeout"'`。
- 阈值要给出可用的经验值并说明依据。
- 每章 900–2000 字(含代码块),小节(h3)2–4 个为宜。
- 术语首次出现给英文原文,例如「基数(cardinality)」。
- 中文引号一律 `「」`;英文/代码里正常用引号。
**跨页面链接**(可选,但有则更好):
- 同模块其它章:`<a href="05-promql.html">第 5 章</a>`,锚点:`<a href="05-promql.html#sec-5-2">…</a>`
- 其它模块:`<a href="../s1-01-nginx/index.html">Nginx 与流量入口</a>`
- 返回目录页:`<a href="index.html">本模块目录</a>`
只能链接**确实存在**的目标。已存在的模块目录:
`s0-01-linux` `s0-02-network` `s0-03-programming` `s1-01-nginx` `s1-02-deploy`
`s1-03-container` `s1-04-cicd`,以及本次同时生成的 8 个:
`s2-01-metrics` `s2-02-logs` `s2-03-trace` `s2-04-dashboard`
`s3-01-slo` `s3-02-ha` `s3-03-capacity` `s3-04-chaos`。
**不要**链接阶段 4+ 的目录页(尚不存在,会变死链)。
---
## 4. 章节收尾约定
- 除最后一章外,每章结尾不要再写「下一章我们将……」这类过渡句,生成器会自动渲染「上一章 / 下一章」卡片。
- **最后一章**固定收尾,结构为:
1. `<div class="box ok">` 验收清单(8–10 条,可勾选式陈述)
2. `<h3 id="sec-x1">自测题</h3>` + 6–8 个 `<details>` 问答,问题要考「判断力」而不是「记忆」,答案要给出推理过程
3. 可选:`<h3 id="sec-x2">下一步</h3>` 指路到后续模块
- 倒数第二章固定为「速查表与高频坑」:一张速查表 + 8–12 个高频坑(每个坑写清现象、原因、处理)。
---
## 5. 自查清单(提交前逐条确认)
- [ ] `node .sre-s23\gen.js --check <dir>` 输出 `OK 校验通过`
- [ ] 每一章都有 `box case`(真实场景)和 `box lab`(动手实操)
- [ ] 全模块正文 ≥ 15000 字
- [ ] 覆盖了任务里列出的**每一个知识点**,一个不漏
- [ ] 代码块内 `<` 已转义为 `&lt;`
- [ ] 中文正文无 ASCII 单引号
- [ ] 最后一章是「完成标准与自测」,含 `box ok` + 6–8 个 `<details>`
- [ ] 倒数第二章是「速查表与高频坑」
- [ ] 只创建了 `content/<dir>.js` 这一个文件,没有改动站点里任何其它文件

75
.sre-s23/check-pre.js Normal file
View File

@@ -0,0 +1,75 @@
#!/usr/bin/env node
/* ==========================================================================
代码块内容体检(针对 JS 模板字面量导致的静默损坏)
生成器用 `html: \`...\`` 承载正文,这带来三类静默损坏,HTML 校验查不出来:
① `${...}` 被当成 JS 表达式求值(通常会直接报 xxx is not defined,但也有不报错的)
② `\"` 丢掉反斜杠 → 渲染后只剩 `"`,JSON / curl 片段坏掉
③ 行尾单个 `\` 吞掉换行 → 命令粘在一起
本脚本对生成后的真实页面做检查:
- data-lang="json" 的 <pre> 能否 JSON.parse
- 出现 `\{` `\}` `\"` 等可疑残留
- shell/json 块里 `${` 未转义残留在不该出现的地方(只报告,人工判断)
node .sre-s23/check-pre.js <模块目录名...>
========================================================================== */
const fs = require("fs");
const path = require("path");
const SITE = path.resolve(__dirname, "..", "knowledge", "sre-learning-path");
const MODDIR = path.join(SITE, "modules");
const unescape = s => s.replace(/&lt;/g, "<").replace(/&gt;/g, ">")
.replace(/&quot;/g, '"').replace(/&#39;/g, "'").replace(/&nbsp;/g, " ")
.replace(/&mdash;/g, "—").replace(/&amp;/g, "&");
const targets = process.argv.slice(2).length
? process.argv.slice(2)
: fs.readdirSync(MODDIR, { withFileTypes: true })
.filter(d => d.isDirectory()).map(d => d.name).filter(d => /^s[23]-/.test(d)).sort();
let problems = 0, blocks = 0;
const notes = [];
for (const d of targets) {
const dir = path.join(MODDIR, d);
if (!fs.existsSync(dir)) continue;
for (const f of fs.readdirSync(dir).filter(x => x.endsWith(".html")).sort()) {
const rel = `${d}/${f}`;
const html = fs.readFileSync(path.join(dir, f), "utf8");
const pres = [...html.matchAll(/<pre([^>]*)>([\s\S]*?)<\/pre>/g)];
pres.forEach((m, i) => {
blocks++;
const attrs = m[1];
const raw = m[2];
const lang = (attrs.match(/data-lang="([^"]*)"/) || [, ""])[1].toLowerCase();
const name = (attrs.match(/data-name="([^"]*)"/) || [, ""])[1];
const body = unescape(raw).replace(/^\n/, "").replace(/\n$/, "");
/* ① JSON 块必须可解析 */
if (lang === "json") {
try { JSON.parse(body); }
catch (e) {
problems++;
console.log(`✗ ${rel} 第 ${i + 1} 个 <pre>(json${name ? " · " + name : ""})无法解析:${e.message}`);
console.log(` 首行:${body.split("\n")[0].slice(0, 110)}`);
}
}
/* ② 可疑残留:\ 后面跟 { } " 这些不该被转义的字符 */
const sus = [...body.matchAll(/\\[{}"]/g)];
if (sus.length) {
notes.push(`${rel} 第 ${i + 1} 个 <pre>(${lang}${name ? " · " + name : ""})有 ${sus.length} 处 \\{ \\} \\" 残留`);
}
/* ③ 反斜杠 + 行尾:单个 \ 吞换行 */
if (/\\\n/.test(body)) notes.push(`${rel} 第 ${i + 1} 个 <pre> 行尾有单个反斜杠(会吞换行)`);
});
}
}
console.log(`\n共检查 ${blocks} 个代码块`);
if (notes.length) {
console.log(`\n需要人工确认的 ${notes.length} 条:`);
notes.forEach(n => console.log(" · " + n));
}
if (problems) { console.log(`\n${problems} 个 JSON 代码块无法解析`); process.exit(1); }
console.log("\nOK 所有 JSON 代码块均可解析");

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

1916
.sre-s23/content/s3-02-ha.js Normal file

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

43
.sre-s23/coverage.js Normal file
View File

@@ -0,0 +1,43 @@
/* 知识点覆盖核对:检查目录页里每个模块要求的知识点,是否真的出现在它自己的页面里。
用法:node .sre-s23/coverage.js
*/
const fs = require("fs");
const path = require("path");
const SITE = path.resolve(__dirname, "..", "knowledge", "sre-learning-path", "modules");
const SPEC = {
"s2-01-metrics": ["四大黄金信号", "USE", "RED", "基数", "cardinality", "counter", "gauge", "histogram", "summary",
"histogram_quantile", "rate", "increase", "by", "without", "offset", "topk", "exporter", "pull",
"relabel", "scrape_config", "服务发现", "保留", "for", "燃烧率", "告警分级", "路由", "反模式"],
"s2-02-logs": ["trace_id", "user_id", "latency", "level", "service", "Fluent Bit", "Filebeat", "Kafka",
"Elasticsearch", "Loki", "Lucene", "LogQL", "count_over_time", "line_format", "脱敏", "采样",
"保留", "热温冷", "慢查询", "指标异常"],
"s2-03-trace": ["traceparent", "Span", "Trace", "父子", "上下文传播", "OpenTelemetry", "SDK", "语义约定",
"自动埋点", "手动埋点", "Collector", "receiver", "processor", "exporter", "头部采样", "尾部采样",
"tail_sampling", "exemplar", "Jaeger", "Tempo", "价值边界"],
"s2-04-dashboard": ["变量", "label_values", "custom", "repeat", "面板", "Stat", "Gauge", "热力图", "状态时间线",
"阈值", "注释", "annotation", "分层", "值班速查", "仪表盘森林", "下钻", "data link", "__url_time_range"],
"s3-01-slo": ["SLI", "SLO", "错误预算", "燃烧率", "14.4", "好事件", "总事件", "28 天", "histogram_quantile",
"recording rule", "alerting rule", "runbook_url", "for", "severity", "预算政策", "冻结", "门禁", "反模式"],
"s3-02-ha": ["SPOF", "单点", "无状态", "会话", "幂等", "超时", "重试", "退避", "jitter", "熔断", "限流",
"降级", "舱壁", "级联", "重试风暴", "惊群", "连接池", "主从", "多副本", "分片", "CAP", "RPO", "RTO",
"备份", "异地多活", "单元化", "误操作", "双人复核", "故障树"],
"s3-03-capacity": ["利特尔", "水位", "QPS", "wrk", "k6", "Locust", "阶梯", "拐点", "瓶颈", "连接池", "慢 SQL",
"GC", "锁竞争", "带宽", "HPA", "stabilizationWindowSeconds", "冷启动", "缩容", "预测", "成本",
"冷热分层", "单位成本", "每千次"],
"s3-04-chaos": ["稳态", "假设", "爆炸半径", "staging", "一键停止", "杀进程", "网络延迟", "丢包", "依赖超时",
"磁盘打满", "时钟偏移", "DNS", "Chaos Mesh", "Litmus", "netem", "stress-ng", "GameDay",
"演练日历", "实验报告", "改进项"]
};
let totalMissing = 0;
for (const [mod, terms] of Object.entries(SPEC)) {
const dir = path.join(SITE, mod);
const text = fs.readdirSync(dir).filter(f => f.endsWith(".html"))
.map(f => fs.readFileSync(path.join(dir, f), "utf8")).join("\n");
const missing = terms.filter(t => !text.includes(t));
totalMissing += missing.length;
console.log(`${missing.length ? "✗" : "✓"} ${mod}:${terms.length - missing.length}/${terms.length} 个关键词命中` +
(missing.length ? ` —— 缺失:${missing.join(", ")}` : ""));
}
console.log(totalMissing ? `\n共 ${totalMissing} 个关键词未命中(需人工判断是否为同义写法)` : "\nOK 全部知识点关键词均已覆盖");

54
.sre-s23/fix-esc.js Normal file
View File

@@ -0,0 +1,54 @@
/* 修复模板字面量导致的两类静默损坏(只作用于正文区,即第一个反引号之后):
① 单反斜杠 + 引号 `\"` → `\\"` (本该显示的 \" 被退化成 ")
② 行尾单反斜杠 `\` → `\\` (本该显示的 bash 续行符吞掉了换行,命令被粘成一行)
用法:
node .sre-s23/fix-esc.js <dir> 只报告(dry run)
node .sre-s23/fix-esc.js <dir> --write 实际写回
*/
const fs = require("fs");
const path = require("path");
const DIR = path.resolve(__dirname, "content");
const dir = process.argv[2];
const write = process.argv.includes("--write");
if (!dir) { console.error("用法:node .sre-s23/fix-esc.js <dir> [--write]"); process.exit(1); }
const p = path.join(DIR, dir + ".js");
const src = fs.readFileSync(p, "utf8");
const firstTick = src.indexOf("`");
if (firstTick < 0) { console.error("找不到模板字面量起点"); process.exit(1); }
const head = src.slice(0, firstTick);
const body = src.slice(firstTick);
const headBad = (head.match(/(?<!\\)\\"/g) || []).length;
if (headBad) console.error(`⚠ JS 字段区有 ${headBad} 处 \\",脚本不会碰,请人工确认`);
/* 统计与定位 */
let quoteHits = 0, contHits = 0;
const qLines = [], cLines = [];
body.split("\n").forEach((ln, i) => {
const q = (ln.match(/(?<!\\)\\"/g) || []).length;
if (q) { quoteHits += q; qLines.push(`${i + 1} ×${q} ${ln.trim().slice(0, 100)}`); }
// 行尾单个反斜杠(前面不是反斜杠)
if (/(?<!\\)\\$/.test(ln)) { contHits++; cLines.push(`${i + 1} ${ln.trim().slice(0, 100)}`); }
});
console.log(`${dir}:`);
console.log(` ① 单反斜杠 \\" ${quoteHits} 处`);
qLines.slice(0, 8).forEach(l => console.log(" L" + l));
if (qLines.length > 8) console.log(` … 另 ${qLines.length - 8} 行`);
console.log(` ② 行尾单反斜杠 \\ ${contHits} 处`);
cLines.slice(0, 8).forEach(l => console.log(" L" + l));
if (cLines.length > 8) console.log(` … 另 ${cLines.length - 8} 行`);
if (write && (quoteHits || contHits)) {
const fixed = head + body
.replace(/(?<!\\)\\"/g, '\\\\"')
.replace(/(?<!\\)\\$/gm, "\\\\");
fs.writeFileSync(p, fixed, "utf8");
const nb = fs.readFileSync(p, "utf8").slice(firstTick);
console.log(`\n已写回;复查:单反斜杠 \\" = ${(nb.match(/(?<!\\)\\"/g) || []).length} 处,` +
`行尾单反斜杠 = ${(nb.split("\n").filter(l => /(?<!\\)\\$/.test(l))).length} 处`);
} else if (!write) {
console.log("\n(dry run,未写盘;加 --write 实际写入)");
}

372
.sre-s23/gen.js Normal file
View File

@@ -0,0 +1,372 @@
#!/usr/bin/env node
/* ==========================================================================
阶段 2 / 3 内容生成器(临时构建工具,全部生成完成并校验通过后可删除)
用法:
node .sre-s23/gen.js --all 生成 content/ 下全部模块
node .sre-s23/gen.js --only <dir> 只生成一个模块
node .sre-s23/gen.js --check <dir> 只校验不写文件
内容源:.sre-s23/content/<dir>.js
module.exports = {
dir, title, sub, no, total,
stage: { num: 2, title: "看得见" },
lead: `...HTML...`,
chapters: [ { file:"01-why", id:"why", title:"...", html:`...` } ]
}
生成物:
knowledge/sre-learning-path/modules/<dir>/index.html
knowledge/sre-learning-path/modules/<dir>/NN-<slug>.html
侧栏目录树留空,由 tools/build-nav.js 统一填充。
========================================================================== */
const fs = require("fs");
const path = require("path");
const SITE = path.resolve(__dirname, "..", "knowledge", "sre-learning-path");
const CONTENT = path.join(__dirname, "content");
/* 完整模块链条:用于生成「上一模块 / 下一模块」 */
const CHAIN = [
["s0-01-linux", "Linux 系统与命令行", "s0"],
["s0-02-network", "计算机网络", "s0"],
["s0-03-programming", "编程与自动化基础", "s0"],
["s1-01-nginx", "Nginx 与流量入口", "s1"],
["s1-02-deploy", "应用部署与发布", "s1"],
["s1-03-container", "容器与镜像", "s1"],
["s1-04-cicd", "CI/CD 流水线", "s1"],
["s2-01-metrics", "指标与 Prometheus", "s2"],
["s2-02-logs", "日志采集与检索", "s2"],
["s2-03-trace", "链路追踪", "s2"],
["s2-04-dashboard", "看板与可视化", "s2"],
["s3-01-slo", "SLI / SLO / 错误预算", "s3"],
["s3-02-ha", "高可用与容灾", "s3"],
["s3-03-capacity", "容量规划与成本", "s3"],
["s3-04-chaos", "混沌工程与演练", "s3"]
];
const STAGE_TITLE = {
s0: "打地基", s1: "服务上线", s2: "看得见",
s3: "稳得住", s4: "上规模"
};
/* ---------------------------------------------------------------- 工具 */
const esc = s => String(s).replace(/&/g, "&amp;").replace(/</g, "&lt;")
.replace(/>/g, "&gt;").replace(/"/g, "&quot;");
const stripTags = s => s.replace(/<[^>]+>/g, "");
const decode = s => s.replace(/&lt;/g, "<").replace(/&gt;/g, ">")
.replace(/&quot;/g, '"').replace(/&#39;/g, "'").replace(/&nbsp;/g, " ")
.replace(/&mdash;/g, "—").replace(/&amp;/g, "&");
const plain = s => decode(stripTags(s)).replace(/\s+/g, " ").trim();
const stripNo = s => s.replace(/^\s*\d+(?:\.\d+)*\s*[\.、]?\s*/, "").trim();
const textLen = s => stripTags(s).replace(/\s+/g, "").length;
/* 统一缩进:去掉公共前导空白,再按 pad 重排 */
function reindent(html, pad) {
const lines = String(html).replace(/\r\n/g, "\n").replace(/^\n+|\n+$/g, "").split("\n");
const indents = lines.filter(l => l.trim()).map(l => (l.match(/^[ \t]*/) || [""])[0].length);
const min = indents.length ? Math.min(...indents) : 0;
return lines.map(l => (l.trim() ? pad + l.slice(min) : "")).join("\n");
}
/* ---------------------------------------------------------------- 校验 */
const LENIENT = process.argv.includes("--lenient"); // 冒烟测试用:跳过字数下限
const problems = [];
const fail = m => problems.push(m);
function validate(mod, srcName) {
const need = ["dir", "title", "sub", "no", "total", "stage", "lead", "chapters"];
for (const k of need) if (!mod[k]) fail(`${srcName}: 缺少字段 ${k}`);
if (!mod.stage || !mod.stage.num || !mod.stage.title) fail(`${srcName}: stage 需要 {num,title}`);
if (!/^s\d-\d\d-[a-z0-9-]+$/.test(mod.dir || "")) fail(`${srcName}: dir 命名应为 sN-NN-slug`);
if (!Array.isArray(mod.chapters) || !mod.chapters.length) { fail(`${srcName}: chapters 为空`); return; }
const files = new Set();
const ids = new Set();
let total = 0;
(mod.chapters || []).forEach((c, i) => {
const tag = `${srcName} 第 ${i + 1} 章`;
if (!/^\d\d-[a-z0-9-]+$/.test(c.file || "")) fail(`${tag}: file 应为 NN-slug(小写连字符)`);
if (c.file && parseInt(c.file.slice(0, 2), 10) !== i + 1) fail(`${tag}: file 序号应为 ${String(i + 1).padStart(2, "0")}`);
if (files.has(c.file)) fail(`${tag}: file 重复 ${c.file}`);
files.add(c.file);
if (!c.title || !c.title.trim()) fail(`${tag}: 缺少 title`);
if (!/^[a-z][a-z0-9-]*$/.test(c.id || "")) fail(`${tag}: id 应为小写连字符(用于 <h2 id>)`);
if (ids.has(c.id)) fail(`${tag}: id 重复 ${c.id}`);
ids.add(c.id);
if (!c.html || (!LENIENT && textLen(c.html) < 600)) fail(`${tag}: 正文过短(${textLen(c.html || "")} 字,至少 600)`);
total += textLen(c.html || "");
/* <pre> 必须有 data-lang,且内部 < 必须转义 */
const pres = (c.html || "").match(/<pre[\s\S]*?<\/pre>/g) || [];
pres.forEach((blk, k) => {
if (!/<pre[^>]*data-lang=/.test(blk)) fail(`${tag}: 第 ${k + 1} 个 <pre> 未标注 data-lang`);
const body = blk.replace(/^<pre[^>]*>/, "").replace(/<\/pre>$/, "");
if (/</.test(body)) fail(`${tag}: 第 ${k + 1} 个 <pre> 内有未转义的 <`);
});
/* 标签配对 */
for (const t of ["div", "section", "details", "table", "ul", "ol", "li", "p", "span"]) {
const o = ((c.html || "").match(new RegExp("<" + t + "(?=[\\s>])", "g")) || []).length;
const cl = ((c.html || "").match(new RegExp("</" + t + ">", "g")) || []).length;
if (o !== cl) fail(`${tag}: <${t}> 开合不匹配 ${o}/${cl}`);
}
/* h3 必须带 id */
const h3all = ((c.html || "").match(/<h3[ >]/g) || []).length;
const h3id = ((c.html || "").match(/<h3 id="/g) || []).length;
if (h3all !== h3id) fail(`${tag}: 有 h3 未补 id(${h3id}/${h3all})`);
/* 中文正文里不出现 ASCII 单引号 */
const prose = (c.html || "").replace(/<pre[\s\S]*?<\/pre>/g, "")
.replace(/<code>[\s\S]*?<\/code>/g, "").replace(/<[^>]+>/g, "");
if (/'/.test(prose)) fail(`${tag}: 中文正文里出现 ASCII 单引号,请改用「」`);
/* 危险:正文里出现裸 < 会被浏览器吞掉 */
const bare = (c.html || "").replace(/<pre[\s\S]*?<\/pre>/g, "")
.replace(/<[a-zA-Z\/!][^>]*>/g, "");
if (/</.test(bare)) fail(`${tag}: 正文里有未转义的 <`);
});
if (!LENIENT && total < 11000) fail(`${srcName}: 全模块正文合计 ${total} 字,偏少(建议 ≥ 14000)`);
mod._total = total;
/* 必须有收尾的自测章 */
const last = (mod.chapters || [])[mod.chapters.length - 1];
if (last && !/自测|checklist/.test(last.file + last.title)) {
fail(`${srcName}: 最后一章应是「完成标准与自测」(当前 ${last.file})`);
}
return problems.length === 0;
}
/* ---------------------------------------------------------------- 模板 */
function head(title, desc) {
return `<!DOCTYPE html>
<html lang="zh-CN" data-theme="light">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>${esc(title)}</title>
<meta name="description" content="${esc(desc)}">
<link rel="stylesheet" href="../../assets/doc.css">
</head>
<body>
<header class="topbar">
<div class="tb-in">
<a class="brand" href="../../index.html"><span class="logo">SRE</span><div>从零到成熟<small>模块详解</small></div></a>
<div class="crumbs">
<a href="../../index.html">学习路径</a><span class="sep">/</span>
<a href="../../index.html#${mod.stageAnchor}">阶段 ${mod.stage.num} · ${esc(mod.stage.title)}</a><span class="sep">/</span>
${mod.crumbTail}
</div>
<div class="spacer"></div>
<button class="btn" id="tocToggle">☰ 导航</button>
<button class="btn" id="themeBtn" title="切换到深色主题">深色</button>
</div>
</header>
<div class="layout" id="layout">
<aside class="sidebar">
<h2>章节目录</h2>
<nav id="chapters"></nav>
<div class="side-foot">
<a class="btn" href="index.html">← 模块目录</a>
<a class="btn" href="../../index.html">学习路径</a>
</div>
</aside>
<div class="mask" id="mask"></div>
<main class="main-col">
<article>
`;
}
let mod = null;
function pager(prevHref, prevK, prevV, nextHref, nextK, nextV) {
const a = prevHref
? `<a class="prev" href="${prevHref}"><span class="k">${prevK}</span><span class="v">${esc(prevV)}</span></a>`
: `<a class="prev disabled"><span class="k">${prevK}</span><span class="v">${esc(prevV)}</span></a>`;
const b = nextHref
? `<a class="next" href="${nextHref}"><span class="k">${nextK}</span><span class="v">${esc(nextV)}</span></a>`
: `<a class="next disabled"><span class="k">${nextK}</span><span class="v">${esc(nextV)}</span></a>`;
return a + "\n " + b;
}
/* ---------------------------------------------------------------- 生成 */
function generate(m) {
mod = m;
mod.stageAnchor = m.stage.anchor || ("s" + m.stage.num);
const outDir = path.join(SITE, "modules", m.dir);
fs.mkdirSync(outDir, { recursive: true });
const idx = CHAIN.findIndex(x => x[0] === m.dir);
const prevMod = idx > 0 ? CHAIN[idx - 1] : null;
const nextMod = idx >= 0 && idx < CHAIN.length - 1 ? CHAIN[idx + 1] : null;
const nextStage = m.stage.anchor === "s2" ? "s3" : "s4";
/* ---- 模块目录页 ---- */
const secTotal = m.chapters.reduce((n, c) =>
n + ((c.html.match(/<h3 id="/g) || []).length), 0);
const kilo = Math.round(m._total / 1000);
const chaplist = m.chapters.map((c, i) => {
const no = i + 1;
const secs = [...c.html.matchAll(/<h3 id="([^"]+)">([\s\S]*?)<\/h3>/g)]
.map(x => `<a href="${c.file}.html#${x[1]}">${esc(stripNo(plain(x[2])))}</a>`).join("");
return ` <li class="chap-item">
<div class="ci-head">
<span class="ci-no">${no}</span>
<a class="ci-title" href="${c.file}.html">${esc(c.title)}</a>
<a class="ci-go" href="${c.file}.html">进入 →</a>
</div>${secs ? `\n <div class="ci-secs">${secs}</div>` : ""}
</li>`;
}).join("\n");
mod.crumbTail = `<b>${esc(m.title)}</b>`;
mod.footTail = "模块目录";
const idxPrev = prevMod
? [`../${prevMod[0]}/index.html`, "← 上一模块", prevMod[1]]
: [null, "← 上一模块", "已经是第一个模块"];
const idxNext = nextMod
? [`../${nextMod[0]}/index.html`, "下一模块 →", nextMod[1]]
: [`../../index.html#${nextStage}`, "下一模块 →", `阶段 ${nextStage.slice(1)} · ${STAGE_TITLE[nextStage]}`];
const idxBody = head(`${m.title} · 阶段 ${m.stage.num} 模块 ${m.no} · SRE 从零到成熟`,
`${m.title} 模块目录:共 ${m.chapters.length} 章、${secTotal} 个小节。`) +
` <div class="modhero">
<span class="mh-no">阶段 ${m.stage.num} · 模块 ${m.no} / ${m.total}</span>
<h1>${esc(m.title)}</h1>
<p class="mh-sub">${esc(m.sub)}</p>
<div class="mh-meta">
<span>共 <b>${m.chapters.length}</b> 章</span>
<span><b>${secTotal}</b> 个小节</span>
<span>约 <b>${kilo}</b> 千字</span>
</div>
</div>
<p class="lead">
${reindent(m.lead, " ")}
</p>
<h2 id="chapters-list">章节目录</h2>
<ol class="chaplist">
${chaplist}
</ol>
<div class="box tip">
<span class="bt">怎么用这一模块</span>
<p>左侧是<b>章节目录树</b>:先看章标题快速定位,进入某一章后该章的小节会展开并跟随滚动高亮;点其它章标题可直接跳到对应页面。</p>
<p>每章结尾都有「上一章 / 下一章」可以连续阅读,代码块右上角可以一键复制。</p>
</div>
` +
`
</article>
<nav class="pager">
${pager(...idxPrev, ...idxNext)}
</nav>
<p class="foot">
${esc(m.title)} · 模块目录<br>
<a href="../../index.html">返回学习路径</a>
</p>
</main>
</div>
<button id="toTop" title="回到顶部">↑</button>
<script src="../../assets/doc.js"></script>
</body>
</html>
`;
fs.writeFileSync(path.join(outDir, "index.html"), idxBody, "utf8");
/* ---- 章节页 ---- */
m.chapters.forEach((c, i) => {
const no = i + 1;
const nc = m.chapters[i + 1];
const pc = m.chapters[i - 1];
mod.crumbTail = `<a href="index.html">${esc(m.title)}</a><span class="sep">/</span><b>第 ${no} 章</b>`;
mod.footTail = `第 ${no} 章 ${c.title}`;
const pv = pc
? [`${pc.file}.html`, "← 上一章", `第 ${no - 1} 章 · ${pc.title}`]
: ["index.html", "← 模块目录", m.title];
const nx = nc
? [`${nc.file}.html`, "下一章 →", `第 ${no + 1} 章 · ${nc.title}`]
: ["index.html", "回到 →", `${m.title} 章节目录`];
const html = head(`${c.title} · ${m.title} · SRE 从零到成熟`,
`${m.title} 第 ${no} 章:${c.title}。本章 ${(c.html.match(/<h3 id="/g) || []).length} 个小节。`) +
` <p class="chapnav">
<a href="index.html">${esc(m.title)}</a>
<span>·</span>
<span>第 <b class="pos">${no}</b> / ${m.chapters.length} 章</span>
</p>
<h2 id="${c.id}"><span class="n">${no}</span>${esc(c.title)}</h2>
${reindent(c.html, " ")}
` +
`
</article>
<nav class="pager">
${pager(...pv, ...nx)}
</nav>
<p class="foot">
${esc(m.title)} · 第 ${no} 章 ${esc(c.title)}<br>
<a href="index.html">模块目录</a> · <a href="../../index.html">返回学习路径</a>
</p>
</main>
</div>
<button id="toTop" title="回到顶部">↑</button>
<script src="../../assets/doc.js"></script>
</body>
</html>
`;
fs.writeFileSync(path.join(outDir, c.file + ".html"), html, "utf8");
});
return { dir: m.dir, chapters: m.chapters.length, secs: secTotal, chars: m._total };
}
/* ---------------------------------------------------------------- 入口 */
const argv = process.argv.slice(2);
const only = argv.includes("--only") ? argv[argv.indexOf("--only") + 1] : null;
const checkOnly = argv.includes("--check") ? argv[argv.indexOf("--check") + 1] : null;
const targets = fs.existsSync(CONTENT)
? fs.readdirSync(CONTENT).filter(f => f.endsWith(".js")).map(f => f.replace(/\.js$/, "")).sort()
: [];
if (!targets.length) { console.error("content/ 下没有内容文件"); process.exit(1); }
const results = [];
for (const name of targets) {
if (only && name !== only) continue;
if (checkOnly && name !== checkOnly) continue;
let m;
try { m = require(path.join(CONTENT, name + ".js")); }
catch (e) { console.error(`✗ ${name}.js 加载失败:${e.message}`); process.exitCode = 1; continue; }
const before = problems.length;
const ok = validate(m, name);
if (!ok) {
console.error(`✗ ${name}(${problems.length - before} 个问题)`);
problems.slice(before).forEach(x => console.error(" - " + x));
process.exitCode = 1;
continue;
}
if (checkOnly) { results.push({ dir: m.dir, chapters: m.chapters.length, chars: m._total, dry: true }); continue; }
results.push(generate(m));
console.log(`✓ modules/${m.dir}:${m.chapters.length} 章 / ${m._total} 字`);
}
if (results.length && !checkOnly) {
console.log("\n小计:" + results.map(r => `${r.dir}=${r.chars}`).join(" "));
console.log("合计 " + results.reduce((n, r) => n + r.chars, 0) + " 字");
}
if (problems.length) { console.error(`\n共 ${problems.length} 个问题`); process.exit(1); }
if (checkOnly && results.length) console.log("OK 校验通过:" + results.map(r => r.dir).join(", "));

View File

@@ -0,0 +1,55 @@
#!/usr/bin/env node
/* ==========================================================================
样式一致性核对
① 以阶段 0 / 1 的既有页面为基线,收集它们用到的全部 class;
② 扫描新模块页面,报告任何「基线里没有、doc.css 里也没有」的 class。
这能证明新页面的样式与既有页面完全同源,而不是自创了一套。
node .sre-s23/verify-template.js <模块目录名...>
========================================================================== */
const fs = require("fs");
const path = require("path");
const SITE = path.resolve(__dirname, "..", "knowledge", "sre-learning-path");
const MODDIR = path.join(SITE, "modules");
const css = fs.readFileSync(path.join(SITE, "assets", "doc.css"), "utf8");
const cssClasses = new Set([...css.matchAll(/\.([a-zA-Z][a-zA-Z0-9_-]*)/g)].map(m => m[1]));
/* 只在复合选择器里出现、单独扫描时会误报的名字 */
const KNOWN = new Set(["prev", "current"]);
const classesOf = dir => {
const set = new Set();
for (const f of fs.readdirSync(path.join(MODDIR, dir))) {
if (!f.endsWith(".html")) continue;
const html = fs.readFileSync(path.join(MODDIR, dir, f), "utf8");
for (const m of html.matchAll(/class="([^"]+)"/g)) {
for (const t of m[1].split(/\s+/)) if (t) set.add(t);
}
}
return set;
};
const all = fs.readdirSync(MODDIR, { withFileTypes: true })
.filter(d => d.isDirectory()).map(d => d.name).sort();
const baseline = new Set();
for (const d of all.filter(x => /^s[01]-/.test(x))) {
for (const t of classesOf(d)) baseline.add(t);
}
const targets = process.argv.slice(2).length
? process.argv.slice(2)
: all.filter(x => /^s[23]-/.test(x));
console.log(`基线:阶段 0/1 共 ${baseline.size} 种 class(来自 ${all.filter(x => /^s[01]-/.test(x)).length} 个模块)\n`);
let bad = 0;
for (const d of targets) {
const set = classesOf(d);
const alien = [...set].filter(t => !baseline.has(t) && !cssClasses.has(t) && !KNOWN.has(t));
const extra = [...set].filter(t => !baseline.has(t) && cssClasses.has(t));
if (alien.length) bad++;
console.log(`${alien.length ? "✗" : "✓"} ${d}:${set.size} 种 class` +
(alien.length ? ` —— 未定义样式:${alien.join(", ")}` : "") +
(extra.length ? `(doc.css 中存在但既有页面未用过:${extra.join(", ")})` : ""));
}
console.log(bad ? `\n有 ${bad} 个模块使用了自创样式` : "\nOK 新页面只使用既有样式");
process.exit(bad ? 1 : 0);