Compare commits
No files matched your search
@@ -24,6 +24,9 @@ UPTIME_SSO_ALLOW_PRIVATE_NETWORKS=auto
|
||||
# Outgoing mail, for email channels and sign-up confirmation.
|
||||
# UPTIME_SMTP_URL=smtp://user:pass@mail.example.com:587?from=uptime@example.com
|
||||
|
||||
# Prometheus metrics of the API, on a listener apart from the console's;
|
||||
# "off" switches them off.
|
||||
# UPTIME_API_METRICS_LISTEN=:9090
|
||||
# Checker and status page reach the API only. Create tokens with:
|
||||
# api agent create --kind checker --region local --name dev
|
||||
# api agent create --kind statuspage --name dev
|
||||
|
||||
@@ -17,7 +17,7 @@ It is built for teams and hosting providers: organizations with members, roles a
|
||||
- **Alerting:** incidents with webhooks (signed), email and over 100 services: chat and messengers (Slack, Discord, Microsoft Teams, Telegram, Matrix, WhatsApp gateways, Nostr, …), push (ntfy, Gotify, Pushover, …), SMS and calls (Twilio, Plivo, …), email APIs (SendGrid, Microsoft 365, …) and incident management (PagerDuty, Opsgenie, Grafana OnCall, Jira Service Management, …), plus Apprise; customers bring their own credentials. Confirmations, maintenance windows (one-off or recurring).
|
||||
- **History:** charts and SLA from one hour to a year, per region; see what the checker saw (redirect chain, timing, certificate, response body).
|
||||
- **Incident communication:** give an outage a title and post updates with a status (investigating, identified, monitoring, resolved), public on status pages or as internal notes.
|
||||
- **Status pages:** unlimited, custom domains with automatic TLS, themes, Markdown, legal notice; served from cache during outages.
|
||||
- **Status pages:** unlimited, custom domains with automatic TLS, themes, Markdown, legal notice; served from cache during outages. Each page has an RSS feed (`feed.rss`) and a read-only JSON API (`api/v1/status`, `summary`, `components`, `incidents`), and visitors can subscribe to incidents by email with double opt-in. Platform admins limit new subscribers per organization and week, and requests are rate limited per visitor.
|
||||
- **Organizations:** members, custom roles scoped to monitor groups or status pages, API tokens, OpenID Connect SSO per organization, sign-up and sign-in with providers such as Google, Microsoft or GitHub, enforced 2FA, audit log.
|
||||
- **Privacy:** GDPR data export (JSON, PDF) and deletion, also for suspended accounts; legal notice, privacy policy and terms of service, with versioned consent on sign-up and again after material changes; configurable retention, no telemetry.
|
||||
- **Operations:** three stateless binaries, horizontally scalable; TimescaleDB and Redis (Sentinel supported); OpenAPI documentation.
|
||||
@@ -125,6 +125,7 @@ All settings are environment variables; [`.env.example`](.env.example) lists the
|
||||
- `UPTIME_SIGNUP` (`first-user`, `open`, `closed`) decides who may sign up. New accounts confirm their email address before signing in (`UPTIME_SIGNUP_VERIFY`: always in the cloud edition, self-hosted when `UPTIME_SMTP_URL` is set); one account per mailbox, and at most `UPTIME_SIGNUPS_PER_IP` (default 2) a day per client address.
|
||||
- `UPTIME_TRUSTED_PROXIES` must name your reverse proxy, or client addresses in the audit log and rate limits will be the proxy's.
|
||||
- `UPTIME_RETENTION_*` set how long results, aggregates, audit entries and captured responses are kept.
|
||||
- `UPTIME_API_METRICS_LISTEN` (default `:9090`, `off` to disable) serves Prometheus metrics at `/metrics`, apart from the public listener: requests by route, dispatched checks and stored results per region, live checkers and overdue checks per region, notification deliveries, background job runs, platform totals and the database and Redis pools. Platform totals are the same on every API instance; aggregate them with `max()`. Keep the port off the internet.
|
||||
|
||||
### Docker Compose
|
||||
|
||||
@@ -151,7 +152,7 @@ helm install uptime uptimesebi/uptimesebi -n uptime --create-namespace \
|
||||
--set ingress.enabled=true --set ingress.tls.enabled=true
|
||||
```
|
||||
|
||||
Every setting can come from an existing secret instead (`existingSecret`); [`values.yaml`](deploy/helm/uptimesebi/values.yaml) explains them all. Migrations run as a hook before each install and upgrade. To try it out without a database and Redis of your own, `--set database.bundled.enabled=true --set redis.bundled.enabled=true` adds a single TimescaleDB and Redis, without backups or high availability. Pods run unprivileged with a read-only root filesystem; the API pods need amd64 nodes, checkers and status page servers run on ARM too.
|
||||
The API pods serve metrics on port 9090 (`api.metrics`); `--set api.metrics.serviceMonitor.enabled=true` adds a ServiceMonitor for the Prometheus Operator, and `api.metrics.prometheusRule.enabled=true` alert rules for a region whose checks fall behind. Every setting can come from an existing secret instead (`existingSecret`); [`values.yaml`](deploy/helm/uptimesebi/values.yaml) explains them all. Migrations run as a hook before each install and upgrade. To try it out without a database and Redis of your own, `--set database.bundled.enabled=true --set redis.bundled.enabled=true` adds a single TimescaleDB and Redis, without backups or high availability. Pods run unprivileged with a read-only root filesystem; the API pods need amd64 nodes, checkers and status page servers run on ARM too.
|
||||
|
||||
Run as many API, checker and status page instances as you need; they share no local state. The supported setups are:
|
||||
|
||||
|
||||
+28
-1
@@ -6,6 +6,7 @@ import (
|
||||
"context"
|
||||
"errors"
|
||||
"log/slog"
|
||||
"net/http"
|
||||
"os"
|
||||
"time"
|
||||
|
||||
@@ -15,6 +16,7 @@ import (
|
||||
"git.zb-server.de/ZB-Server/uptimesebi/internal/config"
|
||||
"git.zb-server.de/ZB-Server/uptimesebi/internal/datapolicy"
|
||||
"git.zb-server.de/ZB-Server/uptimesebi/internal/i18n"
|
||||
"git.zb-server.de/ZB-Server/uptimesebi/internal/metrics"
|
||||
"git.zb-server.de/ZB-Server/uptimesebi/internal/migrations"
|
||||
"git.zb-server.de/ZB-Server/uptimesebi/internal/notify"
|
||||
"git.zb-server.de/ZB-Server/uptimesebi/internal/platform"
|
||||
@@ -80,12 +82,15 @@ func run(log *slog.Logger, level *slog.LevelVar, args []string) error {
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
srv := api.New(cfg, api.Deps{Log: log, DB: tenant.New(deps.DB), Redis: deps.Redis, Keys: keys, Catalog: catalog})
|
||||
m := metrics.New(string(cfg.Edition))
|
||||
m.Register(metrics.DBPool(deps.DB), metrics.RedisPool(deps.Redis))
|
||||
srv := api.New(cfg, api.Deps{Log: log, DB: tenant.New(deps.DB), Redis: deps.Redis, Keys: keys, Catalog: catalog, Metrics: m})
|
||||
health := platform.NewHealth(deps.Probes())
|
||||
r := platform.NewRouter(log)
|
||||
if err := platform.TrustProxies(r, cfg.TrustedProxies); err != nil {
|
||||
return err
|
||||
}
|
||||
r.Use(m.HTTP(api.StreamingRoutes()...))
|
||||
health.Register(r)
|
||||
r.StaticFS("/static", web.Static())
|
||||
srv.Mount(r)
|
||||
@@ -97,9 +102,31 @@ func run(log *slog.Logger, level *slog.LevelVar, args []string) error {
|
||||
go srv.RunDomainWatch(ctx)
|
||||
go srv.RunHeartbeats(ctx)
|
||||
|
||||
if cfg.MetricsListen != config.MetricsOff {
|
||||
go serveMetrics(ctx, log, cfg.MetricsListen, m)
|
||||
}
|
||||
|
||||
return platform.Serve(ctx, log, platform.NewHTTPServer(cfg.Listen, r), health, 5*time.Second, cfg.ShutdownTimeout)
|
||||
}
|
||||
|
||||
// serveMetrics serves /metrics on addr, apart from the public listener,
|
||||
// until ctx ends. Failing to listen is logged but does not stop the API.
|
||||
func serveMetrics(ctx context.Context, log *slog.Logger, addr string, m *metrics.Metrics) {
|
||||
mux := http.NewServeMux()
|
||||
mux.Handle("GET /metrics", m.Handler())
|
||||
srv := platform.NewHTTPServer(addr, mux)
|
||||
go func() {
|
||||
<-ctx.Done()
|
||||
sctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
|
||||
defer cancel()
|
||||
_ = srv.Shutdown(sctx)
|
||||
}()
|
||||
log.Info("metrics listening", "addr", addr)
|
||||
if err := srv.ListenAndServe(); err != nil && !errors.Is(err, http.ErrServerClosed) {
|
||||
log.Error("serving metrics failed", "addr", addr, "error", err)
|
||||
}
|
||||
}
|
||||
|
||||
func migrate(ctx context.Context, log *slog.Logger, cfg config.API, args []string) error {
|
||||
dsn := cfg.DatabaseURL
|
||||
if dsn == "" {
|
||||
|
||||
@@ -88,6 +88,7 @@ func run(log *slog.Logger, level *slog.LevelVar) error {
|
||||
return err
|
||||
}
|
||||
health.Register(r)
|
||||
r.Use(platform.Compress())
|
||||
r.StaticFS("/static", web.Static())
|
||||
pages.Mount(r)
|
||||
go pages.Run(ctx)
|
||||
|
||||
@@ -63,9 +63,15 @@ spec:
|
||||
args: [serve]
|
||||
env:
|
||||
{{- include "uptimesebi.platformEnv" (list . $secret) | nindent 12 }}
|
||||
- name: UPTIME_API_METRICS_LISTEN
|
||||
value: {{ if .Values.api.metrics.enabled }}{{ printf ":%v" .Values.api.metrics.port | quote }}{{ else }}"off"{{ end }}
|
||||
ports:
|
||||
- name: http
|
||||
containerPort: 8080
|
||||
{{- if .Values.api.metrics.enabled }}
|
||||
- name: metrics
|
||||
containerPort: {{ .Values.api.metrics.port }}
|
||||
{{- end }}
|
||||
startupProbe:
|
||||
httpGet: {path: /healthz, port: http}
|
||||
periodSeconds: 2
|
||||
@@ -113,6 +119,11 @@ spec:
|
||||
- name: http
|
||||
port: {{ .Values.api.service.port }}
|
||||
targetPort: http
|
||||
{{- if .Values.api.metrics.enabled }}
|
||||
- name: metrics
|
||||
port: {{ .Values.api.metrics.port }}
|
||||
targetPort: metrics
|
||||
{{- end }}
|
||||
{{- if and .Values.api.podDisruptionBudget.enabled (gt (int .Values.api.replicas) 1) }}
|
||||
---
|
||||
apiVersion: policy/v1
|
||||
|
||||
@@ -0,0 +1,39 @@
|
||||
{{- if and .Values.api.metrics.enabled .Values.api.metrics.prometheusRule.enabled }}
|
||||
{{- $rule := .Values.api.metrics.prometheusRule }}
|
||||
apiVersion: monitoring.coreos.com/v1
|
||||
kind: PrometheusRule
|
||||
metadata:
|
||||
name: {{ include "uptimesebi.fullname" . }}-api
|
||||
labels:
|
||||
{{- include "uptimesebi.labels" . | nindent 4 }}
|
||||
app.kubernetes.io/component: api
|
||||
{{- with $rule.labels }}
|
||||
{{- toYaml . | nindent 4 }}
|
||||
{{- end }}
|
||||
spec:
|
||||
groups:
|
||||
- name: uptimesebi
|
||||
rules:
|
||||
# Every replica reports the same platform values, hence max().
|
||||
- alert: UptimeSebiRegionBehind
|
||||
expr: max by (region) (uptimesebi_checks_overdue) > 0
|
||||
for: {{ $rule.regionBehindFor }}
|
||||
labels:
|
||||
severity: {{ $rule.severity }}
|
||||
annotations:
|
||||
summary: "Region {{ "{{ $labels.region }}" }} falls behind its checks"
|
||||
description: >-
|
||||
{{ "{{ $value }}" }} checks of region {{ "{{ $labels.region }}" }} are more than
|
||||
10 seconds overdue: no checker of the region is live, or its
|
||||
checkers cannot take the work in time.
|
||||
- alert: UptimeSebiPlatformMetricsFailing
|
||||
expr: max(uptimesebi_platform_metrics_error) > 0
|
||||
for: 10m
|
||||
labels:
|
||||
severity: {{ $rule.severity }}
|
||||
annotations:
|
||||
summary: UptimeSebi cannot read its platform metrics
|
||||
description: >-
|
||||
The API fails to read the database or Redis for its platform
|
||||
metrics, so UptimeSebiRegionBehind sees stale values.
|
||||
{{- end }}
|
||||
@@ -0,0 +1,20 @@
|
||||
{{- if and .Values.api.metrics.enabled .Values.api.metrics.serviceMonitor.enabled }}
|
||||
apiVersion: monitoring.coreos.com/v1
|
||||
kind: ServiceMonitor
|
||||
metadata:
|
||||
name: {{ include "uptimesebi.fullname" . }}-api
|
||||
labels:
|
||||
{{- include "uptimesebi.labels" . | nindent 4 }}
|
||||
app.kubernetes.io/component: api
|
||||
{{- with .Values.api.metrics.serviceMonitor.labels }}
|
||||
{{- toYaml . | nindent 4 }}
|
||||
{{- end }}
|
||||
spec:
|
||||
selector:
|
||||
matchLabels:
|
||||
{{- include "uptimesebi.selector" (list . "api") | nindent 6 }}
|
||||
endpoints:
|
||||
- port: metrics
|
||||
path: /metrics
|
||||
interval: {{ .Values.api.metrics.serviceMonitor.interval }}
|
||||
{{- end }}
|
||||
@@ -126,6 +126,28 @@ api:
|
||||
service:
|
||||
type: ClusterIP
|
||||
port: 8080
|
||||
# Prometheus metrics on a port of their own, which the ingress never
|
||||
# exposes.
|
||||
metrics:
|
||||
enabled: true
|
||||
port: 9090
|
||||
# A ServiceMonitor for the Prometheus Operator (kube-prometheus-stack).
|
||||
serviceMonitor:
|
||||
enabled: false
|
||||
interval: 30s
|
||||
# Extra labels, for a Prometheus that selects ServiceMonitors by label.
|
||||
labels: {}
|
||||
# Alert rules for the Prometheus Operator: a region whose checks fall
|
||||
# behind, and platform metrics that cannot be read. Needs the
|
||||
# ServiceMonitor or another scrape of the metrics.
|
||||
prometheusRule:
|
||||
enabled: false
|
||||
# How long checks must stay overdue before the alert fires.
|
||||
regionBehindFor: 5m
|
||||
severity: warning
|
||||
# Extra labels, for a Prometheus that selects rules by label, like
|
||||
# release: <name> with kube-prometheus-stack.
|
||||
labels: {}
|
||||
# The API image is built for amd64 only; checkers and status page servers
|
||||
# run on arm64 and 32-bit ARM too. Also used by the migration job.
|
||||
nodeSelector:
|
||||
|
||||
@@ -23,6 +23,7 @@ require (
|
||||
github.com/nicksnyder/go-i18n/v2 v2.7.0
|
||||
github.com/pquerna/otp v1.5.0
|
||||
github.com/pressly/goose/v3 v3.30.1
|
||||
github.com/prometheus/client_golang v1.25.0
|
||||
github.com/rabbitmq/amqp091-go v1.17.0
|
||||
github.com/redis/go-redis/v9 v9.23.0
|
||||
github.com/twmb/franz-go v1.22.3
|
||||
@@ -32,6 +33,7 @@ require (
|
||||
go.uber.org/zap v1.28.0
|
||||
golang.org/x/crypto v0.59.0
|
||||
golang.org/x/crypto/x509roots/fallback v0.0.0-20261123165210-6c21c5864259
|
||||
golang.org/x/image v0.25.0
|
||||
golang.org/x/net v0.63.0
|
||||
golang.org/x/oauth2 v0.38.0
|
||||
golang.org/x/sync v0.25.0
|
||||
@@ -45,6 +47,7 @@ require (
|
||||
github.com/ImVexed/fasturl v0.0.0-20230304231329-4e41488060f3 // indirect
|
||||
github.com/a-h/parse v0.0.42 // indirect
|
||||
github.com/andybalholm/brotli v1.3.0 // indirect
|
||||
github.com/beorn7/perks v1.0.1 // indirect
|
||||
github.com/boombuler/barcode v1.0.1-0.20190219062509-6c824513bacc // indirect
|
||||
github.com/btcsuite/btcd/btcec/v2 v2.3.4 // indirect
|
||||
github.com/btcsuite/btcd/btcutil v1.1.5 // indirect
|
||||
@@ -79,6 +82,7 @@ require (
|
||||
github.com/json-iterator/go v1.1.12 // indirect
|
||||
github.com/klauspost/compress v1.20.4 // indirect
|
||||
github.com/klauspost/cpuid/v2 v2.4.0 // indirect
|
||||
github.com/kylelemons/godebug v1.1.0 // indirect
|
||||
github.com/leodido/go-urn v1.5.0 // indirect
|
||||
github.com/libdns/libdns v1.1.1 // indirect
|
||||
github.com/mailru/easyjson v0.9.0 // indirect
|
||||
@@ -89,11 +93,15 @@ require (
|
||||
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/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822 // indirect
|
||||
github.com/natefinch/atomic v1.0.1 // indirect
|
||||
github.com/opencontainers/go-digest v1.0.0 // indirect
|
||||
github.com/opencontainers/image-spec v1.1.1 // indirect
|
||||
github.com/pelletier/go-toml/v2 v2.2.4 // indirect
|
||||
github.com/pierrec/lz4/v4 v4.1.33 // indirect
|
||||
github.com/prometheus/client_model v0.6.3 // indirect
|
||||
github.com/prometheus/common v0.72.0 // indirect
|
||||
github.com/prometheus/procfs v0.23.0 // indirect
|
||||
github.com/puzpuzpuz/xsync/v3 v3.5.1 // indirect
|
||||
github.com/quic-go/qpack v0.6.0 // indirect
|
||||
github.com/quic-go/quic-go v0.59.0 // indirect
|
||||
|
||||
@@ -25,6 +25,8 @@ github.com/a-h/templ v0.3.1118/go.mod h1:ttKggixbDULrwkJzfEO5fa4IPGTKiRt3qP09zjP
|
||||
github.com/aead/siphash v1.0.1/go.mod h1:Nywa3cDsYNNK3gaciGTWPwHt0wlpNV15vwmswBAUSII=
|
||||
github.com/andybalholm/brotli v1.3.0 h1:IdkhjSe/+34U+fP7FSR2Q6Poj1hnHUa2GoWmzXJd6qY=
|
||||
github.com/andybalholm/brotli v1.3.0/go.mod h1:rzTDkvFWvIrjDXZHkuS16NPggd91W3kUSvPlQ1pLaKY=
|
||||
github.com/beorn7/perks v1.0.1 h1:VlbKKnNfV8bJzeqoa4cOKqO6bYr3WgKZxO8Z16+hsOM=
|
||||
github.com/beorn7/perks v1.0.1/go.mod h1:G2ZrVWU2WbWT9wwq4/hrbKbnv/1ERSJQ0ibhJ6rlkpw=
|
||||
github.com/boombuler/barcode v1.0.1-0.20190219062509-6c824513bacc h1:biVzkmvwrH8WK8raXaxBx6fRVTlJILwEwQGL1I/ByEI=
|
||||
github.com/boombuler/barcode v1.0.1-0.20190219062509-6c824513bacc/go.mod h1:paBWMcWSl3LHKBqUq+rly7CNSldXjb2rDl3JlRe0mD8=
|
||||
github.com/bsm/ginkgo/v2 v2.12.0 h1:Ny8MWAHyOepLGlLKYmXG4IEkioBysk6GpaRTLC8zwWs=
|
||||
@@ -216,6 +218,8 @@ github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd h1:TRLaZ9cD/w
|
||||
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=
|
||||
github.com/modern-go/reflect2 v1.0.2 h1:xBagoLtFs94CBntxluKeaWgTMpvLxC4ur3nMaC9Gz0M=
|
||||
github.com/modern-go/reflect2 v1.0.2/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk=
|
||||
github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822 h1:C3w9PqII01/Oq1c1nUAm88MOHcQC9l5mIlSMApZMrHA=
|
||||
github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822/go.mod h1:+n7T8mK8HuQTcFwEeznm/DIxMOiR9yIdICNftLE1DvQ=
|
||||
github.com/natefinch/atomic v1.0.1 h1:ZPYKxkqQOx3KZ+RsbnP/YsgvxWQPGxjC0oBt2AhwV0A=
|
||||
github.com/natefinch/atomic v1.0.1/go.mod h1:N/D/ELrljoqDyT3rZrsUmtsuzvHkeB/wWjHV22AZRbM=
|
||||
github.com/nbd-wtf/go-nostr v0.52.3 h1:Xd87pXfJEJRXHpM+fLjQQln8dBNNaoPA10V7BbyP4KI=
|
||||
@@ -248,6 +252,14 @@ github.com/pquerna/otp v1.5.0 h1:NMMR+WrmaqXU4EzdGJEE1aUUI0AMRzsp96fFFWNPwxs=
|
||||
github.com/pquerna/otp v1.5.0/go.mod h1:dkJfzwRKNiegxyNb54X/3fLwhCynbMspSyWKnvi1AEg=
|
||||
github.com/pressly/goose/v3 v3.30.1 h1:KO28meBdbAUIdMbTP7bl9dp1FYZGXcYWb2O7miT09lE=
|
||||
github.com/pressly/goose/v3 v3.30.1/go.mod h1:CHGwuG2acDerUaXwz2i5T18VSauXpYDiL4WxzDvcOIM=
|
||||
github.com/prometheus/client_golang v1.25.0 h1:cDtW1TcFsMi1RJc8khwCKB4VhzwV04aKqbYtNOXuiK0=
|
||||
github.com/prometheus/client_golang v1.25.0/go.mod h1:j2X/4/kaQHLPnmyEU8zjmkndo1T317VpCIQEml8LTKk=
|
||||
github.com/prometheus/client_model v0.6.3 h1:O0jaTVAYNxTHYInEPFJt5I3+sN8zqBtVMPTB1qyxiEo=
|
||||
github.com/prometheus/client_model v0.6.3/go.mod h1:gpN5P9S7Rr6Yr92PiQ+Ixvhf6JZEkF1dnxsYL2aPBEM=
|
||||
github.com/prometheus/common v0.72.0 h1:tAYsE+sPJxIncDAobm4H5aQjmox9ZxEIIqPbiffa8G4=
|
||||
github.com/prometheus/common v0.72.0/go.mod h1:77NWqAQ2tXT7BIK40qjJdw5Acrsrg1TlHAnsQi3i6mk=
|
||||
github.com/prometheus/procfs v0.23.0 h1:ad+S6FTkzwaMgacKLM5h6bNKExS+DMH0YiUwXItH/o4=
|
||||
github.com/prometheus/procfs v0.23.0/go.mod h1:3AVXO0FqLafyYFU/V/IQRZlC8Rgqz8Dm/x6pKLK+RIk=
|
||||
github.com/puzpuzpuz/xsync/v3 v3.5.1 h1:GJYJZwO6IdxN/IKbneznS6yPkVC+c3zyY/j19c++5Fg=
|
||||
github.com/puzpuzpuz/xsync/v3 v3.5.1/go.mod h1:VjzYrABPabuM4KyBh1Ftq6u8nhwY5tBPKP9jpmh0nnA=
|
||||
github.com/quic-go/qpack v0.6.0 h1:g7W+BMYynC1LbYLSqRt8PBg5Tgwxn214ZZR34VIOjz8=
|
||||
@@ -334,6 +346,8 @@ 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/v2 v2.4.4 h1:tuyd0P+2Ont/d6e2rl3be67goVK4R6deVxCUX5vyPaQ=
|
||||
go.yaml.in/yaml/v2 v2.4.4/go.mod h1:gMZqIpDtDqOfM0uNfy0SkpRhvUryYH0Z6wdMYcacYXQ=
|
||||
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=
|
||||
@@ -349,6 +363,8 @@ golang.org/x/crypto/x509roots/fallback v0.0.0-20261123165210-6c21c5864259 h1:wXc
|
||||
golang.org/x/crypto/x509roots/fallback v0.0.0-20261123165210-6c21c5864259/go.mod h1:HPze8vhfG6fO06AM+VSvxRm4E3+5Yk375mgrJ5M2z1E=
|
||||
golang.org/x/exp v0.0.0-20261109185158-a52e3aef5920 h1:qr+tk4P56rtbVVAJDyAr5LAOiaD/XhZCoRTr4SfLxAk=
|
||||
golang.org/x/exp v0.0.0-20261109185158-a52e3aef5920/go.mod h1:J3U+E8RzytcGvwz+uJuAP4zULJ2TkAQBnmPZMexpdXs=
|
||||
golang.org/x/image v0.25.0 h1:Y6uW6rH1y5y/LK1J8BPWZtr6yZ7hrsy6hFrXjgsc2fQ=
|
||||
golang.org/x/image v0.25.0/go.mod h1:tCAmOEGthTtkalusGp1g3xa2gke8J6c2N565dTyl9Rs=
|
||||
golang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4/go.mod h1:jJ57K6gSWd91VN4djpZkiMVwK6gcyfeH4XE8wZrZaV4=
|
||||
golang.org/x/mod v0.8.0/go.mod h1:iBbtSCu2XBx23ZKBPSOrRkjjQPZFPuis4dIYUhu/chs=
|
||||
golang.org/x/mod v0.43.0 h1:MFuq5J6s35W9D3IjkwyWc9vHh0nENOrt5K8Iof4ofmg=
|
||||
|
||||
@@ -164,6 +164,8 @@ func (c *Client) doWith(ctx context.Context, method, path string, header http.He
|
||||
return ErrNotModified
|
||||
case resp.StatusCode == http.StatusTooManyRequests:
|
||||
return ErrRateLimited
|
||||
case resp.StatusCode == http.StatusUnprocessableEntity:
|
||||
return ErrInvalidInput
|
||||
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))
|
||||
|
||||
+21
-11
@@ -88,6 +88,8 @@ type Section struct {
|
||||
|
||||
// PageIncident is an incident of a listed component.
|
||||
type PageIncident struct {
|
||||
// ID identifies the incident in feeds; empty from APIs before it.
|
||||
ID string `json:"id,omitempty"`
|
||||
Component string `json:"component"`
|
||||
StartedAt time.Time `json:"started_at"`
|
||||
ResolvedAt *time.Time `json:"resolved_at,omitempty"`
|
||||
@@ -115,12 +117,14 @@ type PageIncidentUpdate struct {
|
||||
|
||||
// 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"`
|
||||
ShowDetails bool `json:"show_details,omitempty"`
|
||||
Slug string `json:"slug"`
|
||||
Title string `json:"title"`
|
||||
Description string `json:"description"`
|
||||
Theme Theme `json:"theme"`
|
||||
Status string `json:"status"`
|
||||
ShowDetails bool `json:"show_details,omitempty"`
|
||||
// Subscribe offers visitors email subscriptions to incidents.
|
||||
Subscribe bool `json:"subscribe,omitempty"`
|
||||
Sections []Section `json:"sections"`
|
||||
Incidents []PageIncident `json:"incidents"`
|
||||
GeneratedAt time.Time `json:"generated_at"`
|
||||
@@ -358,14 +362,20 @@ type PageRef struct {
|
||||
Host string `json:"host,omitempty"`
|
||||
}
|
||||
|
||||
// PageIndex lists the pages a status page server serves.
|
||||
type PageIndex struct {
|
||||
Pages []PageRef `json:"pages"`
|
||||
// HomeURL is the platform's home page, which the server links from
|
||||
// its error page; empty for none.
|
||||
HomeURL string `json:"home_url,omitempty"`
|
||||
}
|
||||
|
||||
// Pages lists every page this status page server serves, so it can keep
|
||||
// them all cached before anyone visits.
|
||||
func (c *Client) Pages(ctx context.Context) ([]PageRef, error) {
|
||||
var out struct {
|
||||
Pages []PageRef `json:"pages"`
|
||||
}
|
||||
func (c *Client) Pages(ctx context.Context) (PageIndex, error) {
|
||||
var out PageIndex
|
||||
err := c.do(ctx, http.MethodGet, "/pages/index", nil, &out)
|
||||
return out.Pages, err
|
||||
return out, err
|
||||
}
|
||||
|
||||
// ErrNotFound means no published page matches.
|
||||
|
||||
@@ -0,0 +1,66 @@
|
||||
package agentapi
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"net/http"
|
||||
)
|
||||
|
||||
// Visitors of a status page subscribe to its incidents by email. The status
|
||||
// page server passes their requests on; the API checks its limits, mails
|
||||
// the confirmation and later the incidents.
|
||||
|
||||
// SubscribeRequest asks for an email subscription to the page at Host, or
|
||||
// Slug if Host is empty.
|
||||
type SubscribeRequest struct {
|
||||
Host string `json:"host,omitempty"`
|
||||
Slug string `json:"slug,omitempty"`
|
||||
Email string `json:"email"`
|
||||
// IP is the visitor's address, for rate limits.
|
||||
IP string `json:"ip"`
|
||||
// Locale is the language of the mails, as the visitor's browser asks.
|
||||
Locale string `json:"locale,omitempty"`
|
||||
// PageURL is where the visitor saw the page, ending in "/". The API
|
||||
// uses it for the links in mails only where it does not know the
|
||||
// page's address itself.
|
||||
PageURL string `json:"page_url,omitempty"`
|
||||
// Accepted says the visitor accepted the terms and privacy policy the
|
||||
// page links in its form, if it links any.
|
||||
Accepted bool `json:"accepted"`
|
||||
}
|
||||
|
||||
// SubscriptionInfo describes a subscription that was confirmed or ended.
|
||||
type SubscriptionInfo struct {
|
||||
PageTitle string `json:"page_title"`
|
||||
Email string `json:"email"`
|
||||
}
|
||||
|
||||
// ErrInvalidInput means the API refused the request's content, e.g. an
|
||||
// email address that is none.
|
||||
var ErrInvalidInput = errors.New("agentapi: invalid input")
|
||||
|
||||
type tokenRequest struct {
|
||||
Token string `json:"token"`
|
||||
}
|
||||
|
||||
// Subscribe asks for a subscription and has the confirmation mailed. It
|
||||
// succeeds whether or not the address was subscribed already, so it tells
|
||||
// nobody who is. ErrRateLimited means a limit was reached, ErrNotFound
|
||||
// that the page takes no subscriptions.
|
||||
func (c *Client) Subscribe(ctx context.Context, r SubscribeRequest) error {
|
||||
return c.do(ctx, http.MethodPost, "/subscriptions", r, nil)
|
||||
}
|
||||
|
||||
// ConfirmSubscription confirms the subscription token was mailed for.
|
||||
func (c *Client) ConfirmSubscription(ctx context.Context, token string) (SubscriptionInfo, error) {
|
||||
var out SubscriptionInfo
|
||||
err := c.do(ctx, http.MethodPost, "/subscriptions/confirm", tokenRequest{token}, &out)
|
||||
return out, err
|
||||
}
|
||||
|
||||
// Unsubscribe ends the subscription of an unsubscribe token.
|
||||
func (c *Client) Unsubscribe(ctx context.Context, token string) (SubscriptionInfo, error) {
|
||||
var out SubscriptionInfo
|
||||
err := c.do(ctx, http.MethodPost, "/subscriptions/unsubscribe", tokenRequest{token}, &out)
|
||||
return out, err
|
||||
}
|
||||
+44
-5
@@ -53,6 +53,9 @@ func (s *Server) mountAgentAPI(r gin.IRouter) {
|
||||
sp.POST("/storage/lock", s.storageLock)
|
||||
sp.DELETE("/storage/lock", s.storageUnlock)
|
||||
sp.POST("/certificates", s.agentCertificate)
|
||||
sp.POST("/subscriptions", s.agentSubscribe)
|
||||
sp.POST("/subscriptions/confirm", s.agentConfirmSubscription)
|
||||
sp.POST("/subscriptions/unsubscribe", s.agentUnsubscribe)
|
||||
checker := g.Group("", requireAgentKind("checker"))
|
||||
checker.POST("/jobs", s.agentJobs)
|
||||
checker.POST("/results", s.agentResults)
|
||||
@@ -219,12 +222,31 @@ func (s *Server) agentJobs(c *gin.Context) {
|
||||
}
|
||||
}()
|
||||
}
|
||||
entries, err := s.sched.Take(pollCtx, instance, min(req.Max, maxJobBatch), wait)
|
||||
entries, stale, err := s.sched.Take(pollCtx, instance, min(req.Max, maxJobBatch), wait)
|
||||
s.metrics.Stale(stale)
|
||||
if err != nil && pollCtx.Err() == nil {
|
||||
internalError(c, err)
|
||||
return
|
||||
}
|
||||
jobs, orgs, err := s.resolveJobs(ctx, agentOf(c), entries)
|
||||
agent := agentOf(c)
|
||||
if len(entries) > 0 {
|
||||
// The long poll may have waited for a while: settings such as
|
||||
// allow_private apply to the jobs as they are now.
|
||||
err := s.db.Tx(ctx, tenant.System(), func(q *store.Queries) error {
|
||||
var err error
|
||||
agent, err = q.GetAgentByHash(ctx, HashToken(bearerToken(c)))
|
||||
return err
|
||||
})
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
fail(c, http.StatusUnauthorized, "unauthenticated")
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
internalError(c, err)
|
||||
return
|
||||
}
|
||||
}
|
||||
jobs, orgs, err := s.resolveJobs(ctx, agent, entries)
|
||||
if err != nil {
|
||||
internalError(c, err)
|
||||
return
|
||||
@@ -295,6 +317,7 @@ func (s *Server) agentResults(c *gin.Context) {
|
||||
internalError(c, err)
|
||||
return
|
||||
}
|
||||
s.metrics.Rejected("duplicate", len(req.Results)-len(fresh))
|
||||
req.Results = fresh
|
||||
ids := make([]uuid.UUID, len(req.Results))
|
||||
for i, r := range req.Results {
|
||||
@@ -305,6 +328,8 @@ func (s *Server) agentResults(c *gin.Context) {
|
||||
var (
|
||||
accepted []agentapi.Result
|
||||
changed []uuid.UUID
|
||||
unknown int
|
||||
badTime int
|
||||
)
|
||||
err = s.db.Tx(ctx, tenant.System(), func(q *store.Queries) error {
|
||||
a := agentOf(c)
|
||||
@@ -322,7 +347,12 @@ func (s *Server) agentResults(c *gin.Context) {
|
||||
// A checker may only report monitors of its own region, and
|
||||
// timestamps far from now are rejected rather than skewing
|
||||
// history.
|
||||
if !ok || r.StartedAt.After(now.Add(time.Minute)) || r.StartedAt.Before(now.Add(-24*time.Hour)) {
|
||||
switch {
|
||||
case !ok:
|
||||
unknown++
|
||||
continue
|
||||
case r.StartedAt.After(now.Add(time.Minute)) || r.StartedAt.Before(now.Add(-24*time.Hour)):
|
||||
badTime++
|
||||
continue
|
||||
}
|
||||
row := store.InsertCheckResultsParams{
|
||||
@@ -350,6 +380,12 @@ func (s *Server) agentResults(c *gin.Context) {
|
||||
internalError(c, err)
|
||||
return
|
||||
}
|
||||
s.metrics.Rejected("unknown_monitor", unknown)
|
||||
s.metrics.Rejected("bad_time", badTime)
|
||||
label := regionLabel(agentOf(c))
|
||||
for _, r := range accepted {
|
||||
s.metrics.Result(label, r.OK, now.Sub(r.StartedAt))
|
||||
}
|
||||
s.pagesChanged(ctx, changed...)
|
||||
s.evaluateResults(ctx, region, accepted, monitors)
|
||||
s.storeEvidence(ctx, region, instance, accepted, monitors)
|
||||
@@ -377,8 +413,11 @@ func truncateValid(s string, n int) string {
|
||||
}
|
||||
|
||||
// resultClaimTTL covers the retries of a checker that lost the answer to a
|
||||
// report, which happen within minutes.
|
||||
const resultClaimTTL = 2 * time.Hour
|
||||
// report: the next report, seconds later, or the first after the API is
|
||||
// back. A claim is one Redis key per result, so the TTL sets how much of
|
||||
// Redis they take: at 500 results a second, 10 minutes are 300,000 keys,
|
||||
// about 70 MiB.
|
||||
const resultClaimTTL = 10 * time.Minute
|
||||
|
||||
// claimResults drops results already received. A checker that does not get
|
||||
// the answer to a report, say because the connection broke while the API was
|
||||
|
||||
@@ -15,6 +15,7 @@ import (
|
||||
|
||||
"git.zb-server.de/ZB-Server/uptimesebi/internal/agentapi"
|
||||
"git.zb-server.de/ZB-Server/uptimesebi/internal/evaluate"
|
||||
"git.zb-server.de/ZB-Server/uptimesebi/internal/i18n"
|
||||
"git.zb-server.de/ZB-Server/uptimesebi/internal/notify"
|
||||
"git.zb-server.de/ZB-Server/uptimesebi/internal/store"
|
||||
"git.zb-server.de/ZB-Server/uptimesebi/internal/tenant"
|
||||
@@ -99,6 +100,9 @@ func (s *Server) transition(ctx context.Context, m store.MonitorsForResultsRow,
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if _, err := q.EnqueueSubscriberNotifications(ctx, store.EnqueueSubscriberNotificationsParams{IncidentID: inc.ID, Event: event}); err != nil {
|
||||
return err
|
||||
}
|
||||
routes, err := q.MonitorAlertRoutes(ctx, m.ID)
|
||||
if err != nil {
|
||||
return err
|
||||
@@ -124,6 +128,7 @@ func (s *Server) transition(ctx context.Context, m store.MonitorsForResultsRow,
|
||||
}
|
||||
}
|
||||
s.log.InfoContext(ctx, "incident "+event, "monitor", m.ID, "incident", inc.ID, "channels", len(channels))
|
||||
s.metrics.Incident(event)
|
||||
return nil
|
||||
})
|
||||
}
|
||||
@@ -140,6 +145,8 @@ func (s *Server) RunNotifier(ctx context.Context) {
|
||||
case <-tick.C:
|
||||
for s.deliverBatch(ctx) == notifyBatch && ctx.Err() == nil {
|
||||
}
|
||||
for s.deliverSubscriberBatch(ctx) == subscriberBatch && ctx.Err() == nil {
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -161,7 +168,9 @@ func (s *Server) deliverBatch(ctx context.Context) int {
|
||||
return 0
|
||||
}
|
||||
for _, n := range rows {
|
||||
sent := time.Now()
|
||||
sendErr := s.send(ctx, n.ChannelType, n.ChannelConfig, eventOf(n))
|
||||
s.metrics.Notification(n.ChannelType, sendErr, time.Since(sent))
|
||||
err := s.db.Tx(ctx, tenant.System(), func(q *store.Queries) error {
|
||||
if sendErr == nil {
|
||||
return q.MarkNotificationSent(ctx, n.ID)
|
||||
@@ -192,9 +201,40 @@ func eventOf(n store.NotificationDetailsRow) notify.Event {
|
||||
Monitor: notify.Monitor{ID: n.MonitorID, Name: n.MonitorName, Type: n.MonitorType, Target: n.MonitorTarget},
|
||||
}
|
||||
_ = json.Unmarshal(n.Cause, &ev.Cause)
|
||||
_ = json.Unmarshal(n.RegionNames, &ev.RegionNames)
|
||||
return ev
|
||||
}
|
||||
|
||||
// causeLines describes the errors of ev per region, sorted, naming each
|
||||
// region as people know it.
|
||||
func causeLines(ev notify.Event, l *i18n.Localizer) []string {
|
||||
var out []string
|
||||
for region, msg := range ev.Cause {
|
||||
name, ok := ev.RegionNames[region]
|
||||
switch {
|
||||
case ok:
|
||||
case region == heartbeatRegion:
|
||||
name = l.T("monitors.type_heartbeat", nil)
|
||||
case region == alertmanagerRegion:
|
||||
name = "Alertmanager"
|
||||
default:
|
||||
name = region
|
||||
}
|
||||
out = append(out, name+": "+msg)
|
||||
}
|
||||
slices.Sort(out)
|
||||
return out
|
||||
}
|
||||
|
||||
// monitorLink is the address of ev's monitor in the console, or "" if
|
||||
// the platform's own address is unknown.
|
||||
func (s *Server) monitorLink(ev notify.Event) string {
|
||||
if ev.Monitor.ID == (uuid.UUID{}) || !absoluteURL(s.cfg.PublicURL) {
|
||||
return ""
|
||||
}
|
||||
return strings.TrimSuffix(s.cfg.PublicURL, "/") + "/monitors/" + ev.Monitor.ID.String()
|
||||
}
|
||||
|
||||
// webhookConfig is stored for webhook channels; Secret is sealed.
|
||||
type webhookConfig struct {
|
||||
URL string `json:"url"`
|
||||
@@ -252,18 +292,17 @@ func (s *Server) mailFor(ev notify.Event, to []string, locale string) notify.Mai
|
||||
"Target": ev.Monitor.Target,
|
||||
"Since": ev.StartedAt.UTC().Format("2006-01-02 15:04 MST"),
|
||||
}
|
||||
var cause []string
|
||||
for region, msg := range ev.Cause {
|
||||
cause = append(cause, region+": "+msg)
|
||||
}
|
||||
slices.Sort(cause)
|
||||
data["Cause"] = strings.Join(cause, "\n")
|
||||
data["Cause"] = strings.Join(causeLines(ev, l), "\n")
|
||||
if ev.ResolvedAt != nil {
|
||||
data["Duration"] = ev.ResolvedAt.Sub(ev.StartedAt).Round(time.Second).String()
|
||||
}
|
||||
body := l.T("email."+ev.Kind+".body", data)
|
||||
if link := s.monitorLink(ev); link != "" {
|
||||
body += "\n\n" + l.T("email.monitor_link", map[string]any{"Link": link})
|
||||
}
|
||||
return notify.Mail{
|
||||
To: to,
|
||||
Subject: l.T("email."+ev.Kind+".subject", data),
|
||||
Body: l.T("email."+ev.Kind+".body", data),
|
||||
Body: body,
|
||||
}
|
||||
}
|
||||
@@ -128,6 +128,8 @@ func TestAlerting(t *testing.T) {
|
||||
}
|
||||
if msg := mail.Messages()[0].Data; !strings.Contains(msg, "Subject: [DOWN] Shop") || !strings.Contains(msg, "ist in allen Regionen nicht erreichbar") {
|
||||
t.Errorf("down mail = %q, want German down notice", msg)
|
||||
} else if strings.Contains(msg, eu) || strings.Contains(msg, us) || !strings.Contains(msg, "/monitors/"+monitorID) {
|
||||
t.Errorf("down mail = %q, want region names instead of ids and a link to the monitor", msg)
|
||||
}
|
||||
|
||||
healthy.Store(true)
|
||||
|
||||
@@ -22,6 +22,9 @@ func paged(o obj) obj {
|
||||
// show them.
|
||||
var endpoints = []endpoint{
|
||||
// Account
|
||||
{method: "GET", path: "/api/v1/public/regions", tag: "Public", summary: "Platform regions with their locations", public: true,
|
||||
description: "For websites showing where the platform checks from: no authentication, any origin (CORS), cached for up to a minute. Lists platform regions only; `latitude`/`longitude` are absent for regions without a location, and `online` is set while a checker of the region is connected.",
|
||||
resp: obj{"regions": []publicRegion{}}},
|
||||
{method: "POST", path: "/api/v1/auth/signup", tag: "Account", summary: "Create an account", public: true,
|
||||
description: "Depending on the installation, sign-up is open, limited to the first user, or closed. Where addresses are confirmed, answers `{\"status\": \"verification_sent\"}` and mails a link; the account signs in after confirming. Otherwise starts a session, and `org_name`/`org_slug`, if given, create a first organization. One account per mailbox (+suffixes and Gmail dots count as the same address); a client address may create only a few accounts a day (`429 signup_limit`).",
|
||||
req: signupRequest{}, resp: sessionStarted},
|
||||
@@ -188,6 +191,10 @@ var endpoints = []endpoint{
|
||||
description: "Verify it with a TXT record before it is served.", req: domainRequest{}, resp: statusPageView{}},
|
||||
{method: "POST", path: "/api/v1/org/statuspages/:id/domain/verify", tag: "Status pages", summary: "Verify the custom domain", perm: "statuspages.write",
|
||||
status: http.StatusNoContent},
|
||||
{method: "GET", path: "/api/v1/org/statuspages/:id/subscribers", tag: "Status pages", summary: "List email subscribers", perm: "statuspages.write",
|
||||
description: "Counts of confirmed and pending subscribers and the newest 1000 of them.", resp: subscribersView{}},
|
||||
{method: "DELETE", path: "/api/v1/org/statuspages/:id/subscribers/:subscriber", tag: "Status pages", summary: "Remove an email subscriber", perm: "statuspages.write",
|
||||
status: http.StatusNoContent},
|
||||
{method: "GET", path: "/api/v1/org/statuspages/:id/export", tag: "Status pages", summary: "Export the page as a single HTML file", perm: "statuspages.read",
|
||||
media: "text/html"},
|
||||
|
||||
@@ -264,6 +271,8 @@ var endpoints = []endpoint{
|
||||
req: regionRequest{}, status: http.StatusCreated, resp: regionView{}},
|
||||
{method: "DELETE", path: "/api/v1/org/regions/:id", tag: "Organization", summary: "Delete an own region", perm: "org.manage", sessionOnly: true,
|
||||
status: http.StatusNoContent},
|
||||
{method: "PATCH", path: "/api/v1/org/regions/:id", tag: "Organization", summary: "Set or remove the location of an own region", perm: "org.manage", sessionOnly: true,
|
||||
description: "Null for both coordinates removes the location.", req: regionLocation{}, status: http.StatusNoContent},
|
||||
{method: "GET", path: "/api/v1/org/agents", tag: "Organization", summary: "List own checkers and status page servers", perm: "org.manage",
|
||||
resp: obj{"agents": []agentView{}}},
|
||||
{method: "POST", path: "/api/v1/org/agents", tag: "Organization", summary: "Create an agent token", perm: "org.manage", sessionOnly: true,
|
||||
@@ -314,6 +323,11 @@ var endpoints = []endpoint{
|
||||
{method: "PUT", path: "/api/v1/admin/checker-network", tag: "Platform", summary: "Let platform checkers check private addresses or not",
|
||||
description: "Unset, they may on self-hosted installations and may not in the cloud edition. Applies from each checker's next poll.",
|
||||
perm: "platform admin", req: checkerNetwork{}, status: http.StatusNoContent},
|
||||
{method: "GET", path: "/api/v1/admin/statuspage-home", tag: "Platform", summary: "The home page linked from the status page servers' error page", perm: "platform admin",
|
||||
resp: statusPageHome{}},
|
||||
{method: "PUT", path: "/api/v1/admin/statuspage-home", tag: "Platform", summary: "Set the home page linked from the status page servers' error page",
|
||||
description: "Visitors of the bare status page domain and of pages that do not exist see an error page with a link to this URL. Empty links none.",
|
||||
perm: "platform admin", req: statusPageHome{}, status: http.StatusNoContent},
|
||||
{method: "GET", path: "/api/v1/admin/identity-providers", tag: "Platform", summary: "Identity providers for signing up and in",
|
||||
description: "With the callback URL to register at each provider. Secrets are never returned.", perm: "platform admin",
|
||||
resp: obj{"providers": []idpView{}, "callback_url": ""}},
|
||||
@@ -357,6 +371,8 @@ var endpoints = []endpoint{
|
||||
req: regionRequest{}, status: http.StatusCreated, resp: regionView{}},
|
||||
{method: "DELETE", path: "/api/v1/admin/regions/:id", tag: "Platform", summary: "Delete a platform region", perm: "platform admin",
|
||||
status: http.StatusNoContent},
|
||||
{method: "PATCH", path: "/api/v1/admin/regions/:id", tag: "Platform", summary: "Set or remove the location of a platform region", perm: "platform admin",
|
||||
description: "Null for both coordinates removes the location.", req: regionLocation{}, status: http.StatusNoContent},
|
||||
{method: "GET", path: "/api/v1/admin/agents", tag: "Platform", summary: "List platform agents", perm: "platform admin",
|
||||
resp: obj{"agents": []agentView{}}},
|
||||
{method: "POST", path: "/api/v1/admin/agents", tag: "Platform", summary: "Create a platform agent token", perm: "platform admin",
|
||||
|
||||
+48
-44
@@ -61,55 +61,58 @@ var auditActions = map[string]string{
|
||||
"POST /api/v1/invitations/:token/accept": "member.join",
|
||||
"POST /api/v1/invitations/:token/signup": "member.join",
|
||||
|
||||
"PUT /api/v1/org/policy": "org.policy_update",
|
||||
"POST /api/v1/org/monitors": "monitor.create",
|
||||
"PUT /api/v1/org/monitors/:id": "monitor.update",
|
||||
"PUT /api/v1/org/monitors/order": "monitor.order",
|
||||
"DELETE /api/v1/org/monitors/:id": "monitor.delete",
|
||||
"POST /api/v1/org/alertmanager/receivers": "alertmanager.receiver_create",
|
||||
"DELETE /api/v1/org/alertmanager/receivers/:id": "alertmanager.receiver_delete",
|
||||
"POST /api/v1/org/maintenance": "maintenance.create",
|
||||
"PUT /api/v1/org/maintenance/:id": "maintenance.update",
|
||||
"DELETE /api/v1/org/maintenance/:id": "maintenance.delete",
|
||||
"POST /api/v1/org/groups": "group.create",
|
||||
"PUT /api/v1/org/groups/:id": "group.update",
|
||||
"DELETE /api/v1/org/groups/:id": "group.delete",
|
||||
"POST /api/v1/org/regions": "region.create",
|
||||
"DELETE /api/v1/org/regions/:id": "region.delete",
|
||||
"POST /api/v1/org/agents": "agent.create",
|
||||
"DELETE /api/v1/org/agents/:id": "agent.delete",
|
||||
"POST /api/v1/org/statuspages": "statuspage.create",
|
||||
"PUT /api/v1/org/statuspages/:id": "statuspage.update",
|
||||
"DELETE /api/v1/org/statuspages/:id": "statuspage.delete",
|
||||
"POST /api/v1/org/statuspages/:id/groups": "statuspage.group_create",
|
||||
"PUT /api/v1/org/statuspages/:id/groups/:group_id": "statuspage.group_update",
|
||||
"DELETE /api/v1/org/statuspages/:id/groups/:group_id": "statuspage.group_delete",
|
||||
"POST /api/v1/org/statuspages/:id/groups/import": "statuspage.groups_import",
|
||||
"PUT /api/v1/org/statuspages/:id/monitors": "statuspage.monitors_update",
|
||||
"PUT /api/v1/org/statuspages/:id/domain": "statuspage.domain_update",
|
||||
"POST /api/v1/org/statuspages/:id/domain/verify": "statuspage.domain_verify",
|
||||
"POST /api/v1/org/channels": "channel.create",
|
||||
"PUT /api/v1/org/channels/:id": "channel.update",
|
||||
"DELETE /api/v1/org/channels/:id": "channel.delete",
|
||||
"POST /api/v1/org/channels/:id/test": "channel.test",
|
||||
"POST /api/v1/org/sso": "sso.create",
|
||||
"PUT /api/v1/org/sso/:id": "sso.update",
|
||||
"DELETE /api/v1/org/sso/:id": "sso.delete",
|
||||
"DELETE /api/v1/org/members/:user": "member.remove",
|
||||
"POST /api/v1/org/members/:user/roles": "member.role_assign",
|
||||
"DELETE /api/v1/org/assignments/:id": "member.role_unassign",
|
||||
"POST /api/v1/org/invitations": "invitation.create",
|
||||
"DELETE /api/v1/org/invitations/:id": "invitation.delete",
|
||||
"POST /api/v1/org/roles": "role.create",
|
||||
"PUT /api/v1/org/roles/:id": "role.update",
|
||||
"DELETE /api/v1/org/roles/:id": "role.delete",
|
||||
"POST /api/v1/org/tokens": "token.create",
|
||||
"DELETE /api/v1/org/tokens/:id": "token.delete",
|
||||
"PUT /api/v1/org/policy": "org.policy_update",
|
||||
"POST /api/v1/org/monitors": "monitor.create",
|
||||
"PUT /api/v1/org/monitors/:id": "monitor.update",
|
||||
"PUT /api/v1/org/monitors/order": "monitor.order",
|
||||
"DELETE /api/v1/org/monitors/:id": "monitor.delete",
|
||||
"POST /api/v1/org/alertmanager/receivers": "alertmanager.receiver_create",
|
||||
"DELETE /api/v1/org/alertmanager/receivers/:id": "alertmanager.receiver_delete",
|
||||
"POST /api/v1/org/maintenance": "maintenance.create",
|
||||
"PUT /api/v1/org/maintenance/:id": "maintenance.update",
|
||||
"DELETE /api/v1/org/maintenance/:id": "maintenance.delete",
|
||||
"POST /api/v1/org/groups": "group.create",
|
||||
"PUT /api/v1/org/groups/:id": "group.update",
|
||||
"DELETE /api/v1/org/groups/:id": "group.delete",
|
||||
"POST /api/v1/org/regions": "region.create",
|
||||
"DELETE /api/v1/org/regions/:id": "region.delete",
|
||||
"PATCH /api/v1/org/regions/:id": "region.update",
|
||||
"POST /api/v1/org/agents": "agent.create",
|
||||
"DELETE /api/v1/org/agents/:id": "agent.delete",
|
||||
"POST /api/v1/org/statuspages": "statuspage.create",
|
||||
"PUT /api/v1/org/statuspages/:id": "statuspage.update",
|
||||
"DELETE /api/v1/org/statuspages/:id": "statuspage.delete",
|
||||
"POST /api/v1/org/statuspages/:id/groups": "statuspage.group_create",
|
||||
"PUT /api/v1/org/statuspages/:id/groups/:group_id": "statuspage.group_update",
|
||||
"DELETE /api/v1/org/statuspages/:id/groups/:group_id": "statuspage.group_delete",
|
||||
"POST /api/v1/org/statuspages/:id/groups/import": "statuspage.groups_import",
|
||||
"PUT /api/v1/org/statuspages/:id/monitors": "statuspage.monitors_update",
|
||||
"PUT /api/v1/org/statuspages/:id/domain": "statuspage.domain_update",
|
||||
"POST /api/v1/org/statuspages/:id/domain/verify": "statuspage.domain_verify",
|
||||
"DELETE /api/v1/org/statuspages/:id/subscribers/:subscriber": "statuspage.subscriber_delete",
|
||||
"POST /api/v1/org/channels": "channel.create",
|
||||
"PUT /api/v1/org/channels/:id": "channel.update",
|
||||
"DELETE /api/v1/org/channels/:id": "channel.delete",
|
||||
"POST /api/v1/org/channels/:id/test": "channel.test",
|
||||
"POST /api/v1/org/sso": "sso.create",
|
||||
"PUT /api/v1/org/sso/:id": "sso.update",
|
||||
"DELETE /api/v1/org/sso/:id": "sso.delete",
|
||||
"DELETE /api/v1/org/members/:user": "member.remove",
|
||||
"POST /api/v1/org/members/:user/roles": "member.role_assign",
|
||||
"DELETE /api/v1/org/assignments/:id": "member.role_unassign",
|
||||
"POST /api/v1/org/invitations": "invitation.create",
|
||||
"DELETE /api/v1/org/invitations/:id": "invitation.delete",
|
||||
"POST /api/v1/org/roles": "role.create",
|
||||
"PUT /api/v1/org/roles/:id": "role.update",
|
||||
"DELETE /api/v1/org/roles/:id": "role.delete",
|
||||
"POST /api/v1/org/tokens": "token.create",
|
||||
"DELETE /api/v1/org/tokens/:id": "token.delete",
|
||||
|
||||
"PUT /api/v1/admin/legal/:kind": "platform.legal_update",
|
||||
"PUT /api/v1/org/legal/:kind": "org.legal_update",
|
||||
"PUT /api/v1/admin/check-types": "platform.check_types_update",
|
||||
"PUT /api/v1/admin/checker-network": "platform.checker_network_update",
|
||||
"PUT /api/v1/admin/statuspage-home": "platform.statuspage_home_update",
|
||||
"PUT /api/v1/admin/limits": "platform.limits_update",
|
||||
"POST /api/v1/admin/identity-providers": "platform.idp_create",
|
||||
"PUT /api/v1/admin/identity-providers/:id": "platform.idp_update",
|
||||
@@ -127,6 +130,7 @@ var auditActions = map[string]string{
|
||||
"PATCH /api/v1/org/agents/:id": "agent.update",
|
||||
"POST /api/v1/admin/regions": "platform.region_create",
|
||||
"DELETE /api/v1/admin/regions/:id": "platform.region_delete",
|
||||
"PATCH /api/v1/admin/regions/:id": "platform.region_update",
|
||||
"POST /api/v1/admin/agents": "platform.agent_create",
|
||||
"DELETE /api/v1/admin/agents/:id": "platform.agent_delete",
|
||||
}
|
||||
|
||||
@@ -85,7 +85,9 @@ func TestCheckerNetwork(t *testing.T) {
|
||||
}
|
||||
waitResult := func(id string, ok bool, what string) {
|
||||
t.Helper()
|
||||
waitFor(t, 20*time.Second, what, func() bool {
|
||||
// Two runs at most: the one already handed out, then the next on
|
||||
// the monitor's phase, up to one and a half intervals later.
|
||||
waitFor(t, 30*time.Second, what, func() bool {
|
||||
got, msg, seen := latestOf(owner, id)
|
||||
return seen && got == ok && (ok || strings.Contains(msg, "non-public"))
|
||||
})
|
||||
|
||||
+86
-57
@@ -19,6 +19,7 @@ import (
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/google/uuid"
|
||||
"github.com/jackc/pgx/v5"
|
||||
"golang.org/x/sync/errgroup"
|
||||
|
||||
"git.zb-server.de/ZB-Server/uptimesebi/internal/auth"
|
||||
"git.zb-server.de/ZB-Server/uptimesebi/internal/authz"
|
||||
@@ -72,8 +73,10 @@ func (s *Server) dashboard(c *gin.Context) {
|
||||
return
|
||||
}
|
||||
v := web.DashboardView{Counts: map[web.Status]int{}, Empty: true}
|
||||
timer := newStepTimer()
|
||||
if p != nil && me.Policy == "" {
|
||||
data, err := s.loadMonitorData(c.Request.Context(), p, web.RangeByKey(c.Query("range")))
|
||||
timer.done("load")
|
||||
if err != nil {
|
||||
internalError(c, err)
|
||||
return
|
||||
@@ -84,21 +87,14 @@ func (s *Server) dashboard(c *gin.Context) {
|
||||
if !s.dashboardPage(c, &v, data) {
|
||||
return
|
||||
}
|
||||
timer.done("arrange")
|
||||
if err := s.dashboardBars(c.Request.Context(), p, &v, &data); err != nil {
|
||||
internalError(c, err)
|
||||
return
|
||||
}
|
||||
timer.done("bars")
|
||||
v.Range = data.rng.Key
|
||||
var earliest time.Time
|
||||
if err := s.db.Tx(c.Request.Context(), p.scope(), func(q *store.Queries) error {
|
||||
var err error
|
||||
earliest, err = earliestData(c.Request.Context(), q, p.Org.ID, data.now)
|
||||
return err
|
||||
}); err != nil {
|
||||
internalError(c, err)
|
||||
return
|
||||
}
|
||||
v.Ranges = rangeOptions(c, data.rng, earliest, data.now)
|
||||
v.Ranges = rangeOptions(c, data.rng, data.firstCreated, data.now)
|
||||
for _, m := range data.rows {
|
||||
v.Counts[m.Status]++
|
||||
if m.Unchecked {
|
||||
@@ -111,7 +107,11 @@ func (s *Server) dashboard(c *gin.Context) {
|
||||
}
|
||||
slices.SortFunc(v.DeadRegions, func(a, b web.DeadRegion) int { return strings.Compare(a.Name, b.Name) })
|
||||
}
|
||||
timer.done("rest")
|
||||
timer.header(c)
|
||||
web.Render(c, http.StatusOK, web.Dashboard(s.pageFor(c, "console.monitors.title"), me, v))
|
||||
timer.done("render")
|
||||
timer.logIfSlow(c, s.log)
|
||||
}
|
||||
|
||||
// dashboardBars loads the bars of the monitors v shows, and only those.
|
||||
@@ -218,13 +218,28 @@ func (o monitorSort) key(m web.MonitorRow) cursor {
|
||||
}
|
||||
|
||||
func (o monitorSort) sort(ms []web.MonitorRow) {
|
||||
slices.SortFunc(ms, func(a, b web.MonitorRow) int {
|
||||
ka, kb := o.key(a), o.key(b)
|
||||
if c := strings.Compare(ka.S, kb.S); c != 0 {
|
||||
// Keys are worked out once per row, not per comparison, and the rows
|
||||
// moved once: with thousands of monitors sorting was a good part of
|
||||
// the dashboard's time.
|
||||
type keyed struct {
|
||||
key, id string
|
||||
i int
|
||||
}
|
||||
keys := make([]keyed, len(ms))
|
||||
for i, m := range ms {
|
||||
keys[i] = keyed{o.key(m).S, m.ID, i}
|
||||
}
|
||||
slices.SortFunc(keys, func(a, b keyed) int {
|
||||
if c := strings.Compare(a.key, b.key); c != 0 {
|
||||
return c
|
||||
}
|
||||
return strings.Compare(a.ID, b.ID)
|
||||
return strings.Compare(a.id, b.id)
|
||||
})
|
||||
sorted := make([]web.MonitorRow, len(ms))
|
||||
for i, k := range keys {
|
||||
sorted[i] = ms[k.i]
|
||||
}
|
||||
copy(ms, sorted)
|
||||
}
|
||||
|
||||
// dashboardStatuses are the statuses the dashboard counts, in order.
|
||||
@@ -379,6 +394,11 @@ type monitorData struct {
|
||||
regionOf map[uuid.UUID]store.Region
|
||||
rng web.TimeRange
|
||||
now time.Time
|
||||
// firstCreated is when the oldest monitor was created: the monitor
|
||||
// list offers no ranges reaching far before it. (Finding the first
|
||||
// result instead read results of every monitor, slow for large
|
||||
// organizations.)
|
||||
firstCreated time.Time
|
||||
// first is when the monitor of a detail page first reported, from
|
||||
// any region; firstRegion the same per region.
|
||||
first time.Time
|
||||
@@ -423,25 +443,6 @@ func loadFirstData(ctx context.Context, q *store.Queries, org, monitor uuid.UUID
|
||||
return first, perRegion, nil
|
||||
}
|
||||
|
||||
// earliestData finds when any monitor of org first reported, for the
|
||||
// ranges the monitor list offers: to the day if that was over two days
|
||||
// ago, otherwise exactly.
|
||||
func earliestData(ctx context.Context, q *store.Queries, org uuid.UUID, now time.Time) (time.Time, error) {
|
||||
none := func(t time.Time, err error) (time.Time, bool, error) {
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return time.Time{}, false, nil
|
||||
}
|
||||
return t, err == nil, err
|
||||
}
|
||||
recentSince := now.Add(-2 * 24 * time.Hour)
|
||||
daily, ok, err := none(q.EarliestDataDaily(ctx, org))
|
||||
if err != nil || (ok && daily.Before(recentSince)) {
|
||||
return daily, err
|
||||
}
|
||||
exact, _, err := none(q.EarliestDataRecent(ctx, store.EarliestDataRecentParams{OrgID: org, Time: recentSince}))
|
||||
return exact, err
|
||||
}
|
||||
|
||||
// rangeBuckets loads the selected range for the monitors ids.
|
||||
func rangeBuckets(ctx context.Context, q *store.Queries, org uuid.UUID, ids []uuid.UUID, rng web.TimeRange, now time.Time) (map[uuid.UUID][]web.Bucket, error) {
|
||||
out := map[uuid.UUID][]web.Bucket{}
|
||||
@@ -498,39 +499,50 @@ func (s *Server) loadMonitorData(ctx context.Context, p *principal, rng web.Time
|
||||
spans []store.IncidentsSinceRow
|
||||
)
|
||||
var groups []store.MonitorGroup
|
||||
err := s.db.Tx(ctx, p.scope(), func(q *store.Queries) error {
|
||||
// The queries run in parallel: for large organizations each takes a
|
||||
// while, mostly to move its rows.
|
||||
g, gctx := errgroup.WithContext(ctx)
|
||||
tx := func(f func(q *store.Queries) error) {
|
||||
g.Go(func() error { return s.db.Tx(gctx, p.scope(), f) })
|
||||
}
|
||||
tx(func(q *store.Queries) error {
|
||||
var err error
|
||||
if groups, err = q.ListGroups(ctx); err != nil {
|
||||
if groups, err = q.ListGroups(gctx); err != nil {
|
||||
return err
|
||||
}
|
||||
if monitors, err = q.ListMonitors(ctx, p.Org.ID); err != nil {
|
||||
return err
|
||||
}
|
||||
if assigned, err = q.AllMonitorRegions(ctx, p.Org.ID); err != nil {
|
||||
return err
|
||||
}
|
||||
if regions, err = q.ListVisibleRegions(ctx); err != nil {
|
||||
return err
|
||||
}
|
||||
if latest, err = q.LatestResults(ctx, p.Org.ID); err != nil {
|
||||
return err
|
||||
}
|
||||
if open, err = q.OpenIncidents(ctx, p.Org.ID); err != nil {
|
||||
return err
|
||||
}
|
||||
if spans, err = q.IncidentsSince(ctx, store.IncidentsSinceParams{OrgID: p.Org.ID, ResolvedAt: ptr(now.Add(-web.SLAWindows[len(web.SLAWindows)-1].Window))}); err != nil {
|
||||
return err
|
||||
}
|
||||
if d.statuses, err = loadCustomStatuses(ctx, q); err != nil {
|
||||
if monitors, err = q.ListMonitors(gctx, p.Org.ID); err != nil {
|
||||
return err
|
||||
}
|
||||
ids := make([]uuid.UUID, len(monitors))
|
||||
for i, m := range monitors {
|
||||
ids[i] = m.ID
|
||||
}
|
||||
d.maint, err = maintenanceFor(ctx, q, ids)
|
||||
d.maint, err = maintenanceFor(gctx, q, ids)
|
||||
return err
|
||||
})
|
||||
tx(func(q *store.Queries) (err error) {
|
||||
assigned, err = q.AllMonitorRegions(gctx, p.Org.ID)
|
||||
return err
|
||||
})
|
||||
tx(func(q *store.Queries) (err error) {
|
||||
latest, err = q.LatestResults(gctx, p.Org.ID)
|
||||
return err
|
||||
})
|
||||
tx(func(q *store.Queries) error {
|
||||
var err error
|
||||
if regions, err = q.ListVisibleRegions(gctx); err != nil {
|
||||
return err
|
||||
}
|
||||
if open, err = q.OpenIncidents(gctx, p.Org.ID); err != nil {
|
||||
return err
|
||||
}
|
||||
if spans, err = q.IncidentsSince(gctx, store.IncidentsSinceParams{OrgID: p.Org.ID, ResolvedAt: ptr(now.Add(-web.SLAWindows[len(web.SLAWindows)-1].Window))}); err != nil {
|
||||
return err
|
||||
}
|
||||
d.statuses, err = loadCustomStatuses(gctx, q)
|
||||
return err
|
||||
})
|
||||
err := g.Wait()
|
||||
if err != nil {
|
||||
return d, err
|
||||
}
|
||||
@@ -553,6 +565,9 @@ func (s *Server) loadMonitorData(ctx context.Context, p *principal, rng web.Time
|
||||
if m.Enabled {
|
||||
d.usedRegions = append(d.usedRegions, regionsOf[m.ID]...)
|
||||
}
|
||||
if d.firstCreated.IsZero() || m.CreatedAt.Before(d.firstCreated) {
|
||||
d.firstCreated = m.CreatedAt
|
||||
}
|
||||
}
|
||||
slices.SortFunc(d.usedRegions, func(a, b uuid.UUID) int { return strings.Compare(a.String(), b.String()) })
|
||||
d.usedRegions = slices.Compact(d.usedRegions)
|
||||
@@ -924,8 +939,10 @@ func (s *Server) monitorEditor(c *gin.Context, p *principal, page web.Page, me w
|
||||
return nil, err
|
||||
}
|
||||
checked := slices.Contains(assigned, r.ID) || (idParam == "" && i == 0)
|
||||
f.Regions = append(f.Regions, web.RegionOption{ID: r.ID.String(), Name: r.Name, Own: r.OrgID != nil, Checked: checked, Live: live})
|
||||
f.Regions = append(f.Regions, web.RegionOption{ID: r.ID.String(), Name: r.Name, Own: r.OrgID != nil, Checked: checked, Live: live, Lat: r.Latitude, Lon: r.Longitude})
|
||||
}
|
||||
limits := s.orgLimits(ctx, p.Org)
|
||||
f.RegionLimit, f.OwnRegionsCount = limits.RegionsPerMonitor, limits.OwnRegionsCount
|
||||
t, err := s.loadGroupTree(ctx, p.scope())
|
||||
if err != nil {
|
||||
return nil, err
|
||||
@@ -1318,6 +1335,7 @@ func (s *Server) statusPageEditor(c *gin.Context, p *principal, page web.Page, m
|
||||
pageGroups []store.StatusPageGroup
|
||||
orgGroups []store.MonitorGroup
|
||||
monitors []store.Monitor
|
||||
subs subscribersView
|
||||
own bool
|
||||
)
|
||||
err = s.db.Tx(ctx, p.scope(), func(q *store.Queries) error {
|
||||
@@ -1337,6 +1355,9 @@ func (s *Server) statusPageEditor(c *gin.Context, p *principal, page web.Page, m
|
||||
if monitors, err = q.ListMonitors(ctx, p.Org.ID); err != nil {
|
||||
return err
|
||||
}
|
||||
if subs, err = s.pageSubscribers(ctx, q, id); err != nil {
|
||||
return err
|
||||
}
|
||||
own, err = q.OrgServesOwnPages(ctx, &p.Org.ID)
|
||||
return err
|
||||
})
|
||||
@@ -1359,7 +1380,15 @@ func (s *Server) statusPageEditor(c *gin.Context, p *principal, page web.Page, m
|
||||
e.RecordName, e.RecordValue = v.DomainRecord.Name, v.DomainRecord.Value
|
||||
}
|
||||
e.DomainChangesPerDay = domainChangesPerDay
|
||||
e.MonitorLimit = s.orgLimits(c.Request.Context(), p.Org).MonitorsPerPage
|
||||
limits := s.orgLimits(c.Request.Context(), p.Org)
|
||||
e.MonitorLimit = limits.MonitorsPerPage
|
||||
e.Subscriptions, e.MailAvailable, e.SubscriberLimit = row.Subscriptions, s.smtp != nil, limits.SubscribersPerWeek
|
||||
e.SubscribersConfirmed, e.SubscribersPending = subs.Confirmed, subs.Pending
|
||||
for _, sub := range subs.Subscribers {
|
||||
e.Subscribers = append(e.Subscribers, web.PageSubscriberRow{
|
||||
ID: sub.ID.String(), Email: sub.Email, Since: sub.CreatedAt.Local().Format("2006-01-02"), Pending: sub.ConfirmedAt == nil,
|
||||
})
|
||||
}
|
||||
if v.CNAMERecord != nil {
|
||||
e.CNAMEValue = v.CNAMERecord.Value
|
||||
}
|
||||
|
||||
@@ -81,7 +81,7 @@ func (s *Server) RunDomainWatch(ctx context.Context) {
|
||||
defer tick.Stop()
|
||||
for {
|
||||
if ok, err := s.rdb.SetNX(ctx, keyDomainWatch, 1, domainWatchEvery-5*time.Second).Result(); err == nil && ok {
|
||||
if err := s.WatchDomains(ctx, time.Now()); err != nil && ctx.Err() == nil {
|
||||
if err := s.metrics.Job("domain_watch", func() error { return s.WatchDomains(ctx, time.Now()) }); err != nil && ctx.Err() == nil {
|
||||
s.log.WarnContext(ctx, "checking custom domains failed", "error", err)
|
||||
}
|
||||
}
|
||||
|
||||
+75
-28
@@ -37,9 +37,15 @@ const (
|
||||
|
||||
// storeEvidence keeps the evidence of accepted results: per monitor and
|
||||
// region the latest success, and failures unless an identical one was kept
|
||||
// within failureEvidenceEvery. Evidence is an aid; failures are logged and
|
||||
// never fail the report.
|
||||
// within failureEvidenceEvery. All of a report's evidence is written in one
|
||||
// transaction, so a report full of it stays quick and the checker can go
|
||||
// on. Evidence is an aid; failures are logged and never fail the report.
|
||||
func (s *Server) storeEvidence(ctx context.Context, region string, checker uuid.UUID, results []agentapi.Result, monitors map[uuid.UUID]store.MonitorsForResultsRow) {
|
||||
var (
|
||||
successes = map[uuid.UUID]agentapi.Result{}
|
||||
failures []agentapi.Result
|
||||
failed []uuid.UUID
|
||||
)
|
||||
for _, r := range results {
|
||||
m, ok := monitors[r.MonitorID]
|
||||
if len(r.Evidence) == 0 || !ok {
|
||||
@@ -49,34 +55,75 @@ func (s *Server) storeEvidence(ctx context.Context, region string, checker uuid.
|
||||
s.log.WarnContext(ctx, "dropping malformed evidence", "monitor", m.ID, "bytes", len(r.Evidence))
|
||||
continue
|
||||
}
|
||||
err := s.db.Tx(ctx, tenant.System(), func(q *store.Queries) error {
|
||||
if r.OK {
|
||||
if err := q.DeleteSuccessEvidence(ctx, store.DeleteSuccessEvidenceParams{MonitorID: m.ID, Region: region}); err != nil {
|
||||
return err
|
||||
}
|
||||
} else {
|
||||
last, err := q.LastFailureEvidence(ctx, store.LastFailureEvidenceParams{MonitorID: m.ID, Region: region})
|
||||
if err == nil && last.Error == r.Error && r.StartedAt.Sub(last.Time) < failureEvidenceEvery {
|
||||
return nil
|
||||
}
|
||||
if err != nil && !errors.Is(err, pgx.ErrNoRows) {
|
||||
return err
|
||||
}
|
||||
if r.OK {
|
||||
// Only the latest success is kept anyway.
|
||||
if prev, seen := successes[r.MonitorID]; !seen || r.StartedAt.After(prev.StartedAt) {
|
||||
successes[r.MonitorID] = r
|
||||
}
|
||||
row := store.InsertEvidenceParams{
|
||||
OrgID: m.OrgID, MonitorID: m.ID, Region: region, CheckerID: checker, Time: r.StartedAt, Ok: r.OK, Evidence: r.Evidence,
|
||||
}
|
||||
if r.StatusCode > 0 {
|
||||
row.StatusCode = ptr(int32(r.StatusCode))
|
||||
}
|
||||
if r.Error != "" {
|
||||
row.Error = ptr(truncateValid(r.Error, 500))
|
||||
}
|
||||
return q.InsertEvidence(ctx, row)
|
||||
})
|
||||
if err != nil {
|
||||
s.log.WarnContext(ctx, "storing evidence failed", "monitor", m.ID, "error", err)
|
||||
continue
|
||||
}
|
||||
failures = append(failures, r)
|
||||
if !slices.Contains(failed, r.MonitorID) {
|
||||
failed = append(failed, r.MonitorID)
|
||||
}
|
||||
}
|
||||
if len(successes) == 0 && len(failures) == 0 {
|
||||
return
|
||||
}
|
||||
slices.SortFunc(failures, func(a, b agentapi.Result) int { return a.StartedAt.Compare(b.StartedAt) })
|
||||
insert := func(q *store.Queries, r agentapi.Result) error {
|
||||
m := monitors[r.MonitorID]
|
||||
row := store.InsertEvidenceParams{
|
||||
OrgID: m.OrgID, MonitorID: m.ID, Region: region, CheckerID: checker, Time: r.StartedAt, Ok: r.OK, Evidence: r.Evidence,
|
||||
}
|
||||
if r.StatusCode > 0 {
|
||||
row.StatusCode = ptr(int32(r.StatusCode))
|
||||
}
|
||||
if r.Error != "" {
|
||||
row.Error = ptr(truncateValid(r.Error, 500))
|
||||
}
|
||||
return q.InsertEvidence(ctx, row)
|
||||
}
|
||||
err := s.db.Tx(ctx, tenant.System(), func(q *store.Queries) error {
|
||||
if len(successes) > 0 {
|
||||
ids := make([]uuid.UUID, 0, len(successes))
|
||||
for id := range successes {
|
||||
ids = append(ids, id)
|
||||
}
|
||||
if err := q.DeleteSuccessEvidence(ctx, store.DeleteSuccessEvidenceParams{Region: region, MonitorIds: ids}); err != nil {
|
||||
return err
|
||||
}
|
||||
for _, r := range successes {
|
||||
if err := insert(q, r); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
}
|
||||
if len(failures) == 0 {
|
||||
return nil
|
||||
}
|
||||
rows, err := q.LastFailureEvidence(ctx, store.LastFailureEvidenceParams{Region: region, MonitorIds: failed})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
last := make(map[uuid.UUID]store.LastFailureEvidenceRow, len(rows))
|
||||
for _, l := range rows {
|
||||
last[l.MonitorID] = l
|
||||
}
|
||||
for _, r := range failures {
|
||||
kept := truncateValid(r.Error, 500)
|
||||
if l, ok := last[r.MonitorID]; ok && l.Error == kept && r.StartedAt.Sub(l.Time) < failureEvidenceEvery {
|
||||
continue
|
||||
}
|
||||
if err := insert(q, r); err != nil {
|
||||
return err
|
||||
}
|
||||
last[r.MonitorID] = store.LastFailureEvidenceRow{MonitorID: r.MonitorID, Time: r.StartedAt, Error: kept}
|
||||
}
|
||||
return nil
|
||||
})
|
||||
if err != nil {
|
||||
s.log.WarnContext(ctx, "storing evidence failed", "results", len(successes)+len(failures), "error", err)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -2,12 +2,17 @@ package api_test
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"git.zb-server.de/ZB-Server/uptimesebi/internal/agentapi"
|
||||
)
|
||||
|
||||
func TestEvidence(t *testing.T) {
|
||||
@@ -103,3 +108,62 @@ func TestEvidence(t *testing.T) {
|
||||
t.Error("the monitor page links evidence for a viewer")
|
||||
}
|
||||
}
|
||||
|
||||
// TestEvidenceBatch stores a report with evidence of several monitors and
|
||||
// runs at once, as a checker sends after a backlog.
|
||||
func TestEvidenceBatch(t *testing.T) {
|
||||
e := newEnv(t)
|
||||
tok, region := e.platformChecker(t, uniq("ev-batch-"))
|
||||
owner := e.browser(t)
|
||||
owner.signup("o@"+uniq("evb")+".test", uniq("evb-"))
|
||||
monitor := func() uuid.UUID {
|
||||
_, m := owner.do("POST", "/api/v1/org/monitors", map[string]any{
|
||||
"name": "m", "type": "tcp", "target": "example.com:443", "interval_seconds": 3600, "regions": []string{region},
|
||||
})
|
||||
return uuid.MustParse(m["id"].(string))
|
||||
}
|
||||
up, down := monitor(), monitor()
|
||||
client := agentapi.NewClient(e.srv.URL, tok, uuid.New(), "test").WithHTTPClient(e.srv.Client())
|
||||
ev := json.RawMessage(`{"steps":[]}`)
|
||||
at := time.Now().Add(-time.Minute).Truncate(time.Millisecond)
|
||||
run := func(m uuid.UUID, after time.Duration, ok bool, msg string) agentapi.Result {
|
||||
return agentapi.Result{MonitorID: m, ScheduledAt: at.Add(after), StartedAt: at.Add(after), OK: ok, Error: msg, Evidence: ev}
|
||||
}
|
||||
if err := client.Report(context.Background(), []agentapi.Result{
|
||||
run(up, 0, true, ""),
|
||||
run(up, time.Second, true, ""),
|
||||
run(down, 0, false, "boom"),
|
||||
run(down, time.Second, false, "boom"),
|
||||
run(down, 2*time.Second, false, "other"),
|
||||
}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
// The latest success only; failures unless the same one was just kept.
|
||||
if n := e.count(t, `SELECT count(*) FROM check_evidence WHERE monitor_id = $1 AND ok AND time = $2`, up, at.Add(time.Second)); n != 1 {
|
||||
t.Errorf("success evidence of the latest run = %d rows, want 1", n)
|
||||
}
|
||||
if n := e.count(t, `SELECT count(*) FROM check_evidence WHERE monitor_id = $1`, up); n != 1 {
|
||||
t.Errorf("success evidence rows = %d, want 1", n)
|
||||
}
|
||||
if n := e.count(t, `SELECT count(*) FROM check_evidence WHERE monitor_id = $1 AND NOT ok`, down); n != 2 {
|
||||
t.Errorf("failure evidence rows = %d, want 2: boom once, then other", n)
|
||||
}
|
||||
|
||||
// The next report replaces the success and thins out the failure
|
||||
// already kept.
|
||||
if err := client.Report(context.Background(), []agentapi.Result{
|
||||
run(up, 5*time.Second, true, ""),
|
||||
run(down, 10*time.Second, false, "other"),
|
||||
}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if n := e.count(t, `SELECT count(*) FROM check_evidence WHERE monitor_id = $1 AND ok AND time = $2`, up, at.Add(5*time.Second)); n != 1 {
|
||||
t.Errorf("success evidence after the next report: latest run kept %d times, want 1", n)
|
||||
}
|
||||
if n := e.count(t, `SELECT count(*) FROM check_evidence WHERE monitor_id = $1`, up); n != 1 {
|
||||
t.Errorf("success evidence rows after the next report = %d, want 1", n)
|
||||
}
|
||||
if n := e.count(t, `SELECT count(*) FROM check_evidence WHERE monitor_id = $1 AND NOT ok`, down); n != 2 {
|
||||
t.Errorf("failure evidence rows after the next report = %d, want still 2", n)
|
||||
}
|
||||
}
|
||||
+16
-13
@@ -6,6 +6,7 @@ import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"math"
|
||||
"net/http"
|
||||
"time"
|
||||
|
||||
@@ -335,6 +336,8 @@ type exportStatusPage struct {
|
||||
CustomDomain *string `json:"custom_domain"`
|
||||
Groups []pageGroupView `json:"groups"`
|
||||
Monitors []exportPageMember `json:"monitors"`
|
||||
Subscriptions bool `json:"subscriptions"`
|
||||
Subscribers []subscriberView `json:"subscribers"`
|
||||
}
|
||||
|
||||
type exportPageMember struct {
|
||||
@@ -529,10 +532,19 @@ func (s *Server) buildOrgExport(ctx context.Context, p *principal) (orgExport, e
|
||||
MonitorID: m.MonitorID, GroupID: m.GroupID, Section: m.Section, Label: m.Label,
|
||||
})
|
||||
}
|
||||
subs, err := q.ListPageSubscribers(ctx, store.ListPageSubscribersParams{PageID: pg.ID, MaxRows: math.MaxInt32})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
subscribers := []subscriberView{}
|
||||
for _, r := range subs {
|
||||
subscribers = append(subscribers, subscriberView{r.ID, r.Email, r.Locale, r.CreatedAt, r.ConfirmedAt})
|
||||
}
|
||||
x.StatusPages = append(x.StatusPages, exportStatusPage{
|
||||
ID: pg.ID, Slug: pg.Slug, Title: pg.Title, Description: pg.Description,
|
||||
Published: pg.Published, ShowComponentDetails: pg.ShowComponentDetails,
|
||||
CustomDomain: pg.CustomDomain, Groups: exportedGroups, Monitors: members,
|
||||
Subscriptions: pg.Subscriptions, Subscribers: subscribers,
|
||||
})
|
||||
}
|
||||
|
||||
@@ -639,19 +651,6 @@ func (s *Server) loadUser(ctx context.Context, id uuid.UUID) (store.User, error)
|
||||
return u, err
|
||||
}
|
||||
|
||||
// purgeOrg deletes an organization with everything in it, including check
|
||||
// results and status page server storage, which have no foreign key.
|
||||
func purgeOrg(ctx context.Context, q *store.Queries, org uuid.UUID) error {
|
||||
if err := q.PurgeOrgCheckData(ctx, org); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := q.DeleteOrgStorage(ctx, org); err != nil {
|
||||
return err
|
||||
}
|
||||
_, err := q.DeleteOrg(ctx, org)
|
||||
return err
|
||||
}
|
||||
|
||||
// deleteAccount erases the signed-in user (Art. 17). Organizations the
|
||||
// user is the last owner of go with the account, monitors and all, even
|
||||
// when they have other members: nobody would be left to run them. The user
|
||||
@@ -732,6 +731,9 @@ func (s *Server) eraseAccount(ctx context.Context, u store.User) (orgsDeleted in
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
if orgsDeleted > 0 {
|
||||
s.wakeOrgPurges()
|
||||
}
|
||||
if err := s.sessions.DeleteAllForUser(ctx, u.ID); err != nil {
|
||||
s.log.ErrorContext(ctx, "ending sessions of deleted account failed", "error", err)
|
||||
}
|
||||
@@ -778,6 +780,7 @@ func (s *Server) deleteOrg(c *gin.Context) {
|
||||
internalError(c, err)
|
||||
return
|
||||
}
|
||||
s.wakeOrgPurges()
|
||||
if sess := auth.Current(c); sess != nil {
|
||||
_ = s.sessions.SwitchOrg(ctx, sess, uuid.Nil)
|
||||
}
|
||||
|
||||
@@ -176,6 +176,12 @@ func TestDeleteOrganization(t *testing.T) {
|
||||
})
|
||||
keepOrg := uuid.MustParse(keep.orgID())
|
||||
e.seedResults(t, keepOrg, uuid.MustParse(km["id"].(string)))
|
||||
// Results older than a week are compressed; the purge goes through them
|
||||
// as well.
|
||||
if _, err := e.dbPool.Exec(context.Background(),
|
||||
`SELECT compress_chunk(c, if_not_compressed => true) FROM show_chunks('check_results', older_than => now() - interval '1 day') c`); err != nil {
|
||||
t.Fatalf("compressing chunks: %v", err)
|
||||
}
|
||||
|
||||
admin := e.joinVia(t, owner.invite("a@"+uniq("d")+".test", owner.roleID("admin")))
|
||||
if st, body := admin.do("POST", "/api/v1/org/delete", map[string]any{"slug": slug, "password": password}); st != http.StatusForbidden {
|
||||
@@ -191,17 +197,33 @@ func TestDeleteOrganization(t *testing.T) {
|
||||
t.Fatalf("owner deletes org = %d %v", st, body)
|
||||
}
|
||||
|
||||
// The organization is gone at once, its check data is purged in the
|
||||
// background, chunk by chunk.
|
||||
for query, want := range map[string]int{
|
||||
`SELECT count(*) FROM orgs WHERE id = $1`: 0,
|
||||
`SELECT count(*) FROM monitors WHERE org_id = $1`: 0,
|
||||
`SELECT count(*) FROM check_results WHERE org_id = $1`: 0,
|
||||
`SELECT count(*) FROM check_results_1h WHERE org_id = $1`: 0,
|
||||
`SELECT count(*) FROM audit_events WHERE org_id = $1`: 0,
|
||||
`SELECT count(*) FROM orgs WHERE id = $1`: 0,
|
||||
`SELECT count(*) FROM monitors WHERE org_id = $1`: 0,
|
||||
`SELECT count(*) FROM org_purges WHERE org_id = $1`: 1,
|
||||
} {
|
||||
if got := e.count(t, query, org); got != want {
|
||||
t.Errorf("%s = %d, want %d", query, got, want)
|
||||
}
|
||||
}
|
||||
if err := e.api.PurgeDeletedOrgs(context.Background()); err != nil {
|
||||
t.Fatalf("PurgeDeletedOrgs() = %v", err)
|
||||
}
|
||||
for query, want := range map[string]int{
|
||||
`SELECT count(*) FROM check_results WHERE org_id = $1`: 0,
|
||||
`SELECT count(*) FROM check_results_1h WHERE org_id = $1`: 0,
|
||||
`SELECT count(*) FROM audit_events WHERE org_id = $1`: 0,
|
||||
`SELECT count(*) FROM org_purges WHERE org_id = $1`: 0,
|
||||
} {
|
||||
if got := e.count(t, query, org); got != want {
|
||||
t.Errorf("%s = %d, want %d", query, got, want)
|
||||
}
|
||||
}
|
||||
if e.count(t, `SELECT count(*) FROM check_results WHERE org_id = $1`, keepOrg) != 30 {
|
||||
t.Error("another organization's results were deleted")
|
||||
}
|
||||
if e.count(t, `SELECT count(*) FROM check_results_1h WHERE org_id = $1`, keepOrg) == 0 {
|
||||
t.Error("another organization's aggregates were deleted")
|
||||
}
|
||||
|
||||
@@ -129,10 +129,12 @@ func (s *Server) RunHeartbeats(ctx context.Context) {
|
||||
if err != nil || !got {
|
||||
continue
|
||||
}
|
||||
if err := s.CheckHeartbeats(ctx, time.Now()); err != nil && ctx.Err() == nil {
|
||||
if err := s.metrics.Job("heartbeats", func() error { return s.CheckHeartbeats(ctx, time.Now()) }); err != nil && ctx.Err() == nil {
|
||||
s.log.ErrorContext(ctx, "checking heartbeats failed", "error", err)
|
||||
}
|
||||
if err := s.CheckAlertmanagerMonitors(ctx, nil, time.Now(), false); err != nil && ctx.Err() == nil {
|
||||
if err := s.metrics.Job("alertmanager_monitors", func() error {
|
||||
return s.CheckAlertmanagerMonitors(ctx, nil, time.Now(), false)
|
||||
}); err != nil && ctx.Err() == nil {
|
||||
s.log.ErrorContext(ctx, "checking alertmanager monitors failed", "error", err)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -29,10 +29,11 @@ func (s *Server) RunHousekeeping(ctx context.Context) {
|
||||
// policies as owner.
|
||||
s.log.WarnContext(ctx, "applying retention policies failed", "error", err)
|
||||
}
|
||||
go s.runOrgPurges(ctx)
|
||||
tick := time.NewTicker(time.Hour)
|
||||
defer tick.Stop()
|
||||
for {
|
||||
if err := s.Housekeep(ctx, time.Now()); err != nil && ctx.Err() == nil {
|
||||
if err := s.metrics.Job("housekeeping", func() error { return s.Housekeep(ctx, time.Now()) }); err != nil && ctx.Err() == nil {
|
||||
s.log.ErrorContext(ctx, "housekeeping failed", "error", err)
|
||||
}
|
||||
select {
|
||||
@@ -47,7 +48,7 @@ func (s *Server) RunHousekeeping(ctx context.Context) {
|
||||
// tokens and incidents older than the daily aggregate.
|
||||
func (s *Server) Housekeep(ctx context.Context, now time.Time) error {
|
||||
keep := s.cfg.Retention
|
||||
var counts [7]int64
|
||||
var counts [9]int64
|
||||
err := s.db.Tx(ctx, tenant.System(), func(q *store.Queries) error {
|
||||
var err error
|
||||
if keep.Housekeeping > 0 {
|
||||
@@ -78,16 +79,24 @@ func (s *Server) Housekeep(ctx context.Context, now time.Time) error {
|
||||
if counts[6], err = q.PurgeUnverifiedUsers(ctx, now.Add(-unverifiedKeep)); err != nil {
|
||||
return err
|
||||
}
|
||||
if counts[7], err = q.PurgeUnconfirmedSubscribers(ctx, now.Add(-subscriberWindow)); err != nil {
|
||||
return err
|
||||
}
|
||||
if keep.Housekeeping > 0 {
|
||||
if counts[8], err = q.PurgeSubscriberNotifications(ctx, now.Add(-keep.Housekeeping)); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
if keep.Daily > 0 {
|
||||
before := now.Add(-keep.Daily)
|
||||
counts[3], err = q.PurgeIncidents(ctx, &before)
|
||||
}
|
||||
return err
|
||||
})
|
||||
if err == nil && counts != [7]int64{} {
|
||||
if err == nil && counts != [9]int64{} {
|
||||
s.log.InfoContext(ctx, "housekeeping purged rows",
|
||||
"notifications", counts[0], "invitations", counts[1], "api_tokens", counts[2], "incidents", counts[3], "audit_events", counts[4], "evidence", counts[5],
|
||||
"unverified_accounts", counts[6])
|
||||
"unverified_accounts", counts[6], "unconfirmed_subscribers", counts[7], "subscriber_notifications", counts[8])
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
@@ -268,6 +268,13 @@ func (s *Server) addIncidentUpdate(c *gin.Context) {
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if public {
|
||||
if _, err := q.EnqueueSubscriberNotifications(ctx, store.EnqueueSubscriberNotificationsParams{
|
||||
IncidentID: d.inc.ID, UpdateID: &u.ID, Event: "update",
|
||||
}); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return q.RefreshIncidentStatus(ctx, d.inc.ID)
|
||||
}); err != nil {
|
||||
internalError(c, err)
|
||||
|
||||
@@ -205,7 +205,9 @@ func (s *Server) legalPage(c *gin.Context) {
|
||||
}
|
||||
me = &m
|
||||
}
|
||||
web.Render(c, http.StatusOK, web.LegalPage(s.pageFor(c, web.LegalTitleID(kind)), me, html))
|
||||
p := s.pageFor(c, web.LegalTitleID(kind))
|
||||
p.Meta = s.publicMeta(c, "/legal/"+kind, web.LegalTitleID(kind))
|
||||
web.Render(c, http.StatusOK, web.LegalPage(p, me, html))
|
||||
return
|
||||
}
|
||||
c.Status(http.StatusNotFound)
|
||||
|
||||
+25
-15
@@ -38,11 +38,14 @@ type Limits struct {
|
||||
OrgsPerAccount int `json:"orgs_per_account"`
|
||||
// MonitorsPerPage limits the monitors one status page shows.
|
||||
MonitorsPerPage int `json:"monitors_per_page"`
|
||||
// SubscribersPerWeek limits the email subscriptions the organization's
|
||||
// status pages gain in seven days.
|
||||
SubscribersPerWeek int `json:"subscribers_per_week"`
|
||||
}
|
||||
|
||||
func (s *Server) defaultLimits() Limits {
|
||||
if s.cloud() {
|
||||
return Limits{OrgsPerAccount: 3}
|
||||
return Limits{OrgsPerAccount: 3, SubscribersPerWeek: 1000}
|
||||
}
|
||||
return Limits{}
|
||||
}
|
||||
@@ -82,6 +85,7 @@ func (s *Server) orgLimits(ctx context.Context, org store.Org) Limits {
|
||||
override(&l.StatusPages, org.LimitStatusPages)
|
||||
override(&l.RegionsPerMonitor, org.LimitRegionsPerMonitor)
|
||||
override(&l.MonitorsPerPage, org.LimitMonitorsPerPage)
|
||||
override(&l.SubscribersPerWeek, org.LimitSubscribersPerWeek)
|
||||
if org.LimitOwnRegionsCount != nil {
|
||||
l.OwnRegionsCount = *org.LimitOwnRegionsCount
|
||||
}
|
||||
@@ -192,7 +196,10 @@ type limitsRequest struct {
|
||||
RegionsPerMonitor int `json:"regions_per_monitor" binding:"min=0,max=1000"`
|
||||
OwnRegionsCount bool `json:"own_regions_count"`
|
||||
OrgsPerAccount int `json:"orgs_per_account" binding:"min=0,max=100000"`
|
||||
MonitorsPerPage int `json:"monitors_per_page" binding:"min=0,max=200"`
|
||||
MonitorsPerPage int `json:"monitors_per_page" binding:"min=0,max=1000000"`
|
||||
// SubscribersPerWeek is new email subscriptions per organization and
|
||||
// seven days.
|
||||
SubscribersPerWeek int `json:"subscribers_per_week" binding:"min=0,max=100000000"`
|
||||
}
|
||||
|
||||
func (s *Server) adminSetLimits(c *gin.Context) {
|
||||
@@ -243,11 +250,12 @@ func (o optBool) MarshalJSON() ([]byte, error) { return json.Marshal(o.v) }
|
||||
// orgLimitsRequest overrides limits for one organization; null follows the
|
||||
// platform default.
|
||||
type orgLimitsRequest struct {
|
||||
Monitors *int32 `json:"monitors" binding:"omitempty,min=0,max=1000000"`
|
||||
StatusPages *int32 `json:"status_pages" binding:"omitempty,min=0,max=1000000"`
|
||||
RegionsPerMonitor *int32 `json:"regions_per_monitor" binding:"omitempty,min=0,max=1000"`
|
||||
OwnRegionsCount optBool `json:"own_regions_count"`
|
||||
MonitorsPerPage *int32 `json:"monitors_per_page" binding:"omitempty,min=0,max=200"`
|
||||
Monitors *int32 `json:"monitors" binding:"omitempty,min=0,max=1000000"`
|
||||
StatusPages *int32 `json:"status_pages" binding:"omitempty,min=0,max=1000000"`
|
||||
RegionsPerMonitor *int32 `json:"regions_per_monitor" binding:"omitempty,min=0,max=1000"`
|
||||
OwnRegionsCount optBool `json:"own_regions_count"`
|
||||
MonitorsPerPage *int32 `json:"monitors_per_page" binding:"omitempty,min=0,max=1000000"`
|
||||
SubscribersPerWeek *int32 `json:"subscribers_per_week" binding:"omitempty,min=0,max=100000000"`
|
||||
}
|
||||
|
||||
func (s *Server) adminSetOrgLimits(c *gin.Context) {
|
||||
@@ -266,7 +274,7 @@ func (s *Server) adminSetOrgLimits(c *gin.Context) {
|
||||
row, err := q.SetOrgLimits(ctx, store.SetOrgLimitsParams{
|
||||
ID: id, Monitors: req.Monitors, StatusPages: req.StatusPages,
|
||||
RegionsPerMonitor: req.RegionsPerMonitor, OwnRegionsCount: req.OwnRegionsCount.v,
|
||||
MonitorsPerPage: req.MonitorsPerPage,
|
||||
MonitorsPerPage: req.MonitorsPerPage, SubscribersPerWeek: req.SubscribersPerWeek,
|
||||
})
|
||||
auditDetail(c, "slug", row.Slug)
|
||||
return err
|
||||
@@ -318,11 +326,12 @@ type adminOrg struct {
|
||||
}
|
||||
|
||||
type orgLimitsView struct {
|
||||
Monitors *int32 `json:"monitors"`
|
||||
StatusPages *int32 `json:"status_pages"`
|
||||
RegionsPerMonitor *int32 `json:"regions_per_monitor"`
|
||||
OwnRegionsCount *bool `json:"own_regions_count"`
|
||||
MonitorsPerPage *int32 `json:"monitors_per_page"`
|
||||
Monitors *int32 `json:"monitors"`
|
||||
StatusPages *int32 `json:"status_pages"`
|
||||
RegionsPerMonitor *int32 `json:"regions_per_monitor"`
|
||||
OwnRegionsCount *bool `json:"own_regions_count"`
|
||||
MonitorsPerPage *int32 `json:"monitors_per_page"`
|
||||
SubscribersPerWeek *int32 `json:"subscribers_per_week"`
|
||||
}
|
||||
|
||||
type adminOwner struct {
|
||||
@@ -349,10 +358,10 @@ func (s *Server) adminOrgs(ctx context.Context, search string, pg pageReq) ([]ad
|
||||
o := &out[i]
|
||||
o.moderatedOrg = moderatedOrg{r.ID, r.Slug, r.Name, r.SuspendedAt, r.SuspendedReason}
|
||||
o.Created = r.CreatedAt.Format("2006-01-02")
|
||||
o.Overrides = orgLimitsView{r.LimitMonitors, r.LimitStatusPages, r.LimitRegionsPerMonitor, r.LimitOwnRegionsCount, r.LimitMonitorsPerPage}
|
||||
o.Overrides = orgLimitsView{r.LimitMonitors, r.LimitStatusPages, r.LimitRegionsPerMonitor, r.LimitOwnRegionsCount, r.LimitMonitorsPerPage, r.LimitSubscribersPerWeek}
|
||||
o.Limits = s.orgLimits(ctx, store.Org{LimitMonitors: r.LimitMonitors, LimitStatusPages: r.LimitStatusPages,
|
||||
LimitRegionsPerMonitor: r.LimitRegionsPerMonitor, LimitOwnRegionsCount: r.LimitOwnRegionsCount,
|
||||
LimitMonitorsPerPage: r.LimitMonitorsPerPage})
|
||||
LimitMonitorsPerPage: r.LimitMonitorsPerPage, LimitSubscribersPerWeek: r.LimitSubscribersPerWeek})
|
||||
o.Limits.OrgsPerAccount = defaults.OrgsPerAccount
|
||||
o.Usage.Monitors, o.Usage.StatusPages = int(r.Monitors), int(r.StatusPages)
|
||||
if r.OwnerID != uuid.Nil {
|
||||
@@ -412,6 +421,7 @@ func (s *Server) orgsView(c *gin.Context, pg pageReq) (web.OrgsView, error) {
|
||||
Monitors: o.Usage.Monitors, StatusPages: o.Usage.StatusPages, Limits: webLimits(o.Limits),
|
||||
MonitorsOverride: optInt(o.Overrides.Monitors), StatusPagesOverride: optInt(o.Overrides.StatusPages),
|
||||
RegionsOverride: optInt(o.Overrides.RegionsPerMonitor), PerPageOverride: optInt(o.Overrides.MonitorsPerPage),
|
||||
SubscribersOverride: optInt(o.Overrides.SubscribersPerWeek),
|
||||
}
|
||||
if o.Overrides.OwnRegionsCount != nil {
|
||||
row.OwnRegionsOverride = strconv.FormatBool(*o.Overrides.OwnRegionsCount)
|
||||
|
||||
@@ -52,6 +52,22 @@ func TestLimits(t *testing.T) {
|
||||
})
|
||||
}
|
||||
|
||||
// The monitor form locks regions beyond the limit; own ones do not count.
|
||||
_, _, html := owner.page("/monitors/new")
|
||||
if !strings.Contains(html, `data-region-limit="1"`) {
|
||||
t.Error("monitor form lacks the region limit")
|
||||
}
|
||||
for id, counted := range map[string]bool{p1: true, o1: false} {
|
||||
i := strings.Index(html, `value="`+id+`"`)
|
||||
if i < 0 {
|
||||
t.Fatalf("monitor form lacks region %s", id)
|
||||
}
|
||||
tag := html[i : i+strings.Index(html[i:], ">")]
|
||||
if strings.Contains(tag, "data-counted") != counted {
|
||||
t.Errorf("region %s counted = %v, want %v", id, !counted, counted)
|
||||
}
|
||||
}
|
||||
|
||||
// Monitors, passive ones included.
|
||||
if st, body := owner.do("POST", "/api/v1/org/monitors", map[string]any{"name": "hb", "type": "heartbeat", "interval_seconds": 3600}); st != http.StatusCreated {
|
||||
t.Fatalf("heartbeat = %d %v", st, body)
|
||||
|
||||
@@ -0,0 +1,187 @@
|
||||
package api
|
||||
|
||||
import (
|
||||
"context"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/prometheus/client_golang/prometheus"
|
||||
|
||||
"git.zb-server.de/ZB-Server/uptimesebi/internal/agentapi"
|
||||
"git.zb-server.de/ZB-Server/uptimesebi/internal/store"
|
||||
"git.zb-server.de/ZB-Server/uptimesebi/internal/tenant"
|
||||
)
|
||||
|
||||
// Platform metrics are read from the database and Redis when scraped, at
|
||||
// most once per platformMetricsTTL, so scrapes stay cheap. Every replica
|
||||
// reports the same platform totals; dashboards take their max().
|
||||
const (
|
||||
platformMetricsTTL = 15 * time.Second
|
||||
// checksLateAfter leaves the runs alone that the next dispatch, every
|
||||
// second, takes anyway.
|
||||
checksLateAfter = 10 * time.Second
|
||||
)
|
||||
|
||||
var (
|
||||
descCheckers = prometheus.NewDesc("uptimesebi_checker_instances",
|
||||
"Live checker instances per platform region.", []string{"region"}, nil)
|
||||
descOverdue = prometheus.NewDesc("uptimesebi_checks_overdue",
|
||||
"Checks of a platform region due for more than 10 seconds and not started: undispatched, as when no checker of the region is live, or waiting in the queue of a checker too busy to take them.", []string{"region"}, nil)
|
||||
descRegions = prometheus.NewDesc("uptimesebi_regions",
|
||||
"Platform regions by whether a checker is live.", []string{"online"}, nil)
|
||||
descOrgs = prometheus.NewDesc("uptimesebi_orgs",
|
||||
"Organizations on the platform.", nil, nil)
|
||||
descUsers = prometheus.NewDesc("uptimesebi_users",
|
||||
"User accounts on the platform.", nil, nil)
|
||||
descMonitors = prometheus.NewDesc("uptimesebi_monitors",
|
||||
"Monitors by type and whether they are enabled.", []string{"type", "enabled"}, nil)
|
||||
descPages = prometheus.NewDesc("uptimesebi_status_pages",
|
||||
"Status pages on the platform.", nil, nil)
|
||||
descSubscribers = prometheus.NewDesc("uptimesebi_status_page_subscribers",
|
||||
"Confirmed subscribers of status pages.", nil, nil)
|
||||
descOpenIncidents = prometheus.NewDesc("uptimesebi_incidents_open",
|
||||
"Incidents not resolved yet.", nil, nil)
|
||||
descPending = prometheus.NewDesc("uptimesebi_notifications_pending",
|
||||
"Notifications waiting for delivery, by kind: channel or subscriber.", []string{"kind"}, nil)
|
||||
descScrapeError = prometheus.NewDesc("uptimesebi_platform_metrics_error",
|
||||
"1 if reading the platform metrics failed on the last attempt.", nil, nil)
|
||||
)
|
||||
|
||||
type platformSnapshot struct {
|
||||
counts store.PlatformCountsRow
|
||||
monitors []store.MonitorCountsRow
|
||||
regions []regionLoad
|
||||
}
|
||||
|
||||
type regionLoad struct {
|
||||
key string
|
||||
checkers int64
|
||||
overdue int64
|
||||
}
|
||||
|
||||
// platformCollector reports the platform's totals, checkers and backlog.
|
||||
type platformCollector struct {
|
||||
s *Server
|
||||
mu sync.Mutex
|
||||
last platformSnapshot
|
||||
err error
|
||||
expires time.Time
|
||||
}
|
||||
|
||||
// Describe implements prometheus.Collector.
|
||||
func (p *platformCollector) Describe(ch chan<- *prometheus.Desc) {
|
||||
for _, d := range []*prometheus.Desc{
|
||||
descCheckers, descOverdue, descRegions, descOrgs, descUsers, descMonitors,
|
||||
descPages, descSubscribers, descOpenIncidents, descPending, descScrapeError,
|
||||
} {
|
||||
ch <- d
|
||||
}
|
||||
}
|
||||
|
||||
// Collect implements prometheus.Collector. It reads the database and
|
||||
// Redis at most once per platformMetricsTTL.
|
||||
func (p *platformCollector) Collect(ch chan<- prometheus.Metric) {
|
||||
p.mu.Lock()
|
||||
if time.Now().After(p.expires) {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
|
||||
snap, err := p.s.platformSnapshot(ctx)
|
||||
cancel()
|
||||
// A failed read keeps the last good values, flagged.
|
||||
if err == nil {
|
||||
p.last = snap
|
||||
} else {
|
||||
p.s.log.Warn("reading platform metrics failed", "error", err)
|
||||
}
|
||||
p.err, p.expires = err, time.Now().Add(platformMetricsTTL)
|
||||
}
|
||||
snap, failed := p.last, p.err != nil
|
||||
p.mu.Unlock()
|
||||
|
||||
gauge := func(d *prometheus.Desc, v int64, labels ...string) {
|
||||
ch <- prometheus.MustNewConstMetric(d, prometheus.GaugeValue, float64(v), labels...)
|
||||
}
|
||||
var online, offline int64
|
||||
for _, r := range snap.regions {
|
||||
gauge(descCheckers, r.checkers, r.key)
|
||||
gauge(descOverdue, r.overdue, r.key)
|
||||
if r.checkers > 0 {
|
||||
online++
|
||||
} else {
|
||||
offline++
|
||||
}
|
||||
}
|
||||
gauge(descRegions, online, "true")
|
||||
gauge(descRegions, offline, "false")
|
||||
c := snap.counts
|
||||
gauge(descOrgs, c.Orgs)
|
||||
gauge(descUsers, c.Users)
|
||||
gauge(descPages, c.StatusPages)
|
||||
gauge(descSubscribers, c.Subscribers)
|
||||
gauge(descOpenIncidents, c.OpenIncidents)
|
||||
gauge(descPending, c.PendingNotifications, "channel")
|
||||
gauge(descPending, c.PendingSubscriberNotifications, "subscriber")
|
||||
for _, m := range snap.monitors {
|
||||
enabled := "false"
|
||||
if m.Enabled {
|
||||
enabled = "true"
|
||||
}
|
||||
gauge(descMonitors, m.Monitors, m.Type, enabled)
|
||||
}
|
||||
var flag int64
|
||||
if failed {
|
||||
flag = 1
|
||||
}
|
||||
gauge(descScrapeError, flag)
|
||||
}
|
||||
|
||||
func (s *Server) platformSnapshot(ctx context.Context) (platformSnapshot, error) {
|
||||
var (
|
||||
snap platformSnapshot
|
||||
regions []store.Region
|
||||
)
|
||||
err := s.db.Tx(ctx, tenant.System(), func(q *store.Queries) error {
|
||||
var err error
|
||||
if snap.counts, err = q.PlatformCounts(ctx); err != nil {
|
||||
return err
|
||||
}
|
||||
if snap.monitors, err = q.MonitorCounts(ctx); err != nil {
|
||||
return err
|
||||
}
|
||||
regions, err = q.ListPlatformRegions(ctx)
|
||||
return err
|
||||
})
|
||||
if err != nil {
|
||||
return snap, err
|
||||
}
|
||||
for _, r := range regions {
|
||||
n, err := s.sched.Instances(ctx, r.ID.String())
|
||||
if err != nil {
|
||||
return snap, err
|
||||
}
|
||||
late, err := s.sched.Overdue(ctx, r.ID.String(), checksLateAfter)
|
||||
if err != nil {
|
||||
return snap, err
|
||||
}
|
||||
snap.regions = append(snap.regions, regionLoad{key: r.Key, checkers: n, overdue: late})
|
||||
}
|
||||
return snap, nil
|
||||
}
|
||||
|
||||
// regionLabel names a checker's region in metrics: the key of a platform
|
||||
// region, or "own" for organizations' checkers, whose regions are many and
|
||||
// not the operator's.
|
||||
func regionLabel(a store.GetAgentByHashRow) string {
|
||||
if a.OrgID != nil {
|
||||
return "own"
|
||||
}
|
||||
if a.RegionKey != nil {
|
||||
return *a.RegionKey
|
||||
}
|
||||
return "none"
|
||||
}
|
||||
|
||||
// StreamingRoutes stay open on purpose: the agents' streams and the
|
||||
// checkers' long polls. Request metrics count them but do not time them.
|
||||
func StreamingRoutes() []string {
|
||||
return []string{agentapi.Prefix + agentapi.StreamPath, agentapi.Prefix + "/jobs"}
|
||||
}
|
||||
@@ -0,0 +1,90 @@
|
||||
package api_test
|
||||
|
||||
import (
|
||||
"context"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strconv"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"git.zb-server.de/ZB-Server/uptimesebi/internal/agentapi"
|
||||
)
|
||||
|
||||
// scrape returns the value of every series of the API's metrics, keyed by
|
||||
// name and labels as the text format prints them.
|
||||
func (e *env) scrape(t *testing.T) map[string]float64 {
|
||||
t.Helper()
|
||||
rec := httptest.NewRecorder()
|
||||
e.metrics.Handler().ServeHTTP(rec, httptest.NewRequest(http.MethodGet, "/metrics", nil))
|
||||
if rec.Code != http.StatusOK || !strings.HasPrefix(rec.Header().Get("Content-Type"), "text/plain") {
|
||||
t.Fatalf("metrics answered %d %q", rec.Code, rec.Header().Get("Content-Type"))
|
||||
}
|
||||
body, _ := io.ReadAll(rec.Body)
|
||||
out := map[string]float64{}
|
||||
for _, line := range strings.Split(string(body), "\n") {
|
||||
if line == "" || strings.HasPrefix(line, "#") {
|
||||
continue
|
||||
}
|
||||
i := strings.LastIndexByte(line, ' ')
|
||||
v, err := strconv.ParseFloat(line[i+1:], 64)
|
||||
if err != nil {
|
||||
t.Fatalf("bad metric line %q", line)
|
||||
}
|
||||
out[line[:i]] = v
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func TestMetrics(t *testing.T) {
|
||||
e := newEnv(t)
|
||||
key := uniq("metrics-")
|
||||
tok, region := e.platformChecker(t, key)
|
||||
owner := e.browser(t)
|
||||
owner.signup("o@"+uniq("id")+".test", uniq("id-"))
|
||||
_, m := owner.do("POST", "/api/v1/org/monitors", map[string]any{
|
||||
"name": "m", "type": "tcp", "target": "example.com:443", "interval_seconds": 3600, "regions": []string{region},
|
||||
})
|
||||
monitor := uuid.MustParse(m["id"].(string))
|
||||
client := agentapi.NewClient(e.srv.URL, tok, uuid.New(), "test").WithHTTPClient(e.srv.Client())
|
||||
at := time.Now().Truncate(time.Millisecond)
|
||||
batch := []agentapi.Result{
|
||||
{MonitorID: monitor, ScheduledAt: at, StartedAt: at, OK: true},
|
||||
{MonitorID: monitor, ScheduledAt: at.Add(time.Second), StartedAt: at.Add(time.Second), OK: false},
|
||||
{MonitorID: uuid.New(), ScheduledAt: at, StartedAt: at, OK: true},
|
||||
}
|
||||
for range 2 {
|
||||
if err := client.Report(context.Background(), batch); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
got := e.scrape(t)
|
||||
for series, want := range map[string]float64{
|
||||
`uptimesebi_check_results_total{ok="true",region="` + key + `"}`: 1,
|
||||
`uptimesebi_check_results_total{ok="false",region="` + key + `"}`: 1,
|
||||
`uptimesebi_check_results_rejected_total{reason="duplicate"}`: 3,
|
||||
`uptimesebi_check_results_rejected_total{reason="unknown_monitor"}`: 1,
|
||||
`uptimesebi_checker_instances{region="` + key + `"}`: 0,
|
||||
`uptimesebi_platform_metrics_error`: 0,
|
||||
} {
|
||||
if v, ok := got[series]; !ok || v != want {
|
||||
t.Errorf("%s = %v (present %v), want %v", series, v, ok, want)
|
||||
}
|
||||
}
|
||||
// Other tests share the database, so totals are at least ours.
|
||||
for series, least := range map[string]float64{
|
||||
`uptimesebi_orgs`: 1,
|
||||
`uptimesebi_users`: 1,
|
||||
`uptimesebi_monitors{enabled="true",type="tcp"}`: 1,
|
||||
`uptimesebi_regions{online="false"}`: 1,
|
||||
} {
|
||||
if got[series] < least {
|
||||
t.Errorf("%s = %v, want at least %v", series, got[series], least)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -205,6 +205,7 @@ func (s *Server) adminDeleteOrg(c *gin.Context) {
|
||||
return purgeOrg(ctx, q, id)
|
||||
})
|
||||
if moderated(c, err) {
|
||||
s.wakeOrgPurges()
|
||||
c.Status(http.StatusNoContent)
|
||||
}
|
||||
}
|
||||
|
||||
+18
-10
@@ -224,7 +224,11 @@ func (s *Server) listMonitors(c *gin.Context) {
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
latest, err := q.LatestResults(ctx, p.Org.ID)
|
||||
ids := make([]uuid.UUID, len(monitors))
|
||||
for i, m := range monitors {
|
||||
ids[i] = m.ID
|
||||
}
|
||||
latest, err := q.LatestResultsForMonitors(ctx, store.LatestResultsForMonitorsParams{OrgID: p.Org.ID, Ids: ids})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -530,6 +534,7 @@ func (s *Server) RunScheduler(ctx context.Context) {
|
||||
return
|
||||
case <-dispatch.C:
|
||||
n, err := s.sched.Dispatch(ctx)
|
||||
s.metrics.Dispatched(n)
|
||||
if err != nil && ctx.Err() == nil {
|
||||
s.log.WarnContext(ctx, "dispatch failed", "error", err)
|
||||
}
|
||||
@@ -551,19 +556,22 @@ func (s *Server) reconcile(ctx context.Context) {
|
||||
// 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
|
||||
rows, err = q.ListEnabledMonitorsForSchedule(ctx)
|
||||
return err
|
||||
})
|
||||
if err == nil {
|
||||
err = s.metrics.Job("reconcile", func() error {
|
||||
var rows []store.ListEnabledMonitorsForScheduleRow
|
||||
err := s.db.Tx(ctx, tenant.System(), func(q *store.Queries) error {
|
||||
var err error
|
||||
rows, err = q.ListEnabledMonitorsForSchedule(ctx)
|
||||
return err
|
||||
})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
want := make([]schedule.Monitor, len(rows))
|
||||
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, start)
|
||||
}
|
||||
return s.sched.Reconcile(ctx, want, start)
|
||||
})
|
||||
if err != nil && ctx.Err() == nil {
|
||||
s.log.WarnContext(ctx, "schedule reconciliation failed", "error", err)
|
||||
}
|
||||
|
||||
@@ -0,0 +1,119 @@
|
||||
package api
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"github.com/jackc/pgx/v5"
|
||||
|
||||
"git.zb-server.de/ZB-Server/uptimesebi/internal/store"
|
||||
"git.zb-server.de/ZB-Server/uptimesebi/internal/tenant"
|
||||
)
|
||||
|
||||
// orgPurgeEvery is how often an instance looks for deleted organizations
|
||||
// whose check data is left, besides right after a deletion.
|
||||
const orgPurgeEvery = time.Minute
|
||||
|
||||
// purgeOrg deletes an organization with everything in it at once, except
|
||||
// its check results and aggregates: they carry no foreign key and can run
|
||||
// to gigabytes, more than a request can delete in time, so it queues them
|
||||
// for PurgeDeletedOrgs. Nothing shows them once the organization is gone.
|
||||
func purgeOrg(ctx context.Context, q *store.Queries, org uuid.UUID) error {
|
||||
if err := q.QueueOrgPurge(ctx, org); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := q.DeleteOrgStorage(ctx, org); err != nil {
|
||||
return err
|
||||
}
|
||||
_, err := q.DeleteOrg(ctx, org)
|
||||
return err
|
||||
}
|
||||
|
||||
// wakeOrgPurges has PurgeDeletedOrgs run soon after a deletion instead of
|
||||
// at the next tick.
|
||||
func (s *Server) wakeOrgPurges() {
|
||||
select {
|
||||
case s.orgPurges <- struct{}{}:
|
||||
default:
|
||||
}
|
||||
}
|
||||
|
||||
// runOrgPurges purges the check data of deleted organizations every
|
||||
// orgPurgeEvery and when woken, until ctx ends.
|
||||
func (s *Server) runOrgPurges(ctx context.Context) {
|
||||
tick := time.NewTicker(orgPurgeEvery)
|
||||
defer tick.Stop()
|
||||
for {
|
||||
if err := s.metrics.Job("org_purge", func() error { return s.PurgeDeletedOrgs(ctx) }); err != nil && ctx.Err() == nil {
|
||||
s.log.ErrorContext(ctx, "purging deleted organizations failed", "error", err)
|
||||
}
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return
|
||||
case <-tick.C:
|
||||
case <-s.orgPurges:
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// PurgeDeletedOrgs deletes the check data of deleted organizations a chunk
|
||||
// at a time, each in a transaction of its own, until none is left. An
|
||||
// instance leases an organization while it purges it; if it stops, another
|
||||
// takes over once the lease runs out and repeats the chunks, which then
|
||||
// delete nothing.
|
||||
func (s *Server) PurgeDeletedOrgs(ctx context.Context) error {
|
||||
for ctx.Err() == nil {
|
||||
var org uuid.UUID
|
||||
err := s.db.Tx(ctx, tenant.System(), func(q *store.Queries) error {
|
||||
var err error
|
||||
org, err = q.ClaimOrgPurge(ctx)
|
||||
return err
|
||||
})
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return nil
|
||||
}
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if err := s.purgeOrgCheckData(ctx, org); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return ctx.Err()
|
||||
}
|
||||
|
||||
func (s *Server) purgeOrgCheckData(ctx context.Context, org uuid.UUID) error {
|
||||
start := time.Now()
|
||||
var chunks []string
|
||||
err := s.db.Tx(ctx, tenant.System(), func(q *store.Queries) error {
|
||||
var err error
|
||||
chunks, err = q.OrgCheckDataChunks(ctx)
|
||||
return err
|
||||
})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
var rows int64
|
||||
for _, chunk := range chunks {
|
||||
err := s.db.Tx(ctx, tenant.System(), func(q *store.Queries) error {
|
||||
n, err := q.PurgeOrgCheckChunk(ctx, store.PurgeOrgCheckChunkParams{OrgID: org, Chunk: chunk})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
rows += n
|
||||
return q.ExtendOrgPurge(ctx, org)
|
||||
})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
err = s.db.Tx(ctx, tenant.System(), func(q *store.Queries) error { return q.FinishOrgPurge(ctx, org) })
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
s.log.InfoContext(ctx, "purged check data of deleted organization",
|
||||
"org", org, "rows", rows, "chunks", len(chunks), "duration", time.Since(start).Round(time.Millisecond))
|
||||
return nil
|
||||
}
|
||||
@@ -104,7 +104,9 @@ func (s *Server) loginPage(c *gin.Context) {
|
||||
}
|
||||
allowed := email || len(signupProviders) > 0
|
||||
providers := s.platformButtons(c.Request.Context(), false)
|
||||
web.Render(c, http.StatusOK, web.Login(s.pageFor(c, "auth.login.title"), allowed, next, providers, c.Query("mfa") == "1"))
|
||||
p := s.pageFor(c, "auth.login.title")
|
||||
p.Meta = s.publicMeta(c, "/login", "auth.login.title")
|
||||
web.Render(c, http.StatusOK, web.Login(p, allowed, next, providers, c.Query("mfa") == "1"))
|
||||
}
|
||||
|
||||
// signupOptions tells whether people may sign up with email, and which
|
||||
@@ -141,7 +143,9 @@ func (s *Server) signupPage(c *gin.Context) {
|
||||
internalError(c, err)
|
||||
return
|
||||
}
|
||||
web.Render(c, http.StatusOK, web.Signup(s.pageFor(c, "auth.signup.title"), providers, email, consent))
|
||||
p := s.pageFor(c, "auth.signup.title")
|
||||
p.Meta = s.publicMeta(c, "/signup", "auth.signup.title")
|
||||
web.Render(c, http.StatusOK, web.Signup(p, providers, email, consent))
|
||||
}
|
||||
|
||||
func (s *Server) signupSentPage(c *gin.Context) {
|
||||
@@ -625,7 +629,7 @@ func (s *Server) adminPage(c *gin.Context) {
|
||||
for _, t := range check.Types {
|
||||
types = append(types, web.CheckTypeOption{Type: string(t), Enabled: !off[string(t)]})
|
||||
}
|
||||
web.Render(c, http.StatusOK, web.AdminPage(s.pageFor(c, "admin.title"), me, v, storageView(c, stats), types, s.platformPrivate(ctx), webLimits(s.platformLimits(ctx)), s.idpAdminView(ctx)))
|
||||
web.Render(c, http.StatusOK, web.AdminPage(s.pageFor(c, "admin.title"), me, v, storageView(c, stats), types, s.platformPrivate(ctx), s.statusPageHome(ctx), webLimits(s.platformLimits(ctx)), s.idpAdminView(ctx)))
|
||||
}
|
||||
|
||||
func (s *Server) adminStatusPagesPage(c *gin.Context) {
|
||||
@@ -670,7 +674,7 @@ func (s *Server) buildRegionsView(ctx context.Context, regions []store.Region, a
|
||||
if err != nil {
|
||||
return v, err
|
||||
}
|
||||
wr := web.Region{ID: r.ID.String(), Key: r.Key, Name: r.Name, Platform: r.OrgID == nil, Manageable: manageable(r), Instances: n}
|
||||
wr := web.Region{ID: r.ID.String(), Key: r.Key, Name: r.Name, Platform: r.OrgID == nil, Manageable: manageable(r), Instances: n, Lat: r.Latitude, Lon: r.Longitude}
|
||||
v.Regions = append(v.Regions, wr)
|
||||
if wr.Manageable {
|
||||
v.OwnRegions = append(v.OwnRegions, wr)
|
||||
|
||||
@@ -134,10 +134,7 @@ func (s *Server) messageFor(ev notify.Event, locale string) notify.Message {
|
||||
switch ev.Kind {
|
||||
case notify.Opened:
|
||||
m.Title = l.T("notify.title_opened", data)
|
||||
for region, msg := range ev.Cause {
|
||||
lines = append(lines, region+": "+msg)
|
||||
}
|
||||
slices.Sort(lines)
|
||||
lines = causeLines(ev, l)
|
||||
case notify.Resolved:
|
||||
m.Title = l.T("notify.title_resolved", data)
|
||||
if ev.ResolvedAt != nil {
|
||||
@@ -151,8 +148,6 @@ func (s *Server) messageFor(ev notify.Event, locale string) notify.Message {
|
||||
lines = append([]string{ev.Monitor.Type + " · " + ev.Monitor.Target}, lines...)
|
||||
}
|
||||
m.Body = strings.Join(lines, "\n")
|
||||
if ev.Monitor.ID != [16]byte{} {
|
||||
m.URL = strings.TrimSuffix(s.cfg.PublicURL, "/") + "/monitors/" + ev.Monitor.ID.String()
|
||||
}
|
||||
m.URL = s.monitorLink(ev)
|
||||
return m
|
||||
}
|
||||
@@ -0,0 +1,82 @@
|
||||
package api
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
|
||||
"git.zb-server.de/ZB-Server/uptimesebi/internal/store"
|
||||
"git.zb-server.de/ZB-Server/uptimesebi/internal/tenant"
|
||||
)
|
||||
|
||||
// publicRegionsTTL is how long an instance serves the platform regions
|
||||
// from memory, so the endpoint costs the database next to nothing however
|
||||
// often a front page asks.
|
||||
const publicRegionsTTL = 30 * time.Second
|
||||
|
||||
// publicRegion is a platform region as anyone may see it. Organizations'
|
||||
// own regions are never listed.
|
||||
type publicRegion struct {
|
||||
Key string `json:"key"`
|
||||
Name string `json:"name"`
|
||||
// Latitude and longitude are absent for regions without a location.
|
||||
Latitude *float64 `json:"latitude,omitempty"`
|
||||
Longitude *float64 `json:"longitude,omitempty"`
|
||||
// Online is set while at least one checker of the region is connected.
|
||||
Online bool `json:"online"`
|
||||
}
|
||||
|
||||
type publicRegionsCache struct {
|
||||
mu sync.Mutex
|
||||
body []byte
|
||||
expires time.Time
|
||||
}
|
||||
|
||||
// listPublicRegions answers without authentication and to any origin, for
|
||||
// a website showing where the platform checks from.
|
||||
func (s *Server) listPublicRegions(c *gin.Context) {
|
||||
c.Header("Access-Control-Allow-Origin", "*")
|
||||
c.Header("Cache-Control", "public, max-age=60")
|
||||
body, err := s.publicRegionsBody(c)
|
||||
if err != nil {
|
||||
internalError(c, err)
|
||||
return
|
||||
}
|
||||
c.Data(http.StatusOK, "application/json; charset=utf-8", body)
|
||||
}
|
||||
|
||||
func (s *Server) publicRegionsBody(c *gin.Context) ([]byte, error) {
|
||||
cache := &s.publicRegions
|
||||
cache.mu.Lock()
|
||||
defer cache.mu.Unlock()
|
||||
if cache.body != nil && time.Now().Before(cache.expires) {
|
||||
return cache.body, nil
|
||||
}
|
||||
ctx := c.Request.Context()
|
||||
var rows []store.Region
|
||||
err := s.db.Tx(ctx, tenant.System(), func(q *store.Queries) error {
|
||||
var err error
|
||||
rows, err = q.ListPlatformRegions(ctx)
|
||||
return err
|
||||
})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
out := make([]publicRegion, len(rows))
|
||||
for i, r := range rows {
|
||||
n, err := s.sched.Instances(ctx, r.ID.String())
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
out[i] = publicRegion{Key: r.Key, Name: r.Name, Latitude: r.Latitude, Longitude: r.Longitude, Online: n > 0}
|
||||
}
|
||||
body, err := json.Marshal(gin.H{"regions": out})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
cache.body, cache.expires = body, time.Now().Add(publicRegionsTTL)
|
||||
return body, nil
|
||||
}
|
||||
@@ -8,6 +8,7 @@ import (
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"github.com/jackc/pgx/v5"
|
||||
)
|
||||
|
||||
func TestTimeRangesAndSLA(t *testing.T) {
|
||||
@@ -53,7 +54,7 @@ func TestTimeRangesAndSLA(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
bars := map[string]int{"1h": 60, "3h": 36, "12h": 48, "24h": 48, "7d": 42, "30d": 60, "90d": 45, "180d": 45, "1y": 52}
|
||||
bars := map[string]int{"1h": 60, "3h": 36, "12h": 48, "24h": 24, "7d": 42, "30d": 60, "90d": 45, "180d": 45, "1y": 52}
|
||||
for key, n := range bars {
|
||||
st, _, html := owner.page("/?range=" + key)
|
||||
if st != http.StatusOK {
|
||||
@@ -99,9 +100,16 @@ func TestRangeAvailabilityAndRegions(t *testing.T) {
|
||||
id := uuid.MustParse(body["id"].(string))
|
||||
org := uuid.MustParse(owner.orgID())
|
||||
|
||||
// Two hours of results: eu always fine, us always failing.
|
||||
// Two hours of results: eu always fine, us always failing. (The
|
||||
// monitor is as old as its results.)
|
||||
ctx := context.Background()
|
||||
now := time.Now()
|
||||
if err := e.asSystem(t, func(tx pgx.Tx) error {
|
||||
_, err := tx.Exec(ctx, `UPDATE monitors SET created_at = $1 WHERE id = $2`, now.Add(-121*time.Minute), id)
|
||||
return err
|
||||
}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
checker := uuid.New()
|
||||
for m := 0; m <= 120; m += 5 {
|
||||
at := now.Add(-time.Duration(m) * time.Minute)
|
||||
|
||||
+86
-8
@@ -28,6 +28,14 @@ type regionView struct {
|
||||
// regions.
|
||||
Own bool `json:"own"`
|
||||
Instances int64 `json:"instances"`
|
||||
// Latitude and longitude place the region on the map; both are absent
|
||||
// for regions without a location.
|
||||
Latitude *float64 `json:"latitude,omitempty"`
|
||||
Longitude *float64 `json:"longitude,omitempty"`
|
||||
}
|
||||
|
||||
func newRegionView(r store.Region, org uuid.UUID, instances int64) regionView {
|
||||
return regionView{ID: r.ID, Key: r.Key, Name: r.Name, Own: r.OrgID != nil && *r.OrgID == org, Instances: instances, Latitude: r.Latitude, Longitude: r.Longitude}
|
||||
}
|
||||
|
||||
func (s *Server) viewRegions(ctx context.Context, rows []store.Region, org uuid.UUID) ([]regionView, error) {
|
||||
@@ -37,7 +45,7 @@ func (s *Server) viewRegions(ctx context.Context, rows []store.Region, org uuid.
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
out[i] = regionView{ID: r.ID, Key: r.Key, Name: r.Name, Own: r.OrgID != nil && *r.OrgID == org, Instances: n}
|
||||
out[i] = newRegionView(r, org, n)
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
@@ -67,6 +75,7 @@ func (s *Server) listOrgRegions(c *gin.Context) {
|
||||
type regionRequest struct {
|
||||
Key string `json:"key" binding:"required,max=40"`
|
||||
Name string `json:"name" binding:"max=100"`
|
||||
regionLocation
|
||||
}
|
||||
|
||||
func (r *regionRequest) normalize() bool {
|
||||
@@ -78,6 +87,20 @@ func (r *regionRequest) normalize() bool {
|
||||
return regionKeyRE.MatchString(r.Key)
|
||||
}
|
||||
|
||||
// regionLocation is where a region's checkers stand; null for both
|
||||
// coordinates means no location.
|
||||
type regionLocation struct {
|
||||
Latitude *float64 `json:"latitude"`
|
||||
Longitude *float64 `json:"longitude"`
|
||||
}
|
||||
|
||||
func (l regionLocation) valid() bool {
|
||||
if l.Latitude == nil || l.Longitude == nil {
|
||||
return l.Latitude == nil && l.Longitude == nil
|
||||
}
|
||||
return *l.Latitude >= -90 && *l.Latitude <= 90 && *l.Longitude >= -180 && *l.Longitude <= 180
|
||||
}
|
||||
|
||||
func (s *Server) createRegion(c *gin.Context, scope tenant.Scope, org *uuid.UUID) {
|
||||
var req regionRequest
|
||||
if !bind(c, &req) {
|
||||
@@ -87,11 +110,15 @@ func (s *Server) createRegion(c *gin.Context, scope tenant.Scope, org *uuid.UUID
|
||||
fail(c, http.StatusUnprocessableEntity, "invalid_region_key")
|
||||
return
|
||||
}
|
||||
if !req.valid() {
|
||||
fail(c, http.StatusUnprocessableEntity, "invalid_location")
|
||||
return
|
||||
}
|
||||
ctx := c.Request.Context()
|
||||
var row store.Region
|
||||
err := s.db.Tx(ctx, scope, func(q *store.Queries) error {
|
||||
var err error
|
||||
row, err = q.CreateRegion(ctx, store.CreateRegionParams{OrgID: org, Key: req.Key, Name: req.Name})
|
||||
row, err = q.CreateRegion(ctx, store.CreateRegionParams{OrgID: org, Key: req.Key, Name: req.Name, Latitude: req.Latitude, Longitude: req.Longitude})
|
||||
return err
|
||||
})
|
||||
if isUniqueViolation(err, "regions_owner_key_key") {
|
||||
@@ -102,7 +129,41 @@ func (s *Server) createRegion(c *gin.Context, scope tenant.Scope, org *uuid.UUID
|
||||
internalError(c, err)
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusCreated, regionView{ID: row.ID, Key: row.Key, Name: row.Name, Own: org != nil})
|
||||
v := newRegionView(row, uuid.Nil, 0)
|
||||
v.Own = org != nil
|
||||
c.JSON(http.StatusCreated, v)
|
||||
}
|
||||
|
||||
// updateRegion sets or removes a region's location.
|
||||
func (s *Server) updateRegion(c *gin.Context, scope tenant.Scope) {
|
||||
id, err := uuid.Parse(c.Param("id"))
|
||||
if err != nil {
|
||||
fail(c, http.StatusNotFound, "not_found")
|
||||
return
|
||||
}
|
||||
var req regionLocation
|
||||
if !bind(c, &req) {
|
||||
return
|
||||
}
|
||||
if !req.valid() {
|
||||
fail(c, http.StatusUnprocessableEntity, "invalid_location")
|
||||
return
|
||||
}
|
||||
ctx := c.Request.Context()
|
||||
var n int64
|
||||
err = s.db.Tx(ctx, scope, func(q *store.Queries) error {
|
||||
n, err = q.UpdateRegionLocation(ctx, store.UpdateRegionLocationParams{ID: id, Latitude: req.Latitude, Longitude: req.Longitude})
|
||||
return err
|
||||
})
|
||||
if err != nil {
|
||||
internalError(c, err)
|
||||
return
|
||||
}
|
||||
if n == 0 {
|
||||
fail(c, http.StatusNotFound, "not_found")
|
||||
return
|
||||
}
|
||||
c.Status(http.StatusNoContent)
|
||||
}
|
||||
|
||||
func (s *Server) deleteRegion(c *gin.Context, scope tenant.Scope) {
|
||||
@@ -141,6 +202,9 @@ func (s *Server) createOrgRegion(c *gin.Context) {
|
||||
// hides platform regions from writes in an org scope.
|
||||
func (s *Server) deleteOrgRegion(c *gin.Context) { s.deleteRegion(c, current(c).scope()) }
|
||||
|
||||
// updateOrgRegion, like deleteOrgRegion, reaches the org's own regions only.
|
||||
func (s *Server) updateOrgRegion(c *gin.Context) { s.updateRegion(c, current(c).scope()) }
|
||||
|
||||
type agentView struct {
|
||||
ID uuid.UUID `json:"id"`
|
||||
Kind string `json:"kind"`
|
||||
@@ -323,11 +387,25 @@ func (s *Server) adminListRegions(c *gin.Context) {
|
||||
func (s *Server) adminCreateRegion(c *gin.Context) { s.createRegion(c, tenant.System(), nil) }
|
||||
|
||||
func (s *Server) adminDeleteRegion(c *gin.Context) {
|
||||
// The system scope could reach org regions; only platform ones are meant.
|
||||
if s.platformRegion(c) {
|
||||
s.deleteRegion(c, tenant.System())
|
||||
}
|
||||
}
|
||||
|
||||
func (s *Server) adminUpdateRegion(c *gin.Context) {
|
||||
if s.platformRegion(c) {
|
||||
s.updateRegion(c, tenant.System())
|
||||
}
|
||||
}
|
||||
|
||||
// platformRegion reports whether the region in the path is a platform one,
|
||||
// answering the request otherwise: the system scope could reach org
|
||||
// regions, but only platform ones are meant.
|
||||
func (s *Server) platformRegion(c *gin.Context) bool {
|
||||
id, err := uuid.Parse(c.Param("id"))
|
||||
if err != nil {
|
||||
fail(c, http.StatusNotFound, "not_found")
|
||||
return
|
||||
return false
|
||||
}
|
||||
ctx := c.Request.Context()
|
||||
var r store.Region
|
||||
@@ -337,13 +415,13 @@ func (s *Server) adminDeleteRegion(c *gin.Context) {
|
||||
})
|
||||
if errors.Is(err, pgx.ErrNoRows) || (err == nil && r.OrgID != nil) {
|
||||
fail(c, http.StatusNotFound, "not_found")
|
||||
return
|
||||
return false
|
||||
}
|
||||
if err != nil {
|
||||
internalError(c, err)
|
||||
return
|
||||
return false
|
||||
}
|
||||
s.deleteRegion(c, tenant.System())
|
||||
return true
|
||||
}
|
||||
|
||||
func (s *Server) adminListAgents(c *gin.Context) { s.listAgents(c, tenant.System(), nil) }
|
||||
|
||||
@@ -2,6 +2,7 @@ package api_test
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
@@ -200,3 +201,129 @@ func TestAgentInstallConsole(t *testing.T) {
|
||||
t.Error("an agent on the platform's release is marked outdated")
|
||||
}
|
||||
}
|
||||
|
||||
func TestRegionLocations(t *testing.T) {
|
||||
e := newEnv(t)
|
||||
_, platformRegion := e.platformChecker(t, uniq("loc-"))
|
||||
|
||||
a := e.browser(t)
|
||||
a.signup("a@"+uniq("a")+".test", uniq("org-a-"))
|
||||
b := e.browser(t)
|
||||
b.signup("b@"+uniq("b")+".test", uniq("org-b-"))
|
||||
|
||||
location := func(br *browser, id string) (any, any) {
|
||||
t.Helper()
|
||||
_, body := br.do("GET", "/api/v1/org/regions", nil)
|
||||
for _, r := range body["regions"].([]any) {
|
||||
if r := r.(map[string]any); r["id"] == id {
|
||||
return r["latitude"], r["longitude"]
|
||||
}
|
||||
}
|
||||
t.Fatalf("region %s not listed", id)
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
st, body := a.do("POST", "/api/v1/org/regions", map[string]any{"key": "berlin", "latitude": 52.52, "longitude": 13.405})
|
||||
if st != http.StatusCreated || body["latitude"] != 52.52 || body["longitude"] != 13.405 {
|
||||
t.Fatalf("create region with location = %d %v", st, body)
|
||||
}
|
||||
berlin := body["id"].(string)
|
||||
plain := a.createRegion("plain")
|
||||
if lat, lon := location(a, plain); lat != nil || lon != nil {
|
||||
t.Errorf("region without location lists %v, %v", lat, lon)
|
||||
}
|
||||
|
||||
for _, tc := range []struct {
|
||||
what string
|
||||
body map[string]any
|
||||
}{
|
||||
{"latitude only", map[string]any{"latitude": 10.0}},
|
||||
{"latitude out of range", map[string]any{"latitude": 91.0, "longitude": 0.0}},
|
||||
{"longitude out of range", map[string]any{"latitude": 0.0, "longitude": -181.0}},
|
||||
} {
|
||||
st, body := a.do("PATCH", "/api/v1/org/regions/"+plain, tc.body)
|
||||
expect(t, tc.what, st, body, http.StatusUnprocessableEntity, "invalid_location")
|
||||
}
|
||||
st, body = a.do("POST", "/api/v1/org/regions", map[string]any{"key": "half", "longitude": 3.0})
|
||||
expect(t, "create with half a location", st, body, http.StatusUnprocessableEntity, "invalid_location")
|
||||
|
||||
st, body = a.do("PATCH", "/api/v1/org/regions/"+plain, map[string]any{"latitude": -33.8688, "longitude": 151.2093})
|
||||
expect(t, "set location", st, body, http.StatusNoContent, "")
|
||||
if lat, lon := location(a, plain); lat != -33.8688 || lon != 151.2093 {
|
||||
t.Errorf("location after PATCH = %v, %v", lat, lon)
|
||||
}
|
||||
st, body = a.do("PATCH", "/api/v1/org/regions/"+berlin, map[string]any{"latitude": nil, "longitude": nil})
|
||||
expect(t, "remove location", st, body, http.StatusNoContent, "")
|
||||
if lat, lon := location(a, berlin); lat != nil || lon != nil {
|
||||
t.Errorf("location after removal = %v, %v", lat, lon)
|
||||
}
|
||||
|
||||
st, body = b.do("PATCH", "/api/v1/org/regions/"+plain, map[string]any{"latitude": 1.0, "longitude": 1.0})
|
||||
expect(t, "other org sets location", st, body, http.StatusNotFound, "not_found")
|
||||
st, body = a.do("PATCH", "/api/v1/org/regions/"+platformRegion, map[string]any{"latitude": 1.0, "longitude": 1.0})
|
||||
expect(t, "org sets platform location", st, body, http.StatusNotFound, "not_found")
|
||||
st, body = a.do("PATCH", "/api/v1/admin/regions/"+platformRegion, map[string]any{"latitude": 1.0, "longitude": 1.0})
|
||||
expect(t, "non-admin sets platform location", st, body, http.StatusForbidden, "forbidden")
|
||||
|
||||
err := tenant.New(e.dbPool).Tx(context.Background(), tenant.Global(), func(q *store.Queries) error {
|
||||
return q.MakeAdmin(context.Background(), a.userIDSelf())
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
st, body = a.do("PATCH", "/api/v1/admin/regions/"+plain, map[string]any{"latitude": 1.0, "longitude": 1.0})
|
||||
expect(t, "admin sets org region location", st, body, http.StatusNotFound, "not_found")
|
||||
st, body = a.do("PATCH", "/api/v1/admin/regions/"+platformRegion, map[string]any{"latitude": 50.1109, "longitude": 8.6821})
|
||||
expect(t, "admin sets platform location", st, body, http.StatusNoContent, "")
|
||||
if lat, lon := location(b, platformRegion); lat != 50.1109 || lon != 8.6821 {
|
||||
t.Errorf("platform location seen by org B = %v, %v", lat, lon)
|
||||
}
|
||||
|
||||
t.Run("public list", func(t *testing.T) {
|
||||
req, _ := http.NewRequest(http.MethodGet, a.base+"/api/v1/public/regions", nil)
|
||||
req.Header.Set("Origin", "https://www.example.org")
|
||||
// The browser's transport trusts the test server; no cookie jar, so no session.
|
||||
resp, err := (&http.Client{Transport: a.hc.Transport}).Do(req)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer func() { _ = resp.Body.Close() }()
|
||||
var body struct {
|
||||
Regions []map[string]any `json:"regions"`
|
||||
}
|
||||
if err := json.NewDecoder(resp.Body).Decode(&body); err != nil || resp.StatusCode != http.StatusOK {
|
||||
t.Fatalf("GET public regions = %d %v", resp.StatusCode, err)
|
||||
}
|
||||
if got := resp.Header.Get("Access-Control-Allow-Origin"); got != "*" {
|
||||
t.Errorf("CORS header = %q, want *", got)
|
||||
}
|
||||
var found map[string]any
|
||||
for _, r := range body.Regions {
|
||||
if r["name"] == "Office plain" || r["key"] == "berlin" {
|
||||
t.Errorf("public list shows an org region: %v", r)
|
||||
}
|
||||
if _, leaked := r["id"]; leaked {
|
||||
t.Errorf("public list exposes region ids: %v", r)
|
||||
}
|
||||
if r["latitude"] == 50.1109 {
|
||||
found = r
|
||||
}
|
||||
}
|
||||
if _, isBool := found["online"].(bool); found == nil || found["longitude"] != 8.6821 || !isBool {
|
||||
t.Errorf("platform region in public list = %v, want its location and online state", found)
|
||||
}
|
||||
})
|
||||
|
||||
_, _, html := a.page("/monitors/new")
|
||||
if !strings.Contains(html, `data-region-map="select"`) || !strings.Contains(html, `data-lat="50.1109"`) || !strings.Contains(html, `data-lat="-33.8688"`) {
|
||||
t.Errorf("monitor form lacks the region map or markers")
|
||||
}
|
||||
_, _, html = b.page("/monitors/new")
|
||||
if !strings.Contains(html, `data-region-map="select"`) || strings.Contains(html, `data-lat="-33.8688"`) {
|
||||
t.Errorf("org B monitor form: want the platform marker only")
|
||||
}
|
||||
_, _, html = a.page("/settings/regions")
|
||||
if !strings.Contains(html, `data-region-map="edit"`) || !strings.Contains(html, `data-location-toggle="location-`+plain+`"`) {
|
||||
t.Errorf("regions page lacks the map or the location form")
|
||||
}
|
||||
}
|
||||
@@ -39,7 +39,7 @@ func (s *Server) RunRegionWatch(ctx context.Context) {
|
||||
tick := time.NewTicker(regionWatchEvery)
|
||||
defer tick.Stop()
|
||||
for {
|
||||
if err := s.WatchRegions(ctx, time.Now()); err != nil && ctx.Err() == nil {
|
||||
if err := s.metrics.Job("region_watch", func() error { return s.WatchRegions(ctx, time.Now()) }); err != nil && ctx.Err() == nil {
|
||||
s.log.WarnContext(ctx, "watching regions failed", "error", err)
|
||||
}
|
||||
select {
|
||||
|
||||
@@ -0,0 +1,121 @@
|
||||
package api
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"net/url"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
|
||||
"git.zb-server.de/ZB-Server/uptimesebi/internal/i18n"
|
||||
"git.zb-server.de/ZB-Server/uptimesebi/internal/ogimage"
|
||||
"git.zb-server.de/ZB-Server/uptimesebi/internal/web"
|
||||
)
|
||||
|
||||
// indexable reports whether search engines may list the public pages.
|
||||
// Self-hosted installations keep their sign-in out of search results.
|
||||
func (s *Server) indexable() bool { return s.cloud() }
|
||||
|
||||
// publicMeta describes a public page at path, such as the sign-in, for
|
||||
// search engines and link previews; nil where pages are not indexed.
|
||||
func (s *Server) publicMeta(c *gin.Context, path, titleID string) *web.PageMeta {
|
||||
if !s.indexable() {
|
||||
return nil
|
||||
}
|
||||
ctx := c.Request.Context()
|
||||
lang := i18n.Lang(ctx)
|
||||
chosen := s.catalog.IsSupported(c.Query("lang"))
|
||||
title := i18n.T(ctx, titleID) + " · UptimeSebi"
|
||||
image := web.LangURL(s.cfg.PublicURL+"/og.png", lang)
|
||||
return web.NewPageMeta(title, i18n.T(ctx, "meta.app_description"), s.cfg.PublicURL+path, image, "UptimeSebi", lang, chosen, s.catalog.Supported())
|
||||
}
|
||||
|
||||
// appImages keeps the app's preview image per language.
|
||||
type appImages struct {
|
||||
mu sync.Mutex
|
||||
images map[string][]byte
|
||||
}
|
||||
|
||||
// appOGImage serves the preview image of the app's public pages.
|
||||
func (s *Server) appOGImage(c *gin.Context) {
|
||||
l := s.catalog.Match(c.Query("lang"), c.GetHeader("Accept-Language"))
|
||||
ctx := i18n.NewContext(c.Request.Context(), l)
|
||||
s.ogImages.mu.Lock()
|
||||
defer s.ogImages.mu.Unlock()
|
||||
png, ok := s.ogImages.images[l.Lang()]
|
||||
if !ok {
|
||||
host := s.cfg.PublicURL
|
||||
if u, err := url.Parse(host); err == nil {
|
||||
host = u.Host
|
||||
}
|
||||
var err error
|
||||
png, err = ogimage.Render(ogimage.Card{
|
||||
Title: i18n.T(ctx, "meta.app_card_title"),
|
||||
Subtitle: i18n.T(ctx, "meta.app_card_subtitle"),
|
||||
Footer: host,
|
||||
Accent: ogimage.Up,
|
||||
})
|
||||
if err != nil {
|
||||
internalError(c, err)
|
||||
return
|
||||
}
|
||||
if s.ogImages.images == nil {
|
||||
s.ogImages.images = map[string][]byte{}
|
||||
}
|
||||
s.ogImages.images[l.Lang()] = png
|
||||
}
|
||||
c.Header("Cache-Control", "public, max-age=86400")
|
||||
c.Data(http.StatusOK, "image/png", png)
|
||||
}
|
||||
|
||||
// robotsTxt lets crawlers read the sign-in, sign-up and legal pages and
|
||||
// nothing else; self-hosted installations turn them away entirely.
|
||||
func (s *Server) robotsTxt(c *gin.Context) {
|
||||
var b strings.Builder
|
||||
b.WriteString("User-agent: *\n")
|
||||
if s.indexable() {
|
||||
for _, p := range []string{"/login", "/signup", "/legal/", "/og.png", "/static/"} {
|
||||
b.WriteString("Allow: " + p + "\n")
|
||||
}
|
||||
}
|
||||
b.WriteString("Disallow: /\n")
|
||||
if s.indexable() {
|
||||
b.WriteString("\nSitemap: " + s.cfg.PublicURL + "/sitemap.xml\n")
|
||||
}
|
||||
c.Header("Cache-Control", "public, max-age=3600")
|
||||
c.Data(http.StatusOK, "text/plain; charset=utf-8", []byte(b.String()))
|
||||
}
|
||||
|
||||
// sitemapXML lists the public pages with their language versions.
|
||||
func (s *Server) sitemapXML(c *gin.Context) {
|
||||
if !s.indexable() {
|
||||
c.Status(http.StatusNotFound)
|
||||
return
|
||||
}
|
||||
ctx := c.Request.Context()
|
||||
paths := []string{"/login"}
|
||||
if email, providers, err := s.signupOptions(ctx); err != nil {
|
||||
internalError(c, err)
|
||||
return
|
||||
} else if email || len(providers) > 0 {
|
||||
paths = append(paths, "/signup")
|
||||
}
|
||||
for _, d := range s.platformLegalDocs(ctx) {
|
||||
if d.URL == "" {
|
||||
paths = append(paths, "/legal/"+d.Kind)
|
||||
}
|
||||
}
|
||||
var urls []string
|
||||
for _, p := range paths {
|
||||
urls = append(urls, s.cfg.PublicURL+p)
|
||||
}
|
||||
body, err := web.Sitemap(urls, s.catalog.Supported(), time.Time{})
|
||||
if err != nil {
|
||||
internalError(c, err)
|
||||
return
|
||||
}
|
||||
c.Header("Cache-Control", "public, max-age=3600")
|
||||
c.Data(http.StatusOK, "application/xml; charset=utf-8", body)
|
||||
}
|
||||
@@ -0,0 +1,81 @@
|
||||
package api_test
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"io"
|
||||
"net/http"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"git.zb-server.de/ZB-Server/uptimesebi/internal/config"
|
||||
)
|
||||
|
||||
func (b *browser) raw(path string) (int, http.Header, []byte) {
|
||||
b.t.Helper()
|
||||
resp, err := b.hc.Get(b.base + path)
|
||||
if err != nil {
|
||||
b.t.Fatalf("GET %s failed: %v", path, err)
|
||||
}
|
||||
defer func() { _ = resp.Body.Close() }()
|
||||
body, _ := io.ReadAll(resp.Body)
|
||||
return resp.StatusCode, resp.Header, body
|
||||
}
|
||||
|
||||
func TestPublicPagesForSearchEngines(t *testing.T) {
|
||||
const publicURL = "https://app.example.test"
|
||||
cloud := newEnvWith(t, func(c *config.API) {
|
||||
c.Edition, c.SignupVerify, c.PublicURL = config.EditionCloud, "off", publicURL
|
||||
})
|
||||
b := cloud.browser(t)
|
||||
|
||||
_, _, html := b.page("/login?next=/monitors&lang=de")
|
||||
for _, want := range []string{
|
||||
`<link rel="canonical" href="` + publicURL + `/login?lang=de">`,
|
||||
`<link rel="alternate" hreflang="en" href="` + publicURL + `/login?lang=en">`,
|
||||
`<link rel="alternate" hreflang="x-default" href="` + publicURL + `/login">`,
|
||||
`<meta property="og:image" content="` + publicURL + `/og.png?lang=de">`,
|
||||
`<meta name="description" content="UptimeSebi überwacht`,
|
||||
`<html lang="de">`,
|
||||
} {
|
||||
if !strings.Contains(html, want) {
|
||||
t.Errorf("login page lacks %s", want)
|
||||
}
|
||||
}
|
||||
if strings.Contains(html, "noindex") {
|
||||
t.Errorf("login page is noindex in the cloud edition")
|
||||
}
|
||||
if _, _, html := b.page("/signup"); !strings.Contains(html, `<link rel="canonical" href="`+publicURL+`/signup">`) {
|
||||
t.Errorf("signup page lacks its canonical address")
|
||||
}
|
||||
|
||||
_, _, robots := b.raw("/robots.txt")
|
||||
if !strings.Contains(string(robots), "Allow: /login\n") || !strings.Contains(string(robots), "Disallow: /\n") || !strings.Contains(string(robots), "Sitemap: "+publicURL+"/sitemap.xml") {
|
||||
t.Errorf("robots.txt = %q", robots)
|
||||
}
|
||||
code, _, sm := b.raw("/sitemap.xml")
|
||||
if code != http.StatusOK || !strings.Contains(string(sm), "<loc>"+publicURL+"/signup</loc>") || !strings.Contains(string(sm), `hreflang="de" href="`+publicURL+`/login?lang=de"`) {
|
||||
t.Errorf("sitemap = %d %s", code, sm)
|
||||
}
|
||||
code, h, png := b.raw("/og.png?lang=en")
|
||||
if code != http.StatusOK || h.Get("Content-Type") != "image/png" || !bytes.HasPrefix(png, []byte("\x89PNG")) {
|
||||
t.Errorf("preview image = %d %s", code, h.Get("Content-Type"))
|
||||
}
|
||||
|
||||
// Signed in, the console stays out of search engines.
|
||||
b.signup("seo@"+uniq("seo")+".test", uniq("seo-"))
|
||||
if _, _, html := b.page("/"); !strings.Contains(html, `<meta name="robots" content="noindex, nofollow">`) || strings.Contains(html, "og:title") {
|
||||
t.Errorf("console page is indexable")
|
||||
}
|
||||
|
||||
// Self-hosted installations keep everything out.
|
||||
self := newEnv(t).browser(t)
|
||||
if _, _, html := self.page("/login"); !strings.Contains(html, "noindex") || strings.Contains(html, "canonical") {
|
||||
t.Errorf("self-hosted login page is indexable")
|
||||
}
|
||||
if _, _, robots := self.raw("/robots.txt"); string(robots) != "User-agent: *\nDisallow: /\n" {
|
||||
t.Errorf("self-hosted robots.txt = %q", robots)
|
||||
}
|
||||
if code, _, _ := self.raw("/sitemap.xml"); code != http.StatusNotFound {
|
||||
t.Errorf("self-hosted sitemap = %d, want 404", code)
|
||||
}
|
||||
}
|
||||
+52
-16
@@ -18,6 +18,7 @@ import (
|
||||
"git.zb-server.de/ZB-Server/uptimesebi/internal/config"
|
||||
"git.zb-server.de/ZB-Server/uptimesebi/internal/evaluate"
|
||||
"git.zb-server.de/ZB-Server/uptimesebi/internal/i18n"
|
||||
"git.zb-server.de/ZB-Server/uptimesebi/internal/metrics"
|
||||
"git.zb-server.de/ZB-Server/uptimesebi/internal/notify"
|
||||
"git.zb-server.de/ZB-Server/uptimesebi/internal/requestid"
|
||||
"git.zb-server.de/ZB-Server/uptimesebi/internal/schedule"
|
||||
@@ -31,20 +32,22 @@ const localeCookie = "lang"
|
||||
|
||||
// Server holds the dependencies shared by all handlers.
|
||||
type Server struct {
|
||||
cfg config.API
|
||||
log *slog.Logger
|
||||
db *tenant.DB
|
||||
rdb redis.UniversalClient
|
||||
keys *sealed.Keyring
|
||||
catalog *i18n.Catalog
|
||||
sessions *auth.Sessions
|
||||
limiter *auth.Limiter
|
||||
totp *auth.TOTPVerifier
|
||||
sso *sso.Client
|
||||
sched *schedule.Scheduler
|
||||
eval *evaluate.Evaluator
|
||||
smtp *notify.SMTP
|
||||
legal *versioned[[]agentapi.LegalDoc]
|
||||
// orgPurges wakes runOrgPurges after an organization was deleted.
|
||||
orgPurges chan struct{}
|
||||
cfg config.API
|
||||
log *slog.Logger
|
||||
db *tenant.DB
|
||||
rdb redis.UniversalClient
|
||||
keys *sealed.Keyring
|
||||
catalog *i18n.Catalog
|
||||
sessions *auth.Sessions
|
||||
limiter *auth.Limiter
|
||||
totp *auth.TOTPVerifier
|
||||
sso *sso.Client
|
||||
sched *schedule.Scheduler
|
||||
eval *evaluate.Evaluator
|
||||
smtp *notify.SMTP
|
||||
legal *versioned[[]agentapi.LegalDoc]
|
||||
// consent caches the versions of the documents accounts accept.
|
||||
consent *versioned[map[string]int64]
|
||||
// checkTypes caches the check types switched off platform-wide.
|
||||
@@ -56,6 +59,8 @@ type Server struct {
|
||||
limits *versioned[Limits]
|
||||
// support caches how the platform runs support tickets.
|
||||
support *versioned[supportSettings]
|
||||
// pageHome caches the home page the status page servers link.
|
||||
pageHome *versioned[string]
|
||||
// draining, once closed, ends the long polls of checkers.
|
||||
draining <-chan struct{}
|
||||
// handler serves the requests agents send over their streams.
|
||||
@@ -63,6 +68,13 @@ type Server struct {
|
||||
// snapshots lets status page servers asking for the same page at once
|
||||
// share one build of it.
|
||||
snapshots singleflight.Group
|
||||
|
||||
// publicRegions caches the answer of the public region list.
|
||||
publicRegions publicRegionsCache
|
||||
// ogImages keeps the preview image of the public pages.
|
||||
ogImages appImages
|
||||
// metrics counts what the instance does, for Prometheus.
|
||||
metrics *metrics.Metrics
|
||||
}
|
||||
|
||||
// Deps are the external resources a Server needs.
|
||||
@@ -72,6 +84,8 @@ type Deps struct {
|
||||
Redis redis.UniversalClient
|
||||
Keys *sealed.Keyring
|
||||
Catalog *i18n.Catalog
|
||||
// Metrics, if nil, are created for the Server alone.
|
||||
Metrics *metrics.Metrics
|
||||
}
|
||||
|
||||
// New returns a Server. It does not register any routes; see Mount.
|
||||
@@ -79,7 +93,13 @@ type Deps struct {
|
||||
func New(cfg config.API, d Deps) *Server {
|
||||
allowPrivate := cfg.SSOAllowPrivate()
|
||||
mail, _ := notify.ParseSMTP(cfg.SMTPURL)
|
||||
return &Server{
|
||||
m := d.Metrics
|
||||
if m == nil {
|
||||
m = metrics.New(string(cfg.Edition))
|
||||
}
|
||||
s := &Server{
|
||||
metrics: m,
|
||||
orgPurges: make(chan struct{}, 1),
|
||||
eval: evaluate.New(d.Redis),
|
||||
smtp: mail,
|
||||
cfg: cfg,
|
||||
@@ -99,7 +119,10 @@ func New(cfg config.API, d Deps) *Server {
|
||||
checkerNet: newVersioned[bool]("checker-network"),
|
||||
limits: newVersioned[Limits]("limits"),
|
||||
support: newVersioned[supportSettings]("support"),
|
||||
pageHome: newVersioned[string]("statuspage-home"),
|
||||
}
|
||||
m.Register(&platformCollector{s: s})
|
||||
return s
|
||||
}
|
||||
|
||||
// EndLongPollsOn makes the checkers' long polls return as soon as ch is
|
||||
@@ -121,6 +144,11 @@ func (s *Server) Mount(r gin.IRouter) {
|
||||
g := r.Group("/", s.sessions.Load(), s.localize(), auth.CSRF(), s.audit(), s.accountGate())
|
||||
|
||||
r.GET("/api/openapi.json", s.openAPIJSON)
|
||||
// Public data for websites: no session, no CSRF.
|
||||
r.GET("/api/v1/public/regions", s.listPublicRegions)
|
||||
r.GET("/robots.txt", s.robotsTxt)
|
||||
r.GET("/sitemap.xml", s.sitemapXML)
|
||||
r.GET("/og.png", s.appOGImage)
|
||||
r.GET("/install.sh", s.installScript)
|
||||
g.GET("/api/docs", s.apiDocsPage)
|
||||
|
||||
@@ -197,6 +225,7 @@ func (s *Server) Mount(r gin.IRouter) {
|
||||
org.GET("/regions", s.listOrgRegions)
|
||||
org.POST("/regions", sessionOnly(), can(authz.OrgManage), s.createOrgRegion)
|
||||
org.DELETE("/regions/:id", sessionOnly(), can(authz.OrgManage), s.deleteOrgRegion)
|
||||
org.PATCH("/regions/:id", sessionOnly(), can(authz.OrgManage), s.updateOrgRegion)
|
||||
org.GET("/agents", can(authz.OrgManage), s.listOrgAgents)
|
||||
org.POST("/agents", sessionOnly(), can(authz.OrgManage), s.createOrgAgent)
|
||||
org.PATCH("/agents/:id", sessionOnly(), can(authz.OrgManage), s.updateOrgAgent)
|
||||
@@ -224,11 +253,14 @@ func (s *Server) Mount(r gin.IRouter) {
|
||||
admin.PUT("/users/:id/suspension", s.adminSuspendUser)
|
||||
admin.DELETE("/users/:id", s.adminDeleteUser)
|
||||
admin.PUT("/checker-network", s.adminSetCheckerNetwork)
|
||||
admin.GET("/statuspage-home", s.adminGetStatusPageHome)
|
||||
admin.PUT("/statuspage-home", s.adminSetStatusPageHome)
|
||||
admin.GET("/legal", s.adminListLegal)
|
||||
admin.PUT("/legal/:kind", s.adminSaveLegal)
|
||||
admin.GET("/regions", s.adminListRegions)
|
||||
admin.POST("/regions", s.adminCreateRegion)
|
||||
admin.DELETE("/regions/:id", s.adminDeleteRegion)
|
||||
admin.PATCH("/regions/:id", s.adminUpdateRegion)
|
||||
admin.GET("/support/settings", s.adminGetSupportSettings)
|
||||
admin.PUT("/support/settings", s.adminSetSupportSettings)
|
||||
admin.GET("/support/tickets", s.adminListTickets)
|
||||
@@ -251,6 +283,8 @@ func (s *Server) Mount(r gin.IRouter) {
|
||||
page.POST("/groups/import", canPage(authz.StatusPagesWrite), s.importStatusPageGroups)
|
||||
page.PUT("/monitors", canPage(authz.StatusPagesWrite), s.setPageMonitors)
|
||||
page.PUT("/domain", canPage(authz.StatusPagesWrite), s.setPageDomain)
|
||||
page.GET("/subscribers", canPage(authz.StatusPagesWrite), s.listPageSubscribers)
|
||||
page.DELETE("/subscribers/:subscriber", canPage(authz.StatusPagesWrite), s.deletePageSubscriber)
|
||||
page.POST("/domain/verify", canPage(authz.StatusPagesWrite), s.verifyPageDomain)
|
||||
page.GET("/export", canPage(authz.StatusPagesRead), s.exportStatusPage)
|
||||
|
||||
@@ -319,7 +353,9 @@ func (s *Server) localize() gin.HandlerFunc {
|
||||
pref = sess.Locale
|
||||
}
|
||||
cookie, _ := c.Cookie(localeCookie)
|
||||
l := s.catalog.Match(pref, cookie, c.GetHeader("Accept-Language"))
|
||||
// ?lang= shows a page in that language, so each language of the
|
||||
// public pages has an address of its own.
|
||||
l := s.catalog.Match(c.Query("lang"), pref, cookie, c.GetHeader("Accept-Language"))
|
||||
c.Request = c.Request.WithContext(i18n.NewContext(c.Request.Context(), l))
|
||||
c.Header("Content-Language", l.Lang())
|
||||
c.Header("Vary", "Accept-Language, Cookie")
|
||||
|
||||
@@ -25,6 +25,7 @@ import (
|
||||
"git.zb-server.de/ZB-Server/uptimesebi/internal/api"
|
||||
"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/metrics"
|
||||
"git.zb-server.de/ZB-Server/uptimesebi/internal/migrations"
|
||||
"git.zb-server.de/ZB-Server/uptimesebi/internal/platform"
|
||||
"git.zb-server.de/ZB-Server/uptimesebi/internal/sealed"
|
||||
@@ -37,6 +38,8 @@ type env struct {
|
||||
dbPool *pgxpool.Pool
|
||||
rdb *redis.Client
|
||||
api *api.Server
|
||||
// metrics are the API's own, as cmd/api serves them.
|
||||
metrics *metrics.Metrics
|
||||
}
|
||||
|
||||
func newEnv(t *testing.T) *env {
|
||||
@@ -104,7 +107,8 @@ func newEnvWith(t *testing.T, adjust func(*config.API)) *env {
|
||||
if adjust != nil {
|
||||
adjust(&cfg)
|
||||
}
|
||||
e.api = api.New(cfg, api.Deps{Log: log, DB: tenant.New(pool), Redis: rdb, Keys: keys, Catalog: catalog})
|
||||
e.metrics = metrics.New(string(cfg.Edition))
|
||||
e.api = api.New(cfg, api.Deps{Log: log, DB: tenant.New(pool), Redis: rdb, Keys: keys, Catalog: catalog, Metrics: e.metrics})
|
||||
e.api.Mount(r)
|
||||
return e
|
||||
}
|
||||
|
||||
@@ -256,7 +256,7 @@ func (s *Server) importStatusPageGroups(c *gin.Context) {
|
||||
pageID := uuid.MustParse(c.Param("id"))
|
||||
p := current(c)
|
||||
ctx := c.Request.Context()
|
||||
var created []store.StatusPageGroup
|
||||
var created []pageGroupView
|
||||
err := s.db.Tx(ctx, p.scope(), func(q *store.Queries) error {
|
||||
if _, err := q.GetStatusPage(ctx, pageID); err != nil {
|
||||
return err
|
||||
@@ -290,54 +290,66 @@ func (s *Server) importStatusPageGroups(c *gin.Context) {
|
||||
if err := q.ClearStatusPageGroups(ctx, pageID); err != nil {
|
||||
return err
|
||||
}
|
||||
mapped := map[uuid.UUID]store.StatusPageGroup{}
|
||||
var createErr error
|
||||
// Large organizations have thousands of monitors and hundreds of
|
||||
// groups, so both are written in a few statements: the groups one
|
||||
// level of nesting at a time, as parents must exist before their
|
||||
// children, the monitors all at once.
|
||||
mapped := map[uuid.UUID]pageGroupView{}
|
||||
var levels []store.CreateStatusPageGroupsParams
|
||||
posByParent := map[uuid.UUID]int32{}
|
||||
tree.walk(func(g store.MonitorGroup, _ int) {
|
||||
if createErr != nil || !needed[g.ID] {
|
||||
tree.walk(func(g store.MonitorGroup, depth int) {
|
||||
if !needed[g.ID] {
|
||||
return
|
||||
}
|
||||
var parentKey uuid.UUID
|
||||
var parentID *uuid.UUID
|
||||
if g.ParentID != nil {
|
||||
if parent, ok := mapped[*g.ParentID]; ok {
|
||||
pid := parent.ID
|
||||
parentID = &pid
|
||||
parentKey = pid
|
||||
}
|
||||
}
|
||||
var parentKey uuid.UUID
|
||||
if parentID != nil {
|
||||
parentKey = *parentID
|
||||
}
|
||||
pos := posByParent[parentKey]
|
||||
posByParent[parentKey] = pos + 1
|
||||
row, err := q.CreateStatusPageGroup(ctx, store.CreateStatusPageGroupParams{
|
||||
PageID: pageID,
|
||||
OrgID: p.Org.ID,
|
||||
ParentID: parentID,
|
||||
Name: g.Name,
|
||||
Position: pos,
|
||||
})
|
||||
if err != nil {
|
||||
createErr = err
|
||||
return
|
||||
}
|
||||
row := pageGroupView{ID: uuid.New(), Name: g.Name, ParentID: parentID, Position: pos}
|
||||
mapped[g.ID] = row
|
||||
created = append(created, row)
|
||||
for len(levels) <= depth {
|
||||
levels = append(levels, store.CreateStatusPageGroupsParams{PageID: pageID, OrgID: p.Org.ID})
|
||||
}
|
||||
l := &levels[depth]
|
||||
l.Ids = append(l.Ids, row.ID)
|
||||
l.ParentIds = append(l.ParentIds, parentKey)
|
||||
l.Names = append(l.Names, row.Name)
|
||||
l.Positions = append(l.Positions, row.Position)
|
||||
})
|
||||
if createErr != nil {
|
||||
return createErr
|
||||
for _, l := range levels {
|
||||
if len(l.Ids) == 0 {
|
||||
continue
|
||||
}
|
||||
if err := q.CreateStatusPageGroups(ctx, l); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
set := store.SetStatusPageMonitorGroupsParams{PageID: pageID}
|
||||
for _, m := range listed {
|
||||
var gid *uuid.UUID
|
||||
var gid uuid.UUID
|
||||
section := ""
|
||||
if m.MonitorGroupID != nil {
|
||||
if g, ok := mapped[*m.MonitorGroupID]; ok {
|
||||
id := g.ID
|
||||
gid = &id
|
||||
gid = g.ID
|
||||
section = g.Name
|
||||
}
|
||||
}
|
||||
if err := q.SetStatusPageMonitorGroup(ctx, store.SetStatusPageMonitorGroupParams{
|
||||
PageID: pageID, MonitorID: m.MonitorID, GroupID: gid, Section: section,
|
||||
}); err != nil {
|
||||
set.MonitorIds = append(set.MonitorIds, m.MonitorID)
|
||||
set.GroupIds = append(set.GroupIds, gid)
|
||||
set.Sections = append(set.Sections, section)
|
||||
}
|
||||
if len(set.MonitorIds) > 0 {
|
||||
if err := q.SetStatusPageMonitorGroups(ctx, set); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
@@ -351,11 +363,10 @@ func (s *Server) importStatusPageGroups(c *gin.Context) {
|
||||
internalError(c, err)
|
||||
return
|
||||
}
|
||||
out := make([]pageGroupView, 0, len(created))
|
||||
for _, g := range created {
|
||||
out = append(out, pageGroupView{ID: g.ID, Name: g.Name, ParentID: g.ParentID, Position: g.Position})
|
||||
if created == nil {
|
||||
created = []pageGroupView{}
|
||||
}
|
||||
c.JSON(http.StatusOK, gin.H{"groups": out})
|
||||
c.JSON(http.StatusOK, gin.H{"groups": created})
|
||||
}
|
||||
|
||||
// resolvePageMonitorGroup returns the status page group ID and section label
|
||||
|
||||
@@ -0,0 +1,77 @@
|
||||
package api
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"net/http"
|
||||
"strings"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/jackc/pgx/v5"
|
||||
|
||||
"git.zb-server.de/ZB-Server/uptimesebi/internal/store"
|
||||
"git.zb-server.de/ZB-Server/uptimesebi/internal/tenant"
|
||||
)
|
||||
|
||||
// The status page servers answer visitors of pages that do not exist, and
|
||||
// of their bare domain, with a page linking the platform's home page.
|
||||
|
||||
const settingStatusPageHome = "statuspage_home"
|
||||
|
||||
type statusPageHome struct {
|
||||
// URL is the home page linked from the status page servers' error
|
||||
// page; empty links none.
|
||||
URL string `json:"url" binding:"max=2000"`
|
||||
}
|
||||
|
||||
func (s *Server) statusPageHome(ctx context.Context) string {
|
||||
v, err := s.pageHome.get(ctx, s.rdb, func(ctx context.Context) (string, error) {
|
||||
var v statusPageHome
|
||||
err := s.db.Tx(ctx, tenant.System(), func(q *store.Queries) error {
|
||||
raw, err := q.GetPlatformSetting(ctx, settingStatusPageHome)
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return nil
|
||||
}
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return json.Unmarshal(raw, &v)
|
||||
})
|
||||
return v.URL, err
|
||||
})
|
||||
if err != nil {
|
||||
s.log.WarnContext(ctx, "loading the status page home failed", "error", err)
|
||||
return ""
|
||||
}
|
||||
return v
|
||||
}
|
||||
|
||||
func (s *Server) adminGetStatusPageHome(c *gin.Context) {
|
||||
c.JSON(http.StatusOK, statusPageHome{URL: s.statusPageHome(c.Request.Context())})
|
||||
}
|
||||
|
||||
func (s *Server) adminSetStatusPageHome(c *gin.Context) {
|
||||
var req statusPageHome
|
||||
if !bind(c, &req) {
|
||||
return
|
||||
}
|
||||
req.URL = strings.TrimSpace(req.URL)
|
||||
if req.URL != "" && !validLegalURL(req.URL) {
|
||||
fail(c, http.StatusUnprocessableEntity, "invalid_legal_url")
|
||||
return
|
||||
}
|
||||
ctx := c.Request.Context()
|
||||
raw, _ := json.Marshal(req)
|
||||
auditDetail(c, "url", req.URL)
|
||||
if err := s.db.Tx(ctx, tenant.System(), func(q *store.Queries) error {
|
||||
return q.SetPlatformSetting(ctx, store.SetPlatformSettingParams{Key: settingStatusPageHome, Value: raw})
|
||||
}); err != nil {
|
||||
internalError(c, err)
|
||||
return
|
||||
}
|
||||
if err := s.pageHome.bump(ctx, s.rdb); err != nil {
|
||||
s.log.ErrorContext(ctx, "announcing the status page home failed", "error", err)
|
||||
}
|
||||
c.Status(http.StatusNoContent)
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
package api_test
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/http"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"git.zb-server.de/ZB-Server/uptimesebi/internal/store"
|
||||
"git.zb-server.de/ZB-Server/uptimesebi/internal/tenant"
|
||||
)
|
||||
|
||||
func TestStatusPageHome(t *testing.T) {
|
||||
e := newEnv(t)
|
||||
admin := e.browser(t)
|
||||
admin.signup("a@"+uniq("home")+".test", uniq("home-"))
|
||||
if err := tenant.New(e.dbPool).Tx(context.Background(), tenant.Global(), func(q *store.Queries) error {
|
||||
return q.MakeAdmin(context.Background(), admin.userIDSelf())
|
||||
}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() { admin.do("PUT", "/api/v1/admin/statuspage-home", map[string]any{"url": ""}) })
|
||||
pages := e.statuspageClient(t, nil)
|
||||
|
||||
st, body := admin.do("PUT", "/api/v1/admin/statuspage-home", map[string]any{"url": "javascript:alert(1)"})
|
||||
expect(t, "script link", st, body, http.StatusUnprocessableEntity, "invalid_legal_url")
|
||||
if st, body := admin.do("PUT", "/api/v1/admin/statuspage-home", map[string]any{"url": " https://example.test/ "}); st != http.StatusNoContent {
|
||||
t.Fatalf("set home = %d %v", st, body)
|
||||
}
|
||||
if _, body := admin.do("GET", "/api/v1/admin/statuspage-home", nil); body["url"] != "https://example.test/" {
|
||||
t.Errorf("home = %v", body)
|
||||
}
|
||||
index, err := pages.Pages(context.Background())
|
||||
if err != nil || index.HomeURL != "https://example.test/" {
|
||||
t.Errorf("page index home = %q %v", index.HomeURL, err)
|
||||
}
|
||||
if _, _, html := admin.page("/admin"); !strings.Contains(html, `value="https://example.test/"`) {
|
||||
t.Error("the admin page does not show the home page")
|
||||
}
|
||||
|
||||
owner := e.browser(t)
|
||||
owner.signup("o@"+uniq("home")+".test", uniq("home-"))
|
||||
if st, _ := owner.do("PUT", "/api/v1/admin/statuspage-home", map[string]any{"url": "https://evil.test/"}); st != http.StatusForbidden {
|
||||
t.Errorf("non-admin sets the home page = %d, want 403", st)
|
||||
}
|
||||
}
|
||||
+21
-13
@@ -53,6 +53,7 @@ func (s *Server) buildSnapshot(ctx context.Context, page store.StatusPage) (agen
|
||||
Title: page.Title,
|
||||
Description: page.Description,
|
||||
ShowDetails: page.ShowComponentDetails,
|
||||
Subscribe: page.Subscriptions && s.smtp != nil,
|
||||
Sections: []agentapi.Section{},
|
||||
Incidents: []agentapi.PageIncident{},
|
||||
GeneratedAt: time.Now(),
|
||||
@@ -127,8 +128,9 @@ func (s *Server) buildSnapshot(ctx context.Context, page store.StatusPage) (agen
|
||||
return err
|
||||
}
|
||||
docs, err := q.LegalDocuments(ctx, &page.OrgID)
|
||||
// Visitors of status pages accept no terms.
|
||||
snap.Legal = slices.DeleteFunc(mergeLegal(docs), func(d agentapi.LegalDoc) bool { return d.Kind == "terms" })
|
||||
// Visitors of status pages accept the platform's terms only when
|
||||
// they subscribe to it.
|
||||
snap.Legal = slices.DeleteFunc(mergeLegal(docs), func(d agentapi.LegalDoc) bool { return d.Kind == "terms" && !snap.Subscribe })
|
||||
return err
|
||||
})
|
||||
if err != nil {
|
||||
@@ -234,7 +236,7 @@ func (s *Server) buildSnapshot(ctx context.Context, page store.StatusPage) (agen
|
||||
for _, i := range incidents {
|
||||
st := statuses.of(i)
|
||||
snap.Incidents = append(snap.Incidents, agentapi.PageIncident{
|
||||
Component: names[i.MonitorID], StartedAt: i.StartedAt, ResolvedAt: i.ResolvedAt,
|
||||
ID: i.ID.String(), Component: names[i.MonitorID], StartedAt: i.StartedAt, ResolvedAt: i.ResolvedAt,
|
||||
Title: i.Title, Status: st.Key, StatusName: st.Name, StatusColor: st.Color, Updates: updatesOf[i.ID],
|
||||
})
|
||||
}
|
||||
@@ -459,16 +461,18 @@ func (s *Server) agentPageIndex(c *gin.Context) {
|
||||
for i, r := range rows {
|
||||
out[i] = agentapi.PageRef{Slug: r.Slug, Host: r.Host}
|
||||
}
|
||||
c.JSON(http.StatusOK, gin.H{"pages": out})
|
||||
c.JSON(http.StatusOK, agentapi.PageIndex{Pages: out, HomeURL: s.statusPageHome(ctx)})
|
||||
}
|
||||
|
||||
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=10000"`
|
||||
Published bool `json:"published"`
|
||||
ShowComponentDetails bool `json:"show_component_details"`
|
||||
Theme agentapi.Theme `json:"theme"`
|
||||
Slug string `json:"slug" binding:"required,max=63"`
|
||||
Title string `json:"title" binding:"required,max=200"`
|
||||
Description string `json:"description" binding:"max=10000"`
|
||||
Published bool `json:"published"`
|
||||
ShowComponentDetails bool `json:"show_component_details"`
|
||||
// Subscriptions lets visitors subscribe to incidents by email.
|
||||
Subscriptions bool `json:"subscriptions"`
|
||||
Theme agentapi.Theme `json:"theme"`
|
||||
}
|
||||
|
||||
func (r *statusPageRequest) normalize() string {
|
||||
@@ -504,6 +508,7 @@ type statusPageView struct {
|
||||
Description string `json:"description"`
|
||||
Published bool `json:"published"`
|
||||
ShowComponentDetails bool `json:"show_component_details"`
|
||||
Subscriptions bool `json:"subscriptions"`
|
||||
Theme agentapi.Theme `json:"theme"`
|
||||
CustomDomain *string `json:"custom_domain"`
|
||||
DomainVerified bool `json:"domain_verified"`
|
||||
@@ -531,7 +536,7 @@ type dnsRecord struct {
|
||||
func (s *Server) viewStatusPage(p store.StatusPage) statusPageView {
|
||||
v := statusPageView{
|
||||
ID: p.ID, Slug: p.Slug, Title: p.Title, Description: p.Description,
|
||||
Published: p.Published, ShowComponentDetails: p.ShowComponentDetails,
|
||||
Published: p.Published, ShowComponentDetails: p.ShowComponentDetails, Subscriptions: p.Subscriptions,
|
||||
CustomDomain: p.CustomDomain, DomainVerified: p.DomainVerifiedAt != nil,
|
||||
Suspended: p.SuspendedAt != nil, SuspendedReason: p.SuspendedReason,
|
||||
}
|
||||
@@ -607,7 +612,7 @@ func (s *Server) createStatusPage(c *gin.Context) {
|
||||
row, err = q.CreateStatusPage(ctx, store.CreateStatusPageParams{
|
||||
OrgID: p.Org.ID, Slug: req.Slug, Title: req.Title, Description: req.Description,
|
||||
Published: req.Published, ShowComponentDetails: req.ShowComponentDetails,
|
||||
DomainToken: newDomainToken(), Theme: theme,
|
||||
DomainToken: newDomainToken(), Theme: theme, Subscriptions: req.Subscriptions,
|
||||
})
|
||||
return err
|
||||
})
|
||||
@@ -650,6 +655,7 @@ func (s *Server) updateStatusPage(c *gin.Context) {
|
||||
row, err = q.UpdateStatusPage(ctx, store.UpdateStatusPageParams{
|
||||
ID: id, Slug: req.Slug, Title: req.Title, Description: req.Description,
|
||||
Published: req.Published, ShowComponentDetails: req.ShowComponentDetails, Theme: theme,
|
||||
Subscriptions: req.Subscriptions,
|
||||
})
|
||||
return err
|
||||
})
|
||||
@@ -694,7 +700,9 @@ type pageMonitor struct {
|
||||
}
|
||||
|
||||
type pageMonitorsRequest struct {
|
||||
Monitors []pageMonitor `json:"monitors" binding:"max=200,dive"`
|
||||
// The organization's limit decides how many; the binding only bounds
|
||||
// a request.
|
||||
Monitors []pageMonitor `json:"monitors" binding:"max=100000,dive"`
|
||||
}
|
||||
|
||||
// setPageMonitors replaces the page's components; their order is the
|
||||
|
||||
@@ -205,7 +205,8 @@ func TestStatusPages(t *testing.T) {
|
||||
own := e.statuspageClient(t, &org)
|
||||
lists := func(c *agentapi.Client) bool {
|
||||
t.Helper()
|
||||
refs, err := c.Pages(context.Background())
|
||||
index, err := c.Pages(context.Background())
|
||||
refs := index.Pages
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
@@ -0,0 +1,450 @@
|
||||
package api
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"encoding/base64"
|
||||
"encoding/binary"
|
||||
"encoding/hex"
|
||||
"errors"
|
||||
"net/http"
|
||||
"net/mail"
|
||||
"net/netip"
|
||||
"net/url"
|
||||
"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/notify"
|
||||
"git.zb-server.de/ZB-Server/uptimesebi/internal/store"
|
||||
"git.zb-server.de/ZB-Server/uptimesebi/internal/tenant"
|
||||
)
|
||||
|
||||
// Visitors subscribe to a status page's incidents by email. A subscription
|
||||
// counts towards the organization's weekly limit as soon as it is asked
|
||||
// for, and nothing but the confirmation is mailed until the address
|
||||
// confirms it, so the form cannot be used to flood strangers' inboxes.
|
||||
|
||||
const (
|
||||
// confirmTTL is how long a confirmation link works.
|
||||
confirmTTL = 48 * time.Hour
|
||||
// subscriberWindow is the window of the weekly limit; unconfirmed
|
||||
// subscriptions are kept as long, so they keep counting.
|
||||
subscriberWindow = 7 * 24 * time.Hour
|
||||
subscriberBatch = 50
|
||||
// maxSubscriberAttempts bounds retries of one mail.
|
||||
maxSubscriberAttempts = 6
|
||||
// maxSubscriberList bounds the subscribers listed in the console.
|
||||
maxSubscriberList = 1000
|
||||
)
|
||||
|
||||
// Rate limits of subscription requests, per visitor address, mailbox and
|
||||
// page, on top of the organization's weekly limit.
|
||||
const (
|
||||
subscribePerIP = 5
|
||||
subscribePerEmail = 3
|
||||
subscribePerPage = 100
|
||||
subscribeIPWindow = time.Hour
|
||||
subscribeMailboxIn = 24 * time.Hour
|
||||
)
|
||||
|
||||
// Token purposes; a token of one is never accepted as the other.
|
||||
const (
|
||||
tokenConfirm = "confirm"
|
||||
tokenUnsubscribe = "unsubscribe"
|
||||
)
|
||||
|
||||
// subscriberToken seals the subscriber's ID and an expiry (zero for none),
|
||||
// so links need no table of their own and an unsubscribe link can be put
|
||||
// into every mail.
|
||||
func (s *Server) subscriberToken(id uuid.UUID, purpose string, expires time.Time) string {
|
||||
b := make([]byte, 24)
|
||||
copy(b, id[:])
|
||||
if !expires.IsZero() {
|
||||
binary.BigEndian.PutUint64(b[16:], uint64(expires.Unix()))
|
||||
}
|
||||
return base64.RawURLEncoding.EncodeToString(s.keys.Seal(b, []byte("subscriber:"+purpose)))
|
||||
}
|
||||
|
||||
func (s *Server) openSubscriberToken(token, purpose string, now time.Time) (uuid.UUID, bool) {
|
||||
raw, err := base64.RawURLEncoding.DecodeString(token)
|
||||
if err != nil || len(token) > 300 {
|
||||
return uuid.Nil, false
|
||||
}
|
||||
b, err := s.keys.Open(raw, []byte("subscriber:"+purpose))
|
||||
if err != nil || len(b) != 24 {
|
||||
return uuid.Nil, false
|
||||
}
|
||||
if exp := binary.BigEndian.Uint64(b[16:]); exp != 0 && now.Unix() > int64(exp) {
|
||||
return uuid.Nil, false
|
||||
}
|
||||
id, err := uuid.FromBytes(b[:16])
|
||||
return id, err == nil
|
||||
}
|
||||
|
||||
// subscriberEmail returns the address in normalized form, or false if it
|
||||
// is none.
|
||||
func subscriberEmail(raw string) (string, bool) {
|
||||
e := normalizeEmail(raw)
|
||||
a, err := mail.ParseAddress(e)
|
||||
if err != nil || a.Address != e || len(e) > 254 || !strings.Contains(e[strings.LastIndexByte(e, '@')+1:], ".") {
|
||||
return "", false
|
||||
}
|
||||
return e, true
|
||||
}
|
||||
|
||||
func mailboxKey(email string) string {
|
||||
sum := sha256.Sum256([]byte(email))
|
||||
return hex.EncodeToString(sum[:12])
|
||||
}
|
||||
|
||||
// subscriberPageURL is the page address for links in mails, ending in "/":
|
||||
// the platform's own where it knows it, else the one the visitor used.
|
||||
func (s *Server) subscriberPageURL(page store.StatusPage, ownServers bool, given string) string {
|
||||
if known := s.pageURL(page, ownServers); absoluteURL(known) {
|
||||
return strings.TrimSuffix(known, "/") + "/"
|
||||
}
|
||||
if !absoluteURL(given) || len(given) > 500 {
|
||||
return ""
|
||||
}
|
||||
u, _ := url.Parse(given)
|
||||
u.RawQuery, u.Fragment = "", ""
|
||||
return strings.TrimSuffix(u.String(), "/") + "/"
|
||||
}
|
||||
|
||||
func absoluteURL(raw string) bool {
|
||||
u, err := url.Parse(raw)
|
||||
return err == nil && (u.Scheme == "https" || u.Scheme == "http") && u.Host != ""
|
||||
}
|
||||
|
||||
// agentSubscribe asks for a subscription for a visitor of a status page
|
||||
// server and mails the confirmation. It answers the same whether the
|
||||
// address was subscribed already or not.
|
||||
func (s *Server) agentSubscribe(c *gin.Context) {
|
||||
var req agentapi.SubscribeRequest
|
||||
if !bind(c, &req) {
|
||||
return
|
||||
}
|
||||
email, ok := subscriberEmail(req.Email)
|
||||
if !ok {
|
||||
fail(c, http.StatusUnprocessableEntity, "invalid_email")
|
||||
return
|
||||
}
|
||||
if !req.Accepted {
|
||||
fail(c, http.StatusUnprocessableEntity, "consent_required")
|
||||
return
|
||||
}
|
||||
ctx := c.Request.Context()
|
||||
a := agentOf(c)
|
||||
var host, slug *string
|
||||
if h := strings.ToLower(strings.TrimSpace(req.Host)); h != "" {
|
||||
host = &h
|
||||
} else if sl := strings.ToLower(strings.TrimSpace(req.Slug)); sl != "" {
|
||||
slug = &sl
|
||||
} else {
|
||||
fail(c, http.StatusBadRequest, "invalid_input")
|
||||
return
|
||||
}
|
||||
page, ok, err := s.agentServes(ctx, a, host, slug)
|
||||
if err != nil {
|
||||
internalError(c, err)
|
||||
return
|
||||
}
|
||||
if !ok || !page.Subscriptions || s.smtp == nil {
|
||||
fail(c, http.StatusNotFound, "not_found")
|
||||
return
|
||||
}
|
||||
ip := c.ClientIP()
|
||||
if addr, err := netip.ParseAddr(req.IP); err == nil {
|
||||
ip = addr.String()
|
||||
}
|
||||
if !s.limit(c, "subscribe:ip:"+ip, subscribePerIP, subscribeIPWindow) ||
|
||||
!s.limit(c, "subscribe:mailbox:"+mailboxKey(email), subscribePerEmail, subscribeMailboxIn) ||
|
||||
!s.limit(c, "subscribe:page:"+page.ID.String(), subscribePerPage, time.Hour) {
|
||||
return
|
||||
}
|
||||
locale := s.catalog.Match(req.Locale).Lang()
|
||||
pageURL := s.subscriberPageURL(page, a.OrgID != nil, req.PageURL)
|
||||
var (
|
||||
sub store.StatusPageSubscriber
|
||||
send bool
|
||||
)
|
||||
err = s.db.Tx(ctx, tenant.Org(page.OrgID, uuid.Nil), func(q *store.Queries) error {
|
||||
org, err := q.GetOrg(ctx, page.OrgID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if err := q.LockOrgUsage(ctx, page.OrgID); err != nil {
|
||||
return err
|
||||
}
|
||||
existing, err := q.GetPageSubscriberByEmail(ctx, store.GetPageSubscriberByEmailParams{PageID: page.ID, Email: email})
|
||||
switch {
|
||||
case err == nil && existing.ConfirmedAt != nil:
|
||||
return nil
|
||||
case err == nil:
|
||||
sub, send = existing, true
|
||||
return q.TouchPendingSubscriber(ctx, store.TouchPendingSubscriberParams{ID: existing.ID, Locale: locale, PageUrl: pageURL})
|
||||
case !errors.Is(err, pgx.ErrNoRows):
|
||||
return err
|
||||
}
|
||||
if max := s.orgLimits(ctx, org).SubscribersPerWeek; max > 0 {
|
||||
n, err := q.CountRecentSubscribers(ctx, store.CountRecentSubscribersParams{OrgID: page.OrgID, CreatedAt: time.Now().Add(-subscriberWindow)})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if n >= int64(max) {
|
||||
return limitError{"subscriber_limit", max}
|
||||
}
|
||||
}
|
||||
sub, err = q.CreatePageSubscriber(ctx, store.CreatePageSubscriberParams{
|
||||
OrgID: page.OrgID, PageID: page.ID, Email: email, Locale: locale, PageUrl: pageURL,
|
||||
})
|
||||
send = err == nil
|
||||
return err
|
||||
})
|
||||
var le limitError
|
||||
switch {
|
||||
case errors.As(err, &le):
|
||||
s.log.WarnContext(ctx, "status page subscriptions reached the weekly limit", "org", page.OrgID, "page", page.ID, "max", le.max)
|
||||
c.Header("Retry-After", "3600")
|
||||
fail(c, http.StatusTooManyRequests, le.code)
|
||||
return
|
||||
case err != nil:
|
||||
internalError(c, err)
|
||||
return
|
||||
}
|
||||
if send {
|
||||
if err := s.sendSubscriberConfirmation(ctx, sub, page.Title, pageURL); err != nil {
|
||||
s.log.WarnContext(ctx, "mailing a subscription confirmation failed", "page", page.ID, "error", err)
|
||||
internalError(c, err)
|
||||
return
|
||||
}
|
||||
}
|
||||
c.Status(http.StatusAccepted)
|
||||
}
|
||||
|
||||
func (s *Server) sendSubscriberConfirmation(ctx context.Context, sub store.StatusPageSubscriber, title, pageURL string) error {
|
||||
if pageURL == "" {
|
||||
return errors.New("api: no address of the status page for the confirmation link")
|
||||
}
|
||||
token := s.subscriberToken(sub.ID, tokenConfirm, time.Now().Add(confirmTTL))
|
||||
l := s.catalog.Match(sub.Locale)
|
||||
data := map[string]any{"Page": title, "Link": pageURL + "subscribe/confirm?token=" + url.QueryEscape(token), "Hours": int(confirmTTL.Hours())}
|
||||
return s.smtp.Send(ctx, notify.Mail{
|
||||
To: []string{sub.Email}, Subject: l.T("email.subscribe.subject", data), Body: l.T("email.subscribe.body", data),
|
||||
})
|
||||
}
|
||||
|
||||
type subscriptionTokenRequest struct {
|
||||
Token string `json:"token" binding:"required,max=300"`
|
||||
}
|
||||
|
||||
// agentConfirmSubscription confirms a subscription from its mailed link.
|
||||
func (s *Server) agentConfirmSubscription(c *gin.Context) {
|
||||
s.subscriptionByToken(c, tokenConfirm, func(ctx context.Context, q *store.Queries, sub store.GetPageSubscriberRow) error {
|
||||
return q.ConfirmPageSubscriber(ctx, sub.ID)
|
||||
})
|
||||
}
|
||||
|
||||
// agentUnsubscribe ends a subscription from the link in a mail.
|
||||
func (s *Server) agentUnsubscribe(c *gin.Context) {
|
||||
s.subscriptionByToken(c, tokenUnsubscribe, func(ctx context.Context, q *store.Queries, sub store.GetPageSubscriberRow) error {
|
||||
_, err := q.DeletePageSubscriber(ctx, store.DeletePageSubscriberParams{ID: sub.ID, PageID: sub.PageID})
|
||||
return err
|
||||
})
|
||||
}
|
||||
|
||||
func (s *Server) subscriptionByToken(c *gin.Context, purpose string, act func(context.Context, *store.Queries, store.GetPageSubscriberRow) error) {
|
||||
var req subscriptionTokenRequest
|
||||
if !bind(c, &req) {
|
||||
return
|
||||
}
|
||||
id, ok := s.openSubscriberToken(req.Token, purpose, time.Now())
|
||||
if !ok {
|
||||
fail(c, http.StatusNotFound, "not_found")
|
||||
return
|
||||
}
|
||||
ctx := c.Request.Context()
|
||||
a := agentOf(c)
|
||||
var sub store.GetPageSubscriberRow
|
||||
err := s.db.Tx(ctx, tenant.System(), func(q *store.Queries) error {
|
||||
var err error
|
||||
if sub, err = q.GetPageSubscriber(ctx, id); err != nil {
|
||||
return err
|
||||
}
|
||||
// An organization's server acts only on its own pages.
|
||||
if a.OrgID != nil && *a.OrgID != sub.OrgID {
|
||||
return pgx.ErrNoRows
|
||||
}
|
||||
return act(ctx, q, sub)
|
||||
})
|
||||
switch {
|
||||
case errors.Is(err, pgx.ErrNoRows):
|
||||
fail(c, http.StatusNotFound, "not_found")
|
||||
case err != nil:
|
||||
internalError(c, err)
|
||||
default:
|
||||
c.JSON(http.StatusOK, agentapi.SubscriptionInfo{PageTitle: sub.PageTitle, Email: sub.Email})
|
||||
}
|
||||
}
|
||||
|
||||
// deliverSubscriberBatch mails queued incident events to subscribers.
|
||||
func (s *Server) deliverSubscriberBatch(ctx context.Context) int {
|
||||
if s.smtp == nil {
|
||||
return 0
|
||||
}
|
||||
var rows []store.SubscriberNotificationDetailsRow
|
||||
err := s.db.Tx(ctx, tenant.System(), func(q *store.Queries) error {
|
||||
ids, err := q.ClaimSubscriberNotifications(ctx, subscriberBatch)
|
||||
if err != nil || len(ids) == 0 {
|
||||
return err
|
||||
}
|
||||
rows, err = q.SubscriberNotificationDetails(ctx, ids)
|
||||
return err
|
||||
})
|
||||
if err != nil {
|
||||
if ctx.Err() == nil {
|
||||
s.log.WarnContext(ctx, "claiming subscriber notifications failed", "error", err)
|
||||
}
|
||||
return 0
|
||||
}
|
||||
for _, n := range rows {
|
||||
sendErr := s.smtp.Send(ctx, s.subscriberMail(n))
|
||||
s.metrics.SubscriberMail(sendErr)
|
||||
err := s.db.Tx(ctx, tenant.System(), func(q *store.Queries) error {
|
||||
if sendErr == nil {
|
||||
return q.MarkSubscriberNotificationSent(ctx, n.ID)
|
||||
}
|
||||
return q.MarkSubscriberNotificationFailed(ctx, store.MarkSubscriberNotificationFailedParams{
|
||||
ID: n.ID, LastError: ptr(truncateValid(sendErr.Error(), 500)), MaxAttempts: maxSubscriberAttempts,
|
||||
RetryInSeconds: int32(retryDelay(int(n.Attempts)).Seconds()),
|
||||
})
|
||||
})
|
||||
if err != nil {
|
||||
s.log.WarnContext(ctx, "recording subscriber notification failed", "notification", n.ID, "error", err)
|
||||
}
|
||||
if sendErr != nil {
|
||||
s.log.WarnContext(ctx, "mailing a subscriber failed", "notification", n.ID, "page", n.PageID, "attempt", n.Attempts+1, "error", sendErr)
|
||||
}
|
||||
}
|
||||
return len(rows)
|
||||
}
|
||||
|
||||
// subscriberMail is the mail announcing n.
|
||||
func (s *Server) subscriberMail(n store.SubscriberNotificationDetailsRow) notify.Mail {
|
||||
page := store.StatusPage{Slug: n.Slug, CustomDomain: n.CustomDomain, DomainVerifiedAt: n.DomainVerifiedAt}
|
||||
base := s.subscriberPageURL(page, n.OwnServers, n.PageUrl)
|
||||
unsubscribe := base + "unsubscribe?token=" + url.QueryEscape(s.subscriberToken(n.SubscriberID, tokenUnsubscribe, time.Time{}))
|
||||
l := s.catalog.Match(n.Locale)
|
||||
title := n.IncidentTitle
|
||||
if title == "" {
|
||||
title = n.Component
|
||||
}
|
||||
at := n.StartedAt
|
||||
if n.Event == notify.Resolved && n.ResolvedAt != nil {
|
||||
at = *n.ResolvedAt
|
||||
}
|
||||
status := n.UpdateStatusName
|
||||
if status == "" && n.UpdateStatus != "" {
|
||||
status = l.T("incident.status."+n.UpdateStatus, nil)
|
||||
}
|
||||
data := map[string]any{
|
||||
"Page": n.PageTitle, "Title": title, "Component": n.Component, "Link": base,
|
||||
"Time": at.UTC().Format("2006-01-02 15:04") + " UTC", "Status": status, "Message": n.UpdateMessage,
|
||||
"Unsubscribe": unsubscribe,
|
||||
}
|
||||
if n.ResolvedAt != nil {
|
||||
data["Duration"] = n.ResolvedAt.Sub(n.StartedAt).Round(time.Minute).String()
|
||||
}
|
||||
return notify.Mail{
|
||||
To: []string{n.Email},
|
||||
Subject: l.T("email.subscriber."+n.Event+".subject", data),
|
||||
Body: l.T("email.subscriber."+n.Event+".body", data) + l.T("email.subscriber.footer", data),
|
||||
// RFC 8058: mail programs offer unsubscribing with one click.
|
||||
Headers: map[string]string{
|
||||
"List-Unsubscribe": "<" + unsubscribe + ">",
|
||||
"List-Unsubscribe-Post": "List-Unsubscribe=One-Click",
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
// subscriberView is a subscriber in the console.
|
||||
type subscriberView struct {
|
||||
ID uuid.UUID `json:"id"`
|
||||
Email string `json:"email"`
|
||||
Locale string `json:"locale"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
ConfirmedAt *time.Time `json:"confirmed_at"`
|
||||
}
|
||||
|
||||
type subscribersView struct {
|
||||
Confirmed int `json:"confirmed"`
|
||||
Pending int `json:"pending"`
|
||||
Subscribers []subscriberView `json:"subscribers"`
|
||||
}
|
||||
|
||||
func (s *Server) pageSubscribers(ctx context.Context, q *store.Queries, page uuid.UUID) (subscribersView, error) {
|
||||
v := subscribersView{Subscribers: []subscriberView{}}
|
||||
counts, err := q.CountPageSubscribers(ctx, page)
|
||||
if err != nil {
|
||||
return v, err
|
||||
}
|
||||
v.Confirmed, v.Pending = int(counts.Confirmed), int(counts.Pending)
|
||||
rows, err := q.ListPageSubscribers(ctx, store.ListPageSubscribersParams{PageID: page, MaxRows: maxSubscriberList})
|
||||
for _, r := range rows {
|
||||
v.Subscribers = append(v.Subscribers, subscriberView{r.ID, r.Email, r.Locale, r.CreatedAt, r.ConfirmedAt})
|
||||
}
|
||||
return v, err
|
||||
}
|
||||
|
||||
func (s *Server) listPageSubscribers(c *gin.Context) {
|
||||
id := uuid.MustParse(c.Param("id"))
|
||||
p := current(c)
|
||||
ctx := c.Request.Context()
|
||||
var v subscribersView
|
||||
err := s.db.Tx(ctx, p.scope(), func(q *store.Queries) error {
|
||||
if _, err := q.GetStatusPage(ctx, id); err != nil {
|
||||
return err
|
||||
}
|
||||
var err error
|
||||
v, err = s.pageSubscribers(ctx, q, id)
|
||||
return err
|
||||
})
|
||||
switch {
|
||||
case errors.Is(err, pgx.ErrNoRows):
|
||||
fail(c, http.StatusNotFound, "not_found")
|
||||
case err != nil:
|
||||
internalError(c, err)
|
||||
default:
|
||||
c.JSON(http.StatusOK, v)
|
||||
}
|
||||
}
|
||||
|
||||
func (s *Server) deletePageSubscriber(c *gin.Context) {
|
||||
id := uuid.MustParse(c.Param("id"))
|
||||
sub, err := uuid.Parse(c.Param("subscriber"))
|
||||
if err != nil {
|
||||
fail(c, http.StatusNotFound, "not_found")
|
||||
return
|
||||
}
|
||||
p := current(c)
|
||||
ctx := c.Request.Context()
|
||||
var n int64
|
||||
err = s.db.Tx(ctx, p.scope(), func(q *store.Queries) error {
|
||||
var err error
|
||||
n, err = q.DeletePageSubscriber(ctx, store.DeletePageSubscriberParams{ID: sub, PageID: id})
|
||||
return err
|
||||
})
|
||||
switch {
|
||||
case err != nil:
|
||||
internalError(c, err)
|
||||
case n == 0:
|
||||
fail(c, http.StatusNotFound, "not_found")
|
||||
default:
|
||||
c.Status(http.StatusNoContent)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,257 @@
|
||||
package api_test
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"log/slog"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"net/url"
|
||||
"regexp"
|
||||
"strings"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/jackc/pgx/v5"
|
||||
|
||||
"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/notify/notifytest"
|
||||
"git.zb-server.de/ZB-Server/uptimesebi/internal/statuspage"
|
||||
)
|
||||
|
||||
var tokenRE = regexp.MustCompile(`token=([A-Za-z0-9_%-]+)`)
|
||||
|
||||
func TestStatusPageSubscriptions(t *testing.T) {
|
||||
mail := notifytest.NewSMTP(t)
|
||||
e := newEnvWith(t, func(c *config.API) { c.SMTPURL, c.SignupVerify = mail.URL(), "off" })
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
t.Cleanup(cancel)
|
||||
go e.api.RunScheduler(ctx)
|
||||
go e.api.RunNotifier(ctx)
|
||||
|
||||
var healthy atomic.Bool
|
||||
healthy.Store(true)
|
||||
target := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
|
||||
if !healthy.Load() {
|
||||
w.WriteHeader(http.StatusServiceUnavailable)
|
||||
}
|
||||
}))
|
||||
defer target.Close()
|
||||
tok, region := e.platformChecker(t, uniq("eu-"))
|
||||
e.startChecker(t, tok)
|
||||
|
||||
owner := e.browser(t)
|
||||
owner.signup("o@"+uniq("sub")+".test", uniq("sub-"))
|
||||
_, body := owner.do("POST", "/api/v1/org/monitors", map[string]any{
|
||||
"name": "Shop", "type": "http", "target": target.URL, "interval_seconds": 10, "confirmations": 1, "regions": []string{region},
|
||||
})
|
||||
monitorID := body["id"].(string)
|
||||
slug := uniq("subs-")
|
||||
_, body = owner.do("POST", "/api/v1/org/statuspages", map[string]any{"slug": slug, "title": "Shop Status"})
|
||||
pageID := body["id"].(string)
|
||||
page := map[string]any{"slug": slug, "title": "Shop Status", "published": true, "subscriptions": true}
|
||||
st, body := owner.do("PUT", "/api/v1/org/statuspages/"+pageID, page)
|
||||
if st != http.StatusOK || body["subscriptions"] != true {
|
||||
t.Fatalf("enable subscriptions = %d %v", st, body)
|
||||
}
|
||||
owner.do("PUT", "/api/v1/org/statuspages/"+pageID+"/monitors", map[string]any{"monitors": []map[string]any{{"monitor_id": monitorID}}})
|
||||
|
||||
cat, _ := i18n.Load()
|
||||
pages, err := statuspage.New(e.statuspageClient(t, nil), cat, slog.New(slog.DiscardHandler), statuspage.Options{Hosts: []string{"status.test"}})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
gin.SetMode(gin.TestMode)
|
||||
router := gin.New()
|
||||
pages.Mount(router)
|
||||
visitor := "198.51.100.7:1234"
|
||||
visit := func(method, path, form string) (int, string, http.Header) {
|
||||
t.Helper()
|
||||
req := httptest.NewRequest(method, path, strings.NewReader(form))
|
||||
req.Host = "status.test"
|
||||
req.RemoteAddr = visitor
|
||||
if form != "" {
|
||||
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
|
||||
}
|
||||
w := httptest.NewRecorder()
|
||||
router.ServeHTTP(w, req)
|
||||
pages.Wait()
|
||||
return w.Code, w.Body.String(), w.Header()
|
||||
}
|
||||
subscribers := func() (int, int) {
|
||||
_, body := owner.do("GET", "/api/v1/org/statuspages/"+pageID+"/subscribers", nil)
|
||||
return int(body["confirmed"].(float64)), int(body["pending"].(float64))
|
||||
}
|
||||
mailsTo := func(addr string) []string {
|
||||
var out []string
|
||||
for _, m := range mail.Messages() {
|
||||
if len(m.To) == 1 && m.To[0] == addr {
|
||||
out = append(out, m.Data)
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// Subscribers accept the page's privacy policy.
|
||||
if st, body := owner.do("PUT", "/api/v1/org/legal/privacy", map[string]any{"url": "https://shop.example/privacy"}); st != http.StatusNoContent {
|
||||
t.Fatalf("set privacy policy = %d %v", st, body)
|
||||
}
|
||||
t.Cleanup(func() { owner.do("PUT", "/api/v1/org/legal/privacy", map[string]any{}) })
|
||||
pages.Sync(ctx)
|
||||
code, html, _ := visit("GET", "/"+slug, "")
|
||||
if code != 200 || !strings.Contains(html, `action="/`+slug+`/subscribe"`) || !strings.Contains(html, "feed.rss") {
|
||||
t.Fatalf("page = %d, want the subscription form and the feed link", code)
|
||||
}
|
||||
if !strings.Contains(html, `name="accept"`) || !strings.Contains(html, `href="https://shop.example/privacy"`) {
|
||||
t.Error("the subscription form does not ask to accept the privacy policy")
|
||||
}
|
||||
if code, html, _ := visit("POST", "/"+slug+"/subscribe", "email=not-an-address&accept=1"); code != http.StatusUnprocessableEntity {
|
||||
t.Errorf("subscribing an invalid address = %d %.200s", code, html)
|
||||
}
|
||||
visitor = "198.51.100.9:1234" // (not to use up the subscription requests of the first)
|
||||
if code, _, _ := visit("POST", "/"+slug+"/subscribe", "email=visitor@example.test"); code != http.StatusUnprocessableEntity {
|
||||
t.Errorf("subscribing without accepting the privacy policy = %d, want 422", code)
|
||||
}
|
||||
visitor = "198.51.100.7:1234"
|
||||
if code, _, _ := visit("POST", "/"+slug+"/subscribe", "email=Visitor@Example.test&accept=1"); code != 200 {
|
||||
t.Fatalf("subscribe = %d", code)
|
||||
}
|
||||
if c, p := subscribers(); c != 0 || p != 1 {
|
||||
t.Errorf("subscribers after subscribing = %d confirmed, %d pending; want 0, 1", c, p)
|
||||
}
|
||||
sent := mailsTo("visitor@example.test")
|
||||
if len(sent) != 1 || !strings.Contains(sent[0], "Shop Status") {
|
||||
t.Fatalf("confirmation mails = %d", len(sent))
|
||||
}
|
||||
m := tokenRE.FindStringSubmatch(sent[0])
|
||||
if m == nil {
|
||||
t.Fatal("no token in the confirmation mail")
|
||||
}
|
||||
confirm, _ := url.QueryUnescape(m[1])
|
||||
|
||||
// Opening the link only shows a button.
|
||||
if code, html, _ := visit("GET", "/"+slug+"/subscribe/confirm?token="+url.QueryEscape(confirm), ""); code != 200 || !strings.Contains(html, `name="token"`) {
|
||||
t.Errorf("confirmation link = %d", code)
|
||||
}
|
||||
if c, _ := subscribers(); c != 0 {
|
||||
t.Error("opening the confirmation link confirmed the subscription")
|
||||
}
|
||||
if code, _, _ := visit("POST", "/"+slug+"/unsubscribe", "token="+url.QueryEscape(confirm)); code != http.StatusNotFound {
|
||||
t.Errorf("unsubscribing with the confirmation token = %d, want 404", code)
|
||||
}
|
||||
if code, html, _ := visit("POST", "/"+slug+"/subscribe/confirm", "token="+url.QueryEscape(confirm)); code != 200 || !strings.Contains(html, "visitor@example.test") {
|
||||
t.Fatalf("confirm = %d %.300s", code, html)
|
||||
}
|
||||
if c, p := subscribers(); c != 1 || p != 0 {
|
||||
t.Errorf("subscribers after confirming = %d, %d; want 1, 0", c, p)
|
||||
}
|
||||
// Asking again for a confirmed address mails nothing.
|
||||
visit("POST", "/"+slug+"/subscribe", "email=visitor@example.test&accept=1")
|
||||
if n := len(mailsTo("visitor@example.test")); n != 1 {
|
||||
t.Errorf("mails after subscribing a confirmed address again = %d, want 1", n)
|
||||
}
|
||||
|
||||
healthy.Store(false)
|
||||
waitFor(t, 30*time.Second, "outage mail to the subscriber", func() bool { return len(mailsTo("visitor@example.test")) == 2 })
|
||||
outage := mailsTo("visitor@example.test")[1]
|
||||
if !strings.Contains(outage, "Shop") || !strings.Contains(outage, "List-Unsubscribe: <http") || !strings.Contains(outage, "List-Unsubscribe-Post: List-Unsubscribe=One-Click") {
|
||||
t.Errorf("outage mail = %.600s", outage)
|
||||
}
|
||||
_, body = owner.do("GET", "/api/v1/org/incidents", nil)
|
||||
incidentID := body["incidents"].([]any)[0].(map[string]any)["id"].(string)
|
||||
owner.do("POST", "/api/v1/org/incidents/"+incidentID+"/updates", map[string]any{"status": "identified", "message": "Payment provider down", "public": false})
|
||||
owner.do("POST", "/api/v1/org/incidents/"+incidentID+"/updates", map[string]any{"status": "identified", "message": "We found the cause", "public": true})
|
||||
waitFor(t, 10*time.Second, "update mail", func() bool { return len(mailsTo("visitor@example.test")) == 3 })
|
||||
if upd := mailsTo("visitor@example.test")[2]; !strings.Contains(upd, "We found the cause") {
|
||||
t.Errorf("update mail = %.400s", upd)
|
||||
}
|
||||
time.Sleep(3 * time.Second)
|
||||
for _, m := range mailsTo("visitor@example.test") {
|
||||
if strings.Contains(m, "Payment provider down") {
|
||||
t.Error("a private update was mailed to a subscriber")
|
||||
}
|
||||
}
|
||||
|
||||
// Feed and API come from the snapshot.
|
||||
pages.Sync(ctx)
|
||||
code, feed, hdr := visit("GET", "/"+slug+"/feed.rss", "")
|
||||
if code != 200 || !strings.HasPrefix(hdr.Get("Content-Type"), "application/rss+xml") || !strings.Contains(feed, "<rss") ||
|
||||
!strings.Contains(feed, "incident-"+incidentID) || !strings.Contains(feed, "We found the cause") {
|
||||
t.Errorf("feed = %d %.600s", code, feed)
|
||||
}
|
||||
code, raw, hdr := visit("GET", "/"+slug+"/api/v1/summary", "")
|
||||
var summary struct {
|
||||
Page struct{ Title, Status string }
|
||||
Components []struct{ Name, Status string }
|
||||
Incidents []struct{ ID string }
|
||||
}
|
||||
if err := json.Unmarshal([]byte(raw), &summary); code != 200 || err != nil || hdr.Get("Access-Control-Allow-Origin") != "*" ||
|
||||
summary.Page.Title != "Shop Status" || len(summary.Components) != 1 || len(summary.Incidents) != 1 || summary.Incidents[0].ID != incidentID {
|
||||
t.Errorf("summary = %d %v %s", code, err, raw)
|
||||
}
|
||||
if code, _, _ := visit("GET", "/"+slug+"/api/v1/nope", ""); code != 404 {
|
||||
t.Errorf("unknown API resource = %d", code)
|
||||
}
|
||||
|
||||
// The unsubscribe link of mails works with one click, as mail
|
||||
// programs post it.
|
||||
m = tokenRE.FindStringSubmatch(outage)
|
||||
unsub, _ := url.QueryUnescape(m[1])
|
||||
if code, html, _ := visit("POST", "/"+slug+"/unsubscribe?token="+url.QueryEscape(unsub), "List-Unsubscribe=One-Click"); code != 200 {
|
||||
t.Errorf("one-click unsubscribe = %d %.300s", code, html)
|
||||
}
|
||||
if c, p := subscribers(); c != 0 || p != 0 {
|
||||
t.Errorf("subscribers after unsubscribing = %d, %d", c, p)
|
||||
}
|
||||
|
||||
// The weekly limit counts every subscription asked for.
|
||||
if err := e.asSystem(t, func(tx pgx.Tx) error {
|
||||
_, err := tx.Exec(ctx, `UPDATE orgs SET limit_subscribers_per_week = 1 WHERE id = $1`, owner.orgID())
|
||||
return err
|
||||
}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if code, _, _ := visit("POST", "/"+slug+"/subscribe", "email=second@example.test&accept=1"); code != 200 {
|
||||
t.Errorf("subscription within the weekly limit = %d", code)
|
||||
}
|
||||
if code, _, _ := visit("POST", "/"+slug+"/subscribe", "email=third@example.test&accept=1"); code != http.StatusTooManyRequests {
|
||||
t.Errorf("subscription beyond the weekly limit = %d, want 429", code)
|
||||
}
|
||||
if n := len(mailsTo("third@example.test")); n != 0 {
|
||||
t.Errorf("mails beyond the weekly limit = %d", n)
|
||||
}
|
||||
|
||||
// Pages without subscriptions take none. (Another visitor: this one
|
||||
// used up its subscription requests.)
|
||||
visitor = "198.51.100.8:1234"
|
||||
page["subscriptions"] = false
|
||||
owner.do("PUT", "/api/v1/org/statuspages/"+pageID, page)
|
||||
pages.Sync(ctx)
|
||||
if code, html, _ := visit("GET", "/"+slug, ""); code != 200 || strings.Contains(html, "/subscribe\"") {
|
||||
t.Errorf("page without subscriptions = %d, still offers the form", code)
|
||||
}
|
||||
if code, _, _ := visit("POST", "/"+slug+"/subscribe", "email=fourth@example.test&accept=1"); code != http.StatusNotFound {
|
||||
t.Errorf("subscribing where it is off = %d, want 404", code)
|
||||
}
|
||||
|
||||
// This visitor used up its subscription requests on the server.
|
||||
visitor = "198.51.100.7:1234"
|
||||
if code, _, _ := visit("POST", "/"+slug+"/subscribe", "email=fifth@example.test&accept=1"); code != http.StatusTooManyRequests {
|
||||
t.Errorf("sixth subscription request of a visitor = %d, want 429", code)
|
||||
}
|
||||
|
||||
// Polling the API is rate limited per visitor.
|
||||
limited := false
|
||||
for range 70 {
|
||||
if code, _, _ := visit("GET", "/"+slug+"/api/v1/status", ""); code == http.StatusTooManyRequests {
|
||||
limited = true
|
||||
break
|
||||
}
|
||||
}
|
||||
if !limited {
|
||||
t.Error("70 API requests within a minute were all answered")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,61 @@
|
||||
package api
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
// slowPage is when a console page logs how long its steps took.
|
||||
const slowPage = time.Second
|
||||
|
||||
// stepTimer measures the steps of a request. It reports them to the
|
||||
// browser in a Server-Timing header and, when the request was slow, in
|
||||
// the log.
|
||||
type stepTimer struct {
|
||||
start, last time.Time
|
||||
steps []step
|
||||
}
|
||||
|
||||
type step struct {
|
||||
name string
|
||||
d time.Duration
|
||||
}
|
||||
|
||||
func newStepTimer() *stepTimer {
|
||||
now := time.Now()
|
||||
return &stepTimer{start: now, last: now}
|
||||
}
|
||||
|
||||
// done ends the step name.
|
||||
func (t *stepTimer) done(name string) {
|
||||
now := time.Now()
|
||||
t.steps = append(t.steps, step{name, now.Sub(t.last)})
|
||||
t.last = now
|
||||
}
|
||||
|
||||
// header sets the Server-Timing header of the steps so far; call it
|
||||
// before the body is written.
|
||||
func (t *stepTimer) header(c *gin.Context) {
|
||||
parts := make([]string, len(t.steps))
|
||||
for i, s := range t.steps {
|
||||
parts[i] = fmt.Sprintf("%s;dur=%.1f", s.name, float64(s.d.Microseconds())/1000)
|
||||
}
|
||||
c.Header("Server-Timing", strings.Join(parts, ", "))
|
||||
}
|
||||
|
||||
// logIfSlow logs the steps when the request took slowPage or longer.
|
||||
func (t *stepTimer) logIfSlow(c *gin.Context, log *slog.Logger) {
|
||||
total := time.Since(t.start)
|
||||
if total < slowPage {
|
||||
return
|
||||
}
|
||||
attrs := []any{"path", c.Request.URL.Path, "total_ms", total.Milliseconds()}
|
||||
for _, s := range t.steps {
|
||||
attrs = append(attrs, s.name+"_ms", s.d.Milliseconds())
|
||||
}
|
||||
log.WarnContext(c.Request.Context(), "slow console page", attrs...)
|
||||
}
|
||||
@@ -8,6 +8,7 @@ import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"log/slog"
|
||||
"math/rand/v2"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"time"
|
||||
@@ -30,6 +31,9 @@ const (
|
||||
// quickPoll is a long poll answered empty faster than any wait would.
|
||||
quickPoll = 200 * time.Millisecond
|
||||
flushInterval = 2 * time.Second
|
||||
// fullHeartbeat is how often a checker with every slot busy still polls,
|
||||
// so the API keeps it live; well below schedule.StaleAfter.
|
||||
fullHeartbeat = 5 * time.Second
|
||||
// maxPending bounds results kept while the API is unreachable.
|
||||
maxPending = 50_000
|
||||
)
|
||||
@@ -39,6 +43,8 @@ type Runner struct {
|
||||
api API
|
||||
log *slog.Logger
|
||||
slots chan struct{}
|
||||
// freed is signalled when a slot is freed, for a poll waiting for one.
|
||||
freed chan struct{}
|
||||
run func(context.Context, check.Spec) check.Outcome
|
||||
|
||||
results chan agentapi.Result
|
||||
@@ -46,6 +52,8 @@ type Runner struct {
|
||||
|
||||
evidenceMu sync.Mutex
|
||||
evidence map[uuid.UUID]evidenceState
|
||||
// jitter returns a random duration in [0, d), replaced in tests.
|
||||
jitter func(d time.Duration) time.Duration
|
||||
}
|
||||
|
||||
// evidenceState remembers what was last sent for a monitor.
|
||||
@@ -61,13 +69,23 @@ const evidenceEvery = 10 * time.Minute
|
||||
// shouldSendEvidence decides whether a result carries its evidence: every
|
||||
// failure, every change between success and failure, and otherwise every
|
||||
// evidenceEvery. Most results thus stay small.
|
||||
//
|
||||
// Evidence sent for another reason than the period, like the first result
|
||||
// after a start, puts the next periodic one at a random point of the
|
||||
// period. Otherwise every monitor would send its evidence in the same
|
||||
// minute every period after a restart, and the API would have to store all
|
||||
// of it at once.
|
||||
func (r *Runner) shouldSendEvidence(monitor uuid.UUID, ok bool, now time.Time) bool {
|
||||
r.evidenceMu.Lock()
|
||||
defer r.evidenceMu.Unlock()
|
||||
last, seen := r.evidence[monitor]
|
||||
send := !ok || !seen || last.ok != ok || now.Sub(last.sent) >= evidenceEvery
|
||||
if send {
|
||||
periodic := seen && last.ok == ok && now.Sub(last.sent) >= evidenceEvery
|
||||
send := !ok || !seen || last.ok != ok || periodic
|
||||
switch {
|
||||
case periodic:
|
||||
last.sent = now
|
||||
case send:
|
||||
last.sent = now.Add(-r.jitter(evidenceEvery))
|
||||
}
|
||||
last.ok = ok
|
||||
r.evidence[monitor] = last
|
||||
@@ -80,10 +98,12 @@ func New(api API, concurrency int, log *slog.Logger) *Runner {
|
||||
api: api,
|
||||
log: log,
|
||||
slots: make(chan struct{}, max(concurrency, 1)),
|
||||
freed: make(chan struct{}, 1),
|
||||
run: check.Run,
|
||||
results: make(chan agentapi.Result, 1024),
|
||||
|
||||
evidence: map[uuid.UUID]evidenceState{},
|
||||
jitter: rand.N[time.Duration],
|
||||
}
|
||||
}
|
||||
|
||||
@@ -170,19 +190,49 @@ func (r *Runner) poll(ctx context.Context, running *sync.WaitGroup) error {
|
||||
r.slots <- struct{}{}
|
||||
running.Add(1)
|
||||
go func() {
|
||||
defer func() { <-r.slots; running.Done() }()
|
||||
defer func() { r.release(); running.Done() }()
|
||||
r.results <- r.execute(ctx, j)
|
||||
}()
|
||||
}
|
||||
// A long poll answered empty at once, as by an instance shutting
|
||||
// down, is not repeated at once either.
|
||||
if free == 0 || (len(jobs) == 0 && wait > 0 && time.Since(asked) < quickPoll) {
|
||||
switch {
|
||||
case free == 0:
|
||||
// Take work again as soon as a check finishes, not after a
|
||||
// fixed pause, which would cap throughput at slots per pause.
|
||||
r.waitForSlot(ctx, fullHeartbeat)
|
||||
case len(jobs) == 0 && wait > 0 && time.Since(asked) < quickPoll:
|
||||
// A long poll answered empty at once, as by an instance
|
||||
// shutting down, is not repeated at once either.
|
||||
sleep(ctx, time.Second)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// release frees a slot and wakes a poll waiting for one.
|
||||
func (r *Runner) release() {
|
||||
<-r.slots
|
||||
select {
|
||||
case r.freed <- struct{}{}:
|
||||
default:
|
||||
}
|
||||
}
|
||||
|
||||
// waitForSlot returns once a slot is free, ctx is done or at most after
|
||||
// d.
|
||||
func (r *Runner) waitForSlot(ctx context.Context, d time.Duration) {
|
||||
t := time.NewTimer(d)
|
||||
defer t.Stop()
|
||||
for len(r.slots) == cap(r.slots) {
|
||||
select {
|
||||
case <-r.freed:
|
||||
case <-ctx.Done():
|
||||
return
|
||||
case <-t.C:
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (r *Runner) execute(ctx context.Context, j agentapi.Job) agentapi.Result {
|
||||
// Checks already started finish even during shutdown; their timeout
|
||||
// bounds them.
|
||||
|
||||
@@ -10,6 +10,7 @@ import (
|
||||
|
||||
func TestEvidencePolicy(t *testing.T) {
|
||||
r := New(nil, 1, slog.New(slog.DiscardHandler))
|
||||
r.jitter = func(time.Duration) time.Duration { return 0 }
|
||||
m := uuid.New()
|
||||
now := time.Now()
|
||||
steps := []struct {
|
||||
@@ -31,3 +32,39 @@ func TestEvidencePolicy(t *testing.T) {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// TestEvidenceSpreadsAfterStart starts with many healthy monitors at once:
|
||||
// their periodic evidence must not all fall into the same minute again.
|
||||
func TestEvidenceSpreadsAfterStart(t *testing.T) {
|
||||
r := New(nil, 1, slog.New(slog.DiscardHandler))
|
||||
start := time.Now()
|
||||
const monitors = 600
|
||||
ids := make([]uuid.UUID, monitors)
|
||||
for i := range ids {
|
||||
ids[i] = uuid.New()
|
||||
if !r.shouldSendEvidence(ids[i], true, start) {
|
||||
t.Fatal("first result sent no evidence")
|
||||
}
|
||||
}
|
||||
// One result per monitor and minute over the next period.
|
||||
perMinute := map[int]int{}
|
||||
for minute := 1; minute <= int(evidenceEvery/time.Minute); minute++ {
|
||||
for _, id := range ids {
|
||||
if r.shouldSendEvidence(id, true, start.Add(time.Duration(minute)*time.Minute)) {
|
||||
perMinute[minute]++
|
||||
}
|
||||
}
|
||||
}
|
||||
total, peak := 0, 0
|
||||
for _, n := range perMinute {
|
||||
total += n
|
||||
peak = max(peak, n)
|
||||
}
|
||||
if total != monitors {
|
||||
t.Errorf("periodic evidence in the first period = %d, want one per monitor, %d", total, monitors)
|
||||
}
|
||||
// 60 a minute on average; all 600 in one minute without the jitter.
|
||||
if peak > 150 {
|
||||
t.Errorf("busiest minute sent %d evidence, want them spread at about %d a minute", peak, monitors/10)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,108 @@
|
||||
package checker
|
||||
|
||||
import (
|
||||
"context"
|
||||
"log/slog"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"git.zb-server.de/ZB-Server/uptimesebi/internal/agentapi"
|
||||
"git.zb-server.de/ZB-Server/uptimesebi/internal/check"
|
||||
)
|
||||
|
||||
// backlogAPI hands out queued jobs as fast as the checker asks for them.
|
||||
type backlogAPI struct {
|
||||
mu sync.Mutex
|
||||
queued int
|
||||
polls int
|
||||
reported atomic.Int64
|
||||
}
|
||||
|
||||
func (b *backlogAPI) Jobs(ctx context.Context, max int, wait time.Duration) ([]agentapi.Job, error) {
|
||||
b.mu.Lock()
|
||||
b.polls++
|
||||
n := min(max, b.queued)
|
||||
b.queued -= n
|
||||
b.mu.Unlock()
|
||||
if n == 0 {
|
||||
select {
|
||||
case <-time.After(min(wait, 50*time.Millisecond)):
|
||||
case <-ctx.Done():
|
||||
}
|
||||
return nil, nil
|
||||
}
|
||||
jobs := make([]agentapi.Job, n)
|
||||
for i := range jobs {
|
||||
jobs[i] = agentapi.Job{MonitorID: uuid.New(), Type: "tcp", Target: "x:1"}
|
||||
}
|
||||
return jobs, nil
|
||||
}
|
||||
|
||||
func (b *backlogAPI) Report(_ context.Context, rs []agentapi.Result) error {
|
||||
b.reported.Add(int64(len(rs)))
|
||||
return nil
|
||||
}
|
||||
|
||||
func (b *backlogAPI) Release(context.Context) error { return nil }
|
||||
|
||||
// TestFullCheckerTakesWorkAsSlotsFree runs a backlog through a single slot.
|
||||
// A checker pausing a second whenever its slots are full would need about a
|
||||
// second per job.
|
||||
func TestFullCheckerTakesWorkAsSlotsFree(t *testing.T) {
|
||||
const jobs = 10
|
||||
api := &backlogAPI{queued: jobs}
|
||||
r := New(api, 1, slog.New(slog.DiscardHandler))
|
||||
var ran atomic.Int64
|
||||
r.run = func(context.Context, check.Spec) check.Outcome {
|
||||
time.Sleep(5 * time.Millisecond)
|
||||
ran.Add(1)
|
||||
return check.Outcome{OK: true}
|
||||
}
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
done := make(chan error, 1)
|
||||
go func() { done <- r.Run(ctx, time.Second) }()
|
||||
|
||||
start := time.Now()
|
||||
for ran.Load() < jobs && time.Since(start) < 5*time.Second {
|
||||
time.Sleep(5 * time.Millisecond)
|
||||
}
|
||||
took := time.Since(start)
|
||||
cancel()
|
||||
if err := <-done; err != nil {
|
||||
t.Errorf("Run() = %v", err)
|
||||
}
|
||||
if n := ran.Load(); n != jobs {
|
||||
t.Fatalf("ran %d checks in %v, want %d", n, took, jobs)
|
||||
}
|
||||
if took > 2*time.Second {
|
||||
t.Errorf("%d checks through one slot took %v, want well under a second each", jobs, took)
|
||||
}
|
||||
if n := api.reported.Load(); n != jobs {
|
||||
t.Errorf("reported %d results, want %d", n, jobs)
|
||||
}
|
||||
}
|
||||
|
||||
// TestWaitForSlotKeepsPolling bounds the wait, so a checker whose slots
|
||||
// stay busy still polls as a heartbeat.
|
||||
func TestWaitForSlotKeepsPolling(t *testing.T) {
|
||||
r := New(nil, 1, slog.New(slog.DiscardHandler))
|
||||
r.slots <- struct{}{}
|
||||
start := time.Now()
|
||||
r.waitForSlot(context.Background(), 50*time.Millisecond)
|
||||
if took := time.Since(start); took < 50*time.Millisecond || took > time.Second {
|
||||
t.Errorf("waitForSlot() with every slot busy returned after %v, want the bound of 50ms", took)
|
||||
}
|
||||
go func() {
|
||||
time.Sleep(20 * time.Millisecond)
|
||||
r.release()
|
||||
}()
|
||||
start = time.Now()
|
||||
r.waitForSlot(context.Background(), 5*time.Second)
|
||||
if took := time.Since(start); took > time.Second {
|
||||
t.Errorf("waitForSlot() returned %v after a slot was freed, want at once", took)
|
||||
}
|
||||
}
|
||||
@@ -70,6 +70,9 @@ const (
|
||||
SignupClosed SignupMode = "closed"
|
||||
)
|
||||
|
||||
// MetricsOff switches the metrics listener off.
|
||||
const MetricsOff = "off"
|
||||
|
||||
// API configures cmd/api.
|
||||
type API struct {
|
||||
Common
|
||||
@@ -77,6 +80,11 @@ type API struct {
|
||||
Listen string `env:"UPTIME_API_LISTEN" envDefault:":8080"`
|
||||
SecretKeys string `env:"UPTIME_SECRET_KEYS"`
|
||||
Signup SignupMode `env:"UPTIME_SIGNUP" envDefault:"first-user"`
|
||||
|
||||
// MetricsListen is where Prometheus metrics are served, apart from the
|
||||
// public listener; "off" switches them off.
|
||||
MetricsListen string `env:"UPTIME_API_METRICS_LISTEN" envDefault:":9090"`
|
||||
|
||||
// SignupVerify is "auto", "required" or "off": whether new accounts
|
||||
// confirm their email address before signing in. Auto requires it in
|
||||
// the cloud edition and wherever mail can be sent.
|
||||
|
||||
@@ -129,6 +129,7 @@
|
||||
"audit.action.platform.org_suspension": "Organisation gesperrt oder entsperrt",
|
||||
"audit.action.platform.region_create": "Plattform-Region erstellt",
|
||||
"audit.action.platform.region_delete": "Plattform-Region gelöscht",
|
||||
"audit.action.platform.region_update": "Standort einer Plattform-Region geändert",
|
||||
"audit.action.platform.status_page_delete": "Statusseite durch Admin gelöscht",
|
||||
"audit.action.platform.status_page_suspension": "Statusseite gesperrt oder entsperrt",
|
||||
"audit.action.platform.user_delete": "Account durch Admin gelöscht",
|
||||
@@ -136,6 +137,7 @@
|
||||
"audit.action.platform.user_suspension": "Account gesperrt oder entsperrt",
|
||||
"audit.action.region.create": "Region erstellt",
|
||||
"audit.action.region.delete": "Region gelöscht",
|
||||
"audit.action.region.update": "Standort einer Region geändert",
|
||||
"audit.action.role.create": "Rolle erstellt",
|
||||
"audit.action.role.delete": "Rolle gelöscht",
|
||||
"audit.action.role.update": "Rolle geändert",
|
||||
@@ -519,6 +521,7 @@
|
||||
"email.domain_missing.subject": "Der DNS-Eintrag von {{.Domain}} fehlt",
|
||||
"email.domain_off.body": "Der DNS-Eintrag von {{.Domain}} fehlt seit einer Woche, deshalb wird die Statusseite {{.Page}} dort nicht mehr ausgeliefert.\n\nStelle den Eintrag wieder her und prüfe die Domain erneut:\n{{.Link}}",
|
||||
"email.domain_off.subject": "{{.Domain}} wurde abgeschaltet",
|
||||
"email.monitor_link": "In UptimeSebi öffnen: {{.Link}}",
|
||||
"email.opened.body": "{{.Monitor}} ({{.Target}}) ist in allen Regionen nicht erreichbar seit {{.Since}}.\n\nLetzte Fehler:\n{{.Cause}}\n\nDu erhältst diese Nachricht, weil ein Benachrichtigungskanal deiner Organisation diese Adresse nutzt.",
|
||||
"email.opened.subject": "[DOWN] {{.Monitor}}",
|
||||
"email.region_back.body": "Region {{.Region}} hat wieder einen aktiven Checker; seit {{.Since}} hatte sie keinen. Überfällige Prüfungen laufen sofort.\n\n{{.Link}}",
|
||||
@@ -571,6 +574,7 @@
|
||||
"error.invalid_credentials": "E-Mail oder Passwort falsch.",
|
||||
"error.invalid_cursor": "Dieser Seitenlink ist ungültig; beginne bei der ersten Seite.",
|
||||
"error.invalid_domain": "Eine der Domains ist ungültig.",
|
||||
"error.consent_required": "Bitte stimme den Bedingungen zu, um zu abonnieren.",
|
||||
"error.invalid_email": "Bitte eine gültige E-Mail-Adresse eingeben.",
|
||||
"error.invalid_expect_status": "Erwartete Statuscodes müssen Codes wie 200 oder Klassen wie 2xx sein.",
|
||||
"error.invalid_grace": "Die Toleranz muss zwischen 0 Sekunden und einem Tag liegen.",
|
||||
@@ -585,6 +589,7 @@
|
||||
"error.invalid_maintenance_time": "Prüfe Beginn, Wochentage und letzten Tag.",
|
||||
"error.invalid_matchers": "Lege 1 bis 20 Label-Matcher mit gültigen Label-Namen und regulären Ausdrücken an.",
|
||||
"error.invalid_method": "Nur GET- und HEAD-Anfragen werden unterstützt.",
|
||||
"error.invalid_location": "Breitengrad (−90 bis 90) und Längengrad (−180 bis 180) angeben, oder keins von beiden.",
|
||||
"error.invalid_monitor": "Einer der Monitore existiert nicht oder ist doppelt aufgeführt.",
|
||||
"error.invalid_permissions": "Mindestens eine Berechtigung auswählen.",
|
||||
"error.invalid_query": "Gib eine PromQL-Abfrage mit höchstens 2000 Zeichen ein.",
|
||||
@@ -995,6 +1000,9 @@
|
||||
"members.step_down_confirm": "Als Owner zurücktreten? Ohne andere Rollen arbeitest du mit der Admin-Rolle weiter.",
|
||||
"members.title": "Mitglieder",
|
||||
"members.unassign": "Rolle entfernen",
|
||||
"meta.app_card_subtitle": "Monitore, Alarme und Statusseiten, Open Source",
|
||||
"meta.app_card_title": "Uptime-Monitoring und Statusseiten",
|
||||
"meta.app_description": "UptimeSebi überwacht Websites, Server und Dienste aus mehreren Regionen, alarmiert bei Ausfällen und betreibt öffentliche Statusseiten. Open Source.",
|
||||
"moderation.actions": "Sperren oder löschen …",
|
||||
"moderation.created": "Erstellt",
|
||||
"moderation.delete_confirm_org": "Organisation {{.Name}} mit allen Monitoren, Ergebnissen und Statusseiten endgültig löschen?",
|
||||
@@ -1122,6 +1130,7 @@
|
||||
"monitors.ping_intro": "Rufe diese URL am Ende jedes erfolgreichen Laufs auf, per GET, HEAD oder POST. Mit angehängtem /fail meldest du einen Fehler; ein POST-Body oder ?msg= wird als Meldung gespeichert.",
|
||||
"monitors.ping_secret": "Halte die URL geheim: Wer sie kennt, kann den Job als gesund melden. Nur Mitglieder, die diesen Monitor bearbeiten dürfen, sehen sie.",
|
||||
"monitors.ping_url": "Ping-URL",
|
||||
"monitors.platform_regions_limit": "Bis zu {{.Max}} Plattform-Regionen pro Monitor; eigene Regionen zählen nicht.",
|
||||
"monitors.prom_empty_ok": "Keine Daten sind in Ordnung",
|
||||
"monitors.prom_hint": "Ziel ist die Basis-URL von Prometheus, z. B. https://prometheus.example.com. Thanos, Mimir und VictoriaMetrics funktionieren ebenso. Für geschützte Server Authorization-Header nutzen.",
|
||||
"monitors.prom_mode": "Serien",
|
||||
@@ -1138,6 +1147,7 @@
|
||||
"monitors.recent": "Letzte Checks",
|
||||
"monitors.regions": "Regionen",
|
||||
"monitors.regions_hint": "Geprüft von einem zufälligen Checker jeder gewählten Region. Deine eigenen Regionen stehen oben.",
|
||||
"monitors.regions_limit": "Bis zu {{.Max}} Regionen pro Monitor.",
|
||||
"monitors.results_title": "Prüfergebnisse",
|
||||
"monitors.search": "Nach Name oder Ziel suchen",
|
||||
"monitors.secret_unchanged": "unverändert",
|
||||
@@ -1251,6 +1261,7 @@
|
||||
"page.incidents": "Letzte Vorfälle",
|
||||
"page.maintenance_ongoing": "Laufende Wartung",
|
||||
"page.maintenance_upcoming": "Geplante Wartung",
|
||||
"page.meta_description": "Aktueller Status von {{.Title}}: {{.Status}}. Störungen und geplante Wartungen auf einen Blick.",
|
||||
"page.no_incidents": "Keine Vorfälle in den letzten 14 Tagen.",
|
||||
"page.stale": "Live-Aktualisierung derzeit nicht verfügbar. Diese Seite zeigt den Stand von {{.Time}}.",
|
||||
"page.status.degraded": "Einige Systeme haben Probleme",
|
||||
@@ -1259,6 +1270,13 @@
|
||||
"page.status.outage": "Größere Störung",
|
||||
"page.status.unknown": "Status derzeit nicht verfügbar",
|
||||
"page.today": "Heute",
|
||||
"page.pages": "Seite {{.Page}} von {{.Pages}}",
|
||||
"page.search": "Komponenten suchen",
|
||||
"page.search_submit": "Suchen",
|
||||
"page.search_clear": "Alle anzeigen",
|
||||
"page.search_none": "Keine Komponente passt zur Suche.",
|
||||
"page.filter_problems": "Nur Ausfälle ({{.Count}})",
|
||||
"page.filter_no_problems": "Keine Komponente hat einen Ausfall.",
|
||||
"page.updated": "Aktualisiert {{.Time}}",
|
||||
"pager.earlier": "Frühere",
|
||||
"pager.first": "Zum Anfang",
|
||||
@@ -1308,6 +1326,7 @@
|
||||
"pages.monitors_filter": "Monitore filtern",
|
||||
"pages.monitors_all": "Alle hinzufügen",
|
||||
"pages.monitors_none": "Alle entfernen",
|
||||
"pages.monitors_range": "{from}–{to} von {total}",
|
||||
"pages.no_group": "Ohne Gruppe",
|
||||
"pages.open": "Öffnen",
|
||||
"pages.own_servers": "Die Statusseiten dieser Organisation liefern nur ihre eigenen Statusseiten-Server aus, nicht die der Plattform. Ruf sie über die Adresse deiner Server auf oder verbinde eine eigene Domain, die auf sie zeigt.",
|
||||
@@ -1351,6 +1370,16 @@
|
||||
"one": "{{.Count}} aktiv",
|
||||
"other": "{{.Count}} aktiv"
|
||||
},
|
||||
"regions.latitude": "Breitengrad",
|
||||
"regions.location": "Standort",
|
||||
"regions.location_clear": "Standort entfernen",
|
||||
"regions.location_for": "Standort von {{.Name}}: auf die Karte klicken oder die Koordinaten eingeben.",
|
||||
"regions.location_pick_hint": "Ein Klick auf die Karte setzt die Koordinaten einer neuen Region oder der Region, deren Standort du gerade setzt.",
|
||||
"regions.location_set": "Setzen",
|
||||
"regions.longitude": "Längengrad",
|
||||
"regions.map_ctrl_key": "Strg",
|
||||
"regions.map_scroll_hint": "{{.Key}} + Scrollen zoomt die Karte.",
|
||||
"regions.map_touch_hint": "Mit zwei Fingern verschiebst du die Karte.",
|
||||
"regions.own": "diese Organisation",
|
||||
"regions.owner": "Besitzer",
|
||||
"regions.platform": "Plattform",
|
||||
@@ -1556,5 +1585,66 @@
|
||||
"weekday.3": "Mi",
|
||||
"weekday.4": "Do",
|
||||
"weekday.5": "Fr",
|
||||
"weekday.6": "Sa"
|
||||
"weekday.6": "Sa",
|
||||
"limits.subscribers_per_week": "Neue Abonnenten pro Woche",
|
||||
"error.subscriber_limit": "Die Statusseiten dieser Organisation haben ihr Limit von {{.Max}} neuen Abonnenten pro Woche erreicht.",
|
||||
"email.subscribe.subject": "Bestätige dein Abo für {{.Page}}",
|
||||
"email.subscribe.body": "Hallo,\n\njemand, hoffentlich du, möchte E-Mails zu Störungen auf der Statusseite {{.Page}} erhalten. Bestätige das hier:\n\n{{.Link}}\n\nDer Link ist {{.Hours}} Stunden gültig. Wenn du das nicht warst, ignoriere diese E-Mail: Du bekommst sonst nichts zugeschickt.",
|
||||
"email.subscriber.opened.subject": "[{{.Page}}] {{.Title}}: Störung",
|
||||
"email.subscriber.opened.body": "{{.Title}} ist seit {{.Time}} nicht erreichbar.\n\nAktueller Status: {{.Link}}",
|
||||
"email.subscriber.resolved.subject": "[{{.Page}}] {{.Title}}: behoben",
|
||||
"email.subscriber.resolved.body": "{{.Title}} funktioniert seit {{.Time}} wieder, nach {{.Duration}}.\n\nAktueller Status: {{.Link}}",
|
||||
"email.subscriber.update.subject": "[{{.Page}}] {{.Title}}: {{.Status}}",
|
||||
"email.subscriber.update.body": "{{.Status}}: {{.Message}}\n\nAktueller Status: {{.Link}}",
|
||||
"email.subscriber.footer": "\n\n--\nDu bekommst diese E-Mail, weil du {{.Page}} abonniert hast. Abmelden: {{.Unsubscribe}}",
|
||||
"page.subscribe.title": "Benachrichtigungen erhalten",
|
||||
"page.subscribe.intro": "Erhalte eine E-Mail, wenn eine Störung beginnt, sich ändert oder endet.",
|
||||
"page.subscribe.email": "E-Mail-Adresse",
|
||||
"page.subscribe.submit": "Abonnieren",
|
||||
"page.subscribe.privacy": "Deine Adresse wird nur für diese E-Mails verwendet. Jede E-Mail enthält einen Link zum Abmelden.",
|
||||
"page.subscribe.accept_both": "Ich akzeptiere die AGB und habe die Datenschutzerklärung gelesen:",
|
||||
"page.subscribe.accept_terms": "Ich akzeptiere die AGB:",
|
||||
"page.subscribe.accept_privacy": "Ich habe die Datenschutzerklärung gelesen:",
|
||||
"page.subscribe.accept_required": "Bitte stimme den Bedingungen zu, um zu abonnieren.",
|
||||
"page.subscribe.sent_title": "Schau in dein Postfach",
|
||||
"page.subscribe.sent": "Wenn die Adresse abonniert werden kann, ist ein Link zum Bestätigen unterwegs. Er ist 48 Stunden gültig.",
|
||||
"page.subscribe.invalid": "Das ist keine gültige E-Mail-Adresse.",
|
||||
"page.subscribe.limited": "Gerade zu viele Anfragen. Bitte versuche es später noch einmal.",
|
||||
"page.subscribe.failed": "Abonnieren ist gerade nicht möglich. Bitte versuche es später noch einmal.",
|
||||
"page.subscribe.confirm_title": "Abo bestätigen",
|
||||
"page.subscribe.confirm_intro": "Bestätige, dass du E-Mails zu Störungen auf {{.Page}} erhalten möchtest.",
|
||||
"page.subscribe.confirm_button": "Abo bestätigen",
|
||||
"page.subscribe.confirmed_title": "Abo bestätigt",
|
||||
"page.subscribe.confirmed": "{{.Email}} erhält jetzt E-Mails zu Störungen auf {{.Page}}.",
|
||||
"page.subscribe.link_invalid": "Dieser Link ist ungültig oder abgelaufen.",
|
||||
"page.unsubscribe.title": "Abmelden",
|
||||
"page.unsubscribe.intro": "Keine E-Mails mehr zu Störungen auf {{.Page}} erhalten?",
|
||||
"page.unsubscribe.button": "Abmelden",
|
||||
"page.unsubscribe.done_title": "Abgemeldet",
|
||||
"page.unsubscribe.done": "{{.Email}} erhält keine E-Mails mehr von {{.Page}}.",
|
||||
"page.back": "Zurück zur Statusseite",
|
||||
"page.feed": "RSS-Feed",
|
||||
"page.api": "API",
|
||||
"page.feed.description": "Störungen und geplante Wartungen von {{.Page}}",
|
||||
"page.feed.maintenance": "Geplante Wartung: {{.Title}}",
|
||||
"pages.subscriptions": "E-Mail-Abos",
|
||||
"pages.subscriptions_hint": "Besucher können Störungen per E-Mail abonnieren. Sie bestätigen zuerst ihre Adresse, und jede E-Mail enthält einen Link zum Abmelden.",
|
||||
"pages.subscriptions_no_mail": "Braucht einen Mailserver (UPTIME_SMTP_URL) auf der Plattform.",
|
||||
"pages.subscribers": "Abonnenten",
|
||||
"pages.subscribers_counts": "{{.Confirmed}} bestätigt · {{.Pending}} warten auf Bestätigung",
|
||||
"pages.subscribers_none": "Noch keine Abonnenten.",
|
||||
"pages.subscribers_more": "Die neuesten {{.Count}} werden angezeigt.",
|
||||
"pages.subscriber_pending": "unbestätigt",
|
||||
"pages.subscriber_remove": "Entfernen",
|
||||
"pages.subscribers_limit": "Neue Abos pro Woche für die Organisation: {{.Max}}",
|
||||
"pages.feeds": "Feed und API",
|
||||
"pages.feeds_hint": "Jede veröffentlichte Seite hat einen RSS-Feed und eine JSON-API zum Lesen, pro Besucher begrenzt:",
|
||||
"audit.action.statuspage.subscriber_delete": "Abonnent einer Statusseite entfernt",
|
||||
"page.not_found_title": "Seite nicht gefunden",
|
||||
"page.not_found": "Unter dieser Adresse gibt es keine Statusseite, oder sie ist nicht veröffentlicht.",
|
||||
"page.not_found_home": "Zur Hauptseite",
|
||||
"admin.statuspage_home": "Hauptseite der Statusseiten",
|
||||
"admin.statuspage_home_hint": "Wer die Statusseiten-Domain ohne Pfad oder eine Seite aufruft, die es nicht gibt, sieht eine Fehlerseite. Sie verlinkt diese Adresse, z. B. eure Website. Leer: kein Link.",
|
||||
"admin.statuspage_home_url": "Adresse der Hauptseite",
|
||||
"audit.action.platform.statuspage_home_update": "Hauptseite der Statusseiten geändert"
|
||||
}
|
||||
@@ -129,6 +129,7 @@
|
||||
"audit.action.platform.org_suspension": "Organization suspended or reinstated",
|
||||
"audit.action.platform.region_create": "Platform region created",
|
||||
"audit.action.platform.region_delete": "Platform region deleted",
|
||||
"audit.action.platform.region_update": "Platform region location changed",
|
||||
"audit.action.platform.status_page_delete": "Status page deleted by admin",
|
||||
"audit.action.platform.status_page_suspension": "Status page suspended or reinstated",
|
||||
"audit.action.platform.user_delete": "Account deleted by admin",
|
||||
@@ -136,6 +137,7 @@
|
||||
"audit.action.platform.user_suspension": "Account suspended or reinstated",
|
||||
"audit.action.region.create": "Region created",
|
||||
"audit.action.region.delete": "Region deleted",
|
||||
"audit.action.region.update": "Region location changed",
|
||||
"audit.action.role.create": "Role created",
|
||||
"audit.action.role.delete": "Role deleted",
|
||||
"audit.action.role.update": "Role changed",
|
||||
@@ -519,6 +521,7 @@
|
||||
"email.domain_missing.subject": "The DNS record of {{.Domain}} is gone",
|
||||
"email.domain_off.body": "The DNS record of {{.Domain}} has been missing for a week, so the status page {{.Page}} is no longer served there.\n\nRestore the record and verify the domain again:\n{{.Link}}",
|
||||
"email.domain_off.subject": "{{.Domain}} has been switched off",
|
||||
"email.monitor_link": "Open in UptimeSebi: {{.Link}}",
|
||||
"email.opened.body": "{{.Monitor}} ({{.Target}}) is down in all of its regions since {{.Since}}.\n\nLast errors:\n{{.Cause}}\n\nYou receive this because a notification channel of your organization is set up for this address.",
|
||||
"email.opened.subject": "[DOWN] {{.Monitor}}",
|
||||
"email.region_back.body": "Region {{.Region}} has an active checker again; it had none since {{.Since}}. Overdue checks run right away.\n\n{{.Link}}",
|
||||
@@ -571,6 +574,7 @@
|
||||
"error.invalid_credentials": "Wrong email or password.",
|
||||
"error.invalid_cursor": "This page link is invalid; start from the first page.",
|
||||
"error.invalid_domain": "One of the domains is not valid.",
|
||||
"error.consent_required": "Please accept the terms to subscribe.",
|
||||
"error.invalid_email": "Please enter a valid email address.",
|
||||
"error.invalid_expect_status": "Expected status codes must be codes like 200 or classes like 2xx.",
|
||||
"error.invalid_grace": "The grace period must be between 0 seconds and one day.",
|
||||
@@ -585,6 +589,7 @@
|
||||
"error.invalid_maintenance_time": "Check start, weekdays and last day.",
|
||||
"error.invalid_matchers": "Add 1 to 20 label matchers with valid label names and regular expressions.",
|
||||
"error.invalid_method": "Only GET and HEAD requests are supported.",
|
||||
"error.invalid_location": "Give latitude (−90 to 90) and longitude (−180 to 180), or neither.",
|
||||
"error.invalid_monitor": "One of the monitors does not exist or is listed twice.",
|
||||
"error.invalid_permissions": "Choose at least one permission.",
|
||||
"error.invalid_query": "Enter a PromQL query of at most 2000 characters.",
|
||||
@@ -995,6 +1000,9 @@
|
||||
"members.step_down_confirm": "Step down as owner? You keep working with the Admin role unless you have other roles.",
|
||||
"members.title": "Members",
|
||||
"members.unassign": "Remove role",
|
||||
"meta.app_card_subtitle": "Monitors, alerts and status pages, open source",
|
||||
"meta.app_card_title": "Uptime monitoring and status pages",
|
||||
"meta.app_description": "UptimeSebi watches websites, servers and services from several regions, alerts you on outages and runs public status pages. Open source.",
|
||||
"moderation.actions": "Suspend or delete …",
|
||||
"moderation.created": "Created",
|
||||
"moderation.delete_confirm_org": "Delete the organization {{.Name}} with all its monitors, results and status pages for good?",
|
||||
@@ -1122,6 +1130,7 @@
|
||||
"monitors.ping_intro": "Call this URL at the end of every successful run, with GET, HEAD or POST. Append /fail to report a failure; a POST body or ?msg= is stored as the message.",
|
||||
"monitors.ping_secret": "Keep the URL secret: anyone who knows it can report the job as healthy. Only members who may edit this monitor see it.",
|
||||
"monitors.ping_url": "Ping URL",
|
||||
"monitors.platform_regions_limit": "Up to {{.Max}} platform regions per monitor; your own regions do not count.",
|
||||
"monitors.prom_empty_ok": "No data is fine",
|
||||
"monitors.prom_hint": "Target is the Prometheus base URL, e.g. https://prometheus.example.com. Thanos, Mimir and VictoriaMetrics work as well. Use Authorization headers for protected servers.",
|
||||
"monitors.prom_mode": "Series",
|
||||
@@ -1138,6 +1147,7 @@
|
||||
"monitors.recent": "Recent checks",
|
||||
"monitors.regions": "Regions",
|
||||
"monitors.regions_hint": "Checked from a random checker in each selected region. Your own regions are listed first.",
|
||||
"monitors.regions_limit": "Up to {{.Max}} regions per monitor.",
|
||||
"monitors.results_title": "Check results",
|
||||
"monitors.search": "Search by name or target",
|
||||
"monitors.secret_unchanged": "unchanged",
|
||||
@@ -1251,6 +1261,7 @@
|
||||
"page.incidents": "Recent incidents",
|
||||
"page.maintenance_ongoing": "Maintenance in progress",
|
||||
"page.maintenance_upcoming": "Planned maintenance",
|
||||
"page.meta_description": "Current status of {{.Title}}: {{.Status}}. Incidents and planned maintenance at a glance.",
|
||||
"page.no_incidents": "No incidents in the last 14 days.",
|
||||
"page.stale": "Live updates are currently unavailable. This page shows the status as of {{.Time}}.",
|
||||
"page.status.degraded": "Some systems are experiencing problems",
|
||||
@@ -1259,6 +1270,13 @@
|
||||
"page.status.outage": "Major outage",
|
||||
"page.status.unknown": "Status currently unavailable",
|
||||
"page.today": "Today",
|
||||
"page.pages": "Page {{.Page}} of {{.Pages}}",
|
||||
"page.search": "Search components",
|
||||
"page.search_submit": "Search",
|
||||
"page.search_clear": "Show all",
|
||||
"page.search_none": "No component matches the search.",
|
||||
"page.filter_problems": "Outages only ({{.Count}})",
|
||||
"page.filter_no_problems": "No component has an outage.",
|
||||
"page.updated": "Updated {{.Time}}",
|
||||
"pager.earlier": "Earlier",
|
||||
"pager.first": "To the start",
|
||||
@@ -1308,6 +1326,7 @@
|
||||
"pages.monitors_filter": "Filter monitors",
|
||||
"pages.monitors_all": "Add all",
|
||||
"pages.monitors_none": "Remove all",
|
||||
"pages.monitors_range": "{from}–{to} of {total}",
|
||||
"pages.no_group": "No group",
|
||||
"pages.open": "Open",
|
||||
"pages.own_servers": "Your organization's own status page servers serve its pages; the platform's do not. Open them at the address of your servers or connect a custom domain pointing at them.",
|
||||
@@ -1351,6 +1370,16 @@
|
||||
"one": "{{.Count}} live",
|
||||
"other": "{{.Count}} live"
|
||||
},
|
||||
"regions.latitude": "Latitude",
|
||||
"regions.location": "Location",
|
||||
"regions.location_clear": "Remove location",
|
||||
"regions.location_for": "Location of {{.Name}}: click the map or enter the coordinates.",
|
||||
"regions.location_pick_hint": "Click the map to fill in the coordinates of a new region, or of the region whose location you are setting.",
|
||||
"regions.location_set": "Set",
|
||||
"regions.longitude": "Longitude",
|
||||
"regions.map_ctrl_key": "Ctrl",
|
||||
"regions.map_scroll_hint": "Use {{.Key}} + scroll to zoom the map.",
|
||||
"regions.map_touch_hint": "Use two fingers to move the map.",
|
||||
"regions.own": "this organization",
|
||||
"regions.owner": "Owner",
|
||||
"regions.platform": "platform",
|
||||
@@ -1556,5 +1585,66 @@
|
||||
"weekday.3": "Wed",
|
||||
"weekday.4": "Thu",
|
||||
"weekday.5": "Fri",
|
||||
"weekday.6": "Sat"
|
||||
"weekday.6": "Sat",
|
||||
"limits.subscribers_per_week": "New subscribers per week",
|
||||
"error.subscriber_limit": "The status pages of this organization have reached their limit of {{.Max}} new subscribers per week.",
|
||||
"email.subscribe.subject": "Confirm your subscription to {{.Page}}",
|
||||
"email.subscribe.body": "Hello,\n\nsomeone, hopefully you, asked to receive emails about incidents on the status page {{.Page}}. Confirm it here:\n\n{{.Link}}\n\nThe link is valid for {{.Hours}} hours. If you did not ask for this, ignore this email: nothing else will be sent to you.",
|
||||
"email.subscriber.opened.subject": "[{{.Page}}] {{.Title}}: outage",
|
||||
"email.subscriber.opened.body": "{{.Title}} has been unavailable since {{.Time}}.\n\nCurrent status: {{.Link}}",
|
||||
"email.subscriber.resolved.subject": "[{{.Page}}] {{.Title}}: resolved",
|
||||
"email.subscriber.resolved.body": "{{.Title}} is working again since {{.Time}}, after {{.Duration}}.\n\nCurrent status: {{.Link}}",
|
||||
"email.subscriber.update.subject": "[{{.Page}}] {{.Title}}: {{.Status}}",
|
||||
"email.subscriber.update.body": "{{.Status}}: {{.Message}}\n\nCurrent status: {{.Link}}",
|
||||
"email.subscriber.footer": "\n\n--\nYou receive this email because you subscribed to {{.Page}}. Unsubscribe: {{.Unsubscribe}}",
|
||||
"page.subscribe.title": "Get notified",
|
||||
"page.subscribe.intro": "Receive an email when an incident starts, changes or ends.",
|
||||
"page.subscribe.email": "Email address",
|
||||
"page.subscribe.submit": "Subscribe",
|
||||
"page.subscribe.privacy": "Your address is used for these emails only. Every email contains a link to unsubscribe.",
|
||||
"page.subscribe.accept_both": "I accept the terms of service and have read the privacy policy:",
|
||||
"page.subscribe.accept_terms": "I accept the terms of service:",
|
||||
"page.subscribe.accept_privacy": "I have read the privacy policy:",
|
||||
"page.subscribe.accept_required": "Please accept the terms to subscribe.",
|
||||
"page.subscribe.sent_title": "Check your inbox",
|
||||
"page.subscribe.sent": "If the address can be subscribed, a link to confirm it is on its way. The link is valid for 48 hours.",
|
||||
"page.subscribe.invalid": "That is not a valid email address.",
|
||||
"page.subscribe.limited": "Too many requests right now. Please try again later.",
|
||||
"page.subscribe.failed": "Subscribing is not possible right now. Please try again later.",
|
||||
"page.subscribe.confirm_title": "Confirm subscription",
|
||||
"page.subscribe.confirm_intro": "Confirm that you want to receive emails about incidents on {{.Page}}.",
|
||||
"page.subscribe.confirm_button": "Confirm subscription",
|
||||
"page.subscribe.confirmed_title": "Subscription confirmed",
|
||||
"page.subscribe.confirmed": "{{.Email}} now receives emails about incidents on {{.Page}}.",
|
||||
"page.subscribe.link_invalid": "This link is invalid or has expired.",
|
||||
"page.unsubscribe.title": "Unsubscribe",
|
||||
"page.unsubscribe.intro": "Stop receiving emails about incidents on {{.Page}}?",
|
||||
"page.unsubscribe.button": "Unsubscribe",
|
||||
"page.unsubscribe.done_title": "Unsubscribed",
|
||||
"page.unsubscribe.done": "{{.Email}} no longer receives emails from {{.Page}}.",
|
||||
"page.back": "Back to the status page",
|
||||
"page.feed": "RSS feed",
|
||||
"page.api": "API",
|
||||
"page.feed.description": "Incidents and planned maintenance of {{.Page}}",
|
||||
"page.feed.maintenance": "Planned maintenance: {{.Title}}",
|
||||
"pages.subscriptions": "Email subscriptions",
|
||||
"pages.subscriptions_hint": "Visitors can subscribe to incidents by email. They confirm their address first, and every email has a link to unsubscribe.",
|
||||
"pages.subscriptions_no_mail": "Needs a mail server (UPTIME_SMTP_URL) on the platform.",
|
||||
"pages.subscribers": "Subscribers",
|
||||
"pages.subscribers_counts": "{{.Confirmed}} confirmed · {{.Pending}} waiting for confirmation",
|
||||
"pages.subscribers_none": "No subscribers yet.",
|
||||
"pages.subscribers_more": "Showing the newest {{.Count}}.",
|
||||
"pages.subscriber_pending": "unconfirmed",
|
||||
"pages.subscriber_remove": "Remove",
|
||||
"pages.subscribers_limit": "New subscriptions per week for the organization: {{.Max}}",
|
||||
"pages.feeds": "Feed and API",
|
||||
"pages.feeds_hint": "Every published page has an RSS feed and a read-only JSON API, rate limited per visitor:",
|
||||
"audit.action.statuspage.subscriber_delete": "Status page subscriber removed",
|
||||
"page.not_found_title": "Page not found",
|
||||
"page.not_found": "There is no status page at this address, or it is not published.",
|
||||
"page.not_found_home": "Go to the home page",
|
||||
"admin.statuspage_home": "Status page home",
|
||||
"admin.statuspage_home_hint": "Visitors of the bare status page domain and of pages that do not exist see an error page. It links this address, e.g. your website. Empty: no link.",
|
||||
"admin.statuspage_home_url": "Home page URL",
|
||||
"audit.action.platform.statuspage_home_update": "Status page home changed"
|
||||
}
|
||||
@@ -0,0 +1,224 @@
|
||||
// Package metrics holds the Prometheus metrics of the API for operators:
|
||||
// requests, the checker pipeline, notifications, background jobs and the
|
||||
// connection pools. Every Metrics has a registry of its own, so tests and
|
||||
// replicas never share state.
|
||||
package metrics
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"strconv"
|
||||
"time"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/prometheus/client_golang/prometheus"
|
||||
"github.com/prometheus/client_golang/prometheus/collectors"
|
||||
"github.com/prometheus/client_golang/prometheus/promhttp"
|
||||
|
||||
"git.zb-server.de/ZB-Server/uptimesebi/internal/buildinfo"
|
||||
)
|
||||
|
||||
const namespace = "uptimesebi"
|
||||
|
||||
// Metrics are the instruments the API updates as it works.
|
||||
type Metrics struct {
|
||||
reg *prometheus.Registry
|
||||
|
||||
requests *prometheus.CounterVec
|
||||
duration *prometheus.HistogramVec
|
||||
inFlight prometheus.Gauge
|
||||
dispatched prometheus.Counter
|
||||
stale prometheus.Counter
|
||||
results *prometheus.CounterVec
|
||||
rejected *prometheus.CounterVec
|
||||
resultDelay prometheus.Histogram
|
||||
notifications *prometheus.CounterVec
|
||||
notifyDuration *prometheus.HistogramVec
|
||||
subscriberMail *prometheus.CounterVec
|
||||
incidents *prometheus.CounterVec
|
||||
jobRuns *prometheus.CounterVec
|
||||
jobDuration *prometheus.HistogramVec
|
||||
jobSuccess *prometheus.GaugeVec
|
||||
}
|
||||
|
||||
// New returns Metrics with the Go runtime, process and build metrics
|
||||
// registered. edition labels the build info.
|
||||
func New(edition string) *Metrics {
|
||||
reg := prometheus.NewRegistry()
|
||||
m := &Metrics{
|
||||
reg: reg,
|
||||
requests: prometheus.NewCounterVec(prometheus.CounterOpts{
|
||||
Namespace: namespace, Name: "http_requests_total",
|
||||
Help: "HTTP requests by method, route and status code. Requests no route matches have the route \"unmatched\".",
|
||||
}, []string{"method", "route", "code"}),
|
||||
duration: prometheus.NewHistogramVec(prometheus.HistogramOpts{
|
||||
Namespace: namespace, Name: "http_request_duration_seconds",
|
||||
Help: "Time to answer HTTP requests, without long polls and event streams.",
|
||||
Buckets: []float64{0.005, 0.01, 0.025, 0.05, 0.1, 0.25, 0.5, 1, 2.5, 5, 10},
|
||||
}, []string{"method", "route"}),
|
||||
inFlight: prometheus.NewGauge(prometheus.GaugeOpts{
|
||||
Namespace: namespace, Name: "http_requests_in_flight",
|
||||
Help: "HTTP requests being answered, long polls and event streams included.",
|
||||
}),
|
||||
dispatched: prometheus.NewCounter(prometheus.CounterOpts{
|
||||
Namespace: namespace, Name: "checks_dispatched_total",
|
||||
Help: "Checks this instance moved from the schedule to the checkers' queues.",
|
||||
}),
|
||||
stale: prometheus.NewCounter(prometheus.CounterOpts{
|
||||
Namespace: namespace, Name: "checks_stale_total",
|
||||
Help: "Queued checks dropped because they waited longer than two intervals; a newer run of the monitor was queued by then.",
|
||||
}),
|
||||
results: prometheus.NewCounterVec(prometheus.CounterOpts{
|
||||
Namespace: namespace, Name: "check_results_total",
|
||||
Help: "Check results stored, by region (\"own\" for organizations' own checkers) and outcome.",
|
||||
}, []string{"region", "ok"}),
|
||||
rejected: prometheus.NewCounterVec(prometheus.CounterOpts{
|
||||
Namespace: namespace, Name: "check_results_rejected_total",
|
||||
Help: "Check results not stored: duplicate (a retried report), unknown_monitor (not checked in the region) or bad_time (timestamp out of range).",
|
||||
}, []string{"reason"}),
|
||||
resultDelay: prometheus.NewHistogram(prometheus.HistogramOpts{
|
||||
Namespace: namespace, Name: "check_result_delay_seconds",
|
||||
Help: "Time from the start of a check to its result reaching the API.",
|
||||
Buckets: []float64{0.5, 1, 2.5, 5, 10, 30, 60, 120, 300},
|
||||
}),
|
||||
notifications: prometheus.NewCounterVec(prometheus.CounterOpts{
|
||||
Namespace: namespace, Name: "notifications_total",
|
||||
Help: "Notification delivery attempts by channel type and result.",
|
||||
}, []string{"channel_type", "result"}),
|
||||
notifyDuration: prometheus.NewHistogramVec(prometheus.HistogramOpts{
|
||||
Namespace: namespace, Name: "notification_send_duration_seconds",
|
||||
Help: "Time to deliver a notification, by channel type.",
|
||||
Buckets: []float64{0.1, 0.25, 0.5, 1, 2.5, 5, 10, 30},
|
||||
}, []string{"channel_type"}),
|
||||
subscriberMail: prometheus.NewCounterVec(prometheus.CounterOpts{
|
||||
Namespace: namespace, Name: "subscriber_notifications_total",
|
||||
Help: "Mails to status page subscribers by result.",
|
||||
}, []string{"result"}),
|
||||
incidents: prometheus.NewCounterVec(prometheus.CounterOpts{
|
||||
Namespace: namespace, Name: "incidents_total",
|
||||
Help: "Incidents this instance opened or resolved.",
|
||||
}, []string{"event"}),
|
||||
jobRuns: prometheus.NewCounterVec(prometheus.CounterOpts{
|
||||
Namespace: namespace, Name: "job_runs_total",
|
||||
Help: "Runs of background jobs by result, ok or failed.",
|
||||
}, []string{"job", "result"}),
|
||||
jobDuration: prometheus.NewHistogramVec(prometheus.HistogramOpts{
|
||||
Namespace: namespace, Name: "job_duration_seconds",
|
||||
Help: "Duration of background job runs.",
|
||||
Buckets: []float64{0.01, 0.05, 0.1, 0.5, 1, 5, 10, 30, 60, 300},
|
||||
}, []string{"job"}),
|
||||
jobSuccess: prometheus.NewGaugeVec(prometheus.GaugeOpts{
|
||||
Namespace: namespace, Name: "job_last_success_timestamp_seconds",
|
||||
Help: "Unix time of the last successful run of a background job on this instance.",
|
||||
}, []string{"job"}),
|
||||
}
|
||||
build := prometheus.NewGaugeVec(prometheus.GaugeOpts{
|
||||
Namespace: namespace, Name: "build_info",
|
||||
Help: "Always 1; the labels name the running release.",
|
||||
}, []string{"version", "commit", "edition"})
|
||||
build.WithLabelValues(buildinfo.Version, buildinfo.Commit, edition).Set(1)
|
||||
reg.MustRegister(
|
||||
collectors.NewGoCollector(),
|
||||
collectors.NewProcessCollector(collectors.ProcessCollectorOpts{}),
|
||||
build,
|
||||
m.requests, m.duration, m.inFlight,
|
||||
m.dispatched, m.stale, m.results, m.rejected, m.resultDelay,
|
||||
m.notifications, m.notifyDuration, m.subscriberMail,
|
||||
m.incidents,
|
||||
m.jobRuns, m.jobDuration, m.jobSuccess,
|
||||
)
|
||||
return m
|
||||
}
|
||||
|
||||
// Register adds collectors, such as those reading the database when
|
||||
// scraped.
|
||||
func (m *Metrics) Register(cs ...prometheus.Collector) { m.reg.MustRegister(cs...) }
|
||||
|
||||
// Handler serves the metrics in the Prometheus text format.
|
||||
func (m *Metrics) Handler() http.Handler {
|
||||
return promhttp.HandlerFor(m.reg, promhttp.HandlerOpts{Registry: m.reg})
|
||||
}
|
||||
|
||||
// Gatherer exposes the registry to tests.
|
||||
func (m *Metrics) Gatherer() prometheus.Gatherer { return m.reg }
|
||||
|
||||
// HTTP counts and times the requests of r. Routes listed in streaming are
|
||||
// counted but not timed, since they stay open on purpose.
|
||||
func (m *Metrics) HTTP(streaming ...string) gin.HandlerFunc {
|
||||
skip := map[string]bool{}
|
||||
for _, r := range streaming {
|
||||
skip[r] = true
|
||||
}
|
||||
return func(c *gin.Context) {
|
||||
start := time.Now()
|
||||
m.inFlight.Inc()
|
||||
defer m.inFlight.Dec()
|
||||
c.Next()
|
||||
route := c.FullPath()
|
||||
if route == "" {
|
||||
route = "unmatched"
|
||||
}
|
||||
m.requests.WithLabelValues(c.Request.Method, route, strconv.Itoa(c.Writer.Status())).Inc()
|
||||
if !skip[route] {
|
||||
m.duration.WithLabelValues(c.Request.Method, route).Observe(time.Since(start).Seconds())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Dispatched counts checks moved to the checkers' queues.
|
||||
func (m *Metrics) Dispatched(n int) { m.dispatched.Add(float64(n)) }
|
||||
|
||||
// Stale counts n queued checks dropped as out of date.
|
||||
func (m *Metrics) Stale(n int) {
|
||||
if n > 0 {
|
||||
m.stale.Add(float64(n))
|
||||
}
|
||||
}
|
||||
|
||||
// Result counts a stored check result and how long it took to arrive.
|
||||
func (m *Metrics) Result(region string, ok bool, delay time.Duration) {
|
||||
m.results.WithLabelValues(region, strconv.FormatBool(ok)).Inc()
|
||||
m.resultDelay.Observe(max(delay, 0).Seconds())
|
||||
}
|
||||
|
||||
// Rejected counts n check results not stored for reason.
|
||||
func (m *Metrics) Rejected(reason string, n int) {
|
||||
if n > 0 {
|
||||
m.rejected.WithLabelValues(reason).Add(float64(n))
|
||||
}
|
||||
}
|
||||
|
||||
// Notification counts a delivery attempt to a channel of type typ.
|
||||
func (m *Metrics) Notification(typ string, err error, took time.Duration) {
|
||||
m.notifications.WithLabelValues(typ, result(err)).Inc()
|
||||
m.notifyDuration.WithLabelValues(typ).Observe(took.Seconds())
|
||||
}
|
||||
|
||||
// SubscriberMail counts a mail to a status page subscriber.
|
||||
func (m *Metrics) SubscriberMail(err error) { m.subscriberMail.WithLabelValues(result(err)).Inc() }
|
||||
|
||||
// Incident counts an incident event, "opened" or "resolved".
|
||||
func (m *Metrics) Incident(event string) { m.incidents.WithLabelValues(event).Inc() }
|
||||
|
||||
// Job runs one round of the background job name and records its outcome.
|
||||
// It returns run's error.
|
||||
func (m *Metrics) Job(name string, run func() error) error {
|
||||
start := time.Now()
|
||||
err := run()
|
||||
outcome := "ok"
|
||||
if err != nil {
|
||||
outcome = "failed"
|
||||
}
|
||||
m.jobRuns.WithLabelValues(name, outcome).Inc()
|
||||
m.jobDuration.WithLabelValues(name).Observe(time.Since(start).Seconds())
|
||||
if err == nil {
|
||||
m.jobSuccess.WithLabelValues(name).SetToCurrentTime()
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
func result(err error) string {
|
||||
if err != nil {
|
||||
return "failed"
|
||||
}
|
||||
return "sent"
|
||||
}
|
||||
@@ -0,0 +1,137 @@
|
||||
package metrics
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
"github.com/prometheus/client_golang/prometheus"
|
||||
"github.com/prometheus/client_golang/prometheus/testutil"
|
||||
"github.com/redis/go-redis/v9"
|
||||
)
|
||||
|
||||
func TestHTTPCountsRoutesAndTimesShortRequests(t *testing.T) {
|
||||
gin.SetMode(gin.TestMode)
|
||||
m := New("selfhosted")
|
||||
r := gin.New()
|
||||
r.Use(m.HTTP("/stream"))
|
||||
r.GET("/items/:id", func(c *gin.Context) { c.Status(http.StatusTeapot) })
|
||||
r.GET("/stream", func(c *gin.Context) { c.Status(http.StatusOK) })
|
||||
for _, path := range []string{"/items/1", "/items/2", "/stream", "/nowhere"} {
|
||||
r.ServeHTTP(httptest.NewRecorder(), httptest.NewRequest(http.MethodGet, path, nil))
|
||||
}
|
||||
|
||||
if got := testutil.ToFloat64(m.requests.WithLabelValues("GET", "/items/:id", "418")); got != 2 {
|
||||
t.Errorf("requests for the route = %v, want 2", got)
|
||||
}
|
||||
if got := testutil.ToFloat64(m.requests.WithLabelValues("GET", "unmatched", "404")); got != 1 {
|
||||
t.Errorf("unmatched requests = %v, want 1", got)
|
||||
}
|
||||
// The stream is counted, not timed.
|
||||
if got := testutil.CollectAndCount(m.duration); got != 2 {
|
||||
t.Errorf("timed series = %d, want 2: the route and unmatched paths, not the stream", got)
|
||||
}
|
||||
if got := testutil.ToFloat64(m.inFlight); got != 0 {
|
||||
t.Errorf("in flight after the requests = %v, want 0", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestJobRecordsOutcome(t *testing.T) {
|
||||
m := New("cloud")
|
||||
boom := errors.New("boom")
|
||||
if err := m.Job("housekeeping", func() error { return nil }); err != nil {
|
||||
t.Fatalf("Job() = %v, want nil", err)
|
||||
}
|
||||
if err := m.Job("housekeeping", func() error { return boom }); !errors.Is(err, boom) {
|
||||
t.Fatalf("Job() = %v, want the run's error", err)
|
||||
}
|
||||
if got := testutil.ToFloat64(m.jobRuns.WithLabelValues("housekeeping", "ok")); got != 1 {
|
||||
t.Errorf("ok runs = %v, want 1", got)
|
||||
}
|
||||
if got := testutil.ToFloat64(m.jobRuns.WithLabelValues("housekeeping", "failed")); got != 1 {
|
||||
t.Errorf("failed runs = %v, want 1", got)
|
||||
}
|
||||
if got := testutil.ToFloat64(m.jobSuccess.WithLabelValues("housekeeping")); got < float64(time.Now().Add(-time.Minute).Unix()) {
|
||||
t.Errorf("last success = %v, want about now", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCountersAndHandler(t *testing.T) {
|
||||
m := New("cloud")
|
||||
m.Dispatched(3)
|
||||
m.Stale(2)
|
||||
m.Stale(0)
|
||||
m.Result("fsn", true, 2*time.Second)
|
||||
m.Result("fsn", false, -time.Second)
|
||||
m.Rejected("duplicate", 2)
|
||||
m.Rejected("bad_time", 0)
|
||||
m.Notification("slack", nil, time.Second)
|
||||
m.Notification("slack", errors.New("x"), time.Second)
|
||||
m.SubscriberMail(nil)
|
||||
m.Incident("opened")
|
||||
|
||||
for name, c := range map[string]struct {
|
||||
got, want float64
|
||||
}{
|
||||
"dispatched": {testutil.ToFloat64(m.dispatched), 3},
|
||||
"stale": {testutil.ToFloat64(m.stale), 2},
|
||||
"ok results": {testutil.ToFloat64(m.results.WithLabelValues("fsn", "true")), 1},
|
||||
"failed results": {testutil.ToFloat64(m.results.WithLabelValues("fsn", "false")), 1},
|
||||
"duplicates": {testutil.ToFloat64(m.rejected.WithLabelValues("duplicate")), 2},
|
||||
"sent": {testutil.ToFloat64(m.notifications.WithLabelValues("slack", "sent")), 1},
|
||||
"failed": {testutil.ToFloat64(m.notifications.WithLabelValues("slack", "failed")), 1},
|
||||
"subscriber": {testutil.ToFloat64(m.subscriberMail.WithLabelValues("sent")), 1},
|
||||
"incidents": {testutil.ToFloat64(m.incidents.WithLabelValues("opened")), 1},
|
||||
} {
|
||||
if c.got != c.want {
|
||||
t.Errorf("%s = %v, want %v", name, c.got, c.want)
|
||||
}
|
||||
}
|
||||
if got := testutil.CollectAndCount(m.rejected); got != 1 {
|
||||
t.Errorf("rejection series = %d, want 1: zero rejections add none", got)
|
||||
}
|
||||
|
||||
rec := httptest.NewRecorder()
|
||||
m.Handler().ServeHTTP(rec, httptest.NewRequest(http.MethodGet, "/metrics", nil))
|
||||
body, _ := io.ReadAll(rec.Body)
|
||||
for _, want := range []string{`uptimesebi_build_info{commit="none",edition="cloud",version="dev"} 1`, "go_goroutines", "uptimesebi_checks_dispatched_total 3"} {
|
||||
if !strings.Contains(string(body), want) {
|
||||
t.Errorf("metrics lack %q", want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestPoolCollectors(t *testing.T) {
|
||||
// Neither pool connects before it is used.
|
||||
pool, err := pgxpool.New(context.Background(), "postgres://u@127.0.0.1:1/db")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer pool.Close()
|
||||
rdb := redis.NewClient(&redis.Options{Addr: "127.0.0.1:1"})
|
||||
defer func() { _ = rdb.Close() }()
|
||||
|
||||
m := New("cloud")
|
||||
m.Register(DBPool(pool), RedisPool(rdb))
|
||||
for _, c := range []prometheus.Collector{DBPool(pool), RedisPool(rdb)} {
|
||||
if problems, err := testutil.CollectAndLint(c); err != nil || len(problems) > 0 {
|
||||
t.Errorf("pool metrics lint: %v %v", problems, err)
|
||||
}
|
||||
}
|
||||
if got := testutil.CollectAndCount(DBPool(pool)); got != 7 {
|
||||
t.Errorf("DB pool series = %d, want 7", got)
|
||||
}
|
||||
if got := testutil.CollectAndCount(RedisPool(rdb)); got != 6 {
|
||||
t.Errorf("Redis pool series = %d, want 6", got)
|
||||
}
|
||||
if _, err := m.Gatherer().Gather(); err != nil {
|
||||
t.Errorf("Gather() = %v", err)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,81 @@
|
||||
package metrics
|
||||
|
||||
import (
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
"github.com/prometheus/client_golang/prometheus"
|
||||
"github.com/redis/go-redis/v9"
|
||||
)
|
||||
|
||||
// DBPool reports the state of a Postgres connection pool when scraped.
|
||||
func DBPool(pool *pgxpool.Pool) prometheus.Collector { return dbPool{pool} }
|
||||
|
||||
type dbPool struct{ pool *pgxpool.Pool }
|
||||
|
||||
var (
|
||||
dbConns = prometheus.NewDesc(namespace+"_db_pool_connections",
|
||||
"Connections of the Postgres pool by state.", []string{"state"}, nil)
|
||||
dbMax = prometheus.NewDesc(namespace+"_db_pool_max_connections",
|
||||
"Size limit of the Postgres pool.", nil, nil)
|
||||
dbAcquires = prometheus.NewDesc(namespace+"_db_pool_acquires_total",
|
||||
"Connections taken from the Postgres pool.", nil, nil)
|
||||
dbEmptyAcquires = prometheus.NewDesc(namespace+"_db_pool_empty_acquires_total",
|
||||
"Acquires that had to wait for or open a connection because none was idle.", nil, nil)
|
||||
dbAcquireWait = prometheus.NewDesc(namespace+"_db_pool_acquire_seconds_total",
|
||||
"Total time spent acquiring Postgres connections.", nil, nil)
|
||||
)
|
||||
|
||||
// Describe implements prometheus.Collector.
|
||||
func (dbPool) Describe(ch chan<- *prometheus.Desc) {
|
||||
for _, d := range []*prometheus.Desc{dbConns, dbMax, dbAcquires, dbEmptyAcquires, dbAcquireWait} {
|
||||
ch <- d
|
||||
}
|
||||
}
|
||||
|
||||
// Collect implements prometheus.Collector.
|
||||
func (p dbPool) Collect(ch chan<- prometheus.Metric) {
|
||||
s := p.pool.Stat()
|
||||
ch <- prometheus.MustNewConstMetric(dbConns, prometheus.GaugeValue, float64(s.AcquiredConns()), "acquired")
|
||||
ch <- prometheus.MustNewConstMetric(dbConns, prometheus.GaugeValue, float64(s.IdleConns()), "idle")
|
||||
ch <- prometheus.MustNewConstMetric(dbConns, prometheus.GaugeValue, float64(s.ConstructingConns()), "constructing")
|
||||
ch <- prometheus.MustNewConstMetric(dbMax, prometheus.GaugeValue, float64(s.MaxConns()))
|
||||
ch <- prometheus.MustNewConstMetric(dbAcquires, prometheus.CounterValue, float64(s.AcquireCount()))
|
||||
ch <- prometheus.MustNewConstMetric(dbEmptyAcquires, prometheus.CounterValue, float64(s.EmptyAcquireCount()))
|
||||
ch <- prometheus.MustNewConstMetric(dbAcquireWait, prometheus.CounterValue, s.AcquireDuration().Seconds())
|
||||
}
|
||||
|
||||
// RedisPool reports the state of a Redis client's connection pool when
|
||||
// scraped.
|
||||
func RedisPool(rdb redis.UniversalClient) prometheus.Collector { return redisPool{rdb} }
|
||||
|
||||
type redisPool struct{ rdb redis.UniversalClient }
|
||||
|
||||
var (
|
||||
redisConns = prometheus.NewDesc(namespace+"_redis_pool_connections",
|
||||
"Connections of the Redis pool by state.", []string{"state"}, nil)
|
||||
redisHits = prometheus.NewDesc(namespace+"_redis_pool_hits_total",
|
||||
"Times an idle Redis connection was reused.", nil, nil)
|
||||
redisMisses = prometheus.NewDesc(namespace+"_redis_pool_misses_total",
|
||||
"Times no idle Redis connection was available.", nil, nil)
|
||||
redisTimeouts = prometheus.NewDesc(namespace+"_redis_pool_timeouts_total",
|
||||
"Times waiting for a Redis connection timed out.", nil, nil)
|
||||
redisStale = prometheus.NewDesc(namespace+"_redis_pool_stale_total",
|
||||
"Stale Redis connections the pool closed.", nil, nil)
|
||||
)
|
||||
|
||||
// Describe implements prometheus.Collector.
|
||||
func (redisPool) Describe(ch chan<- *prometheus.Desc) {
|
||||
for _, d := range []*prometheus.Desc{redisConns, redisHits, redisMisses, redisTimeouts, redisStale} {
|
||||
ch <- d
|
||||
}
|
||||
}
|
||||
|
||||
// Collect implements prometheus.Collector.
|
||||
func (p redisPool) Collect(ch chan<- prometheus.Metric) {
|
||||
s := p.rdb.PoolStats()
|
||||
ch <- prometheus.MustNewConstMetric(redisConns, prometheus.GaugeValue, float64(s.TotalConns), "total")
|
||||
ch <- prometheus.MustNewConstMetric(redisConns, prometheus.GaugeValue, float64(s.IdleConns), "idle")
|
||||
ch <- prometheus.MustNewConstMetric(redisHits, prometheus.CounterValue, float64(s.Hits))
|
||||
ch <- prometheus.MustNewConstMetric(redisMisses, prometheus.CounterValue, float64(s.Misses))
|
||||
ch <- prometheus.MustNewConstMetric(redisTimeouts, prometheus.CounterValue, float64(s.Timeouts))
|
||||
ch <- prometheus.MustNewConstMetric(redisStale, prometheus.CounterValue, float64(s.StaleConns))
|
||||
}
|
||||
@@ -0,0 +1,68 @@
|
||||
-- +goose Up
|
||||
-- Visitors of a status page can subscribe to its incidents by email once
|
||||
-- the organization allows it on the page.
|
||||
ALTER TABLE status_pages ADD COLUMN subscriptions boolean NOT NULL DEFAULT false;
|
||||
|
||||
-- How many subscriptions the pages of the organization may gain in seven
|
||||
-- days; NULL follows the platform default, 0 means unlimited.
|
||||
ALTER TABLE orgs ADD COLUMN limit_subscribers_per_week integer CHECK (limit_subscribers_per_week >= 0);
|
||||
|
||||
CREATE TABLE status_page_subscribers (
|
||||
id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||
org_id uuid NOT NULL,
|
||||
page_id uuid NOT NULL,
|
||||
email citext NOT NULL CHECK (length(email) BETWEEN 3 AND 254),
|
||||
-- Language of the mails, as the visitor's browser asked for it.
|
||||
locale text NOT NULL DEFAULT 'en',
|
||||
-- Where the subscriber saw the page, for the links in mails when the
|
||||
-- platform does not know where the page is served.
|
||||
page_url text NOT NULL DEFAULT '',
|
||||
created_at timestamptz NOT NULL DEFAULT now(),
|
||||
-- Set once the address confirmed the subscription; until then nothing
|
||||
-- is sent to it but the confirmation.
|
||||
confirmed_at timestamptz,
|
||||
UNIQUE (page_id, email),
|
||||
FOREIGN KEY (page_id, org_id) REFERENCES status_pages (id, org_id) ON DELETE CASCADE
|
||||
);
|
||||
|
||||
-- Counts the subscriptions of the last days for the weekly limit.
|
||||
CREATE INDEX status_page_subscribers_org_idx ON status_page_subscribers (org_id, created_at);
|
||||
|
||||
-- Outbox: a row per subscriber and incident event.
|
||||
CREATE TABLE subscriber_notifications (
|
||||
id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||
org_id uuid NOT NULL REFERENCES orgs (id) ON DELETE CASCADE,
|
||||
subscriber_id uuid NOT NULL REFERENCES status_page_subscribers (id) ON DELETE CASCADE,
|
||||
incident_id uuid NOT NULL REFERENCES incidents (id) ON DELETE CASCADE,
|
||||
-- The public update announced, for event 'update'.
|
||||
update_id uuid REFERENCES incident_updates (id) ON DELETE CASCADE,
|
||||
event text NOT NULL CHECK (event IN ('opened', 'resolved', 'update')),
|
||||
status text NOT NULL DEFAULT 'pending' CHECK (status IN ('pending', 'sent', 'failed')),
|
||||
attempts integer NOT NULL DEFAULT 0,
|
||||
next_attempt_at timestamptz NOT NULL DEFAULT now(),
|
||||
last_error text,
|
||||
created_at timestamptz NOT NULL DEFAULT now(),
|
||||
sent_at timestamptz
|
||||
);
|
||||
|
||||
CREATE UNIQUE INDEX subscriber_notifications_once_idx
|
||||
ON subscriber_notifications (subscriber_id, incident_id, event, coalesce(update_id, '00000000-0000-0000-0000-000000000000'));
|
||||
CREATE INDEX subscriber_notifications_due_idx ON subscriber_notifications (next_attempt_at) WHERE status = 'pending';
|
||||
|
||||
ALTER TABLE status_page_subscribers ENABLE ROW LEVEL SECURITY;
|
||||
ALTER TABLE status_page_subscribers FORCE ROW LEVEL SECURITY;
|
||||
CREATE POLICY status_page_subscribers_tenant ON status_page_subscribers FOR ALL
|
||||
USING (app_scope_system() OR org_id = app_org_id())
|
||||
WITH CHECK (app_scope_system() OR org_id = app_org_id());
|
||||
|
||||
ALTER TABLE subscriber_notifications ENABLE ROW LEVEL SECURITY;
|
||||
ALTER TABLE subscriber_notifications FORCE ROW LEVEL SECURITY;
|
||||
CREATE POLICY subscriber_notifications_tenant ON subscriber_notifications FOR ALL
|
||||
USING (app_scope_system() OR org_id = app_org_id())
|
||||
WITH CHECK (app_scope_system() OR org_id = app_org_id());
|
||||
|
||||
-- +goose Down
|
||||
DROP TABLE subscriber_notifications;
|
||||
DROP TABLE status_page_subscribers;
|
||||
ALTER TABLE orgs DROP COLUMN limit_subscribers_per_week;
|
||||
ALTER TABLE status_pages DROP COLUMN subscriptions;
|
||||
@@ -0,0 +1,72 @@
|
||||
-- +goose Up
|
||||
-- Deleting an organization removes it at once but leaves its check results
|
||||
-- and aggregates, which carry no foreign key, to the background: years of
|
||||
-- results take far longer to delete than a request may last. The purge
|
||||
-- goes a chunk at a time, each in a transaction of its own, so it never
|
||||
-- holds locks for long and resumes where it stopped.
|
||||
CREATE TABLE org_purges (
|
||||
org_id uuid PRIMARY KEY,
|
||||
requested_at timestamptz NOT NULL DEFAULT now(),
|
||||
-- An API instance purging the organization holds it until then.
|
||||
leased_until timestamptz NOT NULL DEFAULT '-infinity'
|
||||
);
|
||||
|
||||
ALTER TABLE org_purges ENABLE ROW LEVEL SECURITY;
|
||||
ALTER TABLE org_purges FORCE ROW LEVEL SECURITY;
|
||||
CREATE POLICY org_purges_system ON org_purges FOR ALL
|
||||
USING (app_scope_system()) WITH CHECK (app_scope_system());
|
||||
|
||||
-- +goose StatementBegin
|
||||
-- The chunks holding check data: those of the raw results first, so the
|
||||
-- aggregates' refresh does not materialize again what was purged from them,
|
||||
-- then those of both aggregates, oldest first. Runs with the owner's rights because the application role
|
||||
-- may not reach TimescaleDB's internal schema.
|
||||
CREATE FUNCTION org_check_data_chunks() RETURNS SETOF text
|
||||
LANGUAGE sql STABLE SECURITY DEFINER SET search_path = public, pg_temp AS $$
|
||||
SELECT format('%I.%I', c.chunk_schema, c.chunk_name)
|
||||
FROM timescaledb_information.chunks c
|
||||
WHERE (c.hypertable_schema, c.hypertable_name) IN (
|
||||
SELECT 'public'::name, 'check_results'::name
|
||||
UNION ALL
|
||||
SELECT materialization_hypertable_schema, materialization_hypertable_name
|
||||
FROM timescaledb_information.continuous_aggregates
|
||||
WHERE view_name IN ('check_results_1h', 'check_results_1d'))
|
||||
ORDER BY c.hypertable_name <> 'check_results', c.range_start, 1
|
||||
$$;
|
||||
-- +goose StatementEnd
|
||||
|
||||
-- +goose StatementBegin
|
||||
-- Deletes an organization's rows in one chunk of org_check_data_chunks,
|
||||
-- through its hypertable and limited to the chunk's time range, so that
|
||||
-- TimescaleDB handles compressed chunks. Chunks dropped meanwhile, and
|
||||
-- names of anything else, delete nothing.
|
||||
CREATE FUNCTION purge_org_check_chunk(org uuid, chunk text) RETURNS bigint
|
||||
LANGUAGE plpgsql SECURITY DEFINER SET search_path = public, pg_temp AS $$
|
||||
DECLARE
|
||||
r record;
|
||||
n bigint;
|
||||
BEGIN
|
||||
SELECT c.hypertable_schema AS hs, c.hypertable_name AS hn, d.column_name AS col,
|
||||
c.range_start AS lo, c.range_end AS hi
|
||||
INTO r
|
||||
FROM timescaledb_information.chunks c
|
||||
JOIN timescaledb_information.dimensions d
|
||||
ON d.hypertable_schema = c.hypertable_schema AND d.hypertable_name = c.hypertable_name
|
||||
AND d.dimension_number = 1
|
||||
WHERE format('%I.%I', c.chunk_schema, c.chunk_name) = chunk
|
||||
AND chunk IN (SELECT org_check_data_chunks());
|
||||
IF NOT FOUND THEN
|
||||
RETURN 0;
|
||||
END IF;
|
||||
EXECUTE format('DELETE FROM %I.%I WHERE org_id = $1 AND %I >= $2 AND %I < $3', r.hs, r.hn, r.col, r.col)
|
||||
USING org, r.lo, r.hi;
|
||||
GET DIAGNOSTICS n = ROW_COUNT;
|
||||
RETURN n;
|
||||
END
|
||||
$$;
|
||||
-- +goose StatementEnd
|
||||
|
||||
-- +goose Down
|
||||
DROP FUNCTION purge_org_check_chunk(uuid, text);
|
||||
DROP FUNCTION org_check_data_chunks();
|
||||
DROP TABLE org_purges;
|
||||
@@ -0,0 +1,16 @@
|
||||
-- +goose Up
|
||||
-- Where a region's checkers stand, so the monitor form can show them on a
|
||||
-- map. Both coordinates are set or neither is.
|
||||
ALTER TABLE regions
|
||||
ADD COLUMN latitude double precision,
|
||||
ADD COLUMN longitude double precision,
|
||||
ADD CONSTRAINT regions_location_check CHECK (
|
||||
(latitude IS NULL AND longitude IS NULL)
|
||||
OR (latitude BETWEEN -90 AND 90 AND longitude BETWEEN -180 AND 180)
|
||||
);
|
||||
|
||||
-- +goose Down
|
||||
ALTER TABLE regions
|
||||
DROP CONSTRAINT regions_location_check,
|
||||
DROP COLUMN latitude,
|
||||
DROP COLUMN longitude;
|
||||
@@ -15,11 +15,13 @@ import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"maps"
|
||||
"mime"
|
||||
"net"
|
||||
"net/http"
|
||||
"net/smtp"
|
||||
"net/url"
|
||||
"slices"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
@@ -53,6 +55,9 @@ type Event struct {
|
||||
ResolvedAt *time.Time `json:"resolved_at,omitempty"`
|
||||
Cause map[string]string `json:"cause,omitempty"`
|
||||
Monitor Monitor `json:"monitor"`
|
||||
// RegionNames names the regions Cause has by id, for messages to
|
||||
// people.
|
||||
RegionNames map[string]string `json:"-"`
|
||||
}
|
||||
|
||||
// Webhook signs requests so receivers can verify they came from us: the
|
||||
@@ -158,6 +163,8 @@ type Mail struct {
|
||||
To []string
|
||||
Subject string
|
||||
Body string
|
||||
// Headers are added to the message, e.g. List-Unsubscribe.
|
||||
Headers map[string]string
|
||||
}
|
||||
|
||||
// Send delivers m.
|
||||
@@ -223,6 +230,12 @@ func compose(from string, m Mail) []byte {
|
||||
fmt.Fprintf(&b, "Subject: %s\r\n", encodeHeader(m.Subject))
|
||||
fmt.Fprintf(&b, "Date: %s\r\n", time.Now().Format(time.RFC1123Z))
|
||||
fmt.Fprintf(&b, "Message-ID: <%s@uptimesebi>\r\n", uuid.NewString())
|
||||
for _, k := range slices.Sorted(maps.Keys(m.Headers)) {
|
||||
// Header injection: values come from the application, but a line
|
||||
// break must never start a header of its own.
|
||||
v := strings.NewReplacer("\r", "", "\n", "").Replace(m.Headers[k])
|
||||
fmt.Fprintf(&b, "%s: %s\r\n", k, v)
|
||||
}
|
||||
b.WriteString("MIME-Version: 1.0\r\nContent-Type: text/plain; charset=utf-8\r\nContent-Transfer-Encoding: 8bit\r\n\r\n")
|
||||
b.WriteString(strings.ReplaceAll(m.Body, "\n", "\r\n"))
|
||||
return b.Bytes()
|
||||
|
||||
@@ -0,0 +1,209 @@
|
||||
// Package ogimage draws the preview images link previews show for status
|
||||
// pages and the app (Open Graph and Twitter cards): 1200×630 PNGs in the
|
||||
// style of the console.
|
||||
package ogimage
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"image"
|
||||
"image/color"
|
||||
"image/draw"
|
||||
"image/png"
|
||||
"math"
|
||||
"strings"
|
||||
"sync"
|
||||
|
||||
"golang.org/x/image/font"
|
||||
"golang.org/x/image/font/gofont/gobold"
|
||||
"golang.org/x/image/font/gofont/goregular"
|
||||
"golang.org/x/image/font/opentype"
|
||||
"golang.org/x/image/math/fixed"
|
||||
)
|
||||
|
||||
// Width and Height are the size link previews expect.
|
||||
const (
|
||||
Width = 1200
|
||||
Height = 630
|
||||
)
|
||||
|
||||
// Colors of the console's palette.
|
||||
var (
|
||||
Paper = color.RGBA{0xf4, 0xf2, 0xee, 0xff}
|
||||
Ink = color.RGBA{0x1c, 0x1d, 0x1f, 0xff}
|
||||
Muted = color.RGBA{0x6b, 0x67, 0x5f, 0xff}
|
||||
Rule = color.RGBA{0xd9, 0xd5, 0xcc, 0xff}
|
||||
Up = color.RGBA{0x2f, 0x7d, 0x4f, 0xff}
|
||||
Down = color.RGBA{0xb3, 0x36, 0x1f, 0xff}
|
||||
Degraded = color.RGBA{0xb5, 0x7b, 0x14, 0xff}
|
||||
Unknown = color.RGBA{0x8a, 0x8a, 0x86, 0xff}
|
||||
Maintenance = color.RGBA{0x3d, 0x6f, 0xa6, 0xff}
|
||||
)
|
||||
|
||||
// Card is what an image shows: a title, a line below it marked with a dot
|
||||
// in Accent, and a footer such as the page's address.
|
||||
type Card struct {
|
||||
Title string
|
||||
Subtitle string
|
||||
Footer string
|
||||
Accent color.Color
|
||||
}
|
||||
|
||||
var (
|
||||
fontsOnce sync.Once
|
||||
regular *opentype.Font
|
||||
bold *opentype.Font
|
||||
fontsErr error
|
||||
)
|
||||
|
||||
func loadFonts() error {
|
||||
fontsOnce.Do(func() {
|
||||
if regular, fontsErr = opentype.Parse(goregular.TTF); fontsErr != nil {
|
||||
return
|
||||
}
|
||||
bold, fontsErr = opentype.Parse(gobold.TTF)
|
||||
})
|
||||
return fontsErr
|
||||
}
|
||||
|
||||
func face(f *opentype.Font, size float64) (font.Face, error) {
|
||||
return opentype.NewFace(f, &opentype.FaceOptions{Size: size, DPI: 72, Hinting: font.HintingFull})
|
||||
}
|
||||
|
||||
const margin = 80
|
||||
|
||||
// Render draws c as a PNG.
|
||||
func Render(c Card) ([]byte, error) {
|
||||
if err := loadFonts(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
accent := c.Accent
|
||||
if accent == nil {
|
||||
accent = Ink
|
||||
}
|
||||
img := image.NewRGBA(image.Rect(0, 0, Width, Height))
|
||||
draw.Draw(img, img.Bounds(), image.NewUniform(Paper), image.Point{}, draw.Src)
|
||||
// A band in the accent colour along the top, and a rule above the footer.
|
||||
fill(img, image.Rect(0, 0, Width, 14), accent)
|
||||
fill(img, image.Rect(margin, Height-130, Width-margin, Height-128), Rule)
|
||||
|
||||
brand, err := face(bold, 30)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
drawText(img, brand, Ink, margin, 104, "UptimeSebi")
|
||||
|
||||
// The title shrinks for long names and wraps onto at most two lines.
|
||||
y := 230
|
||||
for _, size := range []float64{76, 64, 54} {
|
||||
title, err := face(bold, size)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
lines := wrap(title, c.Title, Width-2*margin, 2)
|
||||
if len(lines) == 1 || size == 54 {
|
||||
lh := int(size * 1.15)
|
||||
for _, l := range lines {
|
||||
drawText(img, title, Ink, margin, y, l)
|
||||
y += lh
|
||||
}
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
if c.Subtitle != "" {
|
||||
sub, err := face(regular, 38)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
y += 30
|
||||
dot(img, margin+14, y-13, 14, accent)
|
||||
lines := wrap(sub, c.Subtitle, Width-2*margin-48, 1)
|
||||
drawText(img, sub, Ink, margin+48, y, lines[0])
|
||||
}
|
||||
|
||||
if c.Footer != "" {
|
||||
foot, err := face(regular, 28)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
drawText(img, foot, Muted, margin, Height-72, wrap(foot, c.Footer, Width-2*margin, 1)[0])
|
||||
}
|
||||
|
||||
var buf bytes.Buffer
|
||||
if err := png.Encode(&buf, img); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return buf.Bytes(), nil
|
||||
}
|
||||
|
||||
func fill(img *image.RGBA, r image.Rectangle, c color.Color) {
|
||||
draw.Draw(img, r, image.NewUniform(c), image.Point{}, draw.Src)
|
||||
}
|
||||
|
||||
// dot draws a filled circle of radius r around (cx, cy), smoothing its edge.
|
||||
func dot(img *image.RGBA, cx, cy, r int, c color.Color) {
|
||||
cr, cg, cb, _ := c.RGBA()
|
||||
for y := cy - r - 1; y <= cy+r+1; y++ {
|
||||
for x := cx - r - 1; x <= cx+r+1; x++ {
|
||||
// Coverage from the distance of the pixel centre to the edge.
|
||||
dx, dy := float64(x-cx)+0.5, float64(y-cy)+0.5
|
||||
d := float64(r) - math.Sqrt(dx*dx+dy*dy) + 0.5
|
||||
if d <= 0 {
|
||||
continue
|
||||
}
|
||||
if d > 1 {
|
||||
d = 1
|
||||
}
|
||||
bg := img.RGBAAt(x, y)
|
||||
mix := func(fg uint32, b uint8) uint8 { return uint8(float64(fg>>8)*d + float64(b)*(1-d)) }
|
||||
img.SetRGBA(x, y, color.RGBA{mix(cr, bg.R), mix(cg, bg.G), mix(cb, bg.B), 0xff})
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func drawText(img *image.RGBA, f font.Face, c color.Color, x, y int, s string) {
|
||||
d := font.Drawer{Dst: img, Src: image.NewUniform(c), Face: f, Dot: fixed.P(x, y)}
|
||||
d.DrawString(s)
|
||||
}
|
||||
|
||||
// wrap breaks s into lines no wider than width, at most max of them; the
|
||||
// last one ends in an ellipsis when s does not fit.
|
||||
func wrap(f font.Face, s string, width, max int) []string {
|
||||
words := strings.Fields(s)
|
||||
if len(words) == 0 {
|
||||
return []string{""}
|
||||
}
|
||||
limit := fixed.I(width)
|
||||
var lines []string
|
||||
line := ""
|
||||
for i, w := range words {
|
||||
next := strings.TrimSpace(line + " " + w)
|
||||
if font.MeasureString(f, next) <= limit {
|
||||
line = next
|
||||
continue
|
||||
}
|
||||
if line != "" {
|
||||
lines = append(lines, line)
|
||||
}
|
||||
line = w
|
||||
if len(lines) == max {
|
||||
// Out of lines: finish the last one with what is left.
|
||||
rest := strings.Join(words[i:], " ")
|
||||
lines[max-1] = ellipsize(f, lines[max-1]+" "+rest, limit)
|
||||
return lines
|
||||
}
|
||||
}
|
||||
return append(lines, ellipsize(f, line, limit))
|
||||
}
|
||||
|
||||
// ellipsize shortens s until it fits limit, marking the cut with "…".
|
||||
func ellipsize(f font.Face, s string, limit fixed.Int26_6) string {
|
||||
if font.MeasureString(f, s) <= limit {
|
||||
return s
|
||||
}
|
||||
r := []rune(s)
|
||||
for len(r) > 0 && font.MeasureString(f, string(r)+"…") > limit {
|
||||
r = r[:len(r)-1]
|
||||
}
|
||||
return strings.TrimSpace(string(r)) + "…"
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
package ogimage
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"image/png"
|
||||
"os"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestRender(t *testing.T) {
|
||||
for _, c := range []Card{
|
||||
{Title: "Hetzner Cloud", Subtitle: "All systems operational", Footer: "uptimesebi-status.net/hetzner", Accent: Up},
|
||||
{Title: strings.Repeat("A very long status page name ", 6), Subtitle: strings.Repeat("problems ", 20), Footer: "x", Accent: Down},
|
||||
{Title: ""},
|
||||
} {
|
||||
b, err := Render(c)
|
||||
if err != nil {
|
||||
t.Fatalf("Render(%q) error = %v", c.Title, err)
|
||||
}
|
||||
img, err := png.Decode(bytes.NewReader(b))
|
||||
if err != nil {
|
||||
t.Fatalf("Render(%q) is no PNG: %v", c.Title, err)
|
||||
}
|
||||
if r := img.Bounds(); r.Dx() != Width || r.Dy() != Height {
|
||||
t.Errorf("Render(%q) size = %v, want %dx%d", c.Title, r, Width, Height)
|
||||
}
|
||||
if dir := os.Getenv("OGIMAGE_OUT"); dir != "" {
|
||||
_ = os.WriteFile(dir+"/"+string(rune('a'+len(c.Title)%26))+".png", b, 0o600)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestWrap(t *testing.T) {
|
||||
if err := loadFonts(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
f, err := face(bold, 76)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
lines := wrap(f, strings.Repeat("word ", 100), 1040, 2)
|
||||
if len(lines) != 2 || !strings.HasSuffix(lines[1], "…") {
|
||||
t.Errorf("wrap() = %q, want two lines ending in an ellipsis", lines)
|
||||
}
|
||||
if got := wrap(f, "Short", 1040, 2); len(got) != 1 || got[0] != "Short" {
|
||||
t.Errorf("wrap(Short) = %q", got)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,142 @@
|
||||
package platform
|
||||
|
||||
import (
|
||||
"compress/gzip"
|
||||
"io"
|
||||
"mime"
|
||||
"net/http"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
// compressMin is the smallest body worth compressing, for responses that
|
||||
// state their length.
|
||||
const compressMin = 1024
|
||||
|
||||
var gzipWriters = sync.Pool{New: func() any {
|
||||
w, _ := gzip.NewWriterLevel(io.Discard, gzip.DefaultCompression)
|
||||
return w
|
||||
}}
|
||||
|
||||
// Compress gzips text responses (HTML, CSS, JavaScript, JSON, XML, SVG) for
|
||||
// clients that accept it. Status pages list thousands of components in
|
||||
// markup that repeats itself, so this shrinks them many times over.
|
||||
func Compress() gin.HandlerFunc {
|
||||
return func(c *gin.Context) {
|
||||
c.Writer.Header().Add("Vary", "Accept-Encoding")
|
||||
if c.Request.Method == http.MethodHead || !acceptsGzip(c.Request.Header.Get("Accept-Encoding")) {
|
||||
c.Next()
|
||||
return
|
||||
}
|
||||
w := &gzipWriter{ResponseWriter: c.Writer}
|
||||
c.Writer = w
|
||||
defer w.finish()
|
||||
c.Next()
|
||||
}
|
||||
}
|
||||
|
||||
// acceptsGzip reports whether an Accept-Encoding header allows gzip.
|
||||
func acceptsGzip(header string) bool {
|
||||
for _, part := range strings.Split(header, ",") {
|
||||
name, params, _ := strings.Cut(part, ";")
|
||||
name = strings.ToLower(strings.TrimSpace(name))
|
||||
if name != "gzip" && name != "*" {
|
||||
continue
|
||||
}
|
||||
for _, p := range strings.Split(params, ";") {
|
||||
k, v, _ := strings.Cut(strings.TrimSpace(p), "=")
|
||||
if strings.EqualFold(k, "q") {
|
||||
if q, err := strconv.ParseFloat(strings.TrimSpace(v), 64); err == nil && q == 0 {
|
||||
return false
|
||||
}
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func compressible(contentType string) bool {
|
||||
mt, _, err := mime.ParseMediaType(contentType)
|
||||
if err != nil {
|
||||
return false
|
||||
}
|
||||
switch {
|
||||
case strings.HasPrefix(mt, "text/"):
|
||||
return true
|
||||
case mt == "application/json", mt == "application/javascript", mt == "image/svg+xml",
|
||||
mt == "application/xml", mt == "application/rss+xml", mt == "application/atom+xml":
|
||||
return true
|
||||
}
|
||||
return strings.HasSuffix(mt, "+json") || strings.HasSuffix(mt, "+xml")
|
||||
}
|
||||
|
||||
// gzipWriter decides at the first write whether to compress, when the
|
||||
// handler has set the status and headers.
|
||||
type gzipWriter struct {
|
||||
gin.ResponseWriter
|
||||
decided bool
|
||||
gz *gzip.Writer
|
||||
}
|
||||
|
||||
func (w *gzipWriter) decide() {
|
||||
w.decided = true
|
||||
h := w.Header()
|
||||
switch status := w.Status(); {
|
||||
case status < 200, status == http.StatusNoContent, status == http.StatusNotModified, status == http.StatusPartialContent:
|
||||
return
|
||||
}
|
||||
if h.Get("Content-Encoding") != "" || !compressible(h.Get("Content-Type")) {
|
||||
return
|
||||
}
|
||||
if n, err := strconv.Atoi(h.Get("Content-Length")); err == nil && n < compressMin {
|
||||
return
|
||||
}
|
||||
h.Set("Content-Encoding", "gzip")
|
||||
h.Del("Content-Length")
|
||||
if etag := h.Get("ETag"); etag != "" && !strings.HasPrefix(etag, "W/") {
|
||||
h.Set("ETag", "W/"+etag)
|
||||
}
|
||||
w.gz = gzipWriters.Get().(*gzip.Writer)
|
||||
w.gz.Reset(w.ResponseWriter)
|
||||
}
|
||||
|
||||
// Write compresses b if decide chose to, which it does at the first write.
|
||||
func (w *gzipWriter) Write(b []byte) (int, error) {
|
||||
if !w.decided {
|
||||
if w.Header().Get("Content-Type") == "" {
|
||||
w.Header().Set("Content-Type", http.DetectContentType(b))
|
||||
}
|
||||
w.decide()
|
||||
}
|
||||
if w.gz == nil {
|
||||
return w.ResponseWriter.Write(b)
|
||||
}
|
||||
return w.gz.Write(b)
|
||||
}
|
||||
|
||||
// WriteString writes s like Write, so strings are compressed as well.
|
||||
func (w *gzipWriter) WriteString(s string) (int, error) {
|
||||
return w.Write([]byte(s))
|
||||
}
|
||||
|
||||
// Flush sends what is compressed so far, for responses that stream.
|
||||
func (w *gzipWriter) Flush() {
|
||||
if w.gz != nil {
|
||||
_ = w.gz.Flush()
|
||||
}
|
||||
w.ResponseWriter.Flush()
|
||||
}
|
||||
|
||||
func (w *gzipWriter) finish() {
|
||||
if w.gz == nil {
|
||||
return
|
||||
}
|
||||
_ = w.gz.Close()
|
||||
w.gz.Reset(io.Discard)
|
||||
gzipWriters.Put(w.gz)
|
||||
w.gz = nil
|
||||
}
|
||||
@@ -0,0 +1,86 @@
|
||||
package platform
|
||||
|
||||
import (
|
||||
"compress/gzip"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strconv"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
func TestCompress(t *testing.T) {
|
||||
gin.SetMode(gin.TestMode)
|
||||
page := strings.Repeat("<li>component</li>", 2000)
|
||||
r := gin.New()
|
||||
r.Use(Compress())
|
||||
r.GET("/page", func(c *gin.Context) {
|
||||
c.Header("Content-Type", "text/html; charset=utf-8")
|
||||
c.Status(http.StatusOK)
|
||||
for i := 0; i < 2000; i++ {
|
||||
_, _ = c.Writer.WriteString("<li>component</li>")
|
||||
}
|
||||
})
|
||||
r.GET("/small", func(c *gin.Context) { c.String(http.StatusOK, "ok") })
|
||||
r.GET("/sized", func(c *gin.Context) {
|
||||
c.Header("Content-Length", strconv.Itoa(len("tiny")))
|
||||
c.Data(http.StatusOK, "text/plain", []byte("tiny"))
|
||||
})
|
||||
r.GET("/png", func(c *gin.Context) { c.Data(http.StatusOK, "image/png", []byte(page)) })
|
||||
r.GET("/json", func(c *gin.Context) { c.JSON(http.StatusOK, gin.H{"page": page}) })
|
||||
r.GET("/notmodified", func(c *gin.Context) { c.Status(http.StatusNotModified) })
|
||||
|
||||
get := func(path, accept string) *httptest.ResponseRecorder {
|
||||
req := httptest.NewRequest(http.MethodGet, path, nil)
|
||||
if accept != "" {
|
||||
req.Header.Set("Accept-Encoding", accept)
|
||||
}
|
||||
rec := httptest.NewRecorder()
|
||||
r.ServeHTTP(rec, req)
|
||||
return rec
|
||||
}
|
||||
gunzip := func(t *testing.T, rec *httptest.ResponseRecorder) string {
|
||||
t.Helper()
|
||||
zr, err := gzip.NewReader(rec.Body)
|
||||
if err != nil {
|
||||
t.Fatalf("gzip.NewReader() error = %v", err)
|
||||
}
|
||||
b, err := io.ReadAll(zr)
|
||||
if err != nil {
|
||||
t.Fatalf("reading gzip body error = %v", err)
|
||||
}
|
||||
return string(b)
|
||||
}
|
||||
|
||||
rec := get("/page", "br, gzip;q=0.8")
|
||||
if rec.Header().Get("Content-Encoding") != "gzip" || rec.Header().Get("Vary") != "Accept-Encoding" {
|
||||
t.Fatalf("headers = %v, want gzip with Vary", rec.Header())
|
||||
}
|
||||
if rec.Body.Len() >= len(page)/10 {
|
||||
t.Errorf("compressed size = %d, want far below %d", rec.Body.Len(), len(page))
|
||||
}
|
||||
if got := gunzip(t, rec); got != page {
|
||||
t.Errorf("decompressed body differs: %d bytes, want %d", len(got), len(page))
|
||||
}
|
||||
if rec := get("/json", "gzip"); rec.Header().Get("Content-Encoding") != "gzip" || !strings.Contains(gunzip(t, rec), "component") {
|
||||
t.Errorf("JSON not compressed: %v", rec.Header())
|
||||
}
|
||||
for _, tc := range []struct{ path, accept string }{
|
||||
{"/page", ""},
|
||||
{"/page", "gzip;q=0, deflate"},
|
||||
{"/page", "identity"},
|
||||
{"/sized", "gzip"},
|
||||
{"/png", "gzip"},
|
||||
{"/notmodified", "gzip"},
|
||||
} {
|
||||
if rec := get(tc.path, tc.accept); rec.Header().Get("Content-Encoding") != "" {
|
||||
t.Errorf("GET %s with %q compressed, want plain", tc.path, tc.accept)
|
||||
}
|
||||
}
|
||||
if rec := get("/page", "*"); rec.Header().Get("Content-Encoding") != "gzip" {
|
||||
t.Errorf("Accept-Encoding * not compressed")
|
||||
}
|
||||
}
|
||||
+198
-46
@@ -7,12 +7,18 @@
|
||||
// number of API replicas can dispatch concurrently without a leader, and a
|
||||
// lost job never stops a monitor from running again.
|
||||
//
|
||||
// Each monitor has a fixed phase within its interval, derived from its ID.
|
||||
// After its first run, which is right away, a monitor runs on its phase, so
|
||||
// runs spread evenly over the interval however the monitors were created,
|
||||
// and late runs do not all gather at the moment they were dispatched.
|
||||
//
|
||||
// Instances announce themselves by polling. One that stops polling is
|
||||
// considered gone after StaleAfter; its queued jobs return to the region.
|
||||
package schedule
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/binary"
|
||||
"errors"
|
||||
"fmt"
|
||||
"strconv"
|
||||
@@ -33,6 +39,8 @@ const (
|
||||
const (
|
||||
keyRegions = "sched:regions"
|
||||
keyIntervals = "sched:intervals"
|
||||
// keyPhases holds each monitor's phase within its interval, in ms.
|
||||
keyPhases = "sched:phases"
|
||||
// keyTouched records when each monitor was last upserted, so a
|
||||
// reconciliation based on an older database read leaves it alone.
|
||||
keyTouched = "sched:touched"
|
||||
@@ -60,6 +68,9 @@ func New(rdb redis.UniversalClient) *Scheduler {
|
||||
type Entry struct {
|
||||
MonitorID uuid.UUID
|
||||
ScheduledAt time.Time
|
||||
// DispatchedAt is when the run was queued; zero for runs queued before
|
||||
// dispatch times were recorded.
|
||||
DispatchedAt time.Time
|
||||
}
|
||||
|
||||
// Monitor is the schedule-relevant part of a monitor.
|
||||
@@ -69,20 +80,55 @@ type Monitor struct {
|
||||
Regions []string
|
||||
}
|
||||
|
||||
// phaseOf returns the phase of monitor id within interval, in ms. The ID's
|
||||
// random bits spread the phases of all monitors evenly.
|
||||
func phaseOf(id uuid.UUID, interval time.Duration) int64 {
|
||||
ms := interval.Milliseconds()
|
||||
if ms <= 0 {
|
||||
return 0
|
||||
}
|
||||
return int64(binary.BigEndian.Uint64(id[8:]) % uint64(ms))
|
||||
}
|
||||
|
||||
// nextSlot returns the first time after now, in ms, at which a monitor with
|
||||
// phase and interval, both in ms, runs. dispatchScript computes the same.
|
||||
func nextSlot(now, phase, interval int64) int64 {
|
||||
if interval <= 0 {
|
||||
return now
|
||||
}
|
||||
off := (now - phase) % interval
|
||||
if off < 0 {
|
||||
off += interval
|
||||
}
|
||||
return now - off + interval
|
||||
}
|
||||
|
||||
// Upsert schedules m in its regions and removes it from others it was in.
|
||||
// A monitor new to a region runs right away; an existing schedule keeps its
|
||||
// phase so edits do not cause bursts.
|
||||
// time so edits do not cause bursts.
|
||||
func (s *Scheduler) Upsert(ctx context.Context, m Monitor, previousRegions []string) error {
|
||||
return s.upsert(ctx, m, previousRegions, true)
|
||||
}
|
||||
|
||||
// upsert is Upsert; without runNow, a monitor new to a region first runs on
|
||||
// its phase instead of right away.
|
||||
func (s *Scheduler) upsert(ctx context.Context, m Monitor, previousRegions []string, runNow bool) error {
|
||||
now := s.now().UnixMilli()
|
||||
id := m.ID.String()
|
||||
phase := phaseOf(m.ID, m.Interval)
|
||||
first := now
|
||||
if !runNow {
|
||||
first = nextSlot(now, phase, m.Interval.Milliseconds())
|
||||
}
|
||||
_, err := s.rdb.TxPipelined(ctx, func(p redis.Pipeliner) error {
|
||||
p.HSet(ctx, keyIntervals, id, int64(m.Interval/time.Millisecond))
|
||||
p.HSet(ctx, keyIntervals, id, m.Interval.Milliseconds())
|
||||
p.HSet(ctx, keyPhases, id, phase)
|
||||
p.HSet(ctx, keyTouched, id, now)
|
||||
keep := map[string]bool{}
|
||||
for _, r := range m.Regions {
|
||||
keep[r] = true
|
||||
p.SAdd(ctx, keyRegions, r)
|
||||
p.ZAddNX(ctx, keyDue(r), redis.Z{Score: float64(now), Member: id})
|
||||
p.ZAddNX(ctx, keyDue(r), redis.Z{Score: float64(first), Member: id})
|
||||
}
|
||||
for _, r := range previousRegions {
|
||||
if !keep[r] {
|
||||
@@ -99,6 +145,7 @@ func (s *Scheduler) Upsert(ctx context.Context, m Monitor, previousRegions []str
|
||||
func (s *Scheduler) Remove(ctx context.Context, id uuid.UUID, regions []string) error {
|
||||
_, err := s.rdb.TxPipelined(ctx, func(p redis.Pipeliner) error {
|
||||
p.HDel(ctx, keyIntervals, id.String())
|
||||
p.HDel(ctx, keyPhases, id.String())
|
||||
p.HDel(ctx, keyTouched, id.String())
|
||||
for _, r := range regions {
|
||||
p.ZRem(ctx, keyDue(r), id.String())
|
||||
@@ -112,11 +159,12 @@ func (s *Scheduler) Remove(ctx context.Context, id uuid.UUID, regions []string)
|
||||
// from the database at asOf. It repairs drift after a Redis failover or a
|
||||
// missed update and is safe to run from several replicas. Monitors upserted
|
||||
// after asOf are kept even if want lacks them: they were created while the
|
||||
// database was being read.
|
||||
// database was being read. Monitors it adds back first run on their phase,
|
||||
// so recovering a lost schedule causes no burst.
|
||||
func (s *Scheduler) Reconcile(ctx context.Context, want []Monitor, asOf time.Time) error {
|
||||
byRegion := map[string]map[string]bool{}
|
||||
for _, m := range want {
|
||||
if err := s.Upsert(ctx, m, nil); err != nil {
|
||||
if err := s.upsert(ctx, m, nil, false); err != nil {
|
||||
return err
|
||||
}
|
||||
for _, r := range m.Regions {
|
||||
@@ -139,7 +187,7 @@ func (s *Scheduler) Reconcile(ctx context.Context, want []Monitor, asOf time.Tim
|
||||
if wanted[id] {
|
||||
continue
|
||||
}
|
||||
if err := pruneScript.Run(ctx, s.rdb, []string{keyIntervals, keyTouched}, id, asOfMS).Err(); err != nil {
|
||||
if err := pruneScript.Run(ctx, s.rdb, []string{keyIntervals, keyTouched, keyPhases}, id, asOfMS).Err(); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
@@ -156,7 +204,7 @@ func (s *Scheduler) Reconcile(ctx context.Context, want []Monitor, asOf time.Tim
|
||||
if byRegion[r][id] {
|
||||
continue
|
||||
}
|
||||
if err := pruneScript.Run(ctx, s.rdb, []string{keyDue(r), keyTouched}, id, asOfMS).Err(); err != nil {
|
||||
if err := pruneScript.Run(ctx, s.rdb, []string{keyDue(r), keyTouched, keyPhases}, id, asOfMS).Err(); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
@@ -168,7 +216,8 @@ func (s *Scheduler) Reconcile(ctx context.Context, want []Monitor, asOf time.Tim
|
||||
// upserted at or after asOf. Checking and removing in one step closes the
|
||||
// window in which a concurrent upsert would be undone.
|
||||
//
|
||||
// KEYS: hash or sorted set to prune, touched hash. ARGV: monitor id, asOf ms.
|
||||
// KEYS: hash or sorted set to prune, touched hash, phase hash.
|
||||
// ARGV: monitor id, asOf ms.
|
||||
var pruneScript = redis.NewScript(`
|
||||
local touched = tonumber(redis.call('HGET', KEYS[2], ARGV[1]) or '0')
|
||||
if touched >= tonumber(ARGV[2]) then return 0 end
|
||||
@@ -177,6 +226,7 @@ if redis.call('TYPE', KEYS[1]).ok == 'zset' then
|
||||
else
|
||||
redis.call('HDEL', KEYS[1], ARGV[1])
|
||||
redis.call('HDEL', KEYS[2], ARGV[1])
|
||||
redis.call('HDEL', KEYS[3], ARGV[1])
|
||||
end
|
||||
return 1
|
||||
`)
|
||||
@@ -188,8 +238,14 @@ func (s *Scheduler) Heartbeat(ctx context.Context, region string, instance uuid.
|
||||
|
||||
// dispatchScript runs per region.
|
||||
//
|
||||
// KEYS: due set, instance set, interval hash.
|
||||
// KEYS: due set, instance set, interval hash, phase hash.
|
||||
// ARGV: now ms, stale-before ms, batch limit, job queue prefix, queue TTL s.
|
||||
//
|
||||
// The next run is the monitor's first phase slot after now. A run off its
|
||||
// slot, like the first one, skips a slot less than half an interval away,
|
||||
// so the monitor does not run twice in quick succession. Monitors without
|
||||
// a phase, scheduled before phases existed, run every interval from their
|
||||
// last due time until reconciliation adds one.
|
||||
var dispatchScript = redis.NewScript(`
|
||||
local now = tonumber(ARGV[1])
|
||||
for _, inst in ipairs(redis.call('ZRANGEBYSCORE', KEYS[2], '-inf', ARGV[2])) do
|
||||
@@ -214,10 +270,19 @@ for i = 1, #due, 2 do
|
||||
redis.call('ZREM', KEYS[1], m)
|
||||
else
|
||||
local q = ARGV[4] .. live[math.random(#live)]
|
||||
redis.call('RPUSH', q, m .. '|' .. string.format('%.0f', at))
|
||||
redis.call('RPUSH', q, m .. '|' .. string.format('%.0f', at) .. '|' .. string.format('%.0f', now))
|
||||
redis.call('EXPIRE', q, ARGV[5])
|
||||
local nxt = at + interval
|
||||
if nxt <= now then nxt = now + interval end
|
||||
local nxt
|
||||
local phase = tonumber(redis.call('HGET', KEYS[4], m) or '')
|
||||
if phase == nil then
|
||||
nxt = at + interval
|
||||
if nxt <= now then nxt = now + interval end
|
||||
else
|
||||
nxt = now - ((now - phase) % interval) + interval
|
||||
if (at - phase) % interval ~= 0 and nxt - now < interval / 2 then
|
||||
nxt = nxt + interval
|
||||
end
|
||||
end
|
||||
redis.call('ZADD', KEYS[1], nxt, m)
|
||||
n = n + 1
|
||||
end
|
||||
@@ -236,7 +301,7 @@ func (s *Scheduler) Dispatch(ctx context.Context) (int, error) {
|
||||
total := 0
|
||||
for _, r := range regions {
|
||||
n, err := dispatchScript.Run(ctx, s.rdb,
|
||||
[]string{keyDue(r), keyInstances(r), keyIntervals},
|
||||
[]string{keyDue(r), keyInstances(r), keyIntervals, keyPhases},
|
||||
now.UnixMilli(), now.Add(-StaleAfter).UnixMilli(), 1000, jobsPrefix, int(jobsTTL.Seconds()),
|
||||
).Int()
|
||||
if err != nil {
|
||||
@@ -262,48 +327,100 @@ func (s *Scheduler) LastSeen(ctx context.Context, region string, instance uuid.U
|
||||
return time.UnixMilli(int64(score)), err
|
||||
}
|
||||
|
||||
// staleAfter is how many intervals a queued run may wait before Take drops
|
||||
// it. By then a newer run of the monitor has been dispatched, since the next
|
||||
// run is due at most one and a half intervals after the last dispatch, so
|
||||
// a checker that fell behind catches up instead of working off runs that
|
||||
// are out of date.
|
||||
const staleAfter = 2
|
||||
|
||||
// Take pops up to max queued runs for instance, waiting up to wait for the
|
||||
// first one. It returns within about a second once ctx is done, so long polls
|
||||
// do not hold up shutdown or cancelled requests.
|
||||
func (s *Scheduler) Take(ctx context.Context, instance uuid.UUID, max int, wait time.Duration) ([]Entry, error) {
|
||||
// do not hold up shutdown or cancelled requests. Runs queued for longer than
|
||||
// staleAfter intervals are dropped; Take returns how many.
|
||||
func (s *Scheduler) Take(ctx context.Context, instance uuid.UUID, max int, wait time.Duration) ([]Entry, int, error) {
|
||||
if max <= 0 {
|
||||
return nil, nil
|
||||
return nil, 0, nil
|
||||
}
|
||||
q := jobsPrefix + instance.String()
|
||||
raw, err := s.rdb.LPopCount(ctx, q, max).Result()
|
||||
if err != nil && !errors.Is(err, redis.Nil) {
|
||||
return nil, err
|
||||
}
|
||||
deadline := time.Now().Add(wait)
|
||||
for len(raw) == 0 && ctx.Err() == nil {
|
||||
left := time.Until(deadline)
|
||||
if left <= 0 {
|
||||
return nil, nil
|
||||
stale := 0
|
||||
for ctx.Err() == nil {
|
||||
raw, err := s.rdb.LPopCount(ctx, q, max).Result()
|
||||
if err != nil && !errors.Is(err, redis.Nil) {
|
||||
return nil, stale, err
|
||||
}
|
||||
// BLPOP blocks server side and ignores ctx, so wait in slices.
|
||||
first, err := s.blpop(ctx, min(left, time.Second), q)
|
||||
if errors.Is(err, redis.Nil) {
|
||||
continue
|
||||
}
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
raw = []string{first[1]}
|
||||
if max > 1 {
|
||||
more, err := s.rdb.LPopCount(ctx, q, max-1).Result()
|
||||
if err != nil && !errors.Is(err, redis.Nil) {
|
||||
return nil, err
|
||||
if len(raw) == 0 {
|
||||
left := time.Until(deadline)
|
||||
if left <= 0 {
|
||||
return nil, stale, nil
|
||||
}
|
||||
raw = append(raw, more...)
|
||||
// BLPOP blocks server side and ignores ctx, so wait in slices.
|
||||
first, err := s.blpop(ctx, min(left, time.Second), q)
|
||||
if errors.Is(err, redis.Nil) {
|
||||
continue
|
||||
}
|
||||
if err != nil {
|
||||
return nil, stale, err
|
||||
}
|
||||
raw = []string{first[1]}
|
||||
if max > 1 {
|
||||
more, err := s.rdb.LPopCount(ctx, q, max-1).Result()
|
||||
if err != nil && !errors.Is(err, redis.Nil) {
|
||||
return nil, stale, err
|
||||
}
|
||||
raw = append(raw, more...)
|
||||
}
|
||||
}
|
||||
out, n, err := s.fresh(ctx, raw)
|
||||
if err != nil {
|
||||
return nil, stale, err
|
||||
}
|
||||
stale += n
|
||||
if len(out) > 0 {
|
||||
return out, stale, nil
|
||||
}
|
||||
}
|
||||
out := make([]Entry, 0, len(raw))
|
||||
return nil, stale, nil
|
||||
}
|
||||
|
||||
// fresh parses popped runs and drops those queued for longer than
|
||||
// staleAfter intervals. It returns the rest and how many it dropped.
|
||||
func (s *Scheduler) fresh(ctx context.Context, raw []string) ([]Entry, int, error) {
|
||||
entries := make([]Entry, 0, len(raw))
|
||||
var ids []string
|
||||
for _, r := range raw {
|
||||
if e, ok := parseEntry(r); ok {
|
||||
out = append(out, e)
|
||||
entries = append(entries, e)
|
||||
if !e.DispatchedAt.IsZero() {
|
||||
ids = append(ids, e.MonitorID.String())
|
||||
}
|
||||
}
|
||||
}
|
||||
return out, nil
|
||||
if len(ids) == 0 {
|
||||
return entries, 0, nil
|
||||
}
|
||||
vals, err := s.rdb.HMGet(ctx, keyIntervals, ids...).Result()
|
||||
if err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
interval := make(map[uuid.UUID]time.Duration, len(ids))
|
||||
for i, v := range vals {
|
||||
str, _ := v.(string)
|
||||
if ms, err := strconv.ParseInt(str, 10, 64); err == nil {
|
||||
interval[uuid.MustParse(ids[i])] = time.Duration(ms) * time.Millisecond
|
||||
}
|
||||
}
|
||||
now := s.now()
|
||||
out := entries[:0]
|
||||
for _, e := range entries {
|
||||
// Removed monitors are left to the caller, which drops them.
|
||||
if iv, ok := interval[e.MonitorID]; ok && !e.DispatchedAt.IsZero() && now.Sub(e.DispatchedAt) > staleAfter*iv {
|
||||
continue
|
||||
}
|
||||
out = append(out, e)
|
||||
}
|
||||
return out, len(entries) - len(out), nil
|
||||
}
|
||||
|
||||
// blpop is BLPOP with a timeout below a second, which go-redis would round
|
||||
@@ -332,18 +449,53 @@ func (s *Scheduler) Instances(ctx context.Context, region string) (int64, error)
|
||||
return s.rdb.ZCount(ctx, keyInstances(region), min, "+inf").Result()
|
||||
}
|
||||
|
||||
// overdueScript counts the runs of a region due before a cutoff: those not
|
||||
// dispatched yet and those waiting in an instance's queue.
|
||||
//
|
||||
// KEYS: due set, instance set.
|
||||
// ARGV: cutoff ms, job queue prefix.
|
||||
var overdueScript = redis.NewScript(`
|
||||
local cutoff = tonumber(ARGV[1])
|
||||
local n = redis.call('ZCOUNT', KEYS[1], '-inf', cutoff)
|
||||
for _, inst in ipairs(redis.call('ZRANGE', KEYS[2], 0, -1)) do
|
||||
for _, job in ipairs(redis.call('LRANGE', ARGV[2] .. inst, 0, -1)) do
|
||||
local at = tonumber(string.match(job, '^[^|]*|([^|]*)'))
|
||||
if at ~= nil and at <= cutoff then n = n + 1 end
|
||||
end
|
||||
end
|
||||
return n
|
||||
`)
|
||||
|
||||
// Overdue returns how many runs of region were due more than late ago and
|
||||
// have not started: runs not dispatched, as when the region has no live
|
||||
// instance, and runs left in the queue of an instance too busy to take them.
|
||||
func (s *Scheduler) Overdue(ctx context.Context, region string, late time.Duration) (int64, error) {
|
||||
return overdueScript.Run(ctx, s.rdb, []string{keyDue(region), keyInstances(region)},
|
||||
s.now().Add(-late).UnixMilli(), jobsPrefix).Int64()
|
||||
}
|
||||
|
||||
// parseEntry parses a queued run: "monitor|scheduled ms|dispatched ms",
|
||||
// or without the dispatch time as queued by older releases.
|
||||
func parseEntry(s string) (Entry, bool) {
|
||||
id, at, ok := strings.Cut(s, "|")
|
||||
if !ok {
|
||||
parts := strings.Split(s, "|")
|
||||
if len(parts) < 2 || len(parts) > 3 {
|
||||
return Entry{}, false
|
||||
}
|
||||
mid, err := uuid.Parse(id)
|
||||
mid, err := uuid.Parse(parts[0])
|
||||
if err != nil {
|
||||
return Entry{}, false
|
||||
}
|
||||
ms, err := strconv.ParseFloat(at, 64)
|
||||
ms, err := strconv.ParseFloat(parts[1], 64)
|
||||
if err != nil {
|
||||
return Entry{}, false
|
||||
}
|
||||
return Entry{MonitorID: mid, ScheduledAt: time.UnixMilli(int64(ms))}, true
|
||||
e := Entry{MonitorID: mid, ScheduledAt: time.UnixMilli(int64(ms))}
|
||||
if len(parts) == 3 {
|
||||
d, err := strconv.ParseFloat(parts[2], 64)
|
||||
if err != nil {
|
||||
return Entry{}, false
|
||||
}
|
||||
e.DispatchedAt = time.UnixMilli(int64(d))
|
||||
}
|
||||
return e, true
|
||||
}
|
||||
@@ -33,7 +33,7 @@ func newTest(t *testing.T) (*Scheduler, *time.Time) {
|
||||
|
||||
func takeAll(t *testing.T, s *Scheduler, inst uuid.UUID) []Entry {
|
||||
t.Helper()
|
||||
e, err := s.Take(context.Background(), inst, 1000, 0)
|
||||
e, _, err := s.Take(context.Background(), inst, 1000, 0)
|
||||
if err != nil {
|
||||
t.Fatalf("Take() failed: %v", err)
|
||||
}
|
||||
@@ -100,11 +100,20 @@ func TestDispatchReschedulesAndKeepsRegionsApart(t *testing.T) {
|
||||
if n := mustDispatch(t, s); n != 0 {
|
||||
t.Errorf("Dispatch() before next interval = %d, want 0", n)
|
||||
}
|
||||
*now = now.Add(30 * time.Second)
|
||||
// The next run is on the monitor's phase, at least half an interval
|
||||
// after the first one.
|
||||
next := dueAt(t, s, "eu", m.ID)
|
||||
if off := (next.UnixMilli() - phaseOf(m.ID, m.Interval)) % m.Interval.Milliseconds(); off != 0 {
|
||||
t.Errorf("next run %v is %dms off its phase", next, off)
|
||||
}
|
||||
if gap := next.Sub(*now); gap < m.Interval/2 || gap > 3*m.Interval/2 {
|
||||
t.Errorf("next run %v after the first, want between half and one and a half intervals", gap)
|
||||
}
|
||||
*now = next
|
||||
_ = s.Heartbeat(ctx, "eu", eu)
|
||||
_ = s.Heartbeat(ctx, "us", us)
|
||||
if n := mustDispatch(t, s); n != 2 {
|
||||
t.Errorf("Dispatch() after interval = %d, want 2", n)
|
||||
t.Errorf("Dispatch() on the next slot = %d, want 2", n)
|
||||
}
|
||||
|
||||
// Leaving a region stops runs there.
|
||||
@@ -177,6 +186,9 @@ func TestRemoveAndReconcile(t *testing.T) {
|
||||
if len(got) != 1 || got[0].MonitorID != keep.ID {
|
||||
t.Errorf("jobs after Reconcile = %+v, want only %v", got, keep.ID)
|
||||
}
|
||||
if s.rdb.HExists(ctx, keyPhases, gone.ID.String()).Val() {
|
||||
t.Error("Reconcile left the phase of a removed monitor")
|
||||
}
|
||||
}
|
||||
|
||||
func TestTakeWaits(t *testing.T) {
|
||||
@@ -184,7 +196,7 @@ func TestTakeWaits(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
in := uuid.New()
|
||||
start := time.Now()
|
||||
got, err := s.Take(ctx, in, 10, 300*time.Millisecond)
|
||||
got, _, err := s.Take(ctx, in, 10, 300*time.Millisecond)
|
||||
if err != nil || len(got) != 0 {
|
||||
t.Fatalf("Take() on empty queue = %v, %v", got, err)
|
||||
}
|
||||
@@ -202,7 +214,7 @@ func TestTakeGetsAJobDuringAShortWait(t *testing.T) {
|
||||
time.Sleep(100 * time.Millisecond)
|
||||
s.rdb.RPush(ctx, jobsPrefix+in.String(), monitor.String()+"|1800000000000")
|
||||
}()
|
||||
got, err := s.Take(ctx, in, 10, 600*time.Millisecond)
|
||||
got, _, err := s.Take(ctx, in, 10, 600*time.Millisecond)
|
||||
if err != nil || len(got) != 1 || got[0].MonitorID != monitor {
|
||||
t.Fatalf("Take() = %v, %v; want the job pushed while waiting", got, err)
|
||||
}
|
||||
@@ -213,7 +225,7 @@ func TestTakeReturnsWhenCancelled(t *testing.T) {
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
go func() { time.Sleep(100 * time.Millisecond); cancel() }()
|
||||
start := time.Now()
|
||||
_, _ = s.Take(ctx, uuid.New(), 10, 20*time.Second)
|
||||
_, _, _ = s.Take(ctx, uuid.New(), 10, 20*time.Second)
|
||||
if took := time.Since(start); took > 2*time.Second {
|
||||
t.Errorf("Take() returned %v after cancellation, want within about a second", took)
|
||||
}
|
||||
@@ -239,3 +251,261 @@ func TestReconcileKeepsMonitorsCreatedDuringRead(t *testing.T) {
|
||||
t.Errorf("jobs after Reconcile = %+v, want the freshly created monitor", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestOverdueCountsRunsLeftBehind(t *testing.T) {
|
||||
s, now := newTest(t)
|
||||
ctx := context.Background()
|
||||
for range 2 {
|
||||
_ = s.Upsert(ctx, Monitor{ID: uuid.New(), Interval: time.Minute, Regions: []string{"eu"}}, nil)
|
||||
}
|
||||
overdue := func() int64 {
|
||||
t.Helper()
|
||||
n, err := s.Overdue(ctx, "eu", 10*time.Second)
|
||||
if err != nil {
|
||||
t.Fatalf("Overdue() failed: %v", err)
|
||||
}
|
||||
return n
|
||||
}
|
||||
if n := overdue(); n != 0 {
|
||||
t.Errorf("Overdue() right after scheduling = %d, want 0", n)
|
||||
}
|
||||
// No instance takes the runs.
|
||||
*now = now.Add(11 * time.Second)
|
||||
mustDispatch(t, s)
|
||||
if n := overdue(); n != 2 {
|
||||
t.Errorf("Overdue() without instances = %d, want 2", n)
|
||||
}
|
||||
busy := uuid.New()
|
||||
_ = s.Heartbeat(ctx, "eu", busy)
|
||||
mustDispatch(t, s)
|
||||
// The queued runs were due 11 seconds ago and are still waiting.
|
||||
if n := overdue(); n != 2 {
|
||||
t.Errorf("Overdue() with the runs left in a queue = %d, want 2", n)
|
||||
}
|
||||
if _, _, err := s.Take(ctx, busy, 10, 0); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if n := overdue(); n != 0 {
|
||||
t.Errorf("Overdue() after the instance took the runs = %d, want 0", n)
|
||||
}
|
||||
}
|
||||
|
||||
func dueAt(t *testing.T, s *Scheduler, region string, id uuid.UUID) time.Time {
|
||||
t.Helper()
|
||||
score, err := s.rdb.ZScore(context.Background(), keyDue(region), id.String()).Result()
|
||||
if err != nil {
|
||||
t.Fatalf("no due time for %v in %s: %v", id, region, err)
|
||||
}
|
||||
return time.UnixMilli(int64(score))
|
||||
}
|
||||
|
||||
// TestPhaseSpreadsBurst creates many monitors at once. Their first runs are
|
||||
// right away; after that they spread over the interval instead of all
|
||||
// running in the same second again.
|
||||
func TestPhaseSpreadsBurst(t *testing.T) {
|
||||
s, now := newTest(t)
|
||||
ctx := context.Background()
|
||||
in := uuid.New()
|
||||
const monitors = 600
|
||||
for range monitors {
|
||||
if err := s.Upsert(ctx, Monitor{ID: uuid.New(), Interval: time.Minute, Regions: []string{"eu"}}, nil); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
perSecond := make([]int, 180)
|
||||
for sec := range perSecond {
|
||||
_ = s.Heartbeat(ctx, "eu", in)
|
||||
perSecond[sec] = mustDispatch(t, s)
|
||||
takeAll(t, s, in)
|
||||
*now = now.Add(time.Second)
|
||||
}
|
||||
if perSecond[0] != monitors {
|
||||
t.Errorf("first second dispatched %d, want all %d first runs", perSecond[0], monitors)
|
||||
}
|
||||
total, peak := 0, 0
|
||||
for _, n := range perSecond[60:] {
|
||||
total += n
|
||||
peak = max(peak, n)
|
||||
}
|
||||
if total != 2*monitors {
|
||||
t.Errorf("seconds 60 to 180 dispatched %d runs, want %d: one per monitor and minute", total, 2*monitors)
|
||||
}
|
||||
// 10 per second on average; all 600 at once without phases.
|
||||
if peak > 30 {
|
||||
t.Errorf("busiest second dispatched %d runs, want them spread at about 10 per second", peak)
|
||||
}
|
||||
}
|
||||
|
||||
// TestLateRunSnapsToPhase dispatches runs long overdue. Each comes back on
|
||||
// its own phase instead of all gathering at the dispatch time.
|
||||
func TestLateRunSnapsToPhase(t *testing.T) {
|
||||
s, now := newTest(t)
|
||||
ctx := context.Background()
|
||||
in := uuid.New()
|
||||
ms := []Monitor{}
|
||||
for range 50 {
|
||||
m := Monitor{ID: uuid.New(), Interval: time.Minute, Regions: []string{"eu"}}
|
||||
ms = append(ms, m)
|
||||
_ = s.Upsert(ctx, m, nil)
|
||||
}
|
||||
_ = s.Heartbeat(ctx, "eu", in)
|
||||
mustDispatch(t, s)
|
||||
// No instance for three intervals.
|
||||
*now = now.Add(3*time.Minute + 7*time.Second)
|
||||
_ = s.Heartbeat(ctx, "eu", in)
|
||||
if n := mustDispatch(t, s); n != len(ms) {
|
||||
t.Fatalf("Dispatch() of the overdue runs = %d, want %d", n, len(ms))
|
||||
}
|
||||
distinct := map[time.Time]bool{}
|
||||
for _, m := range ms {
|
||||
got := dueAt(t, s, "eu", m.ID)
|
||||
want := time.UnixMilli(nextSlot(now.UnixMilli(), phaseOf(m.ID, m.Interval), m.Interval.Milliseconds()))
|
||||
if !got.Equal(want) {
|
||||
t.Errorf("monitor next due %v, want its next slot %v", got, want)
|
||||
}
|
||||
distinct[got] = true
|
||||
}
|
||||
if len(distinct) < len(ms)-5 {
|
||||
t.Errorf("%d monitors share %d due times, want them apart", len(ms), len(distinct))
|
||||
}
|
||||
}
|
||||
|
||||
// TestReconcileAddsOnPhase rebuilds a lost schedule without a burst.
|
||||
func TestReconcileAddsOnPhase(t *testing.T) {
|
||||
s, now := newTest(t)
|
||||
ctx := context.Background()
|
||||
in := uuid.New()
|
||||
_ = s.Heartbeat(ctx, "eu", in)
|
||||
ms := []Monitor{}
|
||||
for range 20 {
|
||||
ms = append(ms, Monitor{ID: uuid.New(), Interval: time.Minute, Regions: []string{"eu"}})
|
||||
}
|
||||
if err := s.Reconcile(ctx, ms, *now); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for _, m := range ms {
|
||||
want := time.UnixMilli(nextSlot(now.UnixMilli(), phaseOf(m.ID, m.Interval), m.Interval.Milliseconds()))
|
||||
if got := dueAt(t, s, "eu", m.ID); !got.Equal(want) {
|
||||
t.Errorf("reconciled monitor due %v, want its slot %v", got, want)
|
||||
}
|
||||
}
|
||||
if n := mustDispatch(t, s); n != 0 {
|
||||
t.Errorf("Dispatch() right after Reconcile = %d, want 0", n)
|
||||
}
|
||||
}
|
||||
|
||||
// TestPhaseFallback covers monitors scheduled before phases existed.
|
||||
func TestPhaseFallback(t *testing.T) {
|
||||
s, now := newTest(t)
|
||||
ctx := context.Background()
|
||||
in := uuid.New()
|
||||
_ = s.Heartbeat(ctx, "eu", in)
|
||||
m := Monitor{ID: uuid.New(), Interval: time.Minute, Regions: []string{"eu"}}
|
||||
_ = s.Upsert(ctx, m, nil)
|
||||
s.rdb.HDel(ctx, keyPhases, m.ID.String())
|
||||
mustDispatch(t, s)
|
||||
if got, want := dueAt(t, s, "eu", m.ID), now.Add(time.Minute); !got.Equal(want) {
|
||||
t.Errorf("monitor without phase next due %v, want one interval later, %v", got, want)
|
||||
}
|
||||
}
|
||||
|
||||
func TestNextSlot(t *testing.T) {
|
||||
for _, c := range []struct{ now, phase, interval, want int64 }{
|
||||
{now: 100, phase: 30, interval: 60, want: 150},
|
||||
{now: 150, phase: 30, interval: 60, want: 210},
|
||||
{now: 10, phase: 30, interval: 60, want: 30},
|
||||
{now: 100, phase: 0, interval: 0, want: 100},
|
||||
} {
|
||||
if got := nextSlot(c.now, c.phase, c.interval); got != c.want {
|
||||
t.Errorf("nextSlot(%d, %d, %d) = %d, want %d", c.now, c.phase, c.interval, got, c.want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// TestTakeDropsStaleRuns lets a busy instance fall behind: the runs it left
|
||||
// in its queue for more than two intervals are dropped, the newer ones of
|
||||
// the same monitors are handed out.
|
||||
func TestTakeDropsStaleRuns(t *testing.T) {
|
||||
s, now := newTest(t)
|
||||
ctx := context.Background()
|
||||
busy := uuid.New()
|
||||
m := Monitor{ID: uuid.New(), Interval: time.Minute, Regions: []string{"eu"}}
|
||||
_ = s.Upsert(ctx, m, nil)
|
||||
_ = s.Heartbeat(ctx, "eu", busy)
|
||||
mustDispatch(t, s)
|
||||
|
||||
// Within two intervals the run is still handed out.
|
||||
*now = now.Add(2 * time.Minute)
|
||||
if got, stale, err := s.Take(ctx, busy, 10, 0); err != nil || len(got) != 1 || stale != 0 {
|
||||
t.Fatalf("Take() after two intervals = %v, %d stale, %v; want the run", got, stale, err)
|
||||
}
|
||||
|
||||
// Left waiting longer, it is dropped in favour of the newer run.
|
||||
_ = s.Heartbeat(ctx, "eu", busy)
|
||||
mustDispatch(t, s)
|
||||
*now = now.Add(2*time.Minute + time.Second)
|
||||
_ = s.Heartbeat(ctx, "eu", busy)
|
||||
if n := mustDispatch(t, s); n != 1 {
|
||||
t.Fatalf("Dispatch() of the newer run = %d, want 1", n)
|
||||
}
|
||||
got, stale, err := s.Take(ctx, busy, 10, 0)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if stale != 1 || len(got) != 1 || !got[0].DispatchedAt.Equal(*now) {
|
||||
t.Errorf("Take() = %+v with %d stale, want only the run dispatched now and 1 stale", got, stale)
|
||||
}
|
||||
}
|
||||
|
||||
// TestTakeSkipsAllStaleRuns does not return empty-handed while fresh runs
|
||||
// wait behind a batch of stale ones.
|
||||
func TestTakeSkipsAllStaleRuns(t *testing.T) {
|
||||
s, now := newTest(t)
|
||||
ctx := context.Background()
|
||||
in := uuid.New()
|
||||
for range 5 {
|
||||
_ = s.Upsert(ctx, Monitor{ID: uuid.New(), Interval: time.Minute, Regions: []string{"eu"}}, nil)
|
||||
}
|
||||
_ = s.Heartbeat(ctx, "eu", in)
|
||||
mustDispatch(t, s)
|
||||
*now = now.Add(3 * time.Minute)
|
||||
fresh := Monitor{ID: uuid.New(), Interval: time.Minute, Regions: []string{"eu"}}
|
||||
_ = s.Upsert(ctx, fresh, nil)
|
||||
_ = s.Heartbeat(ctx, "eu", in)
|
||||
mustDispatch(t, s)
|
||||
// The first pop of 5 holds only stale runs.
|
||||
got, stale, err := s.Take(ctx, in, 5, 0)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if stale != 5 {
|
||||
t.Errorf("stale runs = %d, want 5", stale)
|
||||
}
|
||||
// It pops on and hands out the next runs, all dispatched now.
|
||||
if len(got) != 5 {
|
||||
t.Fatalf("Take() = %d runs, want 5", len(got))
|
||||
}
|
||||
for _, e := range got {
|
||||
if !e.DispatchedAt.Equal(*now) {
|
||||
t.Errorf("Take() handed out %+v, want only runs dispatched now", e)
|
||||
}
|
||||
}
|
||||
if rest := takeAll(t, s, in); len(rest) != 1 || rest[0].MonitorID != fresh.ID {
|
||||
t.Errorf("remaining runs = %+v, want the new monitor's", rest)
|
||||
}
|
||||
}
|
||||
|
||||
func TestParseEntry(t *testing.T) {
|
||||
id := uuid.New()
|
||||
if e, ok := parseEntry(id.String() + "|1800000000000"); !ok || !e.DispatchedAt.IsZero() || e.ScheduledAt.UnixMilli() != 1_800_000_000_000 {
|
||||
t.Errorf("entry without dispatch time = %+v, %v", e, ok)
|
||||
}
|
||||
if e, ok := parseEntry(id.String() + "|1800000000000|1800000005000"); !ok || e.DispatchedAt.UnixMilli() != 1_800_000_005_000 {
|
||||
t.Errorf("entry with dispatch time = %+v, %v", e, ok)
|
||||
}
|
||||
for _, bad := range []string{"x|1", id.String(), id.String() + "|1|2|3", id.String() + "|1|x"} {
|
||||
if _, ok := parseEntry(bad); ok {
|
||||
t.Errorf("parseEntry(%q) accepted", bad)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,143 @@
|
||||
package statuspage
|
||||
|
||||
import (
|
||||
"image/color"
|
||||
"net/http"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
|
||||
"git.zb-server.de/ZB-Server/uptimesebi/internal/agentapi"
|
||||
"git.zb-server.de/ZB-Server/uptimesebi/internal/i18n"
|
||||
"git.zb-server.de/ZB-Server/uptimesebi/internal/ogimage"
|
||||
"git.zb-server.de/ZB-Server/uptimesebi/internal/web"
|
||||
)
|
||||
|
||||
// maxDescription bounds a page's description, about what search results
|
||||
// show.
|
||||
const maxDescription = 160
|
||||
|
||||
// origin is the scheme and host the visitor reached the server at.
|
||||
func origin(c *gin.Context) string {
|
||||
scheme := "http"
|
||||
if c.Request.TLS != nil || strings.EqualFold(c.GetHeader("X-Forwarded-Proto"), "https") {
|
||||
scheme = "https"
|
||||
}
|
||||
return scheme + "://" + c.Request.Host
|
||||
}
|
||||
|
||||
var statusAccent = map[string]color.Color{
|
||||
agentapi.PageOperational: ogimage.Up,
|
||||
agentapi.PageDegraded: ogimage.Degraded,
|
||||
agentapi.PageOutage: ogimage.Down,
|
||||
agentapi.PageUnderMaintenance: ogimage.Maintenance,
|
||||
agentapi.PageUnknown: ogimage.Unknown,
|
||||
}
|
||||
|
||||
// pageMeta describes the status page at base for search engines and link
|
||||
// previews, in the language the request was localized to.
|
||||
func (s *Server) pageMeta(c *gin.Context, snap agentapi.PageSnapshot, base string) *web.PageMeta {
|
||||
ctx := c.Request.Context()
|
||||
lang := i18n.Lang(ctx)
|
||||
desc := web.PlainText(snap.Description, maxDescription)
|
||||
if desc == "" {
|
||||
desc = i18n.T(ctx, "page.meta_description", "Title", snap.Title, "Status", i18n.T(ctx, "page.status."+snap.Status))
|
||||
}
|
||||
abs := origin(c) + base
|
||||
image := web.LangURL(abs+"og.png", lang)
|
||||
_, chosen := c.GetQuery("lang")
|
||||
return web.NewPageMeta(snap.Title, desc, abs, image, snap.Title, lang, chosen && s.catalog.IsSupported(c.Query("lang")), s.catalog.Supported())
|
||||
}
|
||||
|
||||
// ogCache keeps each page's preview image until its title, status or
|
||||
// language changes.
|
||||
type ogCache struct {
|
||||
mu sync.Mutex
|
||||
images map[string]ogEntry
|
||||
}
|
||||
|
||||
type ogEntry struct {
|
||||
sig string
|
||||
png []byte
|
||||
}
|
||||
|
||||
// serveOG draws the page's preview image: its name and current status.
|
||||
func (s *Server) serveOG(c *gin.Context, e entry, base string) {
|
||||
s.localizeRequest(c)
|
||||
ctx := c.Request.Context()
|
||||
snap := e.Snap.WithMaintenance(s.now())
|
||||
card := ogimage.Card{
|
||||
Title: snap.Title,
|
||||
Subtitle: i18n.T(ctx, "page.status."+snap.Status),
|
||||
Footer: strings.TrimSuffix(c.Request.Host+base, "/"),
|
||||
Accent: statusAccent[snap.Status],
|
||||
}
|
||||
sig := strings.Join([]string{card.Title, card.Subtitle, card.Footer, snap.Status}, "\x00")
|
||||
key := e.Key + "\x00" + i18n.Lang(ctx)
|
||||
s.og.mu.Lock()
|
||||
cached, ok := s.og.images[key]
|
||||
s.og.mu.Unlock()
|
||||
if !ok || cached.sig != sig {
|
||||
png, err := ogimage.Render(card)
|
||||
if err != nil {
|
||||
s.log.Warn("drawing preview image failed", "page", e.Key, "error", err)
|
||||
c.Status(http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
cached = ogEntry{sig: sig, png: png}
|
||||
s.og.mu.Lock()
|
||||
if s.og.images == nil {
|
||||
s.og.images = map[string]ogEntry{}
|
||||
}
|
||||
s.og.images[key] = cached
|
||||
s.og.mu.Unlock()
|
||||
}
|
||||
c.Header("Cache-Control", "public, max-age=300")
|
||||
c.Data(http.StatusOK, "image/png", cached.png)
|
||||
}
|
||||
|
||||
func (s *Server) forgetOG(key string) {
|
||||
s.og.mu.Lock()
|
||||
defer s.og.mu.Unlock()
|
||||
for k := range s.og.images {
|
||||
if strings.HasPrefix(k, key+"\x00") {
|
||||
delete(s.og.images, k)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (s *Server) serveSitemap(c *gin.Context, base string) {
|
||||
// No lastmod: a snapshot is regenerated every minute, which says
|
||||
// nothing about whether the page changed.
|
||||
body, err := web.Sitemap([]string{origin(c) + base}, s.catalog.Supported(), time.Time{})
|
||||
if err != nil {
|
||||
c.Status(http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
c.Header("Cache-Control", "public, max-age=3600")
|
||||
c.Data(http.StatusOK, "application/xml; charset=utf-8", body)
|
||||
}
|
||||
|
||||
// serveRobots lets crawlers read the pages but not the feeds, the API or
|
||||
// the subscription forms. A custom domain serves one page, so its sitemap
|
||||
// can be named; the shared hosts serve many under their slugs.
|
||||
func (s *Server) serveRobots(c *gin.Context) {
|
||||
var b strings.Builder
|
||||
b.WriteString("User-agent: *\n")
|
||||
prefix := "/*"
|
||||
custom := s.IsCustomDomain(hostOnly(c.Request.Host))
|
||||
if custom {
|
||||
prefix = ""
|
||||
}
|
||||
for _, p := range []string{"/api/", "/subscribe", "/unsubscribe", "/feed.rss"} {
|
||||
b.WriteString("Disallow: " + prefix + p + "\n")
|
||||
}
|
||||
b.WriteString("Allow: /\n")
|
||||
if custom {
|
||||
b.WriteString("\nSitemap: " + origin(c) + "/sitemap.xml\n")
|
||||
}
|
||||
c.Header("Cache-Control", "public, max-age=3600")
|
||||
c.Data(http.StatusOK, "text/plain; charset=utf-8", []byte(b.String()))
|
||||
}
|
||||
@@ -0,0 +1,424 @@
|
||||
package statuspage
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"encoding/xml"
|
||||
"errors"
|
||||
"net/http"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
|
||||
"git.zb-server.de/ZB-Server/uptimesebi/internal/agentapi"
|
||||
"git.zb-server.de/ZB-Server/uptimesebi/internal/i18n"
|
||||
"git.zb-server.de/ZB-Server/uptimesebi/internal/web"
|
||||
)
|
||||
|
||||
// Besides the page itself, every page has an RSS feed, a small read-only
|
||||
// JSON API and, where the organization allows it, email subscriptions.
|
||||
// Feed and API are served from the cached snapshot like the page;
|
||||
// subscriptions are passed on to the API.
|
||||
|
||||
type routeKind int
|
||||
|
||||
const (
|
||||
routePage routeKind = iota
|
||||
routeLegal
|
||||
routeComponent
|
||||
routeFeed
|
||||
routeAPI
|
||||
routeSubscribe
|
||||
routeConfirm
|
||||
routeUnsubscribe
|
||||
routeOG
|
||||
routeSitemap
|
||||
)
|
||||
|
||||
// posts reports whether the route takes form posts.
|
||||
func (k routeKind) posts() bool {
|
||||
return k == routeSubscribe || k == routeConfirm || k == routeUnsubscribe
|
||||
}
|
||||
|
||||
type route struct {
|
||||
kind routeKind
|
||||
// arg is the legal document, component or API resource.
|
||||
arg string
|
||||
}
|
||||
|
||||
// apiResources are the resources of the page API, below api/v1/.
|
||||
var apiResources = map[string]bool{"status": true, "summary": true, "components": true, "incidents": true}
|
||||
|
||||
// routeOf matches the path below a page's base.
|
||||
func routeOf(parts []string) (route, bool) {
|
||||
switch {
|
||||
case len(parts) == 0:
|
||||
return route{kind: routePage}, true
|
||||
case len(parts) == 1 && parts[0] == "feed.rss":
|
||||
return route{kind: routeFeed}, true
|
||||
case len(parts) == 1 && parts[0] == "subscribe":
|
||||
return route{kind: routeSubscribe}, true
|
||||
case len(parts) == 2 && parts[0] == "subscribe" && parts[1] == "confirm":
|
||||
return route{kind: routeConfirm}, true
|
||||
case len(parts) == 1 && parts[0] == "unsubscribe":
|
||||
return route{kind: routeUnsubscribe}, true
|
||||
case len(parts) == 1 && parts[0] == "og.png":
|
||||
return route{kind: routeOG}, true
|
||||
case len(parts) == 1 && parts[0] == "sitemap.xml":
|
||||
return route{kind: routeSitemap}, true
|
||||
case len(parts) == 3 && parts[0] == "api" && parts[1] == "v1" && apiResources[parts[2]]:
|
||||
return route{kind: routeAPI, arg: parts[2]}, true
|
||||
case len(parts) == 1 && parts[0] != "" && parts[0] != "api":
|
||||
return route{kind: routeLegal, arg: parts[0]}, true
|
||||
case len(parts) == 2 && parts[0] == "components" && parts[1] != "":
|
||||
return route{kind: routeComponent, arg: parts[1]}, true
|
||||
}
|
||||
return route{}, false
|
||||
}
|
||||
|
||||
// Requests per visitor address and window, beyond which the server
|
||||
// answers 429: feed and API are cheap but invite polling loops, and every
|
||||
// subscription request costs the API a mail.
|
||||
const (
|
||||
readsPerMinute = 60
|
||||
subscribesPer10Min = 5
|
||||
tokenActionsPer10Min = 20
|
||||
// maxTracked bounds the addresses a limiter remembers per window.
|
||||
maxTracked = 100_000
|
||||
)
|
||||
|
||||
// windowLimiter counts requests per key in fixed windows.
|
||||
type windowLimiter struct {
|
||||
max int
|
||||
window time.Duration
|
||||
|
||||
mu sync.Mutex
|
||||
start time.Time
|
||||
counts map[string]int
|
||||
}
|
||||
|
||||
func newWindowLimiter(max int, window time.Duration) *windowLimiter {
|
||||
return &windowLimiter{max: max, window: window, counts: map[string]int{}}
|
||||
}
|
||||
|
||||
func (l *windowLimiter) allow(key string, now time.Time) bool {
|
||||
l.mu.Lock()
|
||||
defer l.mu.Unlock()
|
||||
if now.Sub(l.start) >= l.window {
|
||||
clear(l.counts)
|
||||
l.start = now
|
||||
}
|
||||
n, seen := l.counts[key]
|
||||
if !seen && len(l.counts) >= maxTracked {
|
||||
// Memory stays bounded during a flood from many addresses; the
|
||||
// API's own limits still apply to subscriptions.
|
||||
return true
|
||||
}
|
||||
l.counts[key] = n + 1
|
||||
return n < l.max
|
||||
}
|
||||
|
||||
// limiters holds the server's rate limits per kind of route.
|
||||
type limiters struct {
|
||||
reads, subscribes, tokens *windowLimiter
|
||||
}
|
||||
|
||||
func newLimiters() limiters {
|
||||
return limiters{
|
||||
reads: newWindowLimiter(readsPerMinute, time.Minute),
|
||||
subscribes: newWindowLimiter(subscribesPer10Min, 10*time.Minute),
|
||||
tokens: newWindowLimiter(tokenActionsPer10Min, 10*time.Minute),
|
||||
}
|
||||
}
|
||||
|
||||
func (s *Server) limiterFor(k routeKind) *windowLimiter {
|
||||
switch k {
|
||||
case routeFeed, routeAPI:
|
||||
return s.limits.reads
|
||||
case routeSubscribe:
|
||||
return s.limits.subscribes
|
||||
case routeConfirm, routeUnsubscribe:
|
||||
return s.limits.tokens
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// pageURL is the absolute address of the page, as the visitor reached it.
|
||||
func pageURL(c *gin.Context, base string) string {
|
||||
scheme := "http"
|
||||
if c.Request.TLS != nil || strings.EqualFold(c.GetHeader("X-Forwarded-Proto"), "https") {
|
||||
scheme = "https"
|
||||
}
|
||||
return scheme + "://" + c.Request.Host + base
|
||||
}
|
||||
|
||||
// RSS 2.0, with the feed's own address as Atom link as validators ask.
|
||||
type rssFeed struct {
|
||||
XMLName xml.Name `xml:"rss"`
|
||||
Version string `xml:"version,attr"`
|
||||
Atom string `xml:"xmlns:atom,attr"`
|
||||
Channel rssChannel `xml:"channel"`
|
||||
}
|
||||
|
||||
type rssChannel struct {
|
||||
Title string `xml:"title"`
|
||||
Link string `xml:"link"`
|
||||
Description string `xml:"description"`
|
||||
Language string `xml:"language,omitempty"`
|
||||
LastBuildDate string `xml:"lastBuildDate"`
|
||||
Self atomLink `xml:"atom:link"`
|
||||
Items []rssItem `xml:"item"`
|
||||
}
|
||||
|
||||
type atomLink struct {
|
||||
Href string `xml:"href,attr"`
|
||||
Rel string `xml:"rel,attr"`
|
||||
Type string `xml:"type,attr"`
|
||||
}
|
||||
|
||||
type rssItem struct {
|
||||
Title string `xml:"title"`
|
||||
Link string `xml:"link"`
|
||||
Description string `xml:"description"`
|
||||
GUID rssGUID `xml:"guid"`
|
||||
PubDate string `xml:"pubDate"`
|
||||
}
|
||||
|
||||
type rssGUID struct {
|
||||
Value string `xml:",chardata"`
|
||||
IsPermaLink bool `xml:"isPermaLink,attr"`
|
||||
}
|
||||
|
||||
// serveFeed renders the page's incidents and planned maintenance as RSS.
|
||||
func (s *Server) serveFeed(c *gin.Context, e entry, base string) {
|
||||
s.localizeRequest(c)
|
||||
ctx := c.Request.Context()
|
||||
snap := e.Snap.WithMaintenance(s.now())
|
||||
link := pageURL(c, base)
|
||||
feed := rssFeed{Version: "2.0", Atom: "http://www.w3.org/2005/Atom", Channel: rssChannel{
|
||||
Title: snap.Title, Link: link, Language: i18n.Lang(ctx),
|
||||
Description: i18n.T(ctx, "page.feed.description", "Page", snap.Title),
|
||||
LastBuildDate: snap.GeneratedAt.UTC().Format(time.RFC1123Z),
|
||||
Self: atomLink{Href: link + "feed.rss", Rel: "self", Type: "application/rss+xml"},
|
||||
}}
|
||||
for _, inc := range snap.Incidents {
|
||||
title := inc.Title
|
||||
if title == "" {
|
||||
title = inc.Component
|
||||
}
|
||||
at, status := inc.StartedAt, i18n.T(ctx, "incidents.ongoing")
|
||||
if inc.ResolvedAt != nil {
|
||||
at, status = *inc.ResolvedAt, i18n.T(ctx, "incidents.resolved")
|
||||
}
|
||||
var desc []string
|
||||
if len(inc.Updates) > 0 {
|
||||
u := inc.Updates[0]
|
||||
if u.At.After(at) {
|
||||
at = u.At
|
||||
}
|
||||
status = u.StatusName
|
||||
if status == "" {
|
||||
status = i18n.T(ctx, "incident.status."+u.Status)
|
||||
}
|
||||
}
|
||||
for _, u := range inc.Updates {
|
||||
name := u.StatusName
|
||||
if name == "" {
|
||||
name = i18n.T(ctx, "incident.status."+u.Status)
|
||||
}
|
||||
desc = append(desc, u.At.UTC().Format("2006-01-02 15:04")+" UTC · "+name+": "+u.Message)
|
||||
}
|
||||
if title != inc.Component {
|
||||
desc = append([]string{inc.Component}, desc...)
|
||||
}
|
||||
id := inc.ID
|
||||
if id == "" {
|
||||
id = digest(inc.Component, inc.StartedAt.String())
|
||||
}
|
||||
feed.Channel.Items = append(feed.Channel.Items, rssItem{
|
||||
Title: title + " – " + status, Link: link, Description: strings.Join(desc, "\n\n"),
|
||||
GUID: rssGUID{Value: "incident-" + id}, PubDate: at.UTC().Format(time.RFC1123Z),
|
||||
})
|
||||
}
|
||||
for _, m := range snap.Maintenance {
|
||||
feed.Channel.Items = append(feed.Channel.Items, rssItem{
|
||||
Title: i18n.T(ctx, "page.feed.maintenance", "Title", m.Title), Link: link,
|
||||
Description: m.Start.UTC().Format("2006-01-02 15:04") + " – " + m.End.UTC().Format("2006-01-02 15:04") + " UTC · " +
|
||||
strings.Join(m.Components, ", ") + "\n\n" + m.Description,
|
||||
GUID: rssGUID{Value: "maintenance-" + digest(m.Title, m.Start.String())},
|
||||
PubDate: m.Start.UTC().Format(time.RFC1123Z),
|
||||
})
|
||||
}
|
||||
out, err := xml.MarshalIndent(feed, "", " ")
|
||||
if err != nil {
|
||||
c.Status(http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
c.Header("Cache-Control", "public, max-age=60")
|
||||
c.Data(http.StatusOK, "application/rss+xml; charset=utf-8", append([]byte(xml.Header), out...))
|
||||
}
|
||||
|
||||
func digest(parts ...string) string {
|
||||
sum := sha256.Sum256([]byte(strings.Join(parts, "\x00")))
|
||||
return hex.EncodeToString(sum[:8])
|
||||
}
|
||||
|
||||
// apiPage describes the page in API answers.
|
||||
type apiPage struct {
|
||||
Title string `json:"title"`
|
||||
URL string `json:"url"`
|
||||
Status string `json:"status"`
|
||||
UpdatedAt time.Time `json:"updated_at"`
|
||||
// Stale is set while the page cannot reach its source and shows an
|
||||
// older state.
|
||||
Stale bool `json:"stale,omitempty"`
|
||||
}
|
||||
|
||||
// apiComponent is a component in API answers.
|
||||
type apiComponent struct {
|
||||
ID string `json:"id,omitempty"`
|
||||
Name string `json:"name"`
|
||||
Group string `json:"group,omitempty"`
|
||||
Status string `json:"status"`
|
||||
// Uptime90d is the share of successful checks over 90 days, -1
|
||||
// without data.
|
||||
Uptime90d float64 `json:"uptime_90d"`
|
||||
}
|
||||
|
||||
func apiComponents(sections []agentapi.Section, group string) []apiComponent {
|
||||
out := []apiComponent{}
|
||||
for _, sec := range sections {
|
||||
g := group
|
||||
if sec.Name != "" {
|
||||
g = strings.TrimPrefix(group+" / "+sec.Name, " / ")
|
||||
}
|
||||
for _, comp := range sec.Components {
|
||||
out = append(out, apiComponent{ID: comp.ID, Name: comp.Name, Group: g, Status: comp.Status, Uptime90d: comp.Uptime})
|
||||
}
|
||||
out = append(out, apiComponents(sec.Children, g)...)
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// serveAPI answers the page's read-only JSON API.
|
||||
func (s *Server) serveAPI(c *gin.Context, e entry, resource, base string) {
|
||||
now := s.now()
|
||||
snap := e.Snap.WithMaintenance(now)
|
||||
page := apiPage{
|
||||
Title: snap.Title, URL: pageURL(c, base), Status: snap.Status, UpdatedAt: snap.GeneratedAt,
|
||||
Stale: now.Sub(e.Fetched) > staleNoticeAfter,
|
||||
}
|
||||
incidents := snap.Incidents
|
||||
if incidents == nil {
|
||||
incidents = []agentapi.PageIncident{}
|
||||
}
|
||||
maintenance := append(snap.Ongoing(now), snap.Upcoming(now)...)
|
||||
if maintenance == nil {
|
||||
maintenance = []agentapi.PageMaintenance{}
|
||||
}
|
||||
var body any
|
||||
switch resource {
|
||||
case "status":
|
||||
body = gin.H{"page": page}
|
||||
case "components":
|
||||
body = gin.H{"page": page, "components": apiComponents(snap.Sections, "")}
|
||||
case "incidents":
|
||||
body = gin.H{"page": page, "incidents": incidents}
|
||||
default:
|
||||
open := []agentapi.PageIncident{}
|
||||
for _, inc := range incidents {
|
||||
if inc.ResolvedAt == nil {
|
||||
open = append(open, inc)
|
||||
}
|
||||
}
|
||||
body = gin.H{"page": page, "components": apiComponents(snap.Sections, ""), "incidents": open, "maintenance": maintenance}
|
||||
}
|
||||
c.Header("Access-Control-Allow-Origin", "*")
|
||||
c.Header("Cache-Control", "public, max-age=30")
|
||||
c.JSON(http.StatusOK, body)
|
||||
}
|
||||
|
||||
// Subscriptions passes subscription requests on; *agentapi.Client
|
||||
// implements it. Without it the server offers no subscriptions.
|
||||
type Subscriptions interface {
|
||||
Subscribe(ctx context.Context, r agentapi.SubscribeRequest) error
|
||||
ConfirmSubscription(ctx context.Context, token string) (agentapi.SubscriptionInfo, error)
|
||||
Unsubscribe(ctx context.Context, token string) (agentapi.SubscriptionInfo, error)
|
||||
}
|
||||
|
||||
// serveSubscription handles the subscription form and the links mailed to
|
||||
// subscribers. Links only show a button; acting on them takes a post, so
|
||||
// mail scanners opening links neither confirm nor end subscriptions.
|
||||
func (s *Server) serveSubscription(c *gin.Context, e entry, kind routeKind, host, slug, base string, a web.PublicAssets) {
|
||||
subs, ok := s.src.(Subscriptions)
|
||||
if !ok || (kind == routeSubscribe && !e.Snap.Subscribe) {
|
||||
c.Status(http.StatusNotFound)
|
||||
return
|
||||
}
|
||||
s.localizeRequest(c)
|
||||
ctx := c.Request.Context()
|
||||
c.Header("Cache-Control", "no-store")
|
||||
a.NoRefresh = true
|
||||
snap := e.Snap
|
||||
notice := func(status int, title, msg string, form *web.NoticeForm) {
|
||||
web.Render(c, status, web.PublicNoticePage(snap, a, title, msg, form))
|
||||
}
|
||||
token := c.PostForm("token")
|
||||
if token == "" {
|
||||
token = c.Query("token")
|
||||
}
|
||||
switch {
|
||||
case kind == routeSubscribe && c.Request.Method != http.MethodPost:
|
||||
c.Redirect(http.StatusSeeOther, base+"#subscribe")
|
||||
case kind == routeSubscribe && c.PostForm("accept") == "" && len(web.SubscribeConsent(snap, base)) > 0:
|
||||
notice(http.StatusUnprocessableEntity, i18n.T(ctx, "page.subscribe.title"), i18n.T(ctx, "page.subscribe.accept_required"), nil)
|
||||
case kind == routeSubscribe:
|
||||
err := subs.Subscribe(ctx, agentapi.SubscribeRequest{
|
||||
Host: host, Slug: slug, Email: c.PostForm("email"), IP: c.ClientIP(),
|
||||
Locale: c.GetHeader("Accept-Language"), PageURL: pageURL(c, base), Accepted: true,
|
||||
})
|
||||
switch {
|
||||
case err == nil:
|
||||
notice(http.StatusOK, i18n.T(ctx, "page.subscribe.sent_title"), i18n.T(ctx, "page.subscribe.sent"), nil)
|
||||
case errors.Is(err, agentapi.ErrInvalidInput):
|
||||
notice(http.StatusUnprocessableEntity, i18n.T(ctx, "page.subscribe.title"), i18n.T(ctx, "page.subscribe.invalid"), nil)
|
||||
case errors.Is(err, agentapi.ErrRateLimited):
|
||||
notice(http.StatusTooManyRequests, i18n.T(ctx, "page.subscribe.title"), i18n.T(ctx, "page.subscribe.limited"), nil)
|
||||
default:
|
||||
if !errors.Is(err, agentapi.ErrNotFound) {
|
||||
s.log.WarnContext(ctx, "passing on a subscription failed", "error", err)
|
||||
}
|
||||
notice(http.StatusServiceUnavailable, i18n.T(ctx, "page.subscribe.title"), i18n.T(ctx, "page.subscribe.failed"), nil)
|
||||
}
|
||||
case token == "":
|
||||
notice(http.StatusNotFound, i18n.T(ctx, "page.subscribe.title"), i18n.T(ctx, "page.subscribe.link_invalid"), nil)
|
||||
case kind == routeConfirm && c.Request.Method != http.MethodPost:
|
||||
notice(http.StatusOK, i18n.T(ctx, "page.subscribe.confirm_title"), i18n.T(ctx, "page.subscribe.confirm_intro", "Page", snap.Title),
|
||||
&web.NoticeForm{Action: base + "subscribe/confirm", Token: token, Button: i18n.T(ctx, "page.subscribe.confirm_button")})
|
||||
case kind == routeUnsubscribe && c.Request.Method != http.MethodPost:
|
||||
notice(http.StatusOK, i18n.T(ctx, "page.unsubscribe.title"), i18n.T(ctx, "page.unsubscribe.intro", "Page", snap.Title),
|
||||
&web.NoticeForm{Action: base + "unsubscribe", Token: token, Button: i18n.T(ctx, "page.unsubscribe.button")})
|
||||
default:
|
||||
act, title, done := subs.ConfirmSubscription, "page.subscribe.confirmed_title", "page.subscribe.confirmed"
|
||||
if kind == routeUnsubscribe {
|
||||
// Also the one-click unsubscribe of mail programs (RFC 8058),
|
||||
// which posts to the link itself.
|
||||
act, title, done = subs.Unsubscribe, "page.unsubscribe.done_title", "page.unsubscribe.done"
|
||||
}
|
||||
info, err := act(ctx, token)
|
||||
switch {
|
||||
case err == nil:
|
||||
notice(http.StatusOK, i18n.T(ctx, title), i18n.T(ctx, done, "Email", info.Email, "Page", info.PageTitle), nil)
|
||||
case errors.Is(err, agentapi.ErrNotFound):
|
||||
notice(http.StatusNotFound, i18n.T(ctx, "page.subscribe.title"), i18n.T(ctx, "page.subscribe.link_invalid"), nil)
|
||||
case errors.Is(err, agentapi.ErrRateLimited):
|
||||
notice(http.StatusTooManyRequests, i18n.T(ctx, "page.subscribe.title"), i18n.T(ctx, "page.subscribe.limited"), nil)
|
||||
default:
|
||||
s.log.WarnContext(ctx, "passing on a subscription link failed", "error", err)
|
||||
notice(http.StatusServiceUnavailable, i18n.T(ctx, "page.subscribe.title"), i18n.T(ctx, "page.subscribe.failed"), nil)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -19,8 +19,10 @@ import (
|
||||
"log/slog"
|
||||
"net"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
@@ -63,7 +65,7 @@ type Source interface {
|
||||
// PageIfChanged answers agentapi.ErrNotModified when the page still
|
||||
// has checksum.
|
||||
PageIfChanged(ctx context.Context, host, slug, checksum string) (agentapi.PageSnapshot, error)
|
||||
Pages(ctx context.Context) ([]agentapi.PageRef, error)
|
||||
Pages(ctx context.Context) (agentapi.PageIndex, error)
|
||||
}
|
||||
|
||||
// Server renders pages for one status page agent.
|
||||
@@ -71,6 +73,8 @@ type Server struct {
|
||||
src Source
|
||||
catalog *i18n.Catalog
|
||||
log *slog.Logger
|
||||
// og keeps the pages' preview images.
|
||||
og ogCache
|
||||
// ownHosts are the hosts that serve pages by slug; any other host is
|
||||
// looked up as a custom domain.
|
||||
ownHosts map[string]bool
|
||||
@@ -78,7 +82,9 @@ type Server struct {
|
||||
dir string
|
||||
now func() time.Time
|
||||
|
||||
mu sync.Mutex
|
||||
mu sync.Mutex
|
||||
// home is the platform's home page, linked from the error page.
|
||||
home string
|
||||
cache map[string]entry
|
||||
refreshing map[string]bool
|
||||
// again holds pages that changed while being refreshed, which are
|
||||
@@ -92,6 +98,7 @@ type Server struct {
|
||||
// the current second.
|
||||
unknownSecond int64
|
||||
unknownCount int
|
||||
limits limiters
|
||||
// background tracks refreshes started by visits.
|
||||
background sync.WaitGroup
|
||||
}
|
||||
@@ -124,7 +131,7 @@ func New(src Source, catalog *i18n.Catalog, log *slog.Logger, o Options) (*Serve
|
||||
s := &Server{
|
||||
src: src, catalog: catalog, log: log, ownHosts: map[string]bool{}, dir: o.CacheDir,
|
||||
now: time.Now, cache: map[string]entry{}, refreshing: map[string]bool{}, again: map[string]bool{}, visited: map[string]time.Time{},
|
||||
missing: map[string]time.Time{},
|
||||
missing: map[string]time.Time{}, limits: newLimiters(),
|
||||
}
|
||||
for _, h := range o.Hosts {
|
||||
s.ownHosts[strings.ToLower(h)] = true
|
||||
@@ -160,9 +167,39 @@ func (s *Server) loadDisk() error {
|
||||
if len(s.cache) > 0 {
|
||||
s.log.Info("loaded cached status pages", "count", len(s.cache))
|
||||
}
|
||||
if raw, err := os.ReadFile(filepath.Join(s.dir, homeFile)); err == nil {
|
||||
s.home = string(raw)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// homeFile keeps the home page across restarts; not .json, which are pages.
|
||||
const homeFile = "home.url"
|
||||
|
||||
// setHome records the home page the error page links.
|
||||
func (s *Server) setHome(url string) {
|
||||
s.mu.Lock()
|
||||
changed := s.home != url
|
||||
s.home = url
|
||||
s.mu.Unlock()
|
||||
if changed && s.dir != "" {
|
||||
if err := os.WriteFile(filepath.Join(s.dir, homeFile), []byte(url), 0o600); err != nil {
|
||||
s.log.Warn("saving the home page failed", "error", err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// notFound answers visitors of a page that does not exist with a page
|
||||
// leading to the platform's home page.
|
||||
func (s *Server) notFound(c *gin.Context) {
|
||||
s.localizeRequest(c)
|
||||
s.mu.Lock()
|
||||
home := s.home
|
||||
s.mu.Unlock()
|
||||
c.Header("Cache-Control", "no-store")
|
||||
web.Render(c, http.StatusNotFound, web.PublicNotFoundPage("/static/dist/app.css", home))
|
||||
}
|
||||
|
||||
func (s *Server) fileFor(key string) string {
|
||||
sum := sha256.Sum256([]byte(key))
|
||||
return filepath.Join(s.dir, hex.EncodeToString(sum[:16])+".json")
|
||||
@@ -186,6 +223,7 @@ func (s *Server) persist(e entry) {
|
||||
}
|
||||
|
||||
func (s *Server) forget(key string) {
|
||||
s.forgetOG(key)
|
||||
s.mu.Lock()
|
||||
delete(s.cache, key)
|
||||
delete(s.visited, key)
|
||||
@@ -226,53 +264,60 @@ func hostOnly(h string) string {
|
||||
}
|
||||
|
||||
func (s *Server) serve(c *gin.Context) {
|
||||
if c.Request.Method != http.MethodGet && c.Request.Method != http.MethodHead {
|
||||
c.Status(http.StatusMethodNotAllowed)
|
||||
if c.Request.URL.Path == "/robots.txt" && (c.Request.Method == http.MethodGet || c.Request.Method == http.MethodHead) {
|
||||
s.serveRobots(c)
|
||||
return
|
||||
}
|
||||
host := hostOnly(c.Request.Host)
|
||||
trimmed := strings.Trim(c.Request.URL.Path, "/")
|
||||
parts := strings.Split(trimmed, "/")
|
||||
var key, slug, base, legal, compID string
|
||||
custom := s.IsCustomDomain(host)
|
||||
switch {
|
||||
case custom:
|
||||
key, base = "host:"+host, "/"
|
||||
switch {
|
||||
case trimmed == "":
|
||||
case len(parts) == 1:
|
||||
legal = parts[0]
|
||||
case len(parts) == 2 && parts[0] == "components" && parts[1] != "":
|
||||
compID = parts[1]
|
||||
default:
|
||||
c.Status(http.StatusNotFound)
|
||||
return
|
||||
}
|
||||
default:
|
||||
slug = parts[0]
|
||||
if slug == "" {
|
||||
c.Status(http.StatusNotFound)
|
||||
return
|
||||
}
|
||||
key, host, base = "slug:"+slug, "", "/"+slug+"/"
|
||||
switch {
|
||||
case len(parts) == 1:
|
||||
case len(parts) == 2:
|
||||
legal = parts[1]
|
||||
case len(parts) == 3 && parts[1] == "components" && parts[2] != "":
|
||||
compID = parts[2]
|
||||
default:
|
||||
c.Status(http.StatusNotFound)
|
||||
return
|
||||
}
|
||||
var parts []string
|
||||
if trimmed := strings.Trim(c.Request.URL.Path, "/"); trimmed != "" {
|
||||
parts = strings.Split(trimmed, "/")
|
||||
}
|
||||
e, ok := s.lookup(c.Request.Context(), key, host, slug)
|
||||
var key, slug, base string
|
||||
if s.IsCustomDomain(host) {
|
||||
key, base = "host:"+host, "/"
|
||||
} else {
|
||||
if len(parts) == 0 {
|
||||
s.notFound(c)
|
||||
return
|
||||
}
|
||||
slug, parts = parts[0], parts[1:]
|
||||
key, host, base = "slug:"+slug, "", "/"+slug+"/"
|
||||
}
|
||||
rt, ok := routeOf(parts)
|
||||
if !ok {
|
||||
c.Status(http.StatusNotFound)
|
||||
return
|
||||
}
|
||||
if legal != "" {
|
||||
s.serveLegal(c, e, legal, base)
|
||||
switch m := c.Request.Method; {
|
||||
case m == http.MethodPost && rt.kind.posts():
|
||||
case m != http.MethodGet && m != http.MethodHead:
|
||||
c.Status(http.StatusMethodNotAllowed)
|
||||
return
|
||||
}
|
||||
if limit := s.limiterFor(rt.kind); limit != nil && !limit.allow(c.ClientIP(), s.now()) {
|
||||
c.Header("Retry-After", "60")
|
||||
c.Status(http.StatusTooManyRequests)
|
||||
return
|
||||
}
|
||||
e, ok := s.lookup(c.Request.Context(), key, host, slug)
|
||||
if !ok {
|
||||
if rt.kind == routeFeed || rt.kind == routeAPI || rt.kind == routeOG || rt.kind == routeSitemap {
|
||||
c.Status(http.StatusNotFound)
|
||||
} else {
|
||||
s.notFound(c)
|
||||
}
|
||||
return
|
||||
}
|
||||
switch rt.kind {
|
||||
case routeLegal:
|
||||
s.serveLegal(c, e, rt.arg, base)
|
||||
return
|
||||
case routeOG:
|
||||
s.serveOG(c, e, base)
|
||||
return
|
||||
case routeSitemap:
|
||||
s.serveSitemap(c, base)
|
||||
return
|
||||
}
|
||||
var staleSince time.Time
|
||||
@@ -286,13 +331,59 @@ func (s *Server) serve(c *gin.Context) {
|
||||
ComponentBase: base,
|
||||
Now: s.now(),
|
||||
}
|
||||
if compID != "" {
|
||||
s.serveComponent(c, e, compID, assets)
|
||||
switch rt.kind {
|
||||
case routeComponent:
|
||||
assets.NoIndex = true
|
||||
s.serveComponent(c, e, rt.arg, assets)
|
||||
return
|
||||
case routeFeed:
|
||||
s.serveFeed(c, e, base)
|
||||
return
|
||||
case routeAPI:
|
||||
s.serveAPI(c, e, rt.arg, base)
|
||||
return
|
||||
case routeSubscribe, routeConfirm, routeUnsubscribe:
|
||||
assets.NoIndex = true
|
||||
s.serveSubscription(c, e, rt.kind, host, slug, base, assets)
|
||||
return
|
||||
}
|
||||
s.localizeRequest(c)
|
||||
c.Header("Cache-Control", "public, max-age=30")
|
||||
web.Render(c, http.StatusOK, web.PublicStatusPage(e.Snap.WithMaintenance(s.now()), assets))
|
||||
assets.PageSize = componentsPerPage
|
||||
assets.Pages = sectionPages(c.Request.URL.Query())
|
||||
if q := c.Query("q"); len(q) <= maxComponentQuery {
|
||||
assets.Query = q
|
||||
}
|
||||
assets.OnlyProblems = c.Query("problems") == "1"
|
||||
snap := e.Snap.WithMaintenance(s.now())
|
||||
assets.Meta = s.pageMeta(c, snap, base)
|
||||
web.Render(c, http.StatusOK, web.PublicStatusPage(snap, assets))
|
||||
}
|
||||
|
||||
// componentsPerPage is how many of its own components a section of a
|
||||
// status page lists at a time; organizations put thousands on one.
|
||||
const componentsPerPage = 25
|
||||
|
||||
// maxComponentQuery bounds the search for components.
|
||||
const maxComponentQuery = 100
|
||||
|
||||
// maxPagedSections bounds the sections a request pages.
|
||||
const maxPagedSections = 100
|
||||
|
||||
// sectionPages reads the pages of sections a request asks for, as
|
||||
// "p.<key>=<page from 1>".
|
||||
func sectionPages(q url.Values) map[string]int {
|
||||
pages := map[string]int{}
|
||||
for k, vs := range q {
|
||||
key, ok := strings.CutPrefix(k, "p.")
|
||||
if !ok || key == "" || len(vs) == 0 || len(pages) >= maxPagedSections {
|
||||
continue
|
||||
}
|
||||
if n, err := strconv.Atoi(vs[0]); err == nil && n > 1 {
|
||||
pages[key] = n - 1
|
||||
}
|
||||
}
|
||||
return pages
|
||||
}
|
||||
|
||||
// serveComponent renders one component's public detail page from the cached
|
||||
@@ -330,14 +421,17 @@ func (s *Server) serveLegal(c *gin.Context, e entry, kind, base string) {
|
||||
}
|
||||
s.localizeRequest(c)
|
||||
c.Header("Cache-Control", "public, max-age=300")
|
||||
web.Render(c, http.StatusOK, web.PublicLegalPage(e.Snap, web.PublicAssets{CSSHref: "/static/dist/app.css"}, kind, html, base))
|
||||
web.Render(c, http.StatusOK, web.PublicLegalPage(e.Snap, web.PublicAssets{CSSHref: "/static/dist/app.css", NoIndex: true}, kind, html, base))
|
||||
}
|
||||
}
|
||||
|
||||
// localizeRequest shows the language ?lang= names, else the visitor's
|
||||
// preferred one; each language has its own address for search engines.
|
||||
func (s *Server) localizeRequest(c *gin.Context) {
|
||||
l := s.catalog.Match(c.GetHeader("Accept-Language"))
|
||||
l := s.catalog.Match(c.Query("lang"), c.GetHeader("Accept-Language"))
|
||||
c.Request = c.Request.WithContext(i18n.NewContext(c.Request.Context(), l))
|
||||
c.Header("Content-Language", l.Lang())
|
||||
c.Writer.Header().Add("Vary", "Accept-Language")
|
||||
}
|
||||
|
||||
// lookup answers from the cache whenever possible and refreshes in the
|
||||
@@ -520,11 +614,13 @@ func (s *Server) Run(ctx context.Context) {
|
||||
func (s *Server) Sync(ctx context.Context) {
|
||||
ctx, cancel := context.WithTimeout(ctx, syncInterval)
|
||||
defer cancel()
|
||||
refs, err := s.src.Pages(ctx)
|
||||
index, err := s.src.Pages(ctx)
|
||||
if err != nil {
|
||||
s.log.WarnContext(ctx, "listing status pages failed", "error", err)
|
||||
return
|
||||
}
|
||||
s.setHome(index.HomeURL)
|
||||
refs := index.Pages
|
||||
todo := map[string]entry{}
|
||||
s.mu.Lock()
|
||||
for key, e := range s.cache {
|
||||
|
||||
@@ -1,8 +1,10 @@
|
||||
package statuspage
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
@@ -25,6 +27,7 @@ type fakeSource struct {
|
||||
err error
|
||||
delay time.Duration
|
||||
pages map[string]agentapi.PageSnapshot
|
||||
home string
|
||||
}
|
||||
|
||||
// PageIfChanged counts calls and answers like the API, sending pages
|
||||
@@ -65,16 +68,16 @@ func (f *fakeSource) page(ctx context.Context, host, slug string) (agentapi.Page
|
||||
}
|
||||
|
||||
// Pages lists the fake's pages by their keys: "host|" or "|slug".
|
||||
func (f *fakeSource) Pages(context.Context) ([]agentapi.PageRef, error) {
|
||||
func (f *fakeSource) Pages(context.Context) (agentapi.PageIndex, error) {
|
||||
f.mu.Lock()
|
||||
defer f.mu.Unlock()
|
||||
if f.err != nil {
|
||||
return nil, f.err
|
||||
return agentapi.PageIndex{}, f.err
|
||||
}
|
||||
var out []agentapi.PageRef
|
||||
out := agentapi.PageIndex{HomeURL: f.home}
|
||||
for k := range f.pages {
|
||||
host, slug, _ := strings.Cut(k, "|")
|
||||
out = append(out, agentapi.PageRef{Host: host, Slug: slug})
|
||||
out.Pages = append(out.Pages, agentapi.PageRef{Host: host, Slug: slug})
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
@@ -128,6 +131,26 @@ func (h harness) get(host, path string) (int, string) {
|
||||
return w.Code, w.Body.String()
|
||||
}
|
||||
|
||||
// The error page links the platform's home page, also after a restart
|
||||
// while the API is down.
|
||||
func TestNotFoundLinksHome(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
now := time.Now()
|
||||
src := newSource()
|
||||
h := newHarness(t, src, dir, &now)
|
||||
if code, body := h.get("status.example.test", "/"); code != 404 || strings.Contains(body, "Zur Hauptseite") {
|
||||
t.Errorf("error page without a home page = %d, links one: %t", code, strings.Contains(body, "Zur Hauptseite"))
|
||||
}
|
||||
src.home = "https://example.test/"
|
||||
h.srv.Sync(context.Background())
|
||||
restarted := newHarness(t, &fakeSource{err: errors.New("connection refused")}, dir, &now)
|
||||
for _, hs := range []harness{h, restarted} {
|
||||
if code, body := hs.get("status.example.test", "/gone"); code != 404 || !strings.Contains(body, `href="https://example.test/"`) {
|
||||
t.Errorf("error page = %d, lacks the link to the home page", code)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestRouting(t *testing.T) {
|
||||
now := time.Now()
|
||||
h := newHarness(t, newSource(), t.TempDir(), &now)
|
||||
@@ -138,8 +161,8 @@ func TestRouting(t *testing.T) {
|
||||
}{
|
||||
{"status.example.test", "/acme", 200, "Acme status"},
|
||||
{"status.example.test:8082", "/acme", 200, "Alle Systeme funktionieren"},
|
||||
{"status.example.test", "/missing", 404, ""},
|
||||
{"status.example.test", "/", 404, ""},
|
||||
{"status.example.test", "/missing", 404, "Seite nicht gefunden"},
|
||||
{"status.example.test", "/", 404, "Seite nicht gefunden"},
|
||||
{"status.acme.test", "/", 200, "Acme on own domain"},
|
||||
{"status.acme.test", "/acme", 404, ""},
|
||||
{"other.test", "/", 404, ""},
|
||||
@@ -587,3 +610,169 @@ func TestEventsRefreshPagesAtOnce(t *testing.T) {
|
||||
t.Errorf("fetches = %d, want 2: one for the event, one for the change during it", calls)
|
||||
}
|
||||
}
|
||||
|
||||
// Every group of a page with many components lists them a page at a time,
|
||||
// and visitors can search them or show those with an outage only.
|
||||
func TestComponentPagingAndSearch(t *testing.T) {
|
||||
comp := func(id, name, status string) agentapi.Component {
|
||||
return agentapi.Component{ID: id, Name: name, Status: status, Days: []agentapi.Day{{Date: "2026-11-26", Uptime: 1}}}
|
||||
}
|
||||
core := agentapi.Section{Name: "Core"}
|
||||
for i := 0; i < 120; i++ {
|
||||
st := agentapi.PageOperational
|
||||
if i == 7 {
|
||||
st = agentapi.PageDegraded
|
||||
}
|
||||
core.Components = append(core.Components, comp(fmt.Sprintf("c%03d", i), fmt.Sprintf("web-%03d", i), st))
|
||||
}
|
||||
edge := agentapi.Section{Name: "Edge"}
|
||||
for i := 0; i < 10; i++ {
|
||||
st := agentapi.PageOperational
|
||||
if i == 3 {
|
||||
st = agentapi.PageOutage
|
||||
}
|
||||
edge.Components = append(edge.Components, comp(fmt.Sprintf("e%d", i), fmt.Sprintf("edge-%d", i), st))
|
||||
}
|
||||
core.Children = []agentapi.Section{edge}
|
||||
other := agentapi.Section{Name: "Other"}
|
||||
for i := 0; i < 30; i++ {
|
||||
other.Components = append(other.Components, comp(fmt.Sprintf("o%02d", i), fmt.Sprintf("other-%02d", i), agentapi.PageOperational))
|
||||
}
|
||||
now := time.Now()
|
||||
h := newHarness(t, &fakeSource{pages: map[string]agentapi.PageSnapshot{
|
||||
"|acme": {Title: "Acme status", Status: agentapi.PageOperational, ShowDetails: true, Sections: []agentapi.Section{core, other}},
|
||||
"|calm": {Title: "Calm", Status: agentapi.PageOperational, Sections: []agentapi.Section{other}},
|
||||
}}, t.TempDir(), &now)
|
||||
if _, body := h.get("status.example.test", "/calm?problems=1"); !strings.Contains(body, "Keine Komponente hat einen Ausfall.") || strings.Contains(body, "other-00") {
|
||||
t.Errorf("outages only without any lacks the notice")
|
||||
}
|
||||
|
||||
tests := []struct {
|
||||
path string
|
||||
has, hasNot []string
|
||||
}{
|
||||
// Every group shows its first page.
|
||||
{"/acme", []string{"web-000", "web-024", "Seite 1 von 5", "edge-0", "edge-9", "other-00", "other-24", "Seite 1 von 2",
|
||||
`id="g-0"`, `id="g-0.0"`, `id="g-1"`, `href="/acme?p.0=2#g-0"`, `href="/acme?p.1=2#g-1"`, `<path d="M0 0h3v22h-3z"`, "Nur Ausfälle (2)"},
|
||||
[]string{"web-025", "other-25", `rel="prev"`, "<rect", "Alle anzeigen"}},
|
||||
// Groups page on their own and keep the others' pages.
|
||||
{"/acme?p.0=2", []string{"web-025", "web-049", "Seite 2 von 5", `href="/acme#g-0"`, "edge-0", "other-00"}, []string{"web-024", "web-050"}},
|
||||
{"/acme?p.0=2&p.1=2", []string{"web-025", "other-29", `href="/acme?p.0=3&p.1=2#g-0"`, `href="/acme?p.0=2#g-1"`}, []string{"other-00"}},
|
||||
{"/acme?p.0=99", []string{"Seite 5 von 5", "web-119", "edge-9"}, nil},
|
||||
{"/acme?p.0=x", []string{"Seite 1 von 5"}, nil},
|
||||
// Outages only: degraded and down components, groups without any left out.
|
||||
{"/acme?problems=1", []string{"web-007", "edge-3", ">Core<", ">Edge<", ">130<", "checked", "Alle anzeigen"},
|
||||
[]string{"web-000", "edge-0", ">Other<", "Seite 1 von"}},
|
||||
{"/acme?problems=1&q=edge", []string{"edge-3"}, []string{"web-007", "edge-0"}},
|
||||
{"/acme?q=EDGE-", []string{"edge-0", "edge-9", `value="EDGE-"`, "Alle anzeigen"}, []string{"web-", "other-"}},
|
||||
{"/acme?q=edge", []string{"edge-0", "edge-9", ">Core<"}, []string{"web-", ">Other<"}},
|
||||
{"/acme?q=web-11", []string{"web-110", "web-119"}, []string{"web-109", "edge-"}},
|
||||
{"/acme?q=nothing", []string{"Keine Komponente passt zur Suche."}, []string{"web-", "edge-"}},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
code, body := h.get("status.example.test", tt.path)
|
||||
if code != http.StatusOK {
|
||||
t.Errorf("GET %s = %d", tt.path, code)
|
||||
continue
|
||||
}
|
||||
for _, s := range tt.has {
|
||||
if !strings.Contains(body, s) {
|
||||
t.Errorf("GET %s lacks %q", tt.path, s)
|
||||
}
|
||||
}
|
||||
for _, s := range tt.hasNot {
|
||||
if strings.Contains(body, s) {
|
||||
t.Errorf("GET %s has %q", tt.path, s)
|
||||
}
|
||||
}
|
||||
}
|
||||
// The detail page keeps the tooltips of the bars.
|
||||
if _, body := h.get("status.example.test", "/acme/components/c000"); !strings.Contains(body, "<title>2026-11-26") {
|
||||
t.Errorf("component page lacks the bar tooltips")
|
||||
}
|
||||
}
|
||||
|
||||
func (h harness) getFull(host, path string) *httptest.ResponseRecorder {
|
||||
req := httptest.NewRequest(http.MethodGet, path, nil)
|
||||
req.Host = host
|
||||
req.Header.Set("Accept-Language", "de")
|
||||
w := httptest.NewRecorder()
|
||||
h.r.ServeHTTP(w, req)
|
||||
return w
|
||||
}
|
||||
|
||||
func TestSearchAndPreviewMetadata(t *testing.T) {
|
||||
now := time.Now()
|
||||
src := newSource()
|
||||
src.set(func(f *fakeSource) {
|
||||
p := f.pages["|acme"]
|
||||
p.Description = "Status of **Acme** services.\n\nSecond paragraph."
|
||||
p.ShowDetails = true
|
||||
p.Sections = []agentapi.Section{{Components: []agentapi.Component{{ID: "c1", Name: "API", Status: agentapi.PageOperational}}}}
|
||||
f.pages["|acme"] = p
|
||||
})
|
||||
h := newHarness(t, src, t.TempDir(), &now)
|
||||
|
||||
_, body := h.get("status.example.test", "/acme")
|
||||
for _, want := range []string{
|
||||
`<meta name="description" content="Status of Acme services. Second paragraph.">`,
|
||||
`<link rel="canonical" href="http://status.example.test/acme/">`,
|
||||
`<link rel="alternate" hreflang="en" href="http://status.example.test/acme/?lang=en">`,
|
||||
`<link rel="alternate" hreflang="x-default" href="http://status.example.test/acme/">`,
|
||||
`<meta property="og:title" content="Acme status">`,
|
||||
`<meta property="og:image" content="http://status.example.test/acme/og.png?lang=de">`,
|
||||
`<meta property="og:locale" content="de_DE">`,
|
||||
`<meta name="twitter:card" content="summary_large_image">`,
|
||||
} {
|
||||
if !strings.Contains(body, want) {
|
||||
t.Errorf("status page lacks %s", want)
|
||||
}
|
||||
}
|
||||
if strings.Contains(body, "noindex") {
|
||||
t.Errorf("status page is noindex")
|
||||
}
|
||||
|
||||
// ?lang= picks the language and becomes the canonical address.
|
||||
_, body = h.get("status.example.test", "/acme?lang=en&q=api")
|
||||
if !strings.Contains(body, "All systems operational") || !strings.Contains(body, `<link rel="canonical" href="http://status.example.test/acme/?lang=en">`) {
|
||||
t.Errorf("?lang=en does not show English with its own canonical address")
|
||||
}
|
||||
|
||||
// A page without a description describes itself by its status.
|
||||
_, body = h.get("status.acme.test", "/")
|
||||
if !strings.Contains(body, `<meta name="description" content="Aktueller Status von Acme on own domain: Größere Störung. Störungen`) {
|
||||
t.Errorf("custom domain page lacks the generated description")
|
||||
}
|
||||
if !strings.Contains(body, `<link rel="canonical" href="http://status.acme.test/">`) {
|
||||
t.Errorf("custom domain canonical address missing")
|
||||
}
|
||||
|
||||
for _, path := range []string{"/acme/components/c1", "/acme/subscribe"} {
|
||||
if code, body := h.get("status.example.test", path); code == 200 && !strings.Contains(body, `<meta name="robots" content="noindex, nofollow">`) {
|
||||
t.Errorf("GET %s is indexable", path)
|
||||
}
|
||||
}
|
||||
|
||||
w := h.getFull("status.example.test", "/acme/og.png")
|
||||
if w.Code != 200 || w.Header().Get("Content-Type") != "image/png" || !bytes.HasPrefix(w.Body.Bytes(), []byte("\x89PNG")) {
|
||||
t.Errorf("preview image = %d %s", w.Code, w.Header().Get("Content-Type"))
|
||||
}
|
||||
if code, _ := h.get("status.example.test", "/missing/og.png"); code != 404 {
|
||||
t.Errorf("preview image of a missing page = %d, want 404", code)
|
||||
}
|
||||
|
||||
w = h.getFull("status.acme.test", "/sitemap.xml")
|
||||
sm := w.Body.String()
|
||||
if w.Code != 200 || !strings.Contains(sm, "<loc>http://status.acme.test/</loc>") || !strings.Contains(sm, `hreflang="de" href="http://status.acme.test/?lang=de"`) {
|
||||
t.Errorf("sitemap = %d %s", w.Code, sm)
|
||||
}
|
||||
|
||||
_, robots := h.get("status.acme.test", "/robots.txt")
|
||||
if !strings.Contains(robots, "Disallow: /api/") || !strings.Contains(robots, "Sitemap: http://status.acme.test/sitemap.xml") {
|
||||
t.Errorf("custom domain robots.txt = %q", robots)
|
||||
}
|
||||
_, robots = h.get("status.example.test", "/robots.txt")
|
||||
if !strings.Contains(robots, "Disallow: /*/api/") || strings.Contains(robots, "Sitemap:") {
|
||||
t.Errorf("shared host robots.txt = %q", robots)
|
||||
}
|
||||
}
|
||||
@@ -56,18 +56,26 @@ func (q *Queries) CreateAgent(ctx context.Context, arg CreateAgentParams) (Agent
|
||||
}
|
||||
|
||||
const createRegion = `-- name: CreateRegion :one
|
||||
INSERT INTO regions (org_id, key, name) VALUES ($1, $2, $3)
|
||||
RETURNING key, name, created_at, id, org_id
|
||||
INSERT INTO regions (org_id, key, name, latitude, longitude) VALUES ($1, $2, $3, $4, $5)
|
||||
RETURNING key, name, created_at, id, org_id, latitude, longitude
|
||||
`
|
||||
|
||||
type CreateRegionParams struct {
|
||||
OrgID *uuid.UUID
|
||||
Key string
|
||||
Name string
|
||||
OrgID *uuid.UUID
|
||||
Key string
|
||||
Name string
|
||||
Latitude *float64
|
||||
Longitude *float64
|
||||
}
|
||||
|
||||
func (q *Queries) CreateRegion(ctx context.Context, arg CreateRegionParams) (Region, error) {
|
||||
row := q.db.QueryRow(ctx, createRegion, arg.OrgID, arg.Key, arg.Name)
|
||||
row := q.db.QueryRow(ctx, createRegion,
|
||||
arg.OrgID,
|
||||
arg.Key,
|
||||
arg.Name,
|
||||
arg.Latitude,
|
||||
arg.Longitude,
|
||||
)
|
||||
var i Region
|
||||
err := row.Scan(
|
||||
&i.Key,
|
||||
@@ -75,6 +83,8 @@ func (q *Queries) CreateRegion(ctx context.Context, arg CreateRegionParams) (Reg
|
||||
&i.CreatedAt,
|
||||
&i.ID,
|
||||
&i.OrgID,
|
||||
&i.Latitude,
|
||||
&i.Longitude,
|
||||
)
|
||||
return i, err
|
||||
}
|
||||
@@ -113,7 +123,7 @@ INSERT INTO regions (org_id, key, name)
|
||||
VALUES (NULL, $1, coalesce(nullif($2::text, ''), $1))
|
||||
ON CONFLICT ON CONSTRAINT regions_owner_key_key
|
||||
DO UPDATE SET name = CASE WHEN $2::text = '' THEN regions.name ELSE EXCLUDED.name END
|
||||
RETURNING key, name, created_at, id, org_id
|
||||
RETURNING key, name, created_at, id, org_id, latitude, longitude
|
||||
`
|
||||
|
||||
type EnsurePlatformRegionParams struct {
|
||||
@@ -131,6 +141,8 @@ func (q *Queries) EnsurePlatformRegion(ctx context.Context, arg EnsurePlatformRe
|
||||
&i.CreatedAt,
|
||||
&i.ID,
|
||||
&i.OrgID,
|
||||
&i.Latitude,
|
||||
&i.Longitude,
|
||||
)
|
||||
return i, err
|
||||
}
|
||||
@@ -181,7 +193,7 @@ func (q *Queries) GetAgentByHash(ctx context.Context, tokenHash []byte) (GetAgen
|
||||
}
|
||||
|
||||
const getRegion = `-- name: GetRegion :one
|
||||
SELECT key, name, created_at, id, org_id FROM regions WHERE id = $1
|
||||
SELECT key, name, created_at, id, org_id, latitude, longitude FROM regions WHERE id = $1
|
||||
`
|
||||
|
||||
func (q *Queries) GetRegion(ctx context.Context, id uuid.UUID) (Region, error) {
|
||||
@@ -193,6 +205,8 @@ func (q *Queries) GetRegion(ctx context.Context, id uuid.UUID) (Region, error) {
|
||||
&i.CreatedAt,
|
||||
&i.ID,
|
||||
&i.OrgID,
|
||||
&i.Latitude,
|
||||
&i.Longitude,
|
||||
)
|
||||
return i, err
|
||||
}
|
||||
@@ -257,7 +271,7 @@ func (q *Queries) ListAgents(ctx context.Context, orgID *uuid.UUID) ([]ListAgent
|
||||
}
|
||||
|
||||
const listPlatformRegions = `-- name: ListPlatformRegions :many
|
||||
SELECT key, name, created_at, id, org_id FROM regions WHERE org_id IS NULL ORDER BY name, key
|
||||
SELECT key, name, created_at, id, org_id, latitude, longitude FROM regions WHERE org_id IS NULL ORDER BY name, key
|
||||
`
|
||||
|
||||
func (q *Queries) ListPlatformRegions(ctx context.Context) ([]Region, error) {
|
||||
@@ -275,6 +289,8 @@ func (q *Queries) ListPlatformRegions(ctx context.Context) ([]Region, error) {
|
||||
&i.CreatedAt,
|
||||
&i.ID,
|
||||
&i.OrgID,
|
||||
&i.Latitude,
|
||||
&i.Longitude,
|
||||
); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -287,7 +303,7 @@ func (q *Queries) ListPlatformRegions(ctx context.Context) ([]Region, error) {
|
||||
}
|
||||
|
||||
const listVisibleRegions = `-- name: ListVisibleRegions :many
|
||||
SELECT key, name, created_at, id, org_id FROM regions ORDER BY org_id IS NULL, name, key
|
||||
SELECT key, name, created_at, id, org_id, latitude, longitude FROM regions ORDER BY org_id IS NULL, name, key
|
||||
`
|
||||
|
||||
// Row-level security limits this to platform regions and the scope's org;
|
||||
@@ -307,6 +323,8 @@ func (q *Queries) ListVisibleRegions(ctx context.Context) ([]Region, error) {
|
||||
&i.CreatedAt,
|
||||
&i.ID,
|
||||
&i.OrgID,
|
||||
&i.Latitude,
|
||||
&i.Longitude,
|
||||
); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -437,3 +455,23 @@ func (q *Queries) TouchAgent(ctx context.Context, arg TouchAgentParams) error {
|
||||
_, err := q.db.Exec(ctx, touchAgent, arg.ID, arg.Release)
|
||||
return err
|
||||
}
|
||||
|
||||
const updateRegionLocation = `-- name: UpdateRegionLocation :execrows
|
||||
UPDATE regions SET latitude = $1, longitude = $2
|
||||
WHERE id = $3
|
||||
`
|
||||
|
||||
type UpdateRegionLocationParams struct {
|
||||
Latitude *float64
|
||||
Longitude *float64
|
||||
ID uuid.UUID
|
||||
}
|
||||
|
||||
// Null coordinates remove the location.
|
||||
func (q *Queries) UpdateRegionLocation(ctx context.Context, arg UpdateRegionLocationParams) (int64, error) {
|
||||
result, err := q.db.Exec(ctx, updateRegionLocation, arg.Latitude, arg.Longitude, arg.ID)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
return result.RowsAffected(), nil
|
||||
}
|
||||
@@ -124,44 +124,6 @@ func (q *Queries) DailyBucketsForMonitors(ctx context.Context, arg DailyBucketsF
|
||||
return items, nil
|
||||
}
|
||||
|
||||
const earliestDataDaily = `-- name: EarliestDataDaily :one
|
||||
SELECT bucket::timestamptz AS first FROM check_results_1d WHERE org_id = $1 ORDER BY bucket LIMIT 1
|
||||
`
|
||||
|
||||
// The day the organization's monitors first reported, if any did.
|
||||
func (q *Queries) EarliestDataDaily(ctx context.Context, orgID uuid.UUID) (time.Time, error) {
|
||||
row := q.db.QueryRow(ctx, earliestDataDaily, orgID)
|
||||
var first time.Time
|
||||
err := row.Scan(&first)
|
||||
return first, err
|
||||
}
|
||||
|
||||
const earliestDataRecent = `-- name: EarliestDataRecent :one
|
||||
SELECT f.time FROM monitors m
|
||||
CROSS JOIN LATERAL (
|
||||
SELECT c.time FROM check_results c
|
||||
WHERE c.org_id = $1 AND c.monitor_id = m.id AND c.time >= $2
|
||||
ORDER BY c.time LIMIT 1
|
||||
) f
|
||||
WHERE m.org_id = $1
|
||||
ORDER BY f.time LIMIT 1
|
||||
`
|
||||
|
||||
type EarliestDataRecentParams struct {
|
||||
OrgID uuid.UUID
|
||||
Time time.Time
|
||||
}
|
||||
|
||||
// When the organization's monitors first reported since $2, exactly: the
|
||||
// first result of each monitor is found through its index, so the cost
|
||||
// does not grow with the days of results.
|
||||
func (q *Queries) EarliestDataRecent(ctx context.Context, arg EarliestDataRecentParams) (time.Time, error) {
|
||||
row := q.db.QueryRow(ctx, earliestDataRecent, arg.OrgID, arg.Time)
|
||||
var time time.Time
|
||||
err := row.Scan(&time)
|
||||
return time, err
|
||||
}
|
||||
|
||||
const firstDataDaily = `-- name: FirstDataDaily :many
|
||||
SELECT monitor_id, region, min(bucket)::timestamptz AS first
|
||||
FROM check_results_1d
|
||||
|
||||
@@ -13,17 +13,18 @@ import (
|
||||
)
|
||||
|
||||
const deleteSuccessEvidence = `-- name: DeleteSuccessEvidence :exec
|
||||
DELETE FROM check_evidence WHERE monitor_id = $1 AND region = $2 AND ok
|
||||
DELETE FROM check_evidence
|
||||
WHERE region = $1 AND ok AND monitor_id = ANY($2::uuid[])
|
||||
`
|
||||
|
||||
type DeleteSuccessEvidenceParams struct {
|
||||
MonitorID uuid.UUID
|
||||
Region string
|
||||
Region string
|
||||
MonitorIds []uuid.UUID
|
||||
}
|
||||
|
||||
// Only the latest success per monitor and region is kept.
|
||||
func (q *Queries) DeleteSuccessEvidence(ctx context.Context, arg DeleteSuccessEvidenceParams) error {
|
||||
_, err := q.db.Exec(ctx, deleteSuccessEvidence, arg.MonitorID, arg.Region)
|
||||
_, err := q.db.Exec(ctx, deleteSuccessEvidence, arg.Region, arg.MonitorIds)
|
||||
return err
|
||||
}
|
||||
|
||||
@@ -124,27 +125,43 @@ func (q *Queries) InsertEvidence(ctx context.Context, arg InsertEvidenceParams)
|
||||
return err
|
||||
}
|
||||
|
||||
const lastFailureEvidence = `-- name: LastFailureEvidence :one
|
||||
SELECT time, coalesce(error, '')::text AS error FROM check_evidence
|
||||
WHERE monitor_id = $1 AND region = $2 AND NOT ok
|
||||
ORDER BY time DESC LIMIT 1
|
||||
const lastFailureEvidence = `-- name: LastFailureEvidence :many
|
||||
SELECT DISTINCT ON (monitor_id) monitor_id, time, coalesce(error, '')::text AS error
|
||||
FROM check_evidence
|
||||
WHERE region = $1 AND NOT ok AND monitor_id = ANY($2::uuid[])
|
||||
ORDER BY monitor_id, time DESC
|
||||
`
|
||||
|
||||
type LastFailureEvidenceParams struct {
|
||||
MonitorID uuid.UUID
|
||||
Region string
|
||||
Region string
|
||||
MonitorIds []uuid.UUID
|
||||
}
|
||||
|
||||
type LastFailureEvidenceRow struct {
|
||||
Time time.Time
|
||||
Error string
|
||||
MonitorID uuid.UUID
|
||||
Time time.Time
|
||||
Error string
|
||||
}
|
||||
|
||||
func (q *Queries) LastFailureEvidence(ctx context.Context, arg LastFailureEvidenceParams) (LastFailureEvidenceRow, error) {
|
||||
row := q.db.QueryRow(ctx, lastFailureEvidence, arg.MonitorID, arg.Region)
|
||||
var i LastFailureEvidenceRow
|
||||
err := row.Scan(&i.Time, &i.Error)
|
||||
return i, err
|
||||
// The newest failure per monitor in region.
|
||||
func (q *Queries) LastFailureEvidence(ctx context.Context, arg LastFailureEvidenceParams) ([]LastFailureEvidenceRow, error) {
|
||||
rows, err := q.db.Query(ctx, lastFailureEvidence, arg.Region, arg.MonitorIds)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
items := []LastFailureEvidenceRow{}
|
||||
for rows.Next() {
|
||||
var i LastFailureEvidenceRow
|
||||
if err := rows.Scan(&i.MonitorID, &i.Time, &i.Error); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
items = append(items, i)
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return items, nil
|
||||
}
|
||||
|
||||
const listEvidence = `-- name: ListEvidence :many
|
||||
|
||||
@@ -345,15 +345,6 @@ func (q *Queries) OwnedOrgs(ctx context.Context, userID uuid.UUID) ([]OwnedOrgsR
|
||||
return items, nil
|
||||
}
|
||||
|
||||
const purgeOrgCheckData = `-- name: PurgeOrgCheckData :exec
|
||||
SELECT purge_org_check_data($1)
|
||||
`
|
||||
|
||||
func (q *Queries) PurgeOrgCheckData(ctx context.Context, org uuid.UUID) error {
|
||||
_, err := q.db.Exec(ctx, purgeOrgCheckData, org)
|
||||
return err
|
||||
}
|
||||
|
||||
const scrubAuditEmail = `-- name: ScrubAuditEmail :exec
|
||||
UPDATE audit_events SET details = details - 'email' WHERE lower(details->>'email') = lower($1::text)
|
||||
`
|
||||
|
||||
@@ -578,7 +578,10 @@ const notificationDetails = `-- name: NotificationDetails :many
|
||||
SELECT n.id, n.org_id, n.event, n.attempts,
|
||||
c.type AS channel_type, c.config AS channel_config, c.id AS channel_id,
|
||||
i.id AS incident_id, i.started_at, i.resolved_at, i.cause,
|
||||
m.id AS monitor_id, m.name AS monitor_name, m.target AS monitor_target, m.type AS monitor_type
|
||||
m.id AS monitor_id, m.name AS monitor_name, m.target AS monitor_target, m.type AS monitor_type,
|
||||
-- The names of the regions the cause names by id.
|
||||
coalesce((SELECT jsonb_object_agg(r.id::text, r.name) FROM regions r
|
||||
WHERE jsonb_typeof(i.cause) = 'object' AND i.cause ? r.id::text), '{}')::jsonb AS region_names
|
||||
FROM notifications n
|
||||
JOIN notification_channels c ON c.id = n.channel_id
|
||||
JOIN incidents i ON i.id = n.incident_id
|
||||
@@ -602,6 +605,7 @@ type NotificationDetailsRow struct {
|
||||
MonitorName string
|
||||
MonitorTarget string
|
||||
MonitorType string
|
||||
RegionNames []byte
|
||||
}
|
||||
|
||||
// System scope.
|
||||
@@ -630,6 +634,7 @@ func (q *Queries) NotificationDetails(ctx context.Context, ids []uuid.UUID) ([]N
|
||||
&i.MonitorName,
|
||||
&i.MonitorTarget,
|
||||
&i.MonitorType,
|
||||
&i.RegionNames,
|
||||
); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
@@ -15,7 +15,7 @@ import (
|
||||
const adminListOrgs = `-- name: AdminListOrgs :many
|
||||
SELECT o.id, o.slug, o.name, o.created_at, o.suspended_at, o.suspended_reason,
|
||||
o.limit_monitors, o.limit_status_pages, o.limit_regions_per_monitor, o.limit_own_regions_count,
|
||||
o.limit_monitors_per_page,
|
||||
o.limit_monitors_per_page, o.limit_subscribers_per_week,
|
||||
(SELECT count(*) FROM monitors m WHERE m.org_id = o.id)::integer AS monitors,
|
||||
(SELECT count(*) FROM status_pages p WHERE p.org_id = o.id)::integer AS status_pages,
|
||||
coalesce(ow.id, '00000000-0000-0000-0000-000000000000'::uuid)::uuid AS owner_id,
|
||||
@@ -52,26 +52,27 @@ type AdminListOrgsParams struct {
|
||||
}
|
||||
|
||||
type AdminListOrgsRow struct {
|
||||
ID uuid.UUID
|
||||
Slug string
|
||||
Name string
|
||||
CreatedAt time.Time
|
||||
SuspendedAt *time.Time
|
||||
SuspendedReason string
|
||||
LimitMonitors *int32
|
||||
LimitStatusPages *int32
|
||||
LimitRegionsPerMonitor *int32
|
||||
LimitOwnRegionsCount *bool
|
||||
LimitMonitorsPerPage *int32
|
||||
Monitors int32
|
||||
StatusPages int32
|
||||
OwnerID uuid.UUID
|
||||
OwnerEmail string
|
||||
OwnerDisabledAt *time.Time
|
||||
OwnerDisabledReason string
|
||||
OwnerIsAdmin bool
|
||||
OwnerLimitOrgs *int32
|
||||
OwnerOrgs int32
|
||||
ID uuid.UUID
|
||||
Slug string
|
||||
Name string
|
||||
CreatedAt time.Time
|
||||
SuspendedAt *time.Time
|
||||
SuspendedReason string
|
||||
LimitMonitors *int32
|
||||
LimitStatusPages *int32
|
||||
LimitRegionsPerMonitor *int32
|
||||
LimitOwnRegionsCount *bool
|
||||
LimitMonitorsPerPage *int32
|
||||
LimitSubscribersPerWeek *int32
|
||||
Monitors int32
|
||||
StatusPages int32
|
||||
OwnerID uuid.UUID
|
||||
OwnerEmail string
|
||||
OwnerDisabledAt *time.Time
|
||||
OwnerDisabledReason string
|
||||
OwnerIsAdmin bool
|
||||
OwnerLimitOrgs *int32
|
||||
OwnerOrgs int32
|
||||
}
|
||||
|
||||
// System scope: organizations with their usage, limit overrides and owner,
|
||||
@@ -105,6 +106,7 @@ func (q *Queries) AdminListOrgs(ctx context.Context, arg AdminListOrgsParams) ([
|
||||
&i.LimitRegionsPerMonitor,
|
||||
&i.LimitOwnRegionsCount,
|
||||
&i.LimitMonitorsPerPage,
|
||||
&i.LimitSubscribersPerWeek,
|
||||
&i.Monitors,
|
||||
&i.StatusPages,
|
||||
&i.OwnerID,
|
||||
@@ -172,18 +174,19 @@ func (q *Queries) LockOrgUsage(ctx context.Context, orgID uuid.UUID) error {
|
||||
const setOrgLimits = `-- name: SetOrgLimits :one
|
||||
UPDATE orgs SET limit_monitors = $1, limit_status_pages = $2,
|
||||
limit_regions_per_monitor = $3, limit_own_regions_count = $4,
|
||||
limit_monitors_per_page = $5
|
||||
WHERE id = $6
|
||||
limit_monitors_per_page = $5, limit_subscribers_per_week = $6
|
||||
WHERE id = $7
|
||||
RETURNING id, slug
|
||||
`
|
||||
|
||||
type SetOrgLimitsParams struct {
|
||||
Monitors *int32
|
||||
StatusPages *int32
|
||||
RegionsPerMonitor *int32
|
||||
OwnRegionsCount *bool
|
||||
MonitorsPerPage *int32
|
||||
ID uuid.UUID
|
||||
Monitors *int32
|
||||
StatusPages *int32
|
||||
RegionsPerMonitor *int32
|
||||
OwnRegionsCount *bool
|
||||
MonitorsPerPage *int32
|
||||
SubscribersPerWeek *int32
|
||||
ID uuid.UUID
|
||||
}
|
||||
|
||||
type SetOrgLimitsRow struct {
|
||||
@@ -198,6 +201,7 @@ func (q *Queries) SetOrgLimits(ctx context.Context, arg SetOrgLimitsParams) (Set
|
||||
arg.RegionsPerMonitor,
|
||||
arg.OwnRegionsCount,
|
||||
arg.MonitorsPerPage,
|
||||
arg.SubscribersPerWeek,
|
||||
arg.ID,
|
||||
)
|
||||
var i SetOrgLimitsRow
|
||||
|
||||
@@ -0,0 +1,81 @@
|
||||
// Code generated by sqlc. DO NOT EDIT.
|
||||
// versions:
|
||||
// sqlc v1.31.1
|
||||
// source: metrics.sql
|
||||
|
||||
package store
|
||||
|
||||
import (
|
||||
"context"
|
||||
)
|
||||
|
||||
const monitorCounts = `-- name: MonitorCounts :many
|
||||
SELECT type, enabled, count(*)::bigint AS monitors
|
||||
FROM monitors
|
||||
GROUP BY type, enabled
|
||||
ORDER BY type, enabled
|
||||
`
|
||||
|
||||
type MonitorCountsRow struct {
|
||||
Type string
|
||||
Enabled bool
|
||||
Monitors int64
|
||||
}
|
||||
|
||||
// System scope. Monitors by type and whether they are enabled.
|
||||
func (q *Queries) MonitorCounts(ctx context.Context) ([]MonitorCountsRow, error) {
|
||||
rows, err := q.db.Query(ctx, monitorCounts)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
items := []MonitorCountsRow{}
|
||||
for rows.Next() {
|
||||
var i MonitorCountsRow
|
||||
if err := rows.Scan(&i.Type, &i.Enabled, &i.Monitors); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
items = append(items, i)
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return items, nil
|
||||
}
|
||||
|
||||
const platformCounts = `-- name: PlatformCounts :one
|
||||
SELECT
|
||||
(SELECT count(*) FROM orgs)::bigint AS orgs,
|
||||
(SELECT count(*) FROM users)::bigint AS users,
|
||||
(SELECT count(*) FROM status_pages)::bigint AS status_pages,
|
||||
(SELECT count(*) FROM status_page_subscribers WHERE confirmed_at IS NOT NULL)::bigint AS subscribers,
|
||||
(SELECT count(*) FROM incidents WHERE resolved_at IS NULL)::bigint AS open_incidents,
|
||||
(SELECT count(*) FROM notifications WHERE status = 'pending')::bigint AS pending_notifications,
|
||||
(SELECT count(*) FROM subscriber_notifications WHERE status = 'pending')::bigint AS pending_subscriber_notifications
|
||||
`
|
||||
|
||||
type PlatformCountsRow struct {
|
||||
Orgs int64
|
||||
Users int64
|
||||
StatusPages int64
|
||||
Subscribers int64
|
||||
OpenIncidents int64
|
||||
PendingNotifications int64
|
||||
PendingSubscriberNotifications int64
|
||||
}
|
||||
|
||||
// System scope. Platform totals for the operator metrics.
|
||||
func (q *Queries) PlatformCounts(ctx context.Context) (PlatformCountsRow, error) {
|
||||
row := q.db.QueryRow(ctx, platformCounts)
|
||||
var i PlatformCountsRow
|
||||
err := row.Scan(
|
||||
&i.Orgs,
|
||||
&i.Users,
|
||||
&i.StatusPages,
|
||||
&i.Subscribers,
|
||||
&i.OpenIncidents,
|
||||
&i.PendingNotifications,
|
||||
&i.PendingSubscriberNotifications,
|
||||
)
|
||||
return i, err
|
||||
}
|
||||
+52
-16
@@ -318,22 +318,29 @@ type NotificationChannel struct {
|
||||
}
|
||||
|
||||
type Org struct {
|
||||
ID uuid.UUID
|
||||
Slug string
|
||||
Name string
|
||||
CreatedAt time.Time
|
||||
UpdatedAt time.Time
|
||||
RequireTotp bool
|
||||
RequireSso bool
|
||||
ApiTokenMaxDays *int32
|
||||
DisabledCheckTypes []string
|
||||
SuspendedAt *time.Time
|
||||
SuspendedReason string
|
||||
LimitMonitors *int32
|
||||
LimitStatusPages *int32
|
||||
LimitRegionsPerMonitor *int32
|
||||
LimitOwnRegionsCount *bool
|
||||
LimitMonitorsPerPage *int32
|
||||
ID uuid.UUID
|
||||
Slug string
|
||||
Name string
|
||||
CreatedAt time.Time
|
||||
UpdatedAt time.Time
|
||||
RequireTotp bool
|
||||
RequireSso bool
|
||||
ApiTokenMaxDays *int32
|
||||
DisabledCheckTypes []string
|
||||
SuspendedAt *time.Time
|
||||
SuspendedReason string
|
||||
LimitMonitors *int32
|
||||
LimitStatusPages *int32
|
||||
LimitRegionsPerMonitor *int32
|
||||
LimitOwnRegionsCount *bool
|
||||
LimitMonitorsPerPage *int32
|
||||
LimitSubscribersPerWeek *int32
|
||||
}
|
||||
|
||||
type OrgPurge struct {
|
||||
OrgID uuid.UUID
|
||||
RequestedAt time.Time
|
||||
LeasedUntil time.Time
|
||||
}
|
||||
|
||||
type PlatformIdentity struct {
|
||||
@@ -377,6 +384,8 @@ type Region struct {
|
||||
CreatedAt time.Time
|
||||
ID uuid.UUID
|
||||
OrgID *uuid.UUID
|
||||
Latitude *float64
|
||||
Longitude *float64
|
||||
}
|
||||
|
||||
type Role struct {
|
||||
@@ -435,6 +444,7 @@ type StatusPage struct {
|
||||
DomainCheckedAt *time.Time
|
||||
DomainFailingSince *time.Time
|
||||
DomainVerifyMethod *string
|
||||
Subscriptions bool
|
||||
}
|
||||
|
||||
type StatusPageGroup struct {
|
||||
@@ -458,6 +468,32 @@ type StatusPageMonitor struct {
|
||||
GroupID *uuid.UUID
|
||||
}
|
||||
|
||||
type StatusPageSubscriber struct {
|
||||
ID uuid.UUID
|
||||
OrgID uuid.UUID
|
||||
PageID uuid.UUID
|
||||
Email string
|
||||
Locale string
|
||||
PageUrl string
|
||||
CreatedAt time.Time
|
||||
ConfirmedAt *time.Time
|
||||
}
|
||||
|
||||
type SubscriberNotification struct {
|
||||
ID uuid.UUID
|
||||
OrgID uuid.UUID
|
||||
SubscriberID uuid.UUID
|
||||
IncidentID uuid.UUID
|
||||
UpdateID *uuid.UUID
|
||||
Event string
|
||||
Status string
|
||||
Attempts int32
|
||||
NextAttemptAt time.Time
|
||||
LastError *string
|
||||
CreatedAt time.Time
|
||||
SentAt *time.Time
|
||||
}
|
||||
|
||||
type SupportMessage struct {
|
||||
ID uuid.UUID
|
||||
TicketID uuid.UUID
|
||||
|
||||
@@ -0,0 +1,109 @@
|
||||
// Code generated by sqlc. DO NOT EDIT.
|
||||
// versions:
|
||||
// sqlc v1.31.1
|
||||
// source: org_purges.sql
|
||||
|
||||
package store
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
const claimOrgPurge = `-- name: ClaimOrgPurge :one
|
||||
UPDATE org_purges SET leased_until = now() + interval '15 minutes'
|
||||
WHERE org_id = (
|
||||
SELECT org_id FROM org_purges WHERE leased_until < now()
|
||||
ORDER BY requested_at LIMIT 1
|
||||
FOR UPDATE SKIP LOCKED
|
||||
)
|
||||
RETURNING org_id
|
||||
`
|
||||
|
||||
// System scope: leases the longest waiting purge no other instance holds.
|
||||
func (q *Queries) ClaimOrgPurge(ctx context.Context) (uuid.UUID, error) {
|
||||
row := q.db.QueryRow(ctx, claimOrgPurge)
|
||||
var org_id uuid.UUID
|
||||
err := row.Scan(&org_id)
|
||||
return org_id, err
|
||||
}
|
||||
|
||||
const countOrgPurges = `-- name: CountOrgPurges :one
|
||||
SELECT count(*) FROM org_purges
|
||||
`
|
||||
|
||||
func (q *Queries) CountOrgPurges(ctx context.Context) (int64, error) {
|
||||
row := q.db.QueryRow(ctx, countOrgPurges)
|
||||
var count int64
|
||||
err := row.Scan(&count)
|
||||
return count, err
|
||||
}
|
||||
|
||||
const extendOrgPurge = `-- name: ExtendOrgPurge :exec
|
||||
UPDATE org_purges SET leased_until = now() + interval '15 minutes' WHERE org_id = $1
|
||||
`
|
||||
|
||||
func (q *Queries) ExtendOrgPurge(ctx context.Context, orgID uuid.UUID) error {
|
||||
_, err := q.db.Exec(ctx, extendOrgPurge, orgID)
|
||||
return err
|
||||
}
|
||||
|
||||
const finishOrgPurge = `-- name: FinishOrgPurge :exec
|
||||
DELETE FROM org_purges WHERE org_id = $1
|
||||
`
|
||||
|
||||
func (q *Queries) FinishOrgPurge(ctx context.Context, orgID uuid.UUID) error {
|
||||
_, err := q.db.Exec(ctx, finishOrgPurge, orgID)
|
||||
return err
|
||||
}
|
||||
|
||||
const orgCheckDataChunks = `-- name: OrgCheckDataChunks :many
|
||||
SELECT chunk::text FROM org_check_data_chunks() AS chunk
|
||||
`
|
||||
|
||||
func (q *Queries) OrgCheckDataChunks(ctx context.Context) ([]string, error) {
|
||||
rows, err := q.db.Query(ctx, orgCheckDataChunks)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
items := []string{}
|
||||
for rows.Next() {
|
||||
var chunk string
|
||||
if err := rows.Scan(&chunk); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
items = append(items, chunk)
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return items, nil
|
||||
}
|
||||
|
||||
const purgeOrgCheckChunk = `-- name: PurgeOrgCheckChunk :one
|
||||
SELECT purge_org_check_chunk($1::uuid, $2::text)::bigint AS rows
|
||||
`
|
||||
|
||||
type PurgeOrgCheckChunkParams struct {
|
||||
OrgID uuid.UUID
|
||||
Chunk string
|
||||
}
|
||||
|
||||
func (q *Queries) PurgeOrgCheckChunk(ctx context.Context, arg PurgeOrgCheckChunkParams) (int64, error) {
|
||||
row := q.db.QueryRow(ctx, purgeOrgCheckChunk, arg.OrgID, arg.Chunk)
|
||||
var rows int64
|
||||
err := row.Scan(&rows)
|
||||
return rows, err
|
||||
}
|
||||
|
||||
const queueOrgPurge = `-- name: QueueOrgPurge :exec
|
||||
INSERT INTO org_purges (org_id) VALUES ($1) ON CONFLICT DO NOTHING
|
||||
`
|
||||
|
||||
// System scope: has the check data of a deleted organization purged.
|
||||
func (q *Queries) QueueOrgPurge(ctx context.Context, orgID uuid.UUID) error {
|
||||
_, err := q.db.Exec(ctx, queueOrgPurge, orgID)
|
||||
return err
|
||||
}
|
||||
@@ -13,7 +13,7 @@ import (
|
||||
|
||||
const createOrg = `-- name: CreateOrg :one
|
||||
INSERT INTO orgs (id, slug, name) VALUES ($1, $2, $3)
|
||||
RETURNING id, slug, name, created_at, updated_at, require_totp, require_sso, api_token_max_days, disabled_check_types, suspended_at, suspended_reason, limit_monitors, limit_status_pages, limit_regions_per_monitor, limit_own_regions_count, limit_monitors_per_page
|
||||
RETURNING id, slug, name, created_at, updated_at, require_totp, require_sso, api_token_max_days, disabled_check_types, suspended_at, suspended_reason, limit_monitors, limit_status_pages, limit_regions_per_monitor, limit_own_regions_count, limit_monitors_per_page, limit_subscribers_per_week
|
||||
`
|
||||
|
||||
type CreateOrgParams struct {
|
||||
@@ -42,6 +42,7 @@ func (q *Queries) CreateOrg(ctx context.Context, arg CreateOrgParams) (Org, erro
|
||||
&i.LimitRegionsPerMonitor,
|
||||
&i.LimitOwnRegionsCount,
|
||||
&i.LimitMonitorsPerPage,
|
||||
&i.LimitSubscribersPerWeek,
|
||||
)
|
||||
return i, err
|
||||
}
|
||||
@@ -59,7 +60,7 @@ func (q *Queries) DeleteOrg(ctx context.Context, id uuid.UUID) (int64, error) {
|
||||
}
|
||||
|
||||
const getOrg = `-- name: GetOrg :one
|
||||
SELECT id, slug, name, created_at, updated_at, require_totp, require_sso, api_token_max_days, disabled_check_types, suspended_at, suspended_reason, limit_monitors, limit_status_pages, limit_regions_per_monitor, limit_own_regions_count, limit_monitors_per_page FROM orgs WHERE id = $1
|
||||
SELECT id, slug, name, created_at, updated_at, require_totp, require_sso, api_token_max_days, disabled_check_types, suspended_at, suspended_reason, limit_monitors, limit_status_pages, limit_regions_per_monitor, limit_own_regions_count, limit_monitors_per_page, limit_subscribers_per_week FROM orgs WHERE id = $1
|
||||
`
|
||||
|
||||
func (q *Queries) GetOrg(ctx context.Context, id uuid.UUID) (Org, error) {
|
||||
@@ -82,12 +83,13 @@ func (q *Queries) GetOrg(ctx context.Context, id uuid.UUID) (Org, error) {
|
||||
&i.LimitRegionsPerMonitor,
|
||||
&i.LimitOwnRegionsCount,
|
||||
&i.LimitMonitorsPerPage,
|
||||
&i.LimitSubscribersPerWeek,
|
||||
)
|
||||
return i, err
|
||||
}
|
||||
|
||||
const getOrgBySlug = `-- name: GetOrgBySlug :one
|
||||
SELECT id, slug, name, created_at, updated_at, require_totp, require_sso, api_token_max_days, disabled_check_types, suspended_at, suspended_reason, limit_monitors, limit_status_pages, limit_regions_per_monitor, limit_own_regions_count, limit_monitors_per_page FROM orgs WHERE slug = $1
|
||||
SELECT id, slug, name, created_at, updated_at, require_totp, require_sso, api_token_max_days, disabled_check_types, suspended_at, suspended_reason, limit_monitors, limit_status_pages, limit_regions_per_monitor, limit_own_regions_count, limit_monitors_per_page, limit_subscribers_per_week FROM orgs WHERE slug = $1
|
||||
`
|
||||
|
||||
func (q *Queries) GetOrgBySlug(ctx context.Context, slug string) (Org, error) {
|
||||
@@ -110,12 +112,13 @@ func (q *Queries) GetOrgBySlug(ctx context.Context, slug string) (Org, error) {
|
||||
&i.LimitRegionsPerMonitor,
|
||||
&i.LimitOwnRegionsCount,
|
||||
&i.LimitMonitorsPerPage,
|
||||
&i.LimitSubscribersPerWeek,
|
||||
)
|
||||
return i, err
|
||||
}
|
||||
|
||||
const listOrgs = `-- name: ListOrgs :many
|
||||
SELECT id, slug, name, created_at, updated_at, require_totp, require_sso, api_token_max_days, disabled_check_types, suspended_at, suspended_reason, limit_monitors, limit_status_pages, limit_regions_per_monitor, limit_own_regions_count, limit_monitors_per_page FROM orgs ORDER BY name
|
||||
SELECT id, slug, name, created_at, updated_at, require_totp, require_sso, api_token_max_days, disabled_check_types, suspended_at, suspended_reason, limit_monitors, limit_status_pages, limit_regions_per_monitor, limit_own_regions_count, limit_monitors_per_page, limit_subscribers_per_week FROM orgs ORDER BY name
|
||||
`
|
||||
|
||||
func (q *Queries) ListOrgs(ctx context.Context) ([]Org, error) {
|
||||
@@ -144,6 +147,7 @@ func (q *Queries) ListOrgs(ctx context.Context) ([]Org, error) {
|
||||
&i.LimitRegionsPerMonitor,
|
||||
&i.LimitOwnRegionsCount,
|
||||
&i.LimitMonitorsPerPage,
|
||||
&i.LimitSubscribersPerWeek,
|
||||
); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -172,7 +176,7 @@ func (q *Queries) SetOrgDisabledCheckTypes(ctx context.Context, arg SetOrgDisabl
|
||||
const updateOrgPolicy = `-- name: UpdateOrgPolicy :one
|
||||
UPDATE orgs SET require_totp = $2, require_sso = $3, api_token_max_days = $4, updated_at = now()
|
||||
WHERE id = $1
|
||||
RETURNING id, slug, name, created_at, updated_at, require_totp, require_sso, api_token_max_days, disabled_check_types, suspended_at, suspended_reason, limit_monitors, limit_status_pages, limit_regions_per_monitor, limit_own_regions_count, limit_monitors_per_page
|
||||
RETURNING id, slug, name, created_at, updated_at, require_totp, require_sso, api_token_max_days, disabled_check_types, suspended_at, suspended_reason, limit_monitors, limit_status_pages, limit_regions_per_monitor, limit_own_regions_count, limit_monitors_per_page, limit_subscribers_per_week
|
||||
`
|
||||
|
||||
type UpdateOrgPolicyParams struct {
|
||||
@@ -207,6 +211,7 @@ func (q *Queries) UpdateOrgPolicy(ctx context.Context, arg UpdateOrgPolicyParams
|
||||
&i.LimitRegionsPerMonitor,
|
||||
&i.LimitOwnRegionsCount,
|
||||
&i.LimitMonitorsPerPage,
|
||||
&i.LimitSubscribersPerWeek,
|
||||
)
|
||||
return i, err
|
||||
}
|
||||
@@ -46,15 +46,25 @@ type Querier interface {
|
||||
// System scope. Leases due rows for five minutes so a crashed sender's rows
|
||||
// come back; SKIP LOCKED lets every API replica work the outbox.
|
||||
ClaimNotifications(ctx context.Context, max int32) ([]uuid.UUID, error)
|
||||
// System scope: leases the longest waiting purge no other instance holds.
|
||||
ClaimOrgPurge(ctx context.Context) (uuid.UUID, error)
|
||||
// System scope; leased like ClaimNotifications.
|
||||
ClaimSubscriberNotifications(ctx context.Context, max int32) ([]uuid.UUID, error)
|
||||
// Shortens tokens that would outlive a newly set maximum lifetime.
|
||||
ClampAPITokenExpiry(ctx context.Context, arg ClampAPITokenExpiryParams) (int64, error)
|
||||
ClearMaintenanceTargets(ctx context.Context, windowID uuid.UUID) error
|
||||
ClearStatusPageGroups(ctx context.Context, pageID uuid.UUID) error
|
||||
ClearStatusPageMonitors(ctx context.Context, pageID uuid.UUID) error
|
||||
ConfirmPageSubscriber(ctx context.Context, id uuid.UUID) error
|
||||
CountMonitors(ctx context.Context, orgID uuid.UUID) (int64, error)
|
||||
CountOpenSupportTickets(ctx context.Context, userID uuid.UUID) (int64, error)
|
||||
CountOrgPurges(ctx context.Context) (int64, error)
|
||||
CountOwnedOrgs(ctx context.Context, userID uuid.UUID) (int64, error)
|
||||
CountOwners(ctx context.Context, orgID uuid.UUID) (int64, error)
|
||||
CountPageSubscribers(ctx context.Context, pageID uuid.UUID) (CountPageSubscribersRow, error)
|
||||
// Subscriptions the organization's pages gained since $2, confirmed or
|
||||
// not, for the weekly limit.
|
||||
CountRecentSubscribers(ctx context.Context, arg CountRecentSubscribersParams) (int64, error)
|
||||
CountRoleAssignments(ctx context.Context, roleID uuid.UUID) (int64, error)
|
||||
CountStatusPageMonitors(ctx context.Context, pageID uuid.UUID) (int64, error)
|
||||
CountStatusPages(ctx context.Context, orgID uuid.UUID) (int64, error)
|
||||
@@ -75,6 +85,7 @@ type Querier interface {
|
||||
CreateMaintenance(ctx context.Context, arg CreateMaintenanceParams) (MaintenanceWindow, error)
|
||||
CreateMonitor(ctx context.Context, arg CreateMonitorParams) (Monitor, error)
|
||||
CreateOrg(ctx context.Context, arg CreateOrgParams) (Org, error)
|
||||
CreatePageSubscriber(ctx context.Context, arg CreatePageSubscriberParams) (StatusPageSubscriber, error)
|
||||
CreatePlatformIDP(ctx context.Context, arg CreatePlatformIDPParams) (PlatformIdentityProvider, error)
|
||||
CreatePlatformIdentity(ctx context.Context, arg CreatePlatformIdentityParams) error
|
||||
CreateRegion(ctx context.Context, arg CreateRegionParams) (Region, error)
|
||||
@@ -82,6 +93,10 @@ type Querier interface {
|
||||
CreateSSOProvider(ctx context.Context, arg CreateSSOProviderParams) (SsoProvider, error)
|
||||
CreateStatusPage(ctx context.Context, arg CreateStatusPageParams) (StatusPage, error)
|
||||
CreateStatusPageGroup(ctx context.Context, arg CreateStatusPageGroupParams) (StatusPageGroup, error)
|
||||
// Creates many groups of a page at once, with ids the caller chose. Parents
|
||||
// must exist before their children are created; a nil parent id (all
|
||||
// zeros) means none.
|
||||
CreateStatusPageGroups(ctx context.Context, arg CreateStatusPageGroupsParams) error
|
||||
CreateSupportTicket(ctx context.Context, arg CreateSupportTicketParams) (SupportTicket, error)
|
||||
CreateUser(ctx context.Context, arg CreateUserParams) (User, error)
|
||||
DailyBuckets(ctx context.Context, arg DailyBucketsParams) ([]DailyBucketsRow, error)
|
||||
@@ -107,6 +122,7 @@ type Querier interface {
|
||||
DeleteMonitorRegions(ctx context.Context, monitorID uuid.UUID) error
|
||||
DeleteOrg(ctx context.Context, id uuid.UUID) (int64, error)
|
||||
DeleteOrgStorage(ctx context.Context, orgID uuid.UUID) error
|
||||
DeletePageSubscriber(ctx context.Context, arg DeletePageSubscriberParams) (int64, error)
|
||||
DeletePlatformIDP(ctx context.Context, id uuid.UUID) (int64, error)
|
||||
DeletePlatformIdentity(ctx context.Context, arg DeletePlatformIdentityParams) (int64, error)
|
||||
DeleteRecoveryCodes(ctx context.Context, userID uuid.UUID) error
|
||||
@@ -124,22 +140,21 @@ type Querier interface {
|
||||
// for two days, after which only the verify button tries again. A verified
|
||||
// one is checked daily, hourly once its record went missing.
|
||||
DomainsToCheck(ctx context.Context, arg DomainsToCheckParams) ([]DomainsToCheckRow, error)
|
||||
// The day the organization's monitors first reported, if any did.
|
||||
EarliestDataDaily(ctx context.Context, orgID uuid.UUID) (time.Time, error)
|
||||
// When the organization's monitors first reported since $2, exactly: the
|
||||
// first result of each monitor is found through its index, so the cost
|
||||
// does not grow with the days of results.
|
||||
EarliestDataRecent(ctx context.Context, arg EarliestDataRecentParams) (time.Time, error)
|
||||
EmailKeyTaken(ctx context.Context, emailKey *string) (bool, error)
|
||||
EnableTOTP(ctx context.Context, arg EnableTOTPParams) error
|
||||
EnqueueNotification(ctx context.Context, arg EnqueueNotificationParams) error
|
||||
// Queues the event of incident for every confirmed subscriber of the
|
||||
// published pages showing its monitor that take subscriptions.
|
||||
EnqueueSubscriberNotifications(ctx context.Context, arg EnqueueSubscriberNotificationsParams) (int64, error)
|
||||
// An empty name names a new region after its key and keeps an existing name.
|
||||
EnsurePlatformRegion(ctx context.Context, arg EnsurePlatformRegionParams) (Region, error)
|
||||
// Evidence of a monitor in a time span, to link results to it.
|
||||
EvidenceBetween(ctx context.Context, arg EvidenceBetweenParams) ([]EvidenceBetweenRow, error)
|
||||
ExtendOrgPurge(ctx context.Context, orgID uuid.UUID) error
|
||||
// System scope: resolves a request to a page by verified custom domain or
|
||||
// by slug.
|
||||
FindPublishedPage(ctx context.Context, arg FindPublishedPageParams) (StatusPage, error)
|
||||
FinishOrgPurge(ctx context.Context, orgID uuid.UUID) error
|
||||
// Alerts of org that fire and were repeated within the stale period.
|
||||
FiringAlerts(ctx context.Context, arg FiringAlertsParams) ([]FiringAlertsRow, error)
|
||||
// FiringAlerts newest first, a page from a keyset cursor (see paging.go)
|
||||
@@ -170,6 +185,8 @@ type Querier interface {
|
||||
GetMonitor(ctx context.Context, id uuid.UUID) (Monitor, error)
|
||||
GetOrg(ctx context.Context, id uuid.UUID) (Org, error)
|
||||
GetOrgBySlug(ctx context.Context, slug string) (Org, error)
|
||||
GetPageSubscriber(ctx context.Context, id uuid.UUID) (GetPageSubscriberRow, error)
|
||||
GetPageSubscriberByEmail(ctx context.Context, arg GetPageSubscriberByEmailParams) (StatusPageSubscriber, error)
|
||||
GetPlatformIDP(ctx context.Context, id uuid.UUID) (PlatformIdentityProvider, error)
|
||||
GetPlatformIdentity(ctx context.Context, arg GetPlatformIdentityParams) (PlatformIdentity, error)
|
||||
GetPlatformSetting(ctx context.Context, key string) ([]byte, error)
|
||||
@@ -200,7 +217,8 @@ type Querier interface {
|
||||
InsertRecoveryCodes(ctx context.Context, arg []InsertRecoveryCodesParams) (int64, error)
|
||||
InvitationOrg(ctx context.Context, hash []byte) (uuid.UUID, error)
|
||||
IsMember(ctx context.Context, arg IsMemberParams) (bool, error)
|
||||
LastFailureEvidence(ctx context.Context, arg LastFailureEvidenceParams) (LastFailureEvidenceRow, error)
|
||||
// The newest failure per monitor in region.
|
||||
LastFailureEvidence(ctx context.Context, arg LastFailureEvidenceParams) ([]LastFailureEvidenceRow, error)
|
||||
// latest_results holds the newest check result per monitor and region
|
||||
// (see migration 00055) and has row-level security.
|
||||
// Whether the newest result of each region of the monitors ids succeeded.
|
||||
@@ -249,6 +267,8 @@ type Querier interface {
|
||||
// By email, a page from a keyset cursor (see paging.go).
|
||||
ListOrgMembersPage(ctx context.Context, arg ListOrgMembersPageParams) ([]ListOrgMembersPageRow, error)
|
||||
ListOrgs(ctx context.Context) ([]Org, error)
|
||||
// The newest subscribers of a page first.
|
||||
ListPageSubscribers(ctx context.Context, arg ListPageSubscribersParams) ([]ListPageSubscribersRow, error)
|
||||
ListPendingInvitations(ctx context.Context) ([]ListPendingInvitationsRow, error)
|
||||
ListPlatformIDPs(ctx context.Context) ([]PlatformIdentityProvider, error)
|
||||
ListPlatformRegions(ctx context.Context) ([]Region, error)
|
||||
@@ -289,10 +309,14 @@ type Querier interface {
|
||||
MarkInvitationAccepted(ctx context.Context, id uuid.UUID) (int64, error)
|
||||
MarkNotificationFailed(ctx context.Context, arg MarkNotificationFailedParams) error
|
||||
MarkNotificationSent(ctx context.Context, id uuid.UUID) error
|
||||
MarkSubscriberNotificationFailed(ctx context.Context, arg MarkSubscriberNotificationFailedParams) error
|
||||
MarkSubscriberNotificationSent(ctx context.Context, id uuid.UUID) error
|
||||
// Every role a member holds, with the scope it applies to.
|
||||
MemberGrants(ctx context.Context, arg MemberGrantsParams) ([]MemberGrantsRow, error)
|
||||
MonitorAlertGroups(ctx context.Context, monitorID uuid.UUID) ([]uuid.UUID, error)
|
||||
MonitorAlertRoutes(ctx context.Context, monitorID uuid.UUID) ([]MonitorAlertRoutesRow, error)
|
||||
// System scope. Monitors by type and whether they are enabled.
|
||||
MonitorCounts(ctx context.Context) ([]MonitorCountsRow, error)
|
||||
MonitorRegions(ctx context.Context, monitorID uuid.UUID) ([]uuid.UUID, error)
|
||||
// System scope: monitors to hand to a checker of region, skipping ones that
|
||||
// were disabled, deleted or moved out of the region since dispatch. An
|
||||
@@ -307,6 +331,7 @@ type Querier interface {
|
||||
OpenIncidents(ctx context.Context, orgID uuid.UUID) ([]Incident, error)
|
||||
OrgAssignmentsExport(ctx context.Context, orgID uuid.UUID) ([]OrgAssignmentsExportRow, error)
|
||||
OrgAuditExport(ctx context.Context, orgID uuid.UUID) ([]OrgAuditExportRow, error)
|
||||
OrgCheckDataChunks(ctx context.Context) ([]string, error)
|
||||
OrgDailyStats(ctx context.Context, orgID uuid.UUID) ([]OrgDailyStatsRow, error)
|
||||
OrgIDBySlug(ctx context.Context, slug string) (uuid.UUID, error)
|
||||
OrgIncidentUpdatesExport(ctx context.Context, orgID uuid.UUID) ([]OrgIncidentUpdatesExportRow, error)
|
||||
@@ -319,6 +344,8 @@ type Querier interface {
|
||||
OrgServesOwnPages(ctx context.Context, orgID *uuid.UUID) (bool, error)
|
||||
// Organizations user owns, with their member and owner counts.
|
||||
OwnedOrgs(ctx context.Context, userID uuid.UUID) ([]OwnedOrgsRow, error)
|
||||
// System scope. Platform totals for the operator metrics.
|
||||
PlatformCounts(ctx context.Context) (PlatformCountsRow, error)
|
||||
// The public updates of incidents shown on a status page, newest first.
|
||||
PublicIncidentUpdates(ctx context.Context, ids []uuid.UUID) ([]PublicIncidentUpdatesRow, error)
|
||||
// Resolved and long silent alerts are history the monitors' results keep.
|
||||
@@ -331,9 +358,15 @@ type Querier interface {
|
||||
PurgeInvitations(ctx context.Context, expiresAt time.Time) (int64, error)
|
||||
// Delivered and given-up notifications; pending ones are still being worked.
|
||||
PurgeNotifications(ctx context.Context, createdAt time.Time) (int64, error)
|
||||
PurgeOrgCheckData(ctx context.Context, org uuid.UUID) error
|
||||
PurgeOrgCheckChunk(ctx context.Context, arg PurgeOrgCheckChunkParams) (int64, error)
|
||||
PurgeSubscriberNotifications(ctx context.Context, createdAt time.Time) (int64, error)
|
||||
// Unconfirmed subscriptions are kept for as long as they count towards the
|
||||
// weekly limit, so letting them lapse frees no room for more.
|
||||
PurgeUnconfirmedSubscribers(ctx context.Context, createdAt time.Time) (int64, error)
|
||||
// Accounts never confirmed; they belong to no organization.
|
||||
PurgeUnverifiedUsers(ctx context.Context, createdAt time.Time) (int64, error)
|
||||
// System scope: has the check data of a deleted organization purged.
|
||||
QueueOrgPurge(ctx context.Context, orgID uuid.UUID) error
|
||||
// Raw results bucketed by width since a point in time, for short ranges.
|
||||
RangeBuckets(ctx context.Context, arg RangeBucketsParams) ([]RangeBucketsRow, error)
|
||||
// The daily aggregate rebucketed by width, for ranges of months.
|
||||
@@ -379,7 +412,9 @@ type Querier interface {
|
||||
SetPlatformSetting(ctx context.Context, arg SetPlatformSettingParams) error
|
||||
// Changing the domain drops a previous verification and its checks.
|
||||
SetStatusPageDomain(ctx context.Context, arg SetStatusPageDomainParams) (StatusPage, error)
|
||||
SetStatusPageMonitorGroup(ctx context.Context, arg SetStatusPageMonitorGroupParams) error
|
||||
// Files many monitors of a page at once; a nil group id (all zeros) files
|
||||
// a monitor under none.
|
||||
SetStatusPageMonitorGroups(ctx context.Context, arg SetStatusPageMonitorGroupsParams) error
|
||||
SetSupportTicketStatus(ctx context.Context, arg SetSupportTicketStatusParams) (int64, error)
|
||||
SetUserAdmin(ctx context.Context, arg SetUserAdminParams) (int64, error)
|
||||
SetUserLocale(ctx context.Context, arg SetUserLocaleParams) error
|
||||
@@ -394,6 +429,8 @@ type Querier interface {
|
||||
StorageGet(ctx context.Context, arg StorageGetParams) (StorageGetRow, error)
|
||||
StorageList(ctx context.Context, arg StorageListParams) ([]StorageListRow, error)
|
||||
StoragePut(ctx context.Context, arg StoragePutParams) error
|
||||
// System scope: what a mail to a subscriber says.
|
||||
SubscriberNotificationDetails(ctx context.Context, ids []uuid.UUID) ([]SubscriberNotificationDetailsRow, error)
|
||||
SupportMessages(ctx context.Context, ticketID uuid.UUID) ([]SupportMessagesRow, error)
|
||||
SupportOptionsAlertGroups(ctx context.Context, orgID uuid.UUID) ([]SupportOptionsAlertGroupsRow, error)
|
||||
SupportOptionsChannels(ctx context.Context, orgID uuid.UUID) ([]SupportOptionsChannelsRow, error)
|
||||
@@ -414,6 +451,9 @@ type Querier interface {
|
||||
// Writes at most once a minute per instance; agents poll far more often.
|
||||
TouchAgentInstance(ctx context.Context, arg TouchAgentInstanceParams) error
|
||||
TouchIdentity(ctx context.Context, arg TouchIdentityParams) error
|
||||
// Keeps a pending subscription's language and link current when the
|
||||
// visitor asks again.
|
||||
TouchPendingSubscriber(ctx context.Context, arg TouchPendingSubscriberParams) error
|
||||
TouchPlatformIdentity(ctx context.Context, arg TouchPlatformIdentityParams) error
|
||||
// A verified domain whose record stayed missing past the grace period.
|
||||
UnverifyDomain(ctx context.Context, id uuid.UUID) error
|
||||
@@ -425,6 +465,8 @@ type Querier interface {
|
||||
UpdateMonitor(ctx context.Context, arg UpdateMonitorParams) (Monitor, error)
|
||||
UpdateOrgPolicy(ctx context.Context, arg UpdateOrgPolicyParams) (Org, error)
|
||||
UpdatePlatformIDP(ctx context.Context, arg UpdatePlatformIDPParams) (PlatformIdentityProvider, error)
|
||||
// Null coordinates remove the location.
|
||||
UpdateRegionLocation(ctx context.Context, arg UpdateRegionLocationParams) (int64, error)
|
||||
UpdateRole(ctx context.Context, arg UpdateRoleParams) (Role, error)
|
||||
UpdateSSOProvider(ctx context.Context, arg UpdateSSOProviderParams) (SsoProvider, error)
|
||||
UpdateStatusPage(ctx context.Context, arg UpdateStatusPageParams) (StatusPage, error)
|
||||
|
||||
@@ -1,7 +1,12 @@
|
||||
-- name: CreateRegion :one
|
||||
INSERT INTO regions (org_id, key, name) VALUES ($1, $2, $3)
|
||||
INSERT INTO regions (org_id, key, name, latitude, longitude) VALUES ($1, $2, $3, $4, $5)
|
||||
RETURNING *;
|
||||
|
||||
-- name: UpdateRegionLocation :execrows
|
||||
-- Null coordinates remove the location.
|
||||
UPDATE regions SET latitude = sqlc.narg(latitude), longitude = sqlc.narg(longitude)
|
||||
WHERE id = sqlc.arg(id);
|
||||
|
||||
-- name: EnsurePlatformRegion :one
|
||||
-- An empty name names a new region after its key and keeps an existing name.
|
||||
INSERT INTO regions (org_id, key, name)
|
||||
|
||||
@@ -125,23 +125,6 @@ FROM check_results_1d
|
||||
WHERE org_id = $1 AND monitor_id = $2
|
||||
GROUP BY 1, 2;
|
||||
|
||||
-- name: EarliestDataDaily :one
|
||||
-- The day the organization's monitors first reported, if any did.
|
||||
SELECT bucket::timestamptz AS first FROM check_results_1d WHERE org_id = $1 ORDER BY bucket LIMIT 1;
|
||||
|
||||
-- name: EarliestDataRecent :one
|
||||
-- When the organization's monitors first reported since $2, exactly: the
|
||||
-- first result of each monitor is found through its index, so the cost
|
||||
-- does not grow with the days of results.
|
||||
SELECT f.time FROM monitors m
|
||||
CROSS JOIN LATERAL (
|
||||
SELECT c.time FROM check_results c
|
||||
WHERE c.org_id = $1 AND c.monitor_id = m.id AND c.time >= $2
|
||||
ORDER BY c.time LIMIT 1
|
||||
) f
|
||||
WHERE m.org_id = $1
|
||||
ORDER BY f.time LIMIT 1;
|
||||
|
||||
-- name: FirstDataRecent :many
|
||||
-- When each region of a monitor first reported since $3, exactly. Used for
|
||||
-- data younger than the daily aggregate's resolution.
|
||||
|
||||
@@ -4,12 +4,15 @@ VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9);
|
||||
|
||||
-- name: DeleteSuccessEvidence :exec
|
||||
-- Only the latest success per monitor and region is kept.
|
||||
DELETE FROM check_evidence WHERE monitor_id = $1 AND region = $2 AND ok;
|
||||
DELETE FROM check_evidence
|
||||
WHERE region = sqlc.arg(region) AND ok AND monitor_id = ANY(sqlc.arg(monitor_ids)::uuid[]);
|
||||
|
||||
-- name: LastFailureEvidence :one
|
||||
SELECT time, coalesce(error, '')::text AS error FROM check_evidence
|
||||
WHERE monitor_id = $1 AND region = $2 AND NOT ok
|
||||
ORDER BY time DESC LIMIT 1;
|
||||
-- name: LastFailureEvidence :many
|
||||
-- The newest failure per monitor in region.
|
||||
SELECT DISTINCT ON (monitor_id) monitor_id, time, coalesce(error, '')::text AS error
|
||||
FROM check_evidence
|
||||
WHERE region = sqlc.arg(region) AND NOT ok AND monitor_id = ANY(sqlc.arg(monitor_ids)::uuid[])
|
||||
ORDER BY monitor_id, time DESC;
|
||||
|
||||
-- name: ListEvidence :many
|
||||
-- Newest first, a page from a keyset cursor (see paging.go).
|
||||
|
||||
@@ -49,9 +49,6 @@ UPDATE audit_events SET details = details - 'email' WHERE lower(details->>'email
|
||||
-- name: DeleteInvitationsForEmail :exec
|
||||
DELETE FROM invitations WHERE email = $1;
|
||||
|
||||
-- name: PurgeOrgCheckData :exec
|
||||
SELECT purge_org_check_data($1);
|
||||
|
||||
-- name: DeleteOrgStorage :exec
|
||||
DELETE FROM agent_storage WHERE owner = 'org:' || sqlc.arg(org_id)::uuid::text;
|
||||
|
||||
|
||||
@@ -47,7 +47,10 @@ RETURNING id;
|
||||
SELECT n.id, n.org_id, n.event, n.attempts,
|
||||
c.type AS channel_type, c.config AS channel_config, c.id AS channel_id,
|
||||
i.id AS incident_id, i.started_at, i.resolved_at, i.cause,
|
||||
m.id AS monitor_id, m.name AS monitor_name, m.target AS monitor_target, m.type AS monitor_type
|
||||
m.id AS monitor_id, m.name AS monitor_name, m.target AS monitor_target, m.type AS monitor_type,
|
||||
-- The names of the regions the cause names by id.
|
||||
coalesce((SELECT jsonb_object_agg(r.id::text, r.name) FROM regions r
|
||||
WHERE jsonb_typeof(i.cause) = 'object' AND i.cause ? r.id::text), '{}')::jsonb AS region_names
|
||||
FROM notifications n
|
||||
JOIN notification_channels c ON c.id = n.channel_id
|
||||
JOIN incidents i ON i.id = n.incident_id
|
||||
|
||||
@@ -15,7 +15,7 @@ SELECT count(*) FROM status_page_monitors WHERE page_id = $1;
|
||||
-- name: SetOrgLimits :one
|
||||
UPDATE orgs SET limit_monitors = sqlc.narg(monitors), limit_status_pages = sqlc.narg(status_pages),
|
||||
limit_regions_per_monitor = sqlc.narg(regions_per_monitor), limit_own_regions_count = sqlc.narg(own_regions_count),
|
||||
limit_monitors_per_page = sqlc.narg(monitors_per_page)
|
||||
limit_monitors_per_page = sqlc.narg(monitors_per_page), limit_subscribers_per_week = sqlc.narg(subscribers_per_week)
|
||||
WHERE id = sqlc.arg(id)
|
||||
RETURNING id, slug;
|
||||
|
||||
@@ -29,7 +29,7 @@ RETURNING id, email;
|
||||
-- keyset cursor.
|
||||
SELECT o.id, o.slug, o.name, o.created_at, o.suspended_at, o.suspended_reason,
|
||||
o.limit_monitors, o.limit_status_pages, o.limit_regions_per_monitor, o.limit_own_regions_count,
|
||||
o.limit_monitors_per_page,
|
||||
o.limit_monitors_per_page, o.limit_subscribers_per_week,
|
||||
(SELECT count(*) FROM monitors m WHERE m.org_id = o.id)::integer AS monitors,
|
||||
(SELECT count(*) FROM status_pages p WHERE p.org_id = o.id)::integer AS status_pages,
|
||||
coalesce(ow.id, '00000000-0000-0000-0000-000000000000'::uuid)::uuid AS owner_id,
|
||||
|
||||
@@ -0,0 +1,17 @@
|
||||
-- name: PlatformCounts :one
|
||||
-- System scope. Platform totals for the operator metrics.
|
||||
SELECT
|
||||
(SELECT count(*) FROM orgs)::bigint AS orgs,
|
||||
(SELECT count(*) FROM users)::bigint AS users,
|
||||
(SELECT count(*) FROM status_pages)::bigint AS status_pages,
|
||||
(SELECT count(*) FROM status_page_subscribers WHERE confirmed_at IS NOT NULL)::bigint AS subscribers,
|
||||
(SELECT count(*) FROM incidents WHERE resolved_at IS NULL)::bigint AS open_incidents,
|
||||
(SELECT count(*) FROM notifications WHERE status = 'pending')::bigint AS pending_notifications,
|
||||
(SELECT count(*) FROM subscriber_notifications WHERE status = 'pending')::bigint AS pending_subscriber_notifications;
|
||||
|
||||
-- name: MonitorCounts :many
|
||||
-- System scope. Monitors by type and whether they are enabled.
|
||||
SELECT type, enabled, count(*)::bigint AS monitors
|
||||
FROM monitors
|
||||
GROUP BY type, enabled
|
||||
ORDER BY type, enabled;
|
||||
@@ -0,0 +1,28 @@
|
||||
-- name: QueueOrgPurge :exec
|
||||
-- System scope: has the check data of a deleted organization purged.
|
||||
INSERT INTO org_purges (org_id) VALUES ($1) ON CONFLICT DO NOTHING;
|
||||
|
||||
-- name: ClaimOrgPurge :one
|
||||
-- System scope: leases the longest waiting purge no other instance holds.
|
||||
UPDATE org_purges SET leased_until = now() + interval '15 minutes'
|
||||
WHERE org_id = (
|
||||
SELECT org_id FROM org_purges WHERE leased_until < now()
|
||||
ORDER BY requested_at LIMIT 1
|
||||
FOR UPDATE SKIP LOCKED
|
||||
)
|
||||
RETURNING org_id;
|
||||
|
||||
-- name: ExtendOrgPurge :exec
|
||||
UPDATE org_purges SET leased_until = now() + interval '15 minutes' WHERE org_id = $1;
|
||||
|
||||
-- name: FinishOrgPurge :exec
|
||||
DELETE FROM org_purges WHERE org_id = $1;
|
||||
|
||||
-- name: CountOrgPurges :one
|
||||
SELECT count(*) FROM org_purges;
|
||||
|
||||
-- name: OrgCheckDataChunks :many
|
||||
SELECT chunk::text FROM org_check_data_chunks() AS chunk;
|
||||
|
||||
-- name: PurgeOrgCheckChunk :one
|
||||
SELECT purge_org_check_chunk(sqlc.arg(org_id)::uuid, sqlc.arg(chunk)::text)::bigint AS rows;
|
||||
@@ -1,6 +1,6 @@
|
||||
-- name: CreateStatusPage :one
|
||||
INSERT INTO status_pages (org_id, slug, title, description, published, show_component_details, domain_token, theme)
|
||||
VALUES ($1, $2, $3, $4, $5, $6, $7, $8)
|
||||
INSERT INTO status_pages (org_id, slug, title, description, published, show_component_details, domain_token, theme, subscriptions)
|
||||
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9)
|
||||
RETURNING *;
|
||||
|
||||
-- name: UpdateStatusPage :one
|
||||
@@ -11,6 +11,7 @@ SET slug = $2,
|
||||
published = $5,
|
||||
show_component_details = $6,
|
||||
theme = $7,
|
||||
subscriptions = $8,
|
||||
updated_at = now()
|
||||
WHERE id = $1
|
||||
RETURNING *;
|
||||
@@ -99,9 +100,23 @@ DELETE FROM status_page_monitors WHERE page_id = $1;
|
||||
INSERT INTO status_page_monitors (page_id, monitor_id, org_id, section, group_id, label, position)
|
||||
VALUES ($1, $2, $3, $4, $5, $6, $7);
|
||||
|
||||
-- name: SetStatusPageMonitorGroup :exec
|
||||
UPDATE status_page_monitors SET group_id = $3, section = $4
|
||||
WHERE page_id = $1 AND monitor_id = $2;
|
||||
-- name: SetStatusPageMonitorGroups :exec
|
||||
-- Files many monitors of a page at once; a nil group id (all zeros) files
|
||||
-- a monitor under none.
|
||||
UPDATE status_page_monitors spm
|
||||
SET group_id = nullif(v.group_id, '00000000-0000-0000-0000-000000000000'::uuid), section = v.section
|
||||
FROM (SELECT unnest(sqlc.arg(monitor_ids)::uuid[]) AS monitor_id, unnest(sqlc.arg(group_ids)::uuid[]) AS group_id,
|
||||
unnest(sqlc.arg(sections)::text[]) AS section) AS v
|
||||
WHERE spm.page_id = sqlc.arg(page_id) AND spm.monitor_id = v.monitor_id;
|
||||
|
||||
-- name: CreateStatusPageGroups :exec
|
||||
-- Creates many groups of a page at once, with ids the caller chose. Parents
|
||||
-- must exist before their children are created; a nil parent id (all
|
||||
-- zeros) means none.
|
||||
INSERT INTO status_page_groups (id, page_id, org_id, parent_id, name, position)
|
||||
SELECT v.id, sqlc.arg(page_id), sqlc.arg(org_id), nullif(v.parent_id, '00000000-0000-0000-0000-000000000000'::uuid), v.name, v.position
|
||||
FROM (SELECT unnest(sqlc.arg(ids)::uuid[]) AS id, unnest(sqlc.arg(parent_ids)::uuid[]) AS parent_id,
|
||||
unnest(sqlc.arg(names)::text[]) AS name, unnest(sqlc.arg(positions)::int[]) AS position) AS v;
|
||||
|
||||
-- name: ListStatusPageGroups :many
|
||||
SELECT * FROM status_page_groups
|
||||
|
||||
@@ -0,0 +1,104 @@
|
||||
-- name: CountRecentSubscribers :one
|
||||
-- Subscriptions the organization's pages gained since $2, confirmed or
|
||||
-- not, for the weekly limit.
|
||||
SELECT count(*) FROM status_page_subscribers WHERE org_id = $1 AND created_at > $2;
|
||||
|
||||
-- name: GetPageSubscriberByEmail :one
|
||||
SELECT * FROM status_page_subscribers WHERE page_id = $1 AND email = $2;
|
||||
|
||||
-- name: CreatePageSubscriber :one
|
||||
INSERT INTO status_page_subscribers (org_id, page_id, email, locale, page_url)
|
||||
VALUES ($1, $2, $3, $4, $5)
|
||||
RETURNING *;
|
||||
|
||||
-- name: TouchPendingSubscriber :exec
|
||||
-- Keeps a pending subscription's language and link current when the
|
||||
-- visitor asks again.
|
||||
UPDATE status_page_subscribers SET locale = $2, page_url = $3
|
||||
WHERE id = $1 AND confirmed_at IS NULL;
|
||||
|
||||
-- name: GetPageSubscriber :one
|
||||
SELECT s.*, p.title AS page_title FROM status_page_subscribers s
|
||||
JOIN status_pages p ON p.id = s.page_id
|
||||
WHERE s.id = $1;
|
||||
|
||||
-- name: ConfirmPageSubscriber :exec
|
||||
UPDATE status_page_subscribers SET confirmed_at = coalesce(confirmed_at, now()) WHERE id = $1;
|
||||
|
||||
-- name: DeletePageSubscriber :execrows
|
||||
DELETE FROM status_page_subscribers WHERE id = $1 AND page_id = $2;
|
||||
|
||||
-- name: ListPageSubscribers :many
|
||||
-- The newest subscribers of a page first.
|
||||
SELECT id, email, locale, created_at, confirmed_at FROM status_page_subscribers
|
||||
WHERE page_id = $1
|
||||
ORDER BY created_at DESC, id
|
||||
LIMIT sqlc.arg(max_rows);
|
||||
|
||||
-- name: CountPageSubscribers :one
|
||||
SELECT count(*) FILTER (WHERE confirmed_at IS NOT NULL)::integer AS confirmed,
|
||||
count(*) FILTER (WHERE confirmed_at IS NULL)::integer AS pending
|
||||
FROM status_page_subscribers WHERE page_id = $1;
|
||||
|
||||
-- name: EnqueueSubscriberNotifications :execrows
|
||||
-- Queues the event of incident for every confirmed subscriber of the
|
||||
-- published pages showing its monitor that take subscriptions.
|
||||
INSERT INTO subscriber_notifications (org_id, subscriber_id, incident_id, update_id, event)
|
||||
SELECT s.org_id, s.id, i.id, sqlc.narg(update_id)::uuid, sqlc.arg(event)
|
||||
FROM incidents i
|
||||
JOIN status_page_monitors spm ON spm.monitor_id = i.monitor_id
|
||||
JOIN status_pages p ON p.id = spm.page_id
|
||||
JOIN status_page_subscribers s ON s.page_id = p.id
|
||||
WHERE i.id = sqlc.arg(incident_id) AND s.confirmed_at IS NOT NULL
|
||||
AND p.published AND p.subscriptions AND p.suspended_at IS NULL
|
||||
ON CONFLICT DO NOTHING;
|
||||
|
||||
-- name: ClaimSubscriberNotifications :many
|
||||
-- System scope; leased like ClaimNotifications.
|
||||
UPDATE subscriber_notifications SET next_attempt_at = now() + interval '5 minutes'
|
||||
WHERE id IN (
|
||||
SELECT id FROM subscriber_notifications
|
||||
WHERE status = 'pending' AND next_attempt_at <= now()
|
||||
ORDER BY next_attempt_at
|
||||
LIMIT sqlc.arg(max)
|
||||
FOR UPDATE SKIP LOCKED
|
||||
)
|
||||
RETURNING id;
|
||||
|
||||
-- name: SubscriberNotificationDetails :many
|
||||
-- System scope: what a mail to a subscriber says.
|
||||
SELECT n.id, n.event, n.attempts,
|
||||
s.id AS subscriber_id, s.email, s.locale, s.page_url,
|
||||
p.id AS page_id, p.slug, p.title AS page_title, p.custom_domain, p.domain_verified_at,
|
||||
EXISTS (SELECT 1 FROM agents a WHERE a.org_id = p.org_id AND a.kind = 'statuspage' AND a.last_seen_at IS NOT NULL) AS own_servers,
|
||||
i.started_at, i.resolved_at, i.title AS incident_title,
|
||||
coalesce(nullif(spm.label, ''), m.name)::text AS component,
|
||||
coalesce(u.status, '')::text AS update_status, coalesce(st.name, '')::text AS update_status_name,
|
||||
coalesce(u.message, '')::text AS update_message
|
||||
FROM subscriber_notifications n
|
||||
JOIN status_page_subscribers s ON s.id = n.subscriber_id
|
||||
JOIN status_pages p ON p.id = s.page_id
|
||||
JOIN incidents i ON i.id = n.incident_id
|
||||
JOIN monitors m ON m.id = i.monitor_id
|
||||
LEFT JOIN status_page_monitors spm ON spm.page_id = p.id AND spm.monitor_id = m.id
|
||||
LEFT JOIN incident_updates u ON u.id = n.update_id
|
||||
LEFT JOIN incident_statuses st ON st.id = u.status_id
|
||||
WHERE n.id = ANY (sqlc.arg(ids)::uuid[]);
|
||||
|
||||
-- name: MarkSubscriberNotificationSent :exec
|
||||
UPDATE subscriber_notifications SET status = 'sent', sent_at = now(), attempts = attempts + 1, last_error = NULL
|
||||
WHERE id = $1;
|
||||
|
||||
-- name: MarkSubscriberNotificationFailed :exec
|
||||
UPDATE subscriber_notifications SET attempts = attempts + 1, last_error = sqlc.arg(last_error),
|
||||
status = CASE WHEN attempts + 1 >= sqlc.arg(max_attempts)::int THEN 'failed' ELSE 'pending' END,
|
||||
next_attempt_at = now() + make_interval(secs => sqlc.arg(retry_in_seconds)::int)
|
||||
WHERE id = sqlc.arg(id);
|
||||
|
||||
-- name: PurgeUnconfirmedSubscribers :execrows
|
||||
-- Unconfirmed subscriptions are kept for as long as they count towards the
|
||||
-- weekly limit, so letting them lapse frees no room for more.
|
||||
DELETE FROM status_page_subscribers WHERE confirmed_at IS NULL AND created_at < $1;
|
||||
|
||||
-- name: PurgeSubscriberNotifications :execrows
|
||||
DELETE FROM subscriber_notifications WHERE status IN ('sent', 'failed') AND created_at < $1;
|
||||
@@ -59,9 +59,9 @@ func (q *Queries) ClearStatusPageMonitors(ctx context.Context, pageID uuid.UUID)
|
||||
}
|
||||
|
||||
const createStatusPage = `-- name: CreateStatusPage :one
|
||||
INSERT INTO status_pages (org_id, slug, title, description, published, show_component_details, domain_token, theme)
|
||||
VALUES ($1, $2, $3, $4, $5, $6, $7, $8)
|
||||
RETURNING id, org_id, slug, title, description, published, custom_domain, domain_token, domain_verified_at, theme, created_at, updated_at, show_component_details, suspended_at, suspended_reason, domain_set_at, domain_checked_at, domain_failing_since, domain_verify_method
|
||||
INSERT INTO status_pages (org_id, slug, title, description, published, show_component_details, domain_token, theme, subscriptions)
|
||||
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9)
|
||||
RETURNING id, org_id, slug, title, description, published, custom_domain, domain_token, domain_verified_at, theme, created_at, updated_at, show_component_details, suspended_at, suspended_reason, domain_set_at, domain_checked_at, domain_failing_since, domain_verify_method, subscriptions
|
||||
`
|
||||
|
||||
type CreateStatusPageParams struct {
|
||||
@@ -73,6 +73,7 @@ type CreateStatusPageParams struct {
|
||||
ShowComponentDetails bool
|
||||
DomainToken string
|
||||
Theme []byte
|
||||
Subscriptions bool
|
||||
}
|
||||
|
||||
func (q *Queries) CreateStatusPage(ctx context.Context, arg CreateStatusPageParams) (StatusPage, error) {
|
||||
@@ -85,6 +86,7 @@ func (q *Queries) CreateStatusPage(ctx context.Context, arg CreateStatusPagePara
|
||||
arg.ShowComponentDetails,
|
||||
arg.DomainToken,
|
||||
arg.Theme,
|
||||
arg.Subscriptions,
|
||||
)
|
||||
var i StatusPage
|
||||
err := row.Scan(
|
||||
@@ -107,6 +109,7 @@ func (q *Queries) CreateStatusPage(ctx context.Context, arg CreateStatusPagePara
|
||||
&i.DomainCheckedAt,
|
||||
&i.DomainFailingSince,
|
||||
&i.DomainVerifyMethod,
|
||||
&i.Subscriptions,
|
||||
)
|
||||
return i, err
|
||||
}
|
||||
@@ -147,6 +150,37 @@ func (q *Queries) CreateStatusPageGroup(ctx context.Context, arg CreateStatusPag
|
||||
return i, err
|
||||
}
|
||||
|
||||
const createStatusPageGroups = `-- name: CreateStatusPageGroups :exec
|
||||
INSERT INTO status_page_groups (id, page_id, org_id, parent_id, name, position)
|
||||
SELECT v.id, $1, $2, nullif(v.parent_id, '00000000-0000-0000-0000-000000000000'::uuid), v.name, v.position
|
||||
FROM (SELECT unnest($3::uuid[]) AS id, unnest($4::uuid[]) AS parent_id,
|
||||
unnest($5::text[]) AS name, unnest($6::int[]) AS position) AS v
|
||||
`
|
||||
|
||||
type CreateStatusPageGroupsParams struct {
|
||||
PageID uuid.UUID
|
||||
OrgID uuid.UUID
|
||||
Ids []uuid.UUID
|
||||
ParentIds []uuid.UUID
|
||||
Names []string
|
||||
Positions []int32
|
||||
}
|
||||
|
||||
// Creates many groups of a page at once, with ids the caller chose. Parents
|
||||
// must exist before their children are created; a nil parent id (all
|
||||
// zeros) means none.
|
||||
func (q *Queries) CreateStatusPageGroups(ctx context.Context, arg CreateStatusPageGroupsParams) error {
|
||||
_, err := q.db.Exec(ctx, createStatusPageGroups,
|
||||
arg.PageID,
|
||||
arg.OrgID,
|
||||
arg.Ids,
|
||||
arg.ParentIds,
|
||||
arg.Names,
|
||||
arg.Positions,
|
||||
)
|
||||
return err
|
||||
}
|
||||
|
||||
const deleteStatusPage = `-- name: DeleteStatusPage :execrows
|
||||
DELETE FROM status_pages WHERE id = $1
|
||||
`
|
||||
@@ -242,7 +276,7 @@ func (q *Queries) DomainsToCheck(ctx context.Context, arg DomainsToCheckParams)
|
||||
}
|
||||
|
||||
const findPublishedPage = `-- name: FindPublishedPage :one
|
||||
SELECT id, org_id, slug, title, description, published, custom_domain, domain_token, domain_verified_at, theme, created_at, updated_at, show_component_details, suspended_at, suspended_reason, domain_set_at, domain_checked_at, domain_failing_since, domain_verify_method FROM status_pages
|
||||
SELECT id, org_id, slug, title, description, published, custom_domain, domain_token, domain_verified_at, theme, created_at, updated_at, show_component_details, suspended_at, suspended_reason, domain_set_at, domain_checked_at, domain_failing_since, domain_verify_method, subscriptions FROM status_pages
|
||||
WHERE published AND suspended_at IS NULL
|
||||
AND NOT EXISTS (SELECT 1 FROM orgs o WHERE o.id = status_pages.org_id AND o.suspended_at IS NOT NULL)
|
||||
AND (($1::citext IS NOT NULL AND custom_domain = $1 AND domain_verified_at IS NOT NULL)
|
||||
@@ -279,12 +313,13 @@ func (q *Queries) FindPublishedPage(ctx context.Context, arg FindPublishedPagePa
|
||||
&i.DomainCheckedAt,
|
||||
&i.DomainFailingSince,
|
||||
&i.DomainVerifyMethod,
|
||||
&i.Subscriptions,
|
||||
)
|
||||
return i, err
|
||||
}
|
||||
|
||||
const getStatusPage = `-- name: GetStatusPage :one
|
||||
SELECT id, org_id, slug, title, description, published, custom_domain, domain_token, domain_verified_at, theme, created_at, updated_at, show_component_details, suspended_at, suspended_reason, domain_set_at, domain_checked_at, domain_failing_since, domain_verify_method FROM status_pages WHERE id = $1
|
||||
SELECT id, org_id, slug, title, description, published, custom_domain, domain_token, domain_verified_at, theme, created_at, updated_at, show_component_details, suspended_at, suspended_reason, domain_set_at, domain_checked_at, domain_failing_since, domain_verify_method, subscriptions FROM status_pages WHERE id = $1
|
||||
`
|
||||
|
||||
func (q *Queries) GetStatusPage(ctx context.Context, id uuid.UUID) (StatusPage, error) {
|
||||
@@ -310,6 +345,7 @@ func (q *Queries) GetStatusPage(ctx context.Context, id uuid.UUID) (StatusPage,
|
||||
&i.DomainCheckedAt,
|
||||
&i.DomainFailingSince,
|
||||
&i.DomainVerifyMethod,
|
||||
&i.Subscriptions,
|
||||
)
|
||||
return i, err
|
||||
}
|
||||
@@ -350,7 +386,7 @@ func (q *Queries) ListStatusPageGroups(ctx context.Context, pageID uuid.UUID) ([
|
||||
}
|
||||
|
||||
const listStatusPages = `-- name: ListStatusPages :many
|
||||
SELECT id, org_id, slug, title, description, published, custom_domain, domain_token, domain_verified_at, theme, created_at, updated_at, show_component_details, suspended_at, suspended_reason, domain_set_at, domain_checked_at, domain_failing_since, domain_verify_method FROM status_pages ORDER BY title
|
||||
SELECT id, org_id, slug, title, description, published, custom_domain, domain_token, domain_verified_at, theme, created_at, updated_at, show_component_details, suspended_at, suspended_reason, domain_set_at, domain_checked_at, domain_failing_since, domain_verify_method, subscriptions FROM status_pages ORDER BY title
|
||||
`
|
||||
|
||||
func (q *Queries) ListStatusPages(ctx context.Context) ([]StatusPage, error) {
|
||||
@@ -382,6 +418,7 @@ func (q *Queries) ListStatusPages(ctx context.Context) ([]StatusPage, error) {
|
||||
&i.DomainCheckedAt,
|
||||
&i.DomainFailingSince,
|
||||
&i.DomainVerifyMethod,
|
||||
&i.Subscriptions,
|
||||
); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -520,7 +557,7 @@ UPDATE status_pages SET
|
||||
custom_domain = $1,
|
||||
updated_at = now()
|
||||
WHERE id = $2
|
||||
RETURNING id, org_id, slug, title, description, published, custom_domain, domain_token, domain_verified_at, theme, created_at, updated_at, show_component_details, suspended_at, suspended_reason, domain_set_at, domain_checked_at, domain_failing_since, domain_verify_method
|
||||
RETURNING id, org_id, slug, title, description, published, custom_domain, domain_token, domain_verified_at, theme, created_at, updated_at, show_component_details, suspended_at, suspended_reason, domain_set_at, domain_checked_at, domain_failing_since, domain_verify_method, subscriptions
|
||||
`
|
||||
|
||||
type SetStatusPageDomainParams struct {
|
||||
@@ -552,28 +589,34 @@ func (q *Queries) SetStatusPageDomain(ctx context.Context, arg SetStatusPageDoma
|
||||
&i.DomainCheckedAt,
|
||||
&i.DomainFailingSince,
|
||||
&i.DomainVerifyMethod,
|
||||
&i.Subscriptions,
|
||||
)
|
||||
return i, err
|
||||
}
|
||||
|
||||
const setStatusPageMonitorGroup = `-- name: SetStatusPageMonitorGroup :exec
|
||||
UPDATE status_page_monitors SET group_id = $3, section = $4
|
||||
WHERE page_id = $1 AND monitor_id = $2
|
||||
const setStatusPageMonitorGroups = `-- name: SetStatusPageMonitorGroups :exec
|
||||
UPDATE status_page_monitors spm
|
||||
SET group_id = nullif(v.group_id, '00000000-0000-0000-0000-000000000000'::uuid), section = v.section
|
||||
FROM (SELECT unnest($2::uuid[]) AS monitor_id, unnest($3::uuid[]) AS group_id,
|
||||
unnest($4::text[]) AS section) AS v
|
||||
WHERE spm.page_id = $1 AND spm.monitor_id = v.monitor_id
|
||||
`
|
||||
|
||||
type SetStatusPageMonitorGroupParams struct {
|
||||
PageID uuid.UUID
|
||||
MonitorID uuid.UUID
|
||||
GroupID *uuid.UUID
|
||||
Section string
|
||||
type SetStatusPageMonitorGroupsParams struct {
|
||||
PageID uuid.UUID
|
||||
MonitorIds []uuid.UUID
|
||||
GroupIds []uuid.UUID
|
||||
Sections []string
|
||||
}
|
||||
|
||||
func (q *Queries) SetStatusPageMonitorGroup(ctx context.Context, arg SetStatusPageMonitorGroupParams) error {
|
||||
_, err := q.db.Exec(ctx, setStatusPageMonitorGroup,
|
||||
// Files many monitors of a page at once; a nil group id (all zeros) files
|
||||
// a monitor under none.
|
||||
func (q *Queries) SetStatusPageMonitorGroups(ctx context.Context, arg SetStatusPageMonitorGroupsParams) error {
|
||||
_, err := q.db.Exec(ctx, setStatusPageMonitorGroups,
|
||||
arg.PageID,
|
||||
arg.MonitorID,
|
||||
arg.GroupID,
|
||||
arg.Section,
|
||||
arg.MonitorIds,
|
||||
arg.GroupIds,
|
||||
arg.Sections,
|
||||
)
|
||||
return err
|
||||
}
|
||||
@@ -652,9 +695,10 @@ SET slug = $2,
|
||||
published = $5,
|
||||
show_component_details = $6,
|
||||
theme = $7,
|
||||
subscriptions = $8,
|
||||
updated_at = now()
|
||||
WHERE id = $1
|
||||
RETURNING id, org_id, slug, title, description, published, custom_domain, domain_token, domain_verified_at, theme, created_at, updated_at, show_component_details, suspended_at, suspended_reason, domain_set_at, domain_checked_at, domain_failing_since, domain_verify_method
|
||||
RETURNING id, org_id, slug, title, description, published, custom_domain, domain_token, domain_verified_at, theme, created_at, updated_at, show_component_details, suspended_at, suspended_reason, domain_set_at, domain_checked_at, domain_failing_since, domain_verify_method, subscriptions
|
||||
`
|
||||
|
||||
type UpdateStatusPageParams struct {
|
||||
@@ -665,6 +709,7 @@ type UpdateStatusPageParams struct {
|
||||
Published bool
|
||||
ShowComponentDetails bool
|
||||
Theme []byte
|
||||
Subscriptions bool
|
||||
}
|
||||
|
||||
func (q *Queries) UpdateStatusPage(ctx context.Context, arg UpdateStatusPageParams) (StatusPage, error) {
|
||||
@@ -676,6 +721,7 @@ func (q *Queries) UpdateStatusPage(ctx context.Context, arg UpdateStatusPagePara
|
||||
arg.Published,
|
||||
arg.ShowComponentDetails,
|
||||
arg.Theme,
|
||||
arg.Subscriptions,
|
||||
)
|
||||
var i StatusPage
|
||||
err := row.Scan(
|
||||
@@ -698,6 +744,7 @@ func (q *Queries) UpdateStatusPage(ctx context.Context, arg UpdateStatusPagePara
|
||||
&i.DomainCheckedAt,
|
||||
&i.DomainFailingSince,
|
||||
&i.DomainVerifyMethod,
|
||||
&i.Subscriptions,
|
||||
)
|
||||
return i, err
|
||||
}
|
||||
|
||||
Loaded 100 of 127 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user