server: split HTTP scaffolding into its own subpackage

Move server.go and interactive.go (and their tests) from the root
checker/ package into checker/server/. Plugin and builtin consumers of
the SDK now import only checker/ and no longer drag net/http,
html/template, or the form-rendering code into their artifacts: on
checker-dane.so this drops the binary by ~1.2 MB and removes 170
html/template symbols along with the net/http contribution that came
from the SDK itself.

Breaking for standalone consumers (main.go):

  NewServer(p)                  -> server.New(p)
  CheckerInteractive            -> server.Interactive
  InteractiveRelatedProviders   -> server.Siblings

Providers that only satisfy the interactive interfaces structurally
(method set match, no explicit type reference) need no source change;
only main.go has to switch its import path and the constructor name.
This commit is contained in:
nemunaire 2026-04-24 12:31:34 +07:00
commit 89cc3f112b
6 changed files with 276 additions and 240 deletions

View file

@ -0,0 +1,452 @@
// Copyright 2020-2026 The happyDomain Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package server
import (
"bytes"
"context"
"encoding/json"
"fmt"
"html/template"
"log"
"maps"
"net/http"
"time"
"git.happydns.org/checker-sdk-go/checker"
)
// Interactive is an optional interface that observation providers
// can implement to expose a human-facing web form usable standalone,
// outside of a happyDomain host. Detect support with a type assertion:
// _, ok := provider.(server.Interactive).
//
// When the provider implements it, Server binds GET and POST on /check.
// GET renders an HTML form built from RenderForm(). POST calls ParseForm
// to obtain the checker.CheckerOptions, then runs the standard pipeline
// (Collect, Evaluate, GetHTMLReport, ExtractMetrics) and renders a
// consolidated result page.
//
// Unlike /evaluate, which relies on happyDomain to fill AutoFill-backed
// options from execution context, an Interactive implementation is
// responsible for resolving whatever it needs from the human inputs
// (typically via direct DNS queries) before Collect runs.
type Interactive interface {
// RenderForm returns the fields the human must fill in to bootstrap
// a check. Typically a minimal set (domain name, nameserver to
// query, …) that ParseForm expands into the full CheckerOptions
// that Collect expects.
RenderForm() []checker.CheckerOptionField
// ParseForm reads the submitted form and returns the CheckerOptions
// ready to feed Collect. It is the checker's responsibility to do
// whatever lookups or resolutions are needed to populate fields
// that would normally be auto-filled by happyDomain. Returning an
// error causes the SDK to re-render the form with the error
// displayed.
ParseForm(r *http.Request) (checker.CheckerOptions, error)
}
// Siblings is an optional interface an interactive ObservationProvider
// can co-implement to declare sibling providers whose Collect the SDK
// runs in-process during /check. Their results are exposed as
// RelatedObservations on ObservationGetter and ReportContext, mirroring
// the cross-checker lineage a happyDomain host resolves.
//
// For each sibling the SDK seeds options from the primary and, when the
// primary implements DiscoveryPublisher, writes its entries into any
// sibling option tagged AutoFill == checker.AutoFillDiscoveryEntries.
// Sibling errors are logged and skipped so the primary result still
// reaches the user.
type Siblings interface {
RelatedProviders() []checker.ObservationProvider
}
// checkResult holds everything the result page needs to render.
type checkResult struct {
Title string
States []checker.CheckState
Metrics []checker.CheckMetric
ReportHTML string
CollectErr string
ReportErr string
MetricsErr string
}
type checkFormPage struct {
Title string
Fields []checker.CheckerOptionField
Error string
}
func (s *Server) handleCheckForm(w http.ResponseWriter, r *http.Request) {
s.renderCheckForm(w, s.interactive.RenderForm(), "")
}
func (s *Server) handleCheckSubmit(w http.ResponseWriter, r *http.Request) {
if err := r.ParseForm(); err != nil {
s.renderCheckForm(w, s.interactive.RenderForm(), fmt.Sprintf("invalid form: %v", err))
return
}
opts, err := s.interactive.ParseForm(r)
if err != nil {
s.renderCheckForm(w, s.interactive.RenderForm(), err.Error())
return
}
result := &checkResult{Title: s.checkPageTitle()}
data, err := s.provider.Collect(r.Context(), opts)
if err != nil {
result.CollectErr = err.Error()
s.renderCheckResult(w, result)
return
}
raw, err := json.Marshal(data)
if err != nil {
result.CollectErr = fmt.Sprintf("failed to marshal collected data: %v", err)
s.renderCheckResult(w, result)
return
}
related := s.collectRelatedObservations(r.Context(), opts, data)
if s.definition != nil {
obs := &mapObservationGetter{
data: map[checker.ObservationKey]json.RawMessage{
s.provider.Key(): raw,
},
related: related,
}
result.States = s.evaluateRules(r.Context(), obs, opts, nil)
}
ctx := checker.NewReportContext(raw, related)
if reporter, ok := s.provider.(checker.CheckerHTMLReporter); ok {
html, rerr := reporter.GetHTMLReport(ctx)
if rerr != nil {
result.ReportErr = rerr.Error()
} else {
result.ReportHTML = html
}
}
if reporter, ok := s.provider.(checker.CheckerMetricsReporter); ok {
metrics, merr := reporter.ExtractMetrics(ctx, time.Now())
if merr != nil {
result.MetricsErr = merr.Error()
} else {
result.Metrics = metrics
}
}
s.renderCheckResult(w, result)
}
// collectRelatedObservations runs sibling providers declared via Siblings
// and returns their results keyed by the sibling's observation key.
// Sibling errors are logged and skipped.
func (s *Server) collectRelatedObservations(ctx context.Context, opts checker.CheckerOptions, data any) map[checker.ObservationKey][]checker.RelatedObservation {
irp, ok := s.provider.(Siblings)
if !ok {
return nil
}
siblings := irp.RelatedProviders()
if len(siblings) == 0 {
return nil
}
var entries []checker.DiscoveryEntry
if dp, ok := s.provider.(checker.DiscoveryPublisher); ok {
e, err := dp.DiscoverEntries(data)
if err != nil {
log.Printf("interactive: DiscoverEntries failed: %v", err)
} else {
entries = e
}
}
related := make(map[checker.ObservationKey][]checker.RelatedObservation, len(siblings))
for _, sp := range siblings {
sOpts := cloneOptions(opts)
siblingID := ""
if dp, ok := sp.(checker.CheckerDefinitionProvider); ok {
if def := dp.Definition(); def != nil {
siblingID = def.ID
if len(entries) > 0 {
fillDiscoveryEntryOption(sOpts, def, entries)
}
}
}
sData, err := sp.Collect(ctx, sOpts)
if err != nil {
log.Printf("interactive: sibling %q Collect failed: %v", sp.Key(), err)
continue
}
raw, err := json.Marshal(sData)
if err != nil {
log.Printf("interactive: sibling %q marshal failed: %v", sp.Key(), err)
continue
}
related[sp.Key()] = append(related[sp.Key()], checker.RelatedObservation{
CheckerID: siblingID,
Key: sp.Key(),
Data: raw,
CollectedAt: time.Now(),
})
}
return related
}
func cloneOptions(opts checker.CheckerOptions) checker.CheckerOptions {
out := make(checker.CheckerOptions, len(opts))
maps.Copy(out, opts)
return out
}
// fillDiscoveryEntryOption mirrors the host's AutoFill wiring: it writes
// entries into every option in def tagged AutoFill == checker.AutoFillDiscoveryEntries.
func fillDiscoveryEntryOption(opts checker.CheckerOptions, def *checker.CheckerDefinition, entries []checker.DiscoveryEntry) {
scopes := [][]checker.CheckerOptionDocumentation{
def.Options.AdminOpts,
def.Options.UserOpts,
def.Options.DomainOpts,
def.Options.ServiceOpts,
def.Options.RunOpts,
}
for _, scope := range scopes {
for _, f := range scope {
if f.AutoFill == checker.AutoFillDiscoveryEntries {
opts[f.Id] = entries
}
}
}
}
func (s *Server) checkPageTitle() string {
if s.definition != nil && s.definition.Name != "" {
return s.definition.Name
}
return "Checker"
}
func renderHTML(w http.ResponseWriter, status int, tpl *template.Template, data any) {
var buf bytes.Buffer
if err := tpl.Execute(&buf, data); err != nil {
log.Printf("render %s: %v", tpl.Name(), err)
http.Error(w, "failed to render page", http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "text/html; charset=utf-8")
w.WriteHeader(status)
w.Write(buf.Bytes())
}
func (s *Server) renderCheckForm(w http.ResponseWriter, fields []checker.CheckerOptionField, errMsg string) {
status := http.StatusOK
if errMsg != "" {
status = http.StatusBadRequest
}
renderHTML(w, status, checkFormTemplate, checkFormPage{
Title: s.checkPageTitle(),
Fields: fields,
Error: errMsg,
})
}
func (s *Server) renderCheckResult(w http.ResponseWriter, result *checkResult) {
renderHTML(w, http.StatusOK, checkResultTemplate, result)
}
func statusClass(s checker.Status) string {
switch s {
case checker.StatusOK:
return "ok"
case checker.StatusInfo:
return "info"
case checker.StatusWarn:
return "warn"
case checker.StatusCrit:
return "crit"
case checker.StatusError:
return "error"
default:
return "unknown"
}
}
// defaultString avoids printing the literal "<nil>" for unset defaults.
func defaultString(v any) string {
if v == nil {
return ""
}
switch t := v.(type) {
case string:
return t
case bool:
if t {
return "true"
}
return ""
default:
return fmt.Sprintf("%v", v)
}
}
func defaultBool(v any) bool {
b, _ := v.(bool)
return b
}
var templateFuncs = template.FuncMap{
"statusClass": statusClass,
"statusString": checker.Status.String,
"defaultString": defaultString,
"defaultBool": defaultBool,
}
const baseCSS = `
body { font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif; max-width: 960px; margin: 2rem auto; padding: 0 1rem; color: #222; }
h1, h2 { border-bottom: 1px solid #eee; padding-bottom: 0.3rem; }
form { display: grid; gap: 1rem; }
label { display: block; font-weight: 600; margin-bottom: 0.25rem; }
.required::after { content: " *"; color: #c00; }
.desc { font-weight: normal; color: #666; font-size: 0.9rem; display: block; margin-top: 0.1rem; }
input[type=text], input[type=password], input[type=number], select, textarea {
width: 100%; padding: 0.5rem; border: 1px solid #bbb; border-radius: 4px; box-sizing: border-box; font: inherit;
}
textarea { min-height: 6rem; }
button { padding: 0.6rem 1.2rem; background: #0b63c5; color: #fff; border: 0; border-radius: 4px; font: inherit; cursor: pointer; }
button:hover { background: #084c98; }
.err { background: #fee; border: 1px solid #fbb; color: #900; padding: 0.6rem 0.8rem; border-radius: 4px; margin: 1rem 0; }
table { border-collapse: collapse; width: 100%; margin: 0.5rem 0 1.5rem; }
th, td { text-align: left; padding: 0.5rem 0.6rem; border-bottom: 1px solid #eee; vertical-align: top; }
th { background: #f7f7f7; }
.badge { display: inline-block; padding: 0.15rem 0.5rem; border-radius: 3px; font-size: 0.8rem; font-weight: 600; color: #fff; }
.badge.ok { background: #2a9d3c; }
.badge.info { background: #3277cc; }
.badge.warn { background: #d08a00; }
.badge.crit { background: #c0392b; }
.badge.error { background: #7a1f1f; }
.badge.unknown { background: #777; }
iframe.report { width: 100%; min-height: 480px; border: 1px solid #ccc; border-radius: 4px; }
.actions { margin-top: 1.5rem; }
.actions a { color: #0b63c5; text-decoration: none; }
.actions a:hover { text-decoration: underline; }
`
var checkFormTemplate = template.Must(template.New("form").Funcs(templateFuncs).Parse(`<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>{{.Title}} Check</title>
<style>` + baseCSS + `</style>
</head>
<body>
<h1>{{.Title}}</h1>
{{if .Error}}<div class="err">{{.Error}}</div>{{end}}
<form method="POST" action="/check">
{{range .Fields}}{{if not .Hide}}
<div>
<label for="{{.Id}}" class="{{if .Required}}required{{end}}">{{if .Label}}{{.Label}}{{else}}{{.Id}}{{end}}
{{if .Description}}<span class="desc">{{.Description}}</span>{{end}}
</label>
{{if .Choices}}
<select id="{{.Id}}" name="{{.Id}}"{{if .Required}} required{{end}}>
{{$def := defaultString .Default}}
{{range .Choices}}<option value="{{.}}"{{if eq . $def}} selected{{end}}>{{.}}</option>{{end}}
</select>
{{else if eq .Type "bool"}}
<input type="checkbox" id="{{.Id}}" name="{{.Id}}" value="true"{{if defaultBool .Default}} checked{{end}}>
{{else if .Textarea}}
<textarea id="{{.Id}}" name="{{.Id}}" placeholder="{{.Placeholder}}"{{if .Required}} required{{end}}>{{defaultString .Default}}</textarea>
{{else if eq .Type "number"}}
<input type="number" step="any" id="{{.Id}}" name="{{.Id}}" placeholder="{{.Placeholder}}" value="{{defaultString .Default}}"{{if .Required}} required{{end}}>
{{else if eq .Type "uint"}}
<input type="number" min="0" step="1" id="{{.Id}}" name="{{.Id}}" placeholder="{{.Placeholder}}" value="{{defaultString .Default}}"{{if .Required}} required{{end}}>
{{else if .Secret}}
<input type="password" id="{{.Id}}" name="{{.Id}}" placeholder="{{.Placeholder}}"{{if .Required}} required{{end}}>
{{else}}
<input type="text" id="{{.Id}}" name="{{.Id}}" placeholder="{{.Placeholder}}" value="{{defaultString .Default}}"{{if .Required}} required{{end}}>
{{end}}
</div>
{{end}}{{end}}
<div><button type="submit">Run check</button></div>
</form>
</body>
</html>`))
var checkResultTemplate = template.Must(template.New("result").Funcs(templateFuncs).Parse(`<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>{{.Title}} Result</title>
<style>` + baseCSS + `</style>
</head>
<body>
<h1>{{.Title}}</h1>
{{if .CollectErr}}<div class="err"><strong>Collect failed:</strong> {{.CollectErr}}</div>{{end}}
{{if .States}}
<h2>Check states</h2>
<table>
<thead><tr><th>Status</th><th>Rule</th><th>Code</th><th>Subject</th><th>Message</th></tr></thead>
<tbody>
{{range .States}}
<tr>
<td><span class="badge {{statusClass .Status}}">{{statusString .Status}}</span></td>
<td>{{.RuleName}}</td>
<td>{{.Code}}</td>
<td>{{.Subject}}</td>
<td>{{.Message}}</td>
</tr>
{{end}}
</tbody>
</table>
{{end}}
{{if .Metrics}}
<h2>Metrics</h2>
<table>
<thead><tr><th>Name</th><th>Value</th><th>Unit</th><th>Labels</th></tr></thead>
<tbody>
{{range .Metrics}}
<tr>
<td>{{.Name}}</td>
<td>{{.Value}}</td>
<td>{{.Unit}}</td>
<td>{{range $k, $v := .Labels}}{{$k}}={{$v}} {{end}}</td>
</tr>
{{end}}
</tbody>
</table>
{{end}}
{{if .MetricsErr}}<div class="err"><strong>Metrics error:</strong> {{.MetricsErr}}</div>{{end}}
{{if .ReportHTML}}
<h2>Report</h2>
<iframe class="report" sandbox srcdoc="{{.ReportHTML}}"></iframe>
{{end}}
{{if .ReportErr}}<div class="err"><strong>Report error:</strong> {{.ReportErr}}</div>{{end}}
<div class="actions"><a href="/check"> Run another check</a></div>
</body>
</html>`))

View file

@ -0,0 +1,380 @@
// Copyright 2020-2026 The happyDomain Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package server
import (
"context"
"errors"
"net/http"
"net/http/httptest"
"net/url"
"strings"
"testing"
"git.happydns.org/checker-sdk-go/checker"
)
// interactiveProvider embeds testProvider and adds Interactive.
type interactiveProvider struct {
*testProvider
fields []checker.CheckerOptionField
parseFn func(r *http.Request) (checker.CheckerOptions, error)
parseErr error
}
func (p *interactiveProvider) RenderForm() []checker.CheckerOptionField {
return p.fields
}
func (p *interactiveProvider) ParseForm(r *http.Request) (checker.CheckerOptions, error) {
if p.parseErr != nil {
return nil, p.parseErr
}
if p.parseFn != nil {
return p.parseFn(r)
}
return checker.CheckerOptions{"domain": r.FormValue("domain")}, nil
}
func postForm(handler http.Handler, path string, values url.Values) *httptest.ResponseRecorder {
req := httptest.NewRequest("POST", path, strings.NewReader(values.Encode()))
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
rec := httptest.NewRecorder()
handler.ServeHTTP(rec, req)
return rec
}
// minimalProvider implements only ObservationProvider.
type minimalProvider struct{ key checker.ObservationKey }
func (m *minimalProvider) Key() checker.ObservationKey { return m.key }
func (m *minimalProvider) Collect(ctx context.Context, opts checker.CheckerOptions) (any, error) {
return nil, nil
}
func TestCheck_NotRegistered_WhenProviderLacksInterface(t *testing.T) {
p := &minimalProvider{key: "test"}
srv := New(p)
defer srv.Close()
rec := doRequest(srv.Handler(), "GET", "/check", nil, nil)
if rec.Code != http.StatusNotFound {
t.Fatalf("GET /check without Interactive = %d, want 404", rec.Code)
}
}
func TestCheck_Form_Renders(t *testing.T) {
p := &interactiveProvider{
testProvider: &testProvider{key: "test"},
fields: []checker.CheckerOptionField{
{Id: "domain", Type: "string", Label: "Domain name", Required: true, Placeholder: "example.com"},
{Id: "verbose", Type: "bool", Label: "Verbose", Default: true},
{Id: "flavor", Type: "string", Choices: []string{"a", "b"}, Default: "b"},
{Id: "hidden", Type: "string", Hide: true},
},
}
srv := New(p)
defer srv.Close()
rec := doRequest(srv.Handler(), "GET", "/check", nil, nil)
if rec.Code != http.StatusOK {
t.Fatalf("GET /check = %d, want 200", rec.Code)
}
body := rec.Body.String()
for _, want := range []string{
`name="domain"`,
`placeholder="example.com"`,
`Domain name`,
`type="checkbox"`,
`name="verbose"`,
` checked`,
`<select id="flavor"`,
`<option value="b" selected>`,
} {
if !strings.Contains(body, want) {
t.Errorf("form body missing %q", want)
}
}
if strings.Contains(body, `name="hidden"`) {
t.Errorf("hidden field should not be rendered")
}
}
func TestCheck_Submit_Success(t *testing.T) {
definition := &checker.CheckerDefinition{
ID: "test",
Name: "Test Checker",
Rules: []checker.CheckRule{
&dummyRule{name: "rule1", desc: "first rule"},
},
}
p := &interactiveProvider{
testProvider: &testProvider{key: "test", definition: definition},
fields: []checker.CheckerOptionField{{Id: "domain", Type: "string"}},
}
srv := New(p)
defer srv.Close()
rec := postForm(srv.Handler(), "/check", url.Values{"domain": {"example.com"}})
if rec.Code != http.StatusOK {
t.Fatalf("POST /check = %d, want 200", rec.Code)
}
body := rec.Body.String()
for _, want := range []string{
`Test Checker`,
`Check states`,
`rule1`,
`rule1 passed`,
`badge ok`,
`Metrics`,
`m1`,
`Report`,
`<iframe`,
} {
if !strings.Contains(body, want) {
t.Errorf("result body missing %q", want)
}
}
}
func TestCheck_Submit_ParseError_RerendersForm(t *testing.T) {
p := &interactiveProvider{
testProvider: &testProvider{key: "test"},
fields: []checker.CheckerOptionField{{Id: "domain", Type: "string"}},
parseErr: errors.New("domain is required"),
}
srv := New(p)
defer srv.Close()
rec := postForm(srv.Handler(), "/check", url.Values{"domain": {""}})
if rec.Code != http.StatusBadRequest {
t.Fatalf("POST /check with bad input = %d, want 400", rec.Code)
}
body := rec.Body.String()
if !strings.Contains(body, "domain is required") {
t.Errorf("body missing error message, got: %s", body)
}
if !strings.Contains(body, `name="domain"`) {
t.Errorf("form not re-rendered on error")
}
}
func TestCheck_Submit_CollectError(t *testing.T) {
p := &interactiveProvider{
testProvider: &testProvider{
key: "test",
collectFn: func(ctx context.Context, opts checker.CheckerOptions) (any, error) {
return nil, errors.New("boom")
},
},
fields: []checker.CheckerOptionField{{Id: "domain", Type: "string"}},
}
srv := New(p)
defer srv.Close()
rec := postForm(srv.Handler(), "/check", url.Values{"domain": {"x"}})
if rec.Code != http.StatusOK {
t.Fatalf("POST /check = %d, want 200 (collect failure still renders a page)", rec.Code)
}
body := rec.Body.String()
if !strings.Contains(body, "Collect failed") || !strings.Contains(body, "boom") {
t.Errorf("body missing Collect error, got: %s", body)
}
if strings.Contains(body, "Check states") {
t.Errorf("states section should not render when Collect failed")
}
}
func TestCheck_NoReporters(t *testing.T) {
// Provider implements Interactive and has a definition (so
// /evaluate-like logic runs) but no HTMLReporter / MetricsReporter.
bare := &bareInteractiveProvider{
key: "test",
def: &checker.CheckerDefinition{
ID: "test",
Rules: []checker.CheckRule{&dummyRule{name: "r", desc: "r"}},
},
}
srv := New(bare)
defer srv.Close()
rec := postForm(srv.Handler(), "/check", url.Values{"domain": {"x"}})
if rec.Code != http.StatusOK {
t.Fatalf("POST /check = %d, want 200", rec.Code)
}
body := rec.Body.String()
if !strings.Contains(body, "Check states") {
t.Errorf("body missing states section")
}
if strings.Contains(body, "<iframe") {
t.Errorf("body should not contain iframe when no HTML reporter")
}
if strings.Contains(body, "<h2>Metrics</h2>") {
t.Errorf("body should not contain metrics section when no metrics reporter")
}
}
// bareInteractiveProvider implements only the required interfaces
// (ObservationProvider, CheckerDefinitionProvider, Interactive),
// no reporters.
type bareInteractiveProvider struct {
key checker.ObservationKey
def *checker.CheckerDefinition
}
func (b *bareInteractiveProvider) Key() checker.ObservationKey { return b.key }
func (b *bareInteractiveProvider) Collect(ctx context.Context, opts checker.CheckerOptions) (any, error) {
return map[string]string{"ok": "1"}, nil
}
func (b *bareInteractiveProvider) Definition() *checker.CheckerDefinition { return b.def }
func (b *bareInteractiveProvider) RenderForm() []checker.CheckerOptionField {
return []checker.CheckerOptionField{{Id: "domain", Type: "string"}}
}
func (b *bareInteractiveProvider) ParseForm(r *http.Request) (checker.CheckerOptions, error) {
return checker.CheckerOptions{"domain": r.FormValue("domain")}, nil
}
type siblingProvider struct {
key checker.ObservationKey
id string
entriesOpt string
gotOpts checker.CheckerOptions
payload any
}
func (s *siblingProvider) Key() checker.ObservationKey { return s.key }
func (s *siblingProvider) Collect(ctx context.Context, opts checker.CheckerOptions) (any, error) {
s.gotOpts = opts
return s.payload, nil
}
func (s *siblingProvider) Definition() *checker.CheckerDefinition {
return &checker.CheckerDefinition{
ID: s.id,
Options: checker.CheckerOptionsDocumentation{
RunOpts: []checker.CheckerOptionDocumentation{
{Id: s.entriesOpt, Type: "array", AutoFill: checker.AutoFillDiscoveryEntries},
},
},
}
}
type primaryWithSibling struct {
key checker.ObservationKey
def *checker.CheckerDefinition
entries []checker.DiscoveryEntry
sibling checker.ObservationProvider
}
func (p *primaryWithSibling) Key() checker.ObservationKey { return p.key }
func (p *primaryWithSibling) Collect(ctx context.Context, opts checker.CheckerOptions) (any, error) {
return map[string]string{"primary": "ok"}, nil
}
func (p *primaryWithSibling) Definition() *checker.CheckerDefinition { return p.def }
func (p *primaryWithSibling) RenderForm() []checker.CheckerOptionField {
return []checker.CheckerOptionField{{Id: "domain", Type: "string"}}
}
func (p *primaryWithSibling) ParseForm(r *http.Request) (checker.CheckerOptions, error) {
return checker.CheckerOptions{"domain": r.FormValue("domain")}, nil
}
func (p *primaryWithSibling) DiscoverEntries(data any) ([]checker.DiscoveryEntry, error) {
return p.entries, nil
}
func (p *primaryWithSibling) RelatedProviders() []checker.ObservationProvider {
return []checker.ObservationProvider{p.sibling}
}
type relatedAssertRule struct {
key checker.ObservationKey
}
func (r *relatedAssertRule) Name() string { return "related_assert" }
func (r *relatedAssertRule) Description() string { return "" }
func (r *relatedAssertRule) Evaluate(ctx context.Context, obs checker.ObservationGetter, opts checker.CheckerOptions) []checker.CheckState {
related, err := obs.GetRelated(ctx, r.key)
if err != nil {
return []checker.CheckState{{Status: checker.StatusError, Message: err.Error()}}
}
if len(related) == 0 {
return []checker.CheckState{{Status: checker.StatusCrit, Message: "no related observation"}}
}
return []checker.CheckState{{Status: checker.StatusOK, Message: "saw related observation"}}
}
func TestCheck_Submit_RunsSiblingAndExposesRelated(t *testing.T) {
sibling := &siblingProvider{
key: "sibling_key",
id: "sibling",
entriesOpt: "endpoints",
payload: map[string]string{"sibling": "ok"},
}
entry := checker.DiscoveryEntry{Type: "fake.v1", Ref: "r1"}
primary := &primaryWithSibling{
key: "primary_key",
def: &checker.CheckerDefinition{
ID: "primary",
Rules: []checker.CheckRule{&relatedAssertRule{key: sibling.key}},
},
entries: []checker.DiscoveryEntry{entry},
sibling: sibling,
}
srv := New(primary)
defer srv.Close()
rec := postForm(srv.Handler(), "/check", url.Values{"domain": {"example.com"}})
if rec.Code != http.StatusOK {
t.Fatalf("POST /check = %d, want 200", rec.Code)
}
body := rec.Body.String()
if !strings.Contains(body, "saw related observation") {
t.Errorf("rule did not see related observation; body:\n%s", body)
}
got, ok := sibling.gotOpts[sibling.entriesOpt].([]checker.DiscoveryEntry)
if !ok {
t.Fatalf("sibling opts missing %q or wrong type: %#v", sibling.entriesOpt, sibling.gotOpts[sibling.entriesOpt])
}
if len(got) != 1 || got[0].Ref != entry.Ref {
t.Errorf("sibling saw entries %v, want [%v]", got, entry)
}
if v, _ := sibling.gotOpts["domain"].(string); v != "example.com" {
t.Errorf("sibling did not receive primary domain opt, got %q", v)
}
}
func TestCheck_Submit_NoSibling_LeavesRelatedEmpty(t *testing.T) {
p := &interactiveProvider{
testProvider: &testProvider{
key: "test",
definition: &checker.CheckerDefinition{
ID: "test",
Rules: []checker.CheckRule{&relatedAssertRule{key: "other"}},
},
},
fields: []checker.CheckerOptionField{{Id: "domain", Type: "string"}},
}
srv := New(p)
defer srv.Close()
rec := postForm(srv.Handler(), "/check", url.Values{"domain": {"example.com"}})
if rec.Code != http.StatusOK {
t.Fatalf("POST /check = %d, want 200", rec.Code)
}
body := rec.Body.String()
if !strings.Contains(body, "no related observation") {
t.Errorf("rule should have seen no related observation; body:\n%s", body)
}
}

419
checker/server/server.go Normal file
View file

@ -0,0 +1,419 @@
// Copyright 2020-2026 The happyDomain Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Package server provides the HTTP server scaffolding used by standalone
// checkers. It is separated from the core checker package so that plugin
// and builtin builds, which never expose an HTTP endpoint, do not pay the
// cost of net/http, html/template, and their transitive dependencies.
package server
import (
"context"
"encoding/json"
"fmt"
"io"
"log"
"math"
"net/http"
"runtime"
"strings"
"sync"
"sync/atomic"
"time"
"git.happydns.org/checker-sdk-go/checker"
)
// maxRequestBodySize is the maximum allowed size for incoming request bodies (1 MB).
const maxRequestBodySize = 1 << 20
// loadSampleInterval is how often the background sampler updates the
// exponentially weighted moving averages reported in HealthResponse.LoadAvg.
// 5 seconds matches the Unix kernel's loadavg cadence.
const loadSampleInterval = 5 * time.Second
// EWMA smoothing factors for 1, 5, and 15-minute windows sampled every
// loadSampleInterval. Derived as 1 - exp(-interval/window) so that the
// steady-state response to a constant InFlight of N converges to N.
var (
loadAlpha1 = 1 - math.Exp(-float64(loadSampleInterval)/float64(1*time.Minute))
loadAlpha5 = 1 - math.Exp(-float64(loadSampleInterval)/float64(5*time.Minute))
loadAlpha15 = 1 - math.Exp(-float64(loadSampleInterval)/float64(15*time.Minute))
)
// updateLoadAvg advances the three EWMAs by one tick given the current
// InFlight sample. It is a pure function to keep the sampler trivially testable.
func updateLoadAvg(prev [3]float64, sample float64) [3]float64 {
return [3]float64{
prev[0] + loadAlpha1*(sample-prev[0]),
prev[1] + loadAlpha5*(sample-prev[1]),
prev[2] + loadAlpha15*(sample-prev[2]),
}
}
// Server is a generic HTTP server for external checkers.
// It always exposes /health and /collect. If the provider implements
// checker.CheckerDefinitionProvider, it also exposes /definition and /evaluate.
// If the provider implements checker.CheckerHTMLReporter or checker.CheckerMetricsReporter,
// it also exposes /report. If the provider implements Interactive,
// it also exposes /check (a human-facing web form).
//
// Security: Server does not perform any authentication or authorization.
// It is intended to be run behind a reverse proxy or in a trusted network
// where access control is handled externally (e.g. by the happyDomain server).
type Server struct {
provider checker.ObservationProvider
definition *checker.CheckerDefinition
interactive Interactive
mux *http.ServeMux
// startTime is captured in New and used to compute uptime.
startTime time.Time
// inFlight counts work requests (/collect, /evaluate, /report) currently
// being processed. /health and /definition are not tracked.
inFlight atomic.Int64
// totalRequests is the cumulative number of work requests served.
totalRequests atomic.Uint64
// loadBits stores the 1, 5, 15-minute EWMAs of inFlight as float64 bit
// patterns (math.Float64bits) so reads and writes are tear-free and
// lock-free across the sampler goroutine and the /health handler.
loadBits [3]atomic.Uint64
// cancelSampler stops the background load-average sampler.
cancelSampler context.CancelFunc
// samplerDone is closed when the sampler goroutine returns.
samplerDone chan struct{}
// closeOnce guarantees Close is idempotent.
closeOnce sync.Once
}
// New creates a new checker HTTP server backed by the given provider.
// Additional endpoints are registered based on optional interfaces the provider implements.
//
// New also starts a background goroutine that samples the in-flight
// request count every loadSampleInterval to compute the load averages
// reported on /health. Call Close to stop it.
func New(provider checker.ObservationProvider) *Server {
ctx, cancel := context.WithCancel(context.Background())
s := &Server{
provider: provider,
startTime: time.Now(),
cancelSampler: cancel,
samplerDone: make(chan struct{}),
}
s.mux = http.NewServeMux()
s.mux.HandleFunc("GET /health", s.handleHealth)
s.mux.Handle("POST /collect", s.TrackWork(http.HandlerFunc(s.handleCollect)))
if dp, ok := provider.(checker.CheckerDefinitionProvider); ok {
if def := dp.Definition(); def != nil {
s.definition = def
s.definition.BuildRulesInfo()
s.mux.HandleFunc("GET /definition", s.handleDefinition)
s.mux.Handle("POST /evaluate", s.TrackWork(http.HandlerFunc(s.handleEvaluate)))
}
}
if _, ok := provider.(checker.CheckerHTMLReporter); ok {
s.mux.Handle("POST /report", s.TrackWork(http.HandlerFunc(s.handleReport)))
} else if _, ok := provider.(checker.CheckerMetricsReporter); ok {
s.mux.Handle("POST /report", s.TrackWork(http.HandlerFunc(s.handleReport)))
}
if ip, ok := provider.(Interactive); ok {
s.interactive = ip
s.mux.HandleFunc("GET /check", s.handleCheckForm)
s.mux.Handle("POST /check", s.TrackWork(http.HandlerFunc(s.handleCheckSubmit)))
}
go s.runSampler(ctx)
return s
}
// Handler returns the http.Handler for this server, allowing callers
// to embed it in a custom server or add middleware.
func (s *Server) Handler() http.Handler {
return requestLogger(s.mux)
}
// Handle registers an auxiliary handler on the server's mux. Must be called
// before ListenAndServe or Handler(). Custom handlers are not tracked by
// TrackWork; wrap them explicitly if you want them counted in /health load.
func (s *Server) Handle(pattern string, handler http.Handler) {
s.mux.Handle(pattern, handler)
}
// HandleFunc is the http.HandlerFunc-flavoured counterpart of Handle.
func (s *Server) HandleFunc(pattern string, handler func(http.ResponseWriter, *http.Request)) {
s.mux.HandleFunc(pattern, handler)
}
// ListenAndServe starts the HTTP server on the given address.
//
// ListenAndServe does not stop the background load-average sampler on return;
// call Close to stop it. This is not required for process-scoped usage but is
// recommended for tests and embedded lifecycles.
func (s *Server) ListenAndServe(addr string) error {
log.Printf("checker listening on %s", addr)
return http.ListenAndServe(addr, requestLogger(s.mux))
}
// Close stops the background load-average sampler goroutine. It is safe to
// call multiple times; subsequent calls are no-ops. Close does not shut down
// any underlying http.Server, callers own that lifecycle.
func (s *Server) Close() error {
s.closeOnce.Do(func() {
s.cancelSampler()
<-s.samplerDone
})
return nil
}
// TrackWork wraps a handler with in-flight and total-request accounting,
// opting custom routes into the load signal reported on /health.
func (s *Server) TrackWork(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
s.inFlight.Add(1)
s.totalRequests.Add(1)
defer s.inFlight.Add(-1)
next.ServeHTTP(w, r)
})
}
// runSampler updates the load-average EWMAs every loadSampleInterval until
// ctx is canceled. It closes s.samplerDone on exit.
func (s *Server) runSampler(ctx context.Context) {
defer close(s.samplerDone)
ticker := time.NewTicker(loadSampleInterval)
defer ticker.Stop()
for {
select {
case <-ctx.Done():
return
case <-ticker.C:
var prev [3]float64
for i := range prev {
prev[i] = math.Float64frombits(s.loadBits[i].Load())
}
next := updateLoadAvg(prev, float64(s.inFlight.Load()))
for i := range next {
s.loadBits[i].Store(math.Float64bits(next[i]))
}
}
}
}
type statusRecorder struct {
http.ResponseWriter
status int
}
func (r *statusRecorder) WriteHeader(code int) {
r.status = code
r.ResponseWriter.WriteHeader(code)
}
func requestLogger(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
start := time.Now()
rec := &statusRecorder{ResponseWriter: w, status: http.StatusOK}
next.ServeHTTP(rec, r)
log.Printf("%s %s %d %s", r.Method, r.URL.Path, rec.status, time.Since(start))
})
}
func (s *Server) handleHealth(w http.ResponseWriter, r *http.Request) {
var load [3]float64
for i := range load {
load[i] = math.Float64frombits(s.loadBits[i].Load())
}
writeJSON(w, http.StatusOK, checker.HealthResponse{
Status: "ok",
Uptime: time.Since(s.startTime).Seconds(),
NumCPU: runtime.NumCPU(),
InFlight: s.inFlight.Load(),
TotalRequests: s.totalRequests.Load(),
LoadAvg: load,
})
}
func (s *Server) handleDefinition(w http.ResponseWriter, r *http.Request) {
writeJSON(w, http.StatusOK, s.definition)
}
func (s *Server) handleCollect(w http.ResponseWriter, r *http.Request) {
var req checker.ExternalCollectRequest
if err := json.NewDecoder(io.LimitReader(r.Body, maxRequestBodySize)).Decode(&req); err != nil {
writeJSON(w, http.StatusBadRequest, checker.ExternalCollectResponse{
Error: fmt.Sprintf("invalid request body: %v", err),
})
return
}
data, err := s.provider.Collect(r.Context(), req.Options)
if err != nil {
writeJSON(w, http.StatusInternalServerError, checker.ExternalCollectResponse{
Error: err.Error(),
})
return
}
raw, err := json.Marshal(data)
if err != nil {
writeJSON(w, http.StatusInternalServerError, checker.ExternalCollectResponse{
Error: fmt.Sprintf("failed to marshal result: %v", err),
})
return
}
resp := checker.ExternalCollectResponse{Data: json.RawMessage(raw)}
// Harvest discovery entries from the native Go value, before it goes
// out of scope. No re-parse; DiscoverEntries operates on the same
// object that was just marshaled above.
if dp, ok := s.provider.(checker.DiscoveryPublisher); ok {
entries, derr := dp.DiscoverEntries(data)
if derr != nil {
log.Printf("DiscoverEntries failed: %v", derr)
} else {
resp.Entries = entries
}
}
writeJSON(w, http.StatusOK, resp)
}
// evaluateRules runs all definition rules against obs/opts, skipping any rule
// whose name maps to false in enabledRules (nil means run all).
func (s *Server) evaluateRules(ctx context.Context, obs checker.ObservationGetter, opts checker.CheckerOptions, enabledRules map[string]bool) []checker.CheckState {
var states []checker.CheckState
for _, rule := range s.definition.Rules {
if len(enabledRules) > 0 {
if enabled, ok := enabledRules[rule.Name()]; ok && !enabled {
continue
}
}
ruleStates := rule.Evaluate(ctx, obs, opts)
if len(ruleStates) == 0 {
ruleStates = []checker.CheckState{{
Status: checker.StatusUnknown,
Message: fmt.Sprintf("rule %q returned no state", rule.Name()),
}}
}
for _, state := range ruleStates {
state.RuleName = rule.Name()
states = append(states, state)
}
}
return states
}
func (s *Server) handleEvaluate(w http.ResponseWriter, r *http.Request) {
var req checker.ExternalEvaluateRequest
if err := json.NewDecoder(io.LimitReader(r.Body, maxRequestBodySize)).Decode(&req); err != nil {
writeJSON(w, http.StatusBadRequest, checker.ExternalEvaluateResponse{
Error: fmt.Sprintf("invalid request body: %v", err),
})
return
}
obs := &mapObservationGetter{data: req.Observations}
states := s.evaluateRules(r.Context(), obs, req.Options, req.EnabledRules)
writeJSON(w, http.StatusOK, checker.ExternalEvaluateResponse{States: states})
}
func (s *Server) handleReport(w http.ResponseWriter, r *http.Request) {
var req checker.ExternalReportRequest
if err := json.NewDecoder(io.LimitReader(r.Body, maxRequestBodySize)).Decode(&req); err != nil {
writeJSON(w, http.StatusBadRequest, map[string]string{
"error": fmt.Sprintf("invalid request body: %v", err),
})
return
}
accept := r.Header.Get("Accept")
if strings.Contains(accept, "text/html") {
reporter, ok := s.provider.(checker.CheckerHTMLReporter)
if !ok {
http.Error(w, "this checker does not support HTML reports", http.StatusNotImplemented)
return
}
html, err := reporter.GetHTMLReport(checker.NewReportContext(req.Data, req.Related))
if err != nil {
http.Error(w, fmt.Sprintf("failed to generate HTML report: %v", err), http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "text/html; charset=utf-8")
w.Write([]byte(html))
return
}
// Default: JSON metrics.
reporter, ok := s.provider.(checker.CheckerMetricsReporter)
if !ok {
http.Error(w, "this checker does not support metrics reports", http.StatusNotImplemented)
return
}
metrics, err := reporter.ExtractMetrics(checker.NewReportContext(req.Data, req.Related), time.Now())
if err != nil {
writeJSON(w, http.StatusInternalServerError, map[string]string{
"error": fmt.Sprintf("failed to extract metrics: %v", err),
})
return
}
writeJSON(w, http.StatusOK, metrics)
}
// mapObservationGetter implements checker.ObservationGetter backed by static maps.
// Both fields are optional: Get reads from data, GetRelated reads from
// related. Leaving related nil preserves the pre-existing "no lineage"
// behavior used by the remote /evaluate path.
type mapObservationGetter struct {
data map[checker.ObservationKey]json.RawMessage
related map[checker.ObservationKey][]checker.RelatedObservation
}
func (g *mapObservationGetter) Get(ctx context.Context, key checker.ObservationKey, dest any) error {
raw, ok := g.data[key]
if !ok {
return fmt.Errorf("observation %q not available", key)
}
return json.Unmarshal(raw, dest)
}
// GetRelated returns the pre-resolved related observations for key, or nil
// when none were seeded. The remote /evaluate path leaves related nil
// because ExternalEvaluateRequest does not currently carry cross-checker
// lineage; the interactive /check path can seed it from sibling providers
// declared via Siblings.
func (g *mapObservationGetter) GetRelated(ctx context.Context, key checker.ObservationKey) ([]checker.RelatedObservation, error) {
return g.related[key], nil
}
func writeJSON(w http.ResponseWriter, status int, v any) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(status)
json.NewEncoder(w).Encode(v)
}

