diff --git a/.github/workflows/deploy.yml b/.github/workflows/deploy.yml new file mode 100644 index 0000000..995192d --- /dev/null +++ b/.github/workflows/deploy.yml @@ -0,0 +1,340 @@ +name: 双线部署 + +# 双线部署(SPEC §0 / §8.1 / §9.2 / §9.3): +# 同一提交 → 同一份静态产物(dist/)→ 两条独立发布通道 +# ① GitHub Pages 镜像(来源 = GitHub Actions,自定义域名栏必须留空) +# ② Cloudflare Pages 主站 hub.oneboy.app(deploy hook 触发同版重建) +# 一侧失败不阻塞另一侧:两个发布 job 互相不依赖,各自独立报错(§0 / §9.2)。 +# +# 触发: +# - main 有新提交时(与 CF Pages Git 集成的生产分支一致) +# - 每日定时重建(数据刷新 + 链接健康巡检 + 构建摘要,§9.2 / §9.3) +# - 手动(workflow_dispatch):dry_run 演练模式 / 注入单侧失败演练 +# +# 密钥红线:Cloudflare Pages deploy hook URL 只从 GitHub Secrets 读取 +# (名称 CLOUDFLARE_PAGES_DEPLOY_HOOK),绝不写进仓库文件、README 或日志。 +on: + push: + branches: [main] + schedule: + # UTC 19:17 = 北京时间 03:17(每日一次,§9.2) + - cron: '17 19 * * *' + workflow_dispatch: + inputs: + dry_run: + description: '演练模式:只构建 + 出摘要,不实际发布(不调用 Pages 发布动作、不调用 deploy hook)' + type: boolean + default: false + simulate_failure: + description: '演练:故意让某一侧发布失败,验证另一侧不受影响(仅 dry_run 模式可用)' + type: choice + options: [none, pages, cloudflare] + default: none + +permissions: + contents: read + +concurrency: + group: deploy-${{ github.workflow }}-${{ github.ref }} + cancel-in-progress: false + +jobs: + build: + name: 构建(同一份静态产物) + runs-on: ubuntu-latest + outputs: + version: ${{ steps.version.outputs.version }} + steps: + - uses: actions/checkout@v7 + with: + # 页脚版本号来自 git describe(§0 / §12 第 8 条),需要完整历史 + fetch-depth: 0 + persist-credentials: false + + - uses: pnpm/action-setup@v6 + + - uses: actions/setup-node@v7 + with: + node-version-file: .nvmrc + cache: pnpm + + - name: 解析运行模式(演练 / 注入失败侧) + id: mode + env: + INPUT_DRY_RUN: ${{ github.event.inputs.dry_run || 'false' }} + INPUT_SIMULATE_FAILURE: ${{ github.event.inputs.simulate_failure || 'none' }} + run: | + set -euo pipefail + dry_run="${INPUT_DRY_RUN}" + simulate="${INPUT_SIMULATE_FAILURE}" + case "$dry_run" in + true|false) ;; + *) echo "::error::dry_run 取值非法:$dry_run"; exit 1 ;; + esac + case "$simulate" in + none|pages|cloudflare) ;; + *) echo "::error::simulate_failure 取值非法:$simulate"; exit 1 ;; + esac + if [ "$simulate" != "none" ] && [ "$dry_run" != "true" ]; then + echo "::error::simulate_failure 只允许在 dry_run=true 的演练模式下使用(正式发布不许注入失败)" + exit 1 + fi + echo "运行模式:dry_run=$dry_run,simulate_failure=$simulate(事件 $GITHUB_EVENT_NAME)" + + - name: 安装依赖 + run: pnpm install --frozen-lockfile + + - name: 密钥红线自检(deploy hook URL 不得出现在仓库任何文件里) + run: | + set -euo pipefail + # 排除工作流目录自身(本文件的正则出现在注释里),只扫会被提交的文件 + if hits=$(grep -rIl --exclude-dir=.git --exclude-dir=node_modules --exclude-dir=dist \ + --exclude-dir=.github -e 'deploy_hooks' . || true); then :; fi + if [ -n "${hits:-}" ]; then + echo "::error::检测到疑似 Cloudflare deploy hook URL 被写进仓库文件(只允许放 GitHub Secrets):" + echo "$hits" + exit 1 + fi + echo "密钥红线自检通过:仓库文件里没有 deploy hook URL" + + - name: 构建(§9.1:一条命令产出 dist/) + run: pnpm build + env: + # 只读公开数据足够;不要求、也不允许任何 PAT 入仓(§9.2) + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + + - name: 记录版本号(git describe,与页脚同源;取不到就中断) + id: version + run: | + set -euo pipefail + # 与 src/lib/build-info.ts 同一命令(不带 --dirty:构建本身会改写自动字段缓存) + if ! version=$(git describe --tags --always 2>&1); then + echo "::error::git describe 失败($version)——版本号是 §12 第 8 条硬性项,请确认 checkout 带了 fetch-depth: 0" + exit 1 + fi + echo "version=$version" >> "$GITHUB_OUTPUT" + echo "版本号:$version" + + - name: 产物自检(双线共用同一份 dist/) + run: | + set -euo pipefail + test -f dist/index.html + test -f dist/sitemap.xml + test -f dist/robots.txt + if [ -f dist/CNAME ]; then + echo "::error::dist/ 里出现了 CNAME:GitHub Pages 自定义域名栏必须留空(§0)" + exit 1 + fi + version=$(git describe --tags --always) + if ! grep -rqF -- "$version" dist/index.html; then + echo "::error::页脚版本号未注入:dist/index.html 里找不到 $version(§12 第 8 条)" + exit 1 + fi + echo "静态页 $(find dist -name 'index.html' | wc -l) 个,产物目录 dist/" + echo "页脚版本号已注入:$version" + + - name: 上传站点产物(两侧发布共用) + uses: actions/upload-artifact@v7 + with: + name: site + path: dist + retention-days: 7 + + - name: 上传构建报告(抓取结果 + 缓存文件,供摘要与维护者取用) + uses: actions/upload-artifact@v7 + with: + name: reports + path: | + github-meta-report.json + src/data/cache/github-meta.json + retention-days: 7 + if-no-files-found: warn + + link-health: + name: 链接健康巡检(§9.3) + runs-on: ubuntu-latest + needs: build + # §9.3:只在每日重建(定时)与手动演练时巡检,日常推送不打扰第三方站点 + if: github.event_name == 'schedule' || github.event_name == 'workflow_dispatch' + steps: + - uses: actions/checkout@v7 + with: + persist-credentials: false + + - uses: pnpm/action-setup@v6 + + - uses: actions/setup-node@v7 + with: + node-version-file: .nvmrc + cache: pnpm + + - name: 安装依赖 + run: pnpm install --frozen-lockfile + + - name: 恢复上次的连续失败计数(不写入仓库) + uses: actions/cache@v6 + with: + path: link-health-state.json + key: link-health-${{ github.run_id }} + restore-keys: | + link-health- + + - name: 巡检全部外链(只出摘要,不硬拦、不改数据) + run: pnpm health:links + + - name: 上传链接健康报告 + uses: actions/upload-artifact@v7 + with: + name: link-health + path: link-health-report.json + retention-days: 7 + if-no-files-found: warn + + publish-github-pages: + name: 发布 GitHub Pages 镜像 + runs-on: ubuntu-latest + needs: build + # 与 CF 侧完全独立:只依赖 build,一侧失败不影响另一侧(§0 / §9.2) + if: always() && needs.build.result == 'success' + permissions: + contents: read + pages: write + id-token: write + environment: + name: github-pages + url: ${{ steps.deployment.outputs.page_url }} + env: + DRY_RUN: ${{ github.event.inputs.dry_run || 'false' }} + SIMULATE_FAILURE: ${{ github.event.inputs.simulate_failure || 'none' }} + steps: + - name: 下载站点产物 + uses: actions/download-artifact@v8 + with: + name: site + path: dist + + - name: 演练|模拟发布 GitHub Pages(不调用官方发布动作) + if: env.DRY_RUN == 'true' + run: | + set -euo pipefail + test -f dist/index.html + echo "演练:本应把 dist/($(find dist -name 'index.html' | wc -l) 个页面)作为 Pages 产物发布,来源 = GitHub Actions" + echo "演练:未调用 actions/configure-pages / upload-pages-artifact / deploy-pages" + if [ "$SIMULATE_FAILURE" = "pages" ]; then + echo "::error::演练注入:GitHub Pages 侧发布失败(另一侧按独立 job 继续)" + exit 1 + fi + echo "演练:GitHub Pages 侧发布成功(模拟)" + + - name: 配置 Pages(来源 = GitHub Actions) + if: env.DRY_RUN != 'true' + uses: actions/configure-pages@v6 + + - name: 上传 Pages 产物 + if: env.DRY_RUN != 'true' + uses: actions/upload-pages-artifact@v5 + with: + path: dist + + - name: 发布(官方 Pages 发布动作) + id: deployment + if: env.DRY_RUN != 'true' + uses: actions/deploy-pages@v5 + + publish-cloudflare-pages: + name: 触发 Cloudflare Pages 主站重建 + runs-on: ubuntu-latest + needs: build + # 与 Pages 侧完全独立:只依赖 build,一侧失败不影响另一侧(§0 / §9.2) + if: always() && needs.build.result == 'success' + env: + DRY_RUN: ${{ github.event.inputs.dry_run || 'false' }} + SIMULATE_FAILURE: ${{ github.event.inputs.simulate_failure || 'none' }} + steps: + - name: 演练|模拟触发主站重建(不调用 deploy hook) + if: env.DRY_RUN == 'true' + run: | + set -euo pipefail + echo "演练:本应用同一提交 POST Cloudflare Pages deploy hook(URL 只来自 GitHub Secrets)" + echo "演练:未读取、未打印 CLOUDFLARE_PAGES_DEPLOY_HOOK" + if [ "$SIMULATE_FAILURE" = "cloudflare" ]; then + echo "::error::演练注入:Cloudflare Pages 侧触发失败(另一侧按独立 job 继续)" + exit 1 + fi + echo "演练:Cloudflare Pages 侧触发成功(模拟)" + + - name: 触发主站同版重建(deploy hook,URL 只从 GitHub Secrets 读取) + if: env.DRY_RUN != 'true' + env: + CLOUDFLARE_PAGES_DEPLOY_HOOK: ${{ secrets.CLOUDFLARE_PAGES_DEPLOY_HOOK }} + run: | + set -euo pipefail + if [ -z "${CLOUDFLARE_PAGES_DEPLOY_HOOK:-}" ]; then + echo "::error::缺少 GitHub Secrets:CLOUDFLARE_PAGES_DEPLOY_HOOK(Cloudflare Pages 项目 → Settings → Builds & deployments → Deploy hooks 生成后填进 Secrets;绝不写进仓库文件)" + exit 1 + fi + # 不回显 URL(密钥红线):只打印状态码 + status=$(curl -sS -o /dev/null -w '%{http_code}' \ + --retry 2 --retry-delay 5 --max-time 30 \ + -X POST "$CLOUDFLARE_PAGES_DEPLOY_HOOK" || echo '000') + echo "deploy hook 响应:HTTP $status" + case "$status" in + 2??) echo "已触发 Cloudflare Pages 主站重建(同提交、同版本号)" ;; + *) + echo "::error::deploy hook 触发失败(HTTP $status)——本侧独立报错,不影响 GitHub Pages 侧" + exit 1 + ;; + esac + + summary: + name: 构建摘要(§9.2 / §9.3 / §12 第 7 条) + runs-on: ubuntu-latest + needs: [build, link-health, publish-github-pages, publish-cloudflare-pages] + if: always() + steps: + - uses: actions/checkout@v7 + with: + persist-credentials: false + + - uses: pnpm/action-setup@v6 + + - uses: actions/setup-node@v7 + with: + node-version-file: .nvmrc + cache: pnpm + + - name: 安装依赖 + run: pnpm install --frozen-lockfile + + - name: 下载构建报告 + uses: actions/download-artifact@v8 + with: + name: reports + path: . + + - name: 下载链接健康报告(推送构建不跑巡检,故允许缺失) + uses: actions/download-artifact@v8 + continue-on-error: true + with: + name: link-health + path: . + + - name: 生成构建摘要(自动字段刷新结果 + 异常项目清单 + 链接健康 + 两侧发布结果) + env: + HUB_META_REPORT: github-meta-report.json + HUB_LINK_REPORT: link-health-report.json + HUB_LINK_EXPECTED: ${{ (github.event_name == 'schedule' || github.event_name == 'workflow_dispatch') && '1' || '0' }} + HUB_VERSION: ${{ needs.build.outputs.version }} + PUBLISH_DRY_RUN: ${{ github.event.inputs.dry_run || 'false' }} + PUBLISH_SIMULATE_FAILURE: ${{ github.event.inputs.simulate_failure || 'none' }} + PUBLISH_GITHUB_PAGES_RESULT: ${{ needs.publish-github-pages.result }} + PUBLISH_CLOUDFLARE_RESULT: ${{ needs.publish-cloudflare-pages.result }} + run: pnpm summary:build + + - name: 上传构建摘要 + uses: actions/upload-artifact@v7 + with: + name: build-summary + path: build-summary.md + retention-days: 7 + if-no-files-found: warn diff --git a/.gitignore b/.gitignore index 9dea0c7..8cd70b7 100644 --- a/.gitignore +++ b/.gitignore @@ -16,3 +16,8 @@ og-report.json # 测试临时目录 tests/.tmp/ + +# 部署工作流产出的报告与状态(不入库:报告每次变化,状态由 actions/cache 持久化) +link-health-report.json +link-health-state.json +build-summary.md diff --git a/README.md b/README.md index ff7eeb9..1ec7644 100644 --- a/README.md +++ b/README.md @@ -4,7 +4,7 @@ Cloudflare Workers 生态的中文精选应用目录:官方自研项目 + 经 **本站是纯静态站点**:无后端、无数据库、无鉴权、无站点级 secret(SPEC v1.4 §0 明示例外项)。构建产物是纯静态 HTML,同时发布到主站 `hub.oneboy.app`(Cloudflare Pages)与镜像 `workerhub.github.io`(GitHub Pages),canonical 恒写主域名。 -> 当前进度:S1-A 脚手架与数据管线、S1-B 内容数据(官方 7 + 第三方 4)、S2-A 页面与组件(页面 / 统一卡片 / 搜索筛选排序 / 主题三档 / SEO)、S2-B 投稿基建(CONTRIBUTING / PR 模板 / 投稿数据校验)均已交付;双线部署(S3)分属后续子单,见文末「范围」。 +> 当前进度:S1-A 脚手架与数据管线、S1-B 内容数据(官方 7 + 第三方 4)、S2-A 页面与组件(页面 / 统一卡片 / 搜索筛选排序 / 主题三档 / SEO)、S2-B 投稿基建(CONTRIBUTING / PR 模板 / 投稿数据校验)、S3 双线部署(GitHub Actions 工作流 + CF deploy hook + 每日重建 + 本文件两份核对表)均已交付;**上线关口(CF Pages 建项、域名绑定、GitHub Pages 启用)归用户**,团队交付停在 PR,见文末「范围」。 ## 技术栈(SPEC §8.1) @@ -26,6 +26,8 @@ pnpm check:links # 只跑外链可达性 pnpm check:screenshots # 只跑截图规格 pnpm check:pr-scope # 投稿 PR 变更范围(只允许数据文件与截图) pnpm fetch:meta # 只跑 GitHub 自动字段抓取 +pnpm health:links # 外链健康巡检(§9.3,每日重建跑的那一步;只出报告不硬拦) +pnpm summary:build # 生成构建摘要 Markdown(§9.2/§9.3,写进 GitHub Actions summary) pnpm lint # astro check(类型检查)+ prettier --check pnpm format # prettier 自动格式化 pnpm test # 单元 + 集成测试(node:test) @@ -162,36 +164,97 @@ src/lib/project-filter.ts 搜索 / 六维筛选 / 五种排序 / URL 状态同 src/lib/project-entry.ts 卡片主入口与详情页部署按钮(唯一真源) src/lib/site.ts 站点常量与绝对地址(canonical 恒写主域名) src/lib/build-info.ts 版本号 / 构建时间 +src/lib/link-health.ts 外链巡检 + 连续失败计数(§9.3) +src/lib/build-summary.ts 构建摘要渲染(§9.2 / §9.3,纯函数) src/components/ui/ shadcn/ui 组件(Badge / Button / Input / Checkbox / Dialog / Dropdown / Separator) src/components/project/ 统一卡片、徽章、截图回退 src/components/site/ 页头页脚、主题切换 island、筛选 island src/layouts/base-layout.astro SEO/OG/canonical、主题防闪烁、页头页脚 src/pages/ 首页 / projects / p/ / categories/ / submit / about / 404 / sitemap.xml / robots.txt public/og/github/ 构建期本地化的仓库 OG 图缓存(§8.3,抓取失败则走首字图) -scripts/ validate-data.ts / validate-submission.ts / check-pr-scope.ts / fetch-github-meta.ts / fetch-og-images.ts +scripts/ validate-data.ts / validate-submission.ts / check-pr-scope.ts / fetch-github-meta.ts / fetch-og-images.ts / link-health.ts / build-summary.ts tests/ 单测 + 进程级集成测试 + 夹具 .github/PULL_REQUEST_TEMPLATE.md 投稿 PR 模板(五条门槛逐项勾选 + 证据栏) .github/workflows/ci.yml 校验与演练(不含发布) +.github/workflows/deploy.yml 双线部署(GitHub Pages 镜像 + CF Pages deploy hook + 每日重建) ``` -## 双线部署设置核对表(供部署子单执行,本单不碰) - -| 项 | 值 / 要求 | -| ---------------------------- | ------------------------------------------------------------------------------------------------------------------------- | -| 主站托管 | Cloudflare Pages,项目连 `WorkerHub/workerhub.github.io` | -| 主站生产分支 | `main` | -| CF Pages 构建命令 | `pnpm build` | -| CF Pages 输出目录 | `dist` | -| CF Pages 环境变量 | 无需业务变量;GitHub 抓取可选注入 `GITHUB_TOKEN`(只读) | -| 域名 | `hub.oneboy.app` 为主域名;`workerhub.oneboy.app` 301 到主域名 | -| 镜像托管 | GitHub Pages,来源 = **GitHub Actions** | -| GitHub Pages 自定义域名栏 | **必须留空**(填任何域名都会让镜像变跳转、双线失效) | -| canonical / sitemap 绝对地址 | 恒为 `https://hub.oneboy.app`,镜像侧同样如此,不按访问域名动态生成 | -| 每日重建 | 同一个工作流:刷新数据构建 → 发布 GitHub Pages → 用 CF Pages deploy hook 触发主站同版重建(hook URL 只进 GitHub Secrets) | -| 发布失败 | 两侧各自独立报错,一侧失败不阻塞另一侧 | +## 双线部署(SPEC §0 / §8.1 / §9.2 / §9.3) + +同一个提交 → **同一份** `dist/` 产物 → 两条**互相独立**的发布通道: + +| 一线 | 托管 | 地址 | 怎么发 | +| ------------ | ------------------------------ | --------------------- | ------------------------------------------------------------------- | +| 主站 | Cloudflare Pages(Git 集成) | `hub.oneboy.app` | CF 自己从 `main` 构建;本工作流另用 **deploy hook** 触发同版重建 | +| 镜像(备用) | GitHub Pages(来源 = Actions) | `workerhub.github.io` | 本工作流构建后用官方 Pages 发布动作上线(不往仓库写 gh-pages 分支) | + +### 工作流 `.github/workflows/deploy.yml` + +``` +触发:push 到 main(有新提交)/ 每日 cron 19:17 UTC(北京 03:17)/ workflow_dispatch(含演练开关) + │ + ├─ build ──────────── pnpm install → 密钥红线自检 → pnpm build → 产物自检 → 上传 dist/ 与构建报告 + │ │ + │ ├─ link-health ── 仅在定时/手动时跑:全部外链可达性巡检(连续失败计数走 actions/cache,不写仓库) + │ │ + │ ├─ publish-github-pages ────── 官方 Pages 动作发布镜像(environment: github-pages) + │ └─ publish-cloudflare-pages ── POST CF Pages deploy hook(URL 只来自 Secrets) + │ + └─ summary ─────────── 汇总进 GitHub Actions summary + build-summary.md 产物 +``` + +- **一侧失败不阻塞另一侧**(§0 / §9.2):两个 publish job 只依赖 `build`,彼此**不互为 `needs`**,各自跑、各自红、各自在日志里报错;`summary` 用 `if: always()` 逐侧标注结果。 +- **构建摘要必含**(§9.2 / §9.3):自动字段刷新结果(成功 / 缓存兜底 / 降级置空 / 数据错误 + 逐项降级原因)、archive 与超过 365 天未更新的异常项目清单、外链巡检结果与**连续失败点名**(阈值:连续 2 次)、两侧发布结果。 +- **不自动改数据**:异常项目与坏链只进摘要,是否下架/修正走人工数据 PR;工作流**不向 `main` 写提交**(自动字段缓存如有变化,作为 `reports` 产物上传,由维护者随数据 PR 提交)。 +- **密钥红线**:CF Pages deploy hook URL 只放 GitHub Secrets,名为 `CLOUDFLARE_PAGES_DEPLOY_HOOK`;`build` 里有一道自检,扫到仓库文件里出现 deploy hook URL 直接失败;日志只打印 HTTP 状态码,不回显 URL。 +- **版本号一致性**(§12 第 10 条):页脚版本号 = 构建时 `git describe --tags --always`(`src/lib/build-info.ts`)。两侧都从同一提交构建,所以值相同;需要固定时可用 `HUB_VERSION` 覆盖。刻意**不用 `--dirty`**:构建本身会改写自动字段缓存文件,带 `--dirty` 会让每次 CI 构建都得到 `-dirty`,两侧无法比较。 + +### 演练(不发出真实发布) + +`workflow_dispatch` 两个输入: + +| 输入 | 值 | 作用 | +| ------------------ | ---------------------- | --------------------------------------------------------------------------------------- | +| `dry_run` | `true` | 只构建 + 出摘要:**不调** Pages 发布动作、**不调** deploy hook(不读也不打印 hook URL) | +| `simulate_failure` | `pages` / `cloudflare` | 演练时故意让一侧失败,验证另一侧照常走完且有独立报错(仅 `dry_run=true` 下允许) | + +等价地可以从仓库里跑:`pnpm build && pnpm health:links && pnpm summary:build`(摘要直接看 `build-summary.md`)。 + +已知平台限制(不是工作流缺陷): + +1. `workflow_dispatch` 要求该工作流文件已存在于**默认分支**,所以合并进 `main` 之前无法从 UI/API 手动触发; +2. `publish-github-pages` 绑定了 `github-pages` 环境,该环境的部署分支策略只放行 `main`,非 `main` 分支跑真实发布会被环境拦下(演练用 `dry_run=true` 不触碰发布动作,因此不受影响)。 + +## 上线设置核对表(两平台,逐项确认) + +下面这些**全部是用户关口的操作**(团队不代建项目、不绑域名、不启 Pages、不动仓库设置),按顺序打勾即可。 + +### A. Cloudflare Pages(主站 `hub.oneboy.app`) + +- [ ] 创建 Pages 项目,连接 GitHub 仓库 `WorkerHub/workerhub.github.io` +- [ ] 生产分支 = `main`;PR 自动预览开启(预览部署不参与双线同版校验) +- [ ] 构建命令 = `pnpm build`,输出目录 = `dist`(构建镜像的 Node 版本需 ≥ 24,仓库 `.nvmrc` 为 24) +- [ ] 环境变量:无业务变量;如需避免 GitHub API 限流,可加只读 `GITHUB_TOKEN`(可选) +- [ ] Settings → Builds & deployments → **Deploy hooks 生成一条 hook**,把 URL 存进 GitHub Secrets:名称 `CLOUDFLARE_PAGES_DEPLOY_HOOK`(**只进 Secrets,不写进仓库文件、README、评论、工单**) +- [ ] 绑定自定义域名 `hub.oneboy.app`;`workerhub.oneboy.app` 做 301 到主域名 +- [ ] (可选,§10)Cloudflare Web Analytics 站点开启后,把 token 作为构建环境变量 `HUB_CF_ANALYTICS_TOKEN` 注入 + +### B. GitHub Pages(镜像 `workerhub.github.io`) + +- [ ] Settings → Pages → **Source = GitHub Actions**(不是 Deploy from a branch) +- [ ] Settings → Pages → **Custom domain 栏必须留空** ← 硬性项:填任何域名都会让镜像变成跳转站,双线即失效(§0) +- [ ] Settings → Environments → `github-pages` 的部署分支策略放行 `main` +- [ ] Actions 权限:仓库允许 Actions 创建 deployment(默认已允许) + +### C. 合并后的首次验证 + +- [ ] 合并本 PR 后,`main` 上触发一次「双线部署」,两侧均为 ✅(首次正式运行前 B 节若未做,Pages 侧会红——属预期,不是工作流问题) +- [ ] 两侧各抽查三页:页脚版本号一致;镜像侧 canonical 指向 `https://hub.oneboy.app` +- [ ] Actions summary 里能看到:自动字段刷新结果、异常项目清单、链接健康(连续失败点名)、两侧发布结果 +- [ ] 次日检查定时重建是否自动跑过一次(cron 19:17 UTC) ## 范围(防止顺带扩大,SPEC §11) -- 已交付:S1-A 脚手架与数据管线(schema + 抓取 + 缓存降级 + CI 校验与演练)、S1-B 内容数据(官方 7 + 第三方 4)、S2-A 页面与组件(页面、统一卡片、搜索筛选排序、主题三档、SEO/分享与 sitemap)、S2-B 投稿基建(CONTRIBUTING、PR 模板、投稿数据校验与演练)。 -- 不在这些单里:每日重建与双线发布(部署子单)、PR 合并与域名绑定(用户关口)。 -- 本站不加后端、不加 D1/KV/DO/R2、不加登录鉴权、不引入任何 secret(SPEC §0)。 +- 已交付:S1-A 脚手架与数据管线(schema + 抓取 + 缓存降级 + CI 校验与演练)、S1-B 内容数据(官方 7 + 第三方 4)、S2-A 页面与组件(页面、统一卡片、搜索筛选排序、主题三档、SEO/分享与 sitemap)、S2-B 投稿基建(CONTRIBUTING、PR 模板、投稿数据校验与演练)、S3 双线部署(`.github/workflows/deploy.yml` + 链接健康 + 构建摘要 + 上文两份核对表)。 +- 不在这些单里:PR 合并与域名绑定 / Pages 建项 / Pages 启用 / deploy hook 入 Secrets(用户关口)。 +- 本站不加后端、不加 D1/KV/DO/R2、不加登录鉴权、不引入任何 secret(SPEC §0);唯一的 secret 是 CF Pages deploy hook URL,且只存于 GitHub Secrets。 diff --git a/package.json b/package.json index 00eee68..d0aec1d 100644 --- a/package.json +++ b/package.json @@ -24,7 +24,9 @@ "test": "node --import tsx --test tests/*.test.ts", "lint:types": "astro check", "lint:format": "prettier --check .", - "fetch:og": "tsx scripts/fetch-og-images.ts" + "fetch:og": "tsx scripts/fetch-og-images.ts", + "health:links": "tsx scripts/link-health.ts", + "summary:build": "tsx scripts/build-summary.ts" }, "dependencies": { "@astrojs/react": "^7.1.1", diff --git a/scripts/build-summary.ts b/scripts/build-summary.ts new file mode 100644 index 0000000..967c43b --- /dev/null +++ b/scripts/build-summary.ts @@ -0,0 +1,102 @@ +#!/usr/bin/env tsx +/** + * 构建摘要 CLI(SPEC §9.2 / §9.3 / §12 第 7 条)。 + * + * 由 deploy 工作流的 `summary` job 调用:把抓取报告 + 链接健康报告 + 两侧发布结果渲染成 + * Markdown,写进 GitHub Actions summary(`$GITHUB_STEP_SUMMARY`)并落一份 `build-summary.md`。 + * + * 输入(环境变量): + * HUB_META_REPORT 抓取报告路径(默认 github-meta-report.json) + * HUB_LINK_REPORT 链接健康报告路径(默认 link-health-report.json) + * HUB_LINK_EXPECTED 置 1 表示本次应跑过链接巡检(每日重建 / 演练) + * HUB_SUMMARY_PATH 摘要落盘路径(默认 build-summary.md) + * HUB_VERSION 版本号(由 build job 的 git describe 输出注入,与页脚一致) + * PUBLISH_GITHUB_PAGES_RESULT / PUBLISH_CLOUDFLARE_RESULT 两侧 job 的 result + * PUBLISH_GITHUB_PAGES_DETAIL / PUBLISH_CLOUDFLARE_DETAIL 两侧补充说明(可选) + * PUBLISH_DRY_RUN 演练模式 + * PUBLISH_SIMULATE_FAILURE 演练注入的失败侧 + * + * 退出码恒为 0:摘要步骤本身不该改变两侧的成败结论。 + */ +import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs'; +import { dirname, resolve } from 'node:path'; + +import { getBuildInfo } from '../src/lib/build-info.js'; +import { + describePublishOutcome, + parseLinkHealthReport, + parseMetaReport, + renderBuildSummary, + type BuildSummaryContext, + type PublishOutcome, + type PublishSide, +} from '../src/lib/build-summary.js'; + +const env = process.env; +const META_REPORT_PATH = resolve(env.HUB_META_REPORT ?? 'github-meta-report.json'); +const LINK_REPORT_PATH = resolve(env.HUB_LINK_REPORT ?? 'link-health-report.json'); +const SUMMARY_PATH = resolve(env.HUB_SUMMARY_PATH ?? 'build-summary.md'); +const LINKS_EXPECTED = env.HUB_LINK_EXPECTED === '1'; + +const readJson = (path: string): unknown => { + if (!existsSync(path)) return null; + try { + return JSON.parse(readFileSync(path, 'utf8')); + } catch (error) { + console.warn(`⚠ 报告文件无法解析(${path}):${(error as Error).message}`); + return null; + } +}; + +const runUrl = + env.GITHUB_SERVER_URL && env.GITHUB_REPOSITORY && env.GITHUB_RUN_ID + ? `${env.GITHUB_SERVER_URL}/${env.GITHUB_REPOSITORY}/actions/runs/${env.GITHUB_RUN_ID}` + : undefined; + +const context: BuildSummaryContext = { + event: env.GITHUB_EVENT_NAME ?? 'local', + ref: env.GITHUB_REF_NAME ?? 'local', + sha: env.GITHUB_SHA ?? '0000000000000000000000000000000000000000', + version: getBuildInfo().version, + generatedAt: new Date().toISOString().replace('T', ' ').slice(0, 16), + dryRun: env.PUBLISH_DRY_RUN === 'true', + simulateFailure: env.PUBLISH_SIMULATE_FAILURE ?? 'none', + runUrl, +}; + +const publishing: PublishOutcome[] = ( + [ + ['github-pages', 'PUBLISH_GITHUB_PAGES'], + ['cloudflare-pages', 'PUBLISH_CLOUDFLARE'], + ] as [PublishSide, string][] +).map(([side, prefix]) => { + const result = env[`${prefix}_RESULT`] ?? 'skipped'; + return { + side, + result, + detail: + env[`${prefix}_DETAIL`] ?? + describePublishOutcome(side, result, { + dryRun: context.dryRun, + simulateFailure: context.simulateFailure, + }), + }; +}); + +const summary = renderBuildSummary({ + context, + meta: parseMetaReport(readJson(META_REPORT_PATH)), + links: parseLinkHealthReport(readJson(LINK_REPORT_PATH)), + linksExpected: LINKS_EXPECTED, + publishing, +}); + +mkdirSync(dirname(SUMMARY_PATH), { recursive: true }); +writeFileSync(SUMMARY_PATH, summary, 'utf8'); +console.log(summary); + +if (env.GITHUB_STEP_SUMMARY) { + writeFileSync(env.GITHUB_STEP_SUMMARY, `${summary}\n`, { flag: 'a' }); + console.log(`摘要已写入 ${env.GITHUB_STEP_SUMMARY}`); +} +console.log(`摘要文件:${SUMMARY_PATH}`); diff --git a/scripts/link-health.ts b/scripts/link-health.ts new file mode 100644 index 0000000..7777b99 --- /dev/null +++ b/scripts/link-health.ts @@ -0,0 +1,89 @@ +#!/usr/bin/env tsx +/** + * 外链健康巡检 CLI(SPEC §9.3,每日重建时由 deploy 工作流调用)。 + * + * 用法:`pnpm health:links` + * + * 输入:`src/data/projects/*.yaml` 里的全部外链(仓库入口 + homepage / docs_url / deploy url / guide)。 + * 输出: + * - `link-health-report.json`(默认,已在 .gitignore)—— 摘要报告,工作流写进 GitHub Actions summary + * - `link-health-state.json`(默认,已在 .gitignore)—— 连续失败计数,CI 侧用 actions/cache 持久化 + * + * 退出码: + * 0 巡检完成(无论有没有坏链)—— §9.3 只出摘要、不硬拦、不改数据 + * 1 数据文件本身非法(连数据都读不出来,没什么可巡检的) + * 2 `HUB_LINK_STRICT=1` 且存在连续失败项目(仅供人工本地排查使用,CI 不开启) + */ +import { mkdirSync, writeFileSync } from 'node:fs'; +import { dirname, resolve } from 'node:path'; + +import { PROJECTS_DIR } from '../src/lib/build-config.js'; +import { + CHRONIC_FAILURE_THRESHOLD, + collectProjectLinks, + readLinkHealthState, + runLinkHealth, + serializeLinkHealthState, +} from '../src/lib/link-health.js'; +import { loadProjects } from '../src/lib/load-projects.js'; + +const env = process.env; +const REPORT_PATH = resolve(env.HUB_LINK_REPORT ?? 'link-health-report.json'); +const STATE_PATH = resolve(env.HUB_LINK_STATE ?? 'link-health-state.json'); +const CONCURRENCY = Number.parseInt(env.HUB_LINK_CONCURRENCY ?? '6', 10); +const THRESHOLD = Number.parseInt(env.HUB_LINK_THRESHOLD ?? String(CHRONIC_FAILURE_THRESHOLD), 10); +const STRICT = env.HUB_LINK_STRICT === '1'; + +const warnings: string[] = []; +const warn = (message: string) => { + warnings.push(message); + console.warn(`⚠ ${message}`); +}; + +const loaded = loadProjects(PROJECTS_DIR); +if (!loaded.ok) { + console.error(loaded.message); + process.exit(1); +} +console.log(loaded.message); + +const refs = collectProjectLinks(loaded.projects); +const previous = readLinkHealthState(STATE_PATH, warn); +console.log( + `外链:${refs.length} 条引用 / ${new Set(refs.map((ref) => ref.url)).size} 个唯一 URL;` + + `上次状态 ${Object.keys(previous.links).length} 条记录(${STATE_PATH})`, +); + +const { state, report } = await runLinkHealth(refs, { + previous, + concurrency: Number.isFinite(CONCURRENCY) && CONCURRENCY > 0 ? CONCURRENCY : 6, + threshold: Number.isFinite(THRESHOLD) && THRESHOLD > 0 ? THRESHOLD : CHRONIC_FAILURE_THRESHOLD, + warn, +}); + +mkdirSync(dirname(REPORT_PATH), { recursive: true }); +writeFileSync(REPORT_PATH, `${JSON.stringify(report, null, 2)}\n`, 'utf8'); +mkdirSync(dirname(STATE_PATH), { recursive: true }); +writeFileSync(STATE_PATH, serializeLinkHealthState(state), 'utf8'); + +console.log( + `链接健康:可达 ${report.totals.ok} / 失败 ${report.totals.failed} / 需人工确认 ${report.totals.blocked}` + + `(共 ${report.totals.links} 条,连续失败 ${report.totals.chronic} 条,阈值 ${report.threshold} 次)`, +); +for (const failure of report.chronicFailures) { + console.warn( + ` ✗ 连续失败 ${failure.consecutiveFailures} 次:${failure.url}(${failure.slugs.join('、')})${failure.detail}`, + ); +} +for (const row of report.rows.filter((item) => item.outcome === 'failed' && !item.chronic)) { + console.warn(` · 本次失败:${row.url}(${row.slugs.join('、')})${row.detail}`); +} +for (const item of report.needsReview) { + console.log(` ? 需人工确认:${item.url}(${item.slugs.join('、')})${item.detail}`); +} +console.log(`报告:${REPORT_PATH};状态:${STATE_PATH}`); + +if (STRICT && report.chronicFailures.length > 0) { + console.error('\nHUB_LINK_STRICT=1:存在连续失败项目,按严格模式退出 2'); + process.exit(2); +} diff --git a/src/lib/build-info.ts b/src/lib/build-info.ts index 4559d69..ae60094 100644 --- a/src/lib/build-info.ts +++ b/src/lib/build-info.ts @@ -1,8 +1,13 @@ /** * 版本号与构建时间(SPEC §0 / §12 第 8 条:页脚版本号由构建时注入,仓库源码里不写死)。 * - * 版本号取 `git describe --tags --always --dirty`;CI 可用 HUB_VERSION 覆盖 + * 版本号取 `git describe --tags --always`;CI 可用 HUB_VERSION 覆盖 * (浅克隆场景下由工作流带 fetch-depth: 0 保证 describe 可用)。 + * + * 刻意**不带 `--dirty`**(双线部署需要):构建本身会改写自动字段缓存 + * `src/data/cache/github-meta.json`,带 `--dirty` 会让每次 CI 构建都得到 + * `-dirty`,主站与镜像两侧、两次构建之间都无法比较,页脚也难看。 + * 版本号只标识「哪一次提交的源码」,构建产物差异由构建时间承担。 */ import { execFileSync } from 'node:child_process'; @@ -12,7 +17,7 @@ function readGitDescribe(): string { const injected = process.env.HUB_VERSION?.trim(); if (injected) return injected; try { - return execFileSync('git', ['describe', '--tags', '--always', '--dirty'], { + return execFileSync('git', ['describe', '--tags', '--always'], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'], }).trim(); diff --git a/src/lib/build-summary.ts b/src/lib/build-summary.ts new file mode 100644 index 0000000..e8d54eb --- /dev/null +++ b/src/lib/build-summary.ts @@ -0,0 +1,344 @@ +/** + * 双线重建的构建摘要(SPEC §9.2 / §9.3 / §12 第 7 条)。 + * + * 摘要必须含:自动字段刷新结果 + archive/久未更新异常项目清单 + 链接健康(连续失败点名) + * + 两侧发布结果(一侧失败不影响另一侧,各自独立报错)。 + * + * 渲染是纯函数,CI 侧只负责把报告文件读进来、把 Markdown 写进 `$GITHUB_STEP_SUMMARY`。 + */ +import { z } from 'zod'; + +import { linkHealthReportSchema, type LinkHealthReport } from './link-health.js'; + +// --------------------------------------------------------------------------- +// 输入:抓取报告(由 scripts/fetch-github-meta.ts 产出) +// --------------------------------------------------------------------------- + +export const metaReportSchema = z.strictObject({ + generatedAt: z.string(), + apiBase: z.string(), + authenticated: z.boolean(), + fetchSkipped: z.boolean(), + cachePath: z.string(), + cacheChanged: z.boolean(), + counts: z.strictObject({ + repos: z.number().int().nonnegative(), + fetched: z.number().int().nonnegative(), + fromCache: z.number().int().nonnegative(), + degradedToEmpty: z.number().int().nonnegative(), + dataErrors: z.number().int().nonnegative(), + }), + projects: z.array( + z.strictObject({ + slug: z.string(), + repo: z.string(), + metaStatus: z.enum(['ok', 'cached', 'empty']), + metaReason: z.string().nullable(), + stars: z.number().int().nonnegative().nullable(), + pushedAt: z.string().nullable(), + archived: z.boolean().nullable(), + }), + ), + anomalies: z.array(z.strictObject({ repo: z.string(), reasons: z.array(z.string()) })), + warnings: z.array(z.string()), +}); + +export type MetaReport = z.infer; + +export type PublishSide = 'github-pages' | 'cloudflare-pages'; + +export interface PublishOutcome { + side: PublishSide; + /** 该 job 的 `needs..result`:success / failure / cancelled / skipped */ + result: string; + /** 人类可读的一句话说明(演练模式、未配置 secret 等) */ + detail: string; +} + +export interface BuildSummaryContext { + /** 触发事件:push / schedule / workflow_dispatch */ + event: string; + ref: string; + sha: string; + /** git describe 注入的版本号(与页脚一致) */ + version: string; + generatedAt: string; + /** 演练模式:只构建 + 出摘要,不实际发布 */ + dryRun: boolean; + /** 演练注入的失败侧(none / pages / cloudflare) */ + simulateFailure: string; + runUrl?: string | undefined; +} + +export interface BuildSummaryInput { + context: BuildSummaryContext; + meta: MetaReport | null; + links: LinkHealthReport | null; + /** 链接健康是否本次运行(推送构建不跑巡检,§9.3 只在每日重建执行) */ + linksExpected: boolean; + publishing: PublishOutcome[]; +} + +// --------------------------------------------------------------------------- +// 报告解析(跨 job 传文件,损坏时降级为「未取得」而不是让摘要步骤失败) +// --------------------------------------------------------------------------- + +export function parseMetaReport(raw: unknown): MetaReport | null { + const parsed = metaReportSchema.safeParse(raw); + return parsed.success ? parsed.data : null; +} + +export function parseLinkHealthReport(raw: unknown): LinkHealthReport | null { + const parsed = linkHealthReportSchema.safeParse(raw); + return parsed.success ? parsed.data : null; +} + +// --------------------------------------------------------------------------- +// 渲染 +// --------------------------------------------------------------------------- + +const cell = (value: string): string => value.replaceAll('|', '\\|'); + +/** 摘要里展示仓库内相对路径(CI 绝对路径冗长且无意义) */ +const shortPath = (path: string): string => { + const marker = '/src/'; + const index = path.indexOf(marker); + return index >= 0 ? `src/${path.slice(index + marker.length)}` : path; +}; +const table = (header: string[], rows: string[][]): string => + [`| ${header.join(' | ')} |`, `| ${header.map(() => '---').join(' | ')} |`] + .concat(rows.map((row) => `| ${row.map(cell).join(' | ')} |`)) + .join('\n'); + +const PUBLISH_LABELS: Record = { + 'github-pages': 'GitHub Pages 镜像(workerhub.github.io)', + 'cloudflare-pages': 'Cloudflare Pages 主站(hub.oneboy.app)', +}; + +const RESULT_LABELS: Record = { + success: '✅ 成功', + failure: '❌ 失败', + cancelled: '⏹ 已取消', + skipped: '⏭ 已跳过', +}; + +const statusLabel = (status: string): string => RESULT_LABELS[status] ?? status; + +/** + * 由 job 结果 + 运行模式推导一句话说明(§0 / §9.2:两侧各自独立报错)。 + * 纯函数:摘要里「一侧失败、另一侧照常」的结论就靠它落到文字上。 + */ +export function describePublishOutcome( + side: PublishSide, + result: string, + options: { dryRun: boolean; simulateFailure: string }, +): string { + const injected = options.simulateFailure === (side === 'github-pages' ? 'pages' : 'cloudflare'); + if (result === 'skipped') { + return options.dryRun ? '演练模式未执行' : '本次未执行(构建未成功)'; + } + if (options.dryRun) { + if (result === 'success') return '演练:模拟发布成功(未实际发布)'; + if (result === 'failure') { + return injected + ? '演练注入失败:本侧按预期失败,另一侧独立执行不受影响' + : '演练:本侧执行失败(未注入)'; + } + return `演练:${statusLabel(result)}`; + } + if (result === 'success') return '已发布(同一提交、同一份 dist/)'; + if (result === 'failure') return '发布失败:见本 job 日志(另一侧独立执行)'; + return statusLabel(result); +} + +function renderContext(context: BuildSummaryContext): string { + const mode = context.dryRun + ? `演练(dry_run,不实际发布${context.simulateFailure !== 'none' ? `;注入失败侧 = ${context.simulateFailure}` : ''})` + : '正式(真实发布)'; + return table( + ['项', '值'], + [ + ['触发', `\`${context.event}\``], + ['分支', `\`${context.ref}\``], + ['提交', `\`${context.sha.slice(0, 12)}\``], + ['版本号(git describe)', `\`${context.version}\``], + ['模式', mode], + ['生成时间', `${context.generatedAt}(UTC)`], + ...(context.runUrl ? [['运行记录', context.runUrl]] : []), + ], + ); +} + +function renderMeta(meta: MetaReport | null): string { + if (!meta) { + return '未取得自动字段抓取报告(`github-meta-report.json` 缺失或损坏)——本次构建的自动字段结果未知。'; + } + const { counts } = meta; + const lines: string[] = [ + `- 仓库数:**${counts.repos}**;抓取成功 **${counts.fetched}**;缓存兜底 **${counts.fromCache}**;降级置空 **${counts.degradedToEmpty}**;数据错误 **${counts.dataErrors}**`, + `- API:\`${meta.apiBase}\`(${meta.authenticated ? '工作流自带 token' : '未认证额度'})${meta.fetchSkipped ? ';本次跳过抓取(HUB_SKIP_FETCH=1)' : ''}`, + `- 缓存文件:\`${shortPath(meta.cachePath)}\`(${meta.cacheChanged ? '**本次有变化**,已作为运行产物上传,由维护者随数据 PR 提交;工作流不向 main 写提交' : '无变化'})`, + ]; + + const degraded = meta.projects.filter((project) => project.metaStatus !== 'ok'); + if (degraded.length > 0) { + lines.push( + '', + '自动字段未直连成功的项目(走缓存/置空,页面正常渲染,§9.2 降级路径):', + '', + table( + ['项目', '仓库', '结果', '原因'], + degraded.map((project) => [ + project.slug, + `\`${project.repo}\``, + project.metaStatus === 'cached' ? '缓存兜底' : '置空', + project.metaReason ?? '—', + ]), + ), + ); + } + + if (meta.warnings.length > 0) { + lines.push('', '
抓取警告(' + meta.warnings.length + ' 条)', ''); + for (const warning of meta.warnings) lines.push(`- ${warning}`); + lines.push('', '
'); + } + + return lines.join('\n'); +} + +function renderAnomalies(meta: MetaReport | null): string { + if (!meta) return '未取得抓取报告,无法判断 archive / 久未更新。'; + if (meta.anomalies.length === 0) { + return '无:本次没有任何项目被 archive 或超过 365 天未更新(§6.3 / §9.2)。'; + } + return [ + `以下 **${meta.anomalies.length}** 个项目需要维护者判断是否下架或修正(**本工作流不自动改数据**,下架走人工数据 PR):`, + '', + table( + ['仓库', '异常'], + meta.anomalies.map((anomaly) => [`\`${anomaly.repo}\``, anomaly.reasons.join(';')]), + ), + ].join('\n'); +} + +function renderLinks(links: LinkHealthReport | null, expected: boolean): string { + if (!links) { + return expected + ? '未取得链接健康报告(`link-health-report.json` 缺失或损坏)。' + : '本次不是每日重建,未跑外链巡检(§9.3 只在每日重建执行)。'; + } + const lines: string[] = [ + `- 外链 **${links.totals.links}** 条:可达 **${links.totals.ok}**;失败 **${links.totals.failed}**;需人工确认 **${links.totals.blocked}**;连续失败 **${links.totals.chronic}**(阈值:连续 ${links.threshold} 次)`, + ]; + + if (links.chronicFailures.length > 0) { + lines.push( + '', + `**连续失败点名(${links.chronicFailures.length} 条)** —— 是否下架/修正走人工数据 PR,本工作流不改数据:`, + '', + table( + ['链接', '连续失败', '涉及项目', '最近一次结果'], + links.chronicFailures.map((failure) => [ + failure.url, + `${failure.consecutiveFailures} 次`, + failure.slugs.join('、'), + failure.detail, + ]), + ), + ); + } else { + lines.push('', '无连续失败项目。'); + } + + if (links.needsReview.length > 0) { + lines.push( + '', + `
需人工确认(反爬/限流,未计入失败,${links.needsReview.length} 条)`, + '', + ...links.needsReview.map( + (item) => `- ${item.url}(${item.slugs.join('、')}):${item.detail}`, + ), + '', + '
', + ); + } + + const failedNow = links.rows.filter((row) => row.outcome === 'failed' && !row.chronic); + if (failedNow.length > 0) { + lines.push( + '', + `本次首次失败(尚未达到点名阈值,${failedNow.length} 条):`, + '', + table( + ['链接', '涉及项目', '结果'], + failedNow.map((row) => [row.url, row.slugs.join('、'), row.detail]), + ), + ); + } + + return lines.join('\n'); +} + +function renderPublishing(publishing: PublishOutcome[], context: BuildSummaryContext): string { + if (publishing.length === 0) return '未取得发布结果。'; + const lines: string[] = [ + table( + ['一侧', '结果', '说明'], + publishing.map((outcome) => [ + PUBLISH_LABELS[outcome.side], + statusLabel(outcome.result), + outcome.detail, + ]), + ), + ]; + const failed = publishing.filter((outcome) => outcome.result === 'failure'); + if (failed.length > 0) { + lines.push( + '', + `**独立报错**:${failed.map((outcome) => PUBLISH_LABELS[outcome.side]).join('、')} 失败;另一侧${failed.length === publishing.length ? '(同样失败)' : '按独立 job 正常执行,不受影响'}(§0 / §9.2:一侧失败不阻塞另一侧)。`, + ); + } + if (context.dryRun) { + lines.push( + '', + '> 演练模式(`dry_run=true`):构建与摘要真实执行,**未调用 GitHub Pages 发布动作、未调用 Cloudflare deploy hook**。', + ); + } + return lines.join('\n'); +} + +/** 渲染完整摘要(Markdown,直接写进 GitHub Actions summary) */ +export function renderBuildSummary(input: BuildSummaryInput): string { + const { context, meta, links, linksExpected, publishing } = input; + return [ + '## 双线重建摘要(hub)', + '', + '同一提交 → 同一份 `dist/` 产物 → 双线发布:GitHub Pages 镜像 + Cloudflare Pages 主站(SPEC §0 / §8.1 / §9.2)。', + '', + '### 本次运行', + '', + renderContext(context), + '', + '### 自动字段刷新结果(§9.2)', + '', + renderMeta(meta), + '', + '### 异常项目清单:archive / 超过 365 天未更新(§6.3 / §9.2)', + '', + renderAnomalies(meta), + '', + '### 链接健康(§9.3)', + '', + renderLinks(links, linksExpected), + '', + '### 双线发布结果(§0 / §9.2)', + '', + renderPublishing(publishing, context), + '', + '---', + '', + '维护者提示:本工作流只构建、发布与出摘要,**不自动改数据、不自动下架、不向 main 写提交**;异常项目与坏链的处置走人工数据 PR。', + '', + ].join('\n'); +} diff --git a/src/lib/link-health.ts b/src/lib/link-health.ts new file mode 100644 index 0000000..7ffa5c3 --- /dev/null +++ b/src/lib/link-health.ts @@ -0,0 +1,374 @@ +/** + * 外链健康检查(SPEC §9.3)。 + * + * 「每日重建时对全部外链做可达性检查并出摘要报告(GitHub Actions summary); + * 连续失败的项目在摘要中点名,是否下架/修正走人工数据 PR,不自动改数据。」 + * + * 与投稿 CI(S2-B 的 `src/lib/submission-checks.ts`)的分工: + * - 投稿 CI:拦新数据(error/warning 分级、可硬拦 PR); + * - 本模块:巡检既有数据(永不硬拦、永不改数据,只出摘要 + 连续失败点名)。 + * 因此这里的严重级别只有「成功 / 失败 / 受限」,且退出码恒为 0(除非数据文件本身非法)。 + * + * 网络与磁盘都在边界上:`runLinkHealth` 注入 fetch 与上一次状态,纯逻辑可单测。 + */ +import { existsSync, readFileSync } from 'node:fs'; +import { z } from 'zod'; + +/** 巡检的外链字段(§9.3「全部外链」:仓库入口 + 数据文件里的全部人工外链) */ +export const LINK_FIELDS = [ + 'repo', + 'homepage', + 'docs_url', + 'deploy.url', + 'deploy.guide_url', +] as const; +export type LinkField = (typeof LINK_FIELDS)[number]; + +export const LINK_HEALTH_STATE_VERSION = 1; +/** 连续失败达到该次数即在摘要中点名(本次 + 上一次都失败 = 2) */ +export const CHRONIC_FAILURE_THRESHOLD = 2; +export const DEFAULT_TIMEOUT_MS = 10_000; +export const DEFAULT_RETRIES = 1; +export const DEFAULT_CONCURRENCY = 6; + +const USER_AGENT = 'workerhub-hub-link-health (+https://hub.oneboy.app)'; + +/** 巡检输入所需的最小项目形状(`ProjectInput` 满足它) */ +export interface LinkSourceProject { + slug: string; + data: { + repo: string; + homepage?: string | undefined; + docs_url?: string | undefined; + deploy: { url?: string | undefined; guide_url?: string | undefined }; + }; +} + +export interface ProjectLinkRef { + slug: string; + field: LinkField; + url: string; +} + +/** 收集全部外链(按项目去重,同一 URL 只查一次由调用方合并) */ +export function collectProjectLinks(projects: readonly LinkSourceProject[]): ProjectLinkRef[] { + const refs: ProjectLinkRef[] = []; + for (const project of projects) { + const { data } = project; + refs.push({ slug: project.slug, field: 'repo', url: `https://github.com/${data.repo}` }); + if (data.homepage) refs.push({ slug: project.slug, field: 'homepage', url: data.homepage }); + if (data.docs_url) refs.push({ slug: project.slug, field: 'docs_url', url: data.docs_url }); + if (data.deploy.url) + refs.push({ slug: project.slug, field: 'deploy.url', url: data.deploy.url }); + if (data.deploy.guide_url) { + refs.push({ slug: project.slug, field: 'deploy.guide_url', url: data.deploy.guide_url }); + } + } + return refs; +} + +export type LinkOutcome = 'ok' | 'failed' | 'blocked'; + +export interface LinkCheckOptions { + /** 便于测试注入 */ + fetchImpl?: typeof fetch; + timeoutMs?: number; + retries?: number; +} + +export interface LinkCheckResult { + url: string; + outcome: LinkOutcome; + /** HTTP 状态码;网络层失败时为 null */ + status: number | null; + detail: string; +} + +const sleep = (ms: number): Promise => new Promise((resolve) => setTimeout(resolve, ms)); + +/** 反爬 / 限流 / 不接受该方法的响应:结论不确定,交人工确认,不算「坏链」 */ +const BLOCKED_STATUSES = new Set([401, 403, 405, 406, 429, 503]); + +/** + * 检查单个外链是否可达。 + * + * - 2xx / 3xx(跟随重定向)→ ok + * - 4xx / 5xx → failed(5xx 与网络错误重试一次) + * - 反爬/限流类状态码 → blocked:只提示人工确认,不计入连续失败 + */ +export async function checkLink( + url: string, + options: LinkCheckOptions = {}, +): Promise { + const fetchImpl = options.fetchImpl ?? fetch; + const timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS; + const retries = Math.max(0, options.retries ?? DEFAULT_RETRIES); + + let lastDetail = ''; + let lastStatus: number | null = null; + + for (let attempt = 0; attempt <= retries; attempt += 1) { + if (attempt > 0) await sleep(300 * attempt); + try { + const response = await fetchImpl(url, { + method: 'GET', + redirect: 'follow', + headers: { 'user-agent': USER_AGENT, accept: 'text/html,application/xhtml+xml' }, + signal: AbortSignal.timeout(timeoutMs), + }); + // 只关心状态码,不下载正文 + await response.body?.cancel(); + + if (response.status < 400) { + return { url, outcome: 'ok', status: response.status, detail: `HTTP ${response.status}` }; + } + if (BLOCKED_STATUSES.has(response.status)) { + return { + url, + outcome: 'blocked', + status: response.status, + detail: `HTTP ${response.status}(疑似反爬/限流,需人工确认)`, + }; + } + lastStatus = response.status; + lastDetail = `HTTP ${response.status}`; + if (response.status < 500) break; // 4xx 是确定性结论,重试无意义 + } catch (error) { + lastStatus = null; + lastDetail = `请求失败:${(error as Error).message}`; + } + } + + return { url, outcome: 'failed', status: lastStatus, detail: lastDetail || '请求失败' }; +} + +// --------------------------------------------------------------------------- +// 连续失败状态(跨运行持久化,CI 侧用 actions/cache 保存,不写入仓库) +// --------------------------------------------------------------------------- + +const linkHealthStateEntrySchema = z.strictObject({ + consecutiveFailures: z.number().int().nonnegative(), + lastOutcome: z.enum(['ok', 'failed', 'blocked']), + lastDetail: z.string(), + lastCheckedAt: z.string(), + lastOkAt: z.string().nullable(), +}); + +export const linkHealthStateSchema = z.strictObject({ + schemaVersion: z.literal(LINK_HEALTH_STATE_VERSION), + links: z.record(z.string(), linkHealthStateEntrySchema), +}); + +export type LinkHealthStateEntry = z.infer; +export type LinkHealthState = z.infer; + +export const emptyLinkHealthState = (): LinkHealthState => ({ + schemaVersion: LINK_HEALTH_STATE_VERSION, + links: {}, +}); + +/** 读取上次状态:缺失 → 空状态;损坏 → 空状态 + 警告(不阻塞巡检) */ +export function readLinkHealthState( + path: string, + warn: (message: string) => void = () => {}, +): LinkHealthState { + if (!existsSync(path)) return emptyLinkHealthState(); + let raw: unknown; + try { + raw = JSON.parse(readFileSync(path, 'utf8')); + } catch (error) { + warn(`链接健康状态文件无法解析(${path}):${(error as Error).message};按空状态处理`); + return emptyLinkHealthState(); + } + const parsed = linkHealthStateSchema.safeParse(raw); + if (!parsed.success) { + warn(`链接健康状态文件 schema 不合法(${path});按空状态处理`); + return emptyLinkHealthState(); + } + return parsed.data; +} + +export function serializeLinkHealthState(state: LinkHealthState): string { + const links: Record = {}; + for (const url of Object.keys(state.links).sort()) links[url] = state.links[url]!; + return `${JSON.stringify({ schemaVersion: LINK_HEALTH_STATE_VERSION, links }, null, 2)}\n`; +} + +// --------------------------------------------------------------------------- +// 巡检与报告 +// --------------------------------------------------------------------------- + +export interface LinkHealthRow { + url: string; + field: LinkField; + slugs: string[]; + outcome: LinkOutcome; + status: number | null; + detail: string; + consecutiveFailures: number; + /** 连续失败达阈值 → 摘要里点名(§9.3) */ + chronic: boolean; +} + +export interface LinkHealthReport { + generatedAt: string; + threshold: number; + totals: { links: number; ok: number; failed: number; blocked: number; chronic: number }; + rows: LinkHealthRow[]; + /** 连续失败点名的项目清单(摘要里逐项列出) */ + chronicFailures: { url: string; slugs: string[]; consecutiveFailures: number; detail: string }[]; + /** 需人工确认(反爬/限流,未计入失败) */ + needsReview: { url: string; slugs: string[]; detail: string }[]; +} + +export interface RunLinkHealthOptions extends LinkCheckOptions { + /** 上次状态(连续失败计数) */ + previous?: LinkHealthState; + concurrency?: number; + threshold?: number; + now?: Date; + warn?: (message: string) => void; +} + +export interface RunLinkHealthResult { + state: LinkHealthState; + report: LinkHealthReport; +} + +/** 逐项巡检全部外链,产出新状态与摘要报告(纯逻辑,网络由 fetchImpl 注入) */ +export async function runLinkHealth( + refs: readonly ProjectLinkRef[], + options: RunLinkHealthOptions = {}, +): Promise { + const now = options.now ?? new Date(); + const checkedAt = now.toISOString(); + const threshold = options.threshold ?? CHRONIC_FAILURE_THRESHOLD; + const concurrency = Math.max(1, options.concurrency ?? DEFAULT_CONCURRENCY); + const previous = options.previous ?? emptyLinkHealthState(); + const warn = options.warn ?? (() => {}); + + // 同一 URL 只查一次,合并引用它的项目 + const byUrl = new Map }>(); + for (const ref of refs) { + const entry = byUrl.get(ref.url) ?? { field: ref.field, slugs: new Set() }; + entry.slugs.add(ref.slug); + byUrl.set(ref.url, entry); + } + const urls = [...byUrl.keys()].sort(); + + const results = new Map(); + for (let index = 0; index < urls.length; index += concurrency) { + const batch = urls.slice(index, index + concurrency); + const batchResults = await Promise.all( + batch.map((url) => + checkLink(url, options).catch((error: unknown): LinkCheckResult => ({ + url, + outcome: 'failed', + status: null, + detail: `请求失败:${(error as Error).message}`, + })), + ), + ); + for (const result of batchResults) results.set(result.url, result); + } + + const state: LinkHealthState = { schemaVersion: LINK_HEALTH_STATE_VERSION, links: {} }; + const rows: LinkHealthRow[] = []; + + for (const url of urls) { + const result = results.get(url)!; + const meta = byUrl.get(url)!; + const prior = previous.links[url]; + const consecutiveFailures = + result.outcome === 'failed' ? (prior?.consecutiveFailures ?? 0) + 1 : 0; + + state.links[url] = { + consecutiveFailures, + lastOutcome: result.outcome, + lastDetail: result.detail, + lastCheckedAt: checkedAt, + lastOkAt: result.outcome === 'ok' ? checkedAt : (prior?.lastOkAt ?? null), + }; + + const chronic = consecutiveFailures >= threshold; + if (chronic) { + warn(`${url} 已连续 ${consecutiveFailures} 次不可达(${result.detail})`); + } + + rows.push({ + url, + field: meta.field, + slugs: [...meta.slugs].sort(), + outcome: result.outcome, + status: result.status, + detail: result.detail, + consecutiveFailures, + chronic, + }); + } + + const count = (outcome: LinkOutcome): number => + rows.filter((row) => row.outcome === outcome).length; + + const report: LinkHealthReport = { + generatedAt: checkedAt, + threshold, + totals: { + links: rows.length, + ok: count('ok'), + failed: count('failed'), + blocked: count('blocked'), + chronic: rows.filter((row) => row.chronic).length, + }, + rows, + chronicFailures: rows + .filter((row) => row.chronic) + .map((row) => ({ + url: row.url, + slugs: row.slugs, + consecutiveFailures: row.consecutiveFailures, + detail: row.detail, + })), + needsReview: rows + .filter((row) => row.outcome === 'blocked') + .map((row) => ({ url: row.url, slugs: row.slugs, detail: row.detail })), + }; + + return { state, report }; +} + +/** 报告 JSON 的解析(CI 跨 job 传文件时用;损坏返回 null,摘要降级显示) */ +export const linkHealthReportSchema = z.strictObject({ + generatedAt: z.string(), + threshold: z.number().int().positive(), + totals: z.strictObject({ + links: z.number().int().nonnegative(), + ok: z.number().int().nonnegative(), + failed: z.number().int().nonnegative(), + blocked: z.number().int().nonnegative(), + chronic: z.number().int().nonnegative(), + }), + rows: z.array( + z.strictObject({ + url: z.string(), + field: z.enum(LINK_FIELDS), + slugs: z.array(z.string()), + outcome: z.enum(['ok', 'failed', 'blocked']), + status: z.number().int().nullable(), + detail: z.string(), + consecutiveFailures: z.number().int().nonnegative(), + chronic: z.boolean(), + }), + ), + chronicFailures: z.array( + z.strictObject({ + url: z.string(), + slugs: z.array(z.string()), + consecutiveFailures: z.number().int().nonnegative(), + detail: z.string(), + }), + ), + needsReview: z.array( + z.strictObject({ url: z.string(), slugs: z.array(z.string()), detail: z.string() }), + ), +}); diff --git a/tests/build-summary.test.ts b/tests/build-summary.test.ts new file mode 100644 index 0000000..6acd1f6 --- /dev/null +++ b/tests/build-summary.test.ts @@ -0,0 +1,160 @@ +/** + * 构建摘要渲染的单测(SPEC §9.2 / §9.3 / §12 第 7 条): + * 摘要必须含自动字段刷新结果、异常项目清单、连续失败点名、两侧独立发布结果。 + */ +import assert from 'node:assert/strict'; +import { test } from 'node:test'; + +import { + describePublishOutcome, + parseLinkHealthReport, + parseMetaReport, + renderBuildSummary, + type BuildSummaryContext, + type MetaReport, +} from '../src/lib/build-summary.js'; +import type { LinkHealthReport } from '../src/lib/link-health.js'; + +const context: BuildSummaryContext = { + event: 'schedule', + ref: 'main', + sha: 'abcdef1234567890abcdef1234567890abcdef12', + version: 'v1.0.0-3-gabcdef1', + generatedAt: '2026-10-27 03:17', + dryRun: false, + simulateFailure: 'none', + runUrl: 'https://github.com/WorkerHub/workerhub.github.io/actions/runs/1', +}; + +const meta: MetaReport = { + generatedAt: '2026-10-27T03:17:00.000Z', + apiBase: 'https://api.github.com', + authenticated: true, + fetchSkipped: false, + cachePath: 'src/data/cache/github-meta.json', + cacheChanged: true, + counts: { repos: 11, fetched: 9, fromCache: 2, degradedToEmpty: 0, dataErrors: 0 }, + projects: [ + { + slug: 'enotify', + repo: 'WorkerHub/enotify', + metaStatus: 'ok', + metaReason: null, + stars: 120, + pushedAt: '2026-10-20T00:00:00Z', + archived: false, + }, + { + slug: 'cloud-mail', + repo: 'maillab/cloud-mail', + metaStatus: 'cached', + metaReason: 'GitHub API 限流(403,remaining=0)', + stars: 14954, + pushedAt: '2026-10-01T00:00:00Z', + archived: false, + }, + ], + anomalies: [{ repo: 'maillab/cloud-mail', reasons: ['超过 365 天未更新(400 天)'] }], + warnings: ['maillab/cloud-mail 自动字段抓取失败(rate-limited)'], +}; + +const links: LinkHealthReport = { + generatedAt: '2026-10-27T03:18:00.000Z', + threshold: 2, + totals: { links: 4, ok: 3, failed: 1, blocked: 0, chronic: 1 }, + rows: [ + { + url: 'https://zeta.oneboy.app', + field: 'homepage', + slugs: ['zeta'], + outcome: 'failed', + status: 502, + detail: 'HTTP 502', + consecutiveFailures: 3, + chronic: true, + }, + ], + chronicFailures: [ + { + url: 'https://zeta.oneboy.app', + slugs: ['zeta'], + consecutiveFailures: 3, + detail: 'HTTP 502', + }, + ], + needsReview: [], +}; + +test('摘要含自动字段刷新结果与异常项目清单(§12 第 7 条)', () => { + const summary = renderBuildSummary({ + context, + meta, + links, + linksExpected: true, + publishing: [ + { side: 'github-pages', result: 'success', detail: '已发布镜像' }, + { side: 'cloudflare-pages', result: 'success', detail: 'deploy hook 已触发(HTTP 200)' }, + ], + }); + + assert.match(summary, /## 双线重建摘要/); + assert.match(summary, /自动字段刷新结果/); + assert.match(summary, /抓取成功 \*\*9\*\*;缓存兜底 \*\*2\*\*/); + assert.match(summary, /异常项目清单/); + assert.match(summary, /maillab\/cloud-mail/); + assert.match(summary, /超过 365 天未更新(400 天)/); + assert.match(summary, /连续失败点名/); + assert.match(summary, /zeta/); + assert.match(summary, /本次有变化/); +}); + +test('一侧失败时摘要逐侧标注并声明独立报错', () => { + const summary = renderBuildSummary({ + context: { ...context, dryRun: true, simulateFailure: 'pages' }, + meta, + links, + linksExpected: true, + publishing: [ + { side: 'github-pages', result: 'failure', detail: '演练注入失败' }, + { side: 'cloudflare-pages', result: 'success', detail: '演练:模拟触发成功' }, + ], + }); + + assert.match(summary, /GitHub Pages 镜像(workerhub\.github\.io) \| ❌ 失败/); + assert.match(summary, /Cloudflare Pages 主站(hub\.oneboy\.app) \| ✅ 成功/); + assert.match(summary, /独立报错/); + assert.match(summary, /未调用 GitHub Pages 发布动作、未调用 Cloudflare deploy hook/); +}); + +test('报告缺失时摘要降级说明,不抛错', () => { + const summary = renderBuildSummary({ + context, + meta: null, + links: null, + linksExpected: false, + publishing: [], + }); + + assert.match(summary, /未取得自动字段抓取报告/); + assert.match(summary, /本次不是每日重建,未跑外链巡检/); + assert.match(summary, /未取得发布结果/); +}); + +test('报告解析对损坏/异构输入返回 null', () => { + assert.equal(parseMetaReport(null), null); + assert.equal(parseMetaReport({ generatedAt: 'x' }), null); + assert.equal(parseLinkHealthReport({ rows: [] }), null); + assert.ok(parseMetaReport(meta)); + assert.ok(parseLinkHealthReport(links)); +}); + +test('describePublishOutcome 区分演练注入失败与真实发布失败', () => { + const drill = { dryRun: true, simulateFailure: 'pages' }; + assert.match(describePublishOutcome('github-pages', 'failure', drill), /演练注入失败/); + assert.match(describePublishOutcome('cloudflare-pages', 'success', drill), /模拟发布成功/); + + const real = { dryRun: false, simulateFailure: 'none' }; + assert.match(describePublishOutcome('github-pages', 'success', real), /已发布/); + assert.match(describePublishOutcome('github-pages', 'failure', real), /发布失败/); + assert.match(describePublishOutcome('cloudflare-pages', 'skipped', real), /未执行/); +}); diff --git a/tests/link-health.test.ts b/tests/link-health.test.ts new file mode 100644 index 0000000..fa99a2f --- /dev/null +++ b/tests/link-health.test.ts @@ -0,0 +1,199 @@ +/** + * 外链健康巡检的单测(SPEC §9.3:只出摘要、连续失败点名、不硬拦、不改数据)。 + * 全部用注入的 fetchImpl,不打真实网络。 + */ +import assert from 'node:assert/strict'; +import { mkdirSync, mkdtempSync, writeFileSync } from 'node:fs'; +import { join } from 'node:path'; +import { test } from 'node:test'; + +import { + CHRONIC_FAILURE_THRESHOLD, + collectProjectLinks, + emptyLinkHealthState, + readLinkHealthState, + runLinkHealth, + serializeLinkHealthState, + type LinkSourceProject, +} from '../src/lib/link-health.js'; + +const TMP_ROOT = join(process.cwd(), 'tests', '.tmp'); +const tmpDir = (): string => { + mkdirSync(TMP_ROOT, { recursive: true }); + return mkdtempSync(join(TMP_ROOT, 'links-')); +}; + +const project = (slug: string, overrides: Partial = {}) => + ({ + slug, + data: { + repo: `WorkerHub/${slug}`, + homepage: `https://${slug}.oneboy.app`, + docs_url: `https://github.com/WorkerHub/${slug}#deploy`, + deploy: { + url: `https://deploy.workers.cloudflare.com/?url=https://github.com/WorkerHub/${slug}`, + }, + ...overrides, + }, + }) satisfies LinkSourceProject; + +const fetchStub = (statuses: Record, fallback = 200): typeof fetch => + (async (input: RequestInfo | URL) => { + const url = typeof input === 'string' ? input : input instanceof URL ? input.href : input.url; + return new Response(null, { status: statuses[url] ?? fallback }); + }) as typeof fetch; + +test('collectProjectLinks 收集仓库入口与数据文件里的全部外链', () => { + const refs = collectProjectLinks([ + project('enotify'), + project('waker', { homepage: undefined, docs_url: undefined, deploy: {} }), + ]); + + assert.deepEqual( + refs.map((ref) => `${ref.slug}:${ref.field}`), + ['enotify:repo', 'enotify:homepage', 'enotify:docs_url', 'enotify:deploy.url', 'waker:repo'], + ); + assert.equal(refs[0]!.url, 'https://github.com/WorkerHub/enotify'); +}); + +test('同一 URL 只检查一次,并合并引用它的项目', async () => { + const shared = 'https://demo.example.org'; + const calls: string[] = []; + const fetchImpl = (async (input: RequestInfo | URL) => { + calls.push(typeof input === 'string' ? input : input instanceof URL ? input.href : input.url); + return new Response(null, { status: 200 }); + }) as typeof fetch; + + const { report } = await runLinkHealth( + [ + { slug: 'alpha', field: 'homepage', url: shared }, + { slug: 'beta', field: 'homepage', url: shared }, + ], + { fetchImpl }, + ); + + assert.deepEqual(calls, [shared]); + assert.equal(report.totals.links, 1); + assert.deepEqual(report.rows[0]!.slugs, ['alpha', 'beta']); +}); + +test('连续失败累计到阈值后点名,恢复可达后计数清零', async () => { + const bad = 'https://broken.example.org'; + const good = 'https://ok.example.org'; + const refs = [ + { slug: 'alpha', field: 'homepage' as const, url: bad }, + { slug: 'beta', field: 'homepage' as const, url: good }, + ]; + + const first = await runLinkHealth(refs, { + fetchImpl: fetchStub({ [bad]: 404 }), + previous: emptyLinkHealthState(), + }); + assert.equal(first.report.totals.failed, 1); + assert.equal(first.report.totals.chronic, 0, '首次失败不点名'); + assert.equal(first.state.links[bad]!.consecutiveFailures, 1); + assert.equal(first.report.rows.find((row) => row.url === bad)!.chronic, false); + + const second = await runLinkHealth(refs, { + fetchImpl: fetchStub({ [bad]: 404 }), + previous: first.state, + }); + assert.equal(second.state.links[bad]!.consecutiveFailures, CHRONIC_FAILURE_THRESHOLD); + assert.equal(second.report.totals.chronic, 1); + assert.deepEqual(second.report.chronicFailures[0]!.slugs, ['alpha']); + + const recovered = await runLinkHealth(refs, { + fetchImpl: fetchStub({}), + previous: second.state, + }); + assert.equal(recovered.state.links[bad]!.consecutiveFailures, 0); + assert.equal(recovered.report.totals.chronic, 0); + assert.equal(recovered.report.totals.ok, 2); + assert.ok(recovered.state.links[bad]!.lastOkAt, '恢复后记录最近可达时间'); +}); + +test('反爬/限流类状态码归入「需人工确认」,不计入连续失败', async () => { + const limited = 'https://protected.example.org'; + const { report, state } = await runLinkHealth( + [{ slug: 'alpha', field: 'homepage', url: limited }], + { + fetchImpl: fetchStub({ [limited]: 403 }), + previous: emptyLinkHealthState(), + }, + ); + + assert.equal(report.totals.blocked, 1); + assert.equal(report.totals.failed, 0); + assert.equal(report.totals.chronic, 0); + assert.equal(state.links[limited]!.consecutiveFailures, 0); + assert.deepEqual( + report.needsReview.map((item) => item.url), + [limited], + ); +}); + +test('网络异常不会让巡检抛错,而是记为失败', async () => { + const down = 'https://unreachable.example.org'; + const fetchImpl = (async () => { + throw new Error('ECONNREFUSED'); + }) as typeof fetch; + + const { report } = await runLinkHealth([{ slug: 'alpha', field: 'homepage', url: down }], { + fetchImpl, + retries: 0, + }); + + assert.equal(report.totals.failed, 1); + assert.match(report.rows[0]!.detail, /ECONNREFUSED/); +}); + +test('状态文件缺失或损坏时按空状态处理并告警,不阻塞巡检', () => { + const dir = tmpDir(); + const missing = join(dir, 'nope.json'); + const warnings: string[] = []; + assert.deepEqual( + readLinkHealthState(missing, (message) => warnings.push(message)), + { + schemaVersion: 1, + links: {}, + }, + ); + assert.equal(warnings.length, 0); + + const corrupt = join(dir, 'corrupt.json'); + writeFileSync(corrupt, '{ not json', 'utf8'); + assert.deepEqual( + readLinkHealthState(corrupt, (message) => warnings.push(message)), + { + schemaVersion: 1, + links: {}, + }, + ); + assert.equal(warnings.length, 1); +}); + +test('状态序列化稳定(键排序,便于跨运行比对)', () => { + const state = { + schemaVersion: 1 as const, + links: { + 'https://b.example.org': { + consecutiveFailures: 2, + lastOutcome: 'failed' as const, + lastDetail: 'HTTP 404', + lastCheckedAt: '2026-10-26T00:00:00.000Z', + lastOkAt: null, + }, + 'https://a.example.org': { + consecutiveFailures: 0, + lastOutcome: 'ok' as const, + lastDetail: 'HTTP 200', + lastCheckedAt: '2026-10-26T00:00:00.000Z', + lastOkAt: '2026-10-26T00:00:00.000Z', + }, + }, + }; + + const text = serializeLinkHealthState(state); + assert.ok(text.indexOf('a.example.org') < text.indexOf('b.example.org')); + assert.deepEqual(JSON.parse(text), state); +});