Skip to content

feat(metrics): opt-in Prometheus /metrics on the loopback fleet server - #62

Merged
GeiserX merged 1 commit into
mainfrom
feat/prometheus-metrics
Jul 9, 2026
Merged

GeiserX merged 1 commit into
mainfrom
feat/prometheus-metrics

Conversation

@GeiserX

@GeiserX GeiserX commented Jul 9, 2026 •

Copy link
Copy Markdown
Owner

What

Adds an opt-in Prometheus /metrics endpoint on the existing loopback fleet server, so a homelab Prometheus/Grafana can scrape the app. The production CashPilot has this; the rewrite didn't. (Gap analysis.)

  • Gauges (cashpilot_ prefix, mirroring the original): cashpilot_up, cashpilot_collect_interval_minutes, cashpilot_earnings_usd_total/_today/_month, cashpilot_service_balance{platform,currency} (+ cashpilot_service_error{platform} for a latest-error platform, no bogus balance), cashpilot_service_health_score{slug}, cashpilot_service_uptime_percent{slug}, cashpilot_fleet_devices{status}, cashpilot_fleet_device_last_seen_seconds{device}.
  • No new dependency — hand-rolled text exposition (escaped labels, text/plain; version=0.0.4).
  • Reuses computeEarningsSummary — the FX/accrual logic is not duplicated.
  • Opt-in + gated: new MetricsEnabled config flag (default false); the route is only registered when enabled → 404 otherwise. Unauthenticated by Prometheus convention, on the loopback-default bind.

Tests

Handler output (metric lines, content-type, error-row handling, label escaping, nil-store safety, non-GET rejection) + the mux gating (404 disabled / 200 enabled) + config default. Verified on macOS: go build/vet/test -race ./... all green.

Summary by CodeRabbit

  • New Features

    • Added an optional Prometheus-compatible /metrics endpoint on the fleet server.
    • Included live status, collection interval, earnings, balance, service health, uptime, fleet device counts, and device staleness metrics.
    • Kept core fleet health routes available, with metrics exposure controlled by configuration.
  • Bug Fixes

    • Improved metrics output handling for non-GET requests and missing data.
    • Ensured metric labels are safely escaped and output stays consistent.

Exposes earnings (per-platform balance + USD total/today/month), per-service
health score + uptime%, and fleet online/offline counts as Prometheus gauges for
a homelab Grafana. Hand-rolled text exposition (no new dependency); reuses
computeEarningsSummary so the FX logic is not duplicated. Gated by a new
MetricsEnabled config flag (default false); the /metrics route is only registered
when enabled (404 otherwise). Unauthenticated by Prometheus convention, on the
loopback-default fleet bind.
@codecov

codecov Bot commented Jul 9, 2026

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 94.00000% with 6 lines in your changes missing coverage. Please review.
✅ Project coverage is 66.38%. Comparing base (1d48731) to head (bcfcad1).

Files with missing lines Patch % Lines
metrics.go 93.47% 3 Missing and 3 partials ⚠️
Additional details and impacted files

Impacted file tree graph

@@            Coverage Diff             @@
##             main      #62      +/-   ##
==========================================
+ Coverage   65.05%   66.38%   +1.32%     
==========================================
  Files           8        9       +1     
  Lines        2012     2109      +97     
==========================================
+ Hits         1309     1400      +91     
- Misses        611      614       +3     
- Partials       92       95       +3     
Files with missing lines Coverage Δ
fleet_server.go 78.57% <100.00%> (+0.88%) ⬆️
internal/config/config.go 67.59% <ø> (ø)
metrics.go 93.47% <93.47%> (ø)
🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

@coderabbitai

coderabbitai Bot commented Jul 9, 2026 •

Copy link
Copy Markdown

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: 832b4681-d344-42bd-b9f0-90bfd4e2d6ab

📥 Commits

Reviewing files that changed from the base of the PR and between 1d48731 and bcfcad1.

📒 Files selected for processing (5)
  • fleet_server.go
  • internal/config/config.go
  • internal/config/config_test.go
  • metrics.go
  • metrics_test.go

📝 Walkthrough

Walkthrough

Adds an opt-in Prometheus /metrics HTTP endpoint gated by a new MetricsEnabled config field. Fleet server route registration is refactored into a fleetMux helper. A new metrics.go renders liveness, earnings, and store-backed gauges in Prometheus text format, with accompanying tests.

Changes

Prometheus metrics endpoint

Layer / File(s) Summary
MetricsEnabled config flag
internal/config/config.go, internal/config/config_test.go
Documents the opt-in MetricsEnabled field and adds a test verifying its default false value and persistence across reload.
Fleet mux route gating
fleet_server.go
Extracts route registration into a new fleetMux(metricsEnabled bool) helper; always registers health/heartbeat routes, conditionally registers /metrics.
Metrics handler and rendering
metrics.go
Adds handleMetrics GET-only HTTP handler, renderMetrics/renderStoreMetrics building Prometheus gauge families (liveness, earnings, balances, error flags, health score, uptime, fleet counts, staleness), plus metricsWriter, label escaping, float formatting, and sortedKeys helpers.
Metrics endpoint tests
metrics_test.go
Adds tests covering full metrics scraping/escaping, 405 on non-GET, nil-store safety, and fleet mux route gating.

Estimated code review effort: 3 (Moderate) | ~25 minutes

Possibly related PRs

  • GeiserX/CashPilot-Desktop#29: Both PRs modify fleet_server.go's startFleetAPI routing, with this PR building on prior Fleet server endpoint/routing setup.
🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 63.64% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title accurately summarizes the main change: an opt-in Prometheus /metrics endpoint on the loopback fleet server.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch feat/prometheus-metrics

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@GeiserX
GeiserX merged commit b34314e into main Jul 9, 2026
5 checks passed
@GeiserX
GeiserX deleted the feat/prometheus-metrics branch July 9, 2026 09:15
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant