Skip to content

A modern and elegant dashboard for network traffic visualization and analysis.

feat: add explicit connections count to agent traffic updates with legacy fallback and update CLI command to upgrade

luoleia81b358d5ad8
diff --git a/README.en.md b/README.en.md
index acfd7d7..cd7a22e 100644
--- a/README.en.md
+++ b/README.en.md
@@ -278,7 +278,7 @@ nekoagent list # list all instances
nekoagent status <instance> # check running state
nekoagent logs <instance> # tail live logs
nekoagent restart <instance> # restart
-nekoagent update <instance> # update to latest version
+nekoagent upgrade # global upgrade (CLI + binary)
```
> The script auto-detects an existing installation — if `neko-agent` is already present, it only adds the new instance without re-downloading.
diff --git a/README.md b/README.md
index 352d0a1..9017984 100644
--- a/README.md
+++ b/README.md
@@ -270,7 +270,7 @@ nekoagent list # 列出所有实例
nekoagent status <instance> # 查看运行状态
nekoagent logs <instance> # 实时日志
nekoagent restart <instance> # 重启
-nekoagent update <instance> # 更新到最新版
+nekoagent upgrade # 全局升级(CLI + 二进制)
```
> 脚本会自动检测已有安装,若已存在则只添加新实例而不重新下载二进制。
diff --git a/apps/agent/README.md b/apps/agent/README.md
index 2963748..7663262 100644
--- a/apps/agent/README.md
+++ b/apps/agent/README.md
@@ -59,7 +59,8 @@ Installer also provides `nekoagent` manager for friendly operations:
nekoagent status backend-1
nekoagent logs backend-1
nekoagent restart backend-1
-nekoagent update backend-1 agent-v1.3.2
+nekoagent upgrade
+nekoagent upgrade agent-v1.3.2
nekoagent remove backend-1
nekoagent uninstall
```
diff --git a/apps/agent/install.sh b/apps/agent/install.sh
index e9e62ac..88a0f60 100755
--- a/apps/agent/install.sh
+++ b/apps/agent/install.sh
@@ -392,7 +392,7 @@ main() {
echo " nekoagent stop $NEKO_INSTANCE_NAME"
echo " nekoagent status $NEKO_INSTANCE_NAME"
echo " nekoagent logs $NEKO_INSTANCE_NAME"
- echo " nekoagent update $NEKO_INSTANCE_NAME"
+ echo " nekoagent upgrade"
echo " nekoagent remove $NEKO_INSTANCE_NAME"
}
diff --git a/apps/agent/internal/agent/runner.go b/apps/agent/internal/agent/runner.go
index bc9f76a..0b62fb5 100644
--- a/apps/agent/internal/agent/runner.go
+++ b/apps/agent/internal/agent/runner.go
@@ -24,9 +24,16 @@ import (
)
type trackedFlow struct {
- LastUpload int64
- LastDown int64
- LastSeenMs int64
+ LastUpload int64
+ LastDown int64
+ LastSeenMs int64
+ Counted bool
+ Domain string
+ IP string
+ SourceIP string
+ Chains []string
+ Rule string
+ RulePayload string
}
type reportPayload struct {
@@ -100,7 +107,7 @@ func (r *Runner) acquireLock() error {
// Use OS temp directory for lock file
lockDir := os.TempDir()
lockPath := fmt.Sprintf("%s/neko-agent-backend-%d.lock", lockDir, r.cfg.BackendID)
-
+
// Check if lock file exists and if process is still running
if data, err := os.ReadFile(lockPath); err == nil {
var pid int
@@ -116,7 +123,7 @@ func (r *Runner) acquireLock() error {
}
}
}
-
+
// Create lock file with exclusive flag (O_EXCL)
file, err := os.OpenFile(lockPath, os.O_CREATE|os.O_EXCL|os.O_RDWR, 0644)
if err != nil {
@@ -125,7 +132,7 @@ func (r *Runner) acquireLock() error {
}
return fmt.Errorf("failed to create lock file: %w", err)
}
-
+
// Write PID to lock file
pid := fmt.Sprintf("%d", os.Getpid())
if _, err := file.WriteString(pid); err != nil {
@@ -133,7 +140,7 @@ func (r *Runner) acquireLock() error {
os.Remove(lockPath)
return fmt.Errorf("failed to write PID to lock file: %w", err)
}
-
+
r.lockFile = file
return nil
}
@@ -407,6 +414,27 @@ func (r *Runner) ingestSnapshots(snapshots []domain.FlowSnapshot, nowMs int64) {
active[s.ID] = struct{}{}
prev, hasPrev := r.flows[s.ID]
+ counted := false
+ if hasPrev {
+ counted = prev.Counted
+ }
+ domainName := strings.TrimSpace(s.Domain)
+ ip := strings.TrimSpace(s.IP)
+ sourceIP := strings.TrimSpace(s.SourceIP)
+ chains := normalizeChains(s.Chains)
+ rule := defaultString(strings.TrimSpace(s.Rule), "Match")
+ rulePayload := strings.TrimSpace(s.RulePayload)
+ if hasPrev {
+ // Keep per-flow metadata stable once first seen, matching direct mode
+ // semantics in collector (existing connection fields are reused).
+ domainName = prev.Domain
+ ip = prev.IP
+ sourceIP = prev.SourceIP
+ chains = cloneStringSlice(prev.Chains)
+ rule = defaultString(prev.Rule, "Match")
+ rulePayload = prev.RulePayload
+ }
+
deltaUp := s.Upload
deltaDown := s.Download
if hasPrev {
@@ -422,7 +450,24 @@ func (r *Runner) ingestSnapshots(snapshots []domain.FlowSnapshot, nowMs int64) {
}
}
- r.flows[s.ID] = trackedFlow{LastUpload: s.Upload, LastDown: s.Download, LastSeenMs: nowMs}
+ connections := int64(0)
+ if (deltaUp > 0 || deltaDown > 0) && !counted {
+ connections = 1
+ counted = true
+ }
+
+ r.flows[s.ID] = trackedFlow{
+ LastUpload: s.Upload,
+ LastDown: s.Download,
+ LastSeenMs: nowMs,
+ Counted: counted,
+ Domain: domainName,
+ IP: ip,
+ SourceIP: sourceIP,
+ Chains: cloneStringSlice(chains),
+ Rule: rule,
+ RulePayload: rulePayload,
+ }
if deltaUp <= 0 && deltaDown <= 0 {
continue
}
@@ -433,15 +478,16 @@ func (r *Runner) ingestSnapshots(snapshots []domain.FlowSnapshot, nowMs int64) {
}
updates = append(updates, domain.TrafficUpdate{
- Domain: s.Domain,
- IP: s.IP,
- Chain: firstChain(s.Chains),
- Chains: s.Chains,
- Rule: defaultString(s.Rule, "Match"),
- RulePayload: s.RulePayload,
+ Domain: domainName,
+ IP: ip,
+ Chain: firstChain(chains),
+ Chains: cloneStringSlice(chains),
+ Rule: rule,
+ RulePayload: rulePayload,
Upload: deltaUp,
Download: deltaDown,
- SourceIP: s.SourceIP,
+ Connections: connections,
+ SourceIP: sourceIP,
TimestampMs: ts,
})
}
@@ -632,6 +678,36 @@ func firstChain(chains []string) string {
return strings.TrimSpace(chains[0])
}
+func normalizeChains(chains []string) []string {
+ if len(chains) == 0 {
+ return []string{"DIRECT"}
+ }
+ out := make([]string, 0, len(chains))
+ for _, chain := range chains {
+ trimmed := strings.TrimSpace(chain)
+ if trimmed == "" {
+ continue
+ }
+ out = append(out, trimmed)
+ if len(out) >= 12 {
+ break
+ }
+ }
+ if len(out) == 0 {
+ return []string{"DIRECT"}
+ }
+ return out
+}
+
+func cloneStringSlice(values []string) []string {
+ if len(values) == 0 {
+ return nil
+ }
+ cloned := make([]string, len(values))
+ copy(cloned, values)
+ return cloned
+}
+
func defaultString(v string, fallback string) string {
if strings.TrimSpace(v) == "" {
return fallback
diff --git a/apps/agent/internal/agent/runner_test.go b/apps/agent/internal/agent/runner_test.go
index 8e0d6dd..1f54150 100644
--- a/apps/agent/internal/agent/runner_test.go
+++ b/apps/agent/internal/agent/runner_test.go
@@ -40,6 +40,9 @@ func TestIngestSnapshotsDeltaCalculation(t *testing.T) {
if first[0].Upload != 10 || first[0].Download != 20 {
t.Fatalf("expected first delta 10/20, got %d/%d", first[0].Upload, first[0].Download)
}
+ if first[0].Connections != 1 {
+ t.Fatalf("expected first connections 1, got %d", first[0].Connections)
+ }
runner.ingestSnapshots([]domain.FlowSnapshot{{
ID: "flow-1",
@@ -56,6 +59,9 @@ func TestIngestSnapshotsDeltaCalculation(t *testing.T) {
if second[0].Upload != 15 || second[0].Download != 30 {
t.Fatalf("expected second delta 15/30, got %d/%d", second[0].Upload, second[0].Download)
}
+ if second[0].Connections != 0 {
+ t.Fatalf("expected second connections 0, got %d", second[0].Connections)
+ }
runner.ingestSnapshots([]domain.FlowSnapshot{{
ID: "flow-1",
@@ -70,3 +76,52 @@ func TestIngestSnapshotsDeltaCalculation(t *testing.T) {
t.Fatalf("expected third batch len 0 when counters reset, got %d", len(third))
}
}
+
+func TestIngestSnapshotsFirstTrafficAfterZeroCarriesConnection(t *testing.T) {
+ runner := NewRunner(config.Config{
+ ServerAPIBase: "http://localhost:3000/api",
+ BackendID: 1,
+ BackendToken: "token",
+ AgentID: "agent-test",
+ GatewayType: "clash",
+ GatewayEndpoint: "http://127.0.0.1:9090",
+ ReportInterval: time.Second,
+ HeartbeatInterval: time.Second,
+ GatewayPollInterval: time.Second,
+ RequestTimeout: time.Second,
+ ReportBatchSize: 100,
+ MaxPendingUpdates: 1000,
+ StaleFlowTimeout: time.Minute,
+ })
+
+ runner.ingestSnapshots([]domain.FlowSnapshot{{
+ ID: "flow-2",
+ Upload: 0,
+ Download: 0,
+ Chains: []string{"DIRECT"},
+ Rule: "Match",
+ }}, 1000)
+
+ if batch := runner.takeBatch(10); len(batch) != 0 {
+ t.Fatalf("expected no batch for zero traffic, got %d", len(batch))
+ }
+
+ runner.ingestSnapshots([]domain.FlowSnapshot{{
+ ID: "flow-2",
+ Upload: 8,
+ Download: 5,
+ Chains: []string{"DIRECT"},
+ Rule: "Match",
+ }}, 2000)
+
+ second := runner.takeBatch(10)
+ if len(second) != 1 {
+ t.Fatalf("expected one update after first traffic, got %d", len(second))
+ }
+ if second[0].Upload != 8 || second[0].Download != 5 {
+ t.Fatalf("expected delta 8/5, got %d/%d", second[0].Upload, second[0].Download)
+ }
+ if second[0].Connections != 1 {
+ t.Fatalf("expected connections 1 for first non-zero traffic, got %d", second[0].Connections)
+ }
+}
diff --git a/apps/agent/internal/domain/types.go b/apps/agent/internal/domain/types.go
index ed32014..32a6dec 100644
--- a/apps/agent/internal/domain/types.go
+++ b/apps/agent/internal/domain/types.go
@@ -9,6 +9,7 @@ type TrafficUpdate struct {
RulePayload string `json:"rulePayload,omitempty"`
Upload int64 `json:"upload"`
Download int64 `json:"download"`
+ Connections int64 `json:"connections,omitempty"`
SourceIP string `json:"sourceIP,omitempty"`
TimestampMs int64 `json:"timestampMs"`
}
diff --git a/apps/agent/nekoagent b/apps/agent/nekoagent
index 4f727b3..02625e7 100755
--- a/apps/agent/nekoagent
+++ b/apps/agent/nekoagent
@@ -132,6 +132,42 @@ get_local_binary_version() {
fi
}
+is_version_arg() {
+ v="${1:-}"
+ case "$v" in
+ ""|latest|agent-v*|v[0-9]*|[0-9]*)
+ return 0
+ ;;
+ *)
+ return 1
+ ;;
+ esac
+}
+
+normalize_version_tag() {
+ version_arg="${1:-latest}"
+ if [ "$version_arg" = "latest" ]; then
+ printf 'latest\n'
+ return 0
+ fi
+ case "$version_arg" in
+ agent-v*)
+ printf '%s\n' "$version_arg"
+ ;;
+ v*)
+ printf 'agent-%s\n' "$version_arg"
+ ;;
+ *)
+ printf 'agent-v%s\n' "$version_arg"
+ ;;
+ esac
+}
+
+target_plain_from_tag() {
+ tag="$1"
+ printf '%s\n' "${tag#agent-v}"
+}
+
# ── Update / download binary ────────────────────────────────────────────────
# Download, verify, and install a new neko-agent binary.
@@ -204,6 +240,35 @@ do_download_binary() {
log "binary installed: $AGENT_BIN"
}
+# Download and install the manager script itself.
+# Usage: do_download_manager <agent-tag>
+# agent-tag: e.g. "agent-v0.2.0"
+do_download_manager() {
+ tag="$1"
+ manager_url="https://raw.githubusercontent.com/${AGENT_REPO}/${tag}/apps/agent/nekoagent"
+
+ tmp_dir="$(mktemp -d)"
+ # shellcheck disable=SC2064
+ trap "rm -rf '$tmp_dir'" EXIT INT TERM
+ new_manager="$tmp_dir/nekoagent"
+
+ log "downloading manager script: $manager_url"
+ download_file "$manager_url" "$new_manager"
+ chmod +x "$new_manager"
+
+ mkdir -p "$INSTALL_DIR"
+ manager_target="$INSTALL_DIR/nekoagent"
+ mv "$new_manager" "$manager_target"
+ log "manager installed: $manager_target"
+
+ current_path="$(command -v "$PROG" 2>/dev/null || true)"
+ if [ -n "$current_path" ] && [ "$current_path" != "$manager_target" ] && [ -w "$current_path" ]; then
+ cp "$manager_target" "$current_path"
+ chmod +x "$current_path" || true
+ log "manager synced to: $current_path"
+ fi
+}
+
# ── Commands ────────────────────────────────────────────────────────────────
version() {
@@ -229,7 +294,7 @@ Usage:
$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 upgrade [version] Upgrade manager+binary globally
$PROG remove <name> Remove instance config/runtime
$PROG delete <name> Alias of remove
$PROG uninstall Uninstall nekoagent + binaries
@@ -246,9 +311,9 @@ Quick add with flags (auto-starts by default):
[--gateway-token <token>] \
[--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 version
+Upgrade examples:
+ $PROG upgrade # upgrade to latest release
+ $PROG upgrade agent-v0.2.0 # upgrade to specific version
Config and runtime paths:
CONFIG_DIR=$CONFIG_DIR
@@ -277,11 +342,9 @@ Examples:
# View logs
$PROG logs home-surge
- # Update to latest version
- $PROG update home-surge
-
- # Update to specific version
- $PROG update home-surge agent-v0.2.0
+ # Global upgrade (recommended)
+ $PROG upgrade
+ $PROG upgrade agent-v0.2.0
# Remove instance
$PROG remove home-surge
@@ -557,52 +620,59 @@ cmd_list() {
fi
}
-cmd_update() {
- name="$1"
- version_arg="${2:-latest}"
-
+cmd_upgrade_global() {
+ version_arg="${1:-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
+ target_tag="$(get_latest_remote_tag "$AGENT_REPO")"
+ if [ -z "$target_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"
+ err "hint: check network access or specify a version: $PROG upgrade 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" ;;
- esac
+ target_tag="$(normalize_version_tag "$version_arg")"
fi
+ target_plain="$(target_plain_from_tag "$target_tag")"
- # Check local binary version — skip download if already up-to-date
local_version="$(get_local_binary_version)"
+ binary_changed=false
if [ -n "$local_version" ] && [ "$local_version" = "$target_plain" ]; then
- log "binary already at $local_version, no download needed"
+ log "binary already at $local_version, no binary download needed"
else
- log "updating binary: ${local_version:-not installed} -> $target_plain"
+ log "upgrading binary: ${local_version:-not installed} -> $target_plain"
+ do_download_binary "$target_tag" "$os" "$arch"
+ binary_changed=true
+ fi
- was_running=false
- if is_running "$name"; then
- was_running=true
- cmd_stop "$name"
- fi
+ do_download_manager "$target_tag"
- do_download_binary "$version_arg" "$os" "$arch"
+ if [ "$binary_changed" = true ]; then
+ restarted_any=false
+ for f in "$CONFIG_DIR"/*.env; do
+ if [ ! -e "$f" ]; then
+ continue
+ fi
+ name="$(basename "$f" .env)"
+ if is_running "$name"; then
+ log "restarting running instance '$name'..."
+ cmd_stop "$name" || true
+ cmd_start "$name"
+ restarted_any=true
+ fi
+ done
- if [ "$was_running" = true ]; then
- cmd_start "$name"
+ if [ "$restarted_any" = false ]; then
+ log "no running instances found; binary upgraded globally"
fi
+ else
+ log "binary unchanged; skipped instance restart"
fi
- log "instance '$name' is at version $target_plain"
+ log "upgrade complete: manager + binary at version $target_plain"
}
cmd_remove() {
@@ -668,12 +738,20 @@ main() {
logs) cmd_logs "$1" ;;
esac
;;
- update|upgrade)
- if [ "$#" -lt 1 ] || [ "$#" -gt 2 ]; then
+ upgrade)
+ if [ "$#" -gt 1 ]; then
usage
exit 1
fi
- cmd_update "$@"
+ if [ "$#" -eq 1 ] && ! is_version_arg "$1"; then
+ err "upgrade only accepts an optional version (e.g. agent-v0.2.0), not instance name"
+ exit 1
+ fi
+ cmd_upgrade_global "${1:-latest}"
+ ;;
+ update)
+ err "'update' command has been removed; use '$PROG upgrade [version]'"
+ exit 1
;;
remove|delete)
if [ "$#" -ne 1 ]; then
diff --git a/apps/collector/src/database/repositories/traffic-writer.repository.ts b/apps/collector/src/database/repositories/traffic-writer.repository.ts
index 2044b8b..de0cd73 100644
--- a/apps/collector/src/database/repositories/traffic-writer.repository.ts
+++ b/apps/collector/src/database/repositories/traffic-writer.repository.ts
@@ -16,6 +16,7 @@ export interface TrafficUpdate {
rulePayload: string;
upload: number;
download: number;
+ connections?: number;
sourceIP?: string;
timestampMs?: number;
}
@@ -28,6 +29,12 @@ export class TrafficWriterRepository extends BaseRepository {
super(db);
}
+ private normalizeConnections(value: number | undefined): number {
+ const safe =
+ typeof value === 'number' && Number.isFinite(value) ? value : 1;
+ return Math.max(0, Math.floor(safe));
+ }
+
private prepareSingleStmts() {
return {
domainUpsert: this.db.prepare(`
@@ -229,6 +236,7 @@ export class TrafficWriterRepository extends BaseRepository {
for (const update of updates) {
if (update.upload === 0 && update.download === 0) continue;
+ const connections = this.normalizeConnections(update.connections);
const ruleName = update.chains.length > 1 ? update.chains[update.chains.length - 1] :
update.rulePayload ? `${update.rule}(${update.rulePayload})` : update.rule;
@@ -240,109 +248,273 @@ export class TrafficWriterRepository extends BaseRepository {
if (update.domain) {
const domainKey = `${update.domain}:${update.ip}:${fullChain}`;
const existing = domainMap.get(domainKey);
- if (existing) { existing.upload += update.upload; existing.download += update.download; existing.count++; }
- else { domainMap.set(domainKey, { ...update, count: 1 }); }
+ if (existing) {
+ existing.upload += update.upload;
+ existing.download += update.download;
+ existing.count += connections;
+ } else {
+ domainMap.set(domainKey, { ...update, count: connections });
+ }
}
// Aggregate IP stats
const ipKey = `${update.ip}:${update.domain}:${fullChain}`;
const existingIp = ipMap.get(ipKey);
- if (existingIp) { existingIp.upload += update.upload; existingIp.download += update.download; existingIp.count++; }
- else { ipMap.set(ipKey, { ...update, rule: ruleName, count: 1 }); }
+ if (existingIp) {
+ existingIp.upload += update.upload;
+ existingIp.download += update.download;
+ existingIp.count += connections;
+ } else {
+ ipMap.set(ipKey, { ...update, rule: ruleName, count: connections });
+ }
// Aggregate chain stats
const existingChain = chainMap.get(fullChain);
- if (existingChain) { existingChain.upload += update.upload; existingChain.download += update.download; existingChain.count++; }
- else { chainMap.set(fullChain, { chains: update.chains, upload: update.upload, download: update.download, count: 1 }); }
+ if (existingChain) {
+ existingChain.upload += update.upload;
+ existingChain.download += update.download;
+ existingChain.count += connections;
+ } else {
+ chainMap.set(fullChain, {
+ chains: update.chains,
+ upload: update.upload,
+ download: update.download,
+ count: connections,
+ });
+ }
// Aggregate rule stats
const ruleKey = `${ruleName}:${finalProxy}`;
const existingRule = ruleProxyMap.get(ruleKey);
- if (existingRule) { existingRule.upload += update.upload; existingRule.download += update.download; existingRule.count++; }
- else { ruleProxyMap.set(ruleKey, { rule: ruleName, proxy: finalProxy, upload: update.upload, download: update.download, count: 1 }); }
+ if (existingRule) {
+ existingRule.upload += update.upload;
+ existingRule.download += update.download;
+ existingRule.count += connections;
+ } else {
+ ruleProxyMap.set(ruleKey, {
+ rule: ruleName,
+ proxy: finalProxy,
+ upload: update.upload,
+ download: update.download,
+ count: connections,
+ });
+ }
// Aggregate hourly stats
const existingHour = hourlyMap.get(hourKey);
- if (existingHour) { existingHour.upload += update.upload; existingHour.download += update.download; existingHour.connections++; }
- else { hourlyMap.set(hourKey, { upload: update.upload, download: update.download, connections: 1 }); }
+ if (existingHour) {
+ existingHour.upload += update.upload;
+ existingHour.download += update.download;
+ existingHour.connections += connections;
+ } else {
+ hourlyMap.set(hourKey, {
+ upload: update.upload,
+ download: update.download,
+ connections,
+ });
+ }
// Aggregate rule_chain_traffic
const fullChainForRule = update.chains.join(' > ');
const ruleChainKey = `${ruleName}:${fullChainForRule}`;
const existingRuleChain = ruleChainMap.get(ruleChainKey);
- if (existingRuleChain) { existingRuleChain.upload += update.upload; existingRuleChain.download += update.download; existingRuleChain.count++; }
- else { ruleChainMap.set(ruleChainKey, { rule: ruleName, chain: fullChainForRule, upload: update.upload, download: update.download, count: 1 }); }
+ if (existingRuleChain) {
+ existingRuleChain.upload += update.upload;
+ existingRuleChain.download += update.download;
+ existingRuleChain.count += connections;
+ } else {
+ ruleChainMap.set(ruleChainKey, {
+ rule: ruleName,
+ chain: fullChainForRule,
+ upload: update.upload,
+ download: update.download,
+ count: connections,
+ });
+ }
// Aggregate rule_domain_traffic
if (update.domain) {
const rdKey = `${ruleName}:${update.domain}`;
const existingRD = ruleDomainMap.get(rdKey);
- if (existingRD) { existingRD.upload += update.upload; existingRD.download += update.download; existingRD.count++; }
- else { ruleDomainMap.set(rdKey, { rule: ruleName, domain: update.domain, upload: update.upload, download: update.download, count: 1 }); }
+ if (existingRD) {
+ existingRD.upload += update.upload;
+ existingRD.download += update.download;
+ existingRD.count += connections;
+ } else {
+ ruleDomainMap.set(rdKey, {
+ rule: ruleName,
+ domain: update.domain,
+ upload: update.upload,
+ download: update.download,
+ count: connections,
+ });
+ }
}
// Aggregate rule_ip_traffic
const riKey = `${ruleName}:${update.ip}`;
const existingRI = ruleIPMap.get(riKey);
- if (existingRI) { existingRI.upload += update.upload; existingRI.download += update.download; existingRI.count++; }
- else { ruleIPMap.set(riKey, { rule: ruleName, ip: update.ip, upload: update.upload, download: update.download, count: 1 }); }
+ if (existingRI) {
+ existingRI.upload += update.upload;
+ existingRI.download += update.download;
+ existingRI.count += connections;
+ } else {
+ ruleIPMap.set(riKey, {
+ rule: ruleName,
+ ip: update.ip,
+ upload: update.upload,
+ download: update.download,
+ count: connections,
+ });
+ }
// Aggregate minute_stats
const existingMinute = minuteMap.get(minuteKey);
- if (existingMinute) { existingMinute.upload += update.upload; existingMinute.download += update.download; existingMinute.connections++; }
- else { minuteMap.set(minuteKey, { upload: update.upload, download: update.download, connections: 1 }); }
+ if (existingMinute) {
+ existingMinute.upload += update.upload;
+ existingMinute.download += update.download;
+ existingMinute.connections += connections;
+ } else {
+ minuteMap.set(minuteKey, {
+ upload: update.upload,
+ download: update.download,
+ connections,
+ });
+ }
// Aggregate minute_dim_stats
const dimKey = `${minuteKey}:${update.domain || ''}:${update.ip || ''}:${update.sourceIP || ''}:${fullChain}:${ruleName}`;
const existingDim = minuteDimMap.get(dimKey);
- if (existingDim) { existingDim.upload += update.upload; existingDim.download += update.download; existingDim.connections++; }
- else { minuteDimMap.set(dimKey, { minute: minuteKey, domain: update.domain || '', ip: update.ip || '', sourceIP: update.sourceIP || '', chain: fullChain, rule: ruleName, upload: update.upload, download: update.download, connections: 1 }); }
+ if (existingDim) {
+ existingDim.upload += update.upload;
+ existingDim.download += update.download;
+ existingDim.connections += connections;
+ } else {
+ minuteDimMap.set(dimKey, {
+ minute: minuteKey,
+ domain: update.domain || '',
+ ip: update.ip || '',
+ sourceIP: update.sourceIP || '',
+ chain: fullChain,
+ rule: ruleName,
+ upload: update.upload,
+ download: update.download,
+ connections,
+ });
+ }
// Aggregate hourly_dim_stats
const hourlyDimKey = `${hourKey}:${update.domain || ''}:${update.ip || ''}:${update.sourceIP || ''}:${fullChain}:${ruleName}`;
const existingHourlyDim = hourlyDimMap.get(hourlyDimKey);
- if (existingHourlyDim) { existingHourlyDim.upload += update.upload; existingHourlyDim.download += update.download; existingHourlyDim.connections++; }
- else { hourlyDimMap.set(hourlyDimKey, { hour: hourKey, domain: update.domain || '', ip: update.ip || '', sourceIP: update.sourceIP || '', chain: fullChain, rule: ruleName, upload: update.upload, download: update.download, connections: 1 }); }
+ if (existingHourlyDim) {
+ existingHourlyDim.upload += update.upload;
+ existingHourlyDim.download += update.download;
+ existingHourlyDim.connections += connections;
+ } else {
+ hourlyDimMap.set(hourlyDimKey, {
+ hour: hourKey,
+ domain: update.domain || '',
+ ip: update.ip || '',
+ sourceIP: update.sourceIP || '',
+ chain: fullChain,
+ rule: ruleName,
+ upload: update.upload,
+ download: update.download,
+ connections,
+ });
+ }
// Aggregate domain_proxy_stats
if (update.domain) {
const dpKey = `${update.domain}:${fullChain}`;
const existingDP = domainProxyMap.get(dpKey);
- if (existingDP) { existingDP.upload += update.upload; existingDP.download += update.download; existingDP.count++; }
- else { domainProxyMap.set(dpKey, { domain: update.domain, chain: fullChain, upload: update.upload, download: update.download, count: 1 }); }
+ if (existingDP) {
+ existingDP.upload += update.upload;
+ existingDP.download += update.download;
+ existingDP.count += connections;
+ } else {
+ domainProxyMap.set(dpKey, {
+ domain: update.domain,
+ chain: fullChain,
+ upload: update.upload,
+ download: update.download,
+ count: connections,
+ });
+ }
}
// Aggregate ip_proxy_stats
const ipPKey = `${update.ip}:${fullChain}`;
const existingIPP = ipProxyMap.get(ipPKey);
if (existingIPP) {
- existingIPP.upload += update.upload; existingIPP.download += update.download; existingIPP.count++;
+ existingIPP.upload += update.upload;
+ existingIPP.download += update.download;
+ existingIPP.count += connections;
if (update.domain && update.domain !== 'unknown') existingIPP.domains.add(update.domain);
} else {
const domains = new Set<string>();
if (update.domain && update.domain !== 'unknown') domains.add(update.domain);
- ipProxyMap.set(ipPKey, { ip: update.ip, chain: fullChain, upload: update.upload, download: update.download, count: 1, domains });
+ ipProxyMap.set(ipPKey, {
+ ip: update.ip,
+ chain: fullChain,
+ upload: update.upload,
+ download: update.download,
+ count: connections,
+ domains,
+ });
}
// Aggregate device stats
if (update.sourceIP) {
const sourceIP = update.sourceIP;
const existingDevice = deviceMap.get(sourceIP);
- if (existingDevice) { existingDevice.upload += update.upload; existingDevice.download += update.download; existingDevice.count++; }
- else { deviceMap.set(sourceIP, { sourceIP, upload: update.upload, download: update.download, count: 1 }); }
+ if (existingDevice) {
+ existingDevice.upload += update.upload;
+ existingDevice.download += update.download;
+ existingDevice.count += connections;
+ } else {
+ deviceMap.set(sourceIP, {
+ sourceIP,
+ upload: update.upload,
+ download: update.download,
+ count: connections,
+ });
+ }
if (update.domain) {
const ddKey = `${sourceIP}:${update.domain}`;
const existingDD = deviceDomainMap.get(ddKey);
- if (existingDD) { existingDD.upload += update.upload; existingDD.download += update.download; existingDD.count++; }
- else { deviceDomainMap.set(ddKey, { sourceIP, domain: update.domain, upload: update.upload, download: update.download, count: 1 }); }
+ if (existingDD) {
+ existingDD.upload += update.upload;
+ existingDD.download += update.download;
+ existingDD.count += connections;
+ } else {
+ deviceDomainMap.set(ddKey, {
+ sourceIP,
+ domain: update.domain,
+ upload: update.upload,
+ download: update.download,
+ count: connections,
+ });
+ }
}
if (update.ip) {
const diKey = `${sourceIP}:${update.ip}`;
const existingDI = deviceIPMap.get(diKey);
- if (existingDI) { existingDI.upload += update.upload; existingDI.download += update.download; existingDI.count++; }
- else { deviceIPMap.set(diKey, { sourceIP, ip: update.ip, upload: update.upload, download: update.download, count: 1 }); }
+ if (existingDI) {
+ existingDI.upload += update.upload;
+ existingDI.download += update.download;
+ existingDI.count += connections;
+ } else {
+ deviceIPMap.set(diKey, {
+ sourceIP,
+ ip: update.ip,
+ upload: update.upload,
+ download: update.download,
+ count: connections,
+ });
+ }
}
}
}
diff --git a/apps/collector/src/database/repositories/traffic-writer.test.ts b/apps/collector/src/database/repositories/traffic-writer.test.ts
index 75f41c3..97d9a86 100644
--- a/apps/collector/src/database/repositories/traffic-writer.test.ts
+++ b/apps/collector/src/database/repositories/traffic-writer.test.ts
@@ -142,7 +142,7 @@ describe('TrafficWriterRepository', () => {
it('should correctly aggregate same-domain updates within a batch', () => {
const now = Date.now();
- const updates = Array.from({ length: 5 }, (_, i) => ({
+ const updates = Array.from({ length: 5 }, (_unused, _i) => ({
domain: 'same.com',
ip: '1.1.1.1',
chain: 'ProxyA',
@@ -208,5 +208,44 @@ describe('TrafficWriterRepository', () => {
const total = trend.reduce((sum, t) => sum + t.upload + t.download, 0);
expect(total).toBe(300);
});
+
+ it('should respect explicit connection deltas for continuous traffic', () => {
+ const now = Date.now();
+ const base = {
+ domain: 'stream.example',
+ ip: '9.9.9.9',
+ chain: 'ProxyA',
+ chains: ['ProxyA', 'Match'],
+ rule: 'Match',
+ rulePayload: '',
+ sourceIP: '192.168.1.30',
+ };
+
+ db.batchUpdateTrafficStats(backendId, [
+ {
+ ...base,
+ upload: 100,
+ download: 200,
+ connections: 1,
+ timestampMs: now,
+ },
+ {
+ ...base,
+ upload: 50,
+ download: 80,
+ connections: 0,
+ timestampMs: now + 1000,
+ },
+ ]);
+
+ const domains = db.getDomainStats(backendId, 10);
+ expect(domains.length).toBe(1);
+ expect(domains[0].totalUpload).toBe(150);
+ expect(domains[0].totalDownload).toBe(280);
+ expect(domains[0].totalConnections).toBe(1);
+
+ const summary = db.getSummary(backendId);
+ expect(summary.totalConnections).toBe(1);
+ });
});
});
diff --git a/apps/collector/src/modules/app/app.ts b/apps/collector/src/modules/app/app.ts
index ab3bad5..fb82e04 100644
--- a/apps/collector/src/modules/app/app.ts
+++ b/apps/collector/src/modules/app/app.ts
@@ -57,6 +57,7 @@ type AgentTrafficUpdatePayload = {
rulePayload?: string;
upload?: number;
download?: number;
+ connections?: number;
sourceIP?: string;
timestampMs?: number;
};
@@ -125,13 +126,11 @@ export async function createApp(options: AppOptions) {
// Keyed by requestId, value is the time it was first seen (ms). TTL: 5 minutes.
const seenRequestIds = new Map<string, number>();
- // Per-backend BatchBuffer for agent mode — mirrors direct mode's 30s batch window so that
- // "connections" is counted as one event per (connection-key, minute) rather than one per
- // 2-second agent report, keeping statistics semantically consistent with direct mode.
+ // Per-backend BatchBuffer for agent mode — mirrors direct mode's 30s batch window and
+ // applies the same deferred flush behavior for sqlite/clickhouse writes.
const agentBatchBuffers = new Map<number, BatchBuffer>();
- // Per-backend set of connection keys seen in the realtime store for the current flush
- // interval. Ensures each connection contributes connections=1 exactly once per flush
- // interval, consistent with direct mode's countedConnectionIds deduplication.
+ // Per-backend legacy fallback dedup set. Only used when an older agent payload
+ // does not provide explicit `connections`.
const agentCountedByBackend = new Map<number, Set<string>>();
// Per-backend flush lock — mirrors direct mode's isFlushing to prevent a slow CH write
// from letting the next timer tick start a second flush before clearTraffic completes.
@@ -464,6 +463,9 @@ export async function createApp(options: AppOptions) {
const timestampMs = Number.isFinite(raw.timestampMs)
? Math.max(0, Math.floor(raw.timestampMs || 0))
: Date.now();
+ const connections = Number.isFinite(raw.connections)
+ ? Math.max(0, Math.floor(raw.connections || 0))
+ : undefined;
return {
domain: String(raw.domain || '').trim().slice(0, 253),
@@ -474,6 +476,7 @@ export async function createApp(options: AppOptions) {
rulePayload: String(raw.rulePayload || '').trim().slice(0, 512),
upload,
download,
+ connections,
sourceIP: String(raw.sourceIP || '').trim().slice(0, 64),
timestampMs,
};
@@ -654,9 +657,9 @@ export async function createApp(options: AppOptions) {
}
>();
- // Get or create per-backend counted-connections set for the current flush interval.
- // Mirrors countedConnectionIds in direct mode: each unique connection key contributes
- // connections=1 exactly once per flush interval regardless of agent report frequency.
+ // Compatibility fallback for older agents that do not send explicit `connections`.
+ // For those payloads only, we deduplicate by a composite key within the current
+ // flush window to avoid counting every 2s report as a new connection.
let agentCounted = agentCountedByBackend.get(backendId);
if (!agentCounted) {
agentCounted = new Set<string>();
@@ -664,24 +667,29 @@ export async function createApp(options: AppOptions) {
}
for (const update of updates) {
- // Connection key matches BatchBuffer's deduplication dimensions (minus minuteKey):
- // domain, ip, full chain, rule, rulePayload, sourceIP.
- const connectionKey = `${update.domain}:${update.ip}:${update.chains.join(' > ')}:${update.rule}:${update.rulePayload}:${update.sourceIP || ''}`;
- const isNewThisFlush = !agentCounted.has(connectionKey);
- agentCounted.add(connectionKey);
+ let connections = Number.isFinite(update.connections)
+ ? Math.max(0, Math.floor(update.connections || 0))
+ : undefined;
+ if (connections === undefined) {
+ // Connection key matches BatchBuffer's deduplication dimensions (minus minuteKey):
+ // domain, ip, full chain, rule, rulePayload, sourceIP.
+ const connectionKey = `${update.domain}:${update.ip}:${update.chains.join(' > ')}:${update.rule}:${update.rulePayload}:${update.sourceIP || ''}`;
+ connections = agentCounted.has(connectionKey) ? 0 : 1;
+ agentCounted.add(connectionKey);
+ }
if (update.ip && update.ip !== '0.0.0.0' && update.ip !== '::') {
const existing = geoBatchByIp.get(update.ip);
if (existing) {
existing.upload += update.upload;
existing.download += update.download;
- if (isNewThisFlush) existing.connections += 1;
+ existing.connections += connections;
existing.timestampMs = Math.max(existing.timestampMs, update.timestampMs || 0);
} else {
geoBatchByIp.set(update.ip, {
upload: update.upload,
download: update.download,
- connections: isNewThisFlush ? 1 : 0,
+ connections,
timestampMs: update.timestampMs || Date.now(),
});
}
@@ -697,6 +705,7 @@ export async function createApp(options: AppOptions) {
rulePayload: update.rulePayload,
upload: update.upload,
download: update.download,
+ connections,
sourceIP: update.sourceIP,
timestampMs: update.timestampMs,
});
@@ -713,7 +722,7 @@ export async function createApp(options: AppOptions) {
upload: update.upload,
download: update.download,
},
- isNewThisFlush ? 1 : 0,
+ connections,
update.timestampMs || Date.now(),
);
}
diff --git a/apps/collector/src/modules/clickhouse/clickhouse.writer.ts b/apps/collector/src/modules/clickhouse/clickhouse.writer.ts
index 3e5b738..a1ca45d 100644
--- a/apps/collector/src/modules/clickhouse/clickhouse.writer.ts
+++ b/apps/collector/src/modules/clickhouse/clickhouse.writer.ts
@@ -97,7 +97,7 @@ export class ClickHouseWriter {
: item.rule,
upload: Math.max(0, Math.floor(item.upload)),
download: Math.max(0, Math.floor(item.download)),
- connections: 1,
+ connections: Math.max(0, Math.floor(item.connections ?? 1)),
}));
// Pre-aggregate by (backend_id, minute) for the lightweight agg table
diff --git a/apps/collector/src/modules/collector/batch-buffer.ts b/apps/collector/src/modules/collector/batch-buffer.ts
index 1d2d52c..c97adb5 100644
--- a/apps/collector/src/modules/collector/batch-buffer.ts
+++ b/apps/collector/src/modules/collector/batch-buffer.ts
@@ -21,6 +21,7 @@ export interface TrafficUpdate {
rulePayload: string;
upload: number;
download: number;
+ connections?: number;
sourceIP?: string;
timestampMs?: number;
}
@@ -38,6 +39,12 @@ export interface GeoIPResult {
timestampMs?: number;
}
+function normalizeConnections(value: number | undefined): number {
+ const safe =
+ typeof value === "number" && Number.isFinite(value) ? value : 1;
+ return Math.max(0, Math.floor(safe));
+}
+
export function toMinuteKey(timestampMs?: number): string {
const date = new Date(timestampMs ?? Date.now()).toISOString();
return `${date.slice(0, 16)}:00`;
@@ -78,15 +85,18 @@ export class BatchBuffer {
update.sourceIP || "",
].join(":");
const existing = this.buffer.get(key);
+ const connections = normalizeConnections(update.connections);
if (existing) {
existing.upload += update.upload;
existing.download += update.download;
+ existing.connections =
+ normalizeConnections(existing.connections) + connections;
if ((update.timestampMs ?? 0) > (existing.timestampMs ?? 0)) {
existing.timestampMs = update.timestampMs;
}
} else {
- this.buffer.set(key, { ...update });
+ this.buffer.set(key, { ...update, connections });
}
}
diff --git a/apps/collector/src/modules/collector/gateway.collector.ts b/apps/collector/src/modules/collector/gateway.collector.ts
index 2075246..b741b6e 100644
--- a/apps/collector/src/modules/collector/gateway.collector.ts
+++ b/apps/collector/src/modules/collector/gateway.collector.ts
@@ -129,6 +129,7 @@ interface TrackedConnection {
lastDownload: number;
totalUpload: number;
totalDownload: number;
+ counted: boolean;
sourceIP?: string;
lastSeen: number;
}
@@ -144,10 +145,6 @@ export function createCollector(
const id = backendId || 0;
const activeConnections = new Map<string, TrackedConnection>();
const batchBuffer = new BatchBuffer();
- // Track which connection IDs have been counted in the realtime store for the
- // current flush interval. Each connection contributes connections=1 exactly once
- // per flush interval, matching the BatchBuffer's per-minute deduplication semantics.
- const countedConnectionIds = new Set<string>();
let lastBroadcastTime = 0;
const broadcastThrottleMs = 500;
let flushInterval: NodeJS.Timeout | null = null;
@@ -209,15 +206,12 @@ export function createCollector(
if (stats.hasTrafficUpdates && stats.trafficOk) {
if (trafficDetailOk && trafficAggOk) {
realtimeStore.clearTraffic(id);
- countedConnectionIds.clear();
} else if (trafficDetailOk && !trafficAggOk) {
// Detail committed, agg failed: clear detail-side realtime only.
realtimeStore.clearTrafficDimensions(id);
- countedConnectionIds.clear();
} else if (!trafficDetailOk && trafficAggOk) {
// Agg committed, detail failed: clear summary-side realtime only.
realtimeStore.clearTrafficSummary(id);
- countedConnectionIds.clear();
}
}
@@ -323,6 +317,7 @@ export function createCollector(
if (!existing) {
// New connection - track it and record initial traffic
+ const hasInitialTraffic = conn.upload > 0 || conn.download > 0;
activeConnections.set(conn.id, {
id: conn.id,
domain,
@@ -334,12 +329,14 @@ export function createCollector(
lastDownload: conn.download,
totalUpload: conn.upload,
totalDownload: conn.download,
+ counted: hasInitialTraffic,
sourceIP,
lastSeen: now,
});
// Record initial traffic for new connection (add to batch buffer)
- if (conn.upload > 0 || conn.download > 0) {
+ if (hasInitialTraffic) {
+ const connections = 1;
batchBuffer.add(id, {
domain,
ip,
@@ -349,11 +346,10 @@ export function createCollector(
rulePayload,
upload: conn.upload,
download: conn.download,
+ connections,
sourceIP,
timestampMs: now,
});
- const isNewThisFlush = !countedConnectionIds.has(conn.id);
- countedConnectionIds.add(conn.id);
realtimeStore.recordTraffic(
id,
{
@@ -366,7 +362,7 @@ export function createCollector(
upload: conn.upload,
download: conn.download,
},
- isNewThisFlush ? 1 : 0,
+ connections,
now
);
@@ -379,7 +375,7 @@ export function createCollector(
};
existingGeo.upload += conn.upload;
existingGeo.download += conn.download;
- if (isNewThisFlush) existingGeo.connections += 1;
+ existingGeo.connections += connections;
geoBatchByIp.set(ip, existingGeo);
}
@@ -394,6 +390,10 @@ export function createCollector(
);
if (uploadDelta > 0 || downloadDelta > 0) {
+ const connections = existing.counted ? 0 : 1;
+ if (connections > 0) {
+ existing.counted = true;
+ }
// Update accumulated traffic for this connection
existing.totalUpload += uploadDelta;
existing.totalDownload += downloadDelta;
@@ -408,11 +408,10 @@ export function createCollector(
rulePayload: existing.rulePayload || "",
upload: uploadDelta,
download: downloadDelta,
+ connections,
sourceIP: existing.sourceIP,
timestampMs: now,
});
- const isNewThisFlush = !countedConnectionIds.has(conn.id);
- countedConnectionIds.add(conn.id);
realtimeStore.recordTraffic(
id,
{
@@ -425,7 +424,7 @@ export function createCollector(
upload: uploadDelta,
download: downloadDelta,
},
- isNewThisFlush ? 1 : 0,
+ connections,
now
);
@@ -438,7 +437,7 @@ export function createCollector(
};
existingGeo.upload += uploadDelta;
existingGeo.download += downloadDelta;
- if (isNewThisFlush) existingGeo.connections += 1;
+ existingGeo.connections += connections;
geoBatchByIp.set(existing.ip, existingGeo);
}
@@ -536,7 +535,6 @@ export function createCollector(
// Keep active connection baselines to avoid replaying historical cumulative
// counters after a DB/log wipe. Only clear pending in-memory deltas.
batchBuffer.clear();
- countedConnectionIds.clear();
};
return collectorWithReset;
diff --git a/apps/collector/src/modules/collector/surge.collector.ts b/apps/collector/src/modules/collector/surge.collector.ts
index 81672fb..34e875a 100644
--- a/apps/collector/src/modules/collector/surge.collector.ts
+++ b/apps/collector/src/modules/collector/surge.collector.ts
@@ -172,6 +172,7 @@ interface TrackedRequest {
completed: boolean;
disconnected: boolean;
lastStatus?: string;
+ counted: boolean;
// Track if initial values have been processed
initialProcessed: boolean;
}
@@ -248,9 +249,6 @@ export function createSurgeCollector(
const id = backendId || 0;
const activeRequests = new Map<string, TrackedRequest>();
const batchBuffer = new BatchBuffer();
- // Track which request IDs have been counted in the realtime store for the current
- // flush interval — same deduplication as gateway direct mode's countedConnectionIds.
- const countedConnectionIds = new Set<string>();
// Track recently completed requests to prevent double counting
// Key: request ID, Value: completion timestamp
@@ -330,13 +328,10 @@ export function createSurgeCollector(
if (stats.hasTrafficUpdates && stats.trafficOk) {
if (trafficDetailOk && trafficAggOk) {
realtimeStore.clearTraffic(id);
- countedConnectionIds.clear();
} else if (trafficDetailOk && !trafficAggOk) {
realtimeStore.clearTrafficDimensions(id);
- countedConnectionIds.clear();
} else if (!trafficDetailOk && trafficAggOk) {
realtimeStore.clearTrafficSummary(id);
- countedConnectionIds.clear();
}
}
@@ -507,6 +502,7 @@ export function createSurgeCollector(
// IMPORTANT: We now record initial traffic immediately to prevent data loss
// for short-lived connections that disappear before the next poll.
// The recentlyCompleted map prevents double counting if the same request reappears.
+ const hasInitialTraffic = currentUpload > 0 || currentDownload > 0;
activeRequests.set(req.id, {
id: req.id,
domain,
@@ -524,6 +520,7 @@ export function createSurgeCollector(
completed: isCompleted,
disconnected: isDisconnected,
lastStatus: req.status,
+ counted: hasInitialTraffic,
initialProcessed: true, // Mark as processed
});
@@ -534,7 +531,8 @@ export function createSurgeCollector(
}
// Record initial traffic if non-zero
- if (currentUpload > 0 || currentDownload > 0) {
+ if (hasInitialTraffic) {
+ const connections = 1;
batchBuffer.add(id, {
domain,
ip,
@@ -544,11 +542,10 @@ export function createSurgeCollector(
rulePayload: rulePayload || "",
upload: currentUpload,
download: currentDownload,
+ connections,
sourceIP,
timestampMs: req.time || now,
});
- const isNewThisFlush = !countedConnectionIds.has(req.id);
- countedConnectionIds.add(req.id);
realtimeStore.recordTraffic(
id,
{
@@ -561,7 +558,7 @@ export function createSurgeCollector(
upload: currentUpload,
download: currentDownload,
},
- isNewThisFlush ? 1 : 0,
+ connections,
now
);
@@ -574,7 +571,7 @@ export function createSurgeCollector(
};
existingGeo.upload += currentUpload;
existingGeo.download += currentDownload;
- if (isNewThisFlush) existingGeo.connections += 1;
+ existingGeo.connections += connections;
geoBatchByIp.set(ip, existingGeo);
}
@@ -590,6 +587,7 @@ export function createSurgeCollector(
// Counter was reset - treat current value as new traffic
uploadDelta = currentUpload;
downloadDelta = currentDownload;
+ existing.counted = false;
if (DEBUG_SURGE) {
console.log(`[SurgeCollector:${id}] Counter reset detected: ${req.id}`);
}
@@ -620,6 +618,10 @@ export function createSurgeCollector(
// Only record if there's actual new traffic
if (uploadDelta > 0 || downloadDelta > 0) {
+ const connections = existing.counted ? 0 : 1;
+ if (connections > 0) {
+ existing.counted = true;
+ }
existing.totalUpload += uploadDelta;
existing.totalDownload += downloadDelta;
@@ -632,11 +634,10 @@ export function createSurgeCollector(
rulePayload: existing.rulePayload || "",
upload: uploadDelta,
download: downloadDelta,
+ connections,
sourceIP: existing.sourceIP,
timestampMs: req.time || now,
});
- const isNewThisFlush = !countedConnectionIds.has(req.id);
- countedConnectionIds.add(req.id);
realtimeStore.recordTraffic(
id,
{
@@ -649,7 +650,7 @@ export function createSurgeCollector(
upload: uploadDelta,
download: downloadDelta,
},
- isNewThisFlush ? 1 : 0,
+ connections,
now
);
@@ -661,7 +662,7 @@ export function createSurgeCollector(
};
existingGeo.upload += uploadDelta;
existingGeo.download += downloadDelta;
- if (isNewThisFlush) existingGeo.connections += 1;
+ existingGeo.connections += connections;
geoBatchByIp.set(existing.ip, existingGeo);
}
@@ -802,7 +803,6 @@ export function createSurgeCollector(
// Keep active request baselines to avoid replaying historical cumulative
// counters after a DB/log wipe. Only clear pending in-memory deltas.
batchBuffer.clear();
- countedConnectionIds.clear();
};
return collectorWithReset;
diff --git a/apps/collector/src/modules/db/db.ts b/apps/collector/src/modules/db/db.ts
index 28e6d0c..412caf3 100644
--- a/apps/collector/src/modules/db/db.ts
+++ b/apps/collector/src/modules/db/db.ts
@@ -29,6 +29,7 @@ export interface TrafficUpdate {
rulePayload: string;
upload: number;
download: number;
+ connections?: number;
sourceIP?: string;
timestampMs?: number;
}
diff --git a/docs/agent/install.en.md b/docs/agent/install.en.md
index 200637b..90ac2d3 100644
--- a/docs/agent/install.en.md
+++ b/docs/agent/install.en.md
@@ -46,7 +46,8 @@ After install, manage agent with:
nekoagent status <instance>
nekoagent logs <instance>
nekoagent restart <instance>
-nekoagent update <instance> agent-vX.Y.Z
+nekoagent upgrade
+nekoagent upgrade agent-vX.Y.Z
nekoagent remove <instance>
```
@@ -85,7 +86,7 @@ Common mapping:
The install script places two binaries into `NEKO_INSTALL_DIR` (default `~/.local/bin`):
- `neko-agent` — the data collection daemon (runs continuously, reports to panel)
-- `nekoagent` — the CLI manager for lifecycle operations (start / stop / update / remove)
+- `nekoagent` — the CLI manager for lifecycle operations (start / stop / upgrade / remove)
The `nekoagent` manager stores:
diff --git a/docs/agent/install.md b/docs/agent/install.md
index e1e4d82..4ae7986 100644
--- a/docs/agent/install.md
+++ b/docs/agent/install.md
@@ -46,7 +46,8 @@ curl -fsSL https://raw.githubusercontent.com/foru17/neko-master/main/apps/agent/
nekoagent status <instance>
nekoagent logs <instance>
nekoagent restart <instance>
-nekoagent update <instance> agent-vX.Y.Z
+nekoagent upgrade
+nekoagent upgrade agent-vX.Y.Z
nekoagent remove <instance>
```
@@ -68,7 +69,7 @@ nekoagent uninstall
安装脚本在 `NEKO_INSTALL_DIR`(默认 `~/.local/bin`)中放置两个二进制文件:
- `neko-agent` — 数据采集守护进程(持续运行,向面板上报数据)
-- `nekoagent` — CLI 管理器(Shell 脚本,管理实例生命周期:start / stop / update / remove)
+- `nekoagent` — CLI 管理器(Shell 脚本,管理实例生命周期:start / stop / upgrade / remove)
`nekoagent` 管理器的存储位置:
diff --git a/docs/agent/quick-start.en.md b/docs/agent/quick-start.en.md
index 62ec1b2..499bc0e 100644
--- a/docs/agent/quick-start.en.md
+++ b/docs/agent/quick-start.en.md
@@ -58,7 +58,7 @@ nekoagent status <instance> # check running state
nekoagent logs <instance> # tail live logs
nekoagent restart <instance> # restart the process
nekoagent stop <instance> # graceful stop (up to ~12s for final flush)
-nekoagent update <instance> # update to latest version
+nekoagent upgrade # global upgrade (CLI + binary)
nekoagent remove <instance> # stop + delete config
```
diff --git a/docs/agent/quick-start.md b/docs/agent/quick-start.md
index 2a0625d..e3335cf 100644
--- a/docs/agent/quick-start.md
+++ b/docs/agent/quick-start.md
@@ -57,7 +57,7 @@ nekoagent status <instance> # 查看运行状态
nekoagent logs <instance> # 实时查看日志
nekoagent restart <instance> # 重启进程
nekoagent stop <instance> # 优雅停止(最多等待约 12 秒完成最终 flush)
-nekoagent update <instance> # 更新到最新版本
+nekoagent upgrade # 全局升级(CLI + 二进制)
nekoagent remove <instance> # 停止并删除配置
```