diff --git a/.env.example b/.env.example
index 4721dac..6c27465 100644
--- a/.env.example
+++ b/.env.example
@@ -22,3 +22,10 @@ UPTIME_API_URL=http://localhost:8080
# Integration tests (make test). The Redis database is flushed by the tests.
UPTIME_TEST_DATABASE_URL=postgres://uptime:uptime@localhost:5432/uptime_test?sslmode=disable
UPTIME_TEST_REDIS_URL=redis://localhost:6379/15
+
+# Status page server: hosts serving pages by slug; enable TLS for custom domains.
+UPTIME_STATUSPAGE_URL=http://localhost:8082
+UPTIME_STATUSPAGE_HOSTS=localhost
+# UPTIME_STATUSPAGE_TLS=true
+# UPTIME_ACME_EMAIL=ops@example.com
+# UPTIME_ACME_CA=https://acme-staging-v02.api.letsencrypt.org/directory
diff --git a/cmd/statuspage/main.go b/cmd/statuspage/main.go
index 7c74a50..7ae9ce7 100644
--- a/cmd/statuspage/main.go
+++ b/cmd/statuspage/main.go
@@ -4,17 +4,26 @@ package main
import (
"context"
+ "crypto/tls"
+ "errors"
"fmt"
"log/slog"
+ "net"
+ "net/http"
"os"
+ "path/filepath"
"time"
+ "github.com/caddyserver/certmagic"
"github.com/google/uuid"
+ "go.uber.org/zap"
"git.zb-server.de/ZB-Server/uptimesebi/internal/agentapi"
"git.zb-server.de/ZB-Server/uptimesebi/internal/buildinfo"
"git.zb-server.de/ZB-Server/uptimesebi/internal/config"
+ "git.zb-server.de/ZB-Server/uptimesebi/internal/i18n"
"git.zb-server.de/ZB-Server/uptimesebi/internal/platform"
+ "git.zb-server.de/ZB-Server/uptimesebi/internal/statuspage"
"git.zb-server.de/ZB-Server/uptimesebi/internal/web"
)
@@ -41,20 +50,118 @@ func run(log *slog.Logger, level *slog.LevelVar) error {
defer stop()
client := agentapi.NewClient(cfg.APIURL, cfg.Token, uuid.New(), buildinfo.Version)
- hello, err := platform.Hello(ctx, client, log)
+ if err := checkToken(ctx, client, log); err != nil {
+ return err
+ }
+ cacheDir, err := resolveCacheDir(cfg.CacheDir)
if err != nil {
return err
}
- if hello.Kind != "statuspage" {
- return fmt.Errorf("token belongs to a %s agent, not a status page server", hello.Kind)
- }
+ catalog, err := i18n.Load()
+ if err != nil {
+ return err
+ }
+ pages, err := statuspage.New(client, catalog, log, statuspage.Options{Hosts: cfg.Hosts, CacheDir: filepath.Join(cacheDir, "pages")})
+ if err != nil {
+ return err
+ }
+ apiProbe := func(ctx context.Context) error { _, err := client.Hello(ctx); return err }
health := platform.NewHealth(map[string]platform.Probe{
- "api": func(ctx context.Context) error { _, err := client.Hello(ctx); return err },
+ "pages": func(ctx context.Context) error { return pages.Ready(ctx, apiProbe) },
})
r := platform.NewRouter(log)
health.Register(r)
r.StaticFS("/static", web.Static())
+ pages.Mount(r)
+ go pages.Run(ctx)
- return platform.Serve(ctx, log, platform.NewHTTPServer(cfg.Listen, r), health, 5*time.Second, cfg.ShutdownTimeout)
+ if !cfg.TLS {
+ return platform.Serve(ctx, log, platform.NewHTTPServer(cfg.Listen, r), health, 5*time.Second, cfg.ShutdownTimeout)
+ }
+ tlsConfig, challenges, err := certificates(ctx, cfg, client, pages, filepath.Join(cacheDir, "certs"), log)
+ if err != nil {
+ return err
+ }
+ https := platform.NewHTTPServer(cfg.TLSListen, r)
+ https.TLSConfig = tlsConfig
+ plain := platform.NewHTTPServer(cfg.Listen, challenges(redirectToHTTPS(r)))
+
+ errs := make(chan error, 2)
+ go func() { errs <- platform.Serve(ctx, log, plain, health, 5*time.Second, cfg.ShutdownTimeout) }()
+ go func() { errs <- platform.ServeTLS(ctx, log, https, health, 5*time.Second, cfg.ShutdownTimeout) }()
+ err = <-errs
+ stop()
+ return errors.Join(err, <-errs)
+}
+
+// certificates sets up on-demand ACME certificates stored through the API,
+// shared by every instance of this status page server.
+func certificates(ctx context.Context, cfg config.StatusPage, client *agentapi.Client, pages *statuspage.Server, certDir string, log *slog.Logger) (*tls.Config, func(http.Handler) http.Handler, error) {
+ var magic *certmagic.Config
+ cache := certmagic.NewCache(certmagic.CacheOptions{
+ GetConfigForCert: func(certmagic.Certificate) (*certmagic.Config, error) { return magic, nil },
+ })
+ magic = certmagic.New(cache, certmagic.Config{
+ Storage: statuspage.NewCertStorage(client, certDir),
+ OnDemand: &certmagic.OnDemandConfig{DecisionFunc: pages.AllowCertificate},
+ Logger: zap.NewNop(),
+ })
+ issuer := certmagic.NewACMEIssuer(magic, certmagic.ACMEIssuer{CA: cfg.ACMECA, Email: cfg.ACMEEmail, Agreed: true})
+ magic.Issuers = []certmagic.Issuer{issuer}
+ go func() {
+ <-ctx.Done()
+ cache.Stop()
+ }()
+ tc := magic.TLSConfig()
+ tc.NextProtos = append([]string{"h2", "http/1.1"}, tc.NextProtos...)
+ log.Info("tls enabled", "ca", cfg.ACMECA, "listen", cfg.TLSListen)
+ return tc, issuer.HTTPChallengeHandler, nil
+}
+
+// redirectToHTTPS sends page requests to HTTPS but keeps health checks on
+// plain HTTP for load balancers and orchestrators.
+func redirectToHTTPS(next http.Handler) http.Handler {
+ return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ if r.URL.Path == "/healthz" || r.URL.Path == "/readyz" {
+ next.ServeHTTP(w, r)
+ return
+ }
+ host, _, err := net.SplitHostPort(r.Host)
+ if err != nil {
+ host = r.Host
+ }
+ http.Redirect(w, r, "https://"+host+r.URL.RequestURI(), http.StatusMovedPermanently)
+ })
+}
+
+// checkToken rejects tokens of the wrong kind or revoked tokens, but starts
+// anyway when the API is unreachable: cached pages must be served exactly
+// when the rest of the system has trouble.
+func checkToken(ctx context.Context, client *agentapi.Client, log *slog.Logger) error {
+ hctx, cancel := context.WithTimeout(ctx, 5*time.Second)
+ defer cancel()
+ hello, err := client.Hello(hctx)
+ switch {
+ case errors.Is(err, agentapi.ErrUnauthorized):
+ return err
+ case err != nil:
+ log.Warn("api unreachable at start; serving cached pages", "error", err)
+ return nil
+ case hello.Kind != "statuspage":
+ return fmt.Errorf("token belongs to a %s agent, not a status page server", hello.Kind)
+ }
+ log.Info("connected to api", "agent", hello.Name)
+ return nil
+}
+
+func resolveCacheDir(dir string) (string, error) {
+ if dir != "" {
+ return dir, nil
+ }
+ base, err := os.UserCacheDir()
+ if err != nil {
+ return "", fmt.Errorf("no cache directory; set UPTIME_STATUSPAGE_CACHE_DIR: %w", err)
+ }
+ return filepath.Join(base, "uptimesebi-statuspage"), nil
}
diff --git a/go.mod b/go.mod
index c932653..e9df13b 100644
--- a/go.mod
+++ b/go.mod
@@ -5,6 +5,7 @@ go 1.27.1
require (
github.com/a-h/templ v0.3.1118
github.com/caarlos0/env/v11 v11.4.2
+ github.com/caddyserver/certmagic v0.25.6
github.com/coreos/go-oidc/v3 v3.21.0
github.com/gin-gonic/gin v1.12.0
github.com/go-jose/go-jose/v4 v4.1.4
@@ -15,7 +16,9 @@ require (
github.com/pquerna/otp v1.5.0
github.com/pressly/goose/v3 v3.30.1
github.com/redis/go-redis/v9 v9.23.0
+ go.uber.org/zap v1.28.0
golang.org/x/crypto v0.59.0
+ golang.org/x/net v0.63.0
golang.org/x/oauth2 v0.38.0
golang.org/x/text v0.44.0
)
@@ -27,6 +30,7 @@ require (
github.com/bytedance/gopkg v0.1.3 // indirect
github.com/bytedance/sonic v1.15.0 // indirect
github.com/bytedance/sonic/loader v0.5.0 // indirect
+ github.com/caddyserver/zerossl v0.1.6 // indirect
github.com/cenkalti/backoff/v4 v4.3.0 // indirect
github.com/cespare/xxhash/v2 v2.3.0 // indirect
github.com/cli/browser v1.3.0 // indirect
@@ -45,9 +49,12 @@ require (
github.com/json-iterator/go v1.1.12 // indirect
github.com/klauspost/cpuid/v2 v2.4.0 // indirect
github.com/leodido/go-urn v1.5.0 // indirect
+ github.com/libdns/libdns v1.1.1 // indirect
github.com/mattn/go-colorable v0.1.16 // indirect
github.com/mattn/go-isatty v0.0.24 // indirect
github.com/mfridman/interpolate v0.2.0 // indirect
+ github.com/mholt/acmez/v3 v3.1.7 // indirect
+ github.com/miekg/dns v1.1.73 // indirect
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect
github.com/modern-go/reflect2 v1.0.2 // indirect
github.com/natefinch/atomic v1.0.1 // indirect
@@ -57,12 +64,13 @@ require (
github.com/sethvargo/go-retry v0.5.0 // indirect
github.com/twitchyliquid64/golang-asm v0.15.1 // indirect
github.com/ugorji/go/codec v1.3.1 // indirect
+ github.com/zeebo/blake3 v0.2.4 // indirect
go.mongodb.org/mongo-driver/v2 v2.5.0 // indirect
go.uber.org/atomic v1.12.0 // indirect
go.uber.org/multierr v1.11.0 // indirect
+ go.uber.org/zap/exp v0.3.0 // indirect
golang.org/x/arch v0.22.0 // indirect
golang.org/x/mod v0.43.0 // indirect
- golang.org/x/net v0.63.0 // indirect
golang.org/x/sync v0.25.0 // indirect
golang.org/x/sys v0.50.0 // indirect
golang.org/x/tools v0.52.0 // indirect
diff --git a/go.sum b/go.sum
index 21e3652..4c4b8e9 100644
--- a/go.sum
+++ b/go.sum
@@ -1,3 +1,5 @@
+code.pfad.fr/check v1.1.0 h1:GWvjdzhSEgHvEHe2uJujDcpmZoySKuHQNrZMfzfO0bE=
+code.pfad.fr/check v1.1.0/go.mod h1:NiUH13DtYsb7xp5wll0U4SXx7KhXQVCtRgdC96IPfoM=
github.com/BurntSushi/toml v1.6.0 h1:dRaEfpa2VI55EwlIW72hMRHdWouJeRF7TPYhI+AUQjk=
github.com/BurntSushi/toml v1.6.0/go.mod h1:ukJfTF/6rtPPRCnwkur4qwRxa8vTRFBF0uk2lLoLwho=
github.com/a-h/parse v0.0.42 h1:OUb8soeTG5+mRWieRyS/OyNU7Xl0+4wr4kPKKPa/WUQ=
@@ -20,6 +22,10 @@ github.com/bytedance/sonic/loader v0.5.0 h1:gXH3KVnatgY7loH5/TkeVyXPfESoqSBSBEiD
github.com/bytedance/sonic/loader v0.5.0/go.mod h1:AR4NYCk5DdzZizZ5djGqQ92eEhCCcdf5x77udYiSJRo=
github.com/caarlos0/env/v11 v11.4.2 h1:fosEVW/SjFBBzATf+buI6vsAfOzXxPrchST/RNzmBWQ=
github.com/caarlos0/env/v11 v11.4.2/go.mod h1:sH0CUPGS25jkIKlk2q4qs0c+C7y++K7W3crU70JVB/k=
+github.com/caddyserver/certmagic v0.25.6 h1:vHMtFSLKTa6kuZz6w0SnRMpQ388tSkww8ye355BgAM4=
+github.com/caddyserver/certmagic v0.25.6/go.mod h1:xq6cRNimqW+Tv91XNc5lNHs2XYTsLhQhYiH01H4AySs=
+github.com/caddyserver/zerossl v0.1.6 h1:1yrhTx5DWi43wOJPQ+Y4mVl++EPmSqqT/4REW//lsas=
+github.com/caddyserver/zerossl v0.1.6/go.mod h1:CxA0acn7oEGO6//4rtrRjYgEoa4MFw/XofZnrYwGqG4=
github.com/cenkalti/backoff/v4 v4.3.0 h1:MyRJ/UdXutAwSAT+s3wNd7MfTIcy71VQueUuFK343L8=
github.com/cenkalti/backoff/v4 v4.3.0/go.mod h1:Y3VNntkOUPxTVeUxJ/G5vcM//AlwfmyYozVcomhLiZE=
github.com/cespare/xxhash/v2 v2.3.0 h1:UL815xU9SqsFlibzuggzjXhog7bL6oX9BbNZnL2UFvs=
@@ -78,12 +84,22 @@ github.com/klauspost/cpuid/v2 v2.4.0 h1:S6Hrbc7+ywsr0r+RLapfGBHfyefhCTwEh3A0tV91
github.com/klauspost/cpuid/v2 v2.4.0/go.mod h1:19jmZ9mjzoF//ddRSUsv0zfBTJWh3QJh9FNxZTMrGxU=
github.com/leodido/go-urn v1.5.0 h1:pLqT2kq1zpHW/1D18QMjMpdtX7cekxqtJJjg5ANyWw0=
github.com/leodido/go-urn v1.5.0/go.mod h1:9BORnCDhdPBJNDEX+w1bJisa8yOKYi116VeO96s4ifE=
+github.com/letsencrypt/challtestsrv v1.4.2 h1:0ON3ldMhZyWlfVNYYpFuWRTmZNnyfiL9Hh5YzC3JVwU=
+github.com/letsencrypt/challtestsrv v1.4.2/go.mod h1:GhqMqcSoeGpYd5zX5TgwA6er/1MbWzx/o7yuuVya+Wk=
+github.com/letsencrypt/pebble/v2 v2.10.1 h1:oKHx3lgN4e5Nno2LKTMrVx+b+NkDptkO9aDireiBDGE=
+github.com/letsencrypt/pebble/v2 v2.10.1/go.mod h1:KtYhQ4YTjT5MtoCZ6RTCXlbrrz6cKyXROCuTpIUDJFY=
+github.com/libdns/libdns v1.1.1 h1:wPrHrXILoSHKWJKGd0EiAVmiJbFShguILTg9leS/P/U=
+github.com/libdns/libdns v1.1.1/go.mod h1:4Bj9+5CQiNMVGf87wjX4CY3HQJypUHRuLvlsfsZqLWQ=
github.com/mattn/go-colorable v0.1.16 h1:+2YjeAe7xP1OQbZW1jERPWWCDLlNqFNCvjiqGiAt84A=
github.com/mattn/go-colorable v0.1.16/go.mod h1:6LmQG8QLFO4G5z1gPvYEzlUgJ2wF+stgPZH1UqBm1s8=
github.com/mattn/go-isatty v0.0.24 h1:tGZZoVgT/KiqK1c8ocVLeDS8BSWMRd47J3Lbz7vsReI=
github.com/mattn/go-isatty v0.0.24/go.mod h1:nMCL3Zebbrt45jsMDgnfIwz6ydEQApk5oEI3HqDio6A=
github.com/mfridman/interpolate v0.2.0 h1:HM9ID8p6CUxoMJX+fECOtGQ2Mu7TW/GIMPyu48nnvUg=
github.com/mfridman/interpolate v0.2.0/go.mod h1:8SfDy95IaPNnIokZh9mvIppmc3fGl8fx+Gu7uusuO9Q=
+github.com/mholt/acmez/v3 v3.1.7 h1:XTqpuUcRdRoIBuDoI+M4mCnRnPTPN4rqH3Mb723Rg4U=
+github.com/mholt/acmez/v3 v3.1.7/go.mod h1:Lwv6P/czh/AOq+c99tAzP68/VP92s+8y+hDs4FCgxvo=
+github.com/miekg/dns v1.1.73 h1:uhT8nJxmTrPJYClxVxTCX+CVn6qnzSiybRk72Z6DgrE=
+github.com/miekg/dns v1.1.73/go.mod h1:RW2Obtfd5NZHvOFe3zYG0W8koWOQtAzyHaLo8vASBuQ=
github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd h1:TRLaZ9cD/w8PVh93nsPXa1VrQ6jlwL5oN8l14QlcNfg=
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=
@@ -130,16 +146,28 @@ github.com/ugorji/go/codec v1.3.1 h1:waO7eEiFDwidsBN6agj1vJQ4AG7lh2yqXyOXqhgQuyY
github.com/ugorji/go/codec v1.3.1/go.mod h1:pRBVtBSKl77K30Bv8R2P+cLSGaTtex6fsA2Wjqmfxj4=
github.com/xyproto/randomstring v1.0.5 h1:YtlWPoRdgMu3NZtP45drfy1GKoojuR7hmRcnhZqKjWU=
github.com/xyproto/randomstring v1.0.5/go.mod h1:rgmS5DeNXLivK7YprL0pY+lTuhNQW3iGxZ18UQApw/E=
+github.com/zeebo/assert v1.1.0 h1:hU1L1vLTHsnO8x8c9KAR5GmM5QscxHg5RNU5z5qbUWY=
+github.com/zeebo/assert v1.1.0/go.mod h1:Pq9JiuJQpG8JLJdtkwrJESF0Foym2/D9XMU5ciN/wJ0=
+github.com/zeebo/blake3 v0.2.4 h1:KYQPkhpRtcqh0ssGYcKLG1JYvddkEA8QwCM/yBqhaZI=
+github.com/zeebo/blake3 v0.2.4/go.mod h1:7eeQ6d2iXWRGF6npfaxl2CU+xy2Fjo2gxeyZGCRUjcE=
+github.com/zeebo/pcg v1.0.1 h1:lyqfGeWiv4ahac6ttHs+I5hwtH/+1mrhlCtVNQM2kHo=
+github.com/zeebo/pcg v1.0.1/go.mod h1:09F0S9iiKrwn9rlI5yjLkmrug154/YRW6KnnXVDM/l4=
github.com/zeebo/xxh3 v1.1.0 h1:s7DLGDK45Dyfg7++yxI0khrfwq9661w9EN78eP/UZVs=
github.com/zeebo/xxh3 v1.1.0/go.mod h1:IisAie1LELR4xhVinxWS5+zf1lA4p0MW4T+w+W07F5s=
go.mongodb.org/mongo-driver/v2 v2.5.0 h1:yXUhImUjjAInNcpTcAlPHiT7bIXhshCTL3jVBkF3xaE=
go.mongodb.org/mongo-driver/v2 v2.5.0/go.mod h1:yOI9kBsufol30iFsl1slpdq1I0eHPzybRWdyYUs8K/0=
go.uber.org/atomic v1.12.0 h1:BvcXdFKuviU4fTL/f+SxdQ5qJX/Jix8pAkgdUcb3XOE=
go.uber.org/atomic v1.12.0/go.mod h1:I6c4cg+6HCxRjfjSsYtApoFILnpc0CGUdGkXVqbYVNk=
+go.uber.org/goleak v1.3.0 h1:2K3zAYmnTNqV73imy9J1T3WC+gmCePx2hEGkimedGto=
+go.uber.org/goleak v1.3.0/go.mod h1:CoHD4mav9JJNrW/WLlf7HGZPjdw8EucARQHekz1X6bE=
go.uber.org/mock v0.6.0 h1:hyF9dfmbgIX5EfOdasqLsWD6xqpNZlXblLB/Dbnwv3Y=
go.uber.org/mock v0.6.0/go.mod h1:KiVJ4BqZJaMj4svdfmHM0AUx4NJYO8ZNpPnZn1Z+BBU=
go.uber.org/multierr v1.11.0 h1:blXXJkSxSSfBVBlC76pxqeO+LN3aDfLQo+309xJstO0=
go.uber.org/multierr v1.11.0/go.mod h1:20+QtiLqy0Nd6FdQB9TLXag12DsQkrbs3htMFfDN80Y=
+go.uber.org/zap v1.28.0 h1:IZzaP1Fv73/T/pBMLk4VutPl36uNC+OSUh3JLG3FIjo=
+go.uber.org/zap v1.28.0/go.mod h1:rDLpOi171uODNm/mxFcuYWxDsqWSAVkFdX4XojSKg/Q=
+go.uber.org/zap/exp v0.3.0 h1:6JYzdifzYkGmTdRR59oYH+Ng7k49H9qVpWwNSsGJj3U=
+go.uber.org/zap/exp v0.3.0/go.mod h1:5I384qq7XGxYyByIhHm6jg5CHkGY0nsTfbDLgDDlgJQ=
go.yaml.in/yaml/v3 v3.0.6 h1:zcDfvjXEqTQmpjniUBLc91xYJMB2c4QOFxEF/LCEckM=
go.yaml.in/yaml/v3 v3.0.6/go.mod h1:HVTZu1O7/Vkt2N+BFy8Zza+lnLsABggaTM2ZpNIGuKg=
golang.org/x/arch v0.22.0 h1:c/Zle32i5ttqRXjdLyyHZESLD/bB90DCU1g9l/0YBDI=
@@ -148,8 +176,6 @@ golang.org/x/crypto v0.59.0 h1:xS2jhqYbzNrpvkWP2YTDf4TJwBy3ykR03i8vFDxEc7c=
golang.org/x/crypto v0.59.0/go.mod h1:veDyUwATGs3c+vN3VfTbzViMGXeTBk3WyhBOkn+F/4U=
golang.org/x/mod v0.43.0 h1:MFuq5J6s35W9D3IjkwyWc9vHh0nENOrt5K8Iof4ofmg=
golang.org/x/mod v0.43.0/go.mod h1:4ec1JnuyBz5+FIVhg86UsA39YG8BpnrZdJYSNHmGzHY=
-golang.org/x/net v0.62.0 h1:18ELalfM5+XNRwzM2nYqXsZQ9ByS1uhj2O/U7+5jqRY=
-golang.org/x/net v0.62.0/go.mod h1:WgDCOTH8iwtB66T4/GfI94AHo/hhdb7Hah9NDseQfiI=
golang.org/x/net v0.63.0 h1:HCoTmNh9EpD1PpK8gBNFY4gcTY4N+KQEO8ylfIKqFJ0=
golang.org/x/net v0.63.0/go.mod h1:15JLg3IX1bLjHK264EZQEbIpTiR/KVLuo9CTRWd0pig=
golang.org/x/oauth2 v0.38.0 h1:uW7XQbcu1eoiQS7uMJvLOjPMl04bTbmY1VeRPxvbspI=
diff --git a/internal/agentapi/agentapi.go b/internal/agentapi/agentapi.go
index b1b8cd0..d9df484 100644
--- a/internal/agentapi/agentapi.go
+++ b/internal/agentapi/agentapi.go
@@ -147,6 +147,8 @@ func (c *Client) do(ctx context.Context, method, path string, in, out any) error
switch {
case resp.StatusCode == http.StatusUnauthorized:
return ErrUnauthorized
+ case resp.StatusCode == http.StatusNotFound:
+ return ErrNotFound
case resp.StatusCode >= 300:
msg, _ := io.ReadAll(io.LimitReader(resp.Body, 1024))
return fmt.Errorf("agentapi: %s %s: %d %s", method, path, resp.StatusCode, bytes.TrimSpace(msg))
diff --git a/internal/agentapi/pages.go b/internal/agentapi/pages.go
new file mode 100644
index 0000000..b74ec44
--- /dev/null
+++ b/internal/agentapi/pages.go
@@ -0,0 +1,83 @@
+package agentapi
+
+import (
+ "context"
+ "errors"
+ "net/http"
+ "net/url"
+ "time"
+)
+
+// Page states, from best to worst.
+const (
+ PageOperational = "operational"
+ PageDegraded = "degraded"
+ PageOutage = "outage"
+ PageUnknown = "unknown"
+)
+
+// Theme customizes a page.
+type Theme struct {
+ // Accent is a #rrggbb color for headings and links.
+ Accent string `json:"accent,omitempty"`
+ LogoURL string `json:"logo_url,omitempty"`
+ // CSS is appended to the page's styles.
+ CSS string `json:"css,omitempty"`
+}
+
+// Day is one bar of a component's 90-day history. Uptime is -1 without data.
+type Day struct {
+ Date string `json:"date"`
+ Uptime float64 `json:"uptime"`
+}
+
+// Component is one monitor as the public sees it. Targets, check details
+// and error messages stay private.
+type Component struct {
+ Name string `json:"name"`
+ Status string `json:"status"`
+ Uptime float64 `json:"uptime"`
+ Days []Day `json:"days"`
+}
+
+// Section groups components under a heading; the first may be unnamed.
+type Section struct {
+ Name string `json:"name"`
+ Components []Component `json:"components"`
+}
+
+// PageIncident is an incident of a listed component.
+type PageIncident struct {
+ Component string `json:"component"`
+ StartedAt time.Time `json:"started_at"`
+ ResolvedAt *time.Time `json:"resolved_at,omitempty"`
+}
+
+// PageSnapshot is everything needed to render a status page.
+type PageSnapshot struct {
+ Slug string `json:"slug"`
+ Title string `json:"title"`
+ Description string `json:"description"`
+ Theme Theme `json:"theme"`
+ Status string `json:"status"`
+ Sections []Section `json:"sections"`
+ Incidents []PageIncident `json:"incidents"`
+ GeneratedAt time.Time `json:"generated_at"`
+}
+
+// ErrNotFound means no published page matches.
+var ErrNotFound = errors.New("agentapi: not found")
+
+// Page fetches the published page for a custom domain host, or for slug if
+// host is empty.
+func (c *Client) Page(ctx context.Context, host, slug string) (PageSnapshot, error) {
+ q := url.Values{}
+ if host != "" {
+ q.Set("host", host)
+ } else {
+ q.Set("slug", slug)
+ }
+ var p PageSnapshot
+ err := c.do(ctx, http.MethodGet, "/pages?"+q.Encode(), nil, &p)
+ return p, err
+}
diff --git a/internal/agentapi/storage.go b/internal/agentapi/storage.go
new file mode 100644
index 0000000..a759276
--- /dev/null
+++ b/internal/agentapi/storage.go
@@ -0,0 +1,108 @@
+package agentapi
+
+import (
+ "bytes"
+ "context"
+ "errors"
+ "fmt"
+ "io"
+ "net/http"
+ "net/url"
+ "strconv"
+ "time"
+)
+
+// StorageInfo describes a stored key; IsTerminal is false for keys that only
+// exist as a prefix of others.
+type StorageInfo struct {
+ Key string `json:"key"`
+ Modified time.Time `json:"modified"`
+ Size int64 `json:"size"`
+ IsTerminal bool `json:"is_terminal"`
+}
+
+// ErrLocked means another instance holds a storage lock.
+var ErrLocked = errors.New("agentapi: locked")
+
+func (c *Client) raw(ctx context.Context, method, path string, body []byte) ([]byte, error) {
+ var rd io.Reader
+ if body != nil {
+ rd = bytes.NewReader(body)
+ }
+ req, err := http.NewRequestWithContext(ctx, method, c.base+"/agent/v1"+path, rd)
+ if err != nil {
+ return nil, err
+ }
+ req.Header.Set("Authorization", "Bearer "+c.token)
+ req.Header.Set(VersionHeader, strconv.Itoa(Version))
+ req.Header.Set(InstanceHeader, c.instance.String())
+ req.Header.Set(ReleaseHeader, c.release)
+ resp, err := c.hc.Do(req)
+ if err != nil {
+ return nil, err
+ }
+ defer func() { _ = resp.Body.Close() }()
+ out, err := io.ReadAll(io.LimitReader(resp.Body, 2<<20))
+ switch {
+ case resp.StatusCode == http.StatusNotFound:
+ return nil, ErrNotFound
+ case resp.StatusCode == http.StatusConflict:
+ return nil, ErrLocked
+ case resp.StatusCode == http.StatusUnauthorized:
+ return nil, ErrUnauthorized
+ case resp.StatusCode >= 300:
+ return nil, fmt.Errorf("agentapi: %s %s: %d", method, path, resp.StatusCode)
+ }
+ return out, err
+}
+
+func keyQuery(name, value string) string { return "?" + url.Values{name: {value}}.Encode() }
+
+// StorageGet returns the value of key or ErrNotFound.
+func (c *Client) StorageGet(ctx context.Context, key string) ([]byte, error) {
+ return c.raw(ctx, http.MethodGet, "/storage"+keyQuery("key", key), nil)
+}
+
+// StoragePut stores value under key.
+func (c *Client) StoragePut(ctx context.Context, key string, value []byte) error {
+ if value == nil {
+ value = []byte{}
+ }
+ _, err := c.raw(ctx, http.MethodPut, "/storage"+keyQuery("key", key), value)
+ return err
+}
+
+// StorageDelete removes key and everything below it.
+func (c *Client) StorageDelete(ctx context.Context, key string) error {
+ _, err := c.raw(ctx, http.MethodDelete, "/storage"+keyQuery("key", key), nil)
+ return err
+}
+
+// StorageStat describes key.
+func (c *Client) StorageStat(ctx context.Context, key string) (StorageInfo, error) {
+ var info StorageInfo
+ err := c.do(ctx, http.MethodGet, "/storage/stat"+keyQuery("key", key), nil, &info)
+ return info, err
+}
+
+// StorageList lists keys below prefix.
+func (c *Client) StorageList(ctx context.Context, prefix string, recursive bool) ([]string, error) {
+ var out struct {
+ Keys []string `json:"keys"`
+ }
+ q := url.Values{"prefix": {prefix}, "recursive": {strconv.FormatBool(recursive)}}
+ err := c.do(ctx, http.MethodGet, "/storage/list?"+q.Encode(), nil, &out)
+ return out.Keys, err
+}
+
+// StorageLock tries to take the lock name once.
+func (c *Client) StorageLock(ctx context.Context, name string) error {
+ _, err := c.raw(ctx, http.MethodPost, "/storage/lock"+keyQuery("name", name), nil)
+ return err
+}
+
+// StorageUnlock releases the lock name.
+func (c *Client) StorageUnlock(ctx context.Context, name string) error {
+ _, err := c.raw(ctx, http.MethodDelete, "/storage/lock"+keyQuery("name", name), nil)
+ return err
+}
diff --git a/internal/api/agent.go b/internal/api/agent.go
index a65f6a2..6ead4ea 100644
--- a/internal/api/agent.go
+++ b/internal/api/agent.go
@@ -32,6 +32,15 @@ const (
func (s *Server) mountAgentAPI(r gin.IRouter) {
g := r.Group("/agent/v1", s.agentAuth())
g.GET("/hello", s.agentHello)
+ sp := g.Group("", requireAgentKind("statuspage"))
+ sp.GET("/pages", s.agentPage)
+ sp.GET("/storage", s.storageGet)
+ sp.PUT("/storage", s.storagePut)
+ sp.DELETE("/storage", s.storageDelete)
+ sp.GET("/storage/stat", s.storageStat)
+ sp.GET("/storage/list", s.storageList)
+ sp.POST("/storage/lock", s.storageLock)
+ sp.DELETE("/storage/lock", s.storageUnlock)
checker := g.Group("", requireAgentKind("checker"))
checker.POST("/jobs", s.agentJobs)
checker.POST("/results", s.agentResults)
diff --git a/internal/api/console.go b/internal/api/console.go
index 3fd63de..deb2bfd 100644
--- a/internal/api/console.go
+++ b/internal/api/console.go
@@ -31,6 +31,8 @@ func (s *Server) registerConsole(r gin.IRouter) {
r.GET("/monitors/:id/edit", s.orgPage("monitors.edit", authz.MonitorsWrite, s.monitorEditor))
r.GET("/incidents", s.orgPage("incidents.title", authz.IncidentsRead, s.incidentsView))
r.GET("/settings/channels", s.orgPage("channels.title", authz.NotificationsRead, s.channelsView))
+ r.GET("/statuspages", s.orgPage("pages.title", "", s.statusPagesView))
+ r.GET("/statuspages/:id", s.orgPage("pages.title", "", s.statusPageEditor))
}
// dashboard is the landing page. Unlike other console pages it renders for
@@ -426,3 +428,85 @@ func (s *Server) channelsView(c *gin.Context, p *principal, page web.Page, me we
}
return web.ChannelsPage(page, me, v), nil
}
+
+func (s *Server) pageURL(p store.StatusPage) string {
+ if p.CustomDomain != nil && p.DomainVerifiedAt != nil {
+ return "https://" + *p.CustomDomain + "/"
+ }
+ return strings.TrimSuffix(s.cfg.StatusPageURL, "/") + "/" + p.Slug
+}
+
+func (s *Server) statusPagesView(c *gin.Context, p *principal, page web.Page, me web.Me) (templ.Component, error) {
+ ctx := c.Request.Context()
+ var rows []store.StatusPage
+ err := s.db.Tx(ctx, p.scope(), func(q *store.Queries) error {
+ var err error
+ rows, err = q.ListStatusPages(ctx)
+ return err
+ })
+ if err != nil {
+ return nil, err
+ }
+ v := web.PagesView{CanWrite: p.Grants.Can(authz.StatusPagesWrite)}
+ for _, r := range rows {
+ if !p.Grants.Can(authz.StatusPagesRead, pageResource(r.ID)) {
+ continue
+ }
+ v.Pages = append(v.Pages, web.PageRow{
+ ID: r.ID.String(), Title: r.Title, Slug: r.Slug, Published: r.Published,
+ URL: s.pageURL(r), Domain: deref(r.CustomDomain),
+ })
+ }
+ return web.StatusPagesPage(page, me, v), nil
+}
+
+func (s *Server) statusPageEditor(c *gin.Context, p *principal, page web.Page, me web.Me) (templ.Component, error) {
+ id, err := uuid.Parse(c.Param("id"))
+ if err != nil || !p.Grants.Can(authz.StatusPagesWrite, pageResource(id)) {
+ return notFoundPage(c)
+ }
+ ctx := c.Request.Context()
+ var (
+ row store.StatusPage
+ listed []store.StatusPageMonitorsRow
+ monitors []store.Monitor
+ )
+ err = s.db.Tx(ctx, p.scope(), func(q *store.Queries) error {
+ var err error
+ if row, err = q.GetStatusPage(ctx, id); err != nil {
+ return err
+ }
+ if listed, err = q.StatusPageMonitors(ctx, id); err != nil {
+ return err
+ }
+ monitors, err = q.ListMonitors(ctx)
+ return err
+ })
+ if errors.Is(err, pgx.ErrNoRows) {
+ return notFoundPage(c)
+ }
+ if err != nil {
+ return nil, err
+ }
+ v := viewStatusPage(row)
+ e := web.PageEditor{
+ ID: row.ID.String(), Title: row.Title, Slug: row.Slug, Description: row.Description,
+ Published: row.Published, Accent: v.Theme.Accent, LogoURL: v.Theme.LogoURL, CSS: v.Theme.CSS,
+ URL: s.pageURL(row), Domain: deref(row.CustomDomain), DomainVerified: v.DomainVerified,
+ }
+ if v.DomainRecord != nil {
+ e.RecordName, e.RecordValue = v.DomainRecord.Name, v.DomainRecord.Value
+ }
+ // Listed monitors keep their order; the rest follow alphabetically.
+ seen := map[uuid.UUID]bool{}
+ for _, l := range listed {
+ seen[l.MonitorID] = true
+ e.Monitors = append(e.Monitors, web.PageMonitorOption{ID: l.MonitorID.String(), Name: l.MonitorName, Included: true, Section: l.Section, Label: l.Label})
+ }
+ for _, m := range monitors {
+ if !seen[m.ID] {
+ e.Monitors = append(e.Monitors, web.PageMonitorOption{ID: m.ID.String(), Name: m.Name})
+ }
+ }
+ return web.StatusPageEditor(page, me, e), nil
+}
diff --git a/internal/api/export_test.go b/internal/api/export_test.go
new file mode 100644
index 0000000..479680e
--- /dev/null
+++ b/internal/api/export_test.go
@@ -0,0 +1,4 @@
+package api
+
+// LookupTXT lets tests replace DNS lookups for domain verification.
+var LookupTXT = &lookupTXT
diff --git a/internal/api/monitors.go b/internal/api/monitors.go
index 8fc4ea0..f9acae7 100644
--- a/internal/api/monitors.go
+++ b/internal/api/monitors.go
@@ -330,9 +330,13 @@ func (s *Server) RunScheduler(ctx context.Context) {
case <-ctx.Done():
return
case <-dispatch.C:
- if _, err := s.sched.Dispatch(ctx); err != nil && ctx.Err() == nil {
+ n, err := s.sched.Dispatch(ctx)
+ if err != nil && ctx.Err() == nil {
s.log.WarnContext(ctx, "dispatch failed", "error", err)
}
+ if n > 0 {
+ s.log.DebugContext(ctx, "dispatched checks", "count", n)
+ }
case <-reconcile.C:
s.reconcile(ctx)
}
@@ -345,6 +349,9 @@ func (s *Server) reconcile(ctx context.Context) {
if err != nil || !ok {
return
}
+ // Taken before reading the database: monitors upserted later survive.
+ start := time.Now()
+ defer func() { s.log.DebugContext(ctx, "schedule reconciled", "took", time.Since(start)) }()
var rows []store.ListEnabledMonitorsForScheduleRow
err = s.db.Tx(ctx, tenant.System(), func(q *store.Queries) error {
var err error
@@ -356,7 +363,7 @@ func (s *Server) reconcile(ctx context.Context) {
for i, r := range rows {
want[i] = schedule.Monitor{ID: r.ID, Interval: time.Duration(r.IntervalSeconds) * time.Second, Regions: r.Regions}
}
- err = s.sched.Reconcile(ctx, want)
+ err = s.sched.Reconcile(ctx, want, start)
}
if err != nil && ctx.Err() == nil {
s.log.WarnContext(ctx, "schedule reconciliation failed", "error", err)
diff --git a/internal/api/server.go b/internal/api/server.go
index f9141b0..1931d86 100644
--- a/internal/api/server.go
+++ b/internal/api/server.go
@@ -127,6 +127,16 @@ func (s *Server) Mount(r gin.IRouter) {
admin.POST("/agents", s.adminCreateAgent)
admin.DELETE("/agents/:id", s.adminDeleteAgent)
+ org.GET("/statuspages", s.listStatusPages)
+ org.POST("/statuspages", can(authz.StatusPagesWrite), s.createStatusPage)
+ page := org.Group("/statuspages/:id")
+ page.PUT("", canPage(authz.StatusPagesWrite), s.updateStatusPage)
+ page.DELETE("", canPage(authz.StatusPagesWrite), s.deleteStatusPage)
+ page.PUT("/monitors", canPage(authz.StatusPagesWrite), s.setPageMonitors)
+ page.PUT("/domain", canPage(authz.StatusPagesWrite), s.setPageDomain)
+ page.POST("/domain/verify", canPage(authz.StatusPagesWrite), s.verifyPageDomain)
+ page.GET("/export", canPage(authz.StatusPagesRead), s.exportStatusPage)
+
org.GET("/incidents", can(authz.IncidentsRead), s.listIncidents)
org.GET("/channels", can(authz.NotificationsRead), s.listChannels)
diff --git a/internal/api/sso_test.go b/internal/api/sso_test.go
index 50976c2..200d86d 100644
--- a/internal/api/sso_test.go
+++ b/internal/api/sso_test.go
@@ -82,6 +82,9 @@ func newEnvWith(t *testing.T, adjust func(*config.API)) *env {
t.Fatal(err)
}
log := slog.New(slog.DiscardHandler)
+ if os.Getenv("UPTIME_TEST_LOG") != "" {
+ log = slog.New(slog.NewTextHandler(os.Stderr, &slog.HandlerOptions{Level: slog.LevelDebug}))
+ }
e := &env{dbPool: pool, rdb: rdb}
r := platform.NewRouter(log)
diff --git a/internal/api/statuspages.go b/internal/api/statuspages.go
new file mode 100644
index 0000000..3d86bd8
--- /dev/null
+++ b/internal/api/statuspages.go
@@ -0,0 +1,568 @@
+package api
+
+import (
+ "context"
+ "crypto/rand"
+ "encoding/hex"
+ "encoding/json"
+ "errors"
+ "net"
+ "net/http"
+ "net/url"
+ "regexp"
+ "slices"
+ "strings"
+ "time"
+
+ "github.com/gin-gonic/gin"
+ "github.com/google/uuid"
+ "github.com/jackc/pgx/v5"
+
+ "git.zb-server.de/ZB-Server/uptimesebi/internal/agentapi"
+ "git.zb-server.de/ZB-Server/uptimesebi/internal/authz"
+ "git.zb-server.de/ZB-Server/uptimesebi/internal/store"
+ "git.zb-server.de/ZB-Server/uptimesebi/internal/tenant"
+ "git.zb-server.de/ZB-Server/uptimesebi/internal/web"
+)
+
+const (
+ historyDays = 90
+ incidentLookback = 14 * 24 * time.Hour
+ // verifyPrefix is the label under which customers publish the TXT record
+ // proving control of a custom domain.
+ verifyPrefix = "_uptimesebi."
+)
+
+var (
+ slugRE = regexp.MustCompile(`^[a-z0-9][a-z0-9-]{1,62}$`)
+ accentRE = regexp.MustCompile(`^#[0-9a-fA-F]{6}$`)
+ domainRE2 = regexp.MustCompile(`^([a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z]{2,63}$`)
+)
+
+// buildSnapshot computes what the public sees of page.
+func (s *Server) buildSnapshot(ctx context.Context, page store.StatusPage) (agentapi.PageSnapshot, error) {
+ snap := agentapi.PageSnapshot{
+ Slug: page.Slug, Title: page.Title, Description: page.Description,
+ Sections: []agentapi.Section{}, Incidents: []agentapi.PageIncident{}, GeneratedAt: time.Now(),
+ }
+ _ = json.Unmarshal(page.Theme, &snap.Theme)
+ var (
+ listed []store.StatusPageMonitorsRow
+ latest []store.LatestResultsRow
+ open []store.Incident
+ daily []store.DailyBucketsForMonitorsRow
+ incidents []store.Incident
+ )
+ now := time.Now()
+ err := s.db.Tx(ctx, tenant.Org(page.OrgID, uuid.Nil), func(q *store.Queries) error {
+ var err error
+ if listed, err = q.StatusPageMonitors(ctx, page.ID); err != nil {
+ return err
+ }
+ ids := make([]uuid.UUID, len(listed))
+ for i, m := range listed {
+ ids[i] = m.MonitorID
+ }
+ if latest, err = q.LatestResults(ctx, page.OrgID); err != nil {
+ return err
+ }
+ if open, err = q.OpenIncidents(ctx); err != nil {
+ return err
+ }
+ if daily, err = q.DailyBucketsForMonitors(ctx, store.DailyBucketsForMonitorsParams{
+ OrgID: page.OrgID, Ids: ids, Bucket: now.AddDate(0, 0, -historyDays),
+ }); err != nil {
+ return err
+ }
+ incidents, err = q.IncidentsForMonitors(ctx, store.IncidentsForMonitorsParams{Ids: ids, Since: ptr(now.Add(-incidentLookback))})
+ return err
+ })
+ if err != nil {
+ return snap, err
+ }
+ failing := map[uuid.UUID]int{}
+ reported := map[uuid.UUID]int{}
+ for _, l := range latest {
+ reported[l.MonitorID]++
+ if !l.Ok {
+ failing[l.MonitorID]++
+ }
+ }
+ down := map[uuid.UUID]bool{}
+ for _, i := range open {
+ down[i.MonitorID] = true
+ }
+ days := map[uuid.UUID][]web.Bucket{}
+ for _, d := range daily {
+ days[d.MonitorID] = append(days[d.MonitorID], web.Bucket{Start: d.Bucket, Total: d.Total, OK: d.OkCount})
+ }
+ names := map[uuid.UUID]string{}
+ worst := agentapi.PageOperational
+ allUnknown, allDown := true, len(listed) > 0
+ for _, m := range listed {
+ name := m.Label
+ if name == "" {
+ name = m.MonitorName
+ }
+ names[m.MonitorID] = name
+ comp := agentapi.Component{Name: name, Uptime: web.Uptime(days[m.MonitorID]), Days: dayHistory(days[m.MonitorID], now)}
+ switch {
+ case down[m.MonitorID]:
+ comp.Status = agentapi.PageOutage
+ case !m.Enabled || reported[m.MonitorID] == 0:
+ comp.Status = agentapi.PageUnknown
+ case failing[m.MonitorID] > 0:
+ comp.Status = agentapi.PageDegraded
+ default:
+ comp.Status = agentapi.PageOperational
+ }
+ if comp.Status != agentapi.PageUnknown {
+ allUnknown = false
+ }
+ if comp.Status != agentapi.PageOutage {
+ allDown = false
+ }
+ worst = worse(worst, comp.Status)
+ if n := len(snap.Sections); n == 0 || snap.Sections[n-1].Name != m.Section {
+ snap.Sections = append(snap.Sections, agentapi.Section{Name: m.Section})
+ }
+ last := &snap.Sections[len(snap.Sections)-1]
+ last.Components = append(last.Components, comp)
+ }
+ // A single failed component is a partial problem; only a complete
+ // failure is reported as an outage of the whole page.
+ snap.Status = worst
+ switch {
+ case allUnknown:
+ snap.Status = agentapi.PageUnknown
+ case worst == agentapi.PageOutage && !allDown:
+ snap.Status = agentapi.PageDegraded
+ }
+ for _, i := range incidents {
+ snap.Incidents = append(snap.Incidents, agentapi.PageIncident{Component: names[i.MonitorID], StartedAt: i.StartedAt, ResolvedAt: i.ResolvedAt})
+ }
+ return snap, nil
+}
+
+// worse returns the more severe state; unknown components do not make the
+// whole page look broken.
+func worse(a, b string) string {
+ rank := map[string]int{agentapi.PageOperational: 0, agentapi.PageUnknown: 0, agentapi.PageDegraded: 1, agentapi.PageOutage: 2}
+ if rank[b] > rank[a] {
+ return b
+ }
+ return a
+}
+
+func dayHistory(buckets []web.Bucket, now time.Time) []agentapi.Day {
+ byDay := map[string]web.Bucket{}
+ for _, b := range buckets {
+ byDay[b.Start.UTC().Format(time.DateOnly)] = b
+ }
+ out := make([]agentapi.Day, historyDays)
+ start := now.UTC().AddDate(0, 0, -(historyDays - 1))
+ for i := range out {
+ d := start.AddDate(0, 0, i).Format(time.DateOnly)
+ out[i] = agentapi.Day{Date: d, Uptime: -1}
+ if b, ok := byDay[d]; ok && b.Total > 0 {
+ out[i].Uptime = float64(b.OK) / float64(b.Total)
+ }
+ }
+ return out
+}
+
+// agentPage serves a page snapshot to status page servers. Org-owned
+// servers only receive their own org's pages.
+func (s *Server) agentPage(c *gin.Context) {
+ ctx := c.Request.Context()
+ var host, slug *string
+ if h := strings.ToLower(strings.TrimSpace(c.Query("host"))); h != "" {
+ host = &h
+ } else if sl := strings.ToLower(strings.TrimSpace(c.Query("slug"))); sl != "" {
+ slug = &sl
+ } else {
+ fail(c, http.StatusBadRequest, "invalid_input")
+ return
+ }
+ var page store.StatusPage
+ err := s.db.Tx(ctx, tenant.System(), func(q *store.Queries) error {
+ var err error
+ page, err = q.FindPublishedPage(ctx, store.FindPublishedPageParams{Host: host, Slug: slug})
+ return err
+ })
+ a := agentOf(c)
+ if errors.Is(err, pgx.ErrNoRows) || (err == nil && a.OrgID != nil && *a.OrgID != page.OrgID) {
+ fail(c, http.StatusNotFound, "not_found")
+ return
+ }
+ if err != nil {
+ internalError(c, err)
+ return
+ }
+ snap, err := s.buildSnapshot(ctx, page)
+ if err != nil {
+ internalError(c, err)
+ return
+ }
+ c.JSON(http.StatusOK, snap)
+}
+
+type statusPageRequest struct {
+ Slug string `json:"slug" binding:"required,max=63"`
+ Title string `json:"title" binding:"required,max=200"`
+ Description string `json:"description" binding:"max=2000"`
+ Published bool `json:"published"`
+ Theme agentapi.Theme `json:"theme"`
+}
+
+func (r *statusPageRequest) normalize() string {
+ r.Slug = strings.ToLower(strings.TrimSpace(r.Slug))
+ r.Title = strings.TrimSpace(r.Title)
+ r.Description = strings.TrimSpace(r.Description)
+ t := &r.Theme
+ t.Accent, t.LogoURL = strings.TrimSpace(t.Accent), strings.TrimSpace(t.LogoURL)
+ switch {
+ case !slugRE.MatchString(r.Slug):
+ return "invalid_slug"
+ case r.Title == "":
+ return "invalid_input"
+ case t.Accent != "" && !accentRE.MatchString(t.Accent):
+ return "invalid_theme"
+ case len(t.CSS) > 20000 || strings.Contains(t.CSS, ""):
+ // The CSS is embedded in a ")
+ } else {
+
+ }
+ if s.Theme.Accent != "" {
+ @templ.Raw("")
+ }
+ if s.Theme.CSS != "" {
+ @templ.Raw("")
+ }
+
+
+
+
+ if s.Theme.LogoURL != "" {
+
+ }
+ { s.Title }
+ if s.Description != "" {
+ { s.Description }
+ }
+
+ if !a.StaleSince.IsZero() {
+
+ { i18n.T(ctx, "page.stale", "Time", a.StaleSince.UTC().Format("2006-01-02 15:04")+" UTC") }
+
+ }
+
+ { i18n.T(ctx, "page.status."+s.Status) }
+
+ for _, sec := range s.Sections {
+
+ if sec.Name != "" {
+ { sec.Name }
+ }
+
+ for _, comp := range sec.Components {
+ -
+
+ @statusDot(PageStatus(comp.Status))
+ { comp.Name }
+ { i18n.T(ctx, "page.component."+comp.Status) }
+
+ @bars(DayBars(comp.Days), 22)
+
+ { i18n.T(ctx, "page.days_ago", "Count", len(comp.Days)) }
+ { UptimeText(comp.Uptime) }
+ { i18n.T(ctx, "page.today") }
+
+
+ }
+
+
+ }
+
+ { i18n.T(ctx, "page.incidents") }
+ if len(s.Incidents) == 0 {
+ { i18n.T(ctx, "page.no_incidents") }
+ } else {
+
+ for _, inc := range s.Incidents {
+ -
+ if inc.ResolvedAt == nil {
+ { i18n.T(ctx, "incidents.ongoing") }
+ } else {
+ { i18n.T(ctx, "incidents.resolved") }
+ }
+ { inc.Component }
+
+ { inc.StartedAt.UTC().Format("2006-01-02 15:04") }
+ if inc.ResolvedAt != nil {
+ – { inc.ResolvedAt.UTC().Format("15:04") }
+ }
+ UTC
+
+
+ }
+
+ }
+
+
+
+
+