Skip to content
Open
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
9 changes: 8 additions & 1 deletion cmd/github-metrics/BUILD.bazel
Original file line number Diff line number Diff line change
Expand Up @@ -8,11 +8,18 @@ repo_files()

go_library(
name = "github-metrics_lib",
srcs = ["main.go"],
srcs = [
"main.go",
"reconciler.go",
],
importpath = "github.com/tbhb-dev/github-metrics/cmd/github-metrics",
visibility = ["//:__pkg__"],
deps = [
"//internal/appauth",
"//internal/budget",
"//internal/ghclient",
"//internal/receiver",
"//internal/reconcile",
"//internal/recorder",
"//internal/store",
"//internal/telemetry",
Expand Down
41 changes: 29 additions & 12 deletions cmd/github-metrics/main.go
Original file line number Diff line number Diff line change
@@ -1,12 +1,18 @@
// SPDX-License-Identifier: Apache-2.0
// Copyright Tony Burns

// Command github-metrics runs the webhook receiver and queue worker.
// Command github-metrics runs the webhook receiver, queue worker and optional reconciler.
//
// WEBHOOK_SECRET_FILE names a file that contains the App's webhook secret.
//
// STORE_FILE names the store file for the webhook queue and dedupe table.
//
// OTEL_EXPORTER_OTLP_ENDPOINT enables metric export and is required for reconciliation.
// GITHUB_APP_ID and GITHUB_INSTALLATION_ID are positive integers that identify
// the GitHub App and its installation. GITHUB_APP_KEY_FILE names the App's
// private key file. Set all three to configure reconciliation.
// GITHUB_API_URL is the GitHub API base and defaults to https://api.github.com.
//
// LISTEN_ADDR is the listen address and defaults to :8080. The health check
// probes that address, or loopback when its host is a wildcard.
//
Expand Down Expand Up @@ -66,14 +72,23 @@ func main() {

log := slog.New(slog.NewJSONHandler(os.Stdout, nil))

err := run(addr, log)
ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
err := run(ctx, addr, log)

stop()

if err != nil {
log.Error("exit", "error", err)
os.Exit(1)
}
}

func run(addr string, log *slog.Logger) error {
func run(ctx context.Context, addr string, log *slog.Logger) error {
cfg, err := reconcilerConfig(os.Getenv)
if err != nil {
return err
}

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

srv := receiver.NewServer(addr, receiver.Handler(secret, repo, log))

ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
ctx, stop := context.WithCancel(ctx)
defer stop()

shutdownTelemetry, meter, err := telemetry.Setup(ctx, "github-metrics", version)
Expand All @@ -116,16 +131,14 @@ func run(addr string, log *slog.Logger) error {

endpoint := os.Getenv("OTEL_EXPORTER_OTLP_ENDPOINT")

consumer, err := newRecorder(endpoint, meter, repo)
consumer, loop, err := newConsumers(ctx, endpoint, cfg, meter, repo, log)
if err != nil {
shutdownCtx, cancel := context.WithTimeout(context.Background(), shutdownTimeout)
shutdownCtx, cancel := context.WithTimeout(context.WithoutCancel(ctx), shutdownTimeout)
defer cancel()

return errors.Join(err, shutdownTelemetry(shutdownCtx), repo.Close())
}

log.InfoContext(ctx, "recorder mode", "configured", endpoint != "")

workerErr := make(chan error, 1)

go func() {
Expand All @@ -134,24 +147,28 @@ func run(addr string, log *slog.Logger) error {
stop()
}()

reconcileErr := startReconciler(ctx, loop, stop)

serveErr := make(chan error, 1)

go func() { serveErr <- srv.ListenAndServe() }()

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

select {
case err = <-serveErr:
// Shut down the worker before closing its store.
// Shut down the worker and reconciler before closing their store.
case <-ctx.Done():
}

stop()

shutdownCtx, cancel := context.WithTimeout(context.Background(), shutdownTimeout)
shutdownCtx, cancel := context.WithTimeout(context.WithoutCancel(ctx), shutdownTimeout)
defer cancel()

return errors.Join(err, srv.Shutdown(shutdownCtx), <-workerErr, shutdownTelemetry(shutdownCtx), repo.Close())
return errors.Join(
err, srv.Shutdown(shutdownCtx), <-workerErr, <-reconcileErr, shutdownTelemetry(shutdownCtx), repo.Close(),
)
}

func logRepairFloor(log *slog.Logger, ledger recorder.Ledger) error {
Expand Down
130 changes: 130 additions & 0 deletions cmd/github-metrics/main_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,13 @@ package main

import (
"bytes"
"context"
"encoding/json"
"errors"
"log/slog"
"net/http/httptest"
"os"
"path/filepath"
"testing"
"time"

Expand Down Expand Up @@ -141,3 +145,129 @@ func TestNewRecorderWithEndpoint(t *testing.T) {
t.Fatalf("metric = %v, want one github.events observation", measurement)
}
}

func TestRunWithoutReconciler(t *testing.T) {
for _, name := range []string{appIDEnv, installationIDEnv, appKeyFileEnv, apiURLEnv, "OTEL_EXPORTER_OTLP_ENDPOINT"} {
t.Setenv(name, "")
}

dir := t.TempDir()
secretFile := filepath.Join(dir, "secret")
t.Setenv("WEBHOOK_SECRET_FILE", secretFile)
t.Setenv("STORE_FILE", filepath.Join(dir, "store.db"))

err := os.WriteFile(secretFile, []byte("test secret"), 0o600)
if err != nil {
t.Fatal(err)
}

address := httptest.NewUnstartedServer(nil)
addr := address.Listener.Addr().String()
address.Close()

ctx, cancel := context.WithTimeout(t.Context(), 5*time.Second)
defer cancel()

var logs bytes.Buffer

log := slog.New(slog.NewJSONHandler(&logs, nil))
done := make(chan error, 1)

go func() { done <- run(ctx, addr, log) }()

ticker := time.NewTicker(10 * time.Millisecond)
defer ticker.Stop()

for probe(addr) != 0 {
select {
case err = <-done:
t.Fatalf("service exited before it was healthy: %v", err)
case <-ctx.Done():
t.Fatalf("service did not become healthy, shutdown error = %v", <-done)
case <-ticker.C:
}
}

cancel()

err = <-done
if err != nil {
t.Fatal(err)
}

if bytes.Count(logs.Bytes(), []byte(`"level":"INFO","msg":"reconciler disabled"`)) != 1 {
t.Fatalf("want one INFO line for the disabled reconciler, got %s", logs.String())
}
}

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

env := map[string]string{apiURLEnv: defaultGitHubAPI}

var disabled reconcileConfig

cfg, err := reconcilerConfig(func(name string) string { return env[name] })
if err != nil || cfg != disabled {
t.Fatalf("want disabled configuration, got error %v", err)
}
}

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

for _, test := range []struct{ set, missing string }{
{appIDEnv, installationIDEnv + ", " + appKeyFileEnv},
{installationIDEnv, appIDEnv + ", " + appKeyFileEnv},
{appKeyFileEnv, appIDEnv + ", " + installationIDEnv},
} {
env := map[string]string{test.set: "test private value"}
want := errMissingReconcilerConfig.Error() + ": " + test.missing

_, err := reconcilerConfig(func(name string) string { return env[name] })
if !errors.Is(err, errMissingReconcilerConfig) || err.Error() != want {
t.Errorf("with %s set, want an error naming only %s", test.set, test.missing)
}
}
}

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

const invalid = "test private value"

for name, want := range map[string]error{appIDEnv: errInvalidAppID, installationIDEnv: errInvalidInstallationID} {
env := map[string]string{appIDEnv: "1", installationIDEnv: "2", appKeyFileEnv: "test-key.pem"}
env[name] = invalid

_, err := reconcilerConfig(func(name string) string { return env[name] })
if !errors.Is(err, want) || err.Error() != want.Error() {
t.Errorf("want an error naming %s without its value", name)
}
}
}

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

const keyFile = "test-key.pem"

for _, apiURL := range []string{"", defaultGitHubAPI + "/api/v3"} {
env := map[string]string{appIDEnv: "1", installationIDEnv: "2", appKeyFileEnv: keyFile, apiURLEnv: apiURL}

cfg, err := reconcilerConfig(func(name string) string { return env[name] })
if err != nil {
t.Fatal(err)
}

wantURL := apiURL
if wantURL == "" {
wantURL = defaultGitHubAPI
}

want := reconcileConfig{keyFile: keyFile, apiURL: wantURL, appID: 1, installationID: 2}
if cfg != want {
t.Fatalf("config = %+v, want %+v", cfg, want)
}
}
}
Loading