Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions .cspell-words.txt
Original file line number Diff line number Diff line change
Expand Up @@ -223,3 +223,5 @@ sdkmetric
stdr
metricdata
nilerr
cibackfill
embedsrcs
23 changes: 22 additions & 1 deletion cmd/github-metrics/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,7 @@ import (
"go.opentelemetry.io/otel/metric"

"github.com/tbhb-dev/github-metrics/internal/receiver"
"github.com/tbhb-dev/github-metrics/internal/reconcile"
"github.com/tbhb-dev/github-metrics/internal/recorder"
"github.com/tbhb-dev/github-metrics/internal/store"
"github.com/tbhb-dev/github-metrics/internal/telemetry"
Expand Down Expand Up @@ -83,12 +84,18 @@ func main() {
}
}

//nolint:funlen // Startup owns service shutdown ordering.
func run(ctx context.Context, addr string, log *slog.Logger) error {
cfg, err := reconcilerConfig(os.Getenv)
if err != nil {
return err
}

backfillCfg, err := ciBackfillConfig(os.Getenv)
if err != nil {
return err
}

file := os.Getenv("WEBHOOK_SECRET_FILE")
if file == "" {
return errNoSecretFile
Expand Down Expand Up @@ -131,7 +138,7 @@ func run(ctx context.Context, addr string, log *slog.Logger) error {

endpoint := os.Getenv("OTEL_EXPORTER_OTLP_ENDPOINT")

consumer, loop, err := newConsumers(ctx, endpoint, cfg, meter, repo, log)
consumer, loop, client, err := newConsumers(ctx, endpoint, cfg, meter, repo, log)
if err != nil {
shutdownCtx, cancel := context.WithTimeout(context.WithoutCancel(ctx), shutdownTimeout)
defer cancel()
Expand All @@ -155,6 +162,18 @@ func run(ctx context.Context, addr string, log *slog.Logger) error {

log.InfoContext(ctx, "listening", "addr", addr)

backfillDone := make(chan struct{})

if client != nil && backfillCfg.Days > 0 {
go func() {
defer close(backfillDone)

reconcile.BackfillCI(ctx, client, repo, log, backfillCfg, time.Now())
}()
} else {
close(backfillDone)
}

select {
case err = <-serveErr:
// Shut down the worker and reconciler before closing their store.
Expand All @@ -166,6 +185,8 @@ func run(ctx context.Context, addr string, log *slog.Logger) error {
shutdownCtx, cancel := context.WithTimeout(context.WithoutCancel(ctx), shutdownTimeout)
defer cancel()

<-backfillDone

return errors.Join(
err, srv.Shutdown(shutdownCtx), <-workerErr, <-reconcileErr, shutdownTelemetry(shutdownCtx), repo.Close(),
)
Expand Down
20 changes: 20 additions & 0 deletions cmd/github-metrics/main_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -271,3 +271,23 @@ func TestReconcilerConfigComplete(t *testing.T) {
}
}
}

func TestCIBackfillConfig(t *testing.T) {
t.Parallel()

for _, value := range []string{
"", "o/r:7", "o/r:1", "o/r:8", "o/r:0", "o/r:-1",
"o/r:day", "o/r", "o:7", "o/r/extra:7", "o/..:7", "o/r:7\n",
} {
cfg, err := ciBackfillConfig(func(string) string { return value })
valid := value == "" || value == "o/r:7" || value == "o/r:1"

if valid {
if err != nil || (value != "" && (cfg.Repository != "o/r" || cfg.Days < 1 || cfg.Days > 7)) {
t.Fatalf("config = %+v, error = %v", cfg, err)
}
} else if err == nil || err.Error() != "GITHUB_CI_BACKFILL must name a repository and days from 1 to 7" {
t.Fatalf("expected redacted variable error, got %v", err)
}
}
}
48 changes: 36 additions & 12 deletions cmd/github-metrics/reconciler.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ import (
"net/http"
"net/url"
"os"
"regexp"
"strconv"
"strings"
"time"
Expand Down Expand Up @@ -40,6 +41,7 @@ var (
errInvalidAppID = errors.New(appIDEnv + " must be a positive integer")
errInvalidInstallationID = errors.New(installationIDEnv + " must be a positive integer")
errInvalidBaseURL = errors.New(apiURLEnv + " must be a valid HTTPS API base URL")
errInvalidCIBackfill = errors.New("GITHUB_CI_BACKFILL must name a repository and days from 1 to 7")
errReadAppKey = errors.New("read " + appKeyFileEnv)
)

Expand Down Expand Up @@ -93,14 +95,36 @@ func reconcilerConfig(env func(string) string) (reconcileConfig, error) {
}, nil
}

// ciBackfillConfig validates the trigger even when reconciliation is disabled.
func ciBackfillConfig(env func(string) string) (reconcile.CIConfig, error) {
const name = "GITHUB_CI_BACKFILL"

var cfg reconcile.CIConfig

value := env(name)
if value == "" {
return cfg, nil
}

match := regexp.MustCompile(`^([A-Za-z0-9]+(?:-[A-Za-z0-9]+)*/[A-Za-z0-9_.-]+):([1-7])$`).FindStringSubmatch(value)
if match == nil || strings.HasSuffix(match[1], "/.") || strings.HasSuffix(match[1], "/..") {
return cfg, errInvalidCIBackfill
}

cfg.Repository = match[1]
cfg.Days = int(match[2][0] - '0')

return cfg, nil
}

//nolint:ireturn // The worker accepts either recorder through its interface.
func newConsumers(
ctx context.Context, endpoint string, cfg reconcileConfig, meter metric.Meter, repo *store.Bolt, log *slog.Logger,
) (worker.Recorder, *reconcile.Loop, error) {
) (worker.Recorder, *reconcile.Loop, *ghclient.Client, error) {
// cspell:ignore contextcheck
consumer, err := newRecorder(endpoint, meter, repo, log) //nolint:contextcheck // Recorder setup seeds its counters.
if err != nil {
return nil, nil, err
return nil, nil, nil, err
}

log.InfoContext(ctx, "recorder mode", "configured", endpoint != "")
Expand All @@ -109,41 +133,41 @@ func newConsumers(
if !configured || cfg.keyFile == "" {
log.InfoContext(ctx, "reconciler disabled")

return consumer, nil, nil
return consumer, nil, nil, nil
}

loop, err := newReconciler(cfg, meter, record, repo, log)
loop, client, err := newReconciler(cfg, meter, record, repo, log)

return consumer, loop, err
return consumer, loop, client, err
}

func newReconciler(
cfg reconcileConfig, meter metric.Meter, record *recorder.Recorder, repo reconcile.Watermarks, log *slog.Logger,
) (*reconcile.Loop, error) {
) (*reconcile.Loop, *ghclient.Client, error) {
// Relative request paths must resolve inside the API base path.
base, err := url.Parse(strings.TrimRight(cfg.apiURL, "/") + "/")
if err != nil || base.Scheme != "https" {
return nil, errInvalidBaseURL
return nil, nil, errInvalidBaseURL
}

key, err := os.ReadFile(cfg.keyFile)
if err != nil {
return nil, errReadAppKey
return nil, nil, errReadAppKey
}

source, err := appauth.New(appauth.Config{
HTTPClient: nil, Now: nil, Logger: log, BaseURL: base.String(), PrivateKeyPEM: key,
AppID: cfg.appID, InstallationID: cfg.installationID,
})
if err != nil {
return nil, fmt.Errorf("create installation token source: %w", err)
return nil, nil, fmt.Errorf("create installation token source: %w", err)
}

tags := ghclient.NewETags()

client, err := ghclient.New(base.String(), http.DefaultClient, budget.New(), source, tags)
if err != nil {
return nil, errInvalidBaseURL
return nil, nil, errInvalidBaseURL
}

lister := reconcile.NewLister(client, tags, base)
Expand All @@ -153,10 +177,10 @@ func newReconciler(

loop, err := reconcile.NewLoop(pass, meter, log, nil)
if err != nil {
return nil, fmt.Errorf("create reconciler loop: %w", err)
return nil, nil, fmt.Errorf("create reconciler loop: %w", err)
}

return loop, nil
return loop, client, nil
}

func startReconciler(ctx context.Context, loop *reconcile.Loop, stop context.CancelFunc) <-chan error {
Expand Down
1 change: 1 addition & 0 deletions deploy/compose.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,7 @@ services:
STORE_FILE: /var/lib/github-metrics/store.db
GITHUB_APP_ID: ${GITHUB_APP_ID:-}
GITHUB_INSTALLATION_ID: ${GITHUB_INSTALLATION_ID:-}
GITHUB_CI_BACKFILL: ${GITHUB_CI_BACKFILL:-}
GITHUB_API_URL: ${GITHUB_API_URL:-}
GITHUB_APP_KEY_FILE: ${GITHUB_APP_ID:+/run/secrets/github_app_key}
WEBHOOK_SECRET_FILE: /run/secrets/webhook_secret
Expand Down
2 changes: 2 additions & 0 deletions docs/architecture/11-risks-and-technical-debt.md
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,8 @@
| The operator never retires the previous webhook secret or never rotates the App key | An old credential keeps working | Gates of the threat-model follow-up, plan step 6 | New, deferred to step 6 |
| Backend access and retention for private-repository names and logins | Wider exposure than the operator intends | The operator confirms it in the threat-model follow-up | Unverified |

Tech debt: CI history backfill caps run and job pages without a resume cursor. A crash after a durable claim can lose a log. Backfilled claims also suppress later live timing metrics. The one-off Loki pass accepts these limits.

## Plan

Step 1 finished. Steps 2, 3, and 5 to 8 remain open work. Today `main` has the receiver, the request budget, and the GitHub client, which are parts of steps 3 and 5.
Expand Down
15 changes: 13 additions & 2 deletions docs/architecture/appendix-a-trace-and-metric-catalog.md
Original file line number Diff line number Diff line change
Expand Up @@ -134,9 +134,20 @@ The start is the earliest of all those times, so a non-agent commit that predate

Only the first end of a PR counts. If a reopened PR ends again, the stored `ended` milestone blocks a second observation.

Every histogram is an exponential (native) histogram, with the SDK's default limit of 160 buckets. Over a range of 1 second to 30 days, 160 buckets give a scale of 2, which means each bucket spans a ratio of about 1.19 and a quantile estimate is off by about 9% at most. Goal thresholds of 600 s and 900 s sit inside a bucket, not on an edge, so a goal check has the same error. D15 records the choice, the fallback, and the backend check. Each attribute set exports one native histogram series, with the count and sum inside it, if Mimir ingests native histograms (unverified).
Completed CI jobs record queue and run durations for every conclusion:

The metric attributes are `vcs.repository.name`, and `github.author.type` with the values `user` or `bot`. The review counter adds `github.review.state`, and the cycle time histogram adds `vcs.change.state` and `github.pull_request.start_source`.
| Instrument | Unit | Start | End | Attributes |
| --- | --- | --- | --- | --- |
| `github.ci.job.queue_seconds` | `s` | Job `created_at` | Job `started_at` | `repository`, `workflow`, `job`, `conclusion`, `event_class` and `runner` |
| `github.ci.job.run_seconds` | `s` | Job `started_at` | Job `completed_at` | `repository`, `workflow`, `job`, `conclusion`, `event_class` and `runner` |

The workflow and job names come from `workflow_name` and `name`. The runner comes from the first `labels` entry or `none` for an empty or missing array. Each attribute removes line breaks and keeps at most 64 characters. Both histograms use explicit boundaries of 5, 15, 30, 60, 120, 300, 600, 900, 1200, 1800, 2700, 3600, 5400 and 7200 seconds. A missing or invalid timestamp skips that duration. A negative duration also skips that observation. The ledger claims the decimal job ID followed by a zero byte and `ci_job` before recording. Jobs without an ID skip recording. A duplicate claim skips all metrics and logs for that delivery; a claim error leaves it for retry.

The `event_class` attribute approximates the trigger because the payload has no triggering event. A `head_branch` with the prefix `gh-readonly-queue/` counts as `merge_group`. The repository's default branch counts as `push`; any other branch counts as `pull_request`. Scheduled and manual runs on the default branch count as `push`, and runs on a non-default branch from other triggers count as `pull_request`.

Every PR histogram is an exponential (native) histogram, with the SDK's default limit of 160 buckets. Over a range of 1 second to 30 days, 160 buckets give a scale of 2, which means each bucket spans a ratio of about 1.19 and a quantile estimate is off by about 9% at most. Goal thresholds of 600 s and 900 s sit inside a bucket, not on an edge, so a goal check has the same error. D15 records the choice, the fallback, and the backend check. Each attribute set exports one native histogram series, with the count and sum inside it, if Mimir ingests native histograms (unverified).

The PR metric attributes are `vcs.repository.name`, and `github.author.type` with the values `user` or `bot`. The review counter adds `github.review.state`, and the cycle time histogram adds `vcs.change.state` and `github.pull_request.start_source`.

### Direct metrics, not derived from traces

Expand Down
4 changes: 4 additions & 0 deletions internal/reconcile/BUILD.bazel
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ repo_files()
go_library(
name = "reconcile",
srcs = [
"cibackfill.go",
"events.go",
"list.go",
"loop.go",
Expand All @@ -28,11 +29,14 @@ go_library(
go_test(
name = "reconcile_test",
srcs = [
"cibackfill_test.go",
"events_test.go",
"list_test.go",
"loop_test.go",
"run_test.go",
],
data = glob(["testdata/**"]),
embedsrcs = ["testdata/ci_jobs.json"],
visibility = ["//:__pkg__"],
deps = [
":reconcile",
Expand Down
Loading
Loading