Forráskód Böngészése

【初始】初始化项目基础结构与核心功能

新增 Cargo.toml 项目配置,引入 tokio、hyper 等依赖,
搭建系统监控网页服务基本框架。

新增模块包括:
- `src/cache.rs`: 实现无锁系统统计缓存机制
- `src/server.rs`: 构建高性能 HTTP 服务器及路由处理
- `src/stats.rs`: 收集并定义系统资源使用数据结构
- `src/lib.rs`: 导出公共接口,组织模块结构
- `src/main.rs`: 主程序入口,解析命令行参数并启动服务

支持通过 / 路由查看实时资源占用情况,/health 路由进行健康检查,
具备高并发、低延迟特性,适用于嵌入式设备监控场景。
PJ568 1 éve
commit
f5f0998188

+ 37 - 0
.dockerignore

@@ -0,0 +1,37 @@
+# Git
+.git
+.gitignore
+
+# Rust
+target/
+Cargo.lock
+**/*.rs.bk
+
+# IDE
+.vscode/
+.idea/
+*.swp
+*.swo
+
+# OS
+.DS_Store
+Thumbs.db
+
+# Documentation
+docs/
+*.md
+
+# Scripts (not needed in container)
+scripts/
+
+# Tests
+tests/
+benches/
+
+# CI/CD
+.github/
+
+# Docker
+Dockerfile*
+docker-compose*.yml
+.dockerignore

+ 49 - 0
.github/workflows/checks.yml

@@ -0,0 +1,49 @@
+name: Checks
+
+on:
+  workflow_dispatch:
+  workflow_call:
+
+jobs:
+  checks:
+    runs-on: ubuntu-latest
+    steps:
+      - name: Checkout
+        uses: actions/checkout@v4
+
+      - name: Setup Rust
+        uses: MatteoH2O1999/setup-rust@v1
+
+      - name: Cache Rust dependencies
+        uses: Swatinem/rust-cache@v2
+
+      - name: Check code formatting
+        run: |
+          rustup component add rustfmt
+          cargo fmt --all -- --check
+
+      - name: Check project
+        run: cargo check --all-targets
+
+      - name: Clippy project
+        run: |
+          rustup component add clippy
+          cargo clippy --all-targets -- -D warnings
+
+      - name: Test project
+        run: cargo test --all-targets
+
+      # - name: Install cargo-audit
+      #   run: cargo install cargo-audit
+      # - name: Audit dependencies for vulnerabilities
+      #   run: cargo audit
+
+      # - name: Install cargo-deny
+      #   run: cargo install cargo-deny
+      # - name: Check bans, licenses, and advisories with cargo-deny
+      #   run: cargo deny check
+
+      - name: Check documentation
+        run: cargo doc --no-deps --document-private-items
+        env:
+          RUSTDOCFLAGS: -D warnings

+ 46 - 0
.github/workflows/docker.yml.bak

@@ -0,0 +1,46 @@
+name: Docker
+
+on:
+  push:
+    tags:
+      - 'v*'
+  workflow_dispatch:
+
+jobs:
+  docker:
+    runs-on: ubuntu-latest
+    steps:
+      - name: Checkout
+        uses: actions/checkout@v4
+
+      - name: Set up Docker Buildx
+        uses: docker/setup-buildx-action@v3
+
+      - name: Login to Docker Hub
+        if: github.event_name != 'pull_request'
+        uses: docker/login-action@v3
+        with:
+          username: ${{ secrets.DOCKER_USERNAME }}
+          password: ${{ secrets.DOCKER_PASSWORD }}
+
+      - name: Extract metadata
+        id: meta
+        uses: docker/metadata-action@v5
+        with:
+          images: your-username/swb-sys-monitor
+          tags: |
+            type=ref,event=branch
+            type=ref,event=pr
+            type=semver,pattern={{version}}
+            type=semver,pattern={{major}}.{{minor}}
+
+      - name: Build and push
+        uses: docker/build-push-action@v5
+        with:
+          context: .
+          platforms: linux/amd64,linux/arm64
+          push: ${{ github.event_name != 'pull_request' }}
+          tags: ${{ steps.meta.outputs.tags }}
+          labels: ${{ steps.meta.outputs.labels }}
+          cache-from: type=gha
+          cache-to: type=gha,mode=max

+ 12 - 0
.github/workflows/pull_request.yml

@@ -0,0 +1,12 @@
+name: pull_request
+
+on:
+  workflow_dispatch:
+  pull_request:
+    branches:
+      - master
+
+jobs:
+  checks:
+    name: Checks
+    uses: ./.github/workflows/checks.yml

+ 97 - 0
.github/workflows/release.yml

@@ -0,0 +1,97 @@
+name: release
+
+on:
+  workflow_dispatch:
+  push:
+    branches:
+      - master
+
+jobs:
+  checks:
+    name: Checks
+    uses: ./.github/workflows/checks.yml
+  release:
+    runs-on: ubuntu-latest
+    permissions: write-all
+    name: Release
+    steps:
+      - name: Checkout
+        uses: actions/checkout@v4
+        with:
+          fetch-depth: 0
+
+      - name: Check version
+        id: version-check
+        run: |
+          VERSION=$(./scripts/is-newer-version.bash)
+          echo "version=${VERSION}" >> $GITHUB_OUTPUT
+          if [ "$VERSION" != "0" ]; then
+            echo "New version detected: $VERSION"
+          else
+            echo "No new version to release"
+          fi
+
+      - name: Push tag
+        if: steps.version-check.outputs.version != '0'
+        id: push-tag
+        run: |
+          tag="v${{ steps.version-check.outputs.version }}"
+          git config user.name "${GITHUB_ACTOR}"
+          git config user.email "${GITHUB_ACTOR}@users.noreply.github.com"
+          git tag -a "${tag}" -m "Release ${tag}"
+          git push origin "${tag}"
+          echo "tag_name=${tag}" >> $GITHUB_OUTPUT
+
+      - name: Checkout
+        if: steps.version-check.outputs.version != '0'
+        uses: actions/checkout@v4
+
+      - name: Setup Rust
+        if: steps.version-check.outputs.version != '0'
+        uses: MatteoH2O1999/setup-rust@v1
+
+      - name: Cache Rust dependencies
+        if: steps.version-check.outputs.version != '0'
+        uses: Swatinem/rust-cache@v2
+        with:
+          cache-on-failure: "true"
+
+      - name: Build project
+        if: steps.version-check.outputs.version != '0'
+        run: cargo build --release
+        shell: bash
+
+      - name: Create release
+        if: steps.version-check.outputs.version != '0'
+        uses: ncipollo/release-action@v1
+        with:
+          generateReleaseNotes: true
+          tag: "v${{ steps.version-check.outputs.version }}"
+          artifacts: "./target/release/swb-sys-monitor"
+
+      - name: Publish project
+        if: steps.version-check.outputs.version != '0'
+        run: |
+          ./scripts/publish-crates-io.bash -n ${{ secrets.CRATES_IO_TOKEN }}  # Dry run check
+          ./scripts/publish-crates-io.bash -y ${{ secrets.CRATES_IO_TOKEN }}  # Actual publish with auto-confirm
+        shell: bash
+
+      # - name: Setup Pages
+      #   uses: actions/configure-pages@v4
+
+      # - name: Upload artifact
+      #   uses: actions/upload-pages-artifact@v3
+      #   with:
+      #     path: ""
+
+      # - name: Deploy to GitHub Pages
+      #   id: deployment
+      #   uses: actions/deploy-pages@v4
+
+      - name: Delete tag if failure or cancelled
+        if: (cancelled() || failure()) && steps.push-tag.outputs.tag_name != ''
+        run: |
+          git config user.name "${GITHUB_ACTOR}"
+          git config user.email "${GITHUB_ACTOR}@users.noreply.github.com"
+          git push --delete origin "${{ steps.push-tag.outputs.tag_name }}"
+          git tag -d "${{ steps.push-tag.outputs.tag_name }}"

+ 4 - 0
.gitignore

@@ -0,0 +1,4 @@
+/target
+
+AGENTS.md
+QWEN.md

+ 36 - 0
CONTRIBUTING.md

@@ -0,0 +1,36 @@
+# 贡献指北
+
+## 项目版本管理
+
+我们使用[语义化版本](https://semver.org/lang/zh-CN/)进行版本管理。
+任何对代码库的更改都不应使用现有版本发布。
+
+## 提交信息格式
+
+提交信息应遵循 [PJ568 提交说明规范](https://github.com/PJ-568/git-commit-regulation)。
+
+## 提交更改
+
+1. Fork 此仓库,在您的仓库新建一个基于此仓库默认分支(branch)的分支。
+2. 在该新建分支对项目进行更改,确保语法不存在问题后应用更改您的仓库。
+3. 向我们的仓库提交拉取请求。请确保您遵循了上述说明。
+4. 我们将定期审查拉取请求,并告知您我们的问题以及在合并您的拉取请求之前需要进行的任何更改。
+5. 我们希望您在 15 日内作出回应,之后如果没有显示活动,您的拉取请求可能会被关闭。
+
+### 参考流程
+
+1. Fork 源码,下载到本地并运行项目;
+2. 添加或修改代码;
+3. 配置 rust 环境并运行 `cargo fmt && cargo clippy` 命令以确保代码格式正确;
+4. 对相关改动进行全面的测试:`cargo test`;
+5. 运行 `cargo bench` 命令,确认性能检测达标;
+6. 确认无误后提交修改到 Github;
+7. 提交 Pull Request。
+
+### 注意事项
+
+- 单次 Pull Request 不应提交过多修改,请确保每次提交都针对特定的功能且务必说明本次改动的具体目的,例如:修复某 bug 、优化某方法 等,方便进行 Code Review;
+- 对于 bug 的修复,应该将本次 Pull Request 和相对应 bug 的 issue 关联起来,让别人知道该问题已经被修复;
+- 对于较大的新功能,你需要先提交 Issues,例如 “【新增】添加 XXX 功能”,确认该功能有被添加的必要后,再开始工作;
+- 对于一些主观的样式、交互逻辑调整:如颜色、图标的使用,某些预设配置的增减修改等,一般不予通过。但可以在 Discussions 中进行讨论;
+- 其他如简单的代码优化、文档修正等,只要修改合理都会被接受。

+ 1372 - 0
Cargo.lock

@@ -0,0 +1,1372 @@
+# This file is automatically @generated by Cargo.
+# It is not intended for manual editing.
+version = 4
+
+[[package]]
+name = "addr2line"
+version = "0.25.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "1b5d307320b3181d6d7954e663bd7c774a838b8220fe0593c86d9fb09f498b4b"
+dependencies = [
+ "gimli",
+]
+
+[[package]]
+name = "adler2"
+version = "2.0.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "320119579fcad9c21884f5c4861d16174d0e06250625266f50fe6898340abefa"
+
+[[package]]
+name = "aho-corasick"
+version = "1.1.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "8e60d3430d3a69478ad0993f19238d2df97c507009a52b3c10addcd7f6bcb916"
+dependencies = [
+ "memchr",
+]
+
+[[package]]
+name = "anes"
+version = "0.1.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "4b46cbb362ab8752921c97e041f5e366ee6297bd428a31275b9fcf1e380f7299"
+
+[[package]]
+name = "anstream"
+version = "0.6.21"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "43d5b281e737544384e969a5ccad3f1cdd24b48086a0fc1b2a5262a26b8f4f4a"
+dependencies = [
+ "anstyle",
+ "anstyle-parse",
+ "anstyle-query",
+ "anstyle-wincon",
+ "colorchoice",
+ "is_terminal_polyfill",
+ "utf8parse",
+]
+
+[[package]]
+name = "anstyle"
+version = "1.0.13"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "5192cca8006f1fd4f7237516f40fa183bb07f8fbdfedaa0036de5ea9b0b45e78"
+
+[[package]]
+name = "anstyle-parse"
+version = "0.2.7"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "4e7644824f0aa2c7b9384579234ef10eb7efb6a0deb83f9630a49594dd9c15c2"
+dependencies = [
+ "utf8parse",
+]
+
+[[package]]
+name = "anstyle-query"
+version = "1.1.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "9e231f6134f61b71076a3eab506c379d4f36122f2af15a9ff04415ea4c3339e2"
+dependencies = [
+ "windows-sys 0.60.2",
+]
+
+[[package]]
+name = "anstyle-wincon"
+version = "3.0.10"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "3e0633414522a32ffaac8ac6cc8f748e090c5717661fddeea04219e2344f5f2a"
+dependencies = [
+ "anstyle",
+ "once_cell_polyfill",
+ "windows-sys 0.60.2",
+]
+
+[[package]]
+name = "anyhow"
+version = "1.0.100"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "a23eb6b1614318a8071c9b2521f36b424b2c83db5eb3a0fead4a6c0809af6e61"
+
+[[package]]
+name = "async-stream"
+version = "0.3.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "0b5a71a6f37880a80d1d7f19efd781e4b5de42c88f0722cc13bcb6cc2cfe8476"
+dependencies = [
+ "async-stream-impl",
+ "futures-core",
+ "pin-project-lite",
+]
+
+[[package]]
+name = "async-stream-impl"
+version = "0.3.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "c7c24de15d275a1ecfd47a380fb4d5ec9bfe0933f309ed5e705b775596a3574d"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn",
+]
+
+[[package]]
+name = "autocfg"
+version = "1.5.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "c08606f8c3cbf4ce6ec8e28fb0014a2c086708fe954eaa885384a6165172e7e8"
+
+[[package]]
+name = "backtrace"
+version = "0.3.76"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "bb531853791a215d7c62a30daf0dde835f381ab5de4589cfe7c649d2cbe92bd6"
+dependencies = [
+ "addr2line",
+ "cfg-if",
+ "libc",
+ "miniz_oxide",
+ "object",
+ "rustc-demangle",
+ "windows-link",
+]
+
+[[package]]
+name = "bitflags"
+version = "2.9.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "2261d10cca569e4643e526d8dc2e62e433cc8aba21ab764233731f8d369bf394"
+
+[[package]]
+name = "bumpalo"
+version = "3.19.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "46c5e41b57b8bba42a04676d81cb89e9ee8e859a1a66f80a5a72e1cb76b34d43"
+
+[[package]]
+name = "bytes"
+version = "1.10.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d71b6127be86fdcfddb610f7182ac57211d4b18a3e9c82eb2d17662f2227ad6a"
+
+[[package]]
+name = "cast"
+version = "0.3.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "37b2a672a2cb129a2e41c10b1224bb368f9f37a2b16b612598138befd7b37eb5"
+
+[[package]]
+name = "cfg-if"
+version = "1.0.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "2fd1289c04a9ea8cb22300a459a72a385d7c73d3259e2ed7dcb2af674838cfa9"
+
+[[package]]
+name = "ciborium"
+version = "0.2.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "42e69ffd6f0917f5c029256a24d0161db17cea3997d185db0d35926308770f0e"
+dependencies = [
+ "ciborium-io",
+ "ciborium-ll",
+ "serde",
+]
+
+[[package]]
+name = "ciborium-io"
+version = "0.2.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "05afea1e0a06c9be33d539b876f1ce3692f4afea2cb41f740e7743225ed1c757"
+
+[[package]]
+name = "ciborium-ll"
+version = "0.2.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "57663b653d948a338bfb3eeba9bb2fd5fcfaecb9e199e87e1eda4d9e8b240fd9"
+dependencies = [
+ "ciborium-io",
+ "half",
+]
+
+[[package]]
+name = "clap"
+version = "4.5.48"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "e2134bb3ea021b78629caa971416385309e0131b351b25e01dc16fb54e1b5fae"
+dependencies = [
+ "clap_builder",
+ "clap_derive",
+]
+
+[[package]]
+name = "clap_builder"
+version = "4.5.48"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "c2ba64afa3c0a6df7fa517765e31314e983f51dda798ffba27b988194fb65dc9"
+dependencies = [
+ "anstream",
+ "anstyle",
+ "clap_lex",
+ "strsim",
+]
+
+[[package]]
+name = "clap_derive"
+version = "4.5.47"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "bbfd7eae0b0f1a6e63d4b13c9c478de77c2eb546fba158ad50b4203dc24b9f9c"
+dependencies = [
+ "heck",
+ "proc-macro2",
+ "quote",
+ "syn",
+]
+
+[[package]]
+name = "clap_lex"
+version = "0.7.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b94f61472cee1439c0b966b47e3aca9ae07e45d070759512cd390ea2bebc6675"
+
+[[package]]
+name = "colorchoice"
+version = "1.0.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b05b61dc5112cbb17e4b6cd61790d9845d13888356391624cbe7e41efeac1e75"
+
+[[package]]
+name = "criterion"
+version = "0.5.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f2b12d017a929603d80db1831cd3a24082f8137ce19c69e6447f54f5fc8d692f"
+dependencies = [
+ "anes",
+ "cast",
+ "ciborium",
+ "clap",
+ "criterion-plot",
+ "is-terminal",
+ "itertools",
+ "num-traits",
+ "once_cell",
+ "oorandom",
+ "plotters",
+ "rayon",
+ "regex",
+ "serde",
+ "serde_derive",
+ "serde_json",
+ "tinytemplate",
+ "walkdir",
+]
+
+[[package]]
+name = "criterion-plot"
+version = "0.5.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "6b50826342786a51a89e2da3a28f1c32b06e387201bc2d19791f622c673706b1"
+dependencies = [
+ "cast",
+ "itertools",
+]
+
+[[package]]
+name = "crossbeam-deque"
+version = "0.8.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "9dd111b7b7f7d55b72c0a6ae361660ee5853c9af73f70c3c2ef6858b950e2e51"
+dependencies = [
+ "crossbeam-epoch",
+ "crossbeam-utils",
+]
+
+[[package]]
+name = "crossbeam-epoch"
+version = "0.9.18"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "5b82ac4a3c2ca9c3460964f020e1402edd5753411d7737aa39c3714ad1b5420e"
+dependencies = [
+ "crossbeam-utils",
+]
+
+[[package]]
+name = "crossbeam-utils"
+version = "0.8.21"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d0a5c400df2834b80a4c3327b3aad3a4c4cd4de0629063962b03235697506a28"
+
+[[package]]
+name = "crunchy"
+version = "0.2.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "460fbee9c2c2f33933d720630a6a0bac33ba7053db5344fac858d4b8952d77d5"
+
+[[package]]
+name = "either"
+version = "1.15.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "48c757948c5ede0e46177b7add2e67155f70e33c07fea8284df6576da70b3719"
+
+[[package]]
+name = "env_filter"
+version = "0.1.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "186e05a59d4c50738528153b83b0b0194d3a29507dfec16eccd4b342903397d0"
+dependencies = [
+ "log",
+ "regex",
+]
+
+[[package]]
+name = "env_logger"
+version = "0.11.8"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "13c863f0904021b108aa8b2f55046443e6b1ebde8fd4a15c399893aae4fa069f"
+dependencies = [
+ "anstream",
+ "anstyle",
+ "env_filter",
+ "jiff",
+ "log",
+]
+
+[[package]]
+name = "equivalent"
+version = "1.0.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "877a4ace8713b0bcf2a4e7eec82529c029f1d0619886d18145fea96c3ffe5c0f"
+
+[[package]]
+name = "fnv"
+version = "1.0.7"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "3f9eec918d3f24069decb9af1554cad7c880e2da24a9afd88aca000531ab82c1"
+
+[[package]]
+name = "futures-channel"
+version = "0.3.31"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "2dff15bf788c671c1934e366d07e30c1814a8ef514e1af724a602e8a2fbe1b10"
+dependencies = [
+ "futures-core",
+]
+
+[[package]]
+name = "futures-core"
+version = "0.3.31"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "05f29059c0c2090612e8d742178b0580d2dc940c837851ad723096f87af6663e"
+
+[[package]]
+name = "futures-sink"
+version = "0.3.31"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "e575fab7d1e0dcb8d0c7bcf9a63ee213816ab51902e6d244a95819acacf1d4f7"
+
+[[package]]
+name = "futures-task"
+version = "0.3.31"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f90f7dce0722e95104fcb095585910c0977252f286e354b5e3bd38902cd99988"
+
+[[package]]
+name = "futures-util"
+version = "0.3.31"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "9fa08315bb612088cc391249efdc3bc77536f16c91f6cf495e6fbe85b20a4a81"
+dependencies = [
+ "futures-core",
+ "futures-task",
+ "pin-project-lite",
+ "pin-utils",
+]
+
+[[package]]
+name = "gimli"
+version = "0.32.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "e629b9b98ef3dd8afe6ca2bd0f89306cec16d43d907889945bc5d6687f2f13c7"
+
+[[package]]
+name = "h2"
+version = "0.3.27"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "0beca50380b1fc32983fc1cb4587bfa4bb9e78fc259aad4a0032d2080309222d"
+dependencies = [
+ "bytes",
+ "fnv",
+ "futures-core",
+ "futures-sink",
+ "futures-util",
+ "http",
+ "indexmap",
+ "slab",
+ "tokio",
+ "tokio-util",
+ "tracing",
+]
+
+[[package]]
+name = "half"
+version = "2.7.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "e54c115d4f30f52c67202f079c5f9d8b49db4691f460fdb0b4c2e838261b2ba5"
+dependencies = [
+ "cfg-if",
+ "crunchy",
+ "zerocopy",
+]
+
+[[package]]
+name = "hashbrown"
+version = "0.16.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "5419bdc4f6a9207fbeba6d11b604d481addf78ecd10c11ad51e76c2f6482748d"
+
+[[package]]
+name = "heck"
+version = "0.5.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea"
+
+[[package]]
+name = "hermit-abi"
+version = "0.5.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "fc0fef456e4baa96da950455cd02c081ca953b141298e41db3fc7e36b1da849c"
+
+[[package]]
+name = "http"
+version = "0.2.12"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "601cbb57e577e2f5ef5be8e7b83f0f63994f25aa94d673e54a92d5c516d101f1"
+dependencies = [
+ "bytes",
+ "fnv",
+ "itoa",
+]
+
+[[package]]
+name = "http-body"
+version = "0.4.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "7ceab25649e9960c0311ea418d17bee82c0dcec1bd053b5f9a66e265a693bed2"
+dependencies = [
+ "bytes",
+ "http",
+ "pin-project-lite",
+]
+
+[[package]]
+name = "httparse"
+version = "1.10.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "6dbf3de79e51f3d586ab4cb9d5c3e2c14aa28ed23d180cf89b4df0454a69cc87"
+
+[[package]]
+name = "httpdate"
+version = "1.0.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "df3b46402a9d5adb4c86a0cf463f42e19994e3ee891101b1841f30a545cb49a9"
+
+[[package]]
+name = "hyper"
+version = "0.14.32"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "41dfc780fdec9373c01bae43289ea34c972e40ee3c9f6b3c8801a35f35586ce7"
+dependencies = [
+ "bytes",
+ "futures-channel",
+ "futures-core",
+ "futures-util",
+ "h2",
+ "http",
+ "http-body",
+ "httparse",
+ "httpdate",
+ "itoa",
+ "pin-project-lite",
+ "socket2 0.5.10",
+ "tokio",
+ "tower-service",
+ "tracing",
+ "want",
+]
+
+[[package]]
+name = "indexmap"
+version = "2.11.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "4b0f83760fb341a774ed326568e19f5a863af4a952def8c39f9ab92fd95b88e5"
+dependencies = [
+ "equivalent",
+ "hashbrown",
+]
+
+[[package]]
+name = "io-uring"
+version = "0.7.10"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "046fa2d4d00aea763528b4950358d0ead425372445dc8ff86312b3c69ff7727b"
+dependencies = [
+ "bitflags",
+ "cfg-if",
+ "libc",
+]
+
+[[package]]
+name = "is-terminal"
+version = "0.4.16"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "e04d7f318608d35d4b61ddd75cbdaee86b023ebe2bd5a66ee0915f0bf93095a9"
+dependencies = [
+ "hermit-abi",
+ "libc",
+ "windows-sys 0.59.0",
+]
+
+[[package]]
+name = "is_terminal_polyfill"
+version = "1.70.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "7943c866cc5cd64cbc25b2e01621d07fa8eb2a1a23160ee81ce38704e97b8ecf"
+
+[[package]]
+name = "itertools"
+version = "0.10.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b0fd2260e829bddf4cb6ea802289de2f86d6a7a690192fbe91b3f46e0f2c8473"
+dependencies = [
+ "either",
+]
+
+[[package]]
+name = "itoa"
+version = "1.0.15"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "4a5f13b858c8d314ee3e8f639011f7ccefe71f97f96e50151fb991f267928e2c"
+
+[[package]]
+name = "jiff"
+version = "0.2.15"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "be1f93b8b1eb69c77f24bbb0afdf66f54b632ee39af40ca21c4365a1d7347e49"
+dependencies = [
+ "jiff-static",
+ "log",
+ "portable-atomic",
+ "portable-atomic-util",
+ "serde",
+]
+
+[[package]]
+name = "jiff-static"
+version = "0.2.15"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "03343451ff899767262ec32146f6d559dd759fdadf42ff0e227c7c48f72594b4"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn",
+]
+
+[[package]]
+name = "js-sys"
+version = "0.3.81"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ec48937a97411dcb524a265206ccd4c90bb711fca92b2792c407f268825b9305"
+dependencies = [
+ "once_cell",
+ "wasm-bindgen",
+]
+
+[[package]]
+name = "libc"
+version = "0.2.176"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "58f929b4d672ea937a23a1ab494143d968337a5f47e56d0815df1e0890ddf174"
+
+[[package]]
+name = "lock_api"
+version = "0.4.14"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "224399e74b87b5f3557511d98dff8b14089b3dadafcab6bb93eab67d3aace965"
+dependencies = [
+ "scopeguard",
+]
+
+[[package]]
+name = "log"
+version = "0.4.28"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "34080505efa8e45a4b816c349525ebe327ceaa8559756f0356cba97ef3bf7432"
+
+[[package]]
+name = "memchr"
+version = "2.7.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f52b00d39961fc5b2736ea853c9cc86238e165017a493d1d5c8eac6bdc4cc273"
+
+[[package]]
+name = "miniz_oxide"
+version = "0.8.9"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "1fa76a2c86f704bdb222d66965fb3d63269ce38518b83cb0575fca855ebb6316"
+dependencies = [
+ "adler2",
+]
+
+[[package]]
+name = "mio"
+version = "1.0.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "78bed444cc8a2160f01cbcf811ef18cac863ad68ae8ca62092e8db51d51c761c"
+dependencies = [
+ "libc",
+ "wasi",
+ "windows-sys 0.59.0",
+]
+
+[[package]]
+name = "num-traits"
+version = "0.2.19"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "071dfc062690e90b734c0b2273ce72ad0ffa95f0c74596bc250dcfd960262841"
+dependencies = [
+ "autocfg",
+]
+
+[[package]]
+name = "object"
+version = "0.37.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ff76201f031d8863c38aa7f905eca4f53abbfa15f609db4277d44cd8938f33fe"
+dependencies = [
+ "memchr",
+]
+
+[[package]]
+name = "once_cell"
+version = "1.21.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "42f5e15c9953c5e4ccceeb2e7382a716482c34515315f7b03532b8b4e8393d2d"
+
+[[package]]
+name = "once_cell_polyfill"
+version = "1.70.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "a4895175b425cb1f87721b59f0f286c2092bd4af812243672510e1ac53e2e0ad"
+
+[[package]]
+name = "oorandom"
+version = "11.1.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d6790f58c7ff633d8771f42965289203411a5e5c68388703c06e14f24770b41e"
+
+[[package]]
+name = "parking_lot"
+version = "0.12.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "93857453250e3077bd71ff98b6a65ea6621a19bb0f559a85248955ac12c45a1a"
+dependencies = [
+ "lock_api",
+ "parking_lot_core",
+]
+
+[[package]]
+name = "parking_lot_core"
+version = "0.9.12"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "2621685985a2ebf1c516881c026032ac7deafcda1a2c9b7850dc81e3dfcb64c1"
+dependencies = [
+ "cfg-if",
+ "libc",
+ "redox_syscall",
+ "smallvec",
+ "windows-link",
+]
+
+[[package]]
+name = "pin-project-lite"
+version = "0.2.16"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "3b3cff922bd51709b605d9ead9aa71031d81447142d828eb4a6eba76fe619f9b"
+
+[[package]]
+name = "pin-utils"
+version = "0.1.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "8b870d8c151b6f2fb93e84a13146138f05d02ed11c7e7c54f8826aaaf7c9f184"
+
+[[package]]
+name = "plotters"
+version = "0.3.7"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "5aeb6f403d7a4911efb1e33402027fc44f29b5bf6def3effcc22d7bb75f2b747"
+dependencies = [
+ "num-traits",
+ "plotters-backend",
+ "plotters-svg",
+ "wasm-bindgen",
+ "web-sys",
+]
+
+[[package]]
+name = "plotters-backend"
+version = "0.3.7"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "df42e13c12958a16b3f7f4386b9ab1f3e7933914ecea48da7139435263a4172a"
+
+[[package]]
+name = "plotters-svg"
+version = "0.3.7"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "51bae2ac328883f7acdfea3d66a7c35751187f870bc81f94563733a154d7a670"
+dependencies = [
+ "plotters-backend",
+]
+
+[[package]]
+name = "portable-atomic"
+version = "1.11.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f84267b20a16ea918e43c6a88433c2d54fa145c92a811b5b047ccbe153674483"
+
+[[package]]
+name = "portable-atomic-util"
+version = "0.2.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d8a2f0d8d040d7848a709caf78912debcc3f33ee4b3cac47d73d1e1069e83507"
+dependencies = [
+ "portable-atomic",
+]
+
+[[package]]
+name = "proc-macro2"
+version = "1.0.101"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "89ae43fd86e4158d6db51ad8e2b80f313af9cc74f5c0e03ccb87de09998732de"
+dependencies = [
+ "unicode-ident",
+]
+
+[[package]]
+name = "quote"
+version = "1.0.41"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ce25767e7b499d1b604768e7cde645d14cc8584231ea6b295e9c9eb22c02e1d1"
+dependencies = [
+ "proc-macro2",
+]
+
+[[package]]
+name = "rayon"
+version = "1.11.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "368f01d005bf8fd9b1206fb6fa653e6c4a81ceb1466406b81792d87c5677a58f"
+dependencies = [
+ "either",
+ "rayon-core",
+]
+
+[[package]]
+name = "rayon-core"
+version = "1.13.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "22e18b0f0062d30d4230b2e85ff77fdfe4326feb054b9783a3460d8435c8ab91"
+dependencies = [
+ "crossbeam-deque",
+ "crossbeam-utils",
+]
+
+[[package]]
+name = "redox_syscall"
+version = "0.5.18"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ed2bf2547551a7053d6fdfafda3f938979645c44812fbfcda098faae3f1a362d"
+dependencies = [
+ "bitflags",
+]
+
+[[package]]
+name = "regex"
+version = "1.11.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "8b5288124840bee7b386bc413c487869b360b2b4ec421ea56425128692f2a82c"
+dependencies = [
+ "aho-corasick",
+ "memchr",
+ "regex-automata",
+ "regex-syntax",
+]
+
+[[package]]
+name = "regex-automata"
+version = "0.4.11"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "833eb9ce86d40ef33cb1306d8accf7bc8ec2bfea4355cbdebb3df68b40925cad"
+dependencies = [
+ "aho-corasick",
+ "memchr",
+ "regex-syntax",
+]
+
+[[package]]
+name = "regex-syntax"
+version = "0.8.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "caf4aa5b0f434c91fe5c7f1ecb6a5ece2130b02ad2a590589dda5146df959001"
+
+[[package]]
+name = "rustc-demangle"
+version = "0.1.26"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "56f7d92ca342cea22a06f2121d944b4fd82af56988c270852495420f961d4ace"
+
+[[package]]
+name = "rustversion"
+version = "1.0.22"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b39cdef0fa800fc44525c84ccb54a029961a8215f9619753635a9c0d2538d46d"
+
+[[package]]
+name = "ryu"
+version = "1.0.20"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "28d3b2b1366ec20994f1fd18c3c594f05c5dd4bc44d8bb0c1c632c8d6829481f"
+
+[[package]]
+name = "same-file"
+version = "1.0.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "93fc1dc3aaa9bfed95e02e6eadabb4baf7e3078b0bd1b4d7b6b0b68378900502"
+dependencies = [
+ "winapi-util",
+]
+
+[[package]]
+name = "scopeguard"
+version = "1.2.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49"
+
+[[package]]
+name = "serde"
+version = "1.0.228"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "9a8e94ea7f378bd32cbbd37198a4a91436180c5bb472411e48b5ec2e2124ae9e"
+dependencies = [
+ "serde_core",
+ "serde_derive",
+]
+
+[[package]]
+name = "serde_core"
+version = "1.0.228"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "41d385c7d4ca58e59fc732af25c3983b67ac852c1a25000afe1175de458b67ad"
+dependencies = [
+ "serde_derive",
+]
+
+[[package]]
+name = "serde_derive"
+version = "1.0.228"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d540f220d3187173da220f885ab66608367b6574e925011a9353e4badda91d79"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn",
+]
+
+[[package]]
+name = "serde_json"
+version = "1.0.145"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "402a6f66d8c709116cf22f558eab210f5a50187f702eb4d7e5ef38d9a7f1c79c"
+dependencies = [
+ "itoa",
+ "memchr",
+ "ryu",
+ "serde",
+ "serde_core",
+]
+
+[[package]]
+name = "signal-hook-registry"
+version = "1.4.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b2a4719bff48cee6b39d12c020eeb490953ad2443b7055bd0b21fca26bd8c28b"
+dependencies = [
+ "libc",
+]
+
+[[package]]
+name = "slab"
+version = "0.4.11"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "7a2ae44ef20feb57a68b23d846850f861394c2e02dc425a50098ae8c90267589"
+
+[[package]]
+name = "smallvec"
+version = "1.15.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "67b1b7a3b5fe4f1376887184045fcf45c69e92af734b7aaddc05fb777b6fbd03"
+
+[[package]]
+name = "socket2"
+version = "0.5.10"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "e22376abed350d73dd1cd119b57ffccad95b4e585a7cda43e286245ce23c0678"
+dependencies = [
+ "libc",
+ "windows-sys 0.52.0",
+]
+
+[[package]]
+name = "socket2"
+version = "0.6.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "233504af464074f9d066d7b5416c5f9b894a5862a6506e306f7b816cdd6f1807"
+dependencies = [
+ "libc",
+ "windows-sys 0.59.0",
+]
+
+[[package]]
+name = "strsim"
+version = "0.11.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "7da8b5736845d9f2fcb837ea5d9e2628564b3b043a70948a3f0b778838c5fb4f"
+
+[[package]]
+name = "swb-sys-monitor"
+version = "0.1.0"
+dependencies = [
+ "anyhow",
+ "clap",
+ "criterion",
+ "env_logger",
+ "hyper",
+ "log",
+ "tokio",
+ "tokio-test",
+]
+
+[[package]]
+name = "syn"
+version = "2.0.106"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ede7c438028d4436d71104916910f5bb611972c5cfd7f89b8300a8186e6fada6"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "unicode-ident",
+]
+
+[[package]]
+name = "tinytemplate"
+version = "1.2.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "be4d6b5f19ff7664e8c98d03e2139cb510db9b0a60b55f8e8709b689d939b6bc"
+dependencies = [
+ "serde",
+ "serde_json",
+]
+
+[[package]]
+name = "tokio"
+version = "1.47.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "89e49afdadebb872d3145a5638b59eb0691ea23e46ca484037cfab3b76b95038"
+dependencies = [
+ "backtrace",
+ "bytes",
+ "io-uring",
+ "libc",
+ "mio",
+ "parking_lot",
+ "pin-project-lite",
+ "signal-hook-registry",
+ "slab",
+ "socket2 0.6.0",
+ "tokio-macros",
+ "windows-sys 0.59.0",
+]
+
+[[package]]
+name = "tokio-macros"
+version = "2.5.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "6e06d43f1345a3bcd39f6a56dbb7dcab2ba47e68e8ac134855e7e2bdbaf8cab8"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn",
+]
+
+[[package]]
+name = "tokio-stream"
+version = "0.1.17"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "eca58d7bba4a75707817a2c44174253f9236b2d5fbd055602e9d5c07c139a047"
+dependencies = [
+ "futures-core",
+ "pin-project-lite",
+ "tokio",
+]
+
+[[package]]
+name = "tokio-test"
+version = "0.4.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "2468baabc3311435b55dd935f702f42cd1b8abb7e754fb7dfb16bd36aa88f9f7"
+dependencies = [
+ "async-stream",
+ "bytes",
+ "futures-core",
+ "tokio",
+ "tokio-stream",
+]
+
+[[package]]
+name = "tokio-util"
+version = "0.7.16"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "14307c986784f72ef81c89db7d9e28d6ac26d16213b109ea501696195e6e3ce5"
+dependencies = [
+ "bytes",
+ "futures-core",
+ "futures-sink",
+ "pin-project-lite",
+ "tokio",
+]
+
+[[package]]
+name = "tower-service"
+version = "0.3.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "8df9b6e13f2d32c91b9bd719c00d1958837bc7dec474d94952798cc8e69eeec3"
+
+[[package]]
+name = "tracing"
+version = "0.1.41"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "784e0ac535deb450455cbfa28a6f0df145ea1bb7ae51b821cf5e7927fdcfbdd0"
+dependencies = [
+ "pin-project-lite",
+ "tracing-core",
+]
+
+[[package]]
+name = "tracing-core"
+version = "0.1.34"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b9d12581f227e93f094d3af2ae690a574abb8a2b9b7a96e7cfe9647b2b617678"
+dependencies = [
+ "once_cell",
+]
+
+[[package]]
+name = "try-lock"
+version = "0.2.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "e421abadd41a4225275504ea4d6566923418b7f05506fbc9c0fe86ba7396114b"
+
+[[package]]
+name = "unicode-ident"
+version = "1.0.19"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f63a545481291138910575129486daeaf8ac54aee4387fe7906919f7830c7d9d"
+
+[[package]]
+name = "utf8parse"
+version = "0.2.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "06abde3611657adf66d383f00b093d7faecc7fa57071cce2578660c9f1010821"
+
+[[package]]
+name = "walkdir"
+version = "2.5.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "29790946404f91d9c5d06f9874efddea1dc06c5efe94541a7d6863108e3a5e4b"
+dependencies = [
+ "same-file",
+ "winapi-util",
+]
+
+[[package]]
+name = "want"
+version = "0.3.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "bfa7760aed19e106de2c7c0b581b509f2f25d3dacaf737cb82ac61bc6d760b0e"
+dependencies = [
+ "try-lock",
+]
+
+[[package]]
+name = "wasi"
+version = "0.11.1+wasi-snapshot-preview1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ccf3ec651a847eb01de73ccad15eb7d99f80485de043efb2f370cd654f4ea44b"
+
+[[package]]
+name = "wasm-bindgen"
+version = "0.2.104"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "c1da10c01ae9f1ae40cbfac0bac3b1e724b320abfcf52229f80b547c0d250e2d"
+dependencies = [
+ "cfg-if",
+ "once_cell",
+ "rustversion",
+ "wasm-bindgen-macro",
+ "wasm-bindgen-shared",
+]
+
+[[package]]
+name = "wasm-bindgen-backend"
+version = "0.2.104"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "671c9a5a66f49d8a47345ab942e2cb93c7d1d0339065d4f8139c486121b43b19"
+dependencies = [
+ "bumpalo",
+ "log",
+ "proc-macro2",
+ "quote",
+ "syn",
+ "wasm-bindgen-shared",
+]
+
+[[package]]
+name = "wasm-bindgen-macro"
+version = "0.2.104"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "7ca60477e4c59f5f2986c50191cd972e3a50d8a95603bc9434501cf156a9a119"
+dependencies = [
+ "quote",
+ "wasm-bindgen-macro-support",
+]
+
+[[package]]
+name = "wasm-bindgen-macro-support"
+version = "0.2.104"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "9f07d2f20d4da7b26400c9f4a0511e6e0345b040694e8a75bd41d578fa4421d7"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn",
+ "wasm-bindgen-backend",
+ "wasm-bindgen-shared",
+]
+
+[[package]]
+name = "wasm-bindgen-shared"
+version = "0.2.104"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "bad67dc8b2a1a6e5448428adec4c3e84c43e561d8c9ee8a9e5aabeb193ec41d1"
+dependencies = [
+ "unicode-ident",
+]
+
+[[package]]
+name = "web-sys"
+version = "0.3.81"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "9367c417a924a74cae129e6a2ae3b47fabb1f8995595ab474029da749a8be120"
+dependencies = [
+ "js-sys",
+ "wasm-bindgen",
+]
+
+[[package]]
+name = "winapi-util"
+version = "0.1.11"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "c2a7b1c03c876122aa43f3020e6c3c3ee5c05081c9a00739faf7503aeba10d22"
+dependencies = [
+ "windows-sys 0.60.2",
+]
+
+[[package]]
+name = "windows-link"
+version = "0.2.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5"
+
+[[package]]
+name = "windows-sys"
+version = "0.52.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "282be5f36a8ce781fad8c8ae18fa3f9beff57ec1b52cb3de0789201425d9a33d"
+dependencies = [
+ "windows-targets 0.52.6",
+]
+
+[[package]]
+name = "windows-sys"
+version = "0.59.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "1e38bc4d79ed67fd075bcc251a1c39b32a1776bbe92e5bef1f0bf1f8c531853b"
+dependencies = [
+ "windows-targets 0.52.6",
+]
+
+[[package]]
+name = "windows-sys"
+version = "0.60.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f2f500e4d28234f72040990ec9d39e3a6b950f9f22d3dba18416c35882612bcb"
+dependencies = [
+ "windows-targets 0.53.5",
+]
+
+[[package]]
+name = "windows-targets"
+version = "0.52.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "9b724f72796e036ab90c1021d4780d4d3d648aca59e491e6b98e725b84e99973"
+dependencies = [
+ "windows_aarch64_gnullvm 0.52.6",
+ "windows_aarch64_msvc 0.52.6",
+ "windows_i686_gnu 0.52.6",
+ "windows_i686_gnullvm 0.52.6",
+ "windows_i686_msvc 0.52.6",
+ "windows_x86_64_gnu 0.52.6",
+ "windows_x86_64_gnullvm 0.52.6",
+ "windows_x86_64_msvc 0.52.6",
+]
+
+[[package]]
+name = "windows-targets"
+version = "0.53.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "4945f9f551b88e0d65f3db0bc25c33b8acea4d9e41163edf90dcd0b19f9069f3"
+dependencies = [
+ "windows-link",
+ "windows_aarch64_gnullvm 0.53.1",
+ "windows_aarch64_msvc 0.53.1",
+ "windows_i686_gnu 0.53.1",
+ "windows_i686_gnullvm 0.53.1",
+ "windows_i686_msvc 0.53.1",
+ "windows_x86_64_gnu 0.53.1",
+ "windows_x86_64_gnullvm 0.53.1",
+ "windows_x86_64_msvc 0.53.1",
+]
+
+[[package]]
+name = "windows_aarch64_gnullvm"
+version = "0.52.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "32a4622180e7a0ec044bb555404c800bc9fd9ec262ec147edd5989ccd0c02cd3"
+
+[[package]]
+name = "windows_aarch64_gnullvm"
+version = "0.53.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "a9d8416fa8b42f5c947f8482c43e7d89e73a173cead56d044f6a56104a6d1b53"
+
+[[package]]
+name = "windows_aarch64_msvc"
+version = "0.52.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "09ec2a7bb152e2252b53fa7803150007879548bc709c039df7627cabbd05d469"
+
+[[package]]
+name = "windows_aarch64_msvc"
+version = "0.53.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b9d782e804c2f632e395708e99a94275910eb9100b2114651e04744e9b125006"
+
+[[package]]
+name = "windows_i686_gnu"
+version = "0.52.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "8e9b5ad5ab802e97eb8e295ac6720e509ee4c243f69d781394014ebfe8bbfa0b"
+
+[[package]]
+name = "windows_i686_gnu"
+version = "0.53.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "960e6da069d81e09becb0ca57a65220ddff016ff2d6af6a223cf372a506593a3"
+
+[[package]]
+name = "windows_i686_gnullvm"
+version = "0.52.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "0eee52d38c090b3caa76c563b86c3a4bd71ef1a819287c19d586d7334ae8ed66"
+
+[[package]]
+name = "windows_i686_gnullvm"
+version = "0.53.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "fa7359d10048f68ab8b09fa71c3daccfb0e9b559aed648a8f95469c27057180c"
+
+[[package]]
+name = "windows_i686_msvc"
+version = "0.52.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "240948bc05c5e7c6dabba28bf89d89ffce3e303022809e73deaefe4f6ec56c66"
+
+[[package]]
+name = "windows_i686_msvc"
+version = "0.53.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "1e7ac75179f18232fe9c285163565a57ef8d3c89254a30685b57d83a38d326c2"
+
+[[package]]
+name = "windows_x86_64_gnu"
+version = "0.52.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "147a5c80aabfbf0c7d901cb5895d1de30ef2907eb21fbbab29ca94c5b08b1a78"
+
+[[package]]
+name = "windows_x86_64_gnu"
+version = "0.53.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "9c3842cdd74a865a8066ab39c8a7a473c0778a3f29370b5fd6b4b9aa7df4a499"
+
+[[package]]
+name = "windows_x86_64_gnullvm"
+version = "0.52.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "24d5b23dc417412679681396f2b49f3de8c1473deb516bd34410872eff51ed0d"
+
+[[package]]
+name = "windows_x86_64_gnullvm"
+version = "0.53.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "0ffa179e2d07eee8ad8f57493436566c7cc30ac536a3379fdf008f47f6bb7ae1"
+
+[[package]]
+name = "windows_x86_64_msvc"
+version = "0.52.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec"
+
+[[package]]
+name = "windows_x86_64_msvc"
+version = "0.53.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d6bbff5f0aada427a1e5a6da5f1f98158182f26556f345ac9e04d36d0ebed650"
+
+[[package]]
+name = "zerocopy"
+version = "0.8.27"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "0894878a5fa3edfd6da3f88c4805f4c8558e2b996227a3d864f47fe11e38282c"
+dependencies = [
+ "zerocopy-derive",
+]
+
+[[package]]
+name = "zerocopy-derive"
+version = "0.8.27"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "88d2b8d9c68ad2b9e4340d7832716a4d21a22a1154777ad56ea55c51a9cf3831"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn",
+]

+ 36 - 0
Cargo.toml

@@ -0,0 +1,36 @@
+[package]
+name = "swb-sys-monitor"
+version = "0.1.0"
+authors = ["PJ568 <[email protected]>"]
+edition = "2024"
+description = "为嵌入式设备高并发监控场景设计的极简网页资源占用显示系统"
+license = "MIT"
+
+[dependencies]
+tokio = { version = "1.0", features = ["full"] }
+hyper = { version = "0.14", features = ["full"] }
+clap = { version = "4.5", features = ["derive"] }
+log = "0.4"
+env_logger = "0.11"
+anyhow = "1.0"
+
+[dev-dependencies]
+criterion = { version = "0.5", features = ["html_reports"] }
+tokio-test = "0.4"
+
+[[bench]]
+name = "main"
+harness = false
+
+# 在调试模式下只启用少量的优化措施
+[profile.dev]
+opt-level = 1
+
+# 对依赖的库启用更高级别的优化
+[profile.dev.package."*"]
+opt-level = 3
+
+# 链接时间优化:以极慢的编译时间为代价,挤出更多的性能
+[profile.release]
+lto = "thin"
+codegen-units = 1

+ 57 - 0
Dockerfile

@@ -0,0 +1,57 @@
+# 多阶段构建 Dockerfile for 资源占用显示系统
+# 使用 Rust 官方镜像作为构建环境
+FROM rust:1.75-alpine as builder
+
+# 设置工作目录
+WORKDIR /app
+
+# 安装构建依赖
+RUN apk add --no-cache musl-dev
+
+# 复制 Cargo 文件
+COPY Cargo.toml Cargo.lock ./
+
+# 创建虚拟 main.rs 以预构建依赖
+RUN mkdir src && echo "fn main() {}" > src/main.rs
+RUN cargo build --release && rm -rf src
+
+# 复制源代码
+COPY . .
+
+# 构建应用
+RUN touch src/main.rs && cargo build --release
+
+# 运行时镜像 - 使用轻量级 Alpine
+FROM alpine:latest
+
+# 安装运行时依赖
+RUN apk add --no-cache ca-certificates tzdata
+
+# 创建非 root 用户
+RUN addgroup -g 1000 -S swb && \
+    adduser -D -s /bin/sh -u 1000 -S swb -G swb
+
+# 设置工作目录
+WORKDIR /app
+
+# 从构建阶段复制二进制文件
+COPY --from=builder /app/target/release/swb-sys-monitor ./
+
+# 设置权限
+RUN chown -R swb:swb /app
+
+# 切换到非 root 用户
+USER swb
+
+# 暴露端口
+EXPOSE 8080
+
+# 设置环境变量
+ENV RUST_LOG=info
+
+# 健康检查
+HEALTHCHECK --interval=30s --timeout=3s --start-period=5s --retries=3 \
+    CMD wget --no-verbose --tries=1 --spider http://localhost:8080/health || exit 1
+
+# 启动命令
+CMD ["./swb-sys-monitor", "--address", "0.0.0.0", "--port", "8080", "--log-level", "info"]

+ 9 - 0
LICENSE

@@ -0,0 +1,9 @@
+ The MIT License (MIT)
+
+Copyright © 2025 PJ568 <[email protected]>
+
+Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

+ 275 - 0
README.en.md

@@ -0,0 +1,275 @@
+# Resource Usage Monitor System
+
+> English | [简体中文](README.md)
+
+A minimal resource usage monitoring system designed specifically for embedded device monitoring scenarios. Supports 200+ high-concurrency client connections.
+
+## Features
+
+- **Minimal code implementation**: Pursuing code simplicity and maintainability
+- **High performance, low memory usage**: Optimized for embedded devices
+- **High concurrency access, lock-free algorithms**: Supports 200+ concurrent connections
+- **Few dependencies, prefer system commands**: Reduces external dependencies
+- **Data expires after 10 seconds**: No need to fetch data again when not expired
+- **No fetching when no users access**: On-demand update strategy
+- **No CSS, no JS**: Pure HTML implementation
+
+## Quick Start
+
+### Installation
+
+#### Install pre-compiled binary package
+
+```bash
+cargo install swb-sys-monitor
+```
+
+#### Compile from source
+
+```bash
+# Clone repository
+git clone https://github.com/swaybien/swb-sys-monitor.git
+cd swb-sys-monitor
+
+# Build release version
+cargo build --release
+
+# Or run directly
+cargo run -- --help
+```
+
+### Usage
+
+```bash
+# Start with default configuration (listen on 0.0.0.0:8080, cache TTL 10 seconds)
+./target/release/swb-sys-monitor
+
+# Custom configuration
+./target/release/swb-sys-monitor --address 127.0.0.1 --port 3000 --ttl 5
+
+# Set log level
+./target/release/swb-sys-monitor --log-level debug
+```
+
+### Access
+
+After starting, visit `http://localhost:8080` in your browser to view system resource usage.
+
+The page automatically refreshes every 10 seconds and displays the following information:
+
+- CPU usage
+- Memory usage (used, available, cached, free)
+- Data acquisition timestamp
+
+#### Health Check Endpoint
+
+The system provides a health check endpoint at `http://localhost:8080/health` for monitoring service status:
+
+```bash
+curl http://localhost:8080/health
+# Returns: OK
+```
+
+## Command Line Arguments
+
+| Parameter     | Short Parameter | Default   | Description                                 |
+| ------------- | --------------- | --------- | ------------------------------------------- |
+| `--address`   | `-a`            | `0.0.0.0` | Server binding address                      |
+| `--port`      | `-p`            | `8080`    | Server port                                 |
+| `--ttl`       | `-t`            | `10`      | Cache TTL in seconds                        |
+| `--log-level` | `-l`            | `info`    | Log level (trace, debug, info, warn, error) |
+| `--help`      | `-h`            | -         | Show help information                       |
+
+## Technical Architecture
+
+### Core Components
+
+1. **System Resource Acquisition Module**: Directly reads `/proc/stat` and `/proc/meminfo` to obtain system information
+2. **Lock-free Data Caching Mechanism**: Uses `AtomicPtr` and `AtomicU64` to implement thread-safe caching
+3. **High-concurrency Web Server**: High-performance HTTP server based on tokio + hyper
+4. **Server-side HTML Rendering**: Pure HTML implementation, no CSS, no JS
+
+### Performance Optimization
+
+- **Lock-free algorithms**: Cache read/write uses atomic operations, supporting high-concurrency access
+- **On-demand updates**: System information is updated only when data is expired and there are requests
+- **Memory optimization**: Uses `String::with_capacity` to pre-allocate capacity, reducing reallocation
+- **Function inlining**: Small functions use `#[inline]` attribute for performance optimization
+
+## Development
+
+### Build Requirements
+
+- Rust 2024 Edition
+- Linux system (currently only supports Linux)
+
+### Development Commands
+
+```bash
+# Compile check
+cargo check --all-targets
+
+# Code style check
+cargo clippy
+
+# Run tests
+cargo test
+
+# Run benchmark tests
+cargo bench
+
+# Build release version
+cargo build --release
+```
+
+### Test Coverage
+
+The project includes comprehensive test coverage:
+
+- Unit tests: caching mechanism, system information acquisition, HTTP server
+- Integration tests: end-to-end functionality tests
+- Performance benchmark tests: performance tests for key operations
+
+## Deployment
+
+### Automatic Installation (Recommended)
+
+Use the provided installation script for automatic deployment to systemd systems:
+
+```bash
+# Clone repository
+git clone https://github.com/swaybien/swb-sys-monitor.git
+cd swb-sys-monitor
+
+# Run installation script
+sudo ./scripts/install.sh
+
+# To uninstall
+sudo ./scripts/uninstall.sh
+```
+
+For detailed deployment script usage instructions, please refer to [Deployment Guide](scripts/README.md).
+
+### Manual Installation
+
+#### System Service Configuration
+
+Create a systemd service file `/etc/systemd/system/swb-sys-monitor.service`:
+
+```ini
+[Unit]
+Description=Resource Status Monitor
+After=network.target
+
+[Service]
+Type=simple
+User=nobody
+ExecStart=/usr/local/bin/swb-sys-monitor
+Restart=always
+RestartSec=5
+
+[Install]
+WantedBy=multi-user.target
+```
+
+Enable and start the service:
+
+```bash
+sudo systemctl enable swb-sys-monitor
+sudo systemctl start swb-sys-monitor
+```
+
+### Docker Deployment
+
+#### Using Docker Compose (Recommended)
+
+```bash
+# Clone repository
+git clone https://github.com/swaybien/swb-sys-monitor.git
+cd swb-sys-monitor
+
+# Start service
+docker-compose up -d
+
+# View logs
+docker-compose logs -f swb-sys-monitor
+
+# Stop service
+docker-compose down
+```
+
+Access URL: http://localhost:18273
+
+#### Using Docker Commands
+
+```bash
+# Build image
+docker build -t swb-sys-monitor .
+
+# Run container
+docker run -d \
+  --name swb-sys-monitor \
+  --restart unless-stopped \
+  -p 18273:8080 \
+  --read-only \
+  --tmpfs /tmp \
+  --cap-drop ALL \
+  --cap-add DAC_OVERRIDE \
+  --security-opt no-new-privileges:true \
+  swb-sys-monitor
+
+# View logs
+docker logs -f swb-sys-monitor
+
+# Stop container
+docker stop swb-sys-monitor
+docker rm swb-sys-monitor
+```
+
+#### Docker Configuration Description
+
+Docker deployment includes the following security features:
+
+- **Read-only file system**: Prevents runtime modifications
+- **Minimal privileges**: Removes all Linux capabilities, only adds necessary ones
+- **Security options**: Enables `no-new-privileges` to prevent privilege escalation
+- **Health check**: Automatically monitors service status
+- **Non-root user**: Runs with unprivileged user inside the container
+
+#### Custom Configuration
+
+You can customize configuration through environment variables:
+
+```yaml
+# docker-compose.yml
+services:
+  swb-sys-monitor:
+    build: .
+    environment:
+      - RUST_LOG=debug
+    command:
+      [
+        "./swb-sys-monitor",
+        "--address",
+        "0.0.0.0",
+        "--port",
+        "8080",
+        "--ttl",
+        "5",
+      ]
+```
+
+## License
+
+This project is licensed under the MIT License. See the [LICENSE](LICENSE) file for details.
+
+## Contributing
+
+Issues and Pull Requests are welcome!
+Please read the [Contributing Guide](CONTRIBUTING.md).
+
+## Related Links
+
+- [Design Document](docs/design.md)
+- [Development Status](docs/status.md)
+- [HTML Template Example](docs/example.html)

+ 275 - 0
README.md

@@ -0,0 +1,275 @@
+# 资源占用显示系统
+
+> [English](README.en.md) | 简体中文
+
+一个极简的资源占用显示系统,专为嵌入式设备监控场景设计。支持 200+ 高并发客户端访问。
+
+## 特性
+
+- **最小最简代码实现**:追求代码简洁性和可维护性;
+- **高性能,内存占用低**:针对嵌入式设备优化;
+- **高并发访问,无锁算法**:支持 200+ 并发连接;
+- **少依赖,尽量使用系统命令**:减少外部依赖;
+- **数据更新后 10 秒算过期**:数据未过期时无须再次获取;
+- **无用户访问时无须获取**:按需更新策略;
+- **无 CSS,无 JS**:纯 HTML 实现。
+
+## 快速开始
+
+### 安装
+
+#### 下载安装预编译二进制包
+
+```bash
+cargo install swb-sys-monitor
+```
+
+#### 从源码编译
+
+```bash
+# 克隆仓库
+git clone https://github.com/swaybien/swb-sys-monitor.git
+cd swb-sys-monitor
+
+# 构建发布版本
+cargo build --release
+
+# 或者直接运行
+cargo run -- --help
+```
+
+### 使用
+
+```bash
+# 使用默认配置启动(监听 0.0.0.0:8080,缓存 TTL 10 秒)
+./target/release/swb-sys-monitor
+
+# 自定义配置
+./target/release/swb-sys-monitor --address 127.0.0.1 --port 3000 --ttl 5
+
+# 设置日志级别
+./target/release/swb-sys-monitor --log-level debug
+```
+
+### 访问
+
+启动后,在浏览器中访问 `http://localhost:8080` 即可查看系统资源占用情况。
+
+页面会每 10 秒自动刷新,显示以下信息:
+
+- 处理器使用率
+- 内存使用情况(已用、可用、缓存、空闲)
+- 数据获取时间戳
+
+#### 健康检查端点
+
+系统提供健康检查端点 `http://localhost:8080/health`,用于监控服务状态:
+
+```bash
+curl http://localhost:8080/health
+# 返回: OK
+```
+
+## 命令行参数
+
+| 参数          | 短参数 | 默认值    | 描述                                       |
+| ------------- | ------ | --------- | ------------------------------------------ |
+| `--address`   | `-a`   | `0.0.0.0` | 服务器绑定地址                             |
+| `--port`      | `-p`   | `8080`    | 服务器端口                                 |
+| `--ttl`       | `-t`   | `10`      | 缓存 TTL 秒数                              |
+| `--log-level` | `-l`   | `info`    | 日志级别 (trace, debug, info, warn, error) |
+| `--help`      | `-h`   | -         | 显示帮助信息                               |
+
+## 技术架构
+
+### 核心组件
+
+1. **系统资源获取模块**:直接读取 `/proc/stat` 和 `/proc/meminfo` 获取系统信息
+2. **无锁数据缓存机制**:使用 `AtomicPtr` 和 `AtomicU64` 实现线程安全缓存
+3. **高并发 Web 服务器**:基于 tokio + hyper 实现高性能 HTTP 服务器
+4. **服务器端 HTML 渲染**:纯 HTML 实现,无 CSS 无 JS
+
+### 性能优化
+
+- **无锁算法**:缓存读写使用原子操作,支持高并发访问
+- **按需更新**:只有数据过期且有请求时才更新系统信息
+- **内存优化**:使用 `String::with_capacity` 预分配容量,减少重新分配
+- **函数内联**:小函数使用 `#[inline]` 属性优化性能
+
+## 开发
+
+### 构建要求
+
+- Rust 2024 Edition
+- Linux 系统(目前仅支持 Linux)
+
+### 开发命令
+
+```bash
+# 编译检查
+cargo check --all-targets
+
+# 代码规范检查
+cargo clippy
+
+# 运行测试
+cargo test
+
+# 运行基准测试
+cargo bench
+
+# 构建发布版本
+cargo build --release
+```
+
+### 测试覆盖
+
+项目包含全面的测试覆盖:
+
+- 单元测试:缓存机制、系统信息获取、HTTP 服务器
+- 集成测试:端到端功能测试
+- 性能基准测试:关键操作的性能测试
+
+## 部署
+
+### 自动安装(推荐)
+
+使用提供的安装脚本自动部署到 systemd 系统:
+
+```bash
+# 克隆仓库
+git clone https://github.com/swaybien/swb-sys-monitor.git
+cd swb-sys-monitor
+
+# 运行安装脚本
+sudo ./scripts/install.sh
+
+# 如需卸载
+sudo ./scripts/uninstall.sh
+```
+
+详细的部署脚本使用说明请参考 [部署指南](scripts/README.md)。
+
+### 手动安装
+
+#### 系统服务配置
+
+创建 systemd 服务文件 `/etc/systemd/system/swb-sys-monitor.service`:
+
+```ini
+[Unit]
+Description=Resource Status Monitor
+After=network.target
+
+[Service]
+Type=simple
+User=nobody
+ExecStart=/usr/local/bin/swb-sys-monitor
+Restart=always
+RestartSec=5
+
+[Install]
+WantedBy=multi-user.target
+```
+
+启用和启动服务:
+
+```bash
+sudo systemctl enable swb-sys-monitor
+sudo systemctl start swb-sys-monitor
+```
+
+### Docker 部署
+
+#### 使用 Docker Compose(推荐)
+
+```bash
+# 克隆仓库
+git clone https://github.com/swaybien/swb-sys-monitor.git
+cd swb-sys-monitor
+
+# 启动服务
+docker-compose up -d
+
+# 查看日志
+docker-compose logs -f swb-sys-monitor
+
+# 停止服务
+docker-compose down
+```
+
+访问地址:http://localhost:18273
+
+#### 使用 Docker 命令
+
+```bash
+# 构建镜像
+docker build -t swb-sys-monitor .
+
+# 运行容器
+docker run -d \
+  --name swb-sys-monitor \
+  --restart unless-stopped \
+  -p 18273:8080 \
+  --read-only \
+  --tmpfs /tmp \
+  --cap-drop ALL \
+  --cap-add DAC_OVERRIDE \
+  --security-opt no-new-privileges:true \
+  swb-sys-monitor
+
+# 查看日志
+docker logs -f swb-sys-monitor
+
+# 停止容器
+docker stop swb-sys-monitor
+docker rm swb-sys-monitor
+```
+
+#### Docker 配置说明
+
+Docker 部署包含以下安全特性:
+
+- **只读文件系统**:防止运行时修改
+- **最小权限**:移除所有 Linux 能力,仅添加必要的能力
+- **安全选项**:启用 `no-new-privileges` 防止权限提升
+- **健康检查**:自动监控服务状态
+- **非 root 用户**:容器内使用非特权用户运行
+
+#### 自定义配置
+
+可以通过环境变量自定义配置:
+
+```yaml
+# docker-compose.yml
+services:
+  swb-sys-monitor:
+    build: .
+    environment:
+      - RUST_LOG=debug
+    command:
+      [
+        "./swb-sys-monitor",
+        "--address",
+        "0.0.0.0",
+        "--port",
+        "8080",
+        "--ttl",
+        "5",
+      ]
+```
+
+## 许可证
+
+本项目采用 MIT 许可证。详见 [LICENSE](LICENSE) 文件。
+
+## 贡献
+
+欢迎提交 Issue 和 Pull Request!
+请阅读[贡献指北](CONTRIBUTING.md)。
+
+## 相关链接
+
+- [设计文档](docs/design.md)
+- [开发状态](docs/status.md)
+- [HTML 模板示例](docs/example.html)

+ 150 - 0
benches/main.rs

@@ -0,0 +1,150 @@
+use criterion::{Criterion, black_box, criterion_group, criterion_main};
+use std::sync::Arc;
+use std::time::Duration;
+use swb_sys_monitor::cache::{SystemStatsCache, create_cache};
+use swb_sys_monitor::server::StatusServer;
+use swb_sys_monitor::stats::{SystemStats, collect_system_stats};
+use tokio::runtime::Runtime;
+
+fn create_test_stats(hostname: &str, cpu_usage: f32) -> SystemStats {
+    SystemStats {
+        hostname: hostname.to_string(),
+        cpu_usage,
+        memory_total: 1024 * 1024 * 1024,    // 1GB
+        memory_used: 512 * 1024 * 1024,      // 512MB
+        memory_available: 256 * 1024 * 1024, // 256MB
+        memory_cached: 128 * 1024 * 1024,    // 128MB
+        memory_free: 128 * 1024 * 1024,      // 128MB
+        timestamp: std::time::Instant::now(),
+    }
+}
+
+fn bench_cache_operations(c: &mut Criterion) {
+    let rt = Runtime::new().unwrap();
+
+    c.bench_function("cache_creation", |b| {
+        b.iter(|| {
+            let cache = create_cache(black_box(10));
+            black_box(cache);
+        })
+    });
+
+    c.bench_function("cache_update_and_get", |b| {
+        let cache = create_cache(10);
+        let stats = create_test_stats("benchmark", 0.5);
+
+        b.iter(|| {
+            cache.update(black_box(stats.clone()));
+            let result = cache.get();
+            black_box(result);
+        })
+    });
+
+    c.bench_function("cache_concurrent_reads", |b| {
+        let cache = Arc::new(SystemStatsCache::new(Duration::from_secs(10)));
+        let stats = create_test_stats("concurrent", 0.7);
+        cache.update(stats);
+
+        b.iter(|| {
+            rt.block_on(async {
+                let mut handles = vec![];
+                for _ in 0..100 {
+                    let cache_clone = cache.clone();
+                    let handle = tokio::spawn(async move {
+                        let result = cache_clone.get();
+                        black_box(result);
+                    });
+                    handles.push(handle);
+                }
+
+                for handle in handles {
+                    handle.await.unwrap();
+                }
+            })
+        })
+    });
+}
+
+fn bench_html_rendering(c: &mut Criterion) {
+    let _server = StatusServer::new(create_cache(10));
+    let stats = create_test_stats("渲染测试主机", 0.65);
+
+    c.bench_function("html_template_rendering", |b| {
+        b.iter(|| {
+            let html = StatusServer::render_html_template(black_box(&stats));
+            black_box(html);
+        })
+    });
+
+    c.bench_function("html_rendering_with_large_values", |b| {
+        let large_stats = SystemStats {
+            hostname: "大型测试主机名称很长很长".to_string(),
+            cpu_usage: 0.95,
+            memory_total: 16 * 1024 * 1024 * 1024,    // 16GB
+            memory_used: 8 * 1024 * 1024 * 1024,      // 8GB
+            memory_available: 4 * 1024 * 1024 * 1024, // 4GB
+            memory_cached: 2 * 1024 * 1024 * 1024,    // 2GB
+            memory_free: 2 * 1024 * 1024 * 1024,      // 2GB
+            timestamp: std::time::Instant::now(),
+        };
+
+        b.iter(|| {
+            let html = StatusServer::render_html_template(black_box(&large_stats));
+            black_box(html);
+        })
+    });
+}
+
+fn bench_system_stats_collection(c: &mut Criterion) {
+    let rt = Runtime::new().unwrap();
+
+    c.bench_function("system_stats_collection", |b| {
+        b.iter(|| {
+            rt.block_on(async {
+                let stats = collect_system_stats().await;
+                let _ = black_box(stats);
+            })
+        })
+    });
+}
+
+fn bench_memory_allocation(c: &mut Criterion) {
+    c.bench_function("string_allocation_with_capacity", |b| {
+        b.iter(|| {
+            let mut s = String::with_capacity(1024);
+            s.push_str("测试字符串内容");
+            black_box(s);
+        })
+    });
+
+    c.bench_function("string_allocation_without_capacity", |b| {
+        b.iter(|| {
+            let mut s = String::new();
+            s.push_str("测试字符串内容");
+            black_box(s);
+        })
+    });
+}
+
+fn bench_cache_ttl_precision(c: &mut Criterion) {
+    let cache = SystemStatsCache::new(Duration::from_millis(1));
+    let stats = create_test_stats("ttl_test", 0.3);
+
+    c.bench_function("cache_ttl_check", |b| {
+        b.iter(|| {
+            cache.update(black_box(stats.clone()));
+            let result = cache.get();
+            black_box(result);
+        })
+    });
+}
+
+criterion_group!(
+    benches,
+    bench_cache_operations,
+    bench_html_rendering,
+    bench_system_stats_collection,
+    bench_memory_allocation,
+    bench_cache_ttl_precision
+);
+criterion_main!(benches);

+ 35 - 0
docker-compose.yml

@@ -0,0 +1,35 @@
+version: '3.8'
+
+services:
+  swb-sys-monitor:
+    build: .
+    container_name: swb-sys-monitor
+    restart: unless-stopped
+    ports:
+      - "18273:8080"
+    environment:
+      - RUST_LOG=info
+    volumes:
+      - /proc:/host/proc:ro
+      - /sys:/host/sys:ro
+    read_only: true
+    tmpfs:
+      - /tmp
+    cap_drop:
+      - ALL
+    cap_add:
+      - DAC_OVERRIDE
+    security_opt:
+      - no-new-privileges:true
+    healthcheck:
+      test: ["CMD", "wget", "--no-verbose", "--tries=1", "--spider", "http://localhost:8080/health"]
+      interval: 30s
+      timeout: 10s
+      retries: 3
+      start_period: 40s
+    networks:
+      - monitoring
+
+networks:
+  monitoring:
+    driver: bridge

+ 548 - 0
docs/design.md

@@ -0,0 +1,548 @@
+# 资源占用显示系统 - 技术设计文档
+
+## 项目概述
+
+本项目是一个极简的资源占用显示系统,严格按照 `docs/example.html` 设计,专为嵌入式设备监控场景设计。系统支持 200+ 高并发客户端访问,数据更新后 10 秒算过期,无 CSS 无 JS,采用服务器端渲染确保最简实现。
+
+### 核心需求
+
+- **最小最简代码实现**:追求代码简洁性和可维护性
+- **高性能,内存占用低**:针对嵌入式设备优化
+- **高并发访问,无锁算法**:支持 200+ 并发连接
+- **少依赖,尽量使用系统命令**:减少外部依赖
+- **数据更新后 10 秒算过期**:数据未过期时无须再次获取
+- **无用户访问时无须获取**:按需更新策略
+- **无 CSS,无 JS**:纯 HTML 实现
+- **严格按照 example.html 设计**:完全遵循设计规范
+
+## 技术架构
+
+### 整体架构图
+
+```mermaid
+graph TB
+    A[客户端浏览器] --> B[HTTP 服务器]
+    B --> C[HTML 渲染器]
+    C --> D[无锁缓存系统]
+    D --> E[系统资源获取器]
+    E --> F[Linux /proc 文件系统]
+```
+
+### 技术栈选择
+
+| 组件       | 选择理由                                 | 替代方案          |
+| ---------- | ---------------------------------------- | ----------------- |
+| 核心语言   | Rust:内存安全、零成本抽象、优秀并发支持 | Go、C++           |
+| Web 框架   | tokio + hyper:最小依赖、高性能          | actix-web、rocket |
+| 异步运行时 | tokio:成熟的异步生态                    | async-std         |
+| 系统调用   | 直接读取 /proc:零依赖、高性能           | sysinfo crate     |
+| 模板引擎   | 简单字符串格式化:无额外依赖             | handlebars、tera  |
+
+## 核心模块设计
+
+### 1. 系统资源获取模块
+
+#### 数据结构
+
+```rust
+#[derive(Debug, Clone)]
+pub struct SystemStats {
+    pub hostname: String,
+    pub cpu_usage: f32,           // CPU 使用率 (0.0-1.0)
+    pub memory_total: u64,        // 总内存字节数
+    pub memory_used: u64,         // 已用内存字节数
+    pub memory_available: u64,    // 可用内存字节数
+    pub memory_cached: u64,       // 缓存内存字节数
+    pub memory_free: u64,         // 空闲内存字节数
+    pub timestamp: Instant,       // 数据获取时间戳
+}
+```
+
+#### 实现策略
+
+1. **Linux 优化路径**:
+
+   - CPU: 读取 `/proc/stat`,计算使用率
+   - 内存: 读取 `/proc/meminfo`,获取详细信息
+   - 主机名: 读取 `/proc/sys/kernel/hostname`
+
+2. **跨平台支持**:
+
+   ```rust
+   #[cfg(target_os = "linux")]
+   fn collect_linux_stats() -> Result<SystemStats>
+
+   #[cfg(target_os = "windows")]
+   fn collect_windows_stats() -> Result<SystemStats>
+
+   #[cfg(target_os = "macos")]
+   fn collect_macos_stats() -> Result<SystemStats>
+   ```
+
+3. **性能优化**:
+   - 只读取必要的数据字段
+   - 使用零拷贝解析技术
+   - 避免频繁文件 I/O
+
+### 2. 无锁数据缓存机制
+
+#### 核心设计
+
+```rust
+use std::sync::atomic::{AtomicPtr, AtomicU64, Ordering};
+use std::time::{Duration, Instant};
+
+pub struct SystemStatsCache {
+    current_stats: AtomicPtr<SystemStats>,
+    last_update: AtomicU64,
+    ttl: Duration,
+}
+
+impl SystemStatsCache {
+    pub fn new(ttl: Duration) -> Self {
+        Self {
+            current_stats: AtomicPtr::new(Box::into_raw(Box::new(SystemStats::default()))),
+            last_update: AtomicU64::new(0),
+            ttl,
+        }
+    }
+
+    // 无锁读取
+    pub fn get(&self) -> Option<SystemStats> {
+        let ptr = self.current_stats.load(Ordering::Acquire);
+        if ptr.is_null() {
+            return None;
+        }
+
+        let stats = unsafe { &*ptr };
+        let now = SystemTime::now()
+            .duration_since(UNIX_EPOCH)
+            .unwrap()
+            .as_secs();
+        let last_update = self.last_update.load(Ordering::Acquire);
+
+        if now - last_update > self.ttl.as_secs() {
+            return None; // 数据过期
+        }
+
+        Some(stats.clone())
+    }
+
+    // 原子更新
+    pub fn update(&self, new_stats: SystemStats) {
+        let boxed_stats = Box::into_raw(Box::new(new_stats));
+        let old_ptr = self.current_stats.swap(boxed_stats, Ordering::Release);
+
+        // 安全释放旧数据
+        if !old_ptr.is_null() {
+            let _ = unsafe { Box::from_raw(old_ptr) };
+        }
+
+        self.last_update.store(
+            SystemTime::now()
+                .duration_since(UNIX_EPOCH)
+                .unwrap()
+                .as_secs(),
+            Ordering::Release
+        );
+    }
+}
+```
+
+#### 缓存更新策略
+
+1. **按需更新策略**:
+
+   ```rust
+   // 只有在数据过期且有请求时才更新
+   pub async fn get_or_update(&self) -> Result<SystemStats> {
+       // 先尝试获取缓存
+       if let Some(stats) = self.get() {
+           return Ok(stats);
+       }
+
+       // 数据过期或不存在,重新获取
+       let new_stats = collect_system_stats().await?;
+       self.update(new_stats.clone());
+       Ok(new_stats)
+   }
+   ```
+
+2. **惰性更新模式**:
+   - 只有在请求时检查数据是否过期
+   - 过期时才重新获取系统数据
+   - 无用户访问时不会主动获取数据
+   - 数据更新后严格 10 秒过期
+
+### 3. 高并发 Web 服务器
+
+#### 服务器架构
+
+```rust
+use hyper::{Body, Request, Response, Server};
+use hyper::service::{make_service_fn, service_fn};
+use std::convert::Infallible;
+use std::sync::Arc;
+
+pub struct StatusServer {
+    cache: Arc<SystemStatsCache>,
+}
+
+impl StatusServer {
+    pub async fn new(cache: Arc<SystemStatsCache>) -> Result<Self> {
+        Ok(Self { cache })
+    }
+
+    pub async fn run(self, addr: SocketAddr) -> Result<()> {
+        let cache = self.cache;
+
+        let make_svc = make_service_fn(move |_conn| {
+            let cache = cache.clone();
+            async move {
+                Ok::<_, Infallible>(service_fn(move |req| {
+                    let cache = cache.clone();
+                    Self::handle_request(req, cache)
+                }))
+            }
+        });
+
+        let server = Server::bind(&addr).serve(make_svc);
+        println!("服务器运行在: http://{}", addr);
+
+        if let Err(e) = server.await {
+            eprintln!("服务器错误: {}", e);
+        }
+
+        Ok(())
+    }
+
+    async fn handle_request(
+        req: Request<Body>,
+        cache: Arc<SystemStatsCache>,
+    ) -> Result<Response<Body>, Infallible> {
+        match (req.method(), req.uri().path()) {
+            (&Method::GET, "/") => Self::serve_html(req, cache).await,
+            _ => Self::serve_404(),
+        }
+    }
+}
+```
+
+#### 并发优化
+
+1. **连接处理**:
+
+   - 每个连接独立的 async task
+   - 无共享状态,只读取缓存
+   - 使用 `Arc` 共享只读数据
+
+2. **HTTP 优化**:
+   - 启用 HTTP/2 支持多路复用
+   - 设置合理的连接超时
+   - 静态资源缓存策略
+
+### 4. 前端展示逻辑
+
+#### HTML 模板
+
+严格按照 `docs/example.html` 设计,无 CSS,无 JS,使用 HTML 自动刷新机制:
+
+```html
+<!DOCTYPE html>
+<head lang="zh-Hans-CN">
+  <meta charset="UTF-8" />
+  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
+  <meta name="description" content="{{hostname}}的资源占用" />
+  <meta name="keywords" content="资源占用,效率工具" />
+  <meta http-equiv="refresh" content="10" />
+  <link
+    rel="icon"
+    type="image/svg+xml"
+    href="data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 100 100'%3E%3Ctext y='.9em' font-size='90'%3E📊%3C/text%3E%3C/svg%3E"
+  />
+  <title>{{hostname}}资源占用</title>
+</head>
+<body>
+  <fieldset>
+    <legend>{{hostname}}的资源占用</legend>
+    <fieldset>
+      <legend>处理器</legend>
+      <progress value="{{cpu_percent}}" max="100">
+        <p>{{cpu_percent}}%</p>
+      </progress>
+    </fieldset>
+    <fieldset>
+      <legend>内存</legend>
+      <p>已用:</p>
+      <progress value="{{memory_used_mb}}" max="{{memory_total_mb}}">
+        <p>{{memory_used_mb}}/{{memory_total_mb}}MB</p>
+      </progress>
+      <p>可用:</p>
+      <progress value="{{memory_available_mb}}" max="{{memory_total_mb}}">
+        <p>{{memory_available_mb}}/{{memory_total_mb}}MB</p>
+      </progress>
+      <p>缓存:</p>
+      <progress value="{{memory_cached_mb}}" max="{{memory_total_mb}}">
+        <p>{{memory_cached_mb}}/{{memory_total_mb}}MB</p>
+      </progress>
+      <p>空闲:</p>
+      <progress value="{{memory_free_mb}}" max="{{memory_total_mb}}">
+        <p>{{memory_free_mb}}/{{memory_total_mb}}MB</p>
+      </progress>
+    </fieldset>
+    <fieldset>
+      <legend>时间戳</legend>
+      <p>{{timestamp}}</p>
+    </fieldset>
+  </fieldset>
+</body>
+</html>
+```
+
+#### 服务器端渲染
+
+由于无 JavaScript,采用服务器端直接渲染 HTML:
+
+```rust
+impl StatusServer {
+    async fn serve_html(&self, req: Request<Body>) -> Result<Response<Body>, Infallible> {
+        // 获取系统数据
+        let stats = match self.cache.get_or_update().await {
+            Ok(stats) => stats,
+            Err(_) => {
+                return Ok(Response::builder()
+                    .status(500)
+                    .body(Body::from("数据获取失败"))
+                    .unwrap());
+            }
+        };
+
+        // 渲染 HTML 模板
+        let html = self.render_html_template(&stats);
+
+        Ok(Response::builder()
+            .header("content-type", "text/html; charset=utf-8")
+            .body(Body::from(html))
+            .unwrap())
+    }
+
+    fn render_html_template(&self, stats: &SystemStats) -> String {
+        let total_mb = stats.memory_total / 1024 / 1024;
+        let used_mb = stats.memory_used / 1024 / 1024;
+        let available_mb = stats.memory_available / 1024 / 1024;
+        let cached_mb = stats.memory_cached / 1024 / 1024;
+        let free_mb = stats.memory_free / 1024 / 1024;
+
+        let cpu_percent = (stats.cpu_usage * 100.0) as u32;
+
+        format!(
+            include_str!("../templates/index.html"),
+            hostname = stats.hostname,
+            cpu_percent = cpu_percent,
+            memory_total_mb = total_mb,
+            memory_used_mb = used_mb,
+            memory_available_mb = available_mb,
+            memory_cached_mb = cached_mb,
+            memory_free_mb = free_mb
+            timestamp = stats.timestamp
+        )
+    }
+}
+```
+
+## 性能优化策略
+
+### 内存优化
+
+1. **零拷贝设计**:
+
+   - 字符串操作使用 `Cow<str>` 减少分配
+   - HTTP 响应使用流式传输
+   - 避免不必要的数据序列化
+
+2. **内存池管理**:
+
+   - 预分配固定大小的缓冲区
+   - 重用 `SystemStats` 对象
+   - 使用 `Vec::with_capacity()` 预分配容量
+
+3. **栈分配优先**:
+   - 小数据结构使用栈分配
+   - 避免频繁的堆分配
+   - 使用 `#[inline]` 优化小函数
+
+### CPU 优化
+
+1. **计算优化**:
+
+   - CPU 使用率计算使用增量算法
+   - 避免浮点数运算,使用定点数
+   - 缓存计算结果
+
+2. **I/O 优化**:
+
+   - 使用 `mio` 直接操作 epoll/kqueue
+   - 批量读取系统文件
+   - 异步文件操作
+
+3. **并发优化**:
+   - 无锁数据结构
+   - 工作窃取调度
+   - CPU 亲和性设置
+
+### 网络优化
+
+1. **协议优化**:
+
+   - HTTP/2 多路复用
+   - 启用 TCP_NODELAY
+   - 连接池复用
+
+2. **数据压缩**:
+   - 静态资源 gzip 压缩
+   - JSON 数据精简格式
+   - 响应头缓存控制
+
+## 部署和配置
+
+### 编译配置
+
+```toml
+[profile.release]
+lto = true           # 链接时优化
+codegen-units = 1    # 减少代码生成单元
+panic = "abort"      # 减少二进制大小
+strip = true         # 移除调试符号
+```
+
+### 运行时配置
+
+```rust
+#[derive(Debug, Clone)]
+pub struct Config {
+    pub bind_address: String,
+    pub port: u16,
+    pub cache_ttl: Duration,
+    pub update_interval: Duration,
+    pub max_connections: usize,
+}
+
+impl Default for Config {
+    fn default() -> Self {
+        Self {
+            bind_address: "0.0.0.0".to_string(),
+            port: 8080,
+            cache_ttl: Duration::from_secs(10), // 严格 10 秒过期
+            update_interval: Duration::from_secs(10), // 无后台定时更新
+            max_connections: 1000,
+        }
+    }
+}
+```
+
+### 系统服务配置
+
+```ini
+[Unit]
+Description=Resource Status Monitor
+After=network.target
+
+[Service]
+Type=simple
+User=nobody
+ExecStart=/usr/local/bin/swb-status-page
+Restart=always
+RestartSec=5
+
+[Install]
+WantedBy=multi-user.target
+```
+
+## 测试策略
+
+### 单元测试
+
+- 系统资源获取功能测试
+- 缓存机制正确性测试
+- 数据结构序列化测试
+
+### 性能测试
+
+- 并发连接压力测试
+- 内存使用情况监控
+- 响应时间基准测试
+
+### 集成测试
+
+- 端到端功能测试
+- 跨平台兼容性测试
+- 长时间运行稳定性测试
+
+## 安全考虑
+
+### 输入验证
+
+- HTTP 请求路径验证
+- 参数范围检查
+- 防止路径遍历攻击
+
+### 资源限制
+
+- 连接数限制
+- 请求频率限制
+- 内存使用监控
+
+### 错误处理
+
+- 优雅的错误响应
+- 敏感信息过滤
+
+## 扩展性设计
+
+### 插件架构
+
+- 可插拔的数据源
+- 自定义指标支持
+- 第三方集成接口
+
+### 配置管理
+
+- 热重载配置
+- 环境变量支持
+- 配置文件验证
+
+### 监控和告警
+
+- 健康检查端点
+- 指标导出接口
+- 告警规则配置
+
+## 开发计划
+
+### 第一阶段:核心功能
+
+1. 实现基础的系统资源获取
+2. 构建无锁缓存机制(10 秒过期)
+3. 创建极简 HTTP 服务器
+4. 实现服务器端 HTML 渲染
+
+### 第二阶段:性能优化
+
+1. 实现高并发处理(200+ 连接)
+2. 优化内存使用
+3. 完善按需更新策略
+
+### 第三阶段:完善功能
+
+1. 添加配置管理
+2. 实现错误处理
+3. 完善测试覆盖
+
+### 第四阶段:部署和监控
+
+1. 创建部署脚本
+2. 文档完善
+
+## 总结
+
+本设计文档详细描述了资源占用显示系统的技术架构和实现方案。系统采用 Rust 语言,严格按照 `docs/example.html` 设计,无 CSS 无 JS,结合无锁算法和按需更新策略,实现了极简、高性能的监控解决方案。通过服务器端渲染和 10 秒数据过期机制,系统能够在嵌入式设备上稳定运行,支持 200+ 并发客户端访问,同时确保数据未过期时无须再次获取,无用户访问时无须获取。

+ 49 - 0
docs/example.html

@@ -0,0 +1,49 @@
+<!DOCTYPE html>
+<head lang="zh-Hans-CN">
+  <meta charset="UTF-8" />
+  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
+  <meta name="description" content="(hostname)的资源占用" />
+  <meta name="keywords" content="资源占用,效率工具" />
+  <meta http-equiv="refresh" content="10" />
+  <link
+    rel="icon"
+    type="image/svg+xml"
+    href="data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 100 100'%3E%3Ctext y='.9em' font-size='90'%3E📊%3C/text%3E%3C/svg%3E"
+  />
+  <title>(hostname)资源占用</title>
+</head>
+<body>
+  <fieldset>
+    <legend>(hostname)的资源占用</legend>
+    <fieldset>
+      <legend>处理器</legend>
+      <progress value="(占用量)" max="100">
+        <p>(占用比例)%</p>
+      </progress>
+    </fieldset>
+    <fieldset>
+      <legend>内存</legend>
+      <p>已用:</p>
+      <progress value="(当前内存占用量)" max="(总内存量)">
+        <p>(当前内存占用量)/(总内存量)(单位)</p>
+      </progress>
+      <p>可用:</p>
+      <progress value="(量)" max="(总内存量)">
+        <p>(量)/(总内存量)(单位)</p>
+      </progress>
+      <p>缓存:</p>
+      <progress value="(量)" max="(总内存量)">
+        <p>(量)/(总内存量)(单位)</p>
+      </progress>
+      <p>空闲:</p>
+      <progress value="(量)" max="(总内存量)">
+        <p>(量)/(总内存量)(单位)</p>
+      </progress>
+    </fieldset>
+    <fieldset>
+      <legend>时间戳</legend>
+      <p>(数据获取时间戳)</p>
+    </fieldset>
+  </fieldset>
+</body>
+</html>

+ 21 - 0
docs/status.md

@@ -0,0 +1,21 @@
+# 状态
+
+> 严格按照 README.md 开发。
+
+## 开发计划
+
+- [x] 实现基础的系统资源获取
+- [x] 构建 Web 服务器
+- [x] 添加实时数据更新
+- [x] 通过参数传入监听地址、端口和缓存 TTL
+- [x] 实现无锁并发算法
+- [x] 高并发处理(支持 200+ 并发连接)
+- [x] 完善错误处理和日志记录
+- [x] 优化内存使用和性能
+- [x] 完善单元测试覆盖(34 个测试用例全部通过)
+- [x] 添加性能基准测试
+- [x] 验证 HTML 模板与设计文档一致性
+- [x] 验证 10 秒缓存过期机制
+- [x] 创建部署脚本和系统服务配置
+- [x] 更新文档和 README.md(和 README.en.md)
+- [x] 测试高并发场景(200+ 连接)

+ 187 - 0
scripts/README.md

@@ -0,0 +1,187 @@
+# 部署脚本使用指南
+
+本目录包含了资源占用显示系统的部署脚本,用于简化安装和卸载过程。
+
+## 文件说明
+
+- `install.sh` - 自动安装脚本,适用于 systemd 系统
+- `uninstall.sh` - 卸载脚本,完全移除系统中的服务
+- `swb-sys-monitor.service` - systemd 服务配置文件
+
+## 安装脚本使用方法
+
+### 前置要求
+
+- Linux 系统(支持 systemd)
+- Root 权限
+- 网络连接(用于安装 Rust 依赖)
+
+### 安装步骤
+
+1. 确保脚本有执行权限:
+   ```bash
+   chmod +x scripts/install.sh
+   ```
+
+2. 运行安装脚本:
+   ```bash
+   sudo ./scripts/install.sh
+   ```
+
+3. 安装脚本会自动完成以下操作:
+   - 检查系统环境
+   - 安装 Rust 工具链(如果未安装)
+   - 编译项目
+   - 安装二进制文件到 `/usr/local/bin/`
+   - 配置 systemd 服务
+   - 启动服务
+
+### 验证安装
+
+安装完成后,可以通过以下方式验证:
+
+```bash
+# 检查服务状态
+systemctl status swb-sys-monitor
+
+# 查看服务日志
+journalctl -u swb-sys-monitor -f
+
+# 访问健康检查端点
+curl http://localhost:8080/health
+
+# 访问主页面
+curl http://localhost:8080
+```
+
+## 卸载脚本使用方法
+
+### 卸载步骤
+
+1. 确保脚本有执行权限:
+   ```bash
+   chmod +x scripts/uninstall.sh
+   ```
+
+2. 运行卸载脚本:
+   ```bash
+   sudo ./scripts/uninstall.sh
+   ```
+
+3. 卸载脚本会:
+   - 停止并禁用服务
+   - 删除 systemd 服务文件
+   - 删除二进制文件
+   - 可选:清理服务日志
+
+## 服务管理
+
+### 常用命令
+
+```bash
+# 启动服务
+sudo systemctl start swb-sys-monitor
+
+# 停止服务
+sudo systemctl stop swb-sys-monitor
+
+# 重启服务
+sudo systemctl restart swb-sys-monitor
+
+# 查看服务状态
+sudo systemctl status swb-sys-monitor
+
+# 启用开机自启
+sudo systemctl enable swb-sys-monitor
+
+# 禁用开机自启
+sudo systemctl disable swb-sys-monitor
+```
+
+### 查看日志
+
+```bash
+# 查看实时日志
+sudo journalctl -u swb-sys-monitor -f
+
+# 查看最近的日志
+sudo journalctl -u swb-sys-monitor --since "1 hour ago"
+
+# 查看错误日志
+sudo journalctl -u swb-sys-monitor -p err
+```
+
+## 自定义配置
+
+### 修改启动参数
+
+编辑服务配置文件:
+```bash
+sudo nano /etc/systemd/system/swb-sys-monitor.service
+```
+
+修改 `ExecStart` 行,添加所需参数:
+```ini
+ExecStart=/usr/local/bin/swb-sys-monitor --address 127.0.0.1 --port 3000 --ttl 5 --log-level debug
+```
+
+重新加载并重启服务:
+```bash
+sudo systemctl daemon-reload
+sudo systemctl restart swb-sys-monitor
+```
+
+### 修改端口
+
+如果需要修改监听端口,请同时修改:
+
+1. 服务配置文件中的 `ExecStart` 参数
+2. 防火墙规则(如果启用)
+
+```bash
+# 例如:开放 3000 端口
+sudo ufw allow 3000
+```
+
+## 故障排除
+
+### 常见问题
+
+1. **服务启动失败**
+   ```bash
+   # 查看详细错误信息
+   sudo journalctl -u swb-sys-monitor -n 50
+   ```
+
+2. **端口被占用**
+   ```bash
+   # 查看端口占用情况
+   sudo netstat -tlnp | grep :8080
+   # 或使用 ss 命令
+   sudo ss -tlnp | grep :8080
+   ```
+
+3. **权限问题**
+   ```bash
+   # 检查二进制文件权限
+   ls -la /usr/local/bin/swb-sys-monitor
+   
+   # 修复权限
+   sudo chmod +x /usr/local/bin/swb-sys-monitor
+   ```
+
+### 手动测试
+
+如果服务无法正常工作,可以手动运行测试:
+
+```bash
+# 切换到 nobody 用户(服务运行用户)
+sudo -u nobody /usr/local/bin/swb-sys-monitor --log-level debug
+```
+
+## 安全注意事项
+
+- 服务以 `nobody` 用户运行,具有最小权限
+- 只允许访问必要的系统文件(`/proc/stat`、`/proc/meminfo`、`/proc/sys/kernel/hostname`)
+- 使用 systemd 的安全限制(`ReadOnlyPaths`、`ProtectSystem` 等)
+- 建议在生产环境中配置防火墙规则

+ 45 - 0
scripts/get-version.bash

@@ -0,0 +1,45 @@
+#!/usr/bin/env bash
+# 从 Cargo.toml 中获取版本号 | Get version number from Cargo.toml
+
+# 设置定量 | Quantities
+## 当前脚本所在目录 | Current Script Directory
+SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
+## 仓库目录 | Repository Directory
+REPO_DIR="$(dirname "$SCRIPT_DIR")"
+## 文件路径 | File Path
+if [ -n "$1" ]; then
+  FILE_PATH="$1"
+else
+  FILE_PATH="$REPO_DIR/Cargo.toml"
+fi
+## 当前语言 | Current Language
+CURRENT_LANG=0 ### 0: en-US, 1: zh-Hans-CN
+
+# 语言检测 | Language Detection
+if [ $(echo ${LANG/_/-} | grep -Ei "\\b(zh|cn)\\b") ]; then CURRENT_LANG=1;  fi
+
+# 本地化 | Localization
+recho() {
+  if [ "$CURRENT_LANG" == "1" ]; then
+    ## zh-Hans-CN
+    echo "$1";
+  else
+    ## en-US
+    echo "$2";
+  fi
+}
+
+# 提取版本号并打印 | Extract version number and print
+if [ ! -f "$FILE_PATH" ]; then
+  recho "错误:文件 $FILE_PATH 不存在" "Error: File $FILE_PATH does not exist"
+  exit 1
+fi
+
+## 从 Cargo.toml 中提取 [package] 下 version 的值
+VERSION=$(grep -A 10 "\[package\]" "$FILE_PATH" | grep "^version" | sed -E 's/version = "([^"]+)"/\1/')
+if [ -z "$VERSION" ]; then
+  recho "错误:未找到版本号" "Error: Version not found"
+  exit 1
+fi
+
+echo "$VERSION"

+ 190 - 0
scripts/install.sh

@@ -0,0 +1,190 @@
+#!/bin/bash
+
+# 资源占用显示系统安装脚本
+# 支持 systemd 系统的自动安装和配置
+
+set -e
+
+# 颜色定义
+RED='\033[0;31m'
+GREEN='\033[0;32m'
+YELLOW='\033[1;33m'
+NC='\033[0m' # No Color
+
+# 打印函数
+print_info() {
+    echo -e "${GREEN}[INFO]${NC} $1"
+}
+
+print_warn() {
+    echo -e "${YELLOW}[WARN]${NC} $1"
+}
+
+print_error() {
+    echo -e "${RED}[ERROR]${NC} $1"
+}
+
+# 检查是否为 root 用户
+check_root() {
+    if [[ $EUID -ne 0 ]]; then
+        print_error "此脚本需要 root 权限运行"
+        exit 1
+    fi
+}
+
+# 检查系统类型
+check_system() {
+    if ! command -v systemctl &> /dev/null; then
+        print_error "此脚本仅支持 systemd 系统"
+        exit 1
+    fi
+    
+    if [[ ! -f /etc/os-release ]]; then
+        print_error "无法检测操作系统类型"
+        exit 1
+    fi
+    
+    source /etc/os-release
+    print_info "检测到操作系统: $NAME $VERSION"
+}
+
+# 检查 Rust 环境
+check_rust() {
+    if ! command -v cargo &> /dev/null; then
+        print_warn "未检测到 Rust 环境,正在安装..."
+        curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh -s -- -y
+        source $HOME/.cargo/env
+    else
+        print_info "检测到 Rust 环境: $(rustc --version)"
+    fi
+}
+
+# 创建系统用户
+create_user() {
+    if ! id "nobody" &>/dev/null; then
+        print_info "创建系统用户 nobody"
+        useradd --system --no-create-home --shell /usr/sbin/nologin nobody || true
+    else
+        print_info "系统用户 nobody 已存在"
+    fi
+}
+
+# 编译项目
+build_project() {
+    print_info "开始编译项目..."
+    
+    if [[ -d "swb-sys-monitor" ]]; then
+        cd swb-sys-monitor
+    else
+        print_error "项目目录不存在"
+        exit 1
+    fi
+    
+    print_info "运行 cargo build --release..."
+    cargo build --release
+    
+    if [[ ! -f "target/release/swb-sys-monitor" ]]; then
+        print_error "编译失败"
+        exit 1
+    fi
+    
+    print_info "编译成功"
+}
+
+# 安装二进制文件
+install_binary() {
+    print_info "安装二进制文件到 /usr/local/bin/"
+    
+    # 停止可能正在运行的服务
+    systemctl stop swb-sys-monitor 2>/dev/null || true
+    systemctl disable swb-sys-monitor 2>/dev/null || true
+    
+    # 复制二进制文件
+    cp target/release/swb-sys-monitor /usr/local/bin/
+    chmod +x /usr/local/bin/swb-sys-monitor
+    
+    print_info "二进制文件安装完成"
+}
+
+# 安装系统服务
+install_service() {
+    print_info "安装 systemd 服务..."
+    
+    # 复制服务文件
+    cp scripts/swb-sys-monitor.service /etc/systemd/system/
+    
+    # 重新加载 systemd
+    systemctl daemon-reload
+    
+    # 启用服务
+    systemctl enable swb-sys-monitor
+    
+    print_info "系统服务安装完成"
+}
+
+# 启动服务
+start_service() {
+    print_info "启动 swb-sys-monitor 服务..."
+    
+    systemctl start swb-sys-monitor
+    
+    # 等待服务启动
+    sleep 2
+    
+    # 检查服务状态
+    if systemctl is-active --quiet swb-sys-monitor; then
+        print_info "服务启动成功"
+        print_info "服务状态: $(systemctl is-active swb-sys-monitor)"
+    else
+        print_error "服务启动失败"
+        print_error "服务日志:"
+        journalctl -u swb-sys-monitor --no-pager -l
+        exit 1
+    fi
+}
+
+# 显示使用信息
+show_usage() {
+    print_info "安装完成!"
+    echo
+    print_info "服务管理命令:"
+    echo "  启动服务: systemctl start swb-sys-monitor"
+    echo "  停止服务: systemctl stop swb-sys-monitor"
+    echo "  重启服务: systemctl restart swb-sys-monitor"
+    echo "  查看状态: systemctl status swb-sys-monitor"
+    echo "  查看日志: journalctl -u swb-sys-monitor -f"
+    echo
+    print_info "访问地址: http://localhost:8080"
+    print_info "健康检查: http://localhost:8080/health"
+    echo
+    print_info "配置文件位置: /etc/systemd/system/swb-sys-monitor.service"
+    print_info "如需修改启动参数,请编辑服务文件后运行:"
+    echo "  systemctl daemon-reload"
+    echo "  systemctl restart swb-sys-monitor"
+}
+
+# 主函数
+main() {
+    print_info "开始安装资源占用显示系统..."
+    
+    check_root
+    check_system
+    check_rust
+    create_user
+    
+    # 获取项目目录
+    SCRIPT_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" &> /dev/null && pwd )"
+    PROJECT_DIR="$(dirname "$SCRIPT_DIR")"
+    cd "$PROJECT_DIR"
+    
+    build_project
+    install_binary
+    install_service
+    start_service
+    show_usage
+    
+    print_info "安装完成!"
+}
+
+# 运行主函数
+main "$@"

+ 50 - 0
scripts/is-newer-version.bash

@@ -0,0 +1,50 @@
+#!/usr/bin/env bash
+# 判断是否需要发行新版本 | Checking for a Newer Version
+
+# 设置定量 | Quantities
+## 当前脚本所在目录 | Current Script Directory
+SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
+## 仓库目录 | Repository Directory
+REPO_DIR="$(dirname "$SCRIPT_DIR")"
+## 当前语言 | Current Language
+CURRENT_LANG=0 ### 0: en-US, 1: zh-Hans-CN
+
+# 语言检测 | Language Detection
+if [ $(echo ${LANG/_/-} | grep -Ei "\\b(zh|cn)\\b") ]; then CURRENT_LANG=1;  fi
+
+# 本地化 | Localization
+recho() {
+  if [ "$CURRENT_LANG" == "1" ]; then
+    ## zh-Hans-CN
+    echo "$1";
+  else
+    ## en-US
+    echo "$2";
+  fi
+}
+
+# 获取当前版本号 | Get current version number
+CURRENT_VERSION=$("$SCRIPT_DIR/get-version.bash")
+if [ $? -ne 0 ]; then
+  exit 1
+fi
+
+# 获取最新的 git 标签版本 | Get the latest git tag version
+LATEST_TAG=$(git -C "$REPO_DIR" tag -l 'v*' --sort=-v:refname | head -1)
+if [ -z "$LATEST_TAG" ]; then
+  # 没有标签时默认为需要发布 | No tags, assume it needs to be released
+  echo "$CURRENT_VERSION"
+  exit 0
+fi
+
+# 去除标签中的 v 前缀 | Remove the v prefix from the tag
+LATEST_VERSION=${LATEST_TAG#v}
+
+# 比较版本号 | Compare version numbers
+if [ "$(printf "%s\n%s" "$CURRENT_VERSION" "$LATEST_VERSION" | sort -V | head -n1)" != "$CURRENT_VERSION" ]; then
+  # 当前版本较新,需要发布 | The current version is newer, needs to be released
+  echo "$CURRENT_VERSION"
+else
+  # 已经是最新版本 | Already the latest version
+  echo "0"
+fi

+ 425 - 0
scripts/publish-crates-io.bash

@@ -0,0 +1,425 @@
+#!/usr/bin/env bash
+# 发布软件包至 crates.io | Publish to crates.io
+
+# 设置定量 | Quantities
+## 当前脚本所在目录 | Current Script Directory
+SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
+## 仓库目录 | Repository Directory
+REPO_DIR="$(dirname "$SCRIPT_DIR")"
+## 当前语言 | Current Language
+CURRENT_LANG=0 ### 0: en-US, 1: zh-Hans-CN
+
+# 语言检测 | Language Detection
+if [ $(echo ${LANG/_/-} | grep -Ei "\\b(zh|cn)\\b") ]; then CURRENT_LANG=1;  fi
+
+# 本地化 | Localization
+recho() {
+  if [ "$CURRENT_LANG" == "1" ]; then
+    ## zh-Hans-CN
+    echo -e "$1"
+  else
+    ## en-US
+    echo -e "$2"
+  fi
+}
+
+# 颜色定义 | Color definitions
+RED='\033[0;31m'
+GREEN='\033[0;32m'
+YELLOW='\033[1;33m'
+NC='\033[0m' # No Color
+
+# 显示帮助信息 | Show help message
+show_help() {
+  recho \
+    "用法: $0 [选项] [API_TOKEN]
+选项:
+  -h, --help         显示此帮助信息
+  -n, --dry-run      只进行预检,不实际发布
+  -y, --yes          自动确认发布,无需交互
+  -r, --registry     指定要发布的注册表(例如:crates-io)
+参数:
+  API_TOKEN          crates.io 的 API 令牌(可选,也可以通过 CARGO_REGISTRY_TOKEN 环境变量设置)
+示例:
+  $0                       # 使用已保存的令牌或环境变量
+  $0 -n                    # 预检模式
+  $0 -y                    # 自动确认发布
+  $0 -r crates-io          # 指定注册表
+  $0 YOUR_API_TOKEN        # 使用指定的 API 令牌
+  CARGO_REGISTRY_TOKEN=YOUR_API_TOKEN $0  # 通过环境变量设置令牌" \
+    "Usage: $0 [options] [API_TOKEN]
+Options:
+  -h, --help         Show this help message
+  -n, --dry-run      Dry run mode, only performs checks without publishing
+  -y, --yes          Automatically confirm publication without interaction
+  -r, --registry     Specify the registry to publish to (e.g., crates-io)
+Arguments:
+  API_TOKEN          API token for crates.io (optional, can also be set via CARGO_REGISTRY_TOKEN environment variable)
+Examples:
+  $0                       # Use saved token or environment variable
+  $0 -n                    # Dry run mode
+  $0 -y                    # Automatically confirm publication
+  $0 -r crates-io          # Specify registry
+  $0 YOUR_API_TOKEN        # Use specified API token
+  CARGO_REGISTRY_TOKEN=YOUR_API_TOKEN $0  # Set token via environment variable"
+}
+
+# 默认参数 | Default arguments
+DRY_RUN=false
+AUTO_CONFIRM=false
+REGISTRY=""
+
+# 解析命令行参数 | Parse command line arguments
+while [[ $# -gt 0 ]]; do
+  case $1 in
+    -h|--help)
+      show_help
+      exit 0
+      ;;
+    -n|--dry-run)
+      DRY_RUN=true
+      shift
+      ;;
+    -y|--yes)
+      AUTO_CONFIRM=true
+      shift
+      ;;
+    -r|--registry)
+      REGISTRY="$2"
+      shift 2
+      ;;
+    -*)
+      recho \
+        "${RED}错误: 未知选项 $1${NC}" \
+        "${RED}Error: Unknown option $1${NC}"
+      show_help
+      exit 1
+      ;;
+    *)
+      API_TOKEN="$1"
+      shift
+      ;;
+  esac
+done
+
+# 构建 cargo publish 命令的参数 | Build cargo publish command arguments
+CARGO_PUBLISH_ARGS=""
+if [ -n "$REGISTRY" ]; then
+  CARGO_PUBLISH_ARGS="--registry $REGISTRY"
+fi
+
+# 检查是否已安装 cargo | Check if cargo is installed
+if ! command -v cargo &> /dev/null; then
+  recho \
+    "${RED}错误: 未找到 cargo 命令,请先安装 Rust 工具链${NC}" \
+    "${RED}Error: cargo command not found, please install Rust toolchain first${NC}"
+  exit 1
+fi
+
+# 检查 jq 是否已安装 | Check if jq is installed
+if ! command -v jq &> /dev/null; then
+  recho \
+    "${RED}错误: 未找到 jq 命令,请先安装 jq${NC}" \
+    "${RED}Error: jq command not found, please install jq first${NC}"
+  exit 1
+fi
+
+# 获取 API 令牌 | Get API token
+# 如果提供了 API 令牌,则登录 | Login if API token is provided
+if [ -n "$API_TOKEN" ]; then
+  recho \
+    "${YELLOW}正在使用提供的 API 令牌登录...${NC}" \
+    "${YELLOW}Logging in with provided API token...${NC}"
+  cargo login "$API_TOKEN"
+  if [ $? -ne 0 ]; then
+    recho \
+      "${RED}错误: 登录失败${NC}" \
+      "${RED}Error: Login failed${NC}"
+    exit 1
+  fi
+else
+  # 检查环境变量 | Check environment variable
+  if [ -z "$CARGO_REGISTRY_TOKEN" ]; then
+    recho \
+      "${YELLOW}警告: 未提供 API 令牌,且未设置 CARGO_REGISTRY_TOKEN 环境变量。发布可能会失败。${NC}" \
+      "${YELLOW}Warning: No API token provided, and CARGO_REGISTRY_TOKEN environment variable is not set. Publication may fail.${NC}"
+  else
+    recho \
+      "${YELLOW}未提供 API 令牌,将使用 CARGO_REGISTRY_TOKEN 环境变量${NC}" \
+      "${YELLOW}No API token provided, will use CARGO_REGISTRY_TOKEN environment variable${NC}"
+  fi
+fi
+
+# 进入仓库目录 | Change to repository directory
+cd "$REPO_DIR" || {
+  recho \
+    "${RED}错误: 无法进入仓库目录 $REPO_DIR${NC}" \
+    "${RED}Error: Cannot enter repository directory $REPO_DIR${NC}"
+  exit 1
+}
+
+# 检查项目结构 | Check project structure
+recho \
+  "${YELLOW}检查项目结构...${NC}" \
+  "${YELLOW}Checking project structure...${NC}"
+
+if [ ! -f "Cargo.toml" ]; then
+  recho \
+    "${RED}错误: 未找到根 Cargo.toml 文件${NC}" \
+    "${RED}Error: Root Cargo.toml file not found${NC}"
+  exit 1
+fi
+
+# 检查包信息 | Check package information
+recho \
+  "${YELLOW}检查包信息...${NC}" \
+  "${YELLOW}Checking package information...${NC}"
+
+# 获取包元数据 | Get package metadata
+metadata=$(cargo metadata --no-deps --format-version 1)
+if [ $? -ne 0 ]; then
+  recho \
+    "${RED}错误: 获取包元数据失败${NC}" \
+    "${RED}Error: Failed to get package metadata${NC}"
+  exit 1
+fi
+
+# 检查是否是工作区 | Check if this is a workspace
+# 检查是否有 resolve 字段来判断是否为工作区 | Check if there's a resolve field to determine if it's a workspace
+resolve_check=$(echo "$metadata" | jq -r '.resolve' 2>/dev/null)
+workspace_members=$(echo "$metadata" | jq -r '.workspace_members[]' 2>/dev/null)
+
+if [ "$resolve_check" != "null" ] && [ -n "$resolve_check" ]; then
+  # 工作区模式 | Workspace mode
+  recho \
+    "${YELLOW}检测到工作区项目${NC}" \
+    "${YELLOW}Workspace project detected${NC}"
+  
+  # Extract package names from workspace_members
+  members=$(echo "$metadata" | jq -r '.workspace_members[]' | sed 's/.*#\([^@]*\)@.*/\1/')
+  if [ -z "$members" ]; then
+    recho \
+      "${RED}错误: 未找到工作区成员${NC}" \
+      "${RED}Error: No workspace members found${NC}"
+    exit 1
+  fi
+else
+  # 单包模式 | Single package mode
+  recho \
+    "${YELLOW}检测到单包项目${NC}" \
+    "${YELLOW}Single package project detected${NC}"
+  
+  # 获取当前包名 | Get current package name
+  package_name=$(echo "$metadata" | jq -r '.packages[] | select(.name != null) | .name')
+  if [ -z "$package_name" ]; then
+    recho \
+      "${RED}错误: 未找到包名${NC}" \
+      "${RED}Error: Package name not found${NC}"
+    exit 1
+  fi
+  members="$package_name"
+fi
+
+# 显示要发布的包 | Show packages to be published
+recho \
+  "${YELLOW}要发布的包:${NC}" \
+  "${YELLOW}Packages to be published:${NC}"
+echo "$members"
+
+# 确认发布 | Confirm publication
+if [ "$DRY_RUN" = false ]; then
+  if [ "$AUTO_CONFIRM" = false ]; then
+    recho \
+      "${YELLOW}是否继续发布?(y/N)${NC}" \
+      "${YELLOW}Continue with publication? (y/N)${NC}"
+    read -r confirm
+    if [[ ! "$confirm" =~ ^[Yy]$ ]]; then
+      recho \
+        "${YELLOW}已取消发布${NC}" \
+        "${YELLOW}Publication cancelled${NC}"
+      exit 0
+    fi
+  else
+    recho \
+      "${YELLOW}自动确认发布,无需交互。${NC}" \
+      "${YELLOW}Automatically confirming publication without interaction.${NC}"
+  fi
+else
+  recho \
+    "${YELLOW}进入预检模式,将只进行检查,不实际发布。${NC}" \
+    "${YELLOW}Entering dry run mode, will only perform checks without publishing.${NC}"
+fi
+
+# 确定发布顺序 | Determine publish order
+recho \
+  "${YELLOW}正在确定发布顺序...${NC}" \
+  "${YELLOW}Determining publish order...${NC}"
+
+# 检查是否是工作区模式 | Check if this is workspace mode
+resolve_check=$(echo "$metadata" | jq -r '.resolve' 2>/dev/null)
+if [ "$resolve_check" != "null" ] && [ -n "$resolve_check" ]; then
+  # 工作区模式 - 需要处理依赖关系 | Workspace mode - need to handle dependencies
+  recho \
+    "${YELLOW}工作区模式:解析包依赖关系...${NC}" \
+    "${YELLOW}Workspace mode: Resolving package dependencies...${NC}"
+  
+  # 创建一个数组来存储包及其依赖关系 | Create an array to store packages and their dependencies
+  declare -A dependencies
+
+  # 解析依赖关系 | Parse dependencies
+  while IFS= read -r member; do
+    # 获取直接依赖 | Get direct dependencies
+    deps=$(echo "$metadata" | jq -r --arg name "$member" '.packages[] | select(.name == $name) | .dependencies[] | select(.name | startswith("swb-")) | .name')
+
+    # 将依赖关系存储在数组中
+    dependencies["$member"]="$deps"
+  done <<< "$members"
+
+  # 使用 Kahn 算法进行拓扑排序 | Use Kahn's algorithm for topological sorting
+  # 初始化入度数组 | Initialize the in-degree array
+  declare -A in_degree
+  for member in $members; do
+    in_degree["$member"]=0
+  done
+
+  # 计算每个节点的入度 | Calculate the in-degree of each node
+  for member in $members; do
+    deps=${dependencies["$member"]}
+    for dep in $deps; do
+      if [[ -n "${in_degree[$dep]}" ]]; then
+        in_degree["$dep"]=$((${in_degree["$dep"]} + 1))
+      fi
+    done
+  done
+
+  # 初始化队列 | Initialize the queue
+  queue=()
+  for member in $members; do
+    if [[ ${in_degree["$member"]} -eq 0 ]]; then
+      queue+=("$member")
+    fi
+  done
+
+  # 拓扑排序结果 | Topological sort result
+  publish_order=()
+
+  # Kahn 算法主循环 | Kahn's algorithm main loop
+  while [[ ${#queue[@]} -gt 0 ]]; do
+    # 取出队列中的第一个元素 | Remove the first element from the queue
+    current=${queue[0]}
+    queue=("${queue[@]:1}")
+
+    # 添加到发布顺序中 | Add to the publish order
+    publish_order+=("$current")
+
+    # 更新其依赖项的入度 | Update the in-degree of its dependencies
+    deps=${dependencies["$current"]}
+    for dep in $deps; do
+      if [[ -n "${in_degree[$dep]}" ]]; then
+        in_degree["$dep"]=$((${in_degree["$dep"]} - 1))
+        if [[ ${in_degree["$dep"]} -eq 0 ]]; then
+          queue+=("$dep")
+        fi
+      fi
+    done
+  done
+
+  # 检查是否存在循环依赖 | Check for circular dependencies
+  if [[ ${#publish_order[@]} -ne $(echo "$members" | wc -w) ]]; then
+    recho \
+      "${RED}错误: 无法确定发布顺序,请检查包之间的依赖关系是否存在循环。${NC}" \
+      "${RED}Error: Could not determine publish order, please check for circular dependencies between packages.${NC}"
+    exit 1
+  fi
+
+  # 反转顺序以获得正确的发布顺序 | Reverse the order to get the correct publish order
+  publish_order_reversed=()
+  for ((i=${#publish_order[@]}-1; i>=0; i--)); do
+    publish_order_reversed+=("${publish_order[i]}")
+  done
+
+  # 显示发布顺序 | Show publish order
+  recho \
+    "${YELLOW}发布顺序:${NC}" \
+    "${YELLOW}Publish order:${NC}"
+  printf '%s\n' "${publish_order_reversed[@]}"
+else
+  # 单包模式 - 直接发布 | Single package mode - publish directly
+  recho \
+    "${YELLOW}单包模式:直接发布${NC}" \
+    "${YELLOW}Single package mode: Publishing directly${NC}"
+  
+  publish_order_reversed=($members)
+  echo "$members"
+fi
+
+# 发布包 | Publish packages
+recho \
+  "${YELLOW}开始${DRY_RUN:+预检}发布包……${NC}" \
+  "${YELLOW}Starting${DRY_RUN:+ dry run} package publication...${NC}"
+
+# 遍历发布顺序并发布每个包 | Iterate through the publish order and publish each package
+for package in "${publish_order_reversed[@]}"; do
+  # 查找包的目录 | Find package directory
+  package_dir=$(echo "$metadata" | jq -r --arg name "$package" '.packages[] | select(.name == $name) | .manifest_path' | xargs dirname)
+
+  if [ -d "$package_dir" ] && [ -f "$package_dir/Cargo.toml" ]; then
+    recho \
+      "${YELLOW}正在${DRY_RUN:+预检}发布 $package 包……${NC}" \
+      "${YELLOW}${DRY_RUN:+Dry run: }Publishing $package package...${NC}"
+
+    cd "$package_dir" || exit 1
+
+    if [ "$DRY_RUN" = true ]; then
+      # 预检模式 | Dry run mode
+      cargo publish --dry-run $CARGO_PUBLISH_ARGS
+      if [ $? -eq 0 ]; then
+        recho \
+          "${GREEN}$package 包预检成功${NC}" \
+          "${GREEN}$package package dry run successful${NC}"
+      else
+        recho \
+          "${RED}错误: $package 包预检失败${NC}" \
+          "${RED}Error: $package package dry run failed${NC}"
+        exit 1
+      fi
+    else
+      # 实际发布模式 | Actual publish mode
+      cargo publish $CARGO_PUBLISH_ARGS
+      if [ $? -eq 0 ]; then
+        recho \
+          "${GREEN}$package 包发布成功${NC}" \
+          "${GREEN}$package package published successfully${NC}"
+      else
+        recho \
+          "${RED}错误: $package 包发布失败${NC}" \
+          "${RED}Error: $package package publication failed${NC}"
+        exit 1
+      fi
+
+      # 如果不是最后一个包,则等待几秒钟 | Wait a few seconds if it's not the last package
+      if [ "$package" != "${publish_order_reversed[-1]}" ]; then
+        recho \
+          "${YELLOW}等待 10 秒钟以确保 $package 包在 crates.io 上可用...${NC}" \
+          "${YELLOW}Waiting 10 seconds to ensure $package package is available on crates.io...${NC}"
+        sleep 10
+      fi
+    fi
+
+    cd "$REPO_DIR" || exit 1
+  else
+    recho \
+      "${YELLOW}警告: 找不到 $package 包的目录或 Cargo.toml 文件,已跳过。${NC}" \
+      "${YELLOW}Warning: Could not find directory or Cargo.toml file for $package package, skipped.${NC}"
+  fi
+done
+
+if [ "$DRY_RUN" = true ]; then
+  recho \
+    "${GREEN}所有包都已成功通过预检!${NC}" \
+    "${GREEN}All packages have passed dry run successfully!${NC}"
+else
+  recho \
+    "${GREEN}所有包都已成功发布!${NC}" \
+    "${GREEN}All packages have been published successfully!${NC}"
+fi

+ 127 - 0
scripts/setup-pre-commit-hooks.bat

@@ -0,0 +1,127 @@
+@echo off
+setlocal enabledelayedexpansion
+
+:: ANSI color codes for Windows 10+ Command Prompt
+set "RED=[91m"
+set "GREEN=[92m"
+set "YELLOW=[93m"
+set "BLUE=[94m"
+set "CYAN=[96m"
+set "NC=[0m"
+
+:: Function to print colored log messages
+goto :main
+
+:log_info
+echo %CYAN%[INFO]%NC% %~1
+goto :eof
+
+:log_success
+echo %GREEN%[SUCCESS]%NC% %~1
+goto :eof
+
+:log_warning
+echo %YELLOW%[WARNING]%NC% %~1
+goto :eof
+
+:log_error
+echo %RED%[ERROR]%NC% %~1
+goto :eof
+
+:main
+:: Check if we're in a git repository
+if not exist ".git" (
+    call :log_error "Not in a git repository. Please run this script from the root of your git repository."
+    exit /b 1
+)
+
+call :log_info "Setting up pre-commit hooks..."
+
+:: Create .git/hooks directory if it doesn't exist
+if not exist ".git\hooks" (
+    call :log_info "Creating .git/hooks directory..."
+    mkdir ".git\hooks"
+)
+
+:: Create the pre-commit hook content
+call :log_info "Writing pre-commit hook to .git/hooks/pre-commit..."
+
+(
+echo @echo off
+echo setlocal enabledelayedexpansion
+echo.
+echo :: ANSI color codes for Windows 10+ Command Prompt
+echo set "RED=[91m"
+echo set "GREEN=[92m"
+echo set "YELLOW=[93m"
+echo set "BLUE=[94m"
+echo set "CYAN=[96m"
+echo set "NC=[0m"
+echo.
+echo echo %%CYAN%%[INFO]%%NC%% Running pre-commit checks...
+echo.
+echo :: Check if cargo is available
+echo where cargo ^>nul 2^>^&1
+echo if ^^!errorlevel^^! neq 0 ^(
+echo     echo %%RED%%[ERROR]%%NC%% Cargo is not installed or not in PATH
+echo     exit /b 1
+echo ^)
+echo.
+echo :: Run cargo fmt check
+echo echo %%CYAN%%[INFO]%%NC%% Checking code formatting with cargo fmt...
+echo cargo fmt --all -- --check ^>nul 2^>^&1
+echo if ^^!errorlevel^^! neq 0 ^(
+echo     echo %%RED%%[ERROR]%%NC%% Code formatting check failed. Please run 'cargo fmt' to fix formatting issues.
+echo     exit /b 1
+echo ^)
+echo echo %%GREEN%%[SUCCESS]%%NC%% Code formatting check passed
+echo.
+echo :: Run cargo clippy
+echo echo %%CYAN%%[INFO]%%NC%% Running cargo clippy...
+echo cargo clippy --all-targets --all-features -- -D warnings -A dead_code ^>nul 2^>^&1
+echo if ^^!errorlevel^^! neq 0 ^(
+echo     echo %%RED%%[ERROR]%%NC%% Clippy check failed. Please fix the warnings and errors.
+echo     exit /b 1
+echo ^)
+echo echo %%GREEN%%[SUCCESS]%%NC%% Clippy check passed
+echo.
+echo :: Run tests
+echo echo %%CYAN%%[INFO]%%NC%% Running tests...
+echo cargo test ^>nul 2^>^&1
+echo if ^^!errorlevel^^! neq 0 ^(
+echo     echo %%RED%%[ERROR]%%NC%% Tests failed. Please fix the failing tests.
+echo     exit /b 1
+echo ^)
+echo echo %%GREEN%%[SUCCESS]%%NC%% All tests passed
+echo.
+echo echo %%GREEN%%[SUCCESS]%%NC%% All pre-commit checks passed!
+) > ".git\hooks\pre-commit"
+
+:: Also create .cmd version for Windows compatibility
+copy ".git\hooks\pre-commit" ".git\hooks\pre-commit.cmd" >nul
+
+:: Set executable permissions
+call :log_info "Setting executable permissions on pre-commit hooks..."
+icacls ".git\hooks\pre-commit" /grant Everyone:F >nul 2>&1
+icacls ".git\hooks\pre-commit.cmd" /grant Everyone:F >nul 2>&1
+if !errorlevel! equ 0 (
+    call :log_info "Executable permissions set successfully"
+) else (
+    call :log_warning "Could not set executable permissions"
+)
+
+:: Verify the installation
+if exist ".git\hooks\pre-commit" (
+    if exist ".git\hooks\pre-commit.cmd" (
+        call :log_success "Pre-commit hook successfully installed!"
+        call :log_info "The hook will run automatically before each commit."
+        call :log_info "Created both 'pre-commit' and 'pre-commit.cmd' for maximum Windows compatibility."
+        call :log_info "To test the hook manually, run: .git/hooks/pre-commit.cmd"
+    ) else (
+        call :log_error "Failed to create .cmd version of pre-commit hook"
+        exit /b 1
+    )
+) else (
+    call :log_error "Failed to install pre-commit hook"
+    exit /b 1
+)

+ 116 - 0
scripts/setup-pre-commit-hooks.ps1

@@ -0,0 +1,116 @@
+# PowerShell script to setup pre-commit hooks
+
+# Function to print colored log messages
+function Write-LogInfo {
+    param([string]$Message)
+    Write-Host "[INFO] $Message" -ForegroundColor Cyan
+}
+
+function Write-LogSuccess {
+    param([string]$Message)
+    Write-Host "[SUCCESS] $Message" -ForegroundColor Green
+}
+
+function Write-LogWarning {
+    param([string]$Message)
+    Write-Host "[WARNING] $Message" -ForegroundColor Yellow
+}
+
+function Write-LogError {
+    param([string]$Message)
+    Write-Host "[ERROR] $Message" -ForegroundColor Red
+}
+
+# Check if we're in a git repository
+if (-not (Test-Path ".git")) {
+    Write-LogError "Not in a git repository. Please run this script from the root of your git repository."
+    exit 1
+}
+
+Write-LogInfo "Setting up pre-commit hooks..."
+
+# Create .git/hooks directory if it doesn't exist
+if (-not (Test-Path ".git/hooks")) {
+    Write-LogInfo "Creating .git/hooks directory..."
+    New-Item -ItemType Directory -Path ".git/hooks" -Force | Out-Null
+}
+
+# Pre-commit hook content (Windows batch version)
+$PreCommitHookContent = @'
+@echo off
+setlocal enabledelayedexpansion
+
+:: ANSI color codes for Windows 10+ Command Prompt
+set "RED=[91m"
+set "GREEN=[92m"
+set "YELLOW=[93m"
+set "BLUE=[94m"
+set "CYAN=[96m"
+set "NC=[0m"
+
+echo %CYAN%[INFO]%NC% Running pre-commit checks...
+
+:: Check if cargo is available
+where cargo >nul 2>&1
+if !errorlevel! neq 0 (
+    echo %RED%[ERROR]%NC% Cargo is not installed or not in PATH
+    exit /b 1
+)
+
+:: Run cargo fmt check
+echo %CYAN%[INFO]%NC% Checking code formatting with cargo fmt...
+cargo fmt --all -- --check >nul 2>&1
+if !errorlevel! neq 0 (
+    echo %RED%[ERROR]%NC% Code formatting check failed. Please run 'cargo fmt' to fix formatting issues.
+    exit /b 1
+)
+echo %GREEN%[SUCCESS]%NC% Code formatting check passed
+
+:: Run cargo clippy
+echo %CYAN%[INFO]%NC% Running cargo clippy...
+cargo clippy --all-targets --all-features -- -D warnings -A dead_code >nul 2>&1
+if !errorlevel! neq 0 (
+    echo %RED%[ERROR]%NC% Clippy check failed. Please fix the warnings and errors.
+    exit /b 1
+)
+echo %GREEN%[SUCCESS]%NC% Clippy check passed
+
+:: Run tests
+echo %CYAN%[INFO]%NC% Running tests...
+cargo test >nul 2>&1
+if !errorlevel! neq 0 (
+    echo %RED%[ERROR]%NC% Tests failed. Please fix the failing tests.
+    exit /b 1
+)
+echo %GREEN%[SUCCESS]%NC% All tests passed
+
+echo %GREEN%[SUCCESS]%NC% All pre-commit checks passed!
+'@
+
+# Write the pre-commit hook (both standard and .cmd versions for Windows compatibility)
+Write-LogInfo "Writing pre-commit hook to .git/hooks/pre-commit..."
+$PreCommitHookContent | Out-File -FilePath ".git/hooks/pre-commit" -Encoding ASCII
+$PreCommitHookContent | Out-File -FilePath ".git/hooks/pre-commit.cmd" -Encoding ASCII
+
+# Set executable permissions (Windows equivalent)
+try {
+    $acl = Get-Acl ".git/hooks/pre-commit"
+    $accessRule = New-Object System.Security.AccessControl.FileSystemAccessRule("Everyone", "FullControl", "Allow")
+    $acl.SetAccessRule($accessRule)
+    Set-Acl ".git/hooks/pre-commit" $acl
+    Set-Acl ".git/hooks/pre-commit.cmd" $acl
+    Write-LogInfo "Set executable permissions on pre-commit hooks"
+} catch {
+    Write-LogWarning "Could not set executable permissions: $($_.Exception.Message)"
+}
+
+# Verify the installation
+if ((Test-Path ".git/hooks/pre-commit") -and (Test-Path ".git/hooks/pre-commit.cmd")) {
+    Write-LogSuccess "Pre-commit hook successfully installed!"
+    Write-LogInfo "The hook will run automatically before each commit."
+    Write-LogInfo "Created both 'pre-commit' and 'pre-commit.cmd' for maximum Windows compatibility."
+    Write-LogInfo "To test the hook manually, run: .git/hooks/pre-commit.cmd"
+} else {
+    Write-LogError "Failed to install pre-commit hook"
+    exit 1
+}

+ 120 - 0
scripts/setup-pre-commit-hooks.sh

@@ -0,0 +1,120 @@
+#!/bin/bash
+
+# Colors for output
+RED='\033[0;31m'
+GREEN='\033[0;32m'
+YELLOW='\033[1;33m'
+BLUE='\033[0;34m'
+CYAN='\033[0;36m'
+NC='\033[0m' # No Color
+
+# Function to print colored log messages
+log_info() {
+    echo -e "${CYAN}[INFO]${NC} $1"
+}
+
+log_success() {
+    echo -e "${GREEN}[SUCCESS]${NC} $1"
+}
+
+log_warning() {
+    echo -e "${YELLOW}[WARNING]${NC} $1"
+}
+
+log_error() {
+    echo -e "${RED}[ERROR]${NC} $1"
+}
+
+# Check if we're in a git repository
+if [ ! -d ".git" ]; then
+    log_error "Not in a git repository. Please run this script from the root of your git repository."
+    exit 1
+fi
+
+log_info "Setting up pre-commit hooks..."
+
+# Create .git/hooks directory if it doesn't exist
+if [ ! -d ".git/hooks" ]; then
+    log_info "Creating .git/hooks directory..."
+    mkdir -p .git/hooks
+fi
+
+# Create the pre-commit hook file
+cat > .git/hooks/pre-commit << 'EOF'
+#!/bin/bash
+
+# Colors for output
+RED='\033[0;31m'
+GREEN='\033[0;32m'
+YELLOW='\033[1;33m'
+BLUE='\033[0;34m'
+CYAN='\033[0;36m'
+NC='\033[0m' # No Color
+
+log_info() {
+    echo -e "${CYAN}[INFO]${NC} $1"
+}
+
+log_success() {
+    echo -e "${GREEN}[SUCCESS]${NC} $1"
+}
+
+log_warning() {
+    echo -e "${YELLOW}[WARNING]${NC} $1"
+}
+
+log_error() {
+    echo -e "${RED}[ERROR]${NC} $1"
+}
+
+log_info "Running pre-commit checks..."
+
+# Check if cargo is available
+if ! command -v cargo &> /dev/null; then
+    log_error "Cargo is not installed or not in PATH"
+    exit 1
+fi
+
+# Run cargo fmt check
+log_info "Checking code formatting with cargo fmt..."
+if ! cargo fmt --all -- --check; then
+    log_error "Code formatting check failed. Please run '\''cargo fmt'\'' to fix formatting issues."
+    exit 1
+fi
+log_success "Code formatting check passed"
+
+# Run cargo clippy
+log_info "Running cargo clippy..."
+if ! cargo clippy --all-targets --all-features -- -D warnings -A dead_code; then
+    log_error "Clippy check failed. Please fix the warnings and errors."
+    exit 1
+fi
+log_success "Clippy check passed"
+
+# Run tests
+log_info "Running tests..."
+if ! cargo test; then
+    log_error "Tests failed. Please fix the failing tests."
+    exit 1
+fi
+log_success "All tests passed"
+
+log_success "All pre-commit checks passed!"
+EOF
+
+# Write the pre-commit hook
+log_info "Writing pre-commit hook to .git/hooks/pre-commit..."
+
+# Make the hook executable
+chmod +x .git/hooks/pre-commit
+log_success "Pre-commit hook installed and made executable"
+
+# Verify the installation
+if [ -f ".git/hooks/pre-commit" ] && [ -x ".git/hooks/pre-commit" ]; then
+    log_success "Pre-commit hook successfully installed!"
+    log_info "The hook will run automatically before each commit."
+    log_info "To test the hook manually, run: .git/hooks/pre-commit"
+else
+    log_error "Failed to install pre-commit hook"
+    exit 1
+fi

+ 38 - 0
scripts/swb-sys-monitor.service

@@ -0,0 +1,38 @@
+[Unit]
+Description=Resource Status Monitor
+Documentation=https://github.com/swaybien/swb-sys-monitor
+After=network.target
+Wants=network.target
+
+[Service]
+Type=simple
+User=nobody
+Group=nogroup
+ExecStart=/usr/local/bin/swb-sys-monitor --log-level info
+ExecReload=/bin/kill -HUP $MAINPID
+Restart=always
+RestartSec=5
+StandardOutput=journal
+StandardError=journal
+SyslogIdentifier=swb-sys-monitor
+
+# 安全设置
+NoNewPrivileges=true
+PrivateTmp=true
+ProtectSystem=strict
+ProtectHome=true
+ReadWritePaths=/var/log
+ReadOnlyPaths=/proc/stat:/proc/meminfo:/proc/sys/kernel/hostname
+
+# 资源限制
+LimitNOFILE=65536
+LimitNPROC=4096
+
+# 网络设置
+IPAddressDeny=any
+IPAddressAllow=localhost
+IPAddressAllow=127.0.0.1/8
+IPAddressAllow=::1/128
+
+[Install]
+WantedBy=multi-user.target

+ 125 - 0
scripts/uninstall.sh

@@ -0,0 +1,125 @@
+#!/bin/bash
+
+# 资源占用显示系统卸载脚本
+
+set -e
+
+# 颜色定义
+RED='\033[0;31m'
+GREEN='\033[0;32m'
+YELLOW='\033[1;33m'
+NC='\033[0m' # No Color
+
+# 打印函数
+print_info() {
+    echo -e "${GREEN}[INFO]${NC} $1"
+}
+
+print_warn() {
+    echo -e "${YELLOW}[WARN]${NC} $1"
+}
+
+print_error() {
+    echo -e "${RED}[ERROR]${NC} $1"
+}
+
+# 检查是否为 root 用户
+check_root() {
+    if [[ $EUID -ne 0 ]]; then
+        print_error "此脚本需要 root 权限运行"
+        exit 1
+    fi
+}
+
+# 停止并禁用服务
+stop_service() {
+    print_info "停止并禁用 swb-sys-monitor 服务..."
+    
+    if systemctl is-active --quiet swb-sys-monitor 2>/dev/null; then
+        systemctl stop swb-sys-monitor
+        print_info "服务已停止"
+    else
+        print_info "服务未运行"
+    fi
+    
+    if systemctl is-enabled --quiet swb-sys-monitor 2>/dev/null; then
+        systemctl disable swb-sys-monitor
+        print_info "服务已禁用"
+    else
+        print_info "服务未启用"
+    fi
+}
+
+# 删除系统服务文件
+remove_service() {
+    print_info "删除系统服务文件..."
+    
+    if [[ -f /etc/systemd/system/swb-sys-monitor.service ]]; then
+        rm -f /etc/systemd/system/swb-sys-monitor.service
+        systemctl daemon-reload
+        print_info "系统服务文件已删除"
+    else
+        print_info "系统服务文件不存在"
+    fi
+}
+
+# 删除二进制文件
+remove_binary() {
+    print_info "删除二进制文件..."
+    
+    if [[ -f /usr/local/bin/swb-sys-monitor ]]; then
+        rm -f /usr/local/bin/swb-sys-monitor
+        print_info "二进制文件已删除"
+    else
+        print_info "二进制文件不存在"
+    fi
+}
+
+# 清理日志文件(可选)
+clean_logs() {
+    read -p "是否要清理服务日志?[y/N]: " -n 1 -r
+    echo
+    if [[ $REPLY =~ ^[Yy]$ ]]; then
+        print_info "清理服务日志..."
+        journalctl --vacuum-time=1d -u swb-sys-monitor 2>/dev/null || true
+        print_info "日志已清理"
+    fi
+}
+
+# 确认卸载
+confirm_uninstall() {
+    echo
+    print_warn "即将卸载资源占用显示系统"
+    print_warn "这将删除:"
+    echo "  - 系统服务文件"
+    echo "  - 二进制文件"
+    echo "  - 可选:服务日志"
+    echo
+    read -p "确认卸载?[y/N]: " -n 1 -r
+    echo
+    if [[ ! $REPLY =~ ^[Yy]$ ]]; then
+        print_info "卸载已取消"
+        exit 0
+    fi
+}
+
+# 主函数
+main() {
+    print_info "开始卸载资源占用显示系统..."
+    
+    check_root
+    confirm_uninstall
+    
+    stop_service
+    remove_service
+    remove_binary
+    clean_logs
+    
+    print_info "卸载完成!"
+    echo
+    print_info "资源占用显示系统已从您的系统中移除"
+    print_info "如需重新安装,请运行: sudo ./scripts/install.sh"
+}
+
+# 运行主函数
+main "$@"

+ 297 - 0
src/cache.rs

@@ -0,0 +1,297 @@
+use crate::stats::{Result, SystemStats, collect_system_stats};
+use std::sync::Arc;
+use std::sync::atomic::{AtomicPtr, AtomicU64, Ordering};
+use std::time::{Duration, SystemTime, UNIX_EPOCH};
+
+/// 无锁系统统计数据缓存
+pub struct SystemStatsCache {
+    current_stats: AtomicPtr<SystemStats>,
+    last_update: AtomicU64,
+    ttl: Duration,
+}
+
+impl SystemStatsCache {
+    /// 创建新的缓存实例
+    #[inline]
+    pub fn new(ttl: Duration) -> Self {
+        Self {
+            current_stats: AtomicPtr::new(Box::into_raw(Box::new(SystemStats::default()))),
+            last_update: AtomicU64::new(0),
+            ttl,
+        }
+    }
+
+    /// 无锁读取缓存数据
+    pub fn get(&self) -> Option<SystemStats> {
+        // 先加载时间戳,避免 ABA 问题
+        let last_update = self.last_update.load(Ordering::Acquire);
+        if last_update == 0 {
+            return None; // 未初始化
+        }
+
+        // 获取当前时间戳(使用毫秒精度)
+        let now = SystemTime::now()
+            .duration_since(UNIX_EPOCH)
+            .unwrap()
+            .as_millis() as u64;
+
+        // 检查数据是否过期(使用毫秒精度)
+        if now - last_update > self.ttl.as_millis() as u64 {
+            return None; // 数据过期
+        }
+
+        // 加载数据指针
+        let ptr = self.current_stats.load(Ordering::Acquire);
+        if ptr.is_null() {
+            return None;
+        }
+
+        // 安全读取数据
+        let stats = unsafe { &*ptr };
+        Some(stats.clone())
+    }
+
+    /// 原子更新缓存数据
+    pub fn update(&self, new_stats: SystemStats) {
+        // 先获取当前时间戳(使用毫秒精度)
+        let now = SystemTime::now()
+            .duration_since(UNIX_EPOCH)
+            .unwrap()
+            .as_millis() as u64;
+
+        // 创建新数据
+        let boxed_stats = Box::into_raw(Box::new(new_stats));
+
+        // 原子替换数据指针
+        let old_ptr = self.current_stats.swap(boxed_stats, Ordering::Release);
+
+        // 安全释放旧数据
+        if !old_ptr.is_null() {
+            let _ = unsafe { Box::from_raw(old_ptr) };
+        }
+
+        // 最后更新时间戳,确保数据先于时间戳可见
+        self.last_update.store(now, Ordering::Release);
+    }
+
+    /// 按需更新策略:只有在数据过期且有请求时才更新
+    pub async fn get_or_update(&self) -> Result<SystemStats> {
+        // 先尝试获取缓存
+        if let Some(stats) = self.get() {
+            return Ok(stats);
+        }
+
+        // 数据过期或不存在,重新获取
+        let new_stats = collect_system_stats().await?;
+
+        // 更新缓存
+        self.update(new_stats.clone());
+        Ok(new_stats)
+    }
+}
+
+impl Drop for SystemStatsCache {
+    fn drop(&mut self) {
+        let ptr = self.current_stats.load(Ordering::Acquire);
+        if !ptr.is_null() {
+            let _ = unsafe { Box::from_raw(ptr) };
+        }
+    }
+}
+
+/// 缓存类型别名
+pub type CacheRef = Arc<SystemStatsCache>;
+
+/// 创建缓存实例的便捷函数
+#[inline]
+pub fn create_cache(ttl_seconds: u64) -> CacheRef {
+    Arc::new(SystemStatsCache::new(Duration::from_secs(ttl_seconds)))
+}
+
+#[cfg(test)]
+mod tests {
+    use super::*;
+    use std::time::Duration;
+    use tokio::time::sleep;
+
+    fn create_test_stats(hostname: &str, cpu_usage: f32) -> SystemStats {
+        SystemStats {
+            hostname: hostname.to_string(),
+            cpu_usage,
+            memory_total: 1024 * 1024 * 1024,    // 1GB
+            memory_used: 512 * 1024 * 1024,      // 512MB
+            memory_available: 256 * 1024 * 1024, // 256MB
+            memory_cached: 128 * 1024 * 1024,    // 128MB
+            memory_free: 128 * 1024 * 1024,      // 128MB
+            timestamp: std::time::Instant::now(),
+        }
+    }
+
+    #[tokio::test]
+    async fn test_cache_basic_operations() {
+        let cache = SystemStatsCache::new(Duration::from_secs(10));
+
+        // 初始状态应该返回 None
+        assert!(cache.get().is_none());
+
+        // 更新数据
+        let stats = create_test_stats("test", 0.5);
+        cache.update(stats.clone());
+
+        // 应该能获取到数据
+        let cached = cache.get().unwrap();
+        assert_eq!(cached.hostname, "test");
+        assert_eq!(cached.cpu_usage, 0.5);
+    }
+
+    #[tokio::test]
+    async fn test_cache_expiration() {
+        let cache = SystemStatsCache::new(Duration::from_millis(50)); // 减少过期时间
+
+        let stats = create_test_stats("test", 0.5);
+        cache.update(stats);
+
+        // 立即获取应该成功
+        assert!(cache.get().is_some());
+
+        // 等待过期
+        sleep(Duration::from_millis(100)).await;
+
+        // 过期后应该返回 None
+        assert!(cache.get().is_none());
+    }
+
+    #[tokio::test]
+    async fn test_cache_creation() {
+        let cache = SystemStatsCache::new(Duration::from_secs(10));
+
+        // 初始状态应该返回 None
+        assert!(cache.get().is_none());
+    }
+
+    #[tokio::test]
+    async fn test_cache_update_and_get() {
+        let cache = SystemStatsCache::new(Duration::from_secs(10));
+        let stats = create_test_stats("test-host", 0.5);
+
+        // 更新数据
+        cache.update(stats.clone());
+
+        // 应该能获取到数据
+        let cached = cache.get().unwrap();
+        assert_eq!(cached.hostname, "test-host");
+        assert_eq!(cached.cpu_usage, 0.5);
+        assert_eq!(cached.memory_total, 1024 * 1024 * 1024);
+    }
+
+    #[tokio::test]
+    async fn test_cache_multiple_updates() {
+        let cache = SystemStatsCache::new(Duration::from_secs(10));
+
+        // 更新第一次
+        let stats1 = create_test_stats("host1", 0.3);
+        cache.update(stats1.clone());
+
+        let cached1 = cache.get().unwrap();
+        assert_eq!(cached1.hostname, "host1");
+        assert_eq!(cached1.cpu_usage, 0.3);
+
+        // 更新第二次
+        let stats2 = create_test_stats("host2", 0.7);
+        cache.update(stats2.clone());
+
+        let cached2 = cache.get().unwrap();
+        assert_eq!(cached2.hostname, "host2");
+        assert_eq!(cached2.cpu_usage, 0.7);
+    }
+
+    #[tokio::test]
+    async fn test_cache_drop() {
+        let cache = SystemStatsCache::new(Duration::from_secs(10));
+        let stats = create_test_stats("test-host", 0.5);
+        cache.update(stats);
+
+        // 验证数据存在
+        assert!(cache.get().is_some());
+
+        // Drop 缓存(测试 Drop 实现)
+        drop(cache);
+
+        // 如果没有 panic,说明 Drop 实现正确
+    }
+
+    #[tokio::test]
+    async fn test_create_cache_function() {
+        let cache = create_cache(5);
+
+        // 验证缓存创建成功
+        assert!(cache.get().is_none());
+
+        // 测试更新和获取
+        let stats = create_test_stats("test", 0.8);
+        cache.update(stats.clone());
+
+        let cached = cache.get().unwrap();
+        assert_eq!(cached.hostname, "test");
+        assert_eq!(cached.cpu_usage, 0.8);
+    }
+
+    #[tokio::test]
+    async fn test_cache_concurrent_access() {
+        let cache = Arc::new(SystemStatsCache::new(Duration::from_secs(10)));
+        let stats = create_test_stats("concurrent-test", 0.6);
+        cache.update(stats.clone());
+
+        // 创建多个并发读取任务
+        let mut handles = vec![];
+        for i in 0..10 {
+            let cache_clone = cache.clone();
+            let handle = tokio::spawn(async move {
+                let cached = cache_clone.get().unwrap();
+                assert_eq!(cached.hostname, "concurrent-test");
+                assert_eq!(cached.cpu_usage, 0.6);
+                format!("task-{}-{}", i, cached.hostname)
+            });
+            handles.push(handle);
+        }
+
+        // 等待所有任务完成
+        for handle in handles {
+            let result = handle.await.unwrap();
+            assert!(result.starts_with("task-"));
+            assert!(result.ends_with("concurrent-test"));
+        }
+    }
+
+    #[tokio::test]
+    async fn test_cache_zero_ttl() {
+        let cache = SystemStatsCache::new(Duration::from_millis(1)); // 使用 1ms TTL
+        let stats = create_test_stats("zero-ttl", 0.4);
+
+        // 更新数据
+        cache.update(stats);
+
+        // 即使是零 TTL,也应该能立即获取到数据
+        assert!(cache.get().is_some());
+
+        // 等待一段时间后应该过期
+        sleep(Duration::from_millis(10)).await;
+        assert!(cache.get().is_none());
+    }
+
+    #[tokio::test]
+    async fn test_cache_large_ttl() {
+        let cache = SystemStatsCache::new(Duration::from_secs(3600)); // 1 小时
+        let stats = create_test_stats("large-ttl", 0.9);
+
+        // 更新数据
+        cache.update(stats);
+
+        // 应该能获取到数据
+        assert!(cache.get().is_some());
+
+        // 即使等待一段时间,也不应该过期
+        sleep(Duration::from_millis(100)).await;
+        assert!(cache.get().is_some());
+    }
+}

+ 12 - 0
src/lib.rs

@@ -0,0 +1,12 @@
+//! 资源占用显示系统库
+//!
+//! 这个库提供了一个极简的资源占用显示系统,专为嵌入式设备监控场景设计。
+
+pub mod cache;
+pub mod server;
+pub mod stats;
+
+// 重新导出主要的公共类型
+pub use cache::{SystemStatsCache, create_cache};
+pub use server::{Config, StatusServer};
+pub use stats::{SystemStats, collect_system_stats};

+ 93 - 0
src/main.rs

@@ -0,0 +1,93 @@
+mod cache;
+mod server;
+mod stats;
+
+use anyhow::Result;
+use cache::create_cache;
+use clap::Parser;
+use log::info;
+use server::{Config, StatusServer};
+
+/// 资源占用显示系统
+#[derive(Parser, Debug)]
+#[command(author, version, about, long_about = None)]
+struct Args {
+    /// 服务器绑定地址 (默认: 0.0.0.0)
+    #[arg(short, long, default_value = "0.0.0.0")]
+    address: String,
+
+    /// 服务器端口 (默认: 8080)
+    #[arg(short, long, default_value_t = 8080)]
+    port: u16,
+
+    /// 缓存 TTL 秒数 (默认: 10)
+    #[arg(short, long, default_value_t = 10)]
+    ttl: u64,
+
+    /// 日志级别 (trace, debug, info, warn, error)
+    #[arg(short, long, default_value = "info")]
+    log_level: String,
+}
+
+#[tokio::main]
+async fn main() -> Result<()> {
+    let args = Args::parse();
+
+    // 初始化日志系统
+    init_logger(&args.log_level);
+
+    info!("资源占用显示系统启动中...");
+
+    // 从命令行参数创建配置
+    let config = Config {
+        bind_address: args.address.clone(),
+        port: args.port,
+        cache_ttl_seconds: args.ttl,
+    };
+
+    info!(
+        "配置信息 - 地址: {}, 端口: {}, 缓存 TTL: {} 秒",
+        config.bind_address, config.port, config.cache_ttl_seconds
+    );
+
+    // 创建缓存
+    let cache = create_cache(config.cache_ttl_seconds);
+    info!("缓存系统初始化完成");
+
+    // 创建服务器
+    let server = StatusServer::new(cache);
+    info!("服务器实例创建完成");
+
+    // 启动服务器
+    let addr = config.address();
+    info!("服务器将在 {addr} 启动");
+
+    server.run(addr).await?;
+
+    info!("服务器正常关闭");
+
+    Ok(())
+}
+
+/// 初始化日志系统
+fn init_logger(level: &str) {
+    use std::env;
+
+    // 设置默认日志格式
+    unsafe {
+        env::set_var("RUST_LOG", level);
+    }
+
+    // 初始化 env_logger
+    match env_logger::Builder::from_env(env_logger::Env::default().default_filter_or(level))
+        .format_timestamp_secs()
+        .try_init()
+    {
+        Ok(_) => info!("日志系统初始化成功,级别: {level}"),
+        Err(e) => {
+            eprintln!("日志系统初始化失败: {e},使用默认设置");
+            // 设置基本的日志输出
+            env_logger::init();
+        }
+    }
+}

+ 422 - 0
src/server.rs

@@ -0,0 +1,422 @@
+use crate::cache::CacheRef;
+use anyhow::Result;
+use hyper::http::StatusCode;
+use hyper::service::{make_service_fn, service_fn};
+use hyper::{Body, Method, Request, Response, Server};
+use log::{error, info, warn};
+use std::convert::Infallible;
+use std::net::SocketAddr;
+
+/// 状态服务器
+pub struct StatusServer {
+    cache: CacheRef,
+}
+
+impl StatusServer {
+    /// 创建新的状态服务器实例
+    #[inline]
+    pub fn new(cache: CacheRef) -> Self {
+        Self { cache }
+    }
+
+    /// 运行服务器
+    pub async fn run(self, addr: SocketAddr) -> Result<()> {
+        let cache = self.cache;
+
+        let make_svc = make_service_fn(move |_conn| {
+            let cache = cache.clone();
+            async move {
+                Ok::<_, Infallible>(service_fn(move |req| {
+                    let cache = cache.clone();
+                    Self::handle_request(req, cache)
+                }))
+            }
+        });
+
+        // 创建服务器并配置高并发参数
+        let server = Server::bind(&addr)
+            .http1_keepalive(true)
+            .http1_half_close(false)
+            .tcp_keepalive(Some(std::time::Duration::from_secs(10)))
+            .tcp_nodelay(true)
+            .serve(make_svc);
+
+        info!("服务器运行在: http://{addr}");
+        info!("已启用高并发模式,支持 HTTP/1.1 keep-alive");
+
+        server.await.map_err(|e| {
+            error!("服务器错误: {e}");
+            anyhow::anyhow!("服务器运行错误: {e}")
+        })?;
+
+        info!("服务器正常关闭");
+        Ok(())
+    }
+
+    /// 处理 HTTP 请求
+    async fn handle_request(
+        req: Request<Body>,
+        cache: CacheRef,
+    ) -> std::result::Result<Response<Body>, Infallible> {
+        // 添加连接信息头部,便于调试
+        match (req.method(), req.uri().path()) {
+            (&Method::GET, "/") => {
+                match Self::serve_html(cache).await {
+                    Ok(mut response) => {
+                        // 添加缓存控制头,减少客户端重复请求
+                        response.headers_mut().insert(
+                            "Cache-Control",
+                            hyper::header::HeaderValue::from_static(
+                                "no-cache, no-store, must-revalidate",
+                            ),
+                        );
+                        response.headers_mut().insert(
+                            "Pragma",
+                            hyper::header::HeaderValue::from_static("no-cache"),
+                        );
+                        response
+                            .headers_mut()
+                            .insert("Expires", hyper::header::HeaderValue::from_static("0"));
+                        Ok(response)
+                    }
+                    Err(_) => Ok(Self::serve_error(
+                        "数据获取失败".to_string(),
+                        StatusCode::INTERNAL_SERVER_ERROR,
+                    )),
+                }
+            }
+            (&Method::GET, "/health") => Ok(Self::serve_health()),
+            _ => Ok(Self::serve_404()),
+        }
+    }
+
+    /// 提供健康检查端点
+    #[inline]
+    fn serve_health() -> Response<Body> {
+        Response::builder()
+            .status(StatusCode::OK)
+            .header("content-type", "text/plain")
+            .header("Cache-Control", "no-cache")
+            .body(Body::from("OK"))
+            .unwrap()
+    }
+
+    /// 提供 404 页面
+    #[inline]
+    fn serve_404() -> Response<Body> {
+        warn!("请求了不存在的页面");
+        Response::builder()
+            .status(StatusCode::NOT_FOUND)
+            .header("content-type", "text/plain")
+            .body(Body::from("页面未找到"))
+            .unwrap()
+    }
+
+    /// 提供错误页面
+    #[inline]
+    fn serve_error(message: String, status: StatusCode) -> Response<Body> {
+        Response::builder()
+            .status(status)
+            .header("content-type", "text/plain; charset=utf-8")
+            .body(Body::from(message))
+            .unwrap()
+    }
+
+    /// 提供主页面
+    async fn serve_html(cache: CacheRef) -> Result<Response<Body>> {
+        // 获取系统数据
+        let stats = cache.get_or_update().await.map_err(|e| {
+            error!("获取系统数据失败: {e}");
+            e
+        })?;
+
+        // 渲染 HTML 模板
+        let html = Self::render_html_template(&stats);
+
+        Ok(Response::builder()
+            .status(StatusCode::OK)
+            .header("content-type", "text/html; charset=utf-8")
+            .body(Body::from(html))
+            .unwrap())
+    }
+
+    /// 渲染 HTML 模板
+    pub fn render_html_template(stats: &crate::stats::SystemStats) -> String {
+        let total_mb = stats.memory_total / 1024 / 1024;
+        let used_mb = stats.memory_used / 1024 / 1024;
+        let available_mb = stats.memory_available / 1024 / 1024;
+        let cached_mb = stats.memory_cached / 1024 / 1024;
+        let free_mb = stats.memory_free / 1024 / 1024;
+
+        let cpu_percent = (stats.cpu_usage * 100.0) as u32;
+
+        // 格式化时间戳为可读格式
+        let timestamp = format!("{:?}", stats.timestamp);
+
+        // 使用内置模板(编译进二进制文件)
+        let template = include_str!("../templates/index.html");
+
+        // 使用 String::with_capacity 预分配容量,减少重新分配
+        let mut result = String::with_capacity(template.len() + 256);
+
+        // 手动替换变量,避免多次字符串分配
+        result.push_str(template);
+        result = result.replace("{hostname}", &stats.hostname);
+        result = result.replace("{cpu_percent}", &cpu_percent.to_string());
+        result = result.replace("{memory_total_mb}", &total_mb.to_string());
+        result = result.replace("{memory_used_mb}", &used_mb.to_string());
+        result = result.replace("{memory_available_mb}", &available_mb.to_string());
+        result = result.replace("{memory_cached_mb}", &cached_mb.to_string());
+        result = result.replace("{memory_free_mb}", &free_mb.to_string());
+        result = result.replace("{timestamp}", &timestamp);
+
+        result
+    }
+}
+
+#[cfg(test)]
+mod tests {
+    use super::*;
+    use crate::cache::create_cache;
+    use crate::stats::SystemStats;
+    use hyper::{Body, Request, StatusCode};
+    use std::time::Instant;
+
+    fn create_test_stats(hostname: &str, cpu_usage: f32) -> SystemStats {
+        SystemStats {
+            hostname: hostname.to_string(),
+            cpu_usage,
+            memory_total: 1024 * 1024 * 1024,    // 1GB
+            memory_used: 512 * 1024 * 1024,      // 512MB
+            memory_available: 256 * 1024 * 1024, // 256MB
+            memory_cached: 128 * 1024 * 1024,    // 128MB
+            memory_free: 128 * 1024 * 1024,      // 128MB
+            timestamp: Instant::now(),
+        }
+    }
+
+    #[tokio::test]
+    async fn test_config_default() {
+        let config = Config::default();
+        assert_eq!(config.bind_address, "0.0.0.0");
+        assert_eq!(config.port, 8080);
+        assert_eq!(config.cache_ttl_seconds, 10);
+    }
+
+    #[tokio::test]
+    async fn test_config_address() {
+        let config = Config::default();
+        let addr = config.address();
+        assert_eq!(addr.to_string(), "0.0.0.0:8080");
+    }
+
+    #[tokio::test]
+    async fn test_status_server_creation() {
+        let cache = create_cache(10);
+        let _server = StatusServer::new(cache);
+        // 服务器创建成功,没有 panic
+    }
+
+    #[tokio::test]
+    async fn test_serve_health() {
+        let response = StatusServer::serve_health();
+        assert_eq!(response.status(), StatusCode::OK);
+
+        let headers = response.headers();
+        assert_eq!(headers.get("content-type").unwrap(), "text/plain");
+
+        let body = hyper::body::to_bytes(response.into_body()).await.unwrap();
+        assert_eq!(std::str::from_utf8(&body).unwrap(), "OK");
+    }
+
+    #[tokio::test]
+    async fn test_serve_404() {
+        let response = StatusServer::serve_404();
+        assert_eq!(response.status(), StatusCode::NOT_FOUND);
+
+        let headers = response.headers();
+        assert_eq!(headers.get("content-type").unwrap(), "text/plain");
+
+        let body = hyper::body::to_bytes(response.into_body()).await.unwrap();
+        assert_eq!(std::str::from_utf8(&body).unwrap(), "页面未找到");
+    }
+
+    #[tokio::test]
+    async fn test_serve_error() {
+        let message = "测试错误".to_string();
+        let response =
+            StatusServer::serve_error(message.clone(), StatusCode::INTERNAL_SERVER_ERROR);
+        assert_eq!(response.status(), StatusCode::INTERNAL_SERVER_ERROR);
+
+        let headers = response.headers();
+        assert_eq!(
+            headers.get("content-type").unwrap(),
+            "text/plain; charset=utf-8"
+        );
+
+        let body = hyper::body::to_bytes(response.into_body()).await.unwrap();
+        assert_eq!(std::str::from_utf8(&body).unwrap(), message);
+    }
+
+    #[tokio::test]
+    async fn test_render_html_template() {
+        let stats = create_test_stats("测试主机", 0.75);
+        let html = StatusServer::render_html_template(&stats);
+
+        // 检查 HTML 是否包含预期的内容
+        assert!(html.contains("测试主机"));
+        assert!(html.contains("75"));
+        assert!(html.contains("1024")); // 内存总量 MB
+        assert!(html.contains("512")); // 已用内存 MB
+        assert!(html.contains("256")); // 可用内存 MB
+        assert!(html.contains("128")); // 缓存内存 MB
+    }
+
+    #[tokio::test]
+    async fn test_render_html_template_special_chars() {
+        let stats = create_test_stats("主机<>&\"'", 0.5);
+        let html = StatusServer::render_html_template(&stats);
+
+        // 检查特殊字符是否被正确处理
+        assert!(html.contains("主机<>&\"'"));
+        assert!(html.contains("50"));
+    }
+
+    #[tokio::test]
+    async fn test_render_html_template_memory_values() {
+        let stats = SystemStats {
+            hostname: "test".to_string(),
+            cpu_usage: 0.5,
+            memory_total: 2048 * 1024 * 1024,    // 2GB
+            memory_used: 1024 * 1024 * 1024,     // 1GB
+            memory_available: 512 * 1024 * 1024, // 512MB
+            memory_cached: 256 * 1024 * 1024,    // 256MB
+            memory_free: 256 * 1024 * 1024,      // 256MB
+            timestamp: Instant::now(),
+        };
+
+        let html = StatusServer::render_html_template(&stats);
+
+        // 检查内存值是否正确转换为 MB
+        assert!(html.contains("2048")); // 总内存 2GB = 2048MB
+        assert!(html.contains("1024")); // 已用内存 1GB = 1024MB
+        assert!(html.contains("512")); // 可用内存 512MB
+        assert!(html.contains("256")); // 缓存内存 256MB
+        assert!(html.contains("256")); // 空闲内存 256MB
+    }
+
+    #[tokio::test]
+    async fn test_handle_request_root() {
+        let cache = create_cache(10);
+        let request = Request::builder()
+            .method("GET")
+            .uri("/")
+            .body(Body::empty())
+            .unwrap();
+
+        let response = StatusServer::handle_request(request, cache).await.unwrap();
+        assert_eq!(response.status(), StatusCode::OK);
+    }
+
+    #[tokio::test]
+    async fn test_handle_request_health() {
+        let cache = create_cache(10);
+        let request = Request::builder()
+            .method("GET")
+            .uri("/health")
+            .body(Body::empty())
+            .unwrap();
+
+        let response = StatusServer::handle_request(request, cache).await.unwrap();
+        assert_eq!(response.status(), StatusCode::OK);
+
+        let body = hyper::body::to_bytes(response.into_body()).await.unwrap();
+        assert_eq!(std::str::from_utf8(&body).unwrap(), "OK");
+    }
+
+    #[tokio::test]
+    async fn test_handle_request_404() {
+        let cache = create_cache(10);
+        let request = Request::builder()
+            .method("GET")
+            .uri("/notfound")
+            .body(Body::empty())
+            .unwrap();
+
+        let response = StatusServer::handle_request(request, cache).await.unwrap();
+        assert_eq!(response.status(), StatusCode::NOT_FOUND);
+    }
+
+    #[tokio::test]
+    async fn test_handle_request_post_method() {
+        let cache = create_cache(10);
+        let request = Request::builder()
+            .method("POST")
+            .uri("/")
+            .body(Body::empty())
+            .unwrap();
+
+        let response = StatusServer::handle_request(request, cache).await.unwrap();
+        assert_eq!(response.status(), StatusCode::NOT_FOUND);
+    }
+
+    #[tokio::test]
+    async fn test_serve_html_with_cache() {
+        let cache = create_cache(10);
+
+        // 更新缓存数据
+        let stats = create_test_stats("缓存测试", 0.8);
+        cache.update(stats);
+
+        // 模拟请求处理
+        let request = Request::builder()
+            .method("GET")
+            .uri("/")
+            .body(Body::empty())
+            .unwrap();
+
+        let response = StatusServer::handle_request(request, cache.clone())
+            .await
+            .unwrap();
+        assert_eq!(response.status(), StatusCode::OK);
+
+        let body = hyper::body::to_bytes(response.into_body()).await.unwrap();
+        let html = std::str::from_utf8(&body).unwrap();
+
+        // 检查响应是否包含缓存的数据
+        assert!(html.contains("缓存测试"));
+        assert!(html.contains("80"));
+    }
+}
+
+/// 配置结构
+#[derive(Debug, Clone)]
+pub struct Config {
+    /// 服务端绑定地址
+    pub bind_address: String,
+    /// 服务端端口
+    pub port: u16,
+    /// 缓存 TTL(秒)
+    pub cache_ttl_seconds: u64,
+}
+
+impl Default for Config {
+    #[inline]
+    fn default() -> Self {
+        Self {
+            bind_address: "0.0.0.0".to_string(),
+            port: 8080,
+            cache_ttl_seconds: 10, // 严格 10 秒过期
+        }
+    }
+}
+
+impl Config {
+    /// 构建服务器地址
+    #[inline]
+    pub fn address(&self) -> SocketAddr {
+        format!("{}:{}", self.bind_address, self.port)
+            .parse()
+            .expect("无效的地址格式")
+    }
+}

+ 382 - 0
src/stats.rs

@@ -0,0 +1,382 @@
+use std::time::Instant;
+
+/// CPU 时间统计
+#[derive(Debug, Default, Clone)]
+#[allow(dead_code)] // 为未来扩展预留字段
+pub struct CpuTimes {
+    pub user: u64,
+    pub nice: u64,
+    pub system: u64,
+    pub idle: u64,
+    pub total: u64,
+}
+
+use std::sync::atomic::{AtomicU64, Ordering};
+
+/// 全局 CPU 时间缓存,用于增量计算
+static CPU_PREV_TOTAL: AtomicU64 = AtomicU64::new(0);
+static CPU_PREV_IDLE: AtomicU64 = AtomicU64::new(0);
+static CPU_TIMES_INIT: std::sync::Once = std::sync::Once::new();
+
+/// 系统资源统计数据结构
+#[derive(Debug, Clone)]
+pub struct SystemStats {
+    pub hostname: String,
+    pub cpu_usage: f32,        // CPU 使用率 (0.0-1.0)
+    pub memory_total: u64,     // 总内存字节数
+    pub memory_used: u64,      // 已用内存字节数
+    pub memory_available: u64, // 可用内存字节数
+    pub memory_cached: u64,    // 缓存内存字节数
+    pub memory_free: u64,      // 空闲内存字节数
+    pub timestamp: Instant,    // 数据获取时间戳
+}
+
+impl Default for SystemStats {
+    #[inline]
+    fn default() -> Self {
+        Self {
+            hostname: "未知主机".to_string(),
+            cpu_usage: 0.0,
+            memory_total: 0,
+            memory_used: 0,
+            memory_available: 0,
+            memory_cached: 0,
+            memory_free: 0,
+            timestamp: Instant::now(),
+        }
+    }
+}
+
+/// 系统资源获取错误类型
+#[derive(Debug)]
+pub enum StatsError {
+    IoError(std::io::Error),
+    ParseError(String),
+    #[allow(dead_code)] // 为未来跨平台支持预留
+    UnsupportedPlatform,
+}
+
+impl From<std::io::Error> for StatsError {
+    #[inline]
+    fn from(error: std::io::Error) -> Self {
+        StatsError::IoError(error)
+    }
+}
+
+impl std::fmt::Display for StatsError {
+    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+        match self {
+            StatsError::IoError(e) => write!(f, "IO 错误: {e}"),
+            StatsError::ParseError(s) => write!(f, "解析错误: {s}"),
+            StatsError::UnsupportedPlatform => write!(f, "不支持的平台"),
+        }
+    }
+}
+
+impl std::error::Error for StatsError {}
+
+pub type Result<T> = std::result::Result<T, StatsError>;
+
+/// 收集系统统计数据
+pub async fn collect_system_stats() -> Result<SystemStats> {
+    #[cfg(target_os = "linux")]
+    {
+        collect_linux_stats().await
+    }
+
+    #[cfg(not(target_os = "linux"))]
+    {
+        Err(StatsError::UnsupportedPlatform)
+    }
+}
+
+/// Linux 系统统计数据收集
+#[cfg(target_os = "linux")]
+async fn collect_linux_stats() -> Result<SystemStats> {
+    let hostname = get_hostname()?;
+    let cpu_usage = get_cpu_usage().await?;
+    let memory_info = get_memory_info().await?;
+
+    Ok(SystemStats {
+        hostname,
+        cpu_usage,
+        memory_total: memory_info.total,
+        memory_used: memory_info.used,
+        memory_available: memory_info.available,
+        memory_cached: memory_info.cached,
+        memory_free: memory_info.free,
+        timestamp: Instant::now(),
+    })
+}
+
+/// 获取主机名
+#[cfg(target_os = "linux")]
+#[inline]
+fn get_hostname() -> Result<String> {
+    std::fs::read_to_string("/proc/sys/kernel/hostname")
+        .map(|s| s.trim().to_string())
+        .map_err(From::from)
+}
+
+/// 内存信息结构
+#[derive(Debug, Default)]
+struct MemoryInfo {
+    total: u64,
+    used: u64,
+    available: u64,
+    cached: u64,
+    free: u64,
+}
+
+/// 获取内存信息
+#[cfg(target_os = "linux")]
+async fn get_memory_info() -> Result<MemoryInfo> {
+    // 预估 /proc/meminfo 的大小,预分配容量
+    let mut content = String::with_capacity(2048);
+    let file_content = tokio::fs::read_to_string("/proc/meminfo").await?;
+    content.push_str(&file_content);
+
+    let mut info = MemoryInfo::default();
+
+    for line in content.lines() {
+        let mut parts = line.split_whitespace();
+        if let (Some(key), Some(value)) = (parts.next(), parts.next()) {
+            let value = value.parse::<u64>().unwrap_or(0) * 1024; // 转换为字节
+
+            match key {
+                "MemTotal:" => info.total = value,
+                "MemAvailable:" => info.available = value,
+                "Cached:" => info.cached = value,
+                "MemFree:" => info.free = value,
+                _ => {}
+            }
+        }
+    }
+
+    // 计算已用内存 = 总内存 - 可用内存
+    info.used = info.total.saturating_sub(info.available);
+
+    Ok(info)
+}
+
+/// 解析 CPU 时间统计
+#[cfg(target_os = "linux")]
+#[inline]
+fn parse_cpu_times(content: &str) -> Result<CpuTimes> {
+    // 解析第一行 CPU 总时间
+    let first_line = content
+        .lines()
+        .next()
+        .ok_or_else(|| StatsError::ParseError("无法解析 /proc/stat".to_string()))?;
+
+    let mut parts = first_line.split_whitespace().skip(1); // 跳过 "cpu"
+
+    let user: u64 = parts.next().unwrap_or("0").parse().unwrap_or(0);
+    let nice: u64 = parts.next().unwrap_or("0").parse().unwrap_or(0);
+    let system: u64 = parts.next().unwrap_or("0").parse().unwrap_or(0);
+    let idle: u64 = parts.next().unwrap_or("0").parse().unwrap_or(0);
+
+    // 忽略其他字段 (iowait, irq, softirq, steal, guest, guest_nice)
+    let total = user + nice + system + idle;
+
+    Ok(CpuTimes {
+        user,
+        nice,
+        system,
+        idle,
+        total,
+    })
+}
+
+/// CPU 使用率计算(使用增量算法)
+#[cfg(target_os = "linux")]
+async fn get_cpu_usage() -> Result<f32> {
+    // 预估 /proc/stat 的大小,预分配容量
+    let mut content = String::with_capacity(1024);
+    let file_content = tokio::fs::read_to_string("/proc/stat").await?;
+    content.push_str(&file_content);
+
+    let current_times = parse_cpu_times(&content)?;
+
+    // 获取之前的时间统计(线程安全)
+    let (prev_total, prev_idle) = {
+        CPU_TIMES_INIT.call_once(|| {
+            CPU_PREV_TOTAL.store(current_times.total, Ordering::Relaxed);
+            CPU_PREV_IDLE.store(current_times.idle, Ordering::Relaxed);
+        });
+        (
+            CPU_PREV_TOTAL.load(Ordering::Relaxed),
+            CPU_PREV_IDLE.load(Ordering::Relaxed),
+        )
+    };
+
+    // 如果是第一次调用,返回 0 使用率
+    if prev_total == 0 && prev_idle == 0 && current_times.total != 0 {
+        CPU_PREV_TOTAL.store(current_times.total, Ordering::Relaxed);
+        CPU_PREV_IDLE.store(current_times.idle, Ordering::Relaxed);
+        return Ok(0.0);
+    }
+
+    // 计算增量
+    let total_diff = current_times.total.saturating_sub(prev_total);
+    let idle_diff = current_times.idle.saturating_sub(prev_idle);
+
+    // 更新全局缓存
+    CPU_PREV_TOTAL.store(current_times.total, Ordering::Relaxed);
+    CPU_PREV_IDLE.store(current_times.idle, Ordering::Relaxed);
+
+    // 如果总时间差为 0,返回 0 使用率
+    if total_diff == 0 {
+        return Ok(0.0);
+    }
+
+    // 计算使用率:1 - (空闲时间增量 / 总时间增量)
+    let usage = 1.0 - (idle_diff as f32 / total_diff as f32);
+
+    // 确保使用率在合理范围内
+    Ok(usage.clamp(0.0, 1.0))
+}
+
+#[cfg(test)]
+mod tests {
+    use super::*;
+
+    #[test]
+    fn test_system_stats_default() {
+        let stats = SystemStats::default();
+        assert_eq!(stats.hostname, "未知主机");
+        assert_eq!(stats.cpu_usage, 0.0);
+        assert_eq!(stats.memory_total, 0);
+        assert_eq!(stats.memory_used, 0);
+        assert_eq!(stats.memory_available, 0);
+        assert_eq!(stats.memory_cached, 0);
+        assert_eq!(stats.memory_free, 0);
+    }
+
+    #[test]
+    fn test_cpu_times_default() {
+        let times = CpuTimes::default();
+        assert_eq!(times.user, 0);
+        assert_eq!(times.nice, 0);
+        assert_eq!(times.system, 0);
+        assert_eq!(times.idle, 0);
+        assert_eq!(times.total, 0);
+    }
+
+    #[test]
+    fn test_parse_cpu_times_valid() {
+        let content = "cpu  1234 567 890 1234 0 0 0 0 0 0";
+        let times = parse_cpu_times(content).unwrap();
+        assert_eq!(times.user, 1234);
+        assert_eq!(times.nice, 567);
+        assert_eq!(times.system, 890);
+        assert_eq!(times.idle, 1234);
+        assert_eq!(times.total, 1234 + 567 + 890 + 1234);
+    }
+
+    #[test]
+    fn test_parse_cpu_times_invalid() {
+        let content = "invalid content";
+        let result = parse_cpu_times(content).unwrap();
+        assert_eq!(result.total, 0);
+        assert_eq!(result.idle, 0);
+    }
+
+    #[test]
+    fn test_parse_cpu_times_empty() {
+        let content = "";
+        assert!(parse_cpu_times(content).is_err());
+    }
+
+    #[test]
+    fn test_stats_error_display() {
+        let io_error = StatsError::IoError(std::io::Error::new(
+            std::io::ErrorKind::NotFound,
+            "test error",
+        ));
+        assert_eq!(format!("{}", io_error), "IO 错误: test error");
+
+        let parse_error = StatsError::ParseError("test parse error".to_string());
+        assert_eq!(format!("{}", parse_error), "解析错误: test parse error");
+
+        let unsupported_error = StatsError::UnsupportedPlatform;
+        assert_eq!(format!("{}", unsupported_error), "不支持的平台");
+    }
+
+    #[test]
+    fn test_stats_error_from_io() {
+        let io_error =
+            std::io::Error::new(std::io::ErrorKind::PermissionDenied, "permission denied");
+        let stats_error = StatsError::from(io_error);
+        match stats_error {
+            StatsError::IoError(_) => {} // 预期的类型
+            _ => panic!("应该是 IoError 类型"),
+        }
+    }
+
+    #[tokio::test]
+    #[cfg(target_os = "linux")]
+    async fn test_get_hostname() {
+        // 测试获取主机名
+        match get_hostname() {
+            Ok(hostname) => {
+                assert!(!hostname.is_empty());
+                println!("主机名: {}", hostname);
+            }
+            Err(e) => {
+                // 在某些环境中可能失败,这是可以接受的
+                println!("获取主机名失败: {}", e);
+            }
+        }
+    }
+
+    #[tokio::test]
+    #[cfg(target_os = "linux")]
+    async fn test_get_memory_info() {
+        // 测试获取内存信息
+        match get_memory_info().await {
+            Ok(info) => {
+                assert!(info.total > 0);
+                assert!(info.used <= info.total);
+                assert!(info.available <= info.total);
+                assert!(info.cached <= info.total);
+                assert!(info.free <= info.total);
+                println!("内存信息: {:?}", info);
+            }
+            Err(e) => {
+                // 在某些环境中可能失败
+                println!("获取内存信息失败: {}", e);
+            }
+        }
+    }
+
+    #[tokio::test]
+    #[cfg(target_os = "linux")]
+    async fn test_collect_linux_stats() {
+        // 测试完整的 Linux 统计数据收集
+        match collect_linux_stats().await {
+            Ok(stats) => {
+                assert!(!stats.hostname.is_empty());
+                assert!(stats.cpu_usage >= 0.0 && stats.cpu_usage <= 1.0);
+                assert!(stats.memory_total > 0);
+                println!("系统统计: {:?}", stats);
+            }
+            Err(e) => {
+                // 在某些环境中可能失败
+                println!("收集系统统计失败: {}", e);
+            }
+        }
+    }
+
+    #[tokio::test]
+    #[cfg(not(target_os = "linux"))]
+    async fn test_collect_system_stats_unsupported() {
+        // 测试非 Linux 平台
+        let result = collect_system_stats().await;
+        assert!(result.is_err());
+        match result.unwrap_err() {
+            StatsError::UnsupportedPlatform => {} // 预期的错误
+            _ => panic!("应该是 UnsupportedPlatform 错误"),
+        }
+    }
+}

+ 49 - 0
templates/index.html

@@ -0,0 +1,49 @@
+<!DOCTYPE html>
+<head lang="zh-Hans-CN">
+  <meta charset="UTF-8" />
+  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
+  <meta name="description" content="{hostname} 的资源占用" />
+  <meta name="keywords" content="资源占用,效率工具" />
+  <meta http-equiv="refresh" content="10" />
+  <link
+    rel="icon"
+    type="image/svg+xml"
+    href="data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 100 100'%3E%3Ctext y='.9em' font-size='90'%3E📊%3C/text%3E%3C/svg%3E"
+  />
+  <title>{hostname} 资源占用</title>
+</head>
+<body>
+  <fieldset>
+    <legend>{hostname} 的资源占用</legend>
+    <fieldset>
+      <legend>处理器</legend>
+      <progress value="{cpu_percent}" max="100">
+        <p>{cpu_percent}%</p>
+      </progress>
+    </fieldset>
+    <fieldset>
+      <legend>内存</legend>
+      <p>已用:</p>
+      <progress value="{memory_used_mb}" max="{memory_total_mb}">
+        <p>{memory_used_mb}/{memory_total_mb}MB</p>
+      </progress>
+      <p>可用:</p>
+      <progress value="{memory_available_mb}" max="{memory_total_mb}">
+        <p>{memory_available_mb}/{memory_total_mb}MB</p>
+      </progress>
+      <p>缓存:</p>
+      <progress value="{memory_cached_mb}" max="{memory_total_mb}">
+        <p>{memory_cached_mb}/{memory_total_mb}MB</p>
+      </progress>
+      <p>空闲:</p>
+      <progress value="{memory_free_mb}" max="{memory_total_mb}">
+        <p>{memory_free_mb}/{memory_total_mb}MB</p>
+      </progress>
+    </fieldset>
+    <fieldset>
+      <legend>时间戳</legend>
+      <p>{timestamp}</p>
+    </fieldset>
+  </fieldset>
+</body>
+</html>