View file

@ -0,0 +1,568 @@
// Copyright 2020-2026 The happyDomain Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package server
import (
"bytes"
"context"
"encoding/json"
"errors"
"net/http"
"net/http/httptest"
"sync"
"testing"
"time"
"git.happydns.org/checker-sdk-go/checker"
)
// --- test doubles ---
type testProvider struct {
key checker.ObservationKey
collectFn func(ctx context.Context, opts checker.CheckerOptions) (any, error)
definition *checker.CheckerDefinition
htmlFn func(raw json.RawMessage) (string, error)
metricsFn func(raw json.RawMessage, t time.Time) ([]checker.CheckMetric, error)
}
func (p *testProvider) Key() checker.ObservationKey { return p.key }
func (p *testProvider) Collect(ctx context.Context, opts checker.CheckerOptions) (any, error) {
if p.collectFn != nil {
return p.collectFn(ctx, opts)
}
return map[string]string{"result": "ok"}, nil
}
func (p *testProvider) Definition() *checker.CheckerDefinition { return p.definition }
func (p *testProvider) GetHTMLReport(ctx checker.ReportContext) (string, error) {
if p.htmlFn != nil {
return p.htmlFn(ctx.Data())
}
return "<h1>report</h1>", nil
}
func (p *testProvider) ExtractMetrics(ctx checker.ReportContext, t time.Time) ([]checker.CheckMetric, error) {
if p.metricsFn != nil {
return p.metricsFn(ctx.Data(), t)
}
return []checker.CheckMetric{{Name: "m1", Value: 1.0, Timestamp: t}}, nil
}
// dummyRule is a minimal CheckRule for testing evaluate.
type dummyRule struct {
name string
desc string
}
func (r *dummyRule) Name() string { return r.name }
func (r *dummyRule) Description() string { return r.desc }
func (r *dummyRule) Evaluate(ctx context.Context, obs checker.ObservationGetter, opts checker.CheckerOptions) []checker.CheckState {
return []checker.CheckState{{Status: checker.StatusOK, Message: r.name + " passed"}}
}
// codedRule emits a CheckState with a pre-set Code, to verify the server
// stamps RuleName without clobbering rule-provided codes.
type codedRule struct {
name, code string
}
func (r *codedRule) Name() string { return r.name }
func (r *codedRule) Description() string { return "" }
func (r *codedRule) Evaluate(ctx context.Context, obs checker.ObservationGetter, opts checker.CheckerOptions) []checker.CheckState {
return []checker.CheckState{{Status: checker.StatusWarn, Code: r.code, Message: "coded finding"}}
}
// stubProvider is a minimal ObservationProvider that does not implement
// CheckerDefinitionProvider, used to verify conditional endpoint registration.
type stubProvider struct {
key checker.ObservationKey
}
func (s stubProvider) Key() checker.ObservationKey { return s.key }
func (s stubProvider) Collect(ctx context.Context, opts checker.CheckerOptions) (any, error) {
return nil, nil
}
// --- helpers ---
func newTestServer(p *testProvider) *Server {
return New(p)
}
func doRequest(handler http.Handler, method, path string, body any, headers map[string]string) *httptest.ResponseRecorder {
var buf bytes.Buffer
if body != nil {
json.NewEncoder(&buf).Encode(body)
}
req := httptest.NewRequest(method, path, &buf)
if body != nil {
req.Header.Set("Content-Type", "application/json")
}
for k, v := range headers {
req.Header.Set(k, v)
}
rec := httptest.NewRecorder()
handler.ServeHTTP(rec, req)
return rec
}
// --- tests ---
func TestServer_Health(t *testing.T) {
p := &testProvider{key: "test", definition: &checker.CheckerDefinition{ID: "test", Rules: []checker.CheckRule{}}}
srv := newTestServer(p)
defer srv.Close()
rec := doRequest(srv.Handler(), "GET", "/health", nil, nil)
if rec.Code != http.StatusOK {
t.Fatalf("GET /health = %d, want %d", rec.Code, http.StatusOK)
}
var resp checker.HealthResponse
if err := json.NewDecoder(rec.Body).Decode(&resp); err != nil {
t.Fatalf("decode /health: %v", err)
}
if resp.Status != "ok" {
t.Errorf("GET /health status = %q, want \"ok\"", resp.Status)
}
if resp.NumCPU <= 0 {
t.Errorf("NumCPU = %d, want > 0", resp.NumCPU)
}
if resp.Uptime < 0 {
t.Errorf("Uptime = %v, want >= 0", resp.Uptime)
}
if resp.InFlight != 0 {
t.Errorf("InFlight = %d on fresh server, want 0", resp.InFlight)
}
if resp.TotalRequests != 0 {
t.Errorf("TotalRequests = %d on fresh server, want 0", resp.TotalRequests)
}
if resp.LoadAvg != [3]float64{0, 0, 0} {
t.Errorf("LoadAvg = %v on fresh server, want all zero", resp.LoadAvg)
}
}
func TestServer_Health_TracksInFlight(t *testing.T) {
release := make(chan struct{})
var collectEntered sync.WaitGroup
p := &testProvider{
key: "test",
definition: &checker.CheckerDefinition{ID: "test", Rules: []checker.CheckRule{}},
collectFn: func(ctx context.Context, opts checker.CheckerOptions) (any, error) {
collectEntered.Done()
<-release
return map[string]string{"ok": "1"}, nil
},
}
srv := newTestServer(p)
defer srv.Close()
handler := srv.Handler()
const n = 3
collectEntered.Add(n)
var clientsDone sync.WaitGroup
clientsDone.Add(n)
for i := 0; i < n; i++ {
go func() {
defer clientsDone.Done()
doRequest(handler, "POST", "/collect", checker.ExternalCollectRequest{Key: "test"}, nil)
}()
}
// Wait for all n handlers to be inside collectFn (== all n in-flight).
collectEntered.Wait()
// Record /health mid-flight. Also hammer it to verify /health polls
// do not inflate InFlight or TotalRequests.
var mid checker.HealthResponse
for i := 0; i < 5; i++ {
rec := doRequest(handler, "GET", "/health", nil, nil)
if rec.Code != http.StatusOK {
t.Fatalf("GET /health = %d, want %d", rec.Code, http.StatusOK)
}
if err := json.NewDecoder(rec.Body).Decode(&mid); err != nil {
t.Fatalf("decode /health: %v", err)
}
}
if mid.InFlight != n {
t.Errorf("mid-flight InFlight = %d, want %d", mid.InFlight, n)
}
if mid.TotalRequests != n {
t.Errorf("mid-flight TotalRequests = %d, want %d (health polls must not count)", mid.TotalRequests, n)
}
// Release all work and wait for clients to return.
close(release)
clientsDone.Wait()
rec := doRequest(handler, "GET", "/health", nil, nil)
var after checker.HealthResponse
if err := json.NewDecoder(rec.Body).Decode(&after); err != nil {
t.Fatalf("decode /health: %v", err)
}
if after.InFlight != 0 {
t.Errorf("post-flight InFlight = %d, want 0", after.InFlight)
}
if after.TotalRequests != n {
t.Errorf("post-flight TotalRequests = %d, want %d", after.TotalRequests, n)
}
if after.Uptime < mid.Uptime {
t.Errorf("Uptime went backwards: mid=%v after=%v", mid.Uptime, after.Uptime)
}
}
func TestUpdateLoadAvg(t *testing.T) {
load := [3]float64{0, 0, 0}
for i := 0; i < 20; i++ {
load = updateLoadAvg(load, 5)
}
if !(load[0] > load[1] && load[1] > load[2]) {
t.Errorf("expected load[0] > load[1] > load[2], got %v", load)
}
for i, v := range load {
if v <= 0 {
t.Errorf("load[%d] = %v, want > 0", i, v)
}
if v >= 5 {
t.Errorf("load[%d] = %v, want < 5 (not yet converged)", i, v)
}
}
// Constant sample of zero from a non-zero state must decay toward zero.
decaying := load
for i := 0; i < 50; i++ {
decaying = updateLoadAvg(decaying, 0)
}
for i := range decaying {
if decaying[i] >= load[i] {
t.Errorf("decaying[%d] = %v, want < %v", i, decaying[i], load[i])
}
}
}
func TestServer_Close_Idempotent(t *testing.T) {
p := &testProvider{key: "test", definition: &checker.CheckerDefinition{ID: "test", Rules: []checker.CheckRule{}}}
srv := newTestServer(p)
done := make(chan error, 2)
go func() { done <- srv.Close() }()
go func() { done <- srv.Close() }()
for i := 0; i < 2; i++ {
select {
case err := <-done:
if err != nil {
t.Errorf("Close() returned %v, want nil", err)
}
case <-time.After(2 * time.Second):
t.Fatal("Close() deadlocked")
}
}
}
func TestServer_Collect_Success(t *testing.T) {
p := &testProvider{
key: "test",
definition: &checker.CheckerDefinition{ID: "test", Rules: []checker.CheckRule{}},
collectFn: func(ctx context.Context, opts checker.CheckerOptions) (any, error) {
return map[string]int{"count": 42}, nil
},
}
srv := newTestServer(p)
rec := doRequest(srv.Handler(), "POST", "/collect", checker.ExternalCollectRequest{
Key: "test",
Options: checker.CheckerOptions{"a": "b"},
}, nil)
if rec.Code != http.StatusOK {
t.Fatalf("POST /collect = %d, want %d", rec.Code, http.StatusOK)
}
var resp checker.ExternalCollectResponse
json.NewDecoder(rec.Body).Decode(&resp)
if resp.Error != "" {
t.Errorf("POST /collect error = %q, want empty", resp.Error)
}
if resp.Data == nil {
t.Fatal("POST /collect data is nil")
}
}
func TestServer_Collect_ProviderError(t *testing.T) {
p := &testProvider{
key: "test",
definition: &checker.CheckerDefinition{ID: "test", Rules: []checker.CheckRule{}},
collectFn: func(ctx context.Context, opts checker.CheckerOptions) (any, error) {
return nil, errors.New("provider failed")
},
}
srv := newTestServer(p)
rec := doRequest(srv.Handler(), "POST", "/collect", checker.ExternalCollectRequest{Key: "test"}, nil)
if rec.Code != http.StatusInternalServerError {
t.Fatalf("POST /collect = %d, want %d", rec.Code, http.StatusInternalServerError)
}
var resp checker.ExternalCollectResponse
json.NewDecoder(rec.Body).Decode(&resp)
if resp.Error == "" {
t.Error("expected error in response, got empty")
}
}
func TestServer_Collect_BadBody(t *testing.T) {
p := &testProvider{key: "test", definition: &checker.CheckerDefinition{ID: "test", Rules: []checker.CheckRule{}}}
srv := newTestServer(p)
req := httptest.NewRequest("POST", "/collect", bytes.NewBufferString("{invalid"))
rec := httptest.NewRecorder()
srv.Handler().ServeHTTP(rec, req)
if rec.Code != http.StatusBadRequest {
t.Errorf("POST /collect bad body = %d, want %d", rec.Code, http.StatusBadRequest)
}
}
func TestServer_Definition(t *testing.T) {
def := &checker.CheckerDefinition{
ID: "test-checker",
Name: "Test Checker",
Rules: []checker.CheckRule{
&dummyRule{name: "rule1", desc: "first rule"},
},
}
p := &testProvider{key: "test", definition: def}
srv := newTestServer(p)
rec := doRequest(srv.Handler(), "GET", "/definition", nil, nil)
if rec.Code != http.StatusOK {
t.Fatalf("GET /definition = %d, want %d", rec.Code, http.StatusOK)
}
var got checker.CheckerDefinition
json.NewDecoder(rec.Body).Decode(&got)
if got.ID != "test-checker" {
t.Errorf("definition ID = %q, want \"test-checker\"", got.ID)
}
if len(got.RulesInfo) != 1 {
t.Errorf("definition rules = %d, want 1", len(got.RulesInfo))
}
}
func TestServer_Evaluate(t *testing.T) {
def := &checker.CheckerDefinition{
ID: "test-checker",
Name: "Test Checker",
Rules: []checker.CheckRule{
&dummyRule{name: "rule1", desc: "first rule"},
&dummyRule{name: "rule2", desc: "second rule"},
},
}
p := &testProvider{key: "test", definition: def}
srv := newTestServer(p)
rec := doRequest(srv.Handler(), "POST", "/evaluate", checker.ExternalEvaluateRequest{
Observations: map[checker.ObservationKey]json.RawMessage{
"test": json.RawMessage(`{"count":42}`),
},
Options: checker.CheckerOptions{},
}, nil)
if rec.Code != http.StatusOK {
t.Fatalf("POST /evaluate = %d, want %d", rec.Code, http.StatusOK)
}
var resp checker.ExternalEvaluateResponse
json.NewDecoder(rec.Body).Decode(&resp)
if len(resp.States) != 2 {
t.Fatalf("evaluate states = %d, want 2", len(resp.States))
}
if resp.States[0].RuleName != "rule1" {
t.Errorf("evaluate state[0].RuleName = %q, want \"rule1\"", resp.States[0].RuleName)
}
if resp.States[0].Code != "" {
t.Errorf("evaluate state[0].Code = %q, want empty (rule did not set one)", resp.States[0].Code)
}
}
func TestServer_Evaluate_DisabledRule(t *testing.T) {
def := &checker.CheckerDefinition{
ID: "test-checker",
Rules: []checker.CheckRule{
&dummyRule{name: "rule1", desc: "first"},
&dummyRule{name: "rule2", desc: "second"},
},
}
p := &testProvider{key: "test", definition: def}
srv := newTestServer(p)
rec := doRequest(srv.Handler(), "POST", "/evaluate", checker.ExternalEvaluateRequest{
Observations: map[checker.ObservationKey]json.RawMessage{
"test": json.RawMessage(`{}`),
},
EnabledRules: map[string]bool{"rule1": false},
}, nil)
if rec.Code != http.StatusOK {
t.Fatalf("POST /evaluate = %d, want %d", rec.Code, http.StatusOK)
}
var resp checker.ExternalEvaluateResponse
json.NewDecoder(rec.Body).Decode(&resp)
if len(resp.States) != 1 {
t.Fatalf("evaluate with disabled rule: states = %d, want 1", len(resp.States))
}
if resp.States[0].RuleName != "rule2" {
t.Errorf("remaining state rule name = %q, want \"rule2\"", resp.States[0].RuleName)
}
}
func TestServer_Evaluate_RulePreservesCode(t *testing.T) {
def := &checker.CheckerDefinition{
ID: "test-checker",
Rules: []checker.CheckRule{
&codedRule{name: "ruleA", code: "too_many_lookups"},
},
}
p := &testProvider{key: "test", definition: def}
srv := newTestServer(p)
rec := doRequest(srv.Handler(), "POST", "/evaluate", checker.ExternalEvaluateRequest{
Observations: map[checker.ObservationKey]json.RawMessage{"test": json.RawMessage(`{}`)},
}, nil)
if rec.Code != http.StatusOK {
t.Fatalf("POST /evaluate = %d, want %d", rec.Code, http.StatusOK)
}
var resp checker.ExternalEvaluateResponse
json.NewDecoder(rec.Body).Decode(&resp)
if len(resp.States) != 1 {
t.Fatalf("states = %d, want 1", len(resp.States))
}
if resp.States[0].RuleName != "ruleA" {
t.Errorf("state.RuleName = %q, want \"ruleA\"", resp.States[0].RuleName)
}
if resp.States[0].Code != "too_many_lookups" {
t.Errorf("state.Code = %q, want \"too_many_lookups\" (rule-set code must be preserved)", resp.States[0].Code)
}
}
func TestServer_Report_HTML(t *testing.T) {
p := &testProvider{
key: "test",
definition: &checker.CheckerDefinition{ID: "test-checker", Rules: []checker.CheckRule{}},
htmlFn: func(raw json.RawMessage) (string, error) {
return "<p>hello</p>", nil
},
}
srv := newTestServer(p)
rec := doRequest(srv.Handler(), "POST", "/report", checker.ExternalReportRequest{
Key: "test",
Data: json.RawMessage(`{}`),
}, map[string]string{"Accept": "text/html"})
if rec.Code != http.StatusOK {
t.Fatalf("POST /report html = %d, want %d", rec.Code, http.StatusOK)
}
if ct := rec.Header().Get("Content-Type"); ct != "text/html; charset=utf-8" {
t.Errorf("Content-Type = %q, want text/html", ct)
}
if body := rec.Body.String(); body != "<p>hello</p>" {
t.Errorf("body = %q, want \"<p>hello</p>\"", body)
}
}
func TestServer_Report_Metrics(t *testing.T) {
p := &testProvider{
key: "test",
definition: &checker.CheckerDefinition{ID: "test-checker", Rules: []checker.CheckRule{}},
}
srv := newTestServer(p)
rec := doRequest(srv.Handler(), "POST", "/report", checker.ExternalReportRequest{
Key: "test",
Data: json.RawMessage(`{}`),
}, map[string]string{"Accept": "application/json"})
if rec.Code != http.StatusOK {
t.Fatalf("POST /report metrics = %d, want %d", rec.Code, http.StatusOK)
}
var metrics []checker.CheckMetric
json.NewDecoder(rec.Body).Decode(&metrics)
if len(metrics) != 1 {
t.Errorf("metrics count = %d, want 1", len(metrics))
}
}
// TestServer_Report_Related verifies the remote /report path wires
// ExternalReportRequest.Related through to the provider's ReportContext,
// the fix for the "remote checkers can't see related observations" gap.
func TestServer_Report_Related(t *testing.T) {
var gotRelated []checker.RelatedObservation
p := &testProvider{
key: "test",
definition: &checker.CheckerDefinition{ID: "test-checker", Rules: []checker.CheckRule{}},
}
// Replace htmlFn with one that peeks at a related key. We can't do that
// directly through testProvider's htmlFn (which only sees raw), so
// bind to GetHTMLReport via an inline wrapper: use a per-test provider
// that captures the ReportContext before delegating to the template.
srv := New(&relatedPeekingProvider{
base: p,
target: &gotRelated,
})
defer srv.Close()
req := checker.ExternalReportRequest{
Key: "test",
Data: json.RawMessage(`{}`),
Related: map[checker.ObservationKey][]checker.RelatedObservation{
"tls_probes": {
{CheckerID: "tls", Key: "tls_probes", Data: json.RawMessage(`{"ok":true}`), Ref: "ep-1"},
},
},
}
rec := doRequest(srv.Handler(), "POST", "/report", req, map[string]string{"Accept": "text/html"})
if rec.Code != http.StatusOK {
t.Fatalf("POST /report = %d, want 200", rec.Code)
}
if len(gotRelated) != 1 {
t.Fatalf("provider saw %d related observations, want 1", len(gotRelated))
}
if gotRelated[0].CheckerID != "tls" || string(gotRelated[0].Data) != `{"ok":true}` {
t.Errorf("related mismatch: got %+v", gotRelated[0])
}
}
// relatedPeekingProvider forwards to a base testProvider but copies the
// Related("tls_probes") slice observed at GetHTMLReport time into target.
type relatedPeekingProvider struct {
base *testProvider
target *[]checker.RelatedObservation
}
func (p *relatedPeekingProvider) Key() checker.ObservationKey { return p.base.Key() }
func (p *relatedPeekingProvider) Collect(ctx context.Context, opts checker.CheckerOptions) (any, error) {
return p.base.Collect(ctx, opts)
}
func (p *relatedPeekingProvider) Definition() *checker.CheckerDefinition { return p.base.definition }
func (p *relatedPeekingProvider) GetHTMLReport(ctx checker.ReportContext) (string, error) {
*p.target = ctx.Related("tls_probes")
return "<p>ok</p>", nil
}
func TestServer_Report_BadBody(t *testing.T) {
p := &testProvider{
key: "test",
definition: &checker.CheckerDefinition{ID: "test-checker", Rules: []checker.CheckRule{}},
}
srv := newTestServer(p)
req := httptest.NewRequest("POST", "/report", bytes.NewBufferString("{bad"))
rec := httptest.NewRecorder()
srv.Handler().ServeHTTP(rec, req)
if rec.Code != http.StatusBadRequest {
t.Errorf("POST /report bad body = %d, want %d", rec.Code, http.StatusBadRequest)
}
}
func TestServer_NoDefinition_NoEvaluateEndpoint(t *testing.T) {
// A provider that does NOT implement CheckerDefinitionProvider
p := &stubProvider{key: "basic"}
srv := New(p)
rec := doRequest(srv.Handler(), "POST", "/evaluate", nil, nil)
// Should 404 or 405 since /evaluate is not registered
if rec.Code == http.StatusOK {
t.Error("POST /evaluate should not be available without CheckerDefinitionProvider")
}
}