diff --git a/README.md b/README.md index 64fc0c4..f562048 100644 --- a/README.md +++ b/README.md @@ -101,6 +101,27 @@ histogram_quantile(0.95, sum by (le, runner_label) (rate(github_job_queue_second sum by (conclusion) (increase(github_workflow_runs_total[1d])) ``` +## Adoption stats + +Optional, off unless `ADOPTION_REPOS` is set (comma-separated repo names in +`GITHUB_ORG`). Polled on its own `ADOPTION_CACHE_TTL` (default 1h), since +none of it moves fast. Everything is public GitHub data or your own repo +traffic; nothing is collected from the tracked project's users. + +| Metric | Labels | Meaning | +| --- | --- | --- | +| `github_adoption_up` | | 1 if the last poll succeeded, 0 if stale | +| `github_repo_stars`, `_forks`, `_watchers`, `_open_issues` | `repo` | Counts; open issues exclude PRs | +| `github_release_asset_downloads` | `repo`, `tag`, `asset` | Cumulative `download_count` per release asset (drafts skipped). Chart with `increase()` | +| `github_repo_traffic_ok` | `repo` | 0 if the token lacks push access, so the traffic metrics below are absent | +| `github_repo_traffic_views_daily`, `_view_uniques_daily`, `_clones_daily`, `_clone_uniques_daily` | `repo`, `date` | One series per UTC day; today's is partial | +| `github_repo_traffic_referrer_views`, `_referrer_uniques` | `repo`, `referrer` | Top 10 referrers, last 14 days | +| `github_repo_traffic_path_views`, `_path_uniques` | `repo`, `path` | Top 10 content paths, last 14 days | + +GitHub keeps traffic for only 14 days, so the exporter must keep running to +build history; Prometheus is the store. Not covered: container (ghcr.io) pull +counts, which no GitHub API exposes. + ## Rate limit The budget comes from the `X-RateLimit-*` headers of the exporter's own API @@ -124,6 +145,9 @@ window it sees and alerts on the lowest. | `RUNNER_CACHE_MAX_STALE` | `5m` | | | `ORG_CACHE_TTL` | `5m` | | | `ORG_CACHE_MAX_STALE` | `30m` | | +| `ADOPTION_REPOS` | | no; enables [adoption stats](#adoption-stats) | +| `ADOPTION_CACHE_TTL` | `1h` | | +| `ADOPTION_CACHE_MAX_STALE` | `3h` | | ## Token permissions @@ -132,6 +156,8 @@ A fine-grained PAT needs: - Repository permissions: **Metadata** (read, auto-included), **Pull requests** (read), **Actions** (read), **Dependabot alerts** (read). - Organization permissions: whatever GitHub's console offers for self-hosted runners (its REST API docs only document `admin:org` for the classic-PAT path to that endpoint — narrower fine-grained scoping isn't guaranteed available for every org plan). +Adoption traffic (`ADOPTION_REPOS`) additionally needs **Administration** (read) on those repos, which is what GitHub's traffic endpoints require beyond push access. Stars, forks and release downloads need nothing extra. Without it, traffic metrics are simply absent (`github_repo_traffic_ok` = 0). + ## Build / test / run ```bash diff --git a/internal/adoption/adoption.go b/internal/adoption/adoption.go new file mode 100644 index 0000000..17ab189 --- /dev/null +++ b/internal/adoption/adoption.go @@ -0,0 +1,117 @@ +// Package adoption gathers public adoption stats (stars, release downloads) +// and repo traffic for a short list of repos, on a slow TTL. Traffic is a +// rolling 14-day window on GitHub's side, so Prometheus keeps the history. +package adoption + +import ( + "context" + "time" + + "github.com/drumandbytes/github-actions-runner-exporter/internal/github" +) + +type AssetDownloads struct { + Tag string + Asset string + Count int64 +} + +type Day struct { + Date string // YYYY-MM-DD, UTC + Count int + Uniques int +} + +type Hits struct { + Name string // referrer host or content path + Count int + Uniques int +} + +type RepoStats struct { + Name string + + Stars, Forks, Watchers, OpenIssues int + + Downloads []AssetDownloads + + // Traffic* are empty and TrafficOK is false when the token lacks push access. + TrafficOK bool + Views []Day + Clones []Day + Referrers []Hits + Paths []Hits +} + +type Summary struct { + GeneratedAt time.Time + Repos []RepoStats +} + +// Client is the subset of *github.Client this package calls; tests fake it. +type Client interface { + RepoInfo(ctx context.Context, repo string) (github.RepoInfo, error) + OpenPRCount(ctx context.Context, repo string) (int, error) + Releases(ctx context.Context, repo string) ([]github.Release, error) + TrafficViews(ctx context.Context, repo string) ([]github.TrafficDay, error) + TrafficClones(ctx context.Context, repo string) ([]github.TrafficDay, error) + TrafficReferrers(ctx context.Context, repo string) ([]github.Referrer, error) + TrafficPaths(ctx context.Context, repo string) ([]github.PopularPath, error) +} + +// Build fails only when a repo's basic info or releases can't be read; a +// missing traffic permission just leaves TrafficOK false. +func Build(ctx context.Context, client Client, repos []string) (Summary, error) { + s := Summary{GeneratedAt: time.Now()} + for _, name := range repos { + info, err := client.RepoInfo(ctx, name) + if err != nil { + return Summary{}, err + } + releases, err := client.Releases(ctx, name) + if err != nil { + return Summary{}, err + } + + r := RepoStats{ + Name: name, Stars: info.Stars, Forks: info.Forks, Watchers: info.Watchers, + OpenIssues: info.OpenIssuesAndPRs, + } + if prs, err := client.OpenPRCount(ctx, name); err == nil { + r.OpenIssues -= prs + } + for _, rel := range releases { + if rel.Draft { + continue + } + for _, a := range rel.Assets { + r.Downloads = append(r.Downloads, AssetDownloads{Tag: rel.TagName, Asset: a.Name, Count: a.DownloadCount}) + } + } + + views, vErr := client.TrafficViews(ctx, name) + clones, cErr := client.TrafficClones(ctx, name) + refs, rErr := client.TrafficReferrers(ctx, name) + paths, pErr := client.TrafficPaths(ctx, name) + if vErr == nil && cErr == nil && rErr == nil && pErr == nil { + r.TrafficOK = true + r.Views, r.Clones = days(views), days(clones) + for _, x := range refs { + r.Referrers = append(r.Referrers, Hits{x.Referrer, x.Count, x.Uniques}) + } + for _, x := range paths { + r.Paths = append(r.Paths, Hits{x.Path, x.Count, x.Uniques}) + } + } + s.Repos = append(s.Repos, r) + } + return s, nil +} + +func days(in []github.TrafficDay) []Day { + out := make([]Day, 0, len(in)) + for _, d := range in { + out = append(out, Day{d.Timestamp.UTC().Format("2006-01-02"), d.Count, d.Uniques}) + } + return out +} diff --git a/internal/adoption/adoption_test.go b/internal/adoption/adoption_test.go new file mode 100644 index 0000000..4968f1a --- /dev/null +++ b/internal/adoption/adoption_test.go @@ -0,0 +1,58 @@ +package adoption + +import ( + "context" + "errors" + "testing" + "time" + + "github.com/drumandbytes/github-actions-runner-exporter/internal/github" +) + +type fake struct{ trafficErr error } + +func (fake) RepoInfo(context.Context, string) (github.RepoInfo, error) { + return github.RepoInfo{Stars: 5, Forks: 1, Watchers: 2, OpenIssuesAndPRs: 4}, nil +} +func (fake) OpenPRCount(context.Context, string) (int, error) { return 3, nil } +func (fake) Releases(context.Context, string) ([]github.Release, error) { + return []github.Release{ + {TagName: "v1", Assets: []github.ReleaseAsset{{Name: "a.tgz", DownloadCount: 7}}}, + {TagName: "v2", Draft: true, Assets: []github.ReleaseAsset{{Name: "b.tgz", DownloadCount: 1}}}, + }, nil +} +func (f fake) TrafficViews(context.Context, string) ([]github.TrafficDay, error) { + return []github.TrafficDay{{Timestamp: time.Date(2026, 11, 13, 0, 0, 0, 0, time.UTC), Count: 9, Uniques: 4}}, f.trafficErr +} +func (fake) TrafficClones(context.Context, string) ([]github.TrafficDay, error) { return nil, nil } +func (fake) TrafficReferrers(context.Context, string) ([]github.Referrer, error) { + return []github.Referrer{{Referrer: "google.com", Count: 3, Uniques: 2}}, nil +} +func (fake) TrafficPaths(context.Context, string) ([]github.PopularPath, error) { return nil, nil } + +func TestBuild(t *testing.T) { + s, err := Build(context.Background(), fake{}, []string{"delistd"}) + if err != nil { + t.Fatal(err) + } + r := s.Repos[0] + if r.OpenIssues != 1 || r.Stars != 5 { + t.Fatalf("stats = %+v", r) + } + if len(r.Downloads) != 1 || r.Downloads[0].Tag != "v1" { + t.Fatalf("drafts must be skipped: %+v", r.Downloads) + } + if !r.TrafficOK || r.Views[0].Date != "2026-11-13" || r.Referrers[0].Name != "google.com" { + t.Fatalf("traffic = %+v", r) + } +} + +func TestBuildTrafficForbidden(t *testing.T) { + s, err := Build(context.Background(), fake{trafficErr: errors.New("HTTP 403")}, []string{"delistd"}) + if err != nil { + t.Fatal(err) + } + if s.Repos[0].TrafficOK || s.Repos[0].Stars != 5 { + t.Fatalf("%+v", s.Repos[0]) + } +} diff --git a/internal/collector/adoption.go b/internal/collector/adoption.go new file mode 100644 index 0000000..dbf5178 --- /dev/null +++ b/internal/collector/adoption.go @@ -0,0 +1,107 @@ +package collector + +import ( + "fmt" + "time" + + "github.com/prometheus/client_golang/prometheus" + + "github.com/drumandbytes/github-actions-runner-exporter/internal/adoption" + "github.com/drumandbytes/github-actions-runner-exporter/internal/fetch" +) + +// Adoption exposes the adoption.Summary; registered only when ADOPTION_REPOS is set. +type Adoption struct { + fetcher *fetch.Fetcher[adoption.Summary] + + up, stars, forks, watchers, openIssues, downloads *prometheus.Desc + trafficOK *prometheus.Desc + viewsDaily, viewsUniquesDaily *prometheus.Desc + clonesDaily, clonesUniquesDaily *prometheus.Desc + refViews, refUniques, pathViews, pathUniques *prometheus.Desc +} + +func NewAdoption(f *fetch.Fetcher[adoption.Summary], ttl time.Duration) *Adoption { + note := fmt.Sprintf(" Polled every %s.", ttl) + d := func(subsystem, name, help string, labels ...string) *prometheus.Desc { + return prometheus.NewDesc(prometheus.BuildFQName(namespace, subsystem, name), help+note, labels, nil) + } + const window = " Rolling 14-day window on GitHub's side; the series persist in Prometheus after it rolls off." + return &Adoption{ + fetcher: f, + up: d("adoption", "up", "Whether the last adoption poll succeeded (1) or a stale cache is being served (0)."), + + stars: d("repo", "stars", "Stargazers.", "repo"), + forks: d("repo", "forks", "Forks.", "repo"), + watchers: d("repo", "watchers", "Watchers (subscribers).", "repo"), + openIssues: d("repo", "open_issues", "Open issues, excluding pull requests.", "repo"), + downloads: d("release", "asset_downloads", "Cumulative download count of a release asset. Chart with increase(), not raw.", + "repo", "tag", "asset"), + + trafficOK: d("repo", "traffic_ok", "Whether the traffic API answered (1) or the token lacks push access (0).", "repo"), + viewsDaily: d("repo", "traffic_views_daily", "Page views for one UTC day. Today's date is partial."+window, + "repo", "date"), + viewsUniquesDaily: d("repo", "traffic_view_uniques_daily", "Unique visitors for one UTC day."+window, "repo", "date"), + clonesDaily: d("repo", "traffic_clones_daily", "Git clones for one UTC day."+window, "repo", "date"), + clonesUniquesDaily: d("repo", "traffic_clone_uniques_daily", "Unique cloners for one UTC day."+window, + "repo", "date"), + refViews: d("repo", "traffic_referrer_views", "Views from a top-10 referrer."+window, "repo", "referrer"), + refUniques: d("repo", "traffic_referrer_uniques", "Unique visitors from a top-10 referrer."+window, "repo", "referrer"), + pathViews: d("repo", "traffic_path_views", "Views of a top-10 content path."+window, "repo", "path"), + pathUniques: d("repo", "traffic_path_uniques", "Unique visitors of a top-10 content path."+window, "repo", "path"), + } +} + +func (a *Adoption) Describe(ch chan<- *prometheus.Desc) { + for _, d := range []*prometheus.Desc{ + a.up, a.stars, a.forks, a.watchers, a.openIssues, a.downloads, a.trafficOK, + a.viewsDaily, a.viewsUniquesDaily, a.clonesDaily, a.clonesUniquesDaily, + a.refViews, a.refUniques, a.pathViews, a.pathUniques, + } { + ch <- d + } +} + +func (a *Adoption) Collect(ch chan<- prometheus.Metric) { + s, err := a.fetcher.Get() + if err != nil { + ch <- prometheus.MustNewConstMetric(a.up, prometheus.GaugeValue, 0) + return + } + ch <- prometheus.MustNewConstMetric(a.up, prometheus.GaugeValue, 1) + + g := func(d *prometheus.Desc, v float64, l ...string) { + ch <- prometheus.MustNewConstMetric(d, prometheus.GaugeValue, v, l...) + } + for _, r := range s.Repos { + g(a.stars, float64(r.Stars), r.Name) + g(a.forks, float64(r.Forks), r.Name) + g(a.watchers, float64(r.Watchers), r.Name) + g(a.openIssues, float64(r.OpenIssues), r.Name) + for _, x := range r.Downloads { + g(a.downloads, float64(x.Count), r.Name, x.Tag, x.Asset) + } + + if !r.TrafficOK { + g(a.trafficOK, 0, r.Name) + continue + } + g(a.trafficOK, 1, r.Name) + for _, x := range r.Views { + g(a.viewsDaily, float64(x.Count), r.Name, x.Date) + g(a.viewsUniquesDaily, float64(x.Uniques), r.Name, x.Date) + } + for _, x := range r.Clones { + g(a.clonesDaily, float64(x.Count), r.Name, x.Date) + g(a.clonesUniquesDaily, float64(x.Uniques), r.Name, x.Date) + } + for _, x := range r.Referrers { + g(a.refViews, float64(x.Count), r.Name, x.Name) + g(a.refUniques, float64(x.Uniques), r.Name, x.Name) + } + for _, x := range r.Paths { + g(a.pathViews, float64(x.Count), r.Name, x.Name) + g(a.pathUniques, float64(x.Uniques), r.Name, x.Name) + } + } +} diff --git a/internal/config/config.go b/internal/config/config.go index 048f771..a7db059 100644 --- a/internal/config/config.go +++ b/internal/config/config.go @@ -4,6 +4,7 @@ package config import ( "fmt" "os" + "strings" "time" ) @@ -20,6 +21,11 @@ type Config struct { // ~4 API calls per repo per refresh: long interval to stay inside the rate limit OrgCacheTTL time.Duration OrgCacheMaxStale time.Duration + + // repos (names within GITHUB_ORG) to track adoption for; empty disables it + AdoptionRepos []string + AdoptionCacheTTL time.Duration + AdoptionCacheMaxStale time.Duration } func FromEnv() (Config, error) { @@ -34,6 +40,10 @@ func FromEnv() (Config, error) { OrgCacheTTL: envDuration("ORG_CACHE_TTL", 5*time.Minute), OrgCacheMaxStale: envDuration("ORG_CACHE_MAX_STALE", 30*time.Minute), + + AdoptionRepos: splitList(os.Getenv("ADOPTION_REPOS")), + AdoptionCacheTTL: envDuration("ADOPTION_CACHE_TTL", time.Hour), + AdoptionCacheMaxStale: envDuration("ADOPTION_CACHE_MAX_STALE", 3*time.Hour), } if c.GitHubOrg == "" { @@ -63,3 +73,13 @@ func envDuration(key string, def time.Duration) time.Duration { } return d } + +func splitList(v string) []string { + var out []string + for _, p := range strings.Split(v, ",") { + if p = strings.TrimSpace(p); p != "" { + out = append(out, p) + } + } + return out +} diff --git a/internal/github/client.go b/internal/github/client.go index 1f6f57c..0749fe3 100644 --- a/internal/github/client.go +++ b/internal/github/client.go @@ -240,3 +240,54 @@ func (c *Client) RateLimits() map[time.Time]RateLimit { } return out } + +// RepoInfo returns stars, forks, watchers and the open issue+PR count. +func (c *Client) RepoInfo(ctx context.Context, repo string) (RepoInfo, error) { + var out RepoInfo + err := c.get(ctx, fmt.Sprintf("%s/repos/%s/%s", c.baseURL, c.org, repo), &out) + return out, err +} + +// Releases returns a repo's published releases with their assets, following pagination. +func (c *Client) Releases(ctx context.Context, repo string) ([]Release, error) { + next := fmt.Sprintf("%s/repos/%s/%s/releases?per_page=100", c.baseURL, c.org, repo) + var releases []Release + for next != "" { + var out []Release + var err error + if next, err = c.getPage(ctx, next, &out); err != nil { + return nil, err + } + releases = append(releases, out...) + } + return releases, nil +} + +// TrafficViews returns the last 14 days of page views, one entry per UTC day. +// Needs push access to the repo. +func (c *Client) TrafficViews(ctx context.Context, repo string) ([]TrafficDay, error) { + var out trafficResponse + err := c.get(ctx, fmt.Sprintf("%s/repos/%s/%s/traffic/views?per=day", c.baseURL, c.org, repo), &out) + return out.Views, err +} + +// TrafficClones returns the last 14 days of git clones, one entry per UTC day. +func (c *Client) TrafficClones(ctx context.Context, repo string) ([]TrafficDay, error) { + var out trafficResponse + err := c.get(ctx, fmt.Sprintf("%s/repos/%s/%s/traffic/clones?per=day", c.baseURL, c.org, repo), &out) + return out.Clones, err +} + +// TrafficReferrers returns the top 10 referrers of the last 14 days. +func (c *Client) TrafficReferrers(ctx context.Context, repo string) ([]Referrer, error) { + var out []Referrer + err := c.get(ctx, fmt.Sprintf("%s/repos/%s/%s/traffic/popular/referrers", c.baseURL, c.org, repo), &out) + return out, err +} + +// TrafficPaths returns the top 10 content paths of the last 14 days. +func (c *Client) TrafficPaths(ctx context.Context, repo string) ([]PopularPath, error) { + var out []PopularPath + err := c.get(ctx, fmt.Sprintf("%s/repos/%s/%s/traffic/popular/paths", c.baseURL, c.org, repo), &out) + return out, err +} diff --git a/internal/github/client_test.go b/internal/github/client_test.go index 8cda2cd..0024370 100644 --- a/internal/github/client_test.go +++ b/internal/github/client_test.go @@ -108,3 +108,25 @@ func TestRateLimitFromHeaders(t *testing.T) { t.Fatalf("after reset: %+v, want only the later window", got) } } + +func TestReleasesPaginates(t *testing.T) { + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.URL.Query().Get("page") == "" { + w.Header().Set("Link", fmt.Sprintf(`; rel="next"`, r.Host, r.URL.Path)) + _, _ = w.Write([]byte(`[{"tag_name":"v2","assets":[{"name":"a","download_count":5}]}]`)) + return + } + _, _ = w.Write([]byte(`[{"tag_name":"v1","draft":true}]`)) + })) + defer srv.Close() + + c := NewClient("org", "token", time.Second) + c.baseURL = srv.URL + rels, err := c.Releases(context.Background(), "repo") + if err != nil { + t.Fatal(err) + } + if len(rels) != 2 || rels[0].Assets[0].DownloadCount != 5 || !rels[1].Draft { + t.Fatalf("releases = %+v", rels) + } +} diff --git a/internal/github/types.go b/internal/github/types.go index f141da7..86f161e 100644 --- a/internal/github/types.go +++ b/internal/github/types.go @@ -90,3 +90,47 @@ type RateLimit struct { Limit int Remaining int } + +// RepoInfo is the adoption-relevant subset of GET /repos/{owner}/{repo}. +type RepoInfo struct { + Stars int `json:"stargazers_count"` + Forks int `json:"forks_count"` + Watchers int `json:"subscribers_count"` + OpenIssuesAndPRs int `json:"open_issues_count"` // GitHub counts PRs as issues here +} + +type Release struct { + TagName string `json:"tag_name"` + Draft bool `json:"draft"` + Prerelease bool `json:"prerelease"` + Assets []ReleaseAsset `json:"assets"` +} + +type ReleaseAsset struct { + Name string `json:"name"` + DownloadCount int64 `json:"download_count"` // cumulative +} + +// TrafficDay is one day of views or clones (UTC). +type TrafficDay struct { + Timestamp time.Time `json:"timestamp"` + Count int `json:"count"` + Uniques int `json:"uniques"` +} + +type trafficResponse struct { + Views []TrafficDay `json:"views"` + Clones []TrafficDay `json:"clones"` +} + +type Referrer struct { + Referrer string `json:"referrer"` + Count int `json:"count"` + Uniques int `json:"uniques"` +} + +type PopularPath struct { + Path string `json:"path"` + Count int `json:"count"` + Uniques int `json:"uniques"` +} diff --git a/main.go b/main.go index 87a01c0..f8ffba2 100644 --- a/main.go +++ b/main.go @@ -12,6 +12,7 @@ import ( "github.com/prometheus/client_golang/prometheus" "github.com/prometheus/client_golang/prometheus/promhttp" + "github.com/drumandbytes/github-actions-runner-exporter/internal/adoption" "github.com/drumandbytes/github-actions-runner-exporter/internal/collector" "github.com/drumandbytes/github-actions-runner-exporter/internal/config" "github.com/drumandbytes/github-actions-runner-exporter/internal/fetch" @@ -43,6 +44,13 @@ func main() { registry := prometheus.NewRegistry() registry.MustRegister(collector.New(cfg.GitHubOrg, runnerFetcher, orgFetcher, client.RateLimits, cfg.RunnerCacheTTL, cfg.OrgCacheTTL), feed) + if len(cfg.AdoptionRepos) > 0 { + adoptionFetcher := fetch.New(func(ctx context.Context) (adoption.Summary, error) { + return adoption.Build(ctx, client, cfg.AdoptionRepos) + }, cfg.AdoptionCacheTTL, cfg.AdoptionCacheMaxStale, log) + registry.MustRegister(collector.NewAdoption(adoptionFetcher, cfg.AdoptionCacheTTL)) + } + mux := http.NewServeMux() mux.Handle("/metrics", promhttp.HandlerFor(registry, promhttp.HandlerOpts{})) mux.HandleFunc("/healthz", func(w http.ResponseWriter, r *http.Request) {