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
4 changes: 3 additions & 1 deletion SETUP.rst
Original file line number Diff line number Diff line change
Expand Up @@ -378,7 +378,9 @@ without becoming an outage: for how long in the last hour, day, week
and month, every hour of the last 30 days in which it was unavailable,
and every period of the last 90 days with its reason. The bot only
notices while it runs, so the times are as precise as its polling
cycles.
cycles. For Patchwork, the windows also show the share of the bot's
requests that worked, retries included, which tells how it felt to use
it even when the bot got through.

The bot cannot notice that it does not run itself, for example when
GitHub disables Actions on the bot repository. The pages warn when
Expand Down
3 changes: 3 additions & 0 deletions cmd/leadtest/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -342,6 +342,9 @@ func buildPipeline(cfg *config.Config, st *state.Store, workDir string,
Token: cfg.Secrets.PatchworkToken,
MinDelay: cfg.Patchwork.MinDelay.D(),
Logger: log,
OnTry: func(failed bool) {
st.Availability.CountPatchworkTry(failed, time.Now())
},
})
if err != nil {
return nil, err
Expand Down
10 changes: 10 additions & 0 deletions internal/httpx/client.go
Original file line number Diff line number Diff line change
Expand Up @@ -83,6 +83,13 @@ type Options struct {
HTTPClient *http.Client
Logger *slog.Logger
Sleep func(ctx context.Context, d time.Duration) error

// OnTry, when set, is called after each try of a request. A try
// fails on a network error, a timeout or a transient status: 5xx,
// 429 or a rate-limited 403. Other statuses, 404 included, are the
// bot's mistake and count as working. Tries ended by the context
// or by bot protection are not reported.
OnTry func(failed bool)
}

type Client struct {
Expand Down Expand Up @@ -259,6 +266,9 @@ func (c *Client) Do(ctx context.Context, r Request) (*Response, error) {
if ctx.Err() != nil {
return nil, ctx.Err()
}
if c.opts.OnTry != nil && !errors.Is(err, ErrBotProtection) {
c.opts.OnTry(err != nil || isTransientStatus(resp))
}
var retryAfter time.Duration
retry := false
switch {
Expand Down
130 changes: 130 additions & 0 deletions internal/httpx/ontry_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,130 @@
// Copyright 2026 LeadTestKit Authors
// SPDX-License-Identifier: Apache-2.0

package httpx

import (
"context"
"net/http"
"reflect"
"sync"
"sync/atomic"
"testing"
)

// tryRecorder records the tries a client reports.
type tryRecorder struct {
mu sync.Mutex
tries []bool
}

func (r *tryRecorder) onTry(failed bool) {
r.mu.Lock()
r.tries = append(r.tries, failed)
r.mu.Unlock()
}

func (r *tryRecorder) check(t *testing.T, want ...bool) {
t.Helper()
r.mu.Lock()
defer r.mu.Unlock()
if len(want) == 0 && len(r.tries) == 0 {
return
}
if !reflect.DeepEqual(r.tries, want) {
t.Fatalf("tries = %v, want %v", r.tries, want)
}
}

// statuses answers with the given status codes in turn, then 200.
func statuses(codes ...int) http.HandlerFunc {
var n atomic.Int32
return func(w http.ResponseWriter, r *http.Request) {
if i := int(n.Add(1)) - 1; i < len(codes) {
w.WriteHeader(codes[i])
return
}
w.Write([]byte(`{}`))
}
}

func TestOnTryTransientThenSuccess(t *testing.T) {
var rec tryRecorder
c, srv := testClient(t, statuses(502, 502), Options{Attempts: 3, OnTry: rec.onTry})
if _, err := c.Get(context.Background(), srv.URL); err != nil {
t.Fatal(err)
}
rec.check(t, true, true, false)
}

func TestOnTryClientErrors(t *testing.T) {
for _, tc := range []struct {
name string
codes []int
retry int
want []bool
}{
{"404", []int{404}, 0, []bool{false}},
{"400", []int{400}, 0, []bool{false}},
{"404 retried", []int{404}, 1, []bool{false, false}},
} {
t.Run(tc.name, func(t *testing.T) {
var rec tryRecorder
c, srv := testClient(t, statuses(tc.codes...), Options{OnTry: rec.onTry})
c.Do(context.Background(), Request{URL: srv.URL, NotFoundRetries: tc.retry})
rec.check(t, tc.want...)
})
}
}

func TestOnTryNetworkError(t *testing.T) {
var rec tryRecorder
c, srv := testClient(t, statuses(), Options{Attempts: 2, OnTry: rec.onTry})
srv.Close()
if _, err := c.Get(context.Background(), srv.URL); err == nil {
t.Fatal("no error from a closed server")
}
rec.check(t, true, true)
}

func TestOnTryCanceled(t *testing.T) {
var rec tryRecorder
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
c, srv := testClient(t, func(w http.ResponseWriter, r *http.Request) {
cancel()
w.WriteHeader(502)
}, Options{OnTry: rec.onTry})
c.Get(ctx, srv.URL)
rec.check(t)
}

func TestOnTryBotProtection(t *testing.T) {
if !curlAvailable() {
t.Skip("curl not installed")
}
var rec tryRecorder
c, srv := testClient(t, func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "text/html")
w.Write([]byte(`<html><div id="anubis_challenge"></div></html>`))
}, Options{CurlFirst: true, Attempts: 2, OnTry: rec.onTry})
c.Get(context.Background(), srv.URL)
rec.check(t)
}

func TestOnTryRateLimited(t *testing.T) {
var rec tryRecorder
var n atomic.Int32
c, srv := testClient(t, func(w http.ResponseWriter, r *http.Request) {
if n.Add(1) == 1 {
w.Header().Set("X-RateLimit-Remaining", "0")
w.WriteHeader(403)
return
}
w.Write([]byte(`{}`))
}, Options{OnTry: rec.onTry})
if _, err := c.Get(context.Background(), srv.URL); err != nil {
t.Fatal(err)
}
rec.check(t, true, false)
}
4 changes: 3 additions & 1 deletion internal/pages/pages_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,7 @@ func TestRender(t *testing.T) {
st.Meta.Outages = map[string]*state.Outage{state.OutageRuns: {
Since: state.FormatTime(now), Reason: "no workflow run started"}}
st.Availability.Unavailable(state.ServicePatchwork, "lorem", now)
st.Availability.CountPatchworkTry(true, now)
if err := st.Save(); err != nil {
t.Fatal(err)
}
Expand Down Expand Up @@ -97,7 +98,8 @@ func TestRender(t *testing.T) {
var avail state.Availability
b, _ = os.ReadFile(filepath.Join(out, "data", "availability.json"))
if err := json.Unmarshal(b, &avail); err != nil ||
avail.Failing[state.ServicePatchwork].Reason != "lorem" {
avail.Failing[state.ServicePatchwork].Reason != "lorem" ||
len(avail.PatchworkHourlyTries) != 1 || avail.PatchworkHourlyTries[0].Failed != 1 {
t.Errorf("availability = %s, %v", b, err)
}
b, err = os.ReadFile(filepath.Join(out, "data", "history", "2026-03.json"))
Expand Down
64 changes: 54 additions & 10 deletions internal/pages/site/app.js
Original file line number Diff line number Diff line change
Expand Up @@ -589,6 +589,39 @@ function downtime(list, service, seconds) {
sum + Math.max(0, Math.min(p.to, now) - Math.max(p.from, start)), 0);
}

// recordedTime is the part of the last seconds since the bot started
// recording availability, in seconds.
function recordedTime(data, seconds) {
const now = Date.now() / 1000;
return now - Math.max(now - seconds, data.since ? Date.parse(data.since) / 1000 : -Infinity);
}

// successRate counts the tries of a service in the hours and UTC days
// that overlap the last seconds, or is null without any. Only Patchwork
// is counted.
function successRate(data, service, seconds) {
if (service !== "patchwork") return null;
const start = Date.now() / 1000 - seconds;
const counts = (data.patchwork_hourly_tries || []).map(b =>
({ end: Date.parse(b.hour) / 1000 + 3600, b })).concat(
(data.patchwork_daily_tries || []).map(b =>
({ end: Date.parse(b.day + "T00:00:00Z") / 1000 + 86400, b })));
const r = counts.filter(c => c.end > start).reduce((r, c) =>
({ tries: r.tries + c.b.tries, failed: r.failed + (c.b.failed || 0) }), { tries: 0, failed: 0 });
return r.tries ? r : null;
}

// formatRate shows the share of tries that worked in whole percent,
// rounded down so that it only shows 100% when none failed.
function formatRate(r) {
return Math.floor(100 * (r.tries - r.failed) / r.tries) + "%";
}

// rateColor goes from yellow when most tries worked to red when none did.
function rateColor(r) {
return "hsl(" + Math.round(50 * (r.tries - r.failed) / r.tries) + ", 90%, 45%)";
}

async function showAvailability() {
const path = "data/availability.json";
if (!cache.has(path)) {
Expand All @@ -615,21 +648,31 @@ function renderAvailability() {
const used = index.services || MAIN_SERVICES;
const services = used.concat(Object.keys(SERVICES).filter(s =>
!used.includes(s) && list.some(p => p.service === s)));
const summary = el("table", { class: "avail" },
el("tr", {}, el("th", {}, "Service"), el("th", {}, "Now"),
WINDOWS.map(([name]) => el("th", {}, name)), el("th", {}, TIMELINE_DAYS + " days")),
const summary = el("table", { class: "avail summary" },
el("tr", {}, el("th", { class: "fit" }, "Service"), el("th", { class: "fit" }, "Now"),
WINDOWS.map(([name]) => el("th", { class: "fit center" }, name)), el("th"),
el("th", { class: "center" }, TIMELINE_DAYS + " days")),
services.map(service => {
const failing = (data.failing || {})[service];
return el("tr", {},
el("td", {}, SERVICES[service] || service),
el("td", { class: failing ? "down" : "up" },
el("td", { class: "fit" }, SERVICES[service] || service),
el("td", { class: failing ? "fit down" : "fit up" },
failing ? ["unavailable for ", span(failing.since)] : "available"),
WINDOWS.map(([, seconds]) => {
const down = downtime(list, service, seconds);
return el("td", { class: down ? "num down" : "num muted",
title: (100 - 100 * down / seconds).toFixed(2) + "% available" },
duration(down));
}),
const rate = successRate(data, service, seconds);
const recorded = recordedTime(data, seconds);
const parts = [];
if (recorded > 0) parts.push(Math.max(0, 100 - 100 * down / recorded).toFixed(2) +
"% of the time recorded available");
if (rate) parts.push(formatRate(rate) + " of " + rate.tries + " tries worked");
const title = parts.join(", ") || null;
return el("td", { class: "fit window", title }, el("div", {},
el("span", { class: down ? "down" : "muted" },
rate && !down ? "0m" : duration(down)),
rate ? el("span", rate.failed ? { class: "rate", style: "color: " + rateColor(rate) } :
{ class: "rate muted" }, formatRate(rate)) : null));
}), el("td"),
el("td", { class: "timeline" }, el("div", { class: "days" },
timeline(list, service, data))));
}));
Expand All @@ -656,7 +699,8 @@ function renderAvailability() {
"the hours in which the service was unavailable, the higher the longer, red for an ",
"outage. Times are as the bot saw them: from ",
"the first request that failed to the first that worked, as precise as its ",
"polling cycles. The bot keeps them for 90 days."),
"polling cycles. The bot keeps them for 90 days. The percentage is the share ",
"of the bot's requests to Patchwork, retries included, that worked: the lower, the redder."),
rows.length ? el("div", { class: "wide" }, pager(),
el("table", { class: "avail periods" },
el("tr", {}, ["Service", "From", "To", "Duration", "", "Reason"].map(h =>
Expand Down
5 changes: 5 additions & 0 deletions internal/pages/site/style.css
Original file line number Diff line number Diff line change
Expand Up @@ -121,10 +121,15 @@ a:hover .badge { background: color-mix(in srgb, currentColor 20%, transparent);
.avail th, .avail td { padding: 4px 8px; border-bottom: 1px solid var(--line);
white-space: nowrap; }
.avail .num { text-align: right; font-variant-numeric: tabular-nums; }
.avail .window { font-variant-numeric: tabular-nums; }
.avail .window div { display: flex; justify-content: space-between; gap: 2ch; }
.avail .up { color: var(--success); }
.avail .down { color: var(--fail); }
.avail .reason { white-space: normal; overflow-wrap: anywhere; }
.avail .timeline { width: 40%; min-width: 200px; }
/* The columns as narrow as their contents, the space left before the bar. */
.avail.summary th.center { text-align: center; }
.avail.summary .fit { width: 1%; padding: 4px 1.25ch; }
.days { position: relative; height: 16px; border-radius: 3px; overflow: hidden;
background: var(--row); }
.days span { position: absolute; bottom: 0; }
Expand Down
7 changes: 7 additions & 0 deletions internal/pipeline/availability.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,13 @@ import (
// kept for the pages.
const availabilityKept = 90 * 24 * time.Hour

// The counts of tries are kept by hour for triesHourly, then by day, for
// triesKept in all.
const (
triesHourly = 7 * 24 * time.Hour
triesKept = 31 * 24 * time.Hour
)

func serviceName(service string) string {
switch service {
case state.ServicePatchwork:
Expand Down
14 changes: 14 additions & 0 deletions internal/pipeline/outage_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -775,3 +775,17 @@ func TestRefusedReportsRetriedHourly(t *testing.T) {
t.Fatalf("report failure = %+v", f)
}
}

func TestStepPrunesTries(t *testing.T) {
e := newEnv(t, "")
a := e.p.Store.Availability
a.CountPatchworkTry(true, e.now.Add(-31*24*time.Hour-time.Hour))
a.CountPatchworkTry(false, e.now.Add(-30*24*time.Hour))
e.p.Step(context.Background(), false)
day := e.now.Add(-30 * 24 * time.Hour).UTC().Format("2006-01-02")
if len(a.PatchworkHourlyTries) != 0 || len(a.PatchworkDailyTries) != 1 ||
a.PatchworkDailyTries[0].Day != day || a.PatchworkDailyTries[0].Tries != 1 {
t.Fatalf("tries after the step: %d hours, days %+v",
len(a.PatchworkHourlyTries), a.PatchworkDailyTries)
}
}
1 change: 1 addition & 0 deletions internal/pipeline/pipeline.go
Original file line number Diff line number Diff line change
Expand Up @@ -238,6 +238,7 @@ func (p *Pipeline) Step(ctx context.Context, final bool) {
p.steps++
p.pwDown, p.checksDown, p.pwSkipLogged = nil, nil, nil
p.Store.Availability.Prune(p.now().Add(-availabilityKept))
p.Store.Availability.PrunePatchworkTries(p.now(), triesHourly, triesKept)
if p.Store.Availability.Since == "" {
p.Store.Availability.Since = state.FormatTime(p.now())
}
Expand Down
3 changes: 3 additions & 0 deletions internal/pw/client.go
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,8 @@ type Options struct {
Token string
MinDelay time.Duration
Logger *slog.Logger
// OnTry is passed to the HTTP client made when HTTP is nil.
OnTry func(failed bool)

HTTP *httpx.Client
}
Expand Down Expand Up @@ -83,6 +85,7 @@ func New(opts Options) (*Client, error) {
Authorization: auth,
AuthHost: u.Hostname(),
Logger: opts.Logger,
OnTry: opts.OnTry,
})
}
base := strings.TrimRight(opts.APIURL, "/")
Expand Down
20 changes: 20 additions & 0 deletions internal/pw/client_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -335,3 +335,23 @@ func TestWalkEventsFetchErrorKeepsCursor(t *testing.T) {
t.Errorf("cursor %d err %v", cursor, err)
}
}

func TestNewReportsTries(t *testing.T) {
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
w.Write([]byte(`{"id":1}`))
}))
defer srv.Close()
var tries []bool
c, err := New(Options{APIURL: srv.URL + "/api", Logger: slog.New(slog.DiscardHandler),
OnTry: func(failed bool) { tries = append(tries, failed) }})
if err != nil {
t.Fatal(err)
}
if _, err := c.GetPatch(context.Background(), 1); err != nil {
t.Fatal(err)
}
if len(tries) != 1 || tries[0] {
t.Fatalf("tries = %v", tries)
}
}
Loading