A modern and elegant dashboard for network traffic visualization and analysis.
feat: Implement direct agent binary download and update with checksum verification and improved version reporting.
luolei0819e5c56a5e
diff --git a/.github/workflows/agent-release.yml b/.github/workflows/agent-release.ymlindex cb8750b..fea6080 100644--- a/.github/workflows/agent-release.yml+++ b/.github/workflows/agent-release.yml@@ -80,7 +80,10 @@ jobs:rm -rf "$workdir"mkdir -p "$workdir"- go build -trimpath -ldflags "-s -w" -o "$workdir/neko-agent" .+ VERSION_PLAIN="${VERSION#agent-v}"+ go build -trimpath \+ -ldflags "-s -w -X github.com/foru17/neko-master/apps/agent/internal/config.AgentVersion=${VERSION_PLAIN}" \+ -o "$workdir/neko-agent" .chmod +x "$workdir/neko-agent"versioned_archive="neko-agent_${VERSION}_${{ matrix.os }}_${{ matrix.arch }}.tar.gz"diff --git a/CHANGELOG.en.md b/CHANGELOG.en.mdindex 3b3360e..d9ee342 100644--- a/CHANGELOG.en.md+++ b/CHANGELOG.en.md@@ -7,6 +7,62 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0## [Unreleased]+## [1.3.2] - 2026-02-22++### Added++- **ClickHouse high-performance storage backend (major update)** 🗄️+ - Added ClickHouse as an optional analytics storage engine, forming a dual-write architecture alongside SQLite+ - Health-aware write routing: SQLite stats writes are automatically skipped when ClickHouse is healthy, significantly reducing local disk I/O+ - ClickHouse-exclusive mode available for large-scale multi-agent deployments+ - New `ClickHouseWriter` module with batched writes, health monitoring, consecutive-failure fallback, and graceful recovery+- **`NEKO_AGENT_REF` branch testing support**+ - Added `NEKO_AGENT_REF` environment variable to the install script to download `nekoagent` from any GitHub branch+ - E.g. `NEKO_AGENT_REF=refactor/clickhouse` lets you test pre-release branches without modifying the script++### Performance++- **Agent report traffic gzip compression (~10-15x ratio)** 🚀+ - All `neko-agent` HTTP report requests are now gzip-compressed; overnight upload traffic reduced from ~4 GB to ~300 MB+ - Collector transparently decompresses via Fastify `preParsing` hook with no new dependencies+ - Fully backward-compatible: older uncompressed `neko-agent` versions continue to work alongside compressed ones++### Fixed++- **[P0] ClickHouse health check used wrong method, causing silent data loss**+ - Fixed `shouldSkipSqliteStatsWrites` in `app.ts` incorrectly calling `clickHouseWriter.isEnabled()` instead of `clickHouseWriter.isHealthy()`+ - When ClickHouse has consecutive write failures it now correctly falls back to SQLite writes, preventing silent data loss+- **[P1] Agent retry lost requestId, causing duplicate traffic counting**+ - Agent report payload now includes a `requestId` (32-char hex generated via `crypto/rand`)+ - Collector implements server-side idempotency dedup (5-minute TTL Map); duplicate `requestId` arrivals are silently discarded+ - Fixed the old `requeueFront` pattern where re-queuing a failed batch assigned it a new ID, allowing the same data to be counted twice; failed batches now carry the same `requestId` for the entire retry window++### Changed++- **`nekoagent update` / `upgrade` completely rewritten**+ - The old `update` command was re-running the install script and invoking `nekoagent add` — it never actually updated the binary+ - Rewritten to download the target version directly, SHA256-verify it, and replace the installed binary in-place; skips download when already at target version+ - Added `upgrade` as an alias for `update`+- **`nekoagent add` auto-starts by default**+ - `auto_start` default changed from `false` to `true`; instances now start automatically after `add` without requiring a manual `start`+ - Added `--no-start` flag to suppress auto-start when needed+ - Install script `NEKO_AUTO_START=false` now correctly passes `--no-start` through to the `add` command+- **Unified agent versioning**+ - `neko-agent` binary version is now injected at build time via ldflags (`-X ...config.AgentVersion=<tag>`), replacing the previous hardcoded constant+ - CI `agent-release.yml` automatically extracts and injects the version from the git tag; local dev builds report `dev`+ - `nekoagent version` now displays both the manager script version and the `neko-agent` binary version together for consistent version visibility+- **Install script incremental version detection**+ - When an existing installation is detected, the script queries the GitHub Releases API to determine the latest remote version+ - If local version matches the target: skip download and call `nekoagent add` directly; otherwise update the binary first, then add the instance++### Documentation++- **`docs/` directory reorganization**+ - Added `docs/dev/` (ClickHouse analysis and refactor docs) and `docs/research/` (model research reports) subdirectories+ - Added `docs/README.md` (Chinese doc index) and `docs/README.en.md` (English doc index) with categorized clickable links+ - Fixed broken Agent doc links in `README.en.md` that pointed to Chinese `.md` files instead of `.en.md`+ - Architecture guide updated with a dedicated Agent mode section covering deployment topology and data flow+## [1.3.1] - 2026-02-19### Addeddiff --git a/CHANGELOG.md b/CHANGELOG.mdindex 3915a5c..c365d0a 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -7,6 +7,62 @@## [未发布]+## [1.3.2] - 2026-02-22++### 新增++- **ClickHouse 高性能存储后端(重大更新)** 🗄️+ - 新增 ClickHouse 作为可选分析存储引擎,与 SQLite 形成双写架构+ - 健康状态感知路由:ClickHouse 健康时自动跳过 SQLite 统计写入,显著降低本地磁盘 IO+ - 支持纯 ClickHouse 模式,适用于大规模多 Agent 部署场景+ - 新增 `ClickHouseWriter` 模块,支持批量写入、健康检测、连续失败降级与优雅恢复+- **`NEKO_AGENT_REF` 分支测试支持**+ - 安装脚本新增 `NEKO_AGENT_REF` 环境变量,支持指定任意 GitHub 分支下载 `nekoagent` 管理脚本+ - 如 `NEKO_AGENT_REF=refactor/clickhouse` 可测试未合并分支,无需手动修改脚本++### 性能优化++- **Agent 上报流量 Gzip 压缩(~10-15x 压缩比)** 🚀+ - `neko-agent` HTTP 上报请求全面启用 gzip 压缩,实测夜间流量由 ~4 GB 降至 ~300 MB+ - Collector 通过 Fastify `preParsing` Hook 透明解压,零额外依赖+ - 兼容旧版无压缩 `neko-agent` 客户端,新旧版本可并存运行++### 修复++- **[P0] ClickHouse 健康判断方法错误导致静默数据丢失**+ - 修复 `app.ts` 中 `shouldSkipSqliteStatsWrites` 误用 `clickHouseWriter.isEnabled()` 的问题+ - 更正为 `clickHouseWriter.isHealthy()`:ClickHouse 连续写入失败时正确回退到 SQLite,防止数据静默丢失+- **[P1] Agent 重试批次丢失 requestId 导致流量重复计算**+ - Agent 上报 payload 新增 `requestId`(`crypto/rand` 生成 32 位随机 hex)+ - Collector 实现服务端幂等去重(5 分钟 TTL Map),同一 `requestId` 多次到达只处理一次+ - 修复旧 `requeueFront` 逻辑:失败批次重入队列时会生成新 ID,导致重试可被重复计算;现在失败批次在整个重试周期内持有同一 `requestId`++### 变更++- **`nekoagent update` / `upgrade` 彻底重写**+ - 旧版 `update` 实为重新执行安装脚本并调用 `nekoagent add`,从不更新二进制+ - 重写为直接下载目标版本 binary、SHA256 校验后原地替换;版本相同时跳过下载+ - 新增 `upgrade` 作为 `update` 的别名+- **`nekoagent add` 默认自动启动**+ - `auto_start` 默认值由 `false` 改为 `true`,`add` 后实例自动启动,无需再手动 `start`+ - 新增 `--no-start` flag 可在 `add` 时抑制自动启动+ - 安装脚本 `NEKO_AUTO_START=false` 现可正确透传 `--no-start` 到 `add` 命令+- **Agent 版本系统统一**+ - `neko-agent` 二进制版本号改由编译时 ldflags 注入(`-X ...config.AgentVersion=<tag>`),废弃原硬编码常量+ - CI `agent-release.yml` 自动从 git tag 提取版本注入;本地开发版本显示 `dev`+ - `nekoagent version` 同时展示管理脚本版本和 `neko-agent` 二进制版本,版本信息一致可查+- **安装脚本版本检测与增量更新**+ - 检测到已安装时,自动查询 GitHub Releases API 获取远端最新版本号+ - 本地版本 == 目标版本时直接调用 `nekoagent add` 跳过下载;否则先更新二进制再添加实例++### 文档++- **`docs/` 目录重组**+ - 新增 `docs/dev/`(ClickHouse 分析与重构文档)和 `docs/research/`(模型研究报告)子目录+ - 新增 `docs/README.md`(中文文档索引)和 `docs/README.en.md`(英文文档索引),含分类可点击链接+ - 修复主 README 中 Agent 文档链接路径错误(指向中文 `.md` 而非英文 `.en.md`)+ - 架构文档新增独立 Agent 模式章节,描述部署拓扑与完整数据流+## [1.3.1] - 2026-02-19### 新增diff --git a/apps/agent/install.sh b/apps/agent/install.shindex 6adf634..e9e62ac 100755--- a/apps/agent/install.sh+++ b/apps/agent/install.sh@@ -98,6 +98,20 @@ normalize_arch() {esac}+# Query GitHub releases API for the latest agent tag (e.g. "agent-v0.2.0").+# Returns empty string on failure.+get_latest_remote_tag() {+ repo="${1:-foru17/neko-master}"+ api_url="https://api.github.com/repos/${repo}/releases/latest"+ tag=""+ if command -v curl >/dev/null 2>&1; then+ tag="$(curl -fsSL "$api_url" 2>/dev/null | awk -F'"' '/"tag_name"/{print $4; exit}')"+ elif command -v wget >/dev/null 2>&1; then+ tag="$(wget -qO- "$api_url" 2>/dev/null | awk -F'"' '/"tag_name"/{print $4; exit}')"+ fi+ printf '%s\n' "$tag"+}+compute_sha256() {file="$1"if command -v sha256sum >/dev/null 2>&1; then@@ -136,10 +150,10 @@ use_local_agent() {set -- "$@" --gateway-token "$NEKO_GATEWAY_TOKEN"fi- if [ "${NEKO_AUTO_START:-true}" = "true" ]; then- set -- "$@" --auto-start+ if [ "${NEKO_AUTO_START:-true}" != "true" ]; then+ set -- "$@" --no-startfi-+# Execute"$@"}@@ -181,6 +195,10 @@ main() {NEKO_PACKAGE_URL="${NEKO_PACKAGE_URL:-}"NEKO_CHECKSUMS_URL="${NEKO_CHECKSUMS_URL:-}"NEKO_CLI_URL="${NEKO_CLI_URL:-}"+ # NEKO_AGENT_REF: override the git branch/ref used to download the nekoagent manager script.+ # Useful for testing unreleased branches (e.g. NEKO_AGENT_REF=refactor/clickhouse).+ # When unset: uses "main" for latest, or the version tag for pinned versions.+ NEKO_AGENT_REF="${NEKO_AGENT_REF:-}"NEKO_INSTALL_DIR="${NEKO_INSTALL_DIR:-$HOME/.local/bin}"NEKO_BIN_LINK_MODE="${NEKO_BIN_LINK_MODE:-auto}"NEKO_LINK_DIR="${NEKO_LINK_DIR:-/usr/local/bin}"@@ -194,10 +212,39 @@ main() {# Check if nekoagent is already installedexisting_agent="$(detect_existing_install || true)"- # If already installed, just add the new instance+ # If already installed, check whether the binary is up-to-date before decidingif [ -n "$existing_agent" ] && [ "${NEKO_FORCE_INSTALL:-false}" != "true" ]; then- use_local_agent "$existing_agent"- exit 0+ # Locate the neko-agent binary (same dir as nekoagent, or /usr/local/bin fallback)+ existing_bin="$(dirname "$existing_agent")/neko-agent"+ [ -x "$existing_bin" ] || existing_bin="/usr/local/bin/neko-agent"++ local_version=""+ if [ -x "$existing_bin" ]; then+ local_version="$("$existing_bin" --version 2>/dev/null | head -1 || true)"+ fi++ # Determine target plain version (strip "agent-v" prefix)+ if [ "$NEKO_AGENT_VERSION" = "latest" ]; then+ remote_tag="$(get_latest_remote_tag "$NEKO_AGENT_REPO")"+ target_version="${remote_tag#agent-v}"+ else+ target_version="${NEKO_AGENT_VERSION#agent-v}"+ target_version="${target_version#v}"+ fi++ # If versions match, skip download and just add the instance+ if [ -n "$local_version" ] && [ -n "$target_version" ] && [ "$local_version" = "$target_version" ]; then+ echo "[neko-agent] binary already at $local_version, skipping download"+ use_local_agent "$existing_agent"+ exit 0+ fi++ if [ -n "$local_version" ]; then+ echo "[neko-agent] binary update: $local_version -> ${target_version:-latest}"+ else+ echo "[neko-agent] binary not found or version unknown, downloading..."+ fi+ # Fall through to full download/install, then re-use existing nekoagent to add instancefi# Full installation needed@@ -228,7 +275,9 @@ main() {if [ -n "$NEKO_CLI_URL" ]; thencli_url="$NEKO_CLI_URL"else- if [ "$NEKO_AGENT_VERSION" = "latest" ]; then+ if [ -n "$NEKO_AGENT_REF" ]; then+ cli_ref="$NEKO_AGENT_REF"+ elif [ "$NEKO_AGENT_VERSION" = "latest" ]; thencli_ref="main"elsecli_ref="$NEKO_AGENT_VERSION"@@ -329,8 +378,8 @@ main() {if [ -n "$NEKO_GATEWAY_TOKEN" ]; thenset -- "$@" --gateway-token "$NEKO_GATEWAY_TOKEN"fi- if [ "$NEKO_AUTO_START" = "true" ]; then- set -- "$@" --auto-start+ if [ "$NEKO_AUTO_START" != "true" ]; then+ set -- "$@" --no-startfi"$cli_target" "$@"diff --git a/apps/agent/internal/agent/runner.go b/apps/agent/internal/agent/runner.goindex a757f42..bc9f76a 100644--- a/apps/agent/internal/agent/runner.go+++ b/apps/agent/internal/agent/runner.go@@ -2,8 +2,11 @@ package agentimport ("bytes"+ "compress/gzip""context""crypto/md5"+ "crypto/rand"+ "encoding/hex""encoding/json""fmt""io"@@ -28,6 +31,7 @@ type trackedFlow struct {type reportPayload struct {BackendID int `json:"backendId"`+ RequestID string `json:"requestId,omitempty"`AgentID string `json:"agentId"`AgentVersion string `json:"agentVersion,omitempty"`ProtocolVersion int `json:"protocolVersion"`@@ -64,13 +68,15 @@ type Runner struct {hostname stringlockFile *os.File- mu sync.Mutex- queue []domain.TrafficUpdate- flows map[string]trackedFlow- dropped int64+ mu sync.Mutex+ queue []domain.TrafficUpdate+ flows map[string]trackedFlow+ dropped int64+ retryBatch []domain.TrafficUpdate+ retryID string- lastConfigHash string- lastPolicyHash string+ lastConfigHash string+ lastPolicyHash string}func NewRunner(cfg config.Config) *Runner {@@ -462,13 +468,14 @@ func (r *Runner) ingestSnapshots(snapshots []domain.FlowSnapshot, nowMs int64) {}func (r *Runner) flushOnce(ctx context.Context) error {- batch := r.takeBatch(r.cfg.ReportBatchSize)+ batch, requestID := r.takePendingBatch()if len(batch) == 0 {return nil}payload := reportPayload{BackendID: r.cfg.BackendID,+ RequestID: requestID,AgentID: r.cfg.AgentID,AgentVersion: config.AgentVersion,ProtocolVersion: config.AgentProtocolVersion,@@ -476,12 +483,44 @@ func (r *Runner) flushOnce(ctx context.Context) error {}if err := r.postJSON(ctx, "/agent/report", payload); err != nil {- r.requeueFront(batch)+ r.setRetryBatch(batch, requestID)return err}return nil}+// takePendingBatch returns the retry batch (with its original requestId) if one+// exists, otherwise dequeues a fresh batch from the queue and generates a new id.+func (r *Runner) takePendingBatch() ([]domain.TrafficUpdate, string) {+ r.mu.Lock()+ defer r.mu.Unlock()+ if len(r.retryBatch) > 0 {+ batch := r.retryBatch+ id := r.retryID+ r.retryBatch = nil+ r.retryID = ""+ return batch, id+ }+ if len(r.queue) == 0 {+ return nil, ""+ }+ limit := r.cfg.ReportBatchSize+ if limit > len(r.queue) {+ limit = len(r.queue)+ }+ out := make([]domain.TrafficUpdate, limit)+ copy(out, r.queue[:limit])+ r.queue = r.queue[limit:]+ return out, newRequestID()+}++func (r *Runner) setRetryBatch(batch []domain.TrafficUpdate, id string) {+ r.mu.Lock()+ defer r.mu.Unlock()+ r.retryBatch = batch+ r.retryID = id+}+func (r *Runner) sendHeartbeat(ctx context.Context) error {payload := heartbeatPayload{BackendID: r.cfg.BackendID,@@ -502,11 +541,21 @@ func (r *Runner) postJSON(ctx context.Context, path string, payload interface{})return err}- req, err := http.NewRequestWithContext(ctx, http.MethodPost, r.cfg.ServerAPIBase+path, bytes.NewReader(body))+ var buf bytes.Buffer+ gz := gzip.NewWriter(&buf)+ if _, err = gz.Write(body); err != nil {+ return err+ }+ if err = gz.Close(); err != nil {+ return err+ }++ req, err := http.NewRequestWithContext(ctx, http.MethodPost, r.cfg.ServerAPIBase+path, &buf)if err != nil {return err}req.Header.Set("Content-Type", "application/json")+ req.Header.Set("Content-Encoding", "gzip")req.Header.Set("Authorization", "Bearer "+r.cfg.BackendToken)resp, err := r.httpClient.Do(req)@@ -527,6 +576,12 @@ func (r *Runner) postJSON(ctx context.Context, path string, payload interface{})return fmt.Errorf("server http %d: %s", resp.StatusCode, msg)}+func newRequestID() string {+ b := make([]byte, 16)+ _, _ = rand.Read(b)+ return hex.EncodeToString(b)+}+func (r *Runner) takeBatch(limit int) []domain.TrafficUpdate {r.mu.Lock()defer r.mu.Unlock()diff --git a/apps/agent/internal/config/config.go b/apps/agent/internal/config/config.goindex 7bdd1c5..14d6da8 100644--- a/apps/agent/internal/config/config.go+++ b/apps/agent/internal/config/config.go@@ -10,7 +10,9 @@ import ("time")-const AgentVersion = "0.1.0"+// AgentVersion is set at build time via -ldflags "-X ...config.AgentVersion=<tag>"+// Falls back to "dev" for local/untagged builds.+var AgentVersion = "dev"const AgentProtocolVersion = 1var (diff --git a/apps/agent/nekoagent b/apps/agent/nekoagentindex f6e8fbf..4f727b3 100755--- a/apps/agent/nekoagent+++ b/apps/agent/nekoagent@@ -7,6 +7,7 @@ INSTALL_DIR="${NEKO_INSTALL_DIR:-$INSTALL_DIR_DEFAULT}"AGENT_BIN="${NEKO_AGENT_BIN:-$INSTALL_DIR/neko-agent}"CONFIG_DIR="${NEKO_AGENT_CONFIG_DIR:-/etc/neko-agent}"STATE_DIR="${NEKO_AGENT_STATE_DIR:-/var/run/neko-agent}"+AGENT_REPO="${NEKO_AGENT_REPO:-foru17/neko-master}"VERSION="0.2.0"log() {@@ -49,8 +50,170 @@ is_running() {kill -0 "$pid" >/dev/null 2>&1}+# ── Download helpers ────────────────────────────────────────────────────────++download_file() {+ url="$1"+ output="$2"+ if command -v curl >/dev/null 2>&1; then+ curl -fsSL "$url" -o "$output"+ return 0+ fi+ if command -v wget >/dev/null 2>&1; then+ wget -qO "$output" "$url"+ return 0+ fi+ err "curl or wget is required"+ exit 1+}++compute_sha256() {+ file="$1"+ if command -v sha256sum >/dev/null 2>&1; then+ sha256sum "$file" | awk '{print $1}'+ return 0+ fi+ if command -v shasum >/dev/null 2>&1; then+ shasum -a 256 "$file" | awk '{print $1}'+ return 0+ fi+ if command -v openssl >/dev/null 2>&1; then+ openssl dgst -sha256 "$file" | awk '{print $2}'+ return 0+ fi+ echo ""+}++normalize_os() {+ raw="$(uname -s | tr '[:upper:]' '[:lower:]')"+ case "$raw" in+ linux) echo "linux" ;;+ darwin) echo "darwin" ;;+ *)+ err "unsupported OS: $raw"+ exit 1+ ;;+ esac+}++normalize_arch() {+ raw="$(uname -m | tr '[:upper:]' '[:lower:]')"+ case "$raw" in+ x86_64|amd64) echo "amd64" ;;+ aarch64|arm64) echo "arm64" ;;+ armv7l|armv7|armhf) echo "armv7" ;;+ mips) echo "mips" ;;+ mipsle) echo "mipsle" ;;+ *)+ err "unsupported architecture: $raw"+ exit 1+ ;;+ esac+}++# Query GitHub releases API for the latest agent tag (e.g. "agent-v0.2.0").+# Returns empty string on failure — callers must handle this gracefully.+get_latest_remote_tag() {+ repo="${1:-$AGENT_REPO}"+ api_url="https://api.github.com/repos/${repo}/releases/latest"+ tag=""+ if command -v curl >/dev/null 2>&1; then+ tag="$(curl -fsSL "$api_url" 2>/dev/null | awk -F'"' '/"tag_name"/{print $4; exit}')"+ elif command -v wget >/dev/null 2>&1; then+ tag="$(wget -qO- "$api_url" 2>/dev/null | awk -F'"' '/"tag_name"/{print $4; exit}')"+ fi+ printf '%s\n' "$tag"+}++# Return the version string reported by the local neko-agent binary, or "".+get_local_binary_version() {+ if [ -x "$AGENT_BIN" ]; then+ "$AGENT_BIN" --version 2>/dev/null | head -1 || true+ fi+}++# ── Update / download binary ────────────────────────────────────────────────++# Download, verify, and install a new neko-agent binary.+# Usage: do_download_binary <version_arg> <os> <arch>+# version_arg: "latest" or "agent-v0.2.0" style tag+do_download_binary() {+ version_arg="$1"+ os="$2"+ arch="$3"++ if [ "$version_arg" = "latest" ]; then+ release_path="releases/latest/download"+ asset="neko-agent_${os}_${arch}.tar.gz"+ else+ # normalise: accept bare "0.2.0" or full "agent-v0.2.0"+ case "$version_arg" in+ agent-v*) tag="$version_arg" ;;+ v*) tag="agent-${version_arg}" ;;+ *) tag="agent-v${version_arg}" ;;+ esac+ release_path="releases/download/${tag}"+ asset="neko-agent_${tag}_${os}_${arch}.tar.gz"+ fi++ package_url="https://github.com/${AGENT_REPO}/${release_path}/${asset}"+ checksums_url="https://github.com/${AGENT_REPO}/${release_path}/checksums.txt"++ tmp_dir="$(mktemp -d)"+ # shellcheck disable=SC2064+ trap "rm -rf '$tmp_dir'" EXIT INT TERM++ archive_path="$tmp_dir/neko-agent.tar.gz"+ checksums_path="$tmp_dir/checksums.txt"++ log "downloading $package_url"+ download_file "$package_url" "$archive_path"++ log "verifying checksum..."+ download_file "$checksums_url" "$checksums_path"+ expected_hash="$(awk -v a="$asset" '$2 == a {print $1}' "$checksums_path" | head -n 1)"+ if [ -z "$expected_hash" ]; then+ err "cannot find checksum for $asset in checksums.txt"+ exit 1+ fi+ actual_hash="$(compute_sha256 "$archive_path")"+ if [ -z "$actual_hash" ]; then+ err "no sha256 tooling found (sha256sum / shasum / openssl)"+ exit 1+ fi+ if [ "$expected_hash" != "$actual_hash" ]; then+ err "checksum mismatch for $asset"+ err " expected: $expected_hash"+ err " actual: $actual_hash"+ exit 1+ fi++ mkdir -p "$tmp_dir/extract"+ tar -xzf "$archive_path" -C "$tmp_dir/extract"++ new_binary="$tmp_dir/extract/neko-agent"+ if [ ! -f "$new_binary" ]; then+ err "extracted archive does not contain neko-agent"+ exit 1+ fi++ chmod +x "$new_binary"+ install_dir="$(dirname "$AGENT_BIN")"+ mkdir -p "$install_dir"+ mv "$new_binary" "$AGENT_BIN"+ log "binary installed: $AGENT_BIN"+}++# ── Commands ────────────────────────────────────────────────────────────────+version() {- printf '%s\n' "$VERSION"+ manager_ver="$VERSION"+ binary_ver="$(get_local_binary_version)"+ if [ -z "$binary_ver" ]; then+ binary_ver="(binary not found)"+ fi+ printf 'nekoagent %s\n' "$manager_ver"+ printf 'neko-agent %s\n' "$binary_ver"}usage() {@@ -58,22 +221,22 @@ usage() {Neko Agent Manager v${VERSION}Usage:- $PROG init <name> [KEY=VALUE ...] Create/overwrite config file- $PROG add <name> [flags/options] Quick add new backend instance- $PROG start <name> Start agent instance- $PROG stop <name> Stop agent instance- $PROG restart <name> Restart agent instance- $PROG status <name> Show instance status- $PROG logs <name> Tail logs- $PROG list List configured instances- $PROG update <name> [version] Update agent binary and restart- $PROG remove <name> Remove instance config/runtime- $PROG delete <name> Alias of remove- $PROG uninstall Uninstall nekoagent + binaries- $PROG version Show version- $PROG help Show this help--Quick add with flags:+ $PROG init <name> [KEY=VALUE ...] Create/overwrite config file+ $PROG add <name> [flags/options] Quick add new backend instance+ $PROG start <name> Start agent instance+ $PROG stop <name> Stop agent instance+ $PROG restart <name> Restart agent instance+ $PROG status <name> Show instance status+ $PROG logs <name> Tail logs+ $PROG list List configured instances+ $PROG update|upgrade <name> [version] Update binary and restart+ $PROG remove <name> Remove instance config/runtime+ $PROG delete <name> Alias of remove+ $PROG uninstall Uninstall nekoagent + binaries+ $PROG version Show manager and binary version+ $PROG help Show this help++Quick add with flags (auto-starts by default):$PROG add <name> \--server-url <url> \--backend-id <id> \@@ -81,7 +244,11 @@ Quick add with flags:--gateway-type <clash|surge> \--gateway-url <url> \[--gateway-token <token>] \- [--auto-start]+ [--no-start] # skip auto-start after add++Update examples:+ $PROG update home-surge # update to latest release+ $PROG update home-surge agent-v0.2.0 # update to specific versionConfig and runtime paths:CONFIG_DIR=$CONFIG_DIR@@ -99,7 +266,7 @@ Examples:# Add and start a new backend$PROG add home-surge --server-url http://10.0.0.210:3000 --backend-id 3 \\--backend-token ag_xxx --gateway-type surge --gateway-url http://10.0.0.210:9091 \\- --gateway-token xxx --auto-start+ --gateway-token xxx# List all instances$PROG list@@ -113,6 +280,9 @@ Examples:# Update to latest version$PROG update home-surge+ # Update to specific version+ $PROG update home-surge agent-v0.2.0+# Remove instance$PROG remove home-surgeEOF@@ -223,7 +393,7 @@ cmd_add() {gateway_type=""gateway_url=""gateway_token=""- auto_start="false"+ auto_start="true" # default: start immediately after addwhile [ "$#" -gt 0 ]; docase "$1" in@@ -255,6 +425,10 @@ cmd_add() {auto_start="true"shift;;+ --no-start)+ auto_start="false"+ shift+ ;;*)err "unknown flag: $1"exit 1@@ -281,6 +455,7 @@ cmd_add() {fi# Initialize config+ # shellcheck disable=SC2086cmd_init "$name" $config_varslog "instance '$name' added successfully"@@ -308,6 +483,7 @@ cmd_start() {lf="$(log_file "$name")"pf="$(pid_file "$name")"+ # shellcheck disable=SC2086nohup "$AGENT_BIN" $args >> "$lf" 2>&1 &pid=$!printf '%s\n' "$pid" > "$pf"@@ -383,43 +559,50 @@ cmd_list() {cmd_update() {name="$1"- version="${2:-latest}"- load_config "$name"- was_running=false- if is_running "$name"; then- was_running=true- cmd_stop "$name"+ version_arg="${2:-latest}"++ os="$(normalize_os)"+ arch="$(normalize_arch)"++ # Determine the plain version string we're targeting (no "agent-v" prefix)+ if [ "$version_arg" = "latest" ]; then+ log "querying GitHub for latest release..."+ remote_tag="$(get_latest_remote_tag "$AGENT_REPO")"+ if [ -z "$remote_tag" ]; then+ err "failed to determine latest version from GitHub API"+ err "hint: check network access or specify a version: $PROG update $name agent-v0.2.0"+ exit 1+ fi+ target_plain="${remote_tag#agent-v}"+ else+ case "$version_arg" in+ agent-v*) target_plain="${version_arg#agent-v}" ;;+ v*) target_plain="${version_arg#v}" ;;+ *) target_plain="$version_arg" ;;+ esacfi- install_script_url="https://raw.githubusercontent.com/foru17/neko-master/main/apps/agent/install.sh"- tmp_script="$(mktemp)"- trap 'rm -f "$tmp_script"' EXIT INT TERM-- if command -v curl >/dev/null 2>&1; then- curl -fsSL "$install_script_url" -o "$tmp_script"- elif command -v wget >/dev/null 2>&1; then- wget -qO "$tmp_script" "$install_script_url"+ # Check local binary version — skip download if already up-to-date+ local_version="$(get_local_binary_version)"+ if [ -n "$local_version" ] && [ "$local_version" = "$target_plain" ]; then+ log "binary already at $local_version, no download needed"else- err "curl or wget is required"- exit 1- fi+ log "updating binary: ${local_version:-not installed} -> $target_plain"- env \- NEKO_SERVER="$NEKO_SERVER" \- NEKO_BACKEND_ID="$NEKO_BACKEND_ID" \- NEKO_BACKEND_TOKEN="$NEKO_BACKEND_TOKEN" \- NEKO_GATEWAY_TYPE="$NEKO_GATEWAY_TYPE" \- NEKO_GATEWAY_URL="$NEKO_GATEWAY_URL" \- NEKO_GATEWAY_TOKEN="${NEKO_GATEWAY_TOKEN:-}" \- NEKO_AGENT_VERSION="$version" \- NEKO_INSTALL_DIR="$INSTALL_DIR" \- NEKO_AUTO_START="false" \- sh "$tmp_script"+ was_running=false+ if is_running "$name"; then+ was_running=true+ cmd_stop "$name"+ fi- if [ "$was_running" = true ]; then- cmd_start "$name"+ do_download_binary "$version_arg" "$os" "$arch"++ if [ "$was_running" = true ]; then+ cmd_start "$name"+ fifi- log "instance '$name' updated to $version"++ log "instance '$name' is at version $target_plain"}cmd_remove() {@@ -478,14 +661,14 @@ main() {exit 1ficase "$cmd" in- start) cmd_start "$1" ;;- stop) cmd_stop "$1" ;;+ start) cmd_start "$1" ;;+ stop) cmd_stop "$1" ;;restart) cmd_stop "$1" || true; cmd_start "$1" ;;- status) cmd_status "$1" ;;- logs) cmd_logs "$1" ;;+ status) cmd_status "$1" ;;+ logs) cmd_logs "$1" ;;esac;;- update)+ update|upgrade)if [ "$#" -lt 1 ] || [ "$#" -gt 2 ]; thenusageexit 1diff --git a/apps/collector/src/modules/app/app.ts b/apps/collector/src/modules/app/app.tsindex 443171c..8a1446e 100644--- a/apps/collector/src/modules/app/app.ts+++ b/apps/collector/src/modules/app/app.ts@@ -5,6 +5,7 @@*/import crypto from 'crypto';+import { createGunzip } from 'node:zlib';import Fastify from 'fastify';import cors from '@fastify/cors';import cookie from '@fastify/cookie';@@ -86,6 +87,7 @@ type AgentReportPayload = {agentId?: string;protocolVersion?: number;agentVersion?: string;+ requestId?: string;updates?: AgentTrafficUpdatePayload[];};@@ -106,6 +108,34 @@ export async function createApp(options: AppOptions) {// Increase body limit to 5MB for agent config sync (large Clash/Surge configs)const app = Fastify({ logger, bodyLimit: 5 * 1024 * 1024 });+ // Decompress gzip-encoded request bodies (used by the agent to reduce upload bandwidth)+ app.addHook('preParsing', async (request, _reply, payload) => {+ if (request.headers['content-encoding'] === 'gzip') {+ return payload.pipe(createGunzip());+ }+ return payload;+ });++ // In-memory dedup for agent report requestIds — prevents double-counting on POST retry.+ // Keyed by requestId, value is the time it was first seen (ms). TTL: 5 minutes.+ const seenRequestIds = new Map<string, number>();+ const REQUEST_ID_TTL_MS = 5 * 60 * 1000;+ function isDuplicateRequestId(id: string): boolean {+ const now = Date.now();+ if (seenRequestIds.has(id)) {+ return true;+ }+ seenRequestIds.set(id, now);+ // Prune expired entries periodically (every ~500 inserts is fine; map is small)+ if (seenRequestIds.size % 500 === 0) {+ const cutoff = now - REQUEST_ID_TTL_MS;+ for (const [k, ts] of seenRequestIds) {+ if (ts < cutoff) seenRequestIds.delete(k);+ }+ }+ return false;+ }+// Register CORSawait app.register(cors, {origin: true,@@ -466,6 +496,12 @@ export async function createApp(options: AppOptions) {return;}+ // Idempotency: if this requestId has already been processed, skip to avoid double-counting+ const requestId = typeof body?.requestId === 'string' ? body.requestId.slice(0, 64) : '';+ if (requestId && isDuplicateRequestId(requestId)) {+ return { success: true, backendId, accepted: 0, dropped: 0, duplicate: true };+ }+const rawUpdates = Array.isArray(body?.updates) ? body.updates : [];if (rawUpdates.length === 0) {return { success: true, backendId, accepted: 0, dropped: 0 };@@ -488,7 +524,8 @@ export async function createApp(options: AppOptions) {}const clickHouseWriter = getClickHouseWriter();- const skipSqliteStatsWrites = shouldSkipSqliteStatsWrites(clickHouseWriter.isEnabled());+ // Use isHealthy() (not isEnabled()) so SQLite fallback activates when ClickHouse is failing+ const skipSqliteStatsWrites = shouldSkipSqliteStatsWrites(clickHouseWriter.isHealthy());if (!skipSqliteStatsWrites) {db.batchUpdateTrafficStats(backendId, updates);}diff --git a/package.json b/package.jsonindex 2aff390..8ae83bf 100644--- a/package.json+++ b/package.json@@ -1,6 +1,6 @@{"name": "neko-master",- "version": "1.3.1",+ "version": "1.3.2","description": "Modern traffic analytics for edge gateways","private": true,"workspaces": [