Skip to content
Merged
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
14 changes: 8 additions & 6 deletions internal/reconcile/events.go
Original file line number Diff line number Diff line change
Expand Up @@ -40,11 +40,11 @@ type issueEvent struct {
Event string `json:"event"`
}

// FirstEnd reads a pull request's issue events at incremental priority and
// returns the first end. Each page clears its tag first, because the client
// FirstEnd reads a pull request's issue events and returns the first end.
// Each page clears its tag first, because the client
// would answer 304 with an empty body for a URL it saw before.
func (l *Lister) FirstEnd(ctx context.Context, repo string, number int) (End, error) {
events, pages, complete, err := l.events(ctx, repo, number)
func (l *Lister) FirstEnd(ctx context.Context, repo string, number int, priority budget.Priority) (End, error) {
events, pages, complete, err := l.events(ctx, repo, number, priority)
end := End{At: time.Time{}, State: "", Pages: pages}

if err != nil || !complete {
Expand Down Expand Up @@ -76,15 +76,17 @@ func (l *Lister) FirstEnd(ctx context.Context, repo string, number int) (End, er

// events returns the events of up to MaxEventPages pages. The bool is false
// when more pages remain.
func (l *Lister) events(ctx context.Context, repo string, number int) ([]issueEvent, int, bool, error) {
func (l *Lister) events(ctx context.Context, repo string, number int, priority budget.Priority) (
[]issueEvent, int, bool, error,
) {
var events []issueEvent

target := "repos/" + repo + "/issues/" + strconv.Itoa(number) + "/events?per_page=100"

for page := 1; ; page++ {
l.clear(target)

resp, err := l.fetch(ctx, budget.Incremental, target, page)
resp, err := l.fetch(ctx, priority, target, page)
if err != nil {
return nil, page - 1, false, err
}
Expand Down
11 changes: 6 additions & 5 deletions internal/reconcile/events_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ import (
"testing"
"time"

"github.com/tbhb-dev/github-metrics/internal/budget"
"github.com/tbhb-dev/github-metrics/internal/reconcile"
)

Expand Down Expand Up @@ -56,7 +57,7 @@ func TestFirstEndRules(t *testing.T) {
write(t, resp, "["+strings.Join(test.events, ",")+"]")
})

got, err := fake.lister.FirstEnd(t.Context(), "o/r", 7)
got, err := fake.lister.FirstEnd(t.Context(), "o/r", 7, budget.Incremental)
if err != nil || !got.At.Equal(test.at) || got.State != test.state || got.Pages != 1 ||
!slices.Equal(fake.requests, []string{eventsPath}) {
t.Errorf("got = %+v, err = %v, requests = %v", got, err, fake.requests)
Expand All @@ -73,7 +74,7 @@ func TestFirstEndPastThreePagesIsAmbiguous(t *testing.T) {
write(t, resp, "["+event(closedEvent, "2026-01-02T01:00:00Z")+"]")
})

got, err := fake.lister.FirstEnd(t.Context(), "o/r", 7)
got, err := fake.lister.FirstEnd(t.Context(), "o/r", 7, budget.Incremental)
if err != nil || !got.At.IsZero() || got.State != "" || got.Pages != reconcile.MaxEventPages ||
len(fake.requests) != reconcile.MaxEventPages {
t.Errorf("got = %+v, err = %v, requests = %v", got, err, fake.requests)
Expand All @@ -86,7 +87,7 @@ func TestFirstEndClearsTags(t *testing.T) {
fake := newRig(t, tagged(t, `"v1"`, "["+event(closedEvent, "2026-01-02T01:00:00Z")+"]"))

for range 2 {
got, err := fake.lister.FirstEnd(t.Context(), "o/r", 7)
got, err := fake.lister.FirstEnd(t.Context(), "o/r", 7, budget.Incremental)
if err != nil || got.At.IsZero() || got.Pages != 1 {
t.Fatalf("got = %+v, err = %v", got, err)
}
Expand All @@ -108,7 +109,7 @@ func TestFirstEndKeepsBasePath(t *testing.T) {
write(t, resp, "["+event(closedEvent, "2026-01-02T01:00:00Z")+"]")
})

got, err := fake.lister.FirstEnd(t.Context(), "o/r", 7)
got, err := fake.lister.FirstEnd(t.Context(), "o/r", 7, budget.Incremental)
if err != nil || got.At.IsZero() || !slices.Equal(fake.requests, []string{"/api/v3" + eventsPath}) {
t.Errorf("got = %+v, err = %v, requests = %v", got, err, fake.requests)
}
Expand Down Expand Up @@ -145,7 +146,7 @@ func TestFirstEndReadFailure(t *testing.T) {
write(t, resp, "[")
})

got, err := fake.lister.FirstEnd(t.Context(), "o/r", 7)
got, err := fake.lister.FirstEnd(t.Context(), "o/r", 7, budget.Incremental)
_, decodeErr := errors.AsType[*json.SyntaxError](err)

if decodeErr == test.interrupted || errors.Is(err, io.ErrUnexpectedEOF) != test.interrupted ||
Expand Down
54 changes: 44 additions & 10 deletions internal/reconcile/loop.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,12 @@ import (
const (
passInterval = 15 * time.Minute
passTimeout = 14 * time.Minute
// A sweep gets 45 minutes to read the full repair window at the shared request rate.
sweepTimeout = 45 * time.Minute
sweepHour = 3

incremental = "incremental"
sweep = "sweep"
metricPrefix = "github_metrics.reconcile."
seconds = "s"

Expand All @@ -32,7 +37,7 @@ type LoopClock interface {
NewTicker(interval time.Duration) (<-chan time.Time, func())
}

// Loop schedules and reports incremental reconciliation passes.
// Loop schedules and reports incremental passes and daily sweeps.
type Loop struct {
pass Pass
clock LoopClock
Expand Down Expand Up @@ -84,13 +89,26 @@ func (l *Loop) Start(ctx context.Context) error {
return nil
}

started := l.clock.Now()

nextSweep := sweepTime(started)
if started.After(nextSweep) {
nextSweep = nextSweep.AddDate(0, 0, 1)
}

ticks, stop := l.clock.NewTicker(passInterval)
defer stop()

consecutiveErrors := 0

for {
finished, err := l.runPass(ctx)
kind := incremental
if !started.Before(nextSweep) {
kind = sweep
nextSweep = sweepTime(started).AddDate(0, 0, 1)
}

finished, err := l.runPass(ctx, kind, started)
if err != nil {
consecutiveErrors++
} else {
Expand All @@ -104,9 +122,17 @@ func (l *Loop) Start(ctx context.Context) error {
if !waitForNextPass(ctx, ticks, finished) {
return nil
}

started = l.clock.Now()
}
}

func sweepTime(now time.Time) time.Time {
year, month, day := now.UTC().Date()

return time.Date(year, month, day, sweepHour, 0, 0, 0, time.UTC)
}

func waitForNextPass(ctx context.Context, ticks <-chan time.Time, finished time.Time) bool {
for {
select {
Expand All @@ -121,9 +147,17 @@ func waitForNextPass(ctx context.Context, ticks <-chan time.Time, finished time.
}
}

func (l *Loop) runPass(ctx context.Context) (time.Time, error) {
started := l.clock.Now()
passCtx, cancel := context.WithTimeout(ctx, passTimeout)
// sweepPassKey marks a sweep through the pass callback that calls Run.
type sweepPassKey struct{}

func (l *Loop) runPass(ctx context.Context, kind string, started time.Time) (time.Time, error) {
timeout := passTimeout
if kind == sweep {
timeout = sweepTimeout
ctx = context.WithValue(ctx, sweepPassKey{}, true)
}

passCtx, cancel := context.WithTimeout(ctx, timeout)
result, err := l.pass(passCtx)

cancel()
Expand All @@ -137,22 +171,22 @@ func (l *Loop) runPass(ctx context.Context) (time.Time, error) {
level = slog.LevelError
}

kind := attribute.String("kind", incremental)
kindOnly := metric.WithAttributes(kind)
kindAttr := attribute.String("kind", kind)
kindOnly := metric.WithAttributes(kindAttr)

l.runs.Add(ctx, 1, metric.WithAttributes(kind, attribute.String("result", string(result.Result))))
l.runs.Add(ctx, 1, metric.WithAttributes(kindAttr, attribute.String("result", string(result.Result))))
l.duration.Record(ctx, elapsed.Seconds(), kindOnly)

// RunResult currently counts recorded merges. First ends arrive with the issue events read.
l.repairs.Add(ctx, int64(result.Recorded), metric.WithAttributes(kind, attribute.String("milestone", "merged")))
l.repairs.Add(ctx, int64(result.Recorded), metric.WithAttributes(kindAttr, attribute.String("milestone", "merged")))

if result.Result == RunOK {
l.lastSuccess.Record(ctx, finished.Unix(), kindOnly)
}

l.log.LogAttrs(
ctx, level, "reconcile pass finished",
slog.String("kind", incremental), slog.String("result", string(result.Result)),
slog.String("kind", kind), slog.String("result", string(result.Result)),
slog.Int("repos", result.Repositories), slog.Int("pages", result.Pages),
slog.Int("not_modified", result.NotModified), slog.Int("recorded", result.Recorded),
slog.Int("already_counted", result.AlreadyCounted), slog.Int("truncated", result.Truncated),
Expand Down
Loading