Compare commits
33
Commits
No files matched your search
@@ -44,6 +44,20 @@ UPTIME_TEST_REDIS_URL=redis://localhost:6379/15
|
||||
# Reverse proxies allowed to set X-Forwarded-For (comma-separated IPs/CIDRs).
|
||||
# UPTIME_TRUSTED_PROXIES=10.0.0.0/8
|
||||
|
||||
# How long a region with monitors may have no live checker before the
|
||||
# platform's admins (platform regions) or the organization's owners (own
|
||||
# regions) get an email; 0 switches it off.
|
||||
# UPTIME_REGION_ALERT_AFTER=5m
|
||||
|
||||
# Status page servers ask before ordering a certificate for a custom domain.
|
||||
# New orders (not renewals) are limited per organization and day, per hour
|
||||
# for all servers sharing an ACME account (the platform's, or one
|
||||
# organization's), and per domain and day. Let's Encrypt allows 300 new
|
||||
# orders per account in 3 hours.
|
||||
# UPTIME_CERTS_PER_ORG_PER_DAY=20
|
||||
# UPTIME_CERTS_PER_HOUR=30
|
||||
# UPTIME_CERTS_PER_NAME_PER_DAY=5
|
||||
|
||||
# Data retention (0 keeps forever). Raw results feed charts up to 24h, the
|
||||
# hourly aggregate 7d and 30d, the daily aggregate up to a year; resolved
|
||||
# incidents follow the daily aggregate.
|
||||
|
||||
@@ -83,6 +83,41 @@ jobs:
|
||||
curl -fsS -o /dev/null -X POST -H "Authorization: token $TOKEN" \
|
||||
-F "attachment=@$f" "$api/releases/$id/assets?name=$(basename "$f")"
|
||||
done
|
||||
# The ci workflow builds the images of this tag after lint and tests,
|
||||
# which takes longer than this job. A chart published before them makes
|
||||
# clusters that follow the chart repository roll out a release whose
|
||||
# images do not exist yet (ImagePullBackOff in the migrate hook).
|
||||
- name: Wait for the images
|
||||
env:
|
||||
PACKAGE_TOKEN: ${{ secrets.PACKAGE_TOKEN }}
|
||||
run: |
|
||||
set -eu
|
||||
if [ -z "$PACKAGE_TOKEN" ]; then
|
||||
echo "::warning::PACKAGE_TOKEN is not set; not waiting for the images."
|
||||
exit 0
|
||||
fi
|
||||
host="${GITHUB_SERVER_URL#*://}"
|
||||
owner="$(printf '%s' "${GITHUB_REPOSITORY%/*}" | tr 'A-Z' 'a-z')"
|
||||
tag="${GITHUB_REF_NAME#v}"
|
||||
accept="application/vnd.oci.image.index.v1+json,application/vnd.oci.image.manifest.v1+json,application/vnd.docker.distribution.manifest.list.v2+json,application/vnd.docker.distribution.manifest.v2+json"
|
||||
deadline=$(( $(date +%s) + 90 * 60 ))
|
||||
for repo in uptimesebi uptimesebi-checker uptimesebi-statuspage; do
|
||||
until
|
||||
token="$(curl -fsS --user "$GITHUB_ACTOR:$PACKAGE_TOKEN" \
|
||||
"$GITHUB_SERVER_URL/v2/token?service=container_registry&scope=repository:$owner/$repo:pull" \
|
||||
| sed -n 's/.*"token":"\([^"]*\)".*/\1/p')"
|
||||
curl -fsS -o /dev/null -I -H "Authorization: Bearer $token" -H "Accept: $accept" \
|
||||
"$GITHUB_SERVER_URL/v2/$owner/$repo/manifests/$tag"
|
||||
do
|
||||
if [ "$(date +%s)" -ge "$deadline" ]; then
|
||||
echo "::error::$host/$owner/$repo:$tag did not appear within 90 minutes; the chart is not published."
|
||||
exit 1
|
||||
fi
|
||||
echo "waiting for $host/$owner/$repo:$tag"
|
||||
sleep 30
|
||||
done
|
||||
echo "$host/$owner/$repo:$tag is there"
|
||||
done
|
||||
# helm repo add uptimesebi <server>/api/packages/<owner>/helm
|
||||
- name: Publish Helm chart
|
||||
env:
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
|
||||
[](https://git.zb-server.de/ZB-Server/uptimesebi/actions?workflow=ci.yaml) · License: AGPL-3.0-only
|
||||
|
||||
UptimeSebi monitors websites, APIs and services from several regions and tells you when they are down, without false alarms from a single checker losing its network: a monitor only counts as down when **every** region it is checked from fails. It publishes status pages that stay online even while UptimeSebi itself is not, and it can run entirely on your own infrastructure.
|
||||
UptimeSebi monitors websites, APIs and services from several regions and tells you when they are down, without false alarms from a single checker losing its network: a monitor only counts as down when **every** region it is checked from fails. A region whose checkers are gone is left out rather than holding the monitor up, and its admins are told. It publishes status pages that stay online even while UptimeSebi itself is not, and it can run entirely on your own infrastructure.
|
||||
|
||||
It is built for teams and hosting providers: organizations with members, roles and SSO, run either as a shared cloud service or self-hosted.
|
||||
|
||||
@@ -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.
|
||||
@@ -102,6 +102,8 @@ docker run -d --restart unless-stopped -e UPTIME_API_URL=https://uptime.example.
|
||||
git.zb-server.de/zb-server/uptimesebi-checker:latest
|
||||
```
|
||||
|
||||
Agents keep one WebSocket open to the API (`/agent/v1/stream`) and send their requests over it. Over it the API also tells status page servers at once when a page changed, e.g. when a monitor fails or the page is edited. A proxy in front of the API must pass WebSocket upgrades. While the WebSocket is down, agents fall back to plain HTTPS requests, and pages are refreshed every 30 seconds as before.
|
||||
|
||||
The quickest way onto a Linux host with Docker is the install script your platform serves, with its address filled in. It checks the host, writes `/opt/uptimesebi/<kind>/compose.yaml` and `.env` (the token readable only by root) and starts the agent:
|
||||
|
||||
```sh
|
||||
@@ -159,7 +161,7 @@ Run as many API, checker and status page instances as you need; they share no lo
|
||||
| Hybrid | hosted | at the customer | at the customer |
|
||||
| Self-hosted | at the customer | at the customer | at the customer |
|
||||
|
||||
Checkers and status page servers reach the API over HTTPS and never the database, so they can run in other networks.
|
||||
Checkers and status page servers reach the API over HTTPS and never the database, so they can run in other networks. Status page servers fetch every page they serve every five minutes, so each one is cached before its first visit and keeps being served while the API is unreachable. Once one of an organization's own status page servers has connected, only its own servers serve its pages; the platform's no longer do.
|
||||
|
||||
## Usage
|
||||
|
||||
|
||||
@@ -89,9 +89,12 @@ func run(log *slog.Logger, level *slog.LevelVar, args []string) error {
|
||||
health.Register(r)
|
||||
r.StaticFS("/static", web.Static())
|
||||
srv.Mount(r)
|
||||
srv.EndLongPollsOn(health.Draining())
|
||||
go srv.RunScheduler(ctx)
|
||||
go srv.RunNotifier(ctx)
|
||||
go srv.RunHousekeeping(ctx)
|
||||
go srv.RunRegionWatch(ctx)
|
||||
go srv.RunDomainWatch(ctx)
|
||||
go srv.RunHeartbeats(ctx)
|
||||
|
||||
return platform.Serve(ctx, log, platform.NewHTTPServer(cfg.Listen, r), health, 5*time.Second, cfg.ShutdownTimeout)
|
||||
|
||||
@@ -65,6 +65,7 @@ func run(log *slog.Logger, level *slog.LevelVar) error {
|
||||
log = log.With("region", hello.Region, "agent", hello.Name, "instance", instance)
|
||||
log.Info("connected to api")
|
||||
|
||||
client.UseStream(ctx, agentapi.StreamOptions{Log: log})
|
||||
runner := checker.New(client, cfg.Concurrency, log)
|
||||
health := platform.NewHealth(map[string]platform.Probe{"api": runner.Healthy})
|
||||
r := platform.NewRouter(log)
|
||||
|
||||
@@ -77,6 +77,8 @@ func run(log *slog.Logger, level *slog.LevelVar) error {
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
// Pages are told about changes over the stream and fetched through it.
|
||||
client.UseStream(ctx, agentapi.StreamOptions{Log: log, OnEvent: pages.OnEvent})
|
||||
apiProbe := func(ctx context.Context) error { _, err := client.Hello(ctx); return err }
|
||||
health := platform.NewHealth(map[string]platform.Probe{
|
||||
"pages": func(ctx context.Context) error { return pages.Ready(ctx, apiProbe) },
|
||||
@@ -119,6 +121,7 @@ func certificates(ctx context.Context, cfg config.StatusPage, client *agentapi.C
|
||||
magic = certmagic.New(cache, certmagic.Config{
|
||||
Storage: statuspage.NewCertStorage(client, certDir),
|
||||
OnDemand: &certmagic.OnDemandConfig{DecisionFunc: pages.AllowCertificate},
|
||||
OnEvent: pages.OnCertEvent,
|
||||
Logger: zap.NewNop(),
|
||||
})
|
||||
issuer := certmagic.NewACMEIssuer(magic, certmagic.ACMEIssuer{CA: cfg.ACMECA, Email: cfg.ACMEEmail, Agreed: true})
|
||||
|
||||
@@ -170,3 +170,53 @@ $secret being the chart secret to read values from.
|
||||
medium: Memory
|
||||
sizeLimit: 64Mi
|
||||
{{- end -}}
|
||||
|
||||
{{/*
|
||||
HTTPS redirect of an ingress: include with (dict "root" . "ingress" <values>
|
||||
"name" <ingress name>). Traefik needs a redirectScheme middleware, other
|
||||
controllers an annotation. */}}
|
||||
{{- define "uptimesebi.redirects" -}}
|
||||
{{- $i := .ingress -}}
|
||||
{{- if and $i.tls.enabled $i.tls.redirect }}true{{ end -}}
|
||||
{{- end -}}
|
||||
|
||||
{{- define "uptimesebi.traefik" -}}
|
||||
{{- $i := .ingress -}}
|
||||
{{- if contains "traefik" ($i.className | default "") -}}true
|
||||
{{- else if and (not $i.className) (.root.Capabilities.APIVersions.Has "traefik.io/v1alpha1/Middleware") -}}true
|
||||
{{- end -}}
|
||||
{{- end -}}
|
||||
|
||||
{{/* the ingress's annotations, with those the redirect needs. */}}
|
||||
{{- define "uptimesebi.ingressAnnotations" -}}
|
||||
{{- $a := deepCopy (.ingress.annotations | default dict) -}}
|
||||
{{- if include "uptimesebi.redirects" . -}}
|
||||
{{- if include "uptimesebi.traefik" . -}}
|
||||
{{- $key := "traefik.ingress.kubernetes.io/router.middlewares" -}}
|
||||
{{- $mw := printf "%s-%s-https@kubernetescrd" .root.Release.Namespace .name -}}
|
||||
{{- with get $a $key }}{{ $mw = printf "%s,%s" $mw . }}{{ end -}}
|
||||
{{- $_ := set $a $key $mw -}}
|
||||
{{- else -}}
|
||||
{{- $_ := set $a "nginx.ingress.kubernetes.io/ssl-redirect" "true" -}}
|
||||
{{- $_ := set $a "haproxy.org/ssl-redirect" "true" -}}
|
||||
{{- end -}}
|
||||
{{- end -}}
|
||||
{{- with $a }}{{ toYaml . }}{{ end -}}
|
||||
{{- end -}}
|
||||
|
||||
{{/* the Traefik middleware the redirect uses, if it needs one. */}}
|
||||
{{- define "uptimesebi.redirectMiddleware" -}}
|
||||
{{- if and (include "uptimesebi.redirects" .) (include "uptimesebi.traefik" .) }}
|
||||
---
|
||||
apiVersion: traefik.io/v1alpha1
|
||||
kind: Middleware
|
||||
metadata:
|
||||
name: {{ .name }}-https
|
||||
labels:
|
||||
{{- include "uptimesebi.labels" .root | nindent 4 }}
|
||||
spec:
|
||||
redirectScheme:
|
||||
scheme: https
|
||||
permanent: true
|
||||
{{- end }}
|
||||
{{- end -}}
|
||||
@@ -8,6 +8,15 @@ metadata:
|
||||
app.kubernetes.io/component: api
|
||||
spec:
|
||||
replicas: {{ .Values.api.replicas }}
|
||||
# Roll one pod at a time without ever having fewer ready than wanted;
|
||||
# a new pod serves a few seconds before an old one goes, so the ingress
|
||||
# has picked it up.
|
||||
strategy:
|
||||
type: RollingUpdate
|
||||
rollingUpdate:
|
||||
maxUnavailable: 0
|
||||
maxSurge: 1
|
||||
minReadySeconds: 5
|
||||
selector:
|
||||
matchLabels:
|
||||
{{- include "uptimesebi.selector" (list . "api") | nindent 6 }}
|
||||
|
||||
@@ -1,13 +1,14 @@
|
||||
{{- if .Values.ingress.enabled }}
|
||||
{{- $ing := dict "root" . "ingress" .Values.ingress "name" (include "uptimesebi.fullname" .) }}
|
||||
apiVersion: networking.k8s.io/v1
|
||||
kind: Ingress
|
||||
metadata:
|
||||
name: {{ include "uptimesebi.fullname" . }}
|
||||
labels:
|
||||
{{- include "uptimesebi.labels" . | nindent 4 }}
|
||||
{{- with .Values.ingress.annotations }}
|
||||
{{- with include "uptimesebi.ingressAnnotations" $ing }}
|
||||
annotations:
|
||||
{{- toYaml . | nindent 4 }}
|
||||
{{- . | nindent 4 }}
|
||||
{{- end }}
|
||||
spec:
|
||||
{{- with .Values.ingress.className }}
|
||||
@@ -29,4 +30,5 @@ spec:
|
||||
name: {{ include "uptimesebi.fullname" . }}-api
|
||||
port:
|
||||
name: http
|
||||
{{- include "uptimesebi.redirectMiddleware" $ing }}
|
||||
{{- end }}
|
||||
@@ -9,6 +9,15 @@ metadata:
|
||||
app.kubernetes.io/component: statuspage
|
||||
spec:
|
||||
replicas: {{ .Values.statuspage.replicas }}
|
||||
# Roll one pod at a time without ever having fewer ready than wanted;
|
||||
# a new pod serves a few seconds before an old one goes, so the ingress
|
||||
# has picked it up.
|
||||
strategy:
|
||||
type: RollingUpdate
|
||||
rollingUpdate:
|
||||
maxUnavailable: 0
|
||||
maxSurge: 1
|
||||
minReadySeconds: 5
|
||||
selector:
|
||||
matchLabels:
|
||||
{{- include "uptimesebi.selector" (list . "statuspage") | nindent 6 }}
|
||||
@@ -118,6 +127,7 @@ spec:
|
||||
{{- include "uptimesebi.selector" (list . "statuspage") | nindent 6 }}
|
||||
{{- end }}
|
||||
{{- if .Values.statuspage.ingress.enabled }}
|
||||
{{- $ing := dict "root" . "ingress" .Values.statuspage.ingress "name" $name }}
|
||||
---
|
||||
apiVersion: networking.k8s.io/v1
|
||||
kind: Ingress
|
||||
@@ -125,9 +135,9 @@ metadata:
|
||||
name: {{ $name }}
|
||||
labels:
|
||||
{{- include "uptimesebi.labels" . | nindent 4 }}
|
||||
{{- with .Values.statuspage.ingress.annotations }}
|
||||
{{- with include "uptimesebi.ingressAnnotations" $ing }}
|
||||
annotations:
|
||||
{{- toYaml . | nindent 4 }}
|
||||
{{- . | nindent 4 }}
|
||||
{{- end }}
|
||||
spec:
|
||||
{{- with .Values.statuspage.ingress.className }}
|
||||
@@ -152,5 +162,6 @@ spec:
|
||||
port:
|
||||
name: http
|
||||
{{- end }}
|
||||
{{- include "uptimesebi.redirectMiddleware" $ing }}
|
||||
{{- end }}
|
||||
{{- end }}
|
||||
@@ -144,6 +144,9 @@ ingress:
|
||||
enabled: false
|
||||
# Secret with the certificate, e.g. made by cert-manager.
|
||||
secretName: ""
|
||||
# Send plain HTTP to HTTPS: through a redirectScheme middleware with
|
||||
# Traefik, by annotation with ingress-nginx and HAProxy.
|
||||
redirect: true
|
||||
|
||||
# -- Checker --
|
||||
# A checker in the cluster, for checks from the cluster's region. Create
|
||||
@@ -197,6 +200,8 @@ statuspage:
|
||||
tls:
|
||||
enabled: false
|
||||
secretName: ""
|
||||
# Send plain HTTP to HTTPS, as for the console.
|
||||
redirect: true
|
||||
resources:
|
||||
requests:
|
||||
cpu: 50m
|
||||
|
||||
@@ -34,6 +34,7 @@ require (
|
||||
golang.org/x/crypto/x509roots/fallback v0.0.0-20261123165210-6c21c5864259
|
||||
golang.org/x/net v0.63.0
|
||||
golang.org/x/oauth2 v0.38.0
|
||||
golang.org/x/sync v0.25.0
|
||||
golang.org/x/text v0.44.0
|
||||
google.golang.org/grpc v1.85.0
|
||||
layeh.com/radius v0.0.0-20231213012653-1006025d24f8
|
||||
@@ -116,7 +117,6 @@ require (
|
||||
golang.org/x/arch v0.22.0 // indirect
|
||||
golang.org/x/exp v0.0.0-20261109185158-a52e3aef5920 // indirect
|
||||
golang.org/x/mod v0.43.0 // indirect
|
||||
golang.org/x/sync v0.25.0 // indirect
|
||||
golang.org/x/sys v0.50.0 // indirect
|
||||
golang.org/x/tools v0.52.1-0.20261106145633-d407941a339a // indirect
|
||||
google.golang.org/genproto/googleapis/rpc v0.0.0-20261110000943-09e21b237f2c // indirect
|
||||
|
||||
@@ -125,6 +125,11 @@ func (c *Client) WithHTTPClient(hc *http.Client) *Client {
|
||||
func (c *Client) Instance() uuid.UUID { return c.instance }
|
||||
|
||||
func (c *Client) do(ctx context.Context, method, path string, in, out any) error {
|
||||
return c.doWith(ctx, method, path, nil, in, out)
|
||||
}
|
||||
|
||||
// doWith is do with extra request headers.
|
||||
func (c *Client) doWith(ctx context.Context, method, path string, header http.Header, in, out any) error {
|
||||
var body io.Reader
|
||||
if in != nil {
|
||||
b, err := json.Marshal(in)
|
||||
@@ -142,6 +147,9 @@ func (c *Client) do(ctx context.Context, method, path string, in, out any) error
|
||||
req.Header.Set(VersionHeader, fmt.Sprint(Version))
|
||||
req.Header.Set(InstanceHeader, c.instance.String())
|
||||
req.Header.Set(ReleaseHeader, c.release)
|
||||
for k, v := range header {
|
||||
req.Header[k] = v
|
||||
}
|
||||
resp, err := c.hc.Do(req)
|
||||
if err != nil {
|
||||
return err
|
||||
@@ -152,6 +160,12 @@ func (c *Client) do(ctx context.Context, method, path string, in, out any) error
|
||||
return ErrUnauthorized
|
||||
case resp.StatusCode == http.StatusNotFound:
|
||||
return ErrNotFound
|
||||
case resp.StatusCode == http.StatusNotModified:
|
||||
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))
|
||||
|
||||
@@ -2,6 +2,9 @@ package agentapi
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"net/http"
|
||||
"net/url"
|
||||
@@ -85,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"`
|
||||
@@ -112,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"`
|
||||
@@ -348,19 +355,57 @@ func (s PageSnapshot) LegalDocByKind(kind string) (LegalDoc, bool) {
|
||||
return LegalDoc{}, false
|
||||
}
|
||||
|
||||
// PageRef names a page a status page server serves: by Slug on its own
|
||||
// hosts and, when Host is set, by that verified custom domain.
|
||||
type PageRef struct {
|
||||
Slug string `json:"slug"`
|
||||
Host string `json:"host,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"`
|
||||
}
|
||||
err := c.do(ctx, http.MethodGet, "/pages/index", nil, &out)
|
||||
return out.Pages, err
|
||||
}
|
||||
|
||||
// ErrNotFound means no published page matches.
|
||||
var ErrNotFound = errors.New("agentapi: not found")
|
||||
|
||||
// ErrNotModified means the page still matches the checksum sent.
|
||||
var ErrNotModified = errors.New("agentapi: not modified")
|
||||
|
||||
// Checksum identifies the content of s, leaving out when it was generated.
|
||||
func (s PageSnapshot) Checksum() string {
|
||||
s.GeneratedAt = time.Time{}
|
||||
raw, _ := json.Marshal(s)
|
||||
sum := sha256.Sum256(raw)
|
||||
return hex.EncodeToString(sum[:])
|
||||
}
|
||||
|
||||
// Page fetches the published page for a custom domain host, or for slug if
|
||||
// host is empty.
|
||||
func (c *Client) Page(ctx context.Context, host, slug string) (PageSnapshot, error) {
|
||||
return c.PageIfChanged(ctx, host, slug, "")
|
||||
}
|
||||
|
||||
// PageIfChanged is Page, but answers ErrNotModified instead of sending the
|
||||
// page again when it still has the checksum given.
|
||||
func (c *Client) PageIfChanged(ctx context.Context, host, slug, checksum string) (PageSnapshot, error) {
|
||||
q := url.Values{}
|
||||
if host != "" {
|
||||
q.Set("host", host)
|
||||
} else {
|
||||
q.Set("slug", slug)
|
||||
}
|
||||
var h http.Header
|
||||
if checksum != "" {
|
||||
h = http.Header{"If-None-Match": {`"` + checksum + `"`}}
|
||||
}
|
||||
var p PageSnapshot
|
||||
err := c.do(ctx, http.MethodGet, "/pages?"+q.Encode(), nil, &p)
|
||||
err := c.doWith(ctx, http.MethodGet, "/pages?"+q.Encode(), h, nil, &p)
|
||||
return p, err
|
||||
}
|
||||
@@ -106,3 +106,13 @@ func (c *Client) StorageUnlock(ctx context.Context, name string) error {
|
||||
_, err := c.raw(ctx, http.MethodDelete, "/storage/lock"+keyQuery("name", name), nil)
|
||||
return err
|
||||
}
|
||||
|
||||
// ErrRateLimited means the API refused because a limit was reached.
|
||||
var ErrRateLimited = errors.New("agentapi: rate limited")
|
||||
|
||||
// AllowCertificate asks whether this server may order a new certificate
|
||||
// for name. ErrNotFound means it serves no page there, ErrRateLimited that
|
||||
// a limit on orders was reached.
|
||||
func (c *Client) AllowCertificate(ctx context.Context, name string) error {
|
||||
return c.do(ctx, http.MethodPost, "/certificates", map[string]string{"name": name}, nil)
|
||||
}
|
||||
@@ -0,0 +1,363 @@
|
||||
package agentapi
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"log/slog"
|
||||
"net/http"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/coder/websocket"
|
||||
)
|
||||
|
||||
// The stream is one WebSocket from an agent to the API. It carries the
|
||||
// agent's requests, which the API answers as if they had come over HTTP,
|
||||
// and events the API sends unasked, such as which status pages changed.
|
||||
// Agents fall back to plain HTTP while it is down, and an API without it
|
||||
// is asked again only now and then.
|
||||
const (
|
||||
// Prefix is the path of the agent API.
|
||||
Prefix = "/agent/v1"
|
||||
// StreamPath is where agents open the stream, below Prefix.
|
||||
StreamPath = "/stream"
|
||||
// MaxFrame bounds a frame read from the stream.
|
||||
MaxFrame = 64 << 20
|
||||
// EventPages lists pages that changed, as a PagesEvent.
|
||||
EventPages = "pages"
|
||||
)
|
||||
|
||||
// Frame is the header of a stream message. A message is the header as
|
||||
// JSON, a newline and the body. Requests carry ID, Method and Path, replies
|
||||
// the request's ID and Status, events Event; Cancel withdraws a request.
|
||||
type Frame struct {
|
||||
ID uint64 `json:"id,omitempty"`
|
||||
Method string `json:"method,omitempty"`
|
||||
// Path is below Prefix and includes the query.
|
||||
Path string `json:"path,omitempty"`
|
||||
Status int `json:"status,omitempty"`
|
||||
Header http.Header `json:"header,omitempty"`
|
||||
Cancel bool `json:"cancel,omitempty"`
|
||||
Event string `json:"event,omitempty"`
|
||||
}
|
||||
|
||||
// PagesEvent names status pages that changed and should be fetched again.
|
||||
type PagesEvent struct {
|
||||
Pages []PageRef `json:"pages"`
|
||||
}
|
||||
|
||||
// EncodeFrame builds a stream message.
|
||||
func EncodeFrame(f Frame, body []byte) []byte {
|
||||
head, _ := json.Marshal(f)
|
||||
out := make([]byte, 0, len(head)+1+len(body))
|
||||
return append(append(append(out, head...), '\n'), body...)
|
||||
}
|
||||
|
||||
// DecodeFrame splits a stream message into its header and body.
|
||||
func DecodeFrame(msg []byte) (Frame, []byte, error) {
|
||||
var f Frame
|
||||
head, body, ok := bytes.Cut(msg, []byte{'\n'})
|
||||
if !ok {
|
||||
return f, nil, errors.New("agentapi: frame without header")
|
||||
}
|
||||
err := json.Unmarshal(head, &f)
|
||||
return f, body, err
|
||||
}
|
||||
|
||||
// StreamOptions configure UseStream.
|
||||
type StreamOptions struct {
|
||||
Log *slog.Logger
|
||||
// OnEvent receives the events the API sends. It runs on the stream's
|
||||
// reader and must not block.
|
||||
OnEvent func(event string, body []byte)
|
||||
}
|
||||
|
||||
const (
|
||||
pingEvery = 20 * time.Second
|
||||
pingTimeout = 15 * time.Second
|
||||
// unsupportedRetry is how long an API without the stream is not asked
|
||||
// again.
|
||||
unsupportedRetry = 5 * time.Minute
|
||||
)
|
||||
|
||||
var (
|
||||
errStreamClosed = errors.New("agentapi: stream closed")
|
||||
errStreamUnsupported = errors.New("agentapi: API has no stream")
|
||||
)
|
||||
|
||||
// UseStream sends the client's requests over a WebSocket to the API from
|
||||
// now on, while it is open, and keeps reopening it until ctx ends. Call it
|
||||
// before the client is used concurrently.
|
||||
func (c *Client) UseStream(ctx context.Context, o StreamOptions) {
|
||||
if o.Log == nil {
|
||||
o.Log = slog.New(slog.DiscardHandler)
|
||||
}
|
||||
fallback := c.hc.Transport
|
||||
if fallback == nil {
|
||||
fallback = http.DefaultTransport
|
||||
}
|
||||
// The handshake runs over the plain client; a client timeout would end
|
||||
// the stream, so only the context bounds it.
|
||||
dial := *c.hc
|
||||
dial.Timeout = 0
|
||||
t := &streamTransport{c: c, fallback: fallback, dial: &dial, opts: o}
|
||||
hc := *c.hc
|
||||
hc.Transport = t
|
||||
c.hc = &hc
|
||||
go t.run(ctx)
|
||||
}
|
||||
|
||||
// Streaming reports whether requests currently go over the stream.
|
||||
func (c *Client) Streaming() bool {
|
||||
t, ok := c.hc.Transport.(*streamTransport)
|
||||
return ok && t.current() != nil
|
||||
}
|
||||
|
||||
// streamTransport sends requests over the stream while it is open and over
|
||||
// fallback otherwise.
|
||||
type streamTransport struct {
|
||||
c *Client
|
||||
fallback http.RoundTripper
|
||||
dial *http.Client
|
||||
opts StreamOptions
|
||||
|
||||
mu sync.Mutex
|
||||
conn *streamConn
|
||||
}
|
||||
|
||||
func (t *streamTransport) current() *streamConn {
|
||||
t.mu.Lock()
|
||||
defer t.mu.Unlock()
|
||||
return t.conn
|
||||
}
|
||||
|
||||
func (t *streamTransport) set(sc *streamConn) {
|
||||
t.mu.Lock()
|
||||
t.conn = sc
|
||||
t.mu.Unlock()
|
||||
}
|
||||
|
||||
// RoundTrip implements http.RoundTripper.
|
||||
func (t *streamTransport) RoundTrip(req *http.Request) (*http.Response, error) {
|
||||
sc := t.current()
|
||||
path, below := strings.CutPrefix(req.URL.Path, Prefix)
|
||||
if sc == nil || !below || path == StreamPath {
|
||||
return t.fallback.RoundTrip(req)
|
||||
}
|
||||
var body []byte
|
||||
if req.Body != nil {
|
||||
var err error
|
||||
body, err = io.ReadAll(req.Body)
|
||||
_ = req.Body.Close()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
header := req.Header.Clone()
|
||||
// The stream is authenticated once, as the agent that opened it.
|
||||
for _, k := range []string{"Authorization", VersionHeader, InstanceHeader, ReleaseHeader} {
|
||||
header.Del(k)
|
||||
}
|
||||
if req.URL.RawQuery != "" {
|
||||
path += "?" + req.URL.RawQuery
|
||||
}
|
||||
f, rbody, sent, err := sc.roundTrip(req.Context(), Frame{Method: req.Method, Path: path, Header: header}, body)
|
||||
if err != nil {
|
||||
if !sent && req.Context().Err() == nil {
|
||||
// Never reached the API: plain HTTP can still deliver it.
|
||||
retry := req.Clone(req.Context())
|
||||
retry.Body = io.NopCloser(bytes.NewReader(body))
|
||||
return t.fallback.RoundTrip(retry)
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
if f.Header == nil {
|
||||
f.Header = http.Header{}
|
||||
}
|
||||
return &http.Response{
|
||||
Status: fmt.Sprintf("%d %s", f.Status, http.StatusText(f.Status)), StatusCode: f.Status,
|
||||
Proto: "HTTP/1.1", ProtoMajor: 1, ProtoMinor: 1, Header: f.Header,
|
||||
Body: io.NopCloser(bytes.NewReader(rbody)), ContentLength: int64(len(rbody)), Request: req,
|
||||
}, nil
|
||||
}
|
||||
|
||||
// run keeps the stream open until ctx ends.
|
||||
func (t *streamTransport) run(ctx context.Context) {
|
||||
backoff := time.Second
|
||||
var down time.Time
|
||||
for ctx.Err() == nil {
|
||||
sc, err := t.open(ctx)
|
||||
if err != nil {
|
||||
wait := backoff
|
||||
if errors.Is(err, errStreamUnsupported) {
|
||||
wait = unsupportedRetry
|
||||
t.opts.Log.Info("the API has no WebSocket stream yet; using HTTP", "retry_in", wait.String())
|
||||
} else {
|
||||
t.opts.Log.Debug("opening the WebSocket to the API failed", "error", err, "retry_in", wait.String())
|
||||
backoff = min(backoff*2, 30*time.Second)
|
||||
}
|
||||
sleepCtx(ctx, wait)
|
||||
continue
|
||||
}
|
||||
backoff = time.Second
|
||||
if down.IsZero() {
|
||||
t.opts.Log.Info("connected to the API over WebSocket")
|
||||
} else {
|
||||
t.opts.Log.Info("connected to the API over WebSocket again", "down_for", time.Since(down).Round(time.Second).String())
|
||||
}
|
||||
t.set(sc)
|
||||
err = sc.serve(ctx, t.opts.OnEvent)
|
||||
t.set(nil)
|
||||
down = time.Now()
|
||||
if ctx.Err() == nil {
|
||||
t.opts.Log.Info("WebSocket to the API closed; using HTTP until it is back", "error", err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (t *streamTransport) open(ctx context.Context) (*streamConn, error) {
|
||||
u := t.c.base + Prefix + StreamPath
|
||||
switch {
|
||||
case strings.HasPrefix(u, "https://"):
|
||||
u = "wss://" + strings.TrimPrefix(u, "https://")
|
||||
case strings.HasPrefix(u, "http://"):
|
||||
u = "ws://" + strings.TrimPrefix(u, "http://")
|
||||
}
|
||||
h := http.Header{}
|
||||
h.Set("Authorization", "Bearer "+t.c.token)
|
||||
h.Set(VersionHeader, fmt.Sprint(Version))
|
||||
h.Set(InstanceHeader, t.c.instance.String())
|
||||
h.Set(ReleaseHeader, t.c.release)
|
||||
dctx, cancel := context.WithTimeout(ctx, 30*time.Second)
|
||||
defer cancel()
|
||||
ws, resp, err := websocket.Dial(dctx, u, &websocket.DialOptions{
|
||||
HTTPClient: t.dial, HTTPHeader: h, CompressionMode: websocket.CompressionContextTakeover,
|
||||
})
|
||||
if err != nil {
|
||||
if resp != nil {
|
||||
switch resp.StatusCode {
|
||||
case http.StatusNotFound, http.StatusMethodNotAllowed:
|
||||
return nil, errStreamUnsupported
|
||||
case http.StatusUnauthorized:
|
||||
return nil, ErrUnauthorized
|
||||
}
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
ws.SetReadLimit(MaxFrame)
|
||||
return &streamConn{ws: ws, waiting: map[uint64]chan reply{}, closed: make(chan struct{})}, nil
|
||||
}
|
||||
|
||||
type reply struct {
|
||||
f Frame
|
||||
body []byte
|
||||
}
|
||||
|
||||
// streamConn is one open stream.
|
||||
type streamConn struct {
|
||||
ws *websocket.Conn
|
||||
|
||||
mu sync.Mutex
|
||||
next uint64
|
||||
waiting map[uint64]chan reply
|
||||
closed chan struct{}
|
||||
}
|
||||
|
||||
// roundTrip sends a request and waits for its reply. sent reports whether
|
||||
// the request may have reached the API.
|
||||
func (sc *streamConn) roundTrip(ctx context.Context, f Frame, body []byte) (Frame, []byte, bool, error) {
|
||||
ch := make(chan reply, 1)
|
||||
sc.mu.Lock()
|
||||
sc.next++
|
||||
f.ID = sc.next
|
||||
sc.waiting[f.ID] = ch
|
||||
sc.mu.Unlock()
|
||||
defer func() {
|
||||
sc.mu.Lock()
|
||||
delete(sc.waiting, f.ID)
|
||||
sc.mu.Unlock()
|
||||
}()
|
||||
select {
|
||||
case <-sc.closed:
|
||||
return Frame{}, nil, false, errStreamClosed
|
||||
default:
|
||||
}
|
||||
if err := sc.ws.Write(ctx, websocket.MessageBinary, EncodeFrame(f, body)); err != nil {
|
||||
return Frame{}, nil, false, err
|
||||
}
|
||||
select {
|
||||
case r := <-ch:
|
||||
return r.f, r.body, true, nil
|
||||
case <-sc.closed:
|
||||
return Frame{}, nil, true, errStreamClosed
|
||||
case <-ctx.Done():
|
||||
// The API stops working on it, e.g. ends a long poll.
|
||||
cctx, cancel := context.WithTimeout(context.WithoutCancel(ctx), 5*time.Second)
|
||||
_ = sc.ws.Write(cctx, websocket.MessageBinary, EncodeFrame(Frame{ID: f.ID, Cancel: true}, nil))
|
||||
cancel()
|
||||
return Frame{}, nil, true, ctx.Err()
|
||||
}
|
||||
}
|
||||
|
||||
// serve reads replies and events until the stream closes or ctx ends.
|
||||
func (sc *streamConn) serve(ctx context.Context, onEvent func(string, []byte)) error {
|
||||
defer close(sc.closed)
|
||||
done := make(chan struct{})
|
||||
defer close(done)
|
||||
go func() {
|
||||
tick := time.NewTicker(pingEvery)
|
||||
defer tick.Stop()
|
||||
for {
|
||||
select {
|
||||
case <-done:
|
||||
return
|
||||
case <-ctx.Done():
|
||||
_ = sc.ws.Close(websocket.StatusNormalClosure, "agent stopping")
|
||||
return
|
||||
case <-tick.C:
|
||||
pctx, cancel := context.WithTimeout(ctx, pingTimeout)
|
||||
err := sc.ws.Ping(pctx)
|
||||
cancel()
|
||||
if err != nil && ctx.Err() == nil {
|
||||
_ = sc.ws.CloseNow()
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
}()
|
||||
for {
|
||||
_, msg, err := sc.ws.Read(context.WithoutCancel(ctx))
|
||||
if err != nil {
|
||||
_ = sc.ws.CloseNow()
|
||||
return err
|
||||
}
|
||||
f, body, err := DecodeFrame(msg)
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
if f.Event != "" {
|
||||
if onEvent != nil {
|
||||
onEvent(f.Event, body)
|
||||
}
|
||||
continue
|
||||
}
|
||||
sc.mu.Lock()
|
||||
ch := sc.waiting[f.ID]
|
||||
sc.mu.Unlock()
|
||||
if ch != nil {
|
||||
ch <- reply{f: f, body: body}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func sleepCtx(ctx context.Context, d time.Duration) {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
case <-time.After(d):
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
package agentapi
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
func TestFrameRoundTrip(t *testing.T) {
|
||||
in := Frame{ID: 7, Method: http.MethodPut, Path: "/storage?key=a", Header: http.Header{"If-None-Match": {`"x"`}}}
|
||||
f, body, err := DecodeFrame(EncodeFrame(in, []byte("line one\nline two")))
|
||||
if err != nil || f.ID != 7 || f.Path != in.Path || f.Header.Get("If-None-Match") != `"x"` || string(body) != "line one\nline two" {
|
||||
t.Errorf("DecodeFrame(EncodeFrame()) = %+v, %q, %v", f, body, err)
|
||||
}
|
||||
if _, _, err := DecodeFrame([]byte(`{"id":1}`)); err == nil {
|
||||
t.Error("DecodeFrame(no newline) succeeded")
|
||||
}
|
||||
}
|
||||
|
||||
// An API without the stream is used over HTTP.
|
||||
func TestStreamFallsBackToHTTP(t *testing.T) {
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
if r.URL.Path != Prefix+"/hello" {
|
||||
http.NotFound(w, r)
|
||||
return
|
||||
}
|
||||
_ = json.NewEncoder(w).Encode(Hello{Name: "plain", Kind: "checker"})
|
||||
}))
|
||||
defer srv.Close()
|
||||
c := NewClient(srv.URL, "usa_x", uuid.New(), "test")
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
defer cancel()
|
||||
c.UseStream(ctx, StreamOptions{})
|
||||
time.Sleep(100 * time.Millisecond)
|
||||
h, err := c.Hello(ctx)
|
||||
if err != nil || h.Name != "plain" {
|
||||
t.Fatalf("Hello() = %+v, %v", h, err)
|
||||
}
|
||||
if c.Streaming() {
|
||||
t.Error("Streaming() = true against an API without the stream")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
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"`
|
||||
}
|
||||
|
||||
// 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
|
||||
}
|
||||
+37
-6
@@ -32,15 +32,19 @@ const (
|
||||
ctxAgent = "api.agent"
|
||||
ctxInstance = "api.instance"
|
||||
maxJobWait = 25 * time.Second
|
||||
maxJobBatch = 200
|
||||
// drainingPollHold is how long a draining instance still holds a poll.
|
||||
drainingPollHold = time.Second
|
||||
maxJobBatch = 200
|
||||
)
|
||||
|
||||
func (s *Server) mountAgentAPI(r gin.IRouter) {
|
||||
g := r.Group("/agent/v1", s.agentAuth())
|
||||
g := r.Group(agentapi.Prefix, s.agentAuth())
|
||||
g.GET("/hello", s.agentHello)
|
||||
g.GET("/update", s.agentUpdate)
|
||||
g.GET(agentapi.StreamPath, s.agentStream)
|
||||
sp := g.Group("", requireAgentKind("statuspage"))
|
||||
sp.GET("/pages", s.agentPage)
|
||||
sp.GET("/pages/index", s.agentPageIndex)
|
||||
sp.GET("/storage", s.storageGet)
|
||||
sp.PUT("/storage", s.storagePut)
|
||||
sp.DELETE("/storage", s.storageDelete)
|
||||
@@ -48,6 +52,10 @@ func (s *Server) mountAgentAPI(r gin.IRouter) {
|
||||
sp.GET("/storage/list", s.storageList)
|
||||
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)
|
||||
@@ -195,8 +203,27 @@ func (s *Server) agentJobs(c *gin.Context) {
|
||||
return
|
||||
}
|
||||
wait := min(time.Duration(req.WaitMS)*time.Millisecond, maxJobWait)
|
||||
entries, err := s.sched.Take(ctx, instance, min(req.Max, maxJobBatch), wait)
|
||||
if err != nil && ctx.Err() == nil {
|
||||
// A draining instance ends long polls within a second or so, empty, so
|
||||
// the shutdown is not held up and the checker's next poll reaches
|
||||
// another instance. It still holds them that second, so checkers that
|
||||
// poll again at once do not spin against it.
|
||||
pollCtx, stop := context.WithCancel(ctx)
|
||||
defer stop()
|
||||
if s.draining != nil {
|
||||
go func() {
|
||||
select {
|
||||
case <-s.draining:
|
||||
select {
|
||||
case <-time.After(drainingPollHold):
|
||||
case <-pollCtx.Done():
|
||||
}
|
||||
stop()
|
||||
case <-pollCtx.Done():
|
||||
}
|
||||
}()
|
||||
}
|
||||
entries, err := s.sched.Take(pollCtx, instance, min(req.Max, maxJobBatch), wait)
|
||||
if err != nil && pollCtx.Err() == nil {
|
||||
internalError(c, err)
|
||||
return
|
||||
}
|
||||
@@ -278,7 +305,10 @@ func (s *Server) agentResults(c *gin.Context) {
|
||||
}
|
||||
now := time.Now()
|
||||
monitors := map[uuid.UUID]store.MonitorsForResultsRow{}
|
||||
var accepted []agentapi.Result
|
||||
var (
|
||||
accepted []agentapi.Result
|
||||
changed []uuid.UUID
|
||||
)
|
||||
err = s.db.Tx(ctx, tenant.System(), func(q *store.Queries) error {
|
||||
a := agentOf(c)
|
||||
rows, err := q.MonitorsForResults(ctx, store.MonitorsForResultsParams{RegionID: deref(a.RegionID), Ids: ids, AgentOrg: a.OrgID})
|
||||
@@ -314,7 +344,7 @@ func (s *Server) agentResults(c *gin.Context) {
|
||||
if len(params) == 0 {
|
||||
return nil
|
||||
}
|
||||
_, err = q.InsertCheckResults(ctx, params)
|
||||
changed, err = insertResults(ctx, q, params)
|
||||
return err
|
||||
})
|
||||
if err != nil {
|
||||
@@ -323,6 +353,7 @@ func (s *Server) agentResults(c *gin.Context) {
|
||||
internalError(c, err)
|
||||
return
|
||||
}
|
||||
s.pagesChanged(ctx, changed...)
|
||||
s.evaluateResults(ctx, region, accepted, monitors)
|
||||
s.storeEvidence(ctx, region, instance, accepted, monitors)
|
||||
s.finishRunning(ctx, instance, accepted)
|
||||
|
||||
@@ -50,7 +50,9 @@ func (s *Server) evaluateResults(ctx context.Context, region string, results []a
|
||||
Interval: time.Duration(m.IntervalSeconds) * time.Second, Confirmations: int(m.Confirmations), Regions: m.Regions,
|
||||
})
|
||||
if err == nil && t != evaluate.None {
|
||||
err = s.transition(ctx, m, t, r.StartedAt)
|
||||
if err = s.transition(ctx, m, t, r.StartedAt); err == nil {
|
||||
s.pagesChanged(ctx, m.OrgID)
|
||||
}
|
||||
}
|
||||
if err != nil {
|
||||
// The next result re-evaluates; a missed transition only delays
|
||||
@@ -97,6 +99,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
|
||||
@@ -138,6 +143,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 {
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -90,6 +90,9 @@ var endpoints = []endpoint{
|
||||
{method: "POST", path: "/api/v1/org/monitors", tag: "Monitors", summary: "Create a monitor",
|
||||
description: "`type` is one of http, json, prometheus, tcp, tls, dns, icmp, postgres, mysql, mssql, mongodb, redis, mqtt, kafka, rabbitmq, grpc, smtp, radius, snmp, steam, minecraft, docker, heartbeat or alertmanager (GET /api/v1/org/check-types lists those offered); `config` depends on it (see HTTPConfig, JSONConfig, PrometheusConfig, DNSConfig, TLSConfig, DBConfig, BrokerConfig, GRPCConfig, SMTPConfig, RADIUSConfig, SNMPConfig, GameConfig, DockerConfig, HeartbeatConfig, AlertmanagerConfig). Passwords, RADIUS secrets and SNMP communities are stored encrypted and never returned: `secrets_set` names those set, and an update that leaves one empty keeps it. Heartbeat and alertmanager monitors take neither target nor regions; heartbeats return their `ping_url`. Omit `alert_group_ids` to assign the default alert group; an empty array disables notifications.",
|
||||
perm: "monitors.write", req: monitorRequest{}, status: http.StatusCreated, resp: monitorView{}},
|
||||
{method: "PUT", path: "/api/v1/org/monitors/order", tag: "Monitors", summary: "Put monitors in the organization's own order", perm: "monitors.write",
|
||||
description: "Positions follow the order of monitor_ids, usually the monitors of one group; the monitor list sorted by its own order shows positioned monitors first, the rest by name. Needs write access to every monitor given.",
|
||||
req: monitorOrderRequest{}},
|
||||
{method: "PUT", path: "/api/v1/org/monitors/:id", tag: "Monitors", summary: "Change a monitor", perm: "monitors.write",
|
||||
description: "Omitting alert_group_ids preserves existing assignments; an empty array removes all alert groups.",
|
||||
req: monitorRequest{}, resp: monitorView{}},
|
||||
@@ -106,7 +109,7 @@ var endpoints = []endpoint{
|
||||
description: "Platform checkers serve every organization; other organizations' work appears only as a count. `recent` is paged, newest first; a page may hold fewer results than `limit` when some belong to monitors you cannot read.",
|
||||
resp: checkerActivity{}},
|
||||
{method: "GET", path: "/api/v1/org/limits", tag: "Organization", summary: "Limits in effect for the organization and its usage",
|
||||
description: "0 means unlimited. Creating beyond a limit gives 422 monitor_limit, status_page_limit, region_limit or platform_region_limit.",
|
||||
description: "0 means unlimited. Creating beyond a limit gives 422 monitor_limit, status_page_limit, page_monitor_limit, region_limit or platform_region_limit.",
|
||||
resp: usageView{}},
|
||||
{method: "GET", path: "/api/v1/org/check-types", tag: "Monitors", summary: "Monitor types members can create",
|
||||
description: "`own_checkers_only` are the types the platform's checkers do not run: monitors of them use the organization's own regions only, or 422 check_type_own_checkers_only.",
|
||||
@@ -185,6 +188,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"},
|
||||
|
||||
|
||||
+45
-43
@@ -61,49 +61,51 @@ 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",
|
||||
"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",
|
||||
"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",
|
||||
|
||||
@@ -0,0 +1,47 @@
|
||||
package api
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
// A status page server obtains certificates for custom domains on demand,
|
||||
// on the first visit over HTTPS. Before it orders a new one from its CA it
|
||||
// asks here: only for a verified domain of a page it serves, and within the
|
||||
// limits of UPTIME_CERTS_*. The limits count across all instances and keep
|
||||
// one organization, or a flood of handshakes for many names, from using up
|
||||
// the CA's rate limits that the other organizations share.
|
||||
|
||||
type certificateRequest struct {
|
||||
Name string `json:"name" binding:"required,max=253"`
|
||||
}
|
||||
|
||||
func (s *Server) agentCertificate(c *gin.Context) {
|
||||
var req certificateRequest
|
||||
if !bind(c, &req) {
|
||||
return
|
||||
}
|
||||
name := strings.TrimSuffix(strings.ToLower(strings.TrimSpace(req.Name)), ".")
|
||||
ctx := c.Request.Context()
|
||||
page, ok, err := s.agentServes(ctx, agentOf(c), &name, nil)
|
||||
if err != nil {
|
||||
internalError(c, err)
|
||||
return
|
||||
}
|
||||
if !ok {
|
||||
fail(c, http.StatusNotFound, "not_found")
|
||||
return
|
||||
}
|
||||
lim := s.cfg.Certificates
|
||||
if !s.limit(c, "acme:name:"+name, lim.PerNamePerDay, 24*time.Hour) ||
|
||||
!s.limit(c, "acme:org:"+page.OrgID.String(), lim.PerOrgPerDay, 24*time.Hour) ||
|
||||
!s.limit(c, "acme:owner:"+storageOwner(c), lim.PerOwnerPerHour, time.Hour) {
|
||||
s.log.WarnContext(ctx, "certificate order refused by limit", "domain", name, "org", page.OrgID, "agent", agentOf(c).ID)
|
||||
return
|
||||
}
|
||||
s.log.InfoContext(ctx, "certificate order allowed", "domain", name, "org", page.OrgID, "agent", agentOf(c).ID)
|
||||
c.Status(http.StatusNoContent)
|
||||
}
|
||||
@@ -0,0 +1,108 @@
|
||||
package api_test
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"net/http"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"git.zb-server.de/ZB-Server/uptimesebi/internal/agentapi"
|
||||
"git.zb-server.de/ZB-Server/uptimesebi/internal/config"
|
||||
)
|
||||
|
||||
func TestCertificateOrdersAreLimited(t *testing.T) {
|
||||
e := newEnvWith(t, func(c *config.API) {
|
||||
c.StatusPageURL = "https://status.platform.test"
|
||||
c.Certificates = config.Certificates{PerOrgPerDay: 3, PerOwnerPerHour: 100, PerNamePerDay: 2}
|
||||
})
|
||||
ctx := context.Background()
|
||||
owner := e.browser(t)
|
||||
owner.signup("o@"+uniq("cert")+".test", uniq("cert-"))
|
||||
platform := e.statuspageClient(t, nil)
|
||||
|
||||
page := func(domain string) (string, map[string]any) {
|
||||
t.Helper()
|
||||
slug := uniq("cert-")
|
||||
_, p := owner.do("POST", "/api/v1/org/statuspages", map[string]any{"slug": slug, "title": "Status"})
|
||||
id := p["id"].(string)
|
||||
owner.do("PUT", "/api/v1/org/statuspages/"+id, map[string]any{"slug": slug, "title": "Status", "published": true})
|
||||
st, body := owner.do("PUT", "/api/v1/org/statuspages/"+id+"/domain", map[string]any{"domain": domain})
|
||||
if st != http.StatusOK {
|
||||
t.Fatalf("set domain = %d %v", st, body)
|
||||
}
|
||||
return id, body["domain_record"].(map[string]any)
|
||||
}
|
||||
|
||||
// An unverified domain gets no certificate, nor does a made-up name.
|
||||
d1 := uniq("a") + ".example.test"
|
||||
id1, rec1 := page(d1)
|
||||
if err := platform.AllowCertificate(ctx, d1); !errors.Is(err, agentapi.ErrNotFound) {
|
||||
t.Errorf("unverified domain: %v, want not found", err)
|
||||
}
|
||||
if err := platform.AllowCertificate(ctx, uniq("random")+".example.test"); !errors.Is(err, agentapi.ErrNotFound) {
|
||||
t.Errorf("unknown name: %v, want not found", err)
|
||||
}
|
||||
|
||||
// The editor explains the records, with the platform's servers as the
|
||||
// CNAME target.
|
||||
_, _, html := owner.page("/statuspages/" + id1)
|
||||
for _, want := range []string{"Create this CNAME record", ".status.platform.test.", "Prove the domain with this TXT record", "ALIAS or ANAME", "at most 10 times a day"} {
|
||||
if !strings.Contains(html, want) {
|
||||
t.Errorf("the editor lacks %q", want)
|
||||
}
|
||||
}
|
||||
|
||||
verifyDomain(t, owner, id1, rec1)
|
||||
if err := platform.AllowCertificate(ctx, strings.ToUpper(d1)+"."); err != nil {
|
||||
t.Fatalf("verified domain: %v", err)
|
||||
}
|
||||
// A domain whose orders keep failing stops at its own limit.
|
||||
_ = platform.AllowCertificate(ctx, d1)
|
||||
if err := platform.AllowCertificate(ctx, d1); !errors.Is(err, agentapi.ErrRateLimited) {
|
||||
t.Errorf("third order for one domain: %v, want rate limited", err)
|
||||
}
|
||||
|
||||
// The organization's limit covers all its domains.
|
||||
d2 := uniq("b") + ".example.test"
|
||||
id2, rec2 := page(d2)
|
||||
verifyDomain(t, owner, id2, rec2)
|
||||
if err := platform.AllowCertificate(ctx, d2); err != nil {
|
||||
t.Fatalf("second domain: %v", err)
|
||||
}
|
||||
if err := platform.AllowCertificate(ctx, d2); !errors.Is(err, agentapi.ErrRateLimited) {
|
||||
t.Errorf("order beyond the organization's limit: %v, want rate limited", err)
|
||||
}
|
||||
|
||||
// Another organization's server is not allowed the domain at all.
|
||||
other := e.browser(t)
|
||||
other.signup("x@"+uniq("cert")+".test", uniq("cert-"))
|
||||
otherOrg := uuid.MustParse(other.orgID())
|
||||
if err := e.statuspageClient(t, &otherOrg).AllowCertificate(ctx, d2); !errors.Is(err, agentapi.ErrNotFound) {
|
||||
t.Errorf("another organization's server: %v, want not found", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDomainChangesAreLimited(t *testing.T) {
|
||||
e := newEnv(t)
|
||||
owner := e.browser(t)
|
||||
owner.signup("o@"+uniq("dom")+".test", uniq("dom-"))
|
||||
_, p := owner.do("POST", "/api/v1/org/statuspages", map[string]any{"slug": uniq("dom-"), "title": "Status"})
|
||||
id := p["id"].(string)
|
||||
base := uniq("d")
|
||||
for i := range 10 {
|
||||
st, body := owner.do("PUT", "/api/v1/org/statuspages/"+id+"/domain", map[string]any{"domain": base + string(rune('a'+i)) + ".example.test"})
|
||||
if st != http.StatusOK {
|
||||
t.Fatalf("change %d = %d %v", i+1, st, body)
|
||||
}
|
||||
// Saving the same domain again does not count.
|
||||
owner.do("PUT", "/api/v1/org/statuspages/"+id+"/domain", map[string]any{"domain": base + string(rune('a'+i)) + ".example.test"})
|
||||
}
|
||||
st, body := owner.do("PUT", "/api/v1/org/statuspages/"+id+"/domain", map[string]any{"domain": base + "z.example.test"})
|
||||
expect(t, "eleventh change", st, body, http.StatusTooManyRequests, "domain_changes_exceeded")
|
||||
// Removing the domain is always possible.
|
||||
st, body = owner.do("PUT", "/api/v1/org/statuspages/"+id+"/domain", map[string]any{"domain": ""})
|
||||
expect(t, "remove domain", st, body, http.StatusOK, "")
|
||||
}
|
||||
@@ -54,6 +54,8 @@ func (e *env) startChecker(t *testing.T, token string) (uuid.UUID, func()) {
|
||||
id := uuid.New()
|
||||
client := agentapi.NewClient(e.srv.URL, token, id, "test").WithHTTPClient(e.srv.Client())
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
// Checkers talk to the API over the stream, as in production.
|
||||
client.UseStream(ctx, agentapi.StreamOptions{})
|
||||
done := make(chan struct{})
|
||||
go func() {
|
||||
defer close(done)
|
||||
|
||||
@@ -182,7 +182,7 @@ func (s *Server) loadCheckerActivity(ctx context.Context, p *principal, instance
|
||||
a.Siblings = append(a.Siblings, sb.ID)
|
||||
}
|
||||
}
|
||||
monitors, err := q.ListMonitors(ctx)
|
||||
monitors, err := q.ListMonitors(ctx, p.Org.ID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
+360
-75
@@ -6,6 +6,8 @@ import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"math"
|
||||
"net"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"slices"
|
||||
@@ -21,6 +23,7 @@ import (
|
||||
"git.zb-server.de/ZB-Server/uptimesebi/internal/auth"
|
||||
"git.zb-server.de/ZB-Server/uptimesebi/internal/authz"
|
||||
"git.zb-server.de/ZB-Server/uptimesebi/internal/check"
|
||||
"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/maintenance"
|
||||
"git.zb-server.de/ZB-Server/uptimesebi/internal/notify"
|
||||
@@ -77,25 +80,81 @@ func (s *Server) dashboard(c *gin.Context) {
|
||||
}
|
||||
v.Root = buildGroupNodes(data.tree, data.rows)
|
||||
v.Empty = len(data.rows) == 0 && len(v.Root.Children) == 0
|
||||
v.CanWrite = writableAnywhere(p, data.tree)
|
||||
if !s.dashboardPage(c, &v, data) {
|
||||
return
|
||||
}
|
||||
v.CanWrite = writableAnywhere(p, data.tree)
|
||||
if err := s.dashboardBars(c.Request.Context(), p, &v, &data); err != nil {
|
||||
internalError(c, err)
|
||||
return
|
||||
}
|
||||
v.Range = data.rng.Key
|
||||
var earliest time.Time
|
||||
for _, m := range data.byID {
|
||||
if f, ok := data.first[m.ID]; ok && (earliest.IsZero() || f.Before(earliest)) {
|
||||
earliest = f
|
||||
}
|
||||
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)
|
||||
for _, m := range data.rows {
|
||||
v.Counts[m.Status]++
|
||||
if m.Unchecked {
|
||||
v.Unchecked++
|
||||
}
|
||||
}
|
||||
v.Filters = statusFilters(c, v.Counts, v.Filter)
|
||||
for id, since := range s.regionsWithoutChecker(c.Request.Context(), data.usedRegions) {
|
||||
v.DeadRegions = append(v.DeadRegions, web.DeadRegion{Name: data.regionOf[id].Name, Since: since.Local().Format("2006-01-02 15:04")})
|
||||
}
|
||||
slices.SortFunc(v.DeadRegions, func(a, b web.DeadRegion) int { return strings.Compare(a.Name, b.Name) })
|
||||
}
|
||||
web.Render(c, http.StatusOK, web.Dashboard(s.pageFor(c, "console.monitors.title"), me, v))
|
||||
}
|
||||
|
||||
// dashboardBars loads the bars of the monitors v shows, and only those.
|
||||
func (s *Server) dashboardBars(ctx context.Context, p *principal, v *web.DashboardView, data *monitorData) error {
|
||||
var ids []uuid.UUID
|
||||
walk := func(rows []web.MonitorRow, set bool) {
|
||||
for i := range rows {
|
||||
id, err := uuid.Parse(rows[i].ID)
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
if set {
|
||||
rows[i].Bars = data.bars(id)
|
||||
} else {
|
||||
ids = append(ids, id)
|
||||
}
|
||||
}
|
||||
}
|
||||
var tree func(n *web.GroupNode, set bool)
|
||||
tree = func(n *web.GroupNode, set bool) {
|
||||
walk(n.Monitors, set)
|
||||
for i := range n.Children {
|
||||
tree(&n.Children[i], set)
|
||||
}
|
||||
}
|
||||
// A search or filter lists Results instead of the tree.
|
||||
listing := v.Search != "" || v.Filter != ""
|
||||
if listing {
|
||||
walk(v.Results, false)
|
||||
} else {
|
||||
tree(&v.Root, false)
|
||||
}
|
||||
if err := s.loadBars(ctx, p, data, ids); err != nil {
|
||||
return err
|
||||
}
|
||||
if listing {
|
||||
walk(v.Results, true)
|
||||
} else {
|
||||
tree(&v.Root, true)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// groupMonitorsShown is how many of its own monitors a group shows on the
|
||||
// dashboard before linking to all of them.
|
||||
const groupMonitorsShown = 50
|
||||
@@ -103,14 +162,64 @@ const groupMonitorsShown = 50
|
||||
// ungrouped names the pseudo-group of monitors outside any group.
|
||||
const ungrouped = "none"
|
||||
|
||||
func monitorKey(m web.MonitorRow) cursor {
|
||||
id, _ := uuid.Parse(m.ID)
|
||||
return cursor{S: strings.ToLower(m.Name), ID: id}
|
||||
// monitorSort is an order of the monitor list: the organization's own,
|
||||
// or by name, status (problems first), uptime (worst first) or latency
|
||||
// (slowest first). Monitors without a position or data come last.
|
||||
type monitorSort string
|
||||
|
||||
var monitorSorts = []monitorSort{"custom", "name", "status", "uptime", "latency"}
|
||||
|
||||
const sortCookie = "monitor_sort"
|
||||
|
||||
// sortOf returns the order asked for, remembering it in a cookie, or the
|
||||
// one remembered, or the organization's own.
|
||||
func sortOf(c *gin.Context) monitorSort {
|
||||
if q := monitorSort(c.Query("sort")); slices.Contains(monitorSorts, q) {
|
||||
c.SetSameSite(http.SameSiteLaxMode)
|
||||
c.SetCookie(sortCookie, string(q), 365*24*3600, "/", "", c.Request.TLS != nil, true)
|
||||
return q
|
||||
}
|
||||
if v, err := c.Cookie(sortCookie); err == nil && slices.Contains(monitorSorts, monitorSort(v)) {
|
||||
return monitorSort(v)
|
||||
}
|
||||
return "custom"
|
||||
}
|
||||
|
||||
func sortMonitors(ms []web.MonitorRow) {
|
||||
// key orders m by o as a string, so pages can continue after it.
|
||||
func (o monitorSort) key(m web.MonitorRow) cursor {
|
||||
id, _ := uuid.Parse(m.ID)
|
||||
name := strings.ToLower(m.Name)
|
||||
var k string
|
||||
switch o {
|
||||
case "name":
|
||||
k = name
|
||||
case "status":
|
||||
k = fmt.Sprintf("%d|%s", statusRank[m.Status], name)
|
||||
case "uptime":
|
||||
if m.Ratio < 0 {
|
||||
k = "1|" + name
|
||||
} else {
|
||||
k = fmt.Sprintf("0|%.9f|%s", m.Ratio, name)
|
||||
}
|
||||
case "latency":
|
||||
if m.LatencyMS < 0 {
|
||||
k = "1|" + name
|
||||
} else {
|
||||
k = fmt.Sprintf("0|%010d|%s", math.MaxInt32-m.LatencyMS, name)
|
||||
}
|
||||
default:
|
||||
if m.Position < 0 {
|
||||
k = "1|" + name
|
||||
} else {
|
||||
k = fmt.Sprintf("0|%010d|%s", m.Position, name)
|
||||
}
|
||||
}
|
||||
return cursor{S: k, ID: id}
|
||||
}
|
||||
|
||||
func (o monitorSort) sort(ms []web.MonitorRow) {
|
||||
slices.SortFunc(ms, func(a, b web.MonitorRow) int {
|
||||
ka, kb := monitorKey(a), monitorKey(b)
|
||||
ka, kb := o.key(a), o.key(b)
|
||||
if c := strings.Compare(ka.S, kb.S); c != 0 {
|
||||
return c
|
||||
}
|
||||
@@ -118,6 +227,46 @@ func sortMonitors(ms []web.MonitorRow) {
|
||||
})
|
||||
}
|
||||
|
||||
// dashboardStatuses are the statuses the dashboard counts, in order.
|
||||
var dashboardStatuses = []web.Status{web.StatusUp, web.StatusDegraded, web.StatusDown, web.StatusUnknown, web.StatusMaintenance, web.StatusPaused}
|
||||
|
||||
// dashboardURL is the dashboard with key set to value, or removed when
|
||||
// value is empty, keeping the search and range but not the page.
|
||||
func dashboardURL(c *gin.Context, key, value string) string {
|
||||
q := url.Values{}
|
||||
for _, k := range []string{"q", "range", "status", "arrange"} {
|
||||
if v := c.Query(k); v != "" {
|
||||
q.Set(k, v)
|
||||
}
|
||||
}
|
||||
if value == "" {
|
||||
q.Del(key)
|
||||
} else {
|
||||
q.Set(key, value)
|
||||
}
|
||||
if len(q) == 0 {
|
||||
return "/"
|
||||
}
|
||||
return "/?" + q.Encode()
|
||||
}
|
||||
|
||||
// statusFilters are the counts of the statuses present, each linking to
|
||||
// its monitors, the active one back to all.
|
||||
func statusFilters(c *gin.Context, counts map[web.Status]int, active web.Status) []web.StatusFilter {
|
||||
var out []web.StatusFilter
|
||||
for _, st := range dashboardStatuses {
|
||||
if counts[st] == 0 && st != active {
|
||||
continue
|
||||
}
|
||||
f := web.StatusFilter{Status: st, Count: counts[st], Active: st == active, URL: dashboardURL(c, "status", string(st))}
|
||||
if f.Active {
|
||||
f.URL = dashboardURL(c, "status", "")
|
||||
}
|
||||
out = append(out, f)
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// dashboardPage narrows the dashboard to a search or one group, pages it
|
||||
// and caps every group's own monitors. It reports false after answering
|
||||
// with an error.
|
||||
@@ -126,6 +275,20 @@ func (s *Server) dashboardPage(c *gin.Context, v *web.DashboardView, data monito
|
||||
if !ok {
|
||||
return false
|
||||
}
|
||||
order := sortOf(c)
|
||||
v.Sort = string(order)
|
||||
for _, o := range monitorSorts {
|
||||
v.Sorts = append(v.Sorts, web.SortOption{Key: string(o), Active: o == order, URL: dashboardURL(c, "sort", string(o))})
|
||||
}
|
||||
// Arranging by hand shows the whole tree in the organization's order.
|
||||
arranging := order == "custom" && v.CanWrite && c.Query("q") == "" && c.Query("status") == "" && c.Query("group") == ""
|
||||
v.Arrange = arranging && c.Query("arrange") == "1"
|
||||
if arranging {
|
||||
v.ArrangeURL = dashboardURL(c, "arrange", "1")
|
||||
if v.Arrange {
|
||||
v.ArrangeURL = dashboardURL(c, "arrange", "")
|
||||
}
|
||||
}
|
||||
link := func(group string) string {
|
||||
q := url.Values{"group": {group}}
|
||||
if r := c.Query("range"); r != "" {
|
||||
@@ -135,8 +298,8 @@ func (s *Server) dashboardPage(c *gin.Context, v *web.DashboardView, data monito
|
||||
}
|
||||
var capNode func(n *web.GroupNode)
|
||||
capNode = func(n *web.GroupNode) {
|
||||
sortMonitors(n.Monitors)
|
||||
if len(n.Monitors) > groupMonitorsShown {
|
||||
order.sort(n.Monitors)
|
||||
if len(n.Monitors) > groupMonitorsShown && !v.Arrange {
|
||||
n.More = len(n.Monitors) - groupMonitorsShown
|
||||
n.Monitors = n.Monitors[:groupMonitorsShown]
|
||||
n.MoreURL = link(cmp.Or(n.ID, ungrouped))
|
||||
@@ -146,18 +309,25 @@ func (s *Server) dashboardPage(c *gin.Context, v *web.DashboardView, data monito
|
||||
}
|
||||
}
|
||||
var info pageInfo
|
||||
if f := web.Status(c.Query("status")); slices.Contains(dashboardStatuses, f) {
|
||||
v.Filter = f
|
||||
v.AllURL = dashboardURL(c, "status", "")
|
||||
}
|
||||
switch group := c.Query("group"); {
|
||||
case strings.TrimSpace(c.Query("q")) != "":
|
||||
case strings.TrimSpace(c.Query("q")) != "" || v.Filter != "":
|
||||
v.Search = strings.TrimSpace(c.Query("q"))
|
||||
needle := strings.ToLower(v.Search)
|
||||
var hits []web.MonitorRow
|
||||
for _, m := range data.rows {
|
||||
if v.Filter != "" && m.Status != v.Filter {
|
||||
continue
|
||||
}
|
||||
if strings.Contains(strings.ToLower(m.Name), needle) || strings.Contains(strings.ToLower(m.Target), needle) {
|
||||
hits = append(hits, m)
|
||||
}
|
||||
}
|
||||
sortMonitors(hits)
|
||||
v.Results, info = pageSlice(hits, pg, monitorKey)
|
||||
order.sort(hits)
|
||||
v.Results, info = pageSlice(hits, pg, order.key)
|
||||
case group != "":
|
||||
var focus web.GroupNode
|
||||
found := false
|
||||
@@ -182,8 +352,8 @@ func (s *Server) dashboardPage(c *gin.Context, v *web.DashboardView, data monito
|
||||
c.Redirect(http.StatusSeeOther, "/")
|
||||
return false
|
||||
}
|
||||
sortMonitors(focus.Monitors)
|
||||
focus.Monitors, info = pageSlice(focus.Monitors, pg, monitorKey)
|
||||
order.sort(focus.Monitors)
|
||||
focus.Monitors, info = pageSlice(focus.Monitors, pg, order.key)
|
||||
for i := range focus.Children {
|
||||
capNode(&focus.Children[i])
|
||||
}
|
||||
@@ -202,78 +372,96 @@ type monitorData struct {
|
||||
maint map[uuid.UUID][]store.MaintenanceWindow
|
||||
rows []web.MonitorRow
|
||||
byID map[uuid.UUID]store.Monitor
|
||||
// buckets cover the selected range at its resolution.
|
||||
// buckets cover the selected range at its resolution, for the
|
||||
// monitors loadBars was asked for.
|
||||
buckets map[uuid.UUID][]web.Bucket
|
||||
down map[uuid.UUID][]web.Span
|
||||
regionOf map[uuid.UUID]store.Region
|
||||
rng web.TimeRange
|
||||
now time.Time
|
||||
// first is when each monitor first reported, from any region;
|
||||
// firstRegion the same per region.
|
||||
first map[uuid.UUID]time.Time
|
||||
firstRegion map[uuid.UUID]map[string]time.Time
|
||||
// first is when the monitor of a detail page first reported, from
|
||||
// any region; firstRegion the same per region.
|
||||
first time.Time
|
||||
firstRegion map[string]time.Time
|
||||
// statuses are the organization's own incident statuses.
|
||||
statuses customStatuses
|
||||
// usedRegions are the regions the enabled monitors are checked from.
|
||||
usedRegions []uuid.UUID
|
||||
}
|
||||
|
||||
// loadFirstData finds when monitors and their regions first reported. The
|
||||
// loadFirstData finds when monitor and its regions first reported. The
|
||||
// daily aggregate answers to the day, which is precise enough for anything
|
||||
// older than two days; younger data is looked up in the raw results.
|
||||
func loadFirstData(ctx context.Context, q *store.Queries, org uuid.UUID, now time.Time) (map[uuid.UUID]time.Time, map[uuid.UUID]map[string]time.Time, error) {
|
||||
first := map[uuid.UUID]time.Time{}
|
||||
perRegion := map[uuid.UUID]map[string]time.Time{}
|
||||
note := func(m uuid.UUID, region string, t time.Time) {
|
||||
if perRegion[m] == nil {
|
||||
perRegion[m] = map[string]time.Time{}
|
||||
// older than two days; younger data is looked up exactly.
|
||||
func loadFirstData(ctx context.Context, q *store.Queries, org, monitor uuid.UUID, now time.Time) (time.Time, map[string]time.Time, error) {
|
||||
var first time.Time
|
||||
perRegion := map[string]time.Time{}
|
||||
note := func(region string, t time.Time) {
|
||||
if cur, ok := perRegion[region]; !ok || t.Before(cur) {
|
||||
perRegion[region] = t
|
||||
}
|
||||
if cur, ok := perRegion[m][region]; !ok || t.Before(cur) {
|
||||
perRegion[m][region] = t
|
||||
}
|
||||
if cur, ok := first[m]; !ok || t.Before(cur) {
|
||||
first[m] = t
|
||||
if first.IsZero() || t.Before(first) {
|
||||
first = t
|
||||
}
|
||||
}
|
||||
recentSince := now.Add(-2 * 24 * time.Hour)
|
||||
daily, err := q.FirstDataDaily(ctx, org)
|
||||
daily, err := q.FirstDataDaily(ctx, store.FirstDataDailyParams{OrgID: org, MonitorID: monitor})
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
return first, nil, err
|
||||
}
|
||||
for _, r := range daily {
|
||||
if r.First.Before(recentSince) {
|
||||
note(r.MonitorID, r.Region, r.First)
|
||||
note(r.Region, r.First)
|
||||
}
|
||||
}
|
||||
recent, err := q.FirstDataRecent(ctx, store.FirstDataRecentParams{OrgID: org, Time: recentSince})
|
||||
recent, err := q.FirstDataRecent(ctx, store.FirstDataRecentParams{OrgID: org, MonitorID: monitor, Time: recentSince})
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
return first, nil, err
|
||||
}
|
||||
for _, r := range recent {
|
||||
note(r.MonitorID, r.Region, r.First)
|
||||
note(r.Region, r.First)
|
||||
}
|
||||
return first, perRegion, nil
|
||||
}
|
||||
|
||||
// rangeBuckets loads the selected range for all monitors, or one if
|
||||
// monitor is set.
|
||||
func rangeBuckets(ctx context.Context, q *store.Queries, org uuid.UUID, monitor *uuid.UUID, rng web.TimeRange, now time.Time) (map[uuid.UUID][]web.Bucket, error) {
|
||||
// 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{}
|
||||
since := now.Add(-rng.Window).Truncate(rng.Bucket)
|
||||
width := fmt.Sprintf("%d seconds", int(rng.Bucket.Seconds()))
|
||||
switch rng.Source {
|
||||
case web.SourceHourly:
|
||||
rows, err := q.RangeBucketsHourly(ctx, store.RangeBucketsHourlyParams{OrgID: org, Width: width, Since: since, MonitorID: monitor})
|
||||
rows, err := q.RangeBucketsHourly(ctx, store.RangeBucketsHourlyParams{OrgID: org, Width: width, Since: since, Ids: ids})
|
||||
for _, r := range rows {
|
||||
out[r.MonitorID] = append(out[r.MonitorID], web.Bucket{Start: r.Bucket, Total: r.Total, OK: r.OkCount, Latency: r.AvgLatencyMs})
|
||||
}
|
||||
return out, err
|
||||
case web.SourceDaily:
|
||||
rows, err := q.RangeBucketsDaily(ctx, store.RangeBucketsDailyParams{OrgID: org, Width: width, Since: since, MonitorID: monitor})
|
||||
rows, err := q.RangeBucketsDaily(ctx, store.RangeBucketsDailyParams{OrgID: org, Width: width, Since: since, Ids: ids})
|
||||
for _, r := range rows {
|
||||
out[r.MonitorID] = append(out[r.MonitorID], web.Bucket{Start: r.Bucket, Total: r.Total, OK: r.OkCount, Latency: r.AvgLatencyMs})
|
||||
}
|
||||
return out, err
|
||||
}
|
||||
rows, err := q.RangeBuckets(ctx, store.RangeBucketsParams{OrgID: org, Width: width, Since: since, MonitorID: monitor})
|
||||
rows, err := q.RangeBuckets(ctx, store.RangeBucketsParams{OrgID: org, Width: width, Since: since, Ids: ids})
|
||||
for _, r := range rows {
|
||||
out[r.MonitorID] = append(out[r.MonitorID], web.Bucket{Start: r.Bucket, Total: r.Total, OK: r.OkCount, Latency: r.AvgLatencyMs})
|
||||
}
|
||||
@@ -290,9 +478,10 @@ func (d monitorData) slaFor(m store.Monitor, window time.Duration) float64 {
|
||||
return web.SLA(d.down[m.ID], from, d.now)
|
||||
}
|
||||
|
||||
// loadMonitorData assembles everything the monitor list shows.
|
||||
// loadMonitorData assembles everything the monitor list shows for rng.
|
||||
// Incidents are loaded far enough back for every SLA window.
|
||||
// loadMonitorData assembles the status of every monitor for rng.
|
||||
// Incidents are loaded far enough back for every SLA window. The bars of
|
||||
// rng are left to loadBars, for the monitors shown: an organization may
|
||||
// have thousands.
|
||||
func (s *Server) loadMonitorData(ctx context.Context, p *principal, rng web.TimeRange) (monitorData, error) {
|
||||
now := time.Now()
|
||||
d := monitorData{
|
||||
@@ -314,10 +503,10 @@ func (s *Server) loadMonitorData(ctx context.Context, p *principal, rng web.Time
|
||||
if groups, err = q.ListGroups(ctx); err != nil {
|
||||
return err
|
||||
}
|
||||
if monitors, err = q.ListMonitors(ctx); err != nil {
|
||||
if monitors, err = q.ListMonitors(ctx, p.Org.ID); err != nil {
|
||||
return err
|
||||
}
|
||||
if assigned, err = q.AllMonitorRegions(ctx); err != nil {
|
||||
if assigned, err = q.AllMonitorRegions(ctx, p.Org.ID); err != nil {
|
||||
return err
|
||||
}
|
||||
if regions, err = q.ListVisibleRegions(ctx); err != nil {
|
||||
@@ -326,13 +515,10 @@ func (s *Server) loadMonitorData(ctx context.Context, p *principal, rng web.Time
|
||||
if latest, err = q.LatestResults(ctx, p.Org.ID); err != nil {
|
||||
return err
|
||||
}
|
||||
if open, err = q.OpenIncidents(ctx); err != nil {
|
||||
if open, err = q.OpenIncidents(ctx, p.Org.ID); err != nil {
|
||||
return err
|
||||
}
|
||||
if spans, err = q.IncidentsSince(ctx, ptr(now.Add(-web.SLAWindows[len(web.SLAWindows)-1].Window))); err != nil {
|
||||
return err
|
||||
}
|
||||
if d.first, d.firstRegion, err = loadFirstData(ctx, q, p.Org.ID, now); err != nil {
|
||||
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 {
|
||||
@@ -342,10 +528,7 @@ func (s *Server) loadMonitorData(ctx context.Context, p *principal, rng web.Time
|
||||
for i, m := range monitors {
|
||||
ids[i] = m.ID
|
||||
}
|
||||
if d.maint, err = maintenanceFor(ctx, q, ids); err != nil {
|
||||
return err
|
||||
}
|
||||
d.buckets, err = rangeBuckets(ctx, q, p.Org.ID, nil, rng, now)
|
||||
d.maint, err = maintenanceFor(ctx, q, ids)
|
||||
return err
|
||||
})
|
||||
if err != nil {
|
||||
@@ -366,6 +549,13 @@ func (s *Server) loadMonitorData(ctx context.Context, p *principal, rng web.Time
|
||||
for _, a := range assigned {
|
||||
regionsOf[a.MonitorID] = append(regionsOf[a.MonitorID], a.RegionID)
|
||||
}
|
||||
for _, m := range monitors {
|
||||
if m.Enabled {
|
||||
d.usedRegions = append(d.usedRegions, regionsOf[m.ID]...)
|
||||
}
|
||||
}
|
||||
slices.SortFunc(d.usedRegions, func(a, b uuid.UUID) int { return strings.Compare(a.String(), b.String()) })
|
||||
d.usedRegions = slices.Compact(d.usedRegions)
|
||||
latestOf := map[uuid.UUID]map[string]store.LatestResultsRow{}
|
||||
for _, l := range latest {
|
||||
if latestOf[l.MonitorID] == nil {
|
||||
@@ -382,7 +572,10 @@ func (s *Server) loadMonitorData(ctx context.Context, p *principal, rng web.Time
|
||||
continue
|
||||
}
|
||||
d.byID[m.ID] = m
|
||||
row := web.MonitorRow{ID: m.ID.String(), Name: m.Name, Type: m.Type, Target: m.Target, Latency: "–", Uptime: "–"}
|
||||
row := web.MonitorRow{ID: m.ID.String(), Name: m.Name, Type: m.Type, Target: m.Target, Latency: "–", Uptime: "–", Position: -1, LatencyMS: -1}
|
||||
if m.Position != nil {
|
||||
row.Position = int(*m.Position)
|
||||
}
|
||||
keys := idStrings(regionsOf[m.ID])
|
||||
if check.Passive(check.Type(m.Type)) {
|
||||
// The target of a heartbeat is its secret ping token.
|
||||
@@ -393,9 +586,18 @@ func (s *Server) loadMonitorData(ctx context.Context, p *principal, rng web.Time
|
||||
}
|
||||
var latencies []int32
|
||||
failing, reported := 0, 0
|
||||
// A region that has not reported for longer than the evaluator
|
||||
// waits is unknown, whatever its last result said; passive monitors
|
||||
// judge their own lateness.
|
||||
staleBefore := now.Add(-evaluate.StaleAfter(time.Duration(m.IntervalSeconds) * time.Second))
|
||||
for _, key := range keys {
|
||||
rs := web.RegionStatus{Name: d.regionNameString(key), Status: web.StatusUnknown, Detail: "–"}
|
||||
if l, ok := latestOf[m.ID][key]; ok {
|
||||
l, ok := latestOf[m.ID][key]
|
||||
if ok && !check.Passive(check.Type(m.Type)) && l.Time.Before(staleBefore) {
|
||||
rs.Detail = i18n.T(ctx, "monitors.no_data_since", "Time", l.Time.Format("15:04"))
|
||||
ok = false
|
||||
}
|
||||
if ok {
|
||||
reported++
|
||||
rs.Detail = l.Time.Format("15:04:05")
|
||||
if l.Ok {
|
||||
@@ -421,6 +623,8 @@ func (s *Server) loadMonitorData(ctx context.Context, p *principal, rng web.Time
|
||||
row.Status = web.StatusDown
|
||||
case reported == 0:
|
||||
row.Status = web.StatusUnknown
|
||||
// Nobody is checking it, unless it is too new to have results.
|
||||
row.Unchecked = !check.Passive(check.Type(m.Type)) && m.CreatedAt.Before(staleBefore)
|
||||
case failing > 0:
|
||||
row.Status = web.StatusDegraded
|
||||
default:
|
||||
@@ -432,9 +636,10 @@ func (s *Server) loadMonitorData(ctx context.Context, p *principal, rng web.Time
|
||||
sum += l
|
||||
}
|
||||
row.Latency = fmt.Sprintf("%d ms", sum/int32(len(latencies)))
|
||||
row.LatencyMS = int(sum / int32(len(latencies)))
|
||||
}
|
||||
row.Uptime = web.SLAText(d.slaFor(m, rng.Window))
|
||||
row.Bars = web.UptimeBars(d.buckets[m.ID], now, rng.Bucket, rng.Bars(), rng.Layout)
|
||||
row.Ratio = d.slaFor(m, rng.Window)
|
||||
row.Uptime = web.SLAText(row.Ratio)
|
||||
d.rows = append(d.rows, row)
|
||||
}
|
||||
// Problems first, then by name.
|
||||
@@ -442,6 +647,23 @@ func (s *Server) loadMonitorData(ctx context.Context, p *principal, rng web.Time
|
||||
return d, nil
|
||||
}
|
||||
|
||||
// loadBars loads the bars of the selected range for the monitors ids.
|
||||
func (s *Server) loadBars(ctx context.Context, p *principal, d *monitorData, ids []uuid.UUID) error {
|
||||
if len(ids) == 0 {
|
||||
return nil
|
||||
}
|
||||
return s.db.Tx(ctx, p.scope(), func(q *store.Queries) error {
|
||||
var err error
|
||||
d.buckets, err = rangeBuckets(ctx, q, p.Org.ID, ids, d.rng, d.now)
|
||||
return err
|
||||
})
|
||||
}
|
||||
|
||||
// bars are the monitor's bars of the selected range, from loadBars.
|
||||
func (d monitorData) bars(id uuid.UUID) []web.Bar {
|
||||
return web.UptimeBars(d.buckets[id], d.now, d.rng.Bucket, d.rng.Bars(), d.rng.Layout)
|
||||
}
|
||||
|
||||
func (d monitorData) regionName(id uuid.UUID) string {
|
||||
if r, ok := d.regionOf[id]; ok {
|
||||
return r.Name
|
||||
@@ -464,6 +686,16 @@ func (s *Server) monitorDetail(c *gin.Context, p *principal, page web.Page, me w
|
||||
if !ok {
|
||||
return notFoundPage(c)
|
||||
}
|
||||
if err := s.loadBars(ctx, p, &d, []uuid.UUID{id}); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err := s.db.Tx(ctx, p.scope(), func(q *store.Queries) error {
|
||||
var err error
|
||||
d.first, d.firstRegion, err = loadFirstData(ctx, q, p.Org.ID, id, d.now)
|
||||
return err
|
||||
}); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
v := web.MonitorDetailView{
|
||||
Interval: (time.Duration(m.IntervalSeconds) * time.Second).String(),
|
||||
PingURL: s.detailPingURL(p, d, m),
|
||||
@@ -471,7 +703,7 @@ func (s *Server) monitorDetail(c *gin.Context, p *principal, page web.Page, me w
|
||||
Latency: web.Latency(d.buckets[id], d.now.Add(-d.rng.Window).Truncate(d.rng.Bucket), d.now, 480, 96),
|
||||
Maintenance: maintenanceItems(d.maint[id], d.now),
|
||||
Range: d.rng.Key,
|
||||
Ranges: rangeOptions(c, d.rng, d.first[id], d.now),
|
||||
Ranges: rangeOptions(c, d.rng, d.first, d.now),
|
||||
Uptime90: "–",
|
||||
}
|
||||
for _, r := range d.rows {
|
||||
@@ -479,6 +711,7 @@ func (s *Server) monitorDetail(c *gin.Context, p *principal, page web.Page, me w
|
||||
v.Row = r
|
||||
}
|
||||
}
|
||||
v.Row.Bars = d.bars(id)
|
||||
var (
|
||||
daily []store.DailyBucketsRow
|
||||
recent []store.ListResultsRow
|
||||
@@ -507,7 +740,7 @@ func (s *Server) monitorDetail(c *gin.Context, p *principal, page web.Page, me w
|
||||
for _, w := range web.SLAWindows {
|
||||
v.SLAs = append(v.SLAs, web.SLAEntry{
|
||||
Label: w.Key, Value: web.SLAText(d.slaFor(m, w.Window)),
|
||||
Partial: !web.HasEnoughData(d.first[id], d.now, w.Window),
|
||||
Partial: !web.HasEnoughData(d.first, d.now, w.Window),
|
||||
})
|
||||
}
|
||||
regions, err := s.regionHistory(ctx, p, d, m)
|
||||
@@ -1016,19 +1249,45 @@ func (s *Server) channelsView(c *gin.Context, p *principal, page web.Page, me we
|
||||
return web.ChannelsPage(page, me, v), nil
|
||||
}
|
||||
|
||||
func (s *Server) pageURL(p store.StatusPage) string {
|
||||
// cnameTarget is the host custom domains point at to reach the platform's
|
||||
// status page servers, unless that is not known.
|
||||
func (s *Server) cnameTarget() string {
|
||||
u, err := url.Parse(s.cfg.StatusPageURL)
|
||||
if err != nil {
|
||||
return ""
|
||||
}
|
||||
h := u.Hostname()
|
||||
if h == "" || h == "localhost" || net.ParseIP(h) != nil || !strings.Contains(h, ".") {
|
||||
return ""
|
||||
}
|
||||
return h
|
||||
}
|
||||
|
||||
// pageURL is where p is reachable, or empty when only the organization's
|
||||
// own status page servers serve it, at an address the platform does not
|
||||
// know.
|
||||
func (s *Server) pageURL(p store.StatusPage, ownServers bool) string {
|
||||
if p.CustomDomain != nil && p.DomainVerifiedAt != nil {
|
||||
return "https://" + *p.CustomDomain + "/"
|
||||
}
|
||||
if ownServers {
|
||||
return ""
|
||||
}
|
||||
return strings.TrimSuffix(s.cfg.StatusPageURL, "/") + "/" + p.Slug
|
||||
}
|
||||
|
||||
func (s *Server) statusPagesView(c *gin.Context, p *principal, page web.Page, me web.Me) (templ.Component, error) {
|
||||
ctx := c.Request.Context()
|
||||
var rows []store.StatusPage
|
||||
var (
|
||||
rows []store.StatusPage
|
||||
own bool
|
||||
)
|
||||
err := s.db.Tx(ctx, p.scope(), func(q *store.Queries) error {
|
||||
var err error
|
||||
rows, err = q.ListStatusPages(ctx)
|
||||
if rows, err = q.ListStatusPages(ctx); err != nil {
|
||||
return err
|
||||
}
|
||||
own, err = q.OrgServesOwnPages(ctx, &p.Org.ID)
|
||||
return err
|
||||
})
|
||||
if err != nil {
|
||||
@@ -1041,7 +1300,7 @@ func (s *Server) statusPagesView(c *gin.Context, p *principal, page web.Page, me
|
||||
}
|
||||
v.Pages = append(v.Pages, web.PageRow{
|
||||
ID: r.ID.String(), Title: r.Title, Slug: r.Slug, Published: r.Published,
|
||||
URL: s.pageURL(r), Domain: deref(r.CustomDomain), Suspended: r.SuspendedAt != nil,
|
||||
URL: s.pageURL(r, own), Domain: deref(r.CustomDomain), Suspended: r.SuspendedAt != nil,
|
||||
})
|
||||
}
|
||||
return web.StatusPagesPage(page, me, v), nil
|
||||
@@ -1059,6 +1318,8 @@ 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 {
|
||||
var err error
|
||||
@@ -1074,7 +1335,13 @@ func (s *Server) statusPageEditor(c *gin.Context, p *principal, page web.Page, m
|
||||
if orgGroups, err = q.ListGroups(ctx); err != nil {
|
||||
return err
|
||||
}
|
||||
monitors, err = q.ListMonitors(ctx)
|
||||
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
|
||||
})
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
@@ -1083,18 +1350,36 @@ func (s *Server) statusPageEditor(c *gin.Context, p *principal, page web.Page, m
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
v := viewStatusPage(row)
|
||||
v := s.viewStatusPage(row)
|
||||
e := web.PageEditor{
|
||||
ID: row.ID.String(), Title: row.Title, Slug: row.Slug, Description: row.Description,
|
||||
Published: row.Published, ShowDetails: row.ShowComponentDetails,
|
||||
Suspended: row.SuspendedAt != nil, SuspendedReason: row.SuspendedReason,
|
||||
Accent: v.Theme.Accent, LogoURL: v.Theme.LogoURL, CSS: v.Theme.CSS,
|
||||
URL: s.pageURL(row), Domain: deref(row.CustomDomain), DomainVerified: v.DomainVerified,
|
||||
URL: s.pageURL(row, own), OwnServers: own, Domain: deref(row.CustomDomain), DomainVerified: v.DomainVerified,
|
||||
HasOrgGroups: len(orgGroups) > 0,
|
||||
}
|
||||
if v.DomainRecord != nil {
|
||||
e.RecordName, e.RecordValue = v.DomainRecord.Name, v.DomainRecord.Value
|
||||
}
|
||||
e.DomainChangesPerDay = domainChangesPerDay
|
||||
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
|
||||
}
|
||||
e.VerifiedBy = deref(row.DomainVerifyMethod)
|
||||
if f := row.DomainFailingSince; f != nil {
|
||||
e.MissingSince = f.Local().Format("2006-01-02 15:04")
|
||||
e.SwitchOffAt = f.Add(domainGrace).Local().Format("2006-01-02 15:04")
|
||||
}
|
||||
newPageGroupTree(pageGroups).walk(func(g store.StatusPageGroup, depth int) {
|
||||
var parentID string
|
||||
if g.ParentID != nil {
|
||||
@@ -1292,7 +1577,7 @@ func (s *Server) regionHistory(ctx context.Context, p *principal, d monitorData,
|
||||
Name: d.regionNameString(r),
|
||||
Bars: web.UptimeBars(byRegion[r], d.now, rng.Bucket, rng.Bars(), rng.Layout),
|
||||
Uptime: "–",
|
||||
Enough: web.HasEnoughData(d.firstRegion[m.ID][r], d.now, rng.Window),
|
||||
Enough: web.HasEnoughData(d.firstRegion[r], d.now, rng.Window),
|
||||
}
|
||||
if u := web.Uptime(byRegion[r]); u >= 0 {
|
||||
h.Uptime = web.PercentPrecise(u)
|
||||
|
||||
@@ -0,0 +1,161 @@
|
||||
package api_test
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestDashboardFiltersByStatus(t *testing.T) {
|
||||
e := newEnv(t)
|
||||
_, region := e.platformChecker(t, uniq("eu-"))
|
||||
owner := e.browser(t)
|
||||
owner.signup("o@"+uniq("flt")+".test", uniq("flt-"))
|
||||
create := func(name string) string {
|
||||
t.Helper()
|
||||
st, m := owner.do("POST", "/api/v1/org/monitors", map[string]any{"name": name, "type": "http", "target": "https://" + strings.ToLower(name) + ".test", "interval_seconds": 60, "regions": []string{region}})
|
||||
if st != http.StatusCreated {
|
||||
t.Fatalf("create %s = %d %v", name, st, m)
|
||||
}
|
||||
return m["id"].(string)
|
||||
}
|
||||
create("Alpha")
|
||||
create("Beta")
|
||||
gamma := create("Gamma")
|
||||
owner.do("PUT", "/api/v1/org/monitors/"+gamma, map[string]any{"name": "Gamma", "type": "http", "target": "https://gamma.test", "interval_seconds": 60, "regions": []string{region}, "enabled": false})
|
||||
|
||||
_, _, all := owner.page("/")
|
||||
for _, want := range []string{`href="/?status=unknown"`, `href="/?status=paused"`, "Show only the 2 monitors that are no data", "Show only the 1 monitor that is paused"} {
|
||||
if !strings.Contains(all, want) {
|
||||
t.Errorf("the dashboard lacks %q", want)
|
||||
}
|
||||
}
|
||||
|
||||
_, _, paused := owner.page("/?status=paused")
|
||||
if !strings.Contains(paused, "Gamma") || strings.Contains(paused, "Alpha") || strings.Contains(paused, "Beta") {
|
||||
t.Error("?status=paused does not show only the paused monitor")
|
||||
}
|
||||
// The active filter links back to all, and the search keeps it.
|
||||
if !strings.Contains(paused, `aria-current="true"`) || !strings.Contains(paused, `title="Show all statuses"`) {
|
||||
t.Error("the active filter is not marked")
|
||||
}
|
||||
if !strings.Contains(paused, `name="status" value="paused"`) {
|
||||
t.Error("the search form drops the status filter")
|
||||
}
|
||||
|
||||
_, _, both := owner.page("/?status=unknown&q=alp")
|
||||
if !strings.Contains(both, "Alpha") || strings.Contains(both, "Beta") || strings.Contains(both, "Gamma") {
|
||||
t.Error("status filter and search do not combine")
|
||||
}
|
||||
if _, _, none := owner.page("/?status=down"); !strings.Contains(none, "No monitor has this status right now.") {
|
||||
t.Error("an empty filter does not say so")
|
||||
}
|
||||
// An unknown status shows everything.
|
||||
if _, _, bogus := owner.page("/?status=bogus"); !strings.Contains(bogus, "Alpha") || !strings.Contains(bogus, "Gamma") {
|
||||
t.Error("an unknown status filter hides monitors")
|
||||
}
|
||||
}
|
||||
|
||||
func TestSignupSendsSignedInUsersToTheMonitors(t *testing.T) {
|
||||
e := newEnv(t)
|
||||
visitor := e.browser(t)
|
||||
if st, path, _ := visitor.page("/signup"); st != http.StatusOK || path != "/signup" {
|
||||
t.Fatalf("signup for a visitor = %d at %s", st, path)
|
||||
}
|
||||
owner := e.browser(t)
|
||||
owner.signup("o@"+uniq("su")+".test", uniq("su-"))
|
||||
if st, path, html := owner.page("/signup"); st != http.StatusOK || path != "/" || !strings.Contains(html, "Monitors") {
|
||||
t.Errorf("signup when signed in ended at %s (%d), want the monitor list", path, st)
|
||||
}
|
||||
}
|
||||
|
||||
func TestPageEditorOffersAddAndRemoveAll(t *testing.T) {
|
||||
e := newEnv(t)
|
||||
_, region := e.platformChecker(t, uniq("eu-"))
|
||||
owner := e.browser(t)
|
||||
owner.signup("o@"+uniq("pa")+".test", uniq("pa-"))
|
||||
_, mon := owner.do("POST", "/api/v1/org/monitors", map[string]any{"name": "Shop", "type": "http", "target": "https://shop.test", "interval_seconds": 60, "regions": []string{region}})
|
||||
shop := mon["id"].(string)
|
||||
_, p := owner.do("POST", "/api/v1/org/statuspages", map[string]any{"slug": uniq("pa-"), "title": "Status"})
|
||||
_, _, html := owner.page("/statuspages/" + p["id"].(string))
|
||||
for _, want := range []string{`data-check-all="on"`, `data-check-all="off"`, "Add all", "Remove all"} {
|
||||
if !strings.Contains(html, want) {
|
||||
t.Errorf("the page editor lacks %q", want)
|
||||
}
|
||||
}
|
||||
// Monitors not on the page get their fields from the template only
|
||||
// when ticked, so thousands of them stay light.
|
||||
if n := strings.Count(html, `data-field="label"`); n != 1 || !strings.Contains(html, "<template data-row-fields>") {
|
||||
t.Errorf("the page editor renders %d label fields, want only the template's", n)
|
||||
}
|
||||
owner.do("PUT", "/api/v1/org/statuspages/"+p["id"].(string)+"/monitors", map[string]any{"monitors": []map[string]any{{"monitor_id": shop, "label": "Webshop"}}})
|
||||
if _, _, html := owner.page("/statuspages/" + p["id"].(string)); strings.Count(html, `data-field="label"`) != 2 || !strings.Contains(html, `value="Webshop"`) {
|
||||
t.Error("a monitor on the page lacks its fields")
|
||||
}
|
||||
}
|
||||
|
||||
func TestMonitorOrder(t *testing.T) {
|
||||
e := newEnv(t)
|
||||
_, region := e.platformChecker(t, uniq("eu-"))
|
||||
owner := e.browser(t)
|
||||
owner.signup("o@"+uniq("ord")+".test", uniq("ord-"))
|
||||
ids := map[string]string{}
|
||||
for _, n := range []string{"Alpha", "Bravo", "Charlie"} {
|
||||
_, m := owner.do("POST", "/api/v1/org/monitors", map[string]any{"name": n, "type": "http", "target": "https://" + strings.ToLower(n) + ".test", "interval_seconds": 60, "regions": []string{region}})
|
||||
ids[n] = m["id"].(string)
|
||||
}
|
||||
order := func(html string, names ...string) bool {
|
||||
last := -1
|
||||
for _, n := range names {
|
||||
i := strings.Index(html, ">"+n+"<")
|
||||
if i < last || i < 0 {
|
||||
return false
|
||||
}
|
||||
last = i
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
// Without an order of its own, by name.
|
||||
if _, _, html := owner.page("/"); !order(html, "Alpha", "Bravo", "Charlie") {
|
||||
t.Error("monitors without positions are not by name")
|
||||
}
|
||||
st, body := owner.do("PUT", "/api/v1/org/monitors/order", map[string]any{"monitor_ids": []string{ids["Charlie"], ids["Alpha"]}})
|
||||
if st != http.StatusNoContent {
|
||||
t.Fatalf("order = %d %v", st, body)
|
||||
}
|
||||
// Positioned ones first, in their order; the rest after, by name.
|
||||
_, _, html := owner.page("/")
|
||||
if !order(html, "Charlie", "Alpha", "Bravo") {
|
||||
t.Error("the list does not follow the organization's order")
|
||||
}
|
||||
if !strings.Contains(html, "?arrange=1") || !strings.Contains(html, "?sort=name") {
|
||||
t.Error("the dashboard offers neither arranging nor sorting")
|
||||
}
|
||||
if _, _, arr := owner.page("/?arrange=1"); !strings.Contains(arr, `data-sortable="/org/monitors/order"`) || !strings.Contains(arr, `data-sort-id="`+ids["Charlie"]+`"`) {
|
||||
t.Error("arranging does not show the sortable list")
|
||||
}
|
||||
|
||||
// Sorting by name is remembered until changed.
|
||||
if _, _, byName := owner.page("/?sort=name"); !order(byName, "Alpha", "Bravo", "Charlie") {
|
||||
t.Error("?sort=name does not sort by name")
|
||||
}
|
||||
if _, _, again := owner.page("/"); !order(again, "Alpha", "Bravo", "Charlie") || strings.Contains(again, "?arrange=1") {
|
||||
t.Error("the sort order is not remembered, or arranging is offered outside the own order")
|
||||
}
|
||||
owner.page("/?sort=custom")
|
||||
|
||||
// Unknown and duplicate monitors are refused, and nothing changes.
|
||||
st, body = owner.do("PUT", "/api/v1/org/monitors/order", map[string]any{"monitor_ids": []string{ids["Bravo"], "00000000-0000-0000-0000-000000000001"}})
|
||||
expect(t, "unknown monitor", st, body, http.StatusUnprocessableEntity, "invalid_monitor")
|
||||
st, body = owner.do("PUT", "/api/v1/org/monitors/order", map[string]any{"monitor_ids": []string{ids["Bravo"], ids["Bravo"]}})
|
||||
expect(t, "duplicate monitor", st, body, http.StatusUnprocessableEntity, "invalid_monitor")
|
||||
if _, _, html := owner.page("/"); !order(html, "Charlie", "Alpha", "Bravo") {
|
||||
t.Error("a refused order changed the list")
|
||||
}
|
||||
// Another organization cannot touch them.
|
||||
other := e.browser(t)
|
||||
other.signup("x@"+uniq("ord")+".test", uniq("ord-"))
|
||||
st, body = other.do("PUT", "/api/v1/org/monitors/order", map[string]any{"monitor_ids": []string{ids["Alpha"]}})
|
||||
expect(t, "another organization's monitor", st, body, http.StatusUnprocessableEntity, "invalid_monitor")
|
||||
}
|
||||
@@ -0,0 +1,176 @@
|
||||
package api
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"encoding/base32"
|
||||
"net"
|
||||
"slices"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"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"
|
||||
)
|
||||
|
||||
// A custom domain proves it belongs to its page in one of two ways:
|
||||
//
|
||||
// - a CNAME to <label>.<status page host>, where the label is unique to
|
||||
// the page. The platform's status page host has a wildcard record, so
|
||||
// the CNAME also routes the domain; one record does both. A CNAME to
|
||||
// the shared host alone would not do: it proves the domain points at
|
||||
// the platform, not which organization put it there.
|
||||
// - the TXT record _uptimesebi.<domain>, for domains whose CNAME cannot be
|
||||
// seen: behind a proxy such as Cloudflare's, or a domain without a
|
||||
// subdomain using ALIAS or CNAME flattening.
|
||||
//
|
||||
// The domain watch looks for them on its own after a domain is set, and
|
||||
// checks verified domains daily. One whose record has been missing for
|
||||
// domainGrace is switched off, so a record left behind after a page is
|
||||
// gone or moved cannot be claimed by anybody else.
|
||||
|
||||
const (
|
||||
domainWatchEvery = time.Minute
|
||||
domainGrace = 7 * 24 * time.Hour
|
||||
keyDomainWatch = "domainwatch:lock"
|
||||
)
|
||||
|
||||
// lookupCNAME is replaced in tests.
|
||||
var lookupCNAME = net.DefaultResolver.LookupCNAME
|
||||
|
||||
var labelEncoding = base32.NewEncoding("abcdefghijklmnopqrstuvwxyz234567").WithPadding(base32.NoPadding)
|
||||
|
||||
// cnameLabel is the page's label below the status page host, derived from
|
||||
// its domain token.
|
||||
func cnameLabel(token string) string {
|
||||
sum := sha256.Sum256([]byte("cname\x00" + token))
|
||||
return "p" + labelEncoding.EncodeToString(sum[:10])
|
||||
}
|
||||
|
||||
// cnameFor is the CNAME target of the page with token, or empty when the
|
||||
// platform's status page host is not known.
|
||||
func (s *Server) cnameFor(token string) string {
|
||||
host := s.cnameTarget()
|
||||
if host == "" {
|
||||
return ""
|
||||
}
|
||||
return cnameLabel(token) + "." + host
|
||||
}
|
||||
|
||||
// checkDomain looks for the records proving domain belongs to the page
|
||||
// with token and returns "cname", "txt" or "" for neither.
|
||||
func (s *Server) checkDomain(ctx context.Context, domain, token string) string {
|
||||
if target := s.cnameFor(token); target != "" {
|
||||
if c, err := lookupCNAME(ctx, domain); err == nil && strings.EqualFold(strings.TrimSuffix(c, "."), target) {
|
||||
return "cname"
|
||||
}
|
||||
}
|
||||
if records, err := lookupTXT(ctx, verifyPrefix+domain); err == nil && slices.Contains(records, token) {
|
||||
return "txt"
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
// RunDomainWatch checks custom domains until ctx ends. Replicas take
|
||||
// turns through a lock in Redis.
|
||||
func (s *Server) RunDomainWatch(ctx context.Context) {
|
||||
tick := time.NewTicker(domainWatchEvery)
|
||||
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 {
|
||||
s.log.WarnContext(ctx, "checking custom domains failed", "error", err)
|
||||
}
|
||||
}
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return
|
||||
case <-tick.C:
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// WatchDomains checks the domains that are due once.
|
||||
func (s *Server) WatchDomains(ctx context.Context, now time.Time) error {
|
||||
return s.watchDomains(ctx, now, nil)
|
||||
}
|
||||
|
||||
// watchDomains is WatchDomains limited to the page only, unless it is nil.
|
||||
func (s *Server) watchDomains(ctx context.Context, now time.Time, only *uuid.UUID) error {
|
||||
var due []store.DomainsToCheckRow
|
||||
if err := s.db.Tx(ctx, tenant.System(), func(q *store.Queries) error {
|
||||
var err error
|
||||
due, err = q.DomainsToCheck(ctx, store.DomainsToCheckParams{Now: now, PageID: only})
|
||||
return err
|
||||
}); err != nil {
|
||||
return err
|
||||
}
|
||||
for _, d := range due {
|
||||
if err := s.watchDomain(ctx, d, now); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *Server) watchDomain(ctx context.Context, d store.DomainsToCheckRow, now time.Time) error {
|
||||
method := s.checkDomain(ctx, d.Domain, d.DomainToken)
|
||||
var (
|
||||
failing *time.Time
|
||||
off bool
|
||||
)
|
||||
err := s.db.Tx(ctx, tenant.System(), func(q *store.Queries) error {
|
||||
if method != "" {
|
||||
return q.MarkDomainVerified(ctx, store.MarkDomainVerifiedParams{ID: d.ID, Now: now, Method: method})
|
||||
}
|
||||
var err error
|
||||
if failing, err = q.MarkDomainUnconfirmed(ctx, store.MarkDomainUnconfirmedParams{ID: d.ID, Now: now}); err != nil || failing == nil {
|
||||
return err
|
||||
}
|
||||
if now.Sub(*failing) >= domainGrace {
|
||||
off = true
|
||||
return q.UnverifyDomain(ctx, d.ID)
|
||||
}
|
||||
return nil
|
||||
})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
switch {
|
||||
case method != "" && d.DomainVerifiedAt == nil:
|
||||
s.log.InfoContext(ctx, "custom domain verified", "page", d.ID, "domain", d.Domain, "method", method)
|
||||
case off:
|
||||
s.log.InfoContext(ctx, "custom domain switched off: its record is gone", "page", d.ID, "domain", d.Domain)
|
||||
s.mailDomain(ctx, d, "email.domain_off", now)
|
||||
case failing != nil && d.DomainFailingSince == nil:
|
||||
s.log.InfoContext(ctx, "custom domain record missing", "page", d.ID, "domain", d.Domain)
|
||||
s.mailDomain(ctx, d, "email.domain_missing", now.Add(domainGrace))
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// mailDomain tells the organization's owners about d.
|
||||
func (s *Server) mailDomain(ctx context.Context, d store.DomainsToCheckRow, kind string, at time.Time) {
|
||||
if s.smtp == nil {
|
||||
return
|
||||
}
|
||||
var to []string
|
||||
if err := s.db.Tx(ctx, tenant.System(), func(q *store.Queries) error {
|
||||
var err error
|
||||
to, err = q.OrgOwnerEmails(ctx, d.OrgID)
|
||||
return err
|
||||
}); err != nil || len(to) == 0 {
|
||||
return
|
||||
}
|
||||
l := s.catalog.Match("")
|
||||
data := map[string]any{
|
||||
"Domain": d.Domain, "Page": d.Title, "Link": s.ticketLink("/statuspages/" + d.ID.String()),
|
||||
"Date": at.UTC().Format("2006-01-02 15:04 MST"),
|
||||
}
|
||||
if err := s.smtp.Send(ctx, notify.Mail{To: to, Subject: l.T(kind+".subject", data), Body: l.T(kind+".body", data)}); err != nil {
|
||||
s.log.WarnContext(ctx, "mail about a custom domain failed", "page", d.ID, "error", err)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,205 @@
|
||||
package api_test
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"net/http"
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"github.com/jackc/pgx/v5"
|
||||
|
||||
"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/notify/notifytest"
|
||||
)
|
||||
|
||||
// fakeDNS answers CNAME lookups from a map, and TXT lookups with nothing.
|
||||
type fakeDNS struct {
|
||||
mu sync.Mutex
|
||||
cname map[string]string
|
||||
}
|
||||
|
||||
func (d *fakeDNS) set(name, target string) {
|
||||
d.mu.Lock()
|
||||
defer d.mu.Unlock()
|
||||
if target == "" {
|
||||
delete(d.cname, name)
|
||||
} else {
|
||||
d.cname[name] = target
|
||||
}
|
||||
}
|
||||
|
||||
func useFakeDNS(t *testing.T) *fakeDNS {
|
||||
d := &fakeDNS{cname: map[string]string{}}
|
||||
savedC, savedT := *api.LookupCNAME, *api.LookupTXT
|
||||
t.Cleanup(func() { *api.LookupCNAME, *api.LookupTXT = savedC, savedT })
|
||||
*api.LookupCNAME = func(_ context.Context, name string) (string, error) {
|
||||
d.mu.Lock()
|
||||
defer d.mu.Unlock()
|
||||
if c, ok := d.cname[name]; ok {
|
||||
return c, nil
|
||||
}
|
||||
return "", errors.New("no such host")
|
||||
}
|
||||
*api.LookupTXT = func(context.Context, string) ([]string, error) { return nil, errors.New("no such record") }
|
||||
return d
|
||||
}
|
||||
|
||||
func TestCustomDomainByCNAME(t *testing.T) {
|
||||
mail := notifytest.NewSMTP(t)
|
||||
e := newEnvWith(t, func(c *config.API) {
|
||||
c.SMTPURL, c.SignupVerify = mail.URL(), "off"
|
||||
c.StatusPageURL = "https://status.platform.test"
|
||||
})
|
||||
ctx := context.Background()
|
||||
dns := useFakeDNS(t)
|
||||
platform := e.statuspageClient(t, nil)
|
||||
|
||||
newPage := func(b *browser) uuid.UUID {
|
||||
slug := uniq("cn-")
|
||||
_, p := b.do("POST", "/api/v1/org/statuspages", map[string]any{"slug": slug, "title": "Shop status"})
|
||||
b.do("PUT", "/api/v1/org/statuspages/"+p["id"].(string), map[string]any{"slug": slug, "title": "Shop status", "published": true})
|
||||
return uuid.MustParse(p["id"].(string))
|
||||
}
|
||||
setDomain := func(b *browser, id uuid.UUID, domain string) string {
|
||||
t.Helper()
|
||||
st, body := b.do("PUT", "/api/v1/org/statuspages/"+id.String()+"/domain", map[string]any{"domain": domain})
|
||||
if st != http.StatusOK {
|
||||
t.Fatalf("set domain = %d %v", st, body)
|
||||
}
|
||||
rec, _ := body["cname_record"].(map[string]any)
|
||||
if rec == nil || rec["name"] != domain {
|
||||
t.Fatalf("cname_record = %v", body["cname_record"])
|
||||
}
|
||||
return rec["value"].(string)
|
||||
}
|
||||
served := func(domain string) bool {
|
||||
_, err := platform.Page(ctx, domain, "")
|
||||
return err == nil
|
||||
}
|
||||
|
||||
a := e.browser(t)
|
||||
aEmail := "a@" + uniq("cn") + ".test"
|
||||
a.signup(aEmail, uniq("cn-"))
|
||||
pageA := newPage(a)
|
||||
domain := uniq("status") + ".shop.test"
|
||||
target := setDomain(a, pageA, domain)
|
||||
if !strings.HasSuffix(target, ".status.platform.test") || len(target) < 30 {
|
||||
t.Errorf("CNAME target %q is not unique to the page below the status host", target)
|
||||
}
|
||||
if _, _, html := a.page("/statuspages/" + pageA.String()); !strings.Contains(html, target+".") || !strings.Contains(html, "Check now") {
|
||||
t.Error("the editor does not show the page's CNAME record")
|
||||
}
|
||||
|
||||
// A CNAME to the shared host alone proves nothing.
|
||||
now := time.Now()
|
||||
dns.set(domain, "status.platform.test.")
|
||||
if err := e.api.WatchDomainOf(ctx, now, pageA); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if served(domain) {
|
||||
t.Fatal("a CNAME to the shared host verified the domain")
|
||||
}
|
||||
// The page's own target verifies it, without anybody pressing a button.
|
||||
dns.set(domain, strings.ToUpper(target)+".")
|
||||
if err := e.api.WatchDomainOf(ctx, now.Add(time.Minute), pageA); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !served(domain) {
|
||||
t.Fatal("the watch did not verify the domain by its CNAME")
|
||||
}
|
||||
if _, _, html := a.page("/statuspages/" + pageA.String()); !strings.Contains(html, "verified by its CNAME record") {
|
||||
t.Error("the editor does not say how the domain was verified")
|
||||
}
|
||||
|
||||
// Another organization taking the domain over, while the CNAME still
|
||||
// points at the first page, gets nowhere.
|
||||
a.do("PUT", "/api/v1/org/statuspages/"+pageA.String()+"/domain", map[string]any{"domain": ""})
|
||||
b := e.browser(t)
|
||||
b.signup("b@"+uniq("cn")+".test", uniq("cn-"))
|
||||
pageB := newPage(b)
|
||||
setDomain(b, pageB, domain)
|
||||
if err := e.api.WatchDomainOf(ctx, now.Add(2*time.Minute), pageB); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if st, _ := b.do("POST", "/api/v1/org/statuspages/"+pageB.String()+"/domain/verify", nil); st != http.StatusUnprocessableEntity || served(domain) {
|
||||
t.Fatalf("a record left by another page verified the domain (verify = %d)", st)
|
||||
}
|
||||
b.do("PUT", "/api/v1/org/statuspages/"+pageB.String()+"/domain", map[string]any{"domain": ""})
|
||||
|
||||
// Once verified, the record is checked daily. Gone, the owners are told
|
||||
// and, a week later, the domain is switched off.
|
||||
setDomain(a, pageA, domain)
|
||||
if st, body := a.do("POST", "/api/v1/org/statuspages/"+pageA.String()+"/domain/verify", nil); st != http.StatusNoContent {
|
||||
t.Fatalf("verify = %d %v", st, body)
|
||||
}
|
||||
dns.set(domain, "")
|
||||
day := now.Add(25 * time.Hour)
|
||||
if err := e.api.WatchDomainOf(ctx, day, pageA); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
waitFor(t, 5*time.Second, "a mail that the record is gone", func() bool {
|
||||
return mailedTo(mail, aEmail, "is gone", domain)
|
||||
})
|
||||
if !served(domain) {
|
||||
t.Error("the domain was switched off at once")
|
||||
}
|
||||
if _, _, html := a.page("/statuspages/" + pageA.String()); !strings.Contains(html, "has not been found since") {
|
||||
t.Error("the editor does not warn about the missing record")
|
||||
}
|
||||
if err := e.api.WatchDomainOf(ctx, day.Add(8*24*time.Hour), pageA); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if served(domain) {
|
||||
t.Error("the domain is still served a week after its record went")
|
||||
}
|
||||
waitFor(t, 5*time.Second, "a mail that the domain was switched off", func() bool {
|
||||
return mailedTo(mail, aEmail, "switched off", domain)
|
||||
})
|
||||
}
|
||||
|
||||
func TestDomainsVerifiedBeforeAreNotCheckedAgain(t *testing.T) {
|
||||
e := newEnvWith(t, func(c *config.API) { c.StatusPageURL = "https://status.platform.test" })
|
||||
ctx := context.Background()
|
||||
useFakeDNS(t)
|
||||
owner := e.browser(t)
|
||||
owner.signup("o@"+uniq("old")+".test", uniq("old-"))
|
||||
slug := uniq("old-")
|
||||
_, p := owner.do("POST", "/api/v1/org/statuspages", map[string]any{"slug": slug, "title": "Status"})
|
||||
id := p["id"].(string)
|
||||
owner.do("PUT", "/api/v1/org/statuspages/"+id, map[string]any{"slug": slug, "title": "Status", "published": true})
|
||||
domain := uniq("old") + ".example.test"
|
||||
owner.do("PUT", "/api/v1/org/statuspages/"+id+"/domain", map[string]any{"domain": domain})
|
||||
if err := e.asSystem(t, func(tx pgx.Tx) error {
|
||||
_, err := tx.Exec(ctx, `UPDATE status_pages SET domain_verified_at = now() - interval '1 year', domain_set_at = now() - interval '1 year' WHERE id = $1`, id)
|
||||
return err
|
||||
}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := e.api.WatchDomainOf(ctx, time.Now().Add(30*24*time.Hour), uuid.MustParse(id)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := e.statuspageClient(t, nil).Page(ctx, domain, ""); err != nil {
|
||||
t.Errorf("a domain verified before the checks was switched off: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func mailedTo(mail *notifytest.SMTP, to string, want ...string) bool {
|
||||
for _, m := range mail.Messages() {
|
||||
if !strings.Contains(strings.Join(m.To, ","), to) {
|
||||
continue
|
||||
}
|
||||
ok := true
|
||||
for _, w := range want {
|
||||
ok = ok && strings.Contains(m.Data, w)
|
||||
}
|
||||
if ok {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
package api_test
|
||||
|
||||
import (
|
||||
"context"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"git.zb-server.de/ZB-Server/uptimesebi/internal/agentapi"
|
||||
)
|
||||
|
||||
func TestLongPollsEndWhenDraining(t *testing.T) {
|
||||
e := newEnv(t)
|
||||
tok, _ := e.platformChecker(t, uniq("eu-"))
|
||||
drain := make(chan struct{})
|
||||
e.api.EndLongPollsOn(drain)
|
||||
client := agentapi.NewClient(e.srv.URL, tok, uuid.New(), "test").WithHTTPClient(e.srv.Client())
|
||||
|
||||
go func() { time.Sleep(300 * time.Millisecond); close(drain) }()
|
||||
start := time.Now()
|
||||
jobs, err := client.Jobs(context.Background(), 10, 20*time.Second)
|
||||
if err != nil || len(jobs) != 0 {
|
||||
t.Fatalf("Jobs() while draining = %v, %v; want no jobs and no error", jobs, err)
|
||||
}
|
||||
if took := time.Since(start); took > 3*time.Second {
|
||||
t.Errorf("a long poll ran %v after draining began, want it to end within about a second", took)
|
||||
}
|
||||
// Once draining, polls answer at once.
|
||||
start = time.Now()
|
||||
if _, err := client.Jobs(context.Background(), 10, 20*time.Second); err != nil || time.Since(start) > 2*time.Second {
|
||||
t.Errorf("a poll on a draining instance took %v (%v)", time.Since(start), err)
|
||||
}
|
||||
}
|
||||
@@ -1,5 +1,12 @@
|
||||
package api
|
||||
|
||||
import (
|
||||
"context"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
// LookupTXT lets tests replace DNS lookups for domain verification.
|
||||
var LookupTXT = &lookupTXT
|
||||
|
||||
@@ -17,3 +24,17 @@ func DocumentedRoutes() []string {
|
||||
|
||||
// OpenAPI builds the OpenAPI document.
|
||||
func OpenAPI() map[string]any { return buildOpenAPI("https://uptime.example") }
|
||||
|
||||
// WatchRegionsOf runs the region watch for the regions given only, so
|
||||
// tests are not slowed down by the regions other tests left behind.
|
||||
func (s *Server) WatchRegionsOf(ctx context.Context, now time.Time, ids ...uuid.UUID) error {
|
||||
return s.watchRegions(ctx, now, ids)
|
||||
}
|
||||
|
||||
// LookupCNAME lets tests replace DNS lookups for domain verification.
|
||||
var LookupCNAME = &lookupCNAME
|
||||
|
||||
// WatchDomainOf runs the domain watch for one page only.
|
||||
func (s *Server) WatchDomainOf(ctx context.Context, now time.Time, page uuid.UUID) error {
|
||||
return s.watchDomains(ctx, now, &page)
|
||||
}
|
||||
+14
-2
@@ -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 {
|
||||
@@ -472,7 +475,7 @@ func (s *Server) buildOrgExport(ctx context.Context, p *principal) (orgExport, e
|
||||
for _, a := range alertAssignments {
|
||||
alertGroupsByMonitor[a.MonitorID] = append(alertGroupsByMonitor[a.MonitorID], a.GroupID)
|
||||
}
|
||||
regionRows, err := q.AllMonitorRegions(ctx)
|
||||
regionRows, err := q.AllMonitorRegions(ctx, p.Org.ID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -480,7 +483,7 @@ func (s *Server) buildOrgExport(ctx context.Context, p *principal) (orgExport, e
|
||||
for _, r := range regionRows {
|
||||
regions[r.MonitorID] = append(regions[r.MonitorID], r.RegionID)
|
||||
}
|
||||
monitors, err := q.ListMonitors(ctx)
|
||||
monitors, err := q.ListMonitors(ctx, p.Org.ID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -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,
|
||||
})
|
||||
}
|
||||
|
||||
|
||||
@@ -92,13 +92,16 @@ func (s *Server) recordPassive(ctx context.Context, region string, id, org uuid.
|
||||
if msg != "" {
|
||||
row.Error = ptr(truncateValid(msg, 500))
|
||||
}
|
||||
var changed []uuid.UUID
|
||||
err := s.db.Tx(ctx, tenant.System(), func(q *store.Queries) error {
|
||||
_, err := q.InsertCheckResults(ctx, []store.InsertCheckResultsParams{row})
|
||||
var err error
|
||||
changed, err = insertResults(ctx, q, []store.InsertCheckResultsParams{row})
|
||||
return err
|
||||
})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
s.pagesChanged(ctx, changed...)
|
||||
s.evaluateResults(ctx, region,
|
||||
[]agentapi.Result{{MonitorID: id, ScheduledAt: at, StartedAt: at, OK: ok}},
|
||||
map[uuid.UUID]store.MonitorsForResultsRow{id: {
|
||||
|
||||
@@ -47,7 +47,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 +78,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)
|
||||
|
||||
@@ -0,0 +1,72 @@
|
||||
package api_test
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"github.com/jackc/pgx/v5"
|
||||
|
||||
"git.zb-server.de/ZB-Server/uptimesebi/internal/store"
|
||||
)
|
||||
|
||||
// TestLatestResultsKeepTheNewest checks that a result arriving late does
|
||||
// not replace a newer one, and that a batch keeps its newest per region.
|
||||
func TestLatestResultsKeepTheNewest(t *testing.T) {
|
||||
e := newEnv(t)
|
||||
_, region := e.platformChecker(t, uniq("eu-"))
|
||||
owner := e.browser(t)
|
||||
owner.signup("o@"+uniq("lr")+".test", uniq("lr-"))
|
||||
_, m := owner.do("POST", "/api/v1/org/monitors", map[string]any{"name": "Shop", "type": "http", "target": "https://shop.test", "interval_seconds": 60, "regions": []string{region}})
|
||||
id, org := uuid.MustParse(m["id"].(string)), uuid.MustParse(owner.orgID())
|
||||
now := time.Now().Truncate(time.Millisecond)
|
||||
upsert := func(rows ...map[string]any) {
|
||||
t.Helper()
|
||||
for _, r := range rows {
|
||||
r["monitor_id"], r["org_id"], r["region"] = id, org, region
|
||||
}
|
||||
b, _ := json.Marshal(rows)
|
||||
if err := e.asSystem(t, func(tx pgx.Tx) error {
|
||||
_, err := store.New(tx).UpsertLatestResults(context.Background(), b)
|
||||
return err
|
||||
}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
latest := func() (time.Time, bool) {
|
||||
t.Helper()
|
||||
var (
|
||||
at time.Time
|
||||
ok bool
|
||||
)
|
||||
if err := e.asSystem(t, func(tx pgx.Tx) error {
|
||||
return tx.QueryRow(context.Background(), `SELECT time, ok FROM latest_results WHERE monitor_id = $1`, id).Scan(&at, &ok)
|
||||
}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return at, ok
|
||||
}
|
||||
|
||||
upsert(map[string]any{"time": now.Add(-time.Minute), "ok": true}, map[string]any{"time": now, "ok": false, "error": "down"})
|
||||
if at, ok := latest(); !at.Equal(now) || ok {
|
||||
t.Errorf("after a batch latest = %v ok=%t, want the newest (%v, failed)", at, ok, now)
|
||||
}
|
||||
upsert(map[string]any{"time": now.Add(-30 * time.Second), "ok": true})
|
||||
if at, _ := latest(); !at.Equal(now) {
|
||||
t.Errorf("a late result replaced the newest: %v", at)
|
||||
}
|
||||
upsert(map[string]any{"time": now.Add(time.Minute), "ok": true, "latency_ms": 12})
|
||||
if at, ok := latest(); !at.Equal(now.Add(time.Minute)) || !ok {
|
||||
t.Errorf("a newer result was not kept: %v ok=%t", at, ok)
|
||||
}
|
||||
_, body := owner.do("GET", "/api/v1/org/monitors", nil)
|
||||
if got := body["monitors"].([]any)[0].(map[string]any)["latest"].([]any); len(got) != 1 {
|
||||
t.Errorf("the API lists %d latest results, want 1", len(got))
|
||||
}
|
||||
if _, _, html := owner.page("/monitors/" + id.String()); !strings.Contains(html, "12 ms") {
|
||||
t.Error("the monitor page does not show the latest result")
|
||||
}
|
||||
}
|
||||
+30
-12
@@ -36,11 +36,16 @@ type Limits struct {
|
||||
OwnRegionsCount bool `json:"own_regions_count"`
|
||||
// OrgsPerAccount limits the organizations an account owns.
|
||||
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{}
|
||||
}
|
||||
@@ -79,6 +84,8 @@ func (s *Server) orgLimits(ctx context.Context, org store.Org) Limits {
|
||||
override(&l.Monitors, org.LimitMonitors)
|
||||
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
|
||||
}
|
||||
@@ -189,6 +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=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) {
|
||||
@@ -239,10 +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"`
|
||||
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) {
|
||||
@@ -261,6 +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, SubscribersPerWeek: req.SubscribersPerWeek,
|
||||
})
|
||||
auditDetail(c, "slug", row.Slug)
|
||||
return err
|
||||
@@ -312,10 +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"`
|
||||
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 {
|
||||
@@ -342,9 +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}
|
||||
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})
|
||||
LimitRegionsPerMonitor: r.LimitRegionsPerMonitor, LimitOwnRegionsCount: r.LimitOwnRegionsCount,
|
||||
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 {
|
||||
@@ -403,7 +420,8 @@ func (s *Server) orgsView(c *gin.Context, pg pageReq) (web.OrgsView, error) {
|
||||
ID: o.ID.String(), Name: o.Name, Slug: o.Slug, Created: o.Created, Suspended: state(o.SuspendedAt, o.Reason),
|
||||
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),
|
||||
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)
|
||||
|
||||
@@ -155,3 +155,68 @@ func TestLimits(t *testing.T) {
|
||||
t.Error("the organization settings lack the usage")
|
||||
}
|
||||
}
|
||||
|
||||
func TestMonitorsPerStatusPageLimit(t *testing.T) {
|
||||
e := newEnv(t)
|
||||
ctx := context.Background()
|
||||
reset := func() {
|
||||
_ = e.asSystem(t, func(tx pgx.Tx) error {
|
||||
_, err := tx.Exec(ctx, `DELETE FROM platform_settings WHERE key = 'limits'`)
|
||||
return err
|
||||
})
|
||||
}
|
||||
reset()
|
||||
t.Cleanup(reset)
|
||||
admin := e.browser(t)
|
||||
admin.signup("admin@"+uniq("mpp")+".test", uniq("mpp-admin-"))
|
||||
if err := tenant.New(e.dbPool).Tx(ctx, tenant.Global(), func(q *store.Queries) error {
|
||||
return q.MakeAdmin(ctx, admin.userIDSelf())
|
||||
}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if st, body := admin.do("PUT", "/api/v1/admin/limits", map[string]any{"monitors_per_page": 2}); st != http.StatusNoContent {
|
||||
t.Fatalf("set defaults = %d %v", st, body)
|
||||
}
|
||||
|
||||
owner := e.browser(t)
|
||||
owner.signup("o@"+uniq("mpp")+".test", uniq("mpp-"))
|
||||
var ids []map[string]any
|
||||
for range 3 {
|
||||
_, m := owner.do("POST", "/api/v1/org/monitors", map[string]any{"name": "hb", "type": "heartbeat", "interval_seconds": 3600})
|
||||
ids = append(ids, map[string]any{"monitor_id": m["id"]})
|
||||
}
|
||||
_, page := owner.do("POST", "/api/v1/org/statuspages", map[string]any{"slug": uniq("mpp-"), "title": "Status"})
|
||||
set := func(n int) (int, map[string]any) {
|
||||
return owner.do("PUT", "/api/v1/org/statuspages/"+page["id"].(string)+"/monitors", map[string]any{"monitors": ids[:n]})
|
||||
}
|
||||
if st, body := set(2); st != http.StatusNoContent {
|
||||
t.Fatalf("two monitors = %d %v", st, body)
|
||||
}
|
||||
st, body := set(3)
|
||||
expect(t, "three monitors", st, body, http.StatusUnprocessableEntity, "page_monitor_limit")
|
||||
if _, _, html := owner.page("/statuspages/" + page["id"].(string)); !strings.Contains(html, "at most 2 monitors") {
|
||||
t.Error("the editor does not name the limit")
|
||||
}
|
||||
|
||||
// An override for the organization raises it; lowered again, the page
|
||||
// keeps its monitors but cannot grow.
|
||||
org := owner.orgID()
|
||||
if st, body := admin.do("PUT", "/api/v1/admin/orgs/"+org+"/limits", map[string]any{"monitors_per_page": 3}); st != http.StatusNoContent {
|
||||
t.Fatalf("override = %d %v", st, body)
|
||||
}
|
||||
if st, body := set(3); st != http.StatusNoContent {
|
||||
t.Fatalf("three monitors with the override = %d %v", st, body)
|
||||
}
|
||||
admin.do("PUT", "/api/v1/admin/orgs/"+org+"/limits", map[string]any{"monitors_per_page": 1})
|
||||
if st, body := set(3); st != http.StatusNoContent {
|
||||
t.Errorf("saving a page beyond a lowered limit = %d %v", st, body)
|
||||
}
|
||||
if st, body := set(2); st != http.StatusNoContent {
|
||||
t.Errorf("shrinking a page beyond a lowered limit = %d %v", st, body)
|
||||
}
|
||||
st, body = set(3)
|
||||
expect(t, "growing again beyond the lowered limit", st, body, http.StatusUnprocessableEntity, "page_monitor_limit")
|
||||
if _, _, html := admin.page("/admin"); !strings.Contains(html, "Monitors per status page") {
|
||||
t.Error("the admin page does not offer the limit")
|
||||
}
|
||||
}
|
||||
@@ -234,7 +234,7 @@ func (s *Server) loadMaintenanceScope(ctx context.Context, p *principal) (mainte
|
||||
return ms, err
|
||||
}
|
||||
err = s.db.Tx(ctx, p.scope(), func(q *store.Queries) error {
|
||||
rows, err := q.ListMonitors(ctx)
|
||||
rows, err := q.ListMonitors(ctx, p.Org.ID)
|
||||
for _, m := range rows {
|
||||
ms.monitors[m.ID] = m
|
||||
}
|
||||
|
||||
@@ -0,0 +1,66 @@
|
||||
package api
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"net/http"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/google/uuid"
|
||||
"github.com/jackc/pgx/v5"
|
||||
|
||||
"git.zb-server.de/ZB-Server/uptimesebi/internal/authz"
|
||||
"git.zb-server.de/ZB-Server/uptimesebi/internal/store"
|
||||
)
|
||||
|
||||
type monitorOrderRequest struct {
|
||||
// MonitorIDs in the order wanted; usually the monitors of one group.
|
||||
MonitorIDs []uuid.UUID `json:"monitor_ids" binding:"required,min=1,max=1000"`
|
||||
}
|
||||
|
||||
// orderMonitors stores the organization's own order of the monitors given,
|
||||
// which the monitor list follows when sorted by its own order. It needs
|
||||
// write access to every one of them.
|
||||
func (s *Server) orderMonitors(c *gin.Context) {
|
||||
var req monitorOrderRequest
|
||||
if !bind(c, &req) {
|
||||
return
|
||||
}
|
||||
p := current(c)
|
||||
ctx := c.Request.Context()
|
||||
t, err := s.loadGroupTree(ctx, p.scope())
|
||||
if err != nil {
|
||||
internalError(c, err)
|
||||
return
|
||||
}
|
||||
errDenied := errors.New("denied")
|
||||
seen := map[uuid.UUID]bool{}
|
||||
err = s.db.Tx(ctx, p.scope(), func(q *store.Queries) error {
|
||||
for i, id := range req.MonitorIDs {
|
||||
if seen[id] {
|
||||
return pgx.ErrNoRows
|
||||
}
|
||||
seen[id] = true
|
||||
m, err := q.GetMonitor(ctx, id)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if !canInGroup(p, authz.MonitorsWrite, t, m.GroupID) {
|
||||
return errDenied
|
||||
}
|
||||
if _, err := q.SetMonitorPosition(ctx, store.SetMonitorPositionParams{ID: id, Position: new(int32(i))}); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
})
|
||||
switch {
|
||||
case errors.Is(err, errDenied):
|
||||
fail(c, http.StatusForbidden, "forbidden")
|
||||
case errors.Is(err, pgx.ErrNoRows):
|
||||
fail(c, http.StatusUnprocessableEntity, "invalid_monitor")
|
||||
case err != nil:
|
||||
internalError(c, err)
|
||||
default:
|
||||
c.Status(http.StatusNoContent)
|
||||
}
|
||||
}
|
||||
@@ -220,7 +220,7 @@ func (s *Server) listMonitors(c *gin.Context) {
|
||||
for _, a := range assignments {
|
||||
alertGroups[a.MonitorID] = append(alertGroups[a.MonitorID], a.GroupID)
|
||||
}
|
||||
regions, err := q.AllMonitorRegions(ctx)
|
||||
regions, err := q.AllMonitorRegions(ctx, p.Org.ID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
@@ -122,6 +122,11 @@ func (s *Server) signupOptions(ctx context.Context) (bool, []web.IDPButton, erro
|
||||
}
|
||||
|
||||
func (s *Server) signupPage(c *gin.Context) {
|
||||
// Signed in already: straight to the monitors.
|
||||
if auth.Current(c) != nil {
|
||||
c.Redirect(http.StatusSeeOther, "/")
|
||||
return
|
||||
}
|
||||
email, providers, err := s.signupOptions(c.Request.Context())
|
||||
if err != nil {
|
||||
internalError(c, err)
|
||||
|
||||
@@ -0,0 +1,164 @@
|
||||
package api
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"slices"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"github.com/redis/go-redis/v9"
|
||||
|
||||
"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"
|
||||
)
|
||||
|
||||
// A region whose checkers have all gone leaves its monitors unchecked:
|
||||
// they neither go down nor alert. The region watch tells those who run the
|
||||
// region, the platform's admins for platform regions and the owners for an
|
||||
// organization's own, once it has had no live checker for
|
||||
// UPTIME_REGION_ALERT_AFTER, and again when one is back. Every replica runs
|
||||
// it; Redis decides which one sends.
|
||||
|
||||
const (
|
||||
regionWatchEvery = 30 * time.Second
|
||||
// regionWatchTTL bounds the state of a region; one dead for longer is
|
||||
// announced again.
|
||||
regionWatchTTL = 30 * 24 * time.Hour
|
||||
)
|
||||
|
||||
func keyRegionDeadSince(id uuid.UUID) string { return "regionwatch:since:" + id.String() }
|
||||
func keyRegionAlerted(id uuid.UUID) string { return "regionwatch:alerted:" + id.String() }
|
||||
|
||||
// RunRegionWatch watches the regions until ctx ends.
|
||||
func (s *Server) RunRegionWatch(ctx context.Context) {
|
||||
if s.cfg.RegionAlertAfter <= 0 {
|
||||
return
|
||||
}
|
||||
tick := time.NewTicker(regionWatchEvery)
|
||||
defer tick.Stop()
|
||||
for {
|
||||
if err := s.WatchRegions(ctx, time.Now()); err != nil && ctx.Err() == nil {
|
||||
s.log.WarnContext(ctx, "watching regions failed", "error", err)
|
||||
}
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return
|
||||
case <-tick.C:
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// WatchRegions checks every region with checkers and enabled monitors once.
|
||||
func (s *Server) WatchRegions(ctx context.Context, now time.Time) error {
|
||||
return s.watchRegions(ctx, now, nil)
|
||||
}
|
||||
|
||||
// watchRegions is WatchRegions limited to only, unless only is nil.
|
||||
func (s *Server) watchRegions(ctx context.Context, now time.Time, only []uuid.UUID) error {
|
||||
var regions []store.RegionsToWatchRow
|
||||
if err := s.db.Tx(ctx, tenant.System(), func(q *store.Queries) error {
|
||||
var err error
|
||||
regions, err = q.RegionsToWatch(ctx)
|
||||
return err
|
||||
}); err != nil {
|
||||
return err
|
||||
}
|
||||
for _, r := range regions {
|
||||
if only != nil && !slices.Contains(only, r.ID) {
|
||||
continue
|
||||
}
|
||||
live, err := s.sched.Instances(ctx, r.ID.String())
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if live > 0 {
|
||||
since, _ := s.rdb.GetDel(ctx, keyRegionDeadSince(r.ID)).Time()
|
||||
// Only the replica that clears the alert announces the return.
|
||||
if n, err := s.rdb.Del(ctx, keyRegionAlerted(r.ID)).Result(); err == nil && n > 0 {
|
||||
s.mailRegion(ctx, r, since, now, false)
|
||||
}
|
||||
continue
|
||||
}
|
||||
if err := s.rdb.SetNX(ctx, keyRegionDeadSince(r.ID), now, regionWatchTTL).Err(); err != nil {
|
||||
return err
|
||||
}
|
||||
since, err := s.rdb.Get(ctx, keyRegionDeadSince(r.ID)).Time()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if now.Sub(since) < s.cfg.RegionAlertAfter {
|
||||
continue
|
||||
}
|
||||
if first, err := s.rdb.SetNX(ctx, keyRegionAlerted(r.ID), 1, regionWatchTTL).Result(); err == nil && first {
|
||||
if !s.mailRegion(ctx, r, since, now, true) {
|
||||
// Tried again on the next round.
|
||||
s.rdb.Del(ctx, keyRegionAlerted(r.ID))
|
||||
}
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// regionsWithoutChecker returns since when each of ids has had no live
|
||||
// checker, for those the watch found without one.
|
||||
func (s *Server) regionsWithoutChecker(ctx context.Context, ids []uuid.UUID) map[uuid.UUID]time.Time {
|
||||
out := map[uuid.UUID]time.Time{}
|
||||
for _, id := range ids {
|
||||
since, err := s.rdb.Get(ctx, keyRegionDeadSince(id)).Time()
|
||||
if err == nil {
|
||||
out[id] = since
|
||||
} else if !errors.Is(err, redis.Nil) {
|
||||
s.log.WarnContext(ctx, "reading region watch failed", "region", id, "error", err)
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// mailRegion tells the admins or the owners that r has no live checker
|
||||
// since since, or, when down is false, that it has one again. It reports
|
||||
// false if the mail could not be sent and should be tried again.
|
||||
func (s *Server) mailRegion(ctx context.Context, r store.RegionsToWatchRow, since, now time.Time, down bool) bool {
|
||||
if s.smtp == nil {
|
||||
return true
|
||||
}
|
||||
var to []string
|
||||
link := "/admin"
|
||||
err := s.db.Tx(ctx, tenant.System(), func(q *store.Queries) error {
|
||||
var err error
|
||||
if r.OrgID == nil {
|
||||
to, err = q.AdminEmails(ctx)
|
||||
} else {
|
||||
link = "/settings/regions"
|
||||
to, err = q.OrgOwnerEmails(ctx, *r.OrgID)
|
||||
}
|
||||
return err
|
||||
})
|
||||
if err != nil || len(to) == 0 {
|
||||
if err != nil {
|
||||
s.log.WarnContext(ctx, "finding whom to tell about a region failed", "region", r.ID, "error", err)
|
||||
return false
|
||||
}
|
||||
return true
|
||||
}
|
||||
l := s.catalog.Match("")
|
||||
data := map[string]any{
|
||||
"Region": r.Name, "Org": deref(r.OrgName), "Link": s.ticketLink(link),
|
||||
"Since": since.UTC().Format("2006-01-02 15:04 MST"),
|
||||
"Minutes": int(now.Sub(since).Minutes()),
|
||||
}
|
||||
kind := "email.region_back"
|
||||
if down {
|
||||
kind = "email.region_down"
|
||||
}
|
||||
if since.IsZero() {
|
||||
data["Since"], data["Minutes"] = "–", 0
|
||||
}
|
||||
if err := s.smtp.Send(ctx, notify.Mail{To: to, Subject: l.T(kind+".subject", data), Body: l.T(kind+".body", data)}); err != nil {
|
||||
s.log.WarnContext(ctx, "mail about a region failed", "region", r.ID, "error", err)
|
||||
return false
|
||||
}
|
||||
s.log.InfoContext(ctx, "told about a region", "region", r.ID, "down", down, "recipients", len(to))
|
||||
return true
|
||||
}
|
||||
@@ -0,0 +1,135 @@
|
||||
package api_test
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/http"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"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/config"
|
||||
"git.zb-server.de/ZB-Server/uptimesebi/internal/notify/notifytest"
|
||||
)
|
||||
|
||||
func TestUncheckedMonitorsAndRegionsWithoutChecker(t *testing.T) {
|
||||
mail := notifytest.NewSMTP(t)
|
||||
e := newEnvWith(t, func(c *config.API) {
|
||||
c.SMTPURL, c.SignupVerify, c.RegionAlertAfter = mail.URL(), "off", 3*time.Minute
|
||||
})
|
||||
ctx := context.Background()
|
||||
owner := e.browser(t)
|
||||
ownerEmail := "o@" + uniq("rw") + ".test"
|
||||
owner.signup(ownerEmail, uniq("rw-"))
|
||||
// An organization's own region: its owners hear about it.
|
||||
regionName := uniq("Office ")
|
||||
_, reg := owner.do("POST", "/api/v1/org/regions", map[string]any{"key": uniq("office-"), "name": regionName})
|
||||
region := reg["id"].(string)
|
||||
regionID := uuid.MustParse(region)
|
||||
st, agent := owner.do("POST", "/api/v1/org/agents", map[string]any{"kind": "checker", "name": "office-1", "region_id": region})
|
||||
if st != http.StatusCreated {
|
||||
t.Fatalf("create agent = %d %v", st, agent)
|
||||
}
|
||||
tok := agent["token"].(string)
|
||||
mailed := func(to, want string) {
|
||||
t.Helper()
|
||||
waitFor(t, 5*time.Second, "a mail saying "+want, func() bool {
|
||||
for _, m := range mail.Messages() {
|
||||
if strings.Contains(strings.Join(m.To, ","), to) && strings.Contains(m.Data, want) && strings.Contains(m.Data, regionName) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
})
|
||||
}
|
||||
|
||||
// A monitor whose only region last reported ten minutes ago is not
|
||||
// up: nobody is checking it.
|
||||
_, mon := owner.do("POST", "/api/v1/org/monitors", map[string]any{"name": "Shop", "type": "http", "target": "https://example.test", "interval_seconds": 60, "regions": []string{region}})
|
||||
id := mon["id"].(string)
|
||||
org := uuid.MustParse(owner.orgID())
|
||||
if err := e.asSystem(t, func(tx pgx.Tx) error {
|
||||
if _, err := tx.Exec(ctx, `UPDATE monitors SET created_at = now() - interval '1 hour' WHERE id = $1`, id); err != nil {
|
||||
return err
|
||||
}
|
||||
if _, err := tx.Exec(ctx, `INSERT INTO check_results (time, org_id, monitor_id, region, checker_id, ok, latency_ms) VALUES (now() - interval '10 minutes', $1, $2, $3, $4, true, 10)`,
|
||||
org, id, region, uuid.New()); err != nil {
|
||||
return err
|
||||
}
|
||||
// As the API keeps it when the result arrives.
|
||||
_, err := tx.Exec(ctx, `INSERT INTO latest_results (time, org_id, monitor_id, region, ok, latency_ms) VALUES (now() - interval '10 minutes', $1, $2, $3, true, 10)`,
|
||||
org, id, region)
|
||||
return err
|
||||
}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
_, _, dash := owner.page("/")
|
||||
for _, want := range []string{"not being checked", "1 monitor is not being checked"} {
|
||||
if !strings.Contains(dash, want) {
|
||||
t.Errorf("dashboard lacks %q", want)
|
||||
}
|
||||
}
|
||||
if _, _, detail := owner.page("/monitors/" + id); !strings.Contains(detail, "no data since") || !strings.Contains(detail, "1 monitor is not being checked") {
|
||||
t.Error("the monitor page does not say the region has no recent data")
|
||||
}
|
||||
|
||||
// On a status page it shows as unknown, not as operational.
|
||||
slug := uniq("rw-")
|
||||
_, page := owner.do("POST", "/api/v1/org/statuspages", map[string]any{"slug": slug, "title": "Shop status"})
|
||||
owner.do("PUT", "/api/v1/org/statuspages/"+page["id"].(string)+"/monitors", map[string]any{"monitors": []map[string]any{{"monitor_id": id}}})
|
||||
owner.do("PUT", "/api/v1/org/statuspages/"+page["id"].(string), map[string]any{"slug": slug, "title": "Shop status", "published": true})
|
||||
snap, err := e.statuspageClient(t, &org).Page(ctx, "", slug)
|
||||
if err != nil || len(snap.Sections) != 1 || snap.Sections[0].Components[0].Status != agentapi.PageUnknown {
|
||||
t.Errorf("status page = %+v, %v; want the component unknown", snap.Sections, err)
|
||||
}
|
||||
|
||||
// The region has a checker but no live instance: the watch notes it at
|
||||
// once and tells the owners once it has lasted.
|
||||
now := time.Now()
|
||||
if err := e.api.WatchRegionsOf(ctx, now, regionID); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, _, dash := owner.page("/"); !strings.Contains(dash, "Region "+regionName+" has had no active checker since") {
|
||||
t.Error("the dashboard does not name the region without a checker")
|
||||
}
|
||||
if err := e.api.WatchRegionsOf(ctx, now.Add(5*time.Minute), regionID); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
mailed(ownerEmail, "has no active checker")
|
||||
sent := len(mail.Messages())
|
||||
if err := e.api.WatchRegionsOf(ctx, now.Add(10*time.Minute), regionID); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
time.Sleep(200 * time.Millisecond)
|
||||
if n := countMails(mail.Messages()[sent:], regionName); n != 0 {
|
||||
t.Errorf("the region was announced %d more times", n)
|
||||
}
|
||||
|
||||
// A checker coming back is announced too.
|
||||
e.startChecker(t, tok)
|
||||
waitFor(t, 15*time.Second, "the checker to count as live", func() bool {
|
||||
_ = e.api.WatchRegionsOf(ctx, time.Now(), regionID)
|
||||
for _, m := range mail.Messages() {
|
||||
if strings.Contains(m.Data, "is checking again") && strings.Contains(m.Data, regionName) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
})
|
||||
if _, _, dash := owner.page("/"); strings.Contains(dash, "Region "+regionName+" has had no active checker") {
|
||||
t.Error("the dashboard still names the region")
|
||||
}
|
||||
}
|
||||
|
||||
func countMails(ms []notifytest.Message, about string) int {
|
||||
n := 0
|
||||
for _, m := range ms {
|
||||
if strings.Contains(m.Data, about) {
|
||||
n++
|
||||
}
|
||||
}
|
||||
return n
|
||||
}
|
||||
@@ -0,0 +1,74 @@
|
||||
package api
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"slices"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"git.zb-server.de/ZB-Server/uptimesebi/internal/store"
|
||||
)
|
||||
|
||||
// regionKey identifies a monitor in one region.
|
||||
type regionKey struct {
|
||||
monitor uuid.UUID
|
||||
region string
|
||||
}
|
||||
|
||||
// latestRow is a result as UpsertLatestResults reads it.
|
||||
type latestRow struct {
|
||||
MonitorID uuid.UUID `json:"monitor_id"`
|
||||
Region string `json:"region"`
|
||||
OrgID uuid.UUID `json:"org_id"`
|
||||
Time time.Time `json:"time"`
|
||||
OK bool `json:"ok"`
|
||||
LatencyMS *int32 `json:"latency_ms"`
|
||||
StatusCode *int32 `json:"status_code"`
|
||||
Error *string `json:"error"`
|
||||
}
|
||||
|
||||
// insertResults stores results and keeps the newest per monitor and
|
||||
// region in latest_results, which the console reads instead of a day of
|
||||
// results. It returns the organizations whose status changed somewhere,
|
||||
// for pagesChanged once the transaction is committed.
|
||||
func insertResults(ctx context.Context, q *store.Queries, rows []store.InsertCheckResultsParams) ([]uuid.UUID, error) {
|
||||
if _, err := q.InsertCheckResults(ctx, rows); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
latest := make([]latestRow, len(rows))
|
||||
for i, r := range rows {
|
||||
latest[i] = latestRow{
|
||||
MonitorID: r.MonitorID, Region: r.Region, OrgID: r.OrgID, Time: r.Time, OK: r.Ok,
|
||||
LatencyMS: r.LatencyMs, StatusCode: r.StatusCode, Error: r.Error,
|
||||
}
|
||||
}
|
||||
b, err := json.Marshal(latest)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
ids := make([]uuid.UUID, len(rows))
|
||||
for i, r := range rows {
|
||||
ids[i] = r.MonitorID
|
||||
}
|
||||
before, err := q.LatestOK(ctx, ids)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
was := make(map[regionKey]bool, len(before))
|
||||
for _, r := range before {
|
||||
was[regionKey{r.MonitorID, r.Region}] = r.Ok
|
||||
}
|
||||
written, err := q.UpsertLatestResults(ctx, b)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var changed []uuid.UUID
|
||||
for _, w := range written {
|
||||
if ok, seen := was[regionKey{w.MonitorID, w.Region}]; (!seen || ok != w.Ok) && !slices.Contains(changed, w.OrgID) {
|
||||
changed = append(changed, w.OrgID)
|
||||
}
|
||||
}
|
||||
return changed, nil
|
||||
}
|
||||
+20
-2
@@ -10,6 +10,7 @@ import (
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/go-playground/validator/v10"
|
||||
"github.com/redis/go-redis/v9"
|
||||
"golang.org/x/sync/singleflight"
|
||||
|
||||
"git.zb-server.de/ZB-Server/uptimesebi/internal/agentapi"
|
||||
"git.zb-server.de/ZB-Server/uptimesebi/internal/auth"
|
||||
@@ -55,6 +56,13 @@ type Server struct {
|
||||
limits *versioned[Limits]
|
||||
// support caches how the platform runs support tickets.
|
||||
support *versioned[supportSettings]
|
||||
// draining, once closed, ends the long polls of checkers.
|
||||
draining <-chan struct{}
|
||||
// handler serves the requests agents send over their streams.
|
||||
handler http.Handler
|
||||
// snapshots lets status page servers asking for the same page at once
|
||||
// share one build of it.
|
||||
snapshots singleflight.Group
|
||||
}
|
||||
|
||||
// Deps are the external resources a Server needs.
|
||||
@@ -94,9 +102,16 @@ func New(cfg config.API, d Deps) *Server {
|
||||
}
|
||||
}
|
||||
|
||||
// EndLongPollsOn makes the checkers' long polls return as soon as ch is
|
||||
// closed, as when the instance starts draining for a shutdown.
|
||||
func (s *Server) EndLongPollsOn(ch <-chan struct{}) { s.draining = ch }
|
||||
|
||||
// Mount installs session loading, locale resolution and CSRF protection and
|
||||
// registers the JSON API and the console pages below them.
|
||||
func (s *Server) Mount(r gin.IRouter) {
|
||||
if h, ok := r.(http.Handler); ok {
|
||||
s.handler = h
|
||||
}
|
||||
// Agents authenticate with tokens and never carry cookies, so they skip
|
||||
// the session and CSRF middleware.
|
||||
s.mountAgentAPI(r)
|
||||
@@ -145,7 +160,7 @@ func (s *Server) Mount(r gin.IRouter) {
|
||||
v1.POST("/invitations/:token/accept", auth.Require(), s.acceptInvitation)
|
||||
v1.POST("/invitations/:token/signup", s.inviteSignup)
|
||||
|
||||
org := v1.Group("/org", s.orgAccess())
|
||||
org := v1.Group("/org", s.orgAccess(), s.announcePages())
|
||||
org.PUT("/policy", sessionOnly(), can(authz.OrgManage), s.updatePolicy)
|
||||
org.GET("/export", sessionOnly(), can(authz.OrgManage), s.exportOrg)
|
||||
org.GET("/legal", can(authz.OrgManage), s.orgListLegal)
|
||||
@@ -156,6 +171,7 @@ func (s *Server) Mount(r gin.IRouter) {
|
||||
// scoped to a group grant access below that group only.
|
||||
org.GET("/monitors", s.listMonitors)
|
||||
org.POST("/monitors", s.createMonitor)
|
||||
org.PUT("/monitors/order", s.orderMonitors)
|
||||
org.PUT("/monitors/:id", s.updateMonitor)
|
||||
org.DELETE("/monitors/:id", s.deleteMonitor)
|
||||
org.GET("/monitors/:id/evidence", s.listEvidence)
|
||||
@@ -186,7 +202,7 @@ func (s *Server) Mount(r gin.IRouter) {
|
||||
org.PATCH("/agents/:id", sessionOnly(), can(authz.OrgManage), s.updateOrgAgent)
|
||||
org.DELETE("/agents/:id", sessionOnly(), can(authz.OrgManage), s.deleteOrgAgent)
|
||||
|
||||
admin := v1.Group("/admin", s.requireAdmin())
|
||||
admin := v1.Group("/admin", s.requireAdmin(), s.announcePages())
|
||||
admin.GET("/audit", s.listPlatformAudit)
|
||||
admin.GET("/check-types", s.adminListCheckTypes)
|
||||
admin.PUT("/check-types", s.adminSetCheckTypes)
|
||||
@@ -235,6 +251,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)
|
||||
|
||||
|
||||
+177
-35
@@ -22,6 +22,8 @@ import (
|
||||
|
||||
"git.zb-server.de/ZB-Server/uptimesebi/internal/agentapi"
|
||||
"git.zb-server.de/ZB-Server/uptimesebi/internal/authz"
|
||||
"git.zb-server.de/ZB-Server/uptimesebi/internal/check"
|
||||
"git.zb-server.de/ZB-Server/uptimesebi/internal/evaluate"
|
||||
"git.zb-server.de/ZB-Server/uptimesebi/internal/store"
|
||||
"git.zb-server.de/ZB-Server/uptimesebi/internal/tenant"
|
||||
"git.zb-server.de/ZB-Server/uptimesebi/internal/web"
|
||||
@@ -33,6 +35,9 @@ const (
|
||||
// verifyPrefix is the label under which customers publish the TXT record
|
||||
// proving control of a custom domain.
|
||||
verifyPrefix = "_uptimesebi."
|
||||
// domainChangesPerDay bounds how often an organization may set a new
|
||||
// custom domain.
|
||||
domainChangesPerDay = 10
|
||||
)
|
||||
|
||||
var (
|
||||
@@ -48,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(),
|
||||
@@ -79,10 +85,15 @@ func (s *Server) buildSnapshot(ctx context.Context, page store.StatusPage) (agen
|
||||
for i, m := range listed {
|
||||
ids[i] = m.MonitorID
|
||||
}
|
||||
if latest, err = q.LatestResults(ctx, page.OrgID); err != nil {
|
||||
rows, err := q.LatestResultsForMonitors(ctx, store.LatestResultsForMonitorsParams{OrgID: page.OrgID, Ids: ids})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if open, err = q.OpenIncidents(ctx); err != nil {
|
||||
latest = make([]store.LatestResultsRow, len(rows))
|
||||
for i, r := range rows {
|
||||
latest[i] = store.LatestResultsRow(r)
|
||||
}
|
||||
if open, err = q.OpenIncidents(ctx, page.OrgID); err != nil {
|
||||
return err
|
||||
}
|
||||
if daily, err = q.DailyBucketsForMonitors(ctx, store.DailyBucketsForMonitorsParams{
|
||||
@@ -92,7 +103,7 @@ func (s *Server) buildSnapshot(ctx context.Context, page store.StatusPage) (agen
|
||||
}
|
||||
if page.ShowComponentDetails {
|
||||
if hourly, err = q.HourlyBuckets(ctx, store.HourlyBucketsParams{
|
||||
OrgID: page.OrgID, Bucket: now.UTC().Add(-24 * time.Hour),
|
||||
OrgID: page.OrgID, Bucket: now.UTC().Add(-24 * time.Hour), Ids: ids,
|
||||
}); err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -100,7 +111,7 @@ func (s *Server) buildSnapshot(ctx context.Context, page store.StatusPage) (agen
|
||||
return err
|
||||
}
|
||||
}
|
||||
if incidents, err = q.IncidentsForMonitors(ctx, store.IncidentsForMonitorsParams{Ids: ids, Since: ptr(now.Add(-incidentLookback))}); err != nil {
|
||||
if incidents, err = q.IncidentsForMonitors(ctx, store.IncidentsForMonitorsParams{OrgID: page.OrgID, Ids: ids, Since: ptr(now.Add(-incidentLookback))}); err != nil {
|
||||
return err
|
||||
}
|
||||
incidentIDs := make([]uuid.UUID, len(incidents))
|
||||
@@ -127,7 +138,18 @@ func (s *Server) buildSnapshot(ctx context.Context, page store.StatusPage) (agen
|
||||
failing := map[uuid.UUID]int{}
|
||||
reported := map[uuid.UUID]int{}
|
||||
latestByMonitor := map[uuid.UUID][]store.LatestResultsRow{}
|
||||
// A region that has not reported for longer than the evaluator waits
|
||||
// is unknown, whatever its last result said.
|
||||
staleBefore := map[uuid.UUID]time.Time{}
|
||||
for _, m := range listed {
|
||||
if !check.Passive(check.Type(m.MonitorType)) {
|
||||
staleBefore[m.MonitorID] = now.Add(-evaluate.StaleAfter(time.Duration(m.IntervalSeconds) * time.Second))
|
||||
}
|
||||
}
|
||||
for _, l := range latest {
|
||||
if cut, ok := staleBefore[l.MonitorID]; ok && l.Time.Before(cut) {
|
||||
continue
|
||||
}
|
||||
reported[l.MonitorID]++
|
||||
if !l.Ok {
|
||||
failing[l.MonitorID]++
|
||||
@@ -213,7 +235,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],
|
||||
})
|
||||
}
|
||||
@@ -346,36 +368,110 @@ func (s *Server) agentPage(c *gin.Context) {
|
||||
fail(c, http.StatusBadRequest, "invalid_input")
|
||||
return
|
||||
}
|
||||
var page store.StatusPage
|
||||
err := s.db.Tx(ctx, tenant.System(), func(q *store.Queries) error {
|
||||
var err error
|
||||
page, err = q.FindPublishedPage(ctx, store.FindPublishedPageParams{Host: host, Slug: slug})
|
||||
return err
|
||||
})
|
||||
a := agentOf(c)
|
||||
if errors.Is(err, pgx.ErrNoRows) || (err == nil && a.OrgID != nil && *a.OrgID != page.OrgID) {
|
||||
page, ok, err := s.agentServes(ctx, agentOf(c), host, slug)
|
||||
if err != nil {
|
||||
internalError(c, err)
|
||||
return
|
||||
}
|
||||
if !ok {
|
||||
fail(c, http.StatusNotFound, "not_found")
|
||||
return
|
||||
}
|
||||
snap, err := s.sharedSnapshot(ctx, page)
|
||||
if err != nil {
|
||||
internalError(c, err)
|
||||
return
|
||||
}
|
||||
snap, err := s.buildSnapshot(ctx, page)
|
||||
if err != nil {
|
||||
internalError(c, err)
|
||||
// The server sends the checksum of its copy; an unchanged page is not
|
||||
// sent again.
|
||||
etag := `"` + snap.Checksum() + `"`
|
||||
c.Header("ETag", etag)
|
||||
if c.GetHeader("If-None-Match") == etag {
|
||||
c.Status(http.StatusNotModified)
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, snap)
|
||||
}
|
||||
|
||||
// snapshotTimeout bounds a shared snapshot build, which outlives the
|
||||
// request that started it.
|
||||
const snapshotTimeout = time.Minute
|
||||
|
||||
// sharedSnapshot builds page once for all status page servers asking for it
|
||||
// at the same time, as they do when told that it changed. A server giving
|
||||
// up does not cancel the build for the others.
|
||||
func (s *Server) sharedSnapshot(ctx context.Context, page store.StatusPage) (agentapi.PageSnapshot, error) {
|
||||
ch := s.snapshots.DoChan(page.ID.String(), func() (any, error) {
|
||||
ctx, cancel := context.WithTimeout(context.WithoutCancel(ctx), snapshotTimeout)
|
||||
defer cancel()
|
||||
return s.buildSnapshot(ctx, page)
|
||||
})
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return agentapi.PageSnapshot{}, ctx.Err()
|
||||
case r := <-ch:
|
||||
if r.Err != nil {
|
||||
return agentapi.PageSnapshot{}, r.Err
|
||||
}
|
||||
return r.Val.(agentapi.PageSnapshot), nil
|
||||
}
|
||||
}
|
||||
|
||||
// agentServes finds the published page a status page agent serves at host
|
||||
// or slug. The platform's servers leave the pages of organizations that
|
||||
// serve them on their own servers to those, which receive only their own
|
||||
// organization's pages.
|
||||
func (s *Server) agentServes(ctx context.Context, a store.GetAgentByHashRow, host, slug *string) (store.StatusPage, bool, error) {
|
||||
var (
|
||||
page store.StatusPage
|
||||
own bool
|
||||
)
|
||||
err := s.db.Tx(ctx, tenant.System(), func(q *store.Queries) error {
|
||||
var err error
|
||||
if page, err = q.FindPublishedPage(ctx, store.FindPublishedPageParams{Host: host, Slug: slug}); err != nil || a.OrgID != nil {
|
||||
return err
|
||||
}
|
||||
own, err = q.OrgServesOwnPages(ctx, &page.OrgID)
|
||||
return err
|
||||
})
|
||||
switch {
|
||||
case errors.Is(err, pgx.ErrNoRows):
|
||||
return page, false, nil
|
||||
case err != nil:
|
||||
return page, false, err
|
||||
}
|
||||
return page, !own && (a.OrgID == nil || *a.OrgID == page.OrgID), nil
|
||||
}
|
||||
|
||||
// agentPageIndex lists the pages the status page server serves.
|
||||
func (s *Server) agentPageIndex(c *gin.Context) {
|
||||
ctx := c.Request.Context()
|
||||
var rows []store.ServablePagesRow
|
||||
err := s.db.Tx(ctx, tenant.System(), func(q *store.Queries) error {
|
||||
var err error
|
||||
rows, err = q.ServablePages(ctx, agentOf(c).OrgID)
|
||||
return err
|
||||
})
|
||||
if err != nil {
|
||||
internalError(c, err)
|
||||
return
|
||||
}
|
||||
out := make([]agentapi.PageRef, len(rows))
|
||||
for i, r := range rows {
|
||||
out[i] = agentapi.PageRef{Slug: r.Slug, Host: r.Host}
|
||||
}
|
||||
c.JSON(http.StatusOK, gin.H{"pages": out})
|
||||
}
|
||||
|
||||
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 {
|
||||
@@ -411,11 +507,19 @@ 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"`
|
||||
// DomainRecord is the TXT record that proves control of CustomDomain.
|
||||
DomainRecord *dnsRecord `json:"domain_record,omitempty"`
|
||||
// CNAMERecord points CustomDomain at the platform's status page
|
||||
// servers and proves control of it in one, where the platform knows
|
||||
// their host.
|
||||
CNAMERecord *dnsRecord `json:"cname_record,omitempty"`
|
||||
// DomainMissingSince is set when the record of a verified domain has
|
||||
// not been found since then; it is switched off a week later.
|
||||
DomainMissingSince *time.Time `json:"domain_missing_since,omitempty"`
|
||||
// Suspended is set when platform admins took the page offline; it is
|
||||
// not served whatever Published says.
|
||||
Suspended bool `json:"suspended,omitempty"`
|
||||
@@ -428,16 +532,20 @@ type dnsRecord struct {
|
||||
Value string `json:"value"`
|
||||
}
|
||||
|
||||
func viewStatusPage(p store.StatusPage) statusPageView {
|
||||
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,
|
||||
}
|
||||
_ = json.Unmarshal(p.Theme, &v.Theme)
|
||||
if p.CustomDomain != nil {
|
||||
v.DomainRecord = &dnsRecord{Name: verifyPrefix + *p.CustomDomain, Type: "TXT", Value: p.DomainToken}
|
||||
if target := s.cnameFor(p.DomainToken); target != "" {
|
||||
v.CNAMERecord = &dnsRecord{Name: *p.CustomDomain, Type: "CNAME", Value: target}
|
||||
}
|
||||
v.DomainMissingSince = p.DomainFailingSince
|
||||
}
|
||||
return v
|
||||
}
|
||||
@@ -476,7 +584,7 @@ func (s *Server) listStatusPages(c *gin.Context) {
|
||||
out := []statusPageView{}
|
||||
for _, r := range rows {
|
||||
if p.Grants.Can(authz.StatusPagesRead, pageResource(r.ID)) {
|
||||
out = append(out, viewStatusPage(r))
|
||||
out = append(out, s.viewStatusPage(r))
|
||||
}
|
||||
}
|
||||
c.JSON(http.StatusOK, gin.H{"pages": out})
|
||||
@@ -503,7 +611,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
|
||||
})
|
||||
@@ -518,7 +626,7 @@ func (s *Server) createStatusPage(c *gin.Context) {
|
||||
internalError(c, err)
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusCreated, viewStatusPage(row))
|
||||
c.JSON(http.StatusCreated, s.viewStatusPage(row))
|
||||
}
|
||||
|
||||
func newDomainToken() string {
|
||||
@@ -546,6 +654,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
|
||||
})
|
||||
@@ -557,7 +666,7 @@ func (s *Server) updateStatusPage(c *gin.Context) {
|
||||
case err != nil:
|
||||
internalError(c, err)
|
||||
default:
|
||||
c.JSON(http.StatusOK, viewStatusPage(row))
|
||||
c.JSON(http.StatusOK, s.viewStatusPage(row))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -590,7 +699,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
|
||||
@@ -623,6 +734,16 @@ func (s *Server) setPageMonitors(c *gin.Context) {
|
||||
}
|
||||
}
|
||||
}
|
||||
// A page beyond a lowered limit may keep its monitors but not add any.
|
||||
if max := s.orgLimits(ctx, p.Org).MonitorsPerPage; max > 0 && len(req.Monitors) > max {
|
||||
had, err := q.CountStatusPageMonitors(ctx, id)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if int64(len(req.Monitors)) > had {
|
||||
return limitError{"page_monitor_limit", max}
|
||||
}
|
||||
}
|
||||
if err := q.ClearStatusPageMonitors(ctx, id); err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -650,6 +771,7 @@ func (s *Server) setPageMonitors(c *gin.Context) {
|
||||
case isForeignKeyViolation(err), isUniqueViolation(err, "status_page_monitors_pkey"):
|
||||
// Unknown monitors, monitors of other orgs and duplicates.
|
||||
fail(c, http.StatusUnprocessableEntity, "invalid_monitor")
|
||||
case failLimit(c, err):
|
||||
case err != nil:
|
||||
internalError(c, err)
|
||||
default:
|
||||
@@ -675,12 +797,30 @@ func (s *Server) setPageDomain(c *gin.Context) {
|
||||
p := current(c)
|
||||
ctx := c.Request.Context()
|
||||
var row store.StatusPage
|
||||
limited := false
|
||||
err := s.db.Tx(ctx, p.scope(), func(q *store.Queries) error {
|
||||
var err error
|
||||
cur, err := q.GetStatusPage(ctx, id)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
// Every new domain may end in a certificate order; switching domains
|
||||
// over and over would use up the CA's limits for everyone.
|
||||
if domain != "" && domain != deref(cur.CustomDomain) {
|
||||
ok, err := s.limiter.Allow(ctx, "domain_change:"+p.Org.ID.String(), domainChangesPerDay, 24*time.Hour)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if !ok {
|
||||
limited = true
|
||||
return nil
|
||||
}
|
||||
}
|
||||
row, err = q.SetStatusPageDomain(ctx, store.SetStatusPageDomainParams{ID: id, CustomDomain: nonEmpty(domain)})
|
||||
return err
|
||||
})
|
||||
switch {
|
||||
case limited:
|
||||
fail(c, http.StatusTooManyRequests, "domain_changes_exceeded", "Count", domainChangesPerDay)
|
||||
case isUniqueViolation(err, "status_pages_custom_domain_key"):
|
||||
fail(c, http.StatusConflict, "domain_taken")
|
||||
case errors.Is(err, pgx.ErrNoRows):
|
||||
@@ -688,14 +828,14 @@ func (s *Server) setPageDomain(c *gin.Context) {
|
||||
case err != nil:
|
||||
internalError(c, err)
|
||||
default:
|
||||
c.JSON(http.StatusOK, viewStatusPage(row))
|
||||
c.JSON(http.StatusOK, s.viewStatusPage(row))
|
||||
}
|
||||
}
|
||||
|
||||
// lookupTXT is replaced in tests.
|
||||
var lookupTXT = net.DefaultResolver.LookupTXT
|
||||
|
||||
// verifyPageDomain checks the TXT record. Only verified domains are served,
|
||||
// verifyPageDomain looks for the CNAME or the TXT record now. Only verified domains are served,
|
||||
// so nobody can claim a domain they do not control.
|
||||
func (s *Server) verifyPageDomain(c *gin.Context) {
|
||||
id := uuid.MustParse(c.Param("id"))
|
||||
@@ -722,12 +862,14 @@ func (s *Server) verifyPageDomain(c *gin.Context) {
|
||||
fail(c, http.StatusConflict, "no_domain")
|
||||
return
|
||||
}
|
||||
records, err := lookupTXT(ctx, verifyPrefix+*row.CustomDomain)
|
||||
if err != nil || !slices.Contains(records, row.DomainToken) {
|
||||
method := s.checkDomain(ctx, *row.CustomDomain, row.DomainToken)
|
||||
if method == "" {
|
||||
fail(c, http.StatusUnprocessableEntity, "domain_not_verified")
|
||||
return
|
||||
}
|
||||
err = s.db.Tx(ctx, p.scope(), func(q *store.Queries) error { return q.MarkDomainVerified(ctx, id) })
|
||||
err = s.db.Tx(ctx, p.scope(), func(q *store.Queries) error {
|
||||
return q.MarkDomainVerified(ctx, store.MarkDomainVerifiedParams{ID: id, Now: time.Now(), Method: method})
|
||||
})
|
||||
if err != nil {
|
||||
internalError(c, err)
|
||||
return
|
||||
|
||||
@@ -8,6 +8,7 @@ import (
|
||||
"log/slog"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"slices"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
@@ -95,6 +96,12 @@ func TestStatusPages(t *testing.T) {
|
||||
snap.Sections[1].Components[0].Name != "Public API" {
|
||||
t.Errorf("snapshot = %+v, want degraded page with the Public API in outage", snap)
|
||||
}
|
||||
if _, err := platform.PageIfChanged(context.Background(), "", slug, snap.Checksum()); !errors.Is(err, agentapi.ErrNotModified) {
|
||||
t.Errorf("PageIfChanged(current checksum) error = %v, want not modified", err)
|
||||
}
|
||||
if again, err := platform.PageIfChanged(context.Background(), "", slug, "stale"); err != nil || again.Title != "Acme Status" {
|
||||
t.Errorf("PageIfChanged(stale checksum) = %v, %v", again.Title, err)
|
||||
}
|
||||
raw, _ := json.Marshal(snap)
|
||||
for _, secret := range []string{up.URL, down.URL, "unexpected status"} {
|
||||
if strings.Contains(string(raw), secret) {
|
||||
@@ -192,6 +199,37 @@ func TestStatusPages(t *testing.T) {
|
||||
st, body = editor.do("PUT", "/api/v1/org/statuspages/"+second, map[string]any{"slug": "x-second", "title": "x"})
|
||||
expect(t, "edit page out of scope", st, body, http.StatusNotFound, "not_found")
|
||||
})
|
||||
|
||||
t.Run("own servers replace the platform's", func(t *testing.T) {
|
||||
org := uuid.MustParse(owner.orgID())
|
||||
own := e.statuspageClient(t, &org)
|
||||
lists := func(c *agentapi.Client) bool {
|
||||
t.Helper()
|
||||
refs, err := c.Pages(context.Background())
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return slices.ContainsFunc(refs, func(r agentapi.PageRef) bool { return r.Slug == slug && r.Host != "" })
|
||||
}
|
||||
if _, err := platform.Page(context.Background(), "", slug); err != nil || !lists(platform) {
|
||||
t.Fatalf("platform server before the own one connected: %v", err)
|
||||
}
|
||||
if _, err := own.Hello(context.Background()); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := platform.Page(context.Background(), "", slug); !errors.Is(err, agentapi.ErrNotFound) {
|
||||
t.Errorf("platform server still gets the page: %v", err)
|
||||
}
|
||||
if snap, err := own.Page(context.Background(), "", slug); err != nil || snap.Title != "Acme Status" {
|
||||
t.Errorf("own server Page() = %v, %v", snap.Title, err)
|
||||
}
|
||||
if lists(platform) || !lists(own) {
|
||||
t.Error("the page lists do not follow who serves the page")
|
||||
}
|
||||
if _, _, html := owner.page("/statuspages/" + pageID); !strings.Contains(html, "own status page servers serve its pages") {
|
||||
t.Error("the editor does not say who serves the pages")
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
func editorEmail(b *browser) string {
|
||||
|
||||
@@ -119,6 +119,12 @@ func TestAllowCertificate(t *testing.T) {
|
||||
t.Error("AllowCertificate(unknown name) = nil, want refusal")
|
||||
}
|
||||
verifyDomain(t, owner, pageID, record)
|
||||
// A name just found without a page is not asked about again for a
|
||||
// while; the sync picks the newly verified domain up.
|
||||
if err := srv.AllowCertificate(ctx, domain); err == nil {
|
||||
t.Error("AllowCertificate(domain just found missing) = nil, want the miss remembered")
|
||||
}
|
||||
srv.Sync(ctx)
|
||||
if err := srv.AllowCertificate(ctx, domain); err != nil {
|
||||
t.Errorf("AllowCertificate(verified domain) = %v", err)
|
||||
}
|
||||
|
||||
@@ -0,0 +1,357 @@
|
||||
package api
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"path"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/coder/websocket"
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/google/uuid"
|
||||
|
||||
"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"
|
||||
)
|
||||
|
||||
const (
|
||||
// pagesChannel is the Redis channel announcing organizations whose
|
||||
// status pages changed; uuid.Nil stands for all of them.
|
||||
pagesChannel = "uptimesebi:pages-changed"
|
||||
// streamInFlight bounds the requests of one stream handled at once.
|
||||
streamInFlight = 128
|
||||
// streamReadLimit bounds a request read from a stream.
|
||||
streamReadLimit = 16 << 20
|
||||
streamPing = 30 * time.Second
|
||||
// pushFirst and pushEvery pace the page events of one stream: changes
|
||||
// are collected for pushFirst, and a stream gets at most one event per
|
||||
// pushEvery, so a flapping monitor does not have its pages rebuilt
|
||||
// over and over.
|
||||
pushFirst = time.Second
|
||||
pushEvery = 5 * time.Second
|
||||
// drainWait is how long a draining instance lets requests on a stream
|
||||
// finish before closing it.
|
||||
drainWait = 5 * time.Second
|
||||
)
|
||||
|
||||
// streamedKey marks requests that arrived over a stream.
|
||||
type streamedKey struct{}
|
||||
|
||||
// pagesChanged announces that status pages of orgs may look different
|
||||
// now, so status page servers fetch them at once instead of on their next
|
||||
// refresh. Losing the announcement only delays that.
|
||||
func (s *Server) pagesChanged(ctx context.Context, orgs ...uuid.UUID) {
|
||||
if s.rdb == nil {
|
||||
return
|
||||
}
|
||||
for _, org := range orgs {
|
||||
if err := s.rdb.Publish(ctx, pagesChannel, org.String()).Err(); err != nil {
|
||||
s.log.WarnContext(ctx, "announcing changed status pages failed", "org", org, "error", err)
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// announcePages is middleware announcing the changed status pages of the
|
||||
// request's organization, or of all with no organization, after every
|
||||
// change made through it.
|
||||
func (s *Server) announcePages() gin.HandlerFunc {
|
||||
return func(c *gin.Context) {
|
||||
c.Next()
|
||||
if c.Request.Method == http.MethodGet || c.Request.Method == http.MethodHead || c.Writer.Status() >= 400 {
|
||||
return
|
||||
}
|
||||
org := uuid.Nil
|
||||
if p, ok := c.Get(ctxPrincipal); ok {
|
||||
org = p.(*principal).Org.ID
|
||||
}
|
||||
s.pagesChanged(context.WithoutCancel(c.Request.Context()), org)
|
||||
}
|
||||
}
|
||||
|
||||
// agentStream serves an agent's stream: its requests run through the
|
||||
// agent API as if they had come over HTTP, each authenticated again, and
|
||||
// status page servers get told which of their pages changed.
|
||||
func (s *Server) agentStream(c *gin.Context) {
|
||||
up := c.Request
|
||||
if up.Context().Value(streamedKey{}) != nil || s.handler == nil {
|
||||
fail(c, http.StatusNotFound, "not_found")
|
||||
return
|
||||
}
|
||||
ws, err := websocket.Accept(c.Writer, up, &websocket.AcceptOptions{CompressionMode: websocket.CompressionContextTakeover})
|
||||
if err != nil {
|
||||
// Accept has answered the request.
|
||||
return
|
||||
}
|
||||
ws.SetReadLimit(streamReadLimit)
|
||||
a := agentOf(c)
|
||||
ctx, cancel := context.WithCancel(context.WithoutCancel(up.Context()))
|
||||
defer cancel()
|
||||
st := &stream{s: s, ws: ws, up: up.Clone(ctx), ctx: ctx, inflight: map[uint64]context.CancelFunc{}}
|
||||
|
||||
go st.ping(cancel)
|
||||
if a.Kind == "statuspage" {
|
||||
go s.pushPages(ctx, st, a.OrgID)
|
||||
}
|
||||
if s.draining != nil {
|
||||
go func() {
|
||||
select {
|
||||
case <-s.draining:
|
||||
st.drain()
|
||||
case <-ctx.Done():
|
||||
}
|
||||
}()
|
||||
}
|
||||
err = st.read()
|
||||
cancel()
|
||||
st.wg.Wait()
|
||||
_ = ws.CloseNow()
|
||||
s.log.DebugContext(ctx, "agent stream closed", "agent", a.ID, "error", err)
|
||||
}
|
||||
|
||||
// stream is one open agent stream on the API's side.
|
||||
type stream struct {
|
||||
s *Server
|
||||
ws *websocket.Conn
|
||||
up *http.Request
|
||||
ctx context.Context
|
||||
|
||||
mu sync.Mutex
|
||||
inflight map[uint64]context.CancelFunc
|
||||
draining bool
|
||||
wg sync.WaitGroup
|
||||
}
|
||||
|
||||
func (st *stream) read() error {
|
||||
for {
|
||||
_, msg, err := st.ws.Read(st.ctx)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
f, body, err := agentapi.DecodeFrame(msg)
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
st.mu.Lock()
|
||||
if f.Cancel {
|
||||
if cancel := st.inflight[f.ID]; cancel != nil {
|
||||
cancel()
|
||||
}
|
||||
st.mu.Unlock()
|
||||
continue
|
||||
}
|
||||
_, dup := st.inflight[f.ID]
|
||||
refuse := 0
|
||||
switch {
|
||||
case st.draining:
|
||||
refuse = http.StatusServiceUnavailable
|
||||
case dup || f.ID == 0:
|
||||
refuse = http.StatusBadRequest
|
||||
case len(st.inflight) >= streamInFlight:
|
||||
refuse = http.StatusTooManyRequests
|
||||
}
|
||||
if refuse != 0 {
|
||||
st.mu.Unlock()
|
||||
st.reply(f.ID, refuse, nil, nil)
|
||||
continue
|
||||
}
|
||||
rctx, cancel := context.WithCancel(context.WithValue(st.ctx, streamedKey{}, true))
|
||||
st.inflight[f.ID] = cancel
|
||||
st.wg.Add(1)
|
||||
st.mu.Unlock()
|
||||
go func() {
|
||||
defer st.wg.Done()
|
||||
defer func() {
|
||||
st.mu.Lock()
|
||||
delete(st.inflight, f.ID)
|
||||
st.mu.Unlock()
|
||||
cancel()
|
||||
}()
|
||||
st.serve(rctx, f, body)
|
||||
}()
|
||||
}
|
||||
}
|
||||
|
||||
// serve runs one request through the agent API.
|
||||
func (st *stream) serve(ctx context.Context, f agentapi.Frame, body []byte) {
|
||||
u, err := url.Parse(agentapi.Prefix + f.Path)
|
||||
switch {
|
||||
case err != nil, path.Clean(u.Path) != u.Path, !strings.HasPrefix(u.Path, agentapi.Prefix+"/"),
|
||||
u.Path == agentapi.Prefix+agentapi.StreamPath:
|
||||
st.reply(f.ID, http.StatusBadRequest, nil, nil)
|
||||
return
|
||||
}
|
||||
switch f.Method {
|
||||
case http.MethodGet, http.MethodPost, http.MethodPut, http.MethodDelete, http.MethodPatch:
|
||||
default:
|
||||
st.reply(f.ID, http.StatusMethodNotAllowed, nil, nil)
|
||||
return
|
||||
}
|
||||
req, err := http.NewRequestWithContext(ctx, f.Method, u.String(), bytes.NewReader(body))
|
||||
if err != nil {
|
||||
st.reply(f.ID, http.StatusBadRequest, nil, nil)
|
||||
return
|
||||
}
|
||||
if f.Header != nil {
|
||||
req.Header = f.Header
|
||||
}
|
||||
// Who is asking comes from the stream, never from the request.
|
||||
for _, k := range []string{"Authorization", agentapi.VersionHeader, agentapi.InstanceHeader, agentapi.ReleaseHeader,
|
||||
"X-Forwarded-For", "X-Real-Ip", "X-Forwarded-Proto", "X-Forwarded-Host"} {
|
||||
req.Header.Del(k)
|
||||
if v := st.up.Header.Values(k); len(v) > 0 {
|
||||
req.Header[k] = v
|
||||
}
|
||||
}
|
||||
req.Host, req.RemoteAddr, req.RequestURI = st.up.Host, st.up.RemoteAddr, u.RequestURI()
|
||||
w := &replyWriter{header: http.Header{}}
|
||||
st.s.handler.ServeHTTP(w, req)
|
||||
if w.status == 0 {
|
||||
w.status = http.StatusOK
|
||||
}
|
||||
st.reply(f.ID, w.status, w.header, w.body.Bytes())
|
||||
if w.status == http.StatusUnauthorized {
|
||||
// The token was revoked: the stream ends with it.
|
||||
_ = st.ws.Close(websocket.StatusPolicyViolation, "unauthenticated")
|
||||
}
|
||||
}
|
||||
|
||||
func (st *stream) reply(id uint64, status int, h http.Header, body []byte) {
|
||||
st.send(agentapi.Frame{ID: id, Status: status, Header: h}, body)
|
||||
}
|
||||
|
||||
func (st *stream) send(f agentapi.Frame, body []byte) {
|
||||
ctx, cancel := context.WithTimeout(st.ctx, time.Minute)
|
||||
defer cancel()
|
||||
if err := st.ws.Write(ctx, websocket.MessageBinary, agentapi.EncodeFrame(f, body)); err != nil {
|
||||
_ = st.ws.CloseNow()
|
||||
}
|
||||
}
|
||||
|
||||
// ping closes streams whose agent stopped answering.
|
||||
func (st *stream) ping(cancel context.CancelFunc) {
|
||||
tick := time.NewTicker(streamPing)
|
||||
defer tick.Stop()
|
||||
for {
|
||||
select {
|
||||
case <-st.ctx.Done():
|
||||
return
|
||||
case <-tick.C:
|
||||
ctx, stop := context.WithTimeout(st.ctx, streamPing/2)
|
||||
err := st.ws.Ping(ctx)
|
||||
stop()
|
||||
if err != nil {
|
||||
cancel()
|
||||
_ = st.ws.CloseNow()
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// drain refuses new requests, lets those running finish for a while and
|
||||
// closes the stream, so the agent reconnects to another instance.
|
||||
func (st *stream) drain() {
|
||||
st.mu.Lock()
|
||||
st.draining = true
|
||||
st.mu.Unlock()
|
||||
done := make(chan struct{})
|
||||
go func() { st.wg.Wait(); close(done) }()
|
||||
select {
|
||||
case <-done:
|
||||
case <-time.After(drainWait):
|
||||
case <-st.ctx.Done():
|
||||
}
|
||||
_ = st.ws.Close(websocket.StatusGoingAway, "instance shutting down")
|
||||
}
|
||||
|
||||
// pushPages tells a status page server which of its pages changed, for an
|
||||
// organization's server only those of its organization.
|
||||
func (s *Server) pushPages(ctx context.Context, st *stream, agentOrg *uuid.UUID) {
|
||||
sub := s.rdb.Subscribe(ctx, pagesChannel)
|
||||
defer func() { _ = sub.Close() }()
|
||||
msgs := sub.Channel()
|
||||
changed := map[uuid.UUID]bool{}
|
||||
var (
|
||||
due <-chan time.Time
|
||||
last time.Time
|
||||
)
|
||||
for {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return
|
||||
case m, ok := <-msgs:
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
org, err := uuid.Parse(m.Payload)
|
||||
if err != nil || (agentOrg != nil && org != *agentOrg && org != uuid.Nil) {
|
||||
continue
|
||||
}
|
||||
changed[org] = true
|
||||
if due == nil {
|
||||
due = time.After(max(pushFirst, pushEvery-time.Since(last)))
|
||||
}
|
||||
case <-due:
|
||||
due, last = nil, time.Now()
|
||||
refs, err := s.changedPages(ctx, agentOrg, changed)
|
||||
clear(changed)
|
||||
if err != nil {
|
||||
s.log.WarnContext(ctx, "finding changed status pages failed", "error", err)
|
||||
continue
|
||||
}
|
||||
if len(refs) == 0 {
|
||||
continue
|
||||
}
|
||||
body, _ := json.Marshal(agentapi.PagesEvent{Pages: refs})
|
||||
st.send(agentapi.Frame{Event: agentapi.EventPages}, body)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// changedPages lists the pages the server of agentOrg serves of the
|
||||
// organizations changed.
|
||||
func (s *Server) changedPages(ctx context.Context, agentOrg *uuid.UUID, changed map[uuid.UUID]bool) ([]agentapi.PageRef, error) {
|
||||
var rows []store.ServablePagesRow
|
||||
err := s.db.Tx(ctx, tenant.System(), func(q *store.Queries) error {
|
||||
var err error
|
||||
rows, err = q.ServablePages(ctx, agentOrg)
|
||||
return err
|
||||
})
|
||||
var refs []agentapi.PageRef
|
||||
for _, r := range rows {
|
||||
if changed[uuid.Nil] || changed[r.OrgID] {
|
||||
refs = append(refs, agentapi.PageRef{Slug: r.Slug, Host: r.Host})
|
||||
}
|
||||
}
|
||||
return refs, err
|
||||
}
|
||||
|
||||
// replyWriter collects a response to send back over a stream.
|
||||
type replyWriter struct {
|
||||
header http.Header
|
||||
status int
|
||||
body bytes.Buffer
|
||||
}
|
||||
|
||||
// Header implements http.ResponseWriter.
|
||||
func (w *replyWriter) Header() http.Header { return w.header }
|
||||
|
||||
// WriteHeader implements http.ResponseWriter.
|
||||
func (w *replyWriter) WriteHeader(status int) {
|
||||
if w.status == 0 {
|
||||
w.status = status
|
||||
}
|
||||
}
|
||||
|
||||
// Write implements http.ResponseWriter.
|
||||
func (w *replyWriter) Write(b []byte) (int, error) {
|
||||
w.WriteHeader(http.StatusOK)
|
||||
return w.body.Write(b)
|
||||
}
|
||||
@@ -0,0 +1,78 @@
|
||||
package api_test
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"slices"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/jackc/pgx/v5"
|
||||
|
||||
"git.zb-server.de/ZB-Server/uptimesebi/internal/agentapi"
|
||||
)
|
||||
|
||||
func TestAgentStream(t *testing.T) {
|
||||
e := newEnv(t)
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
t.Cleanup(cancel)
|
||||
owner := e.browser(t)
|
||||
owner.signup("o@"+uniq("st")+".test", uniq("st-"))
|
||||
slug := uniq("stream-")
|
||||
_, body := owner.do("POST", "/api/v1/org/statuspages", map[string]any{"slug": slug, "title": "Before"})
|
||||
pageID := body["id"].(string)
|
||||
owner.do("PUT", "/api/v1/org/statuspages/"+pageID, map[string]any{"slug": slug, "title": "Before", "published": true})
|
||||
|
||||
sp := e.statuspageClient(t, nil)
|
||||
events := make(chan agentapi.PagesEvent, 16)
|
||||
sp.UseStream(ctx, agentapi.StreamOptions{OnEvent: func(event string, body []byte) {
|
||||
var ev agentapi.PagesEvent
|
||||
if event == agentapi.EventPages && json.Unmarshal(body, &ev) == nil {
|
||||
events <- ev
|
||||
}
|
||||
}})
|
||||
waitFor(t, 10*time.Second, "stream to open", sp.Streaming)
|
||||
|
||||
snap, err := sp.Page(ctx, "", slug)
|
||||
if err != nil || snap.Title != "Before" {
|
||||
t.Fatalf("Page() over the stream = %q, %v", snap.Title, err)
|
||||
}
|
||||
if _, err := sp.PageIfChanged(ctx, "", slug, snap.Checksum()); !errors.Is(err, agentapi.ErrNotModified) {
|
||||
t.Errorf("PageIfChanged(current checksum) over the stream error = %v, want not modified", err)
|
||||
}
|
||||
if _, err := sp.Page(ctx, "", uniq("missing-")); !errors.Is(err, agentapi.ErrNotFound) {
|
||||
t.Errorf("Page(missing) over the stream error = %v, want not found", err)
|
||||
}
|
||||
|
||||
// Editing the page tells the server at once.
|
||||
owner.do("PUT", "/api/v1/org/statuspages/"+pageID, map[string]any{"slug": slug, "title": "After", "published": true})
|
||||
deadline := time.After(10 * time.Second)
|
||||
for told := false; !told; {
|
||||
select {
|
||||
case ev := <-events:
|
||||
told = slices.ContainsFunc(ev.Pages, func(r agentapi.PageRef) bool { return r.Slug == slug })
|
||||
case <-deadline:
|
||||
t.Fatal("no event for the edited page")
|
||||
}
|
||||
}
|
||||
if snap, err := sp.Page(ctx, "", slug); err != nil || snap.Title != "After" {
|
||||
t.Errorf("Page() after the edit = %q, %v", snap.Title, err)
|
||||
}
|
||||
|
||||
// A revoked token ends the stream.
|
||||
hello, err := sp.Hello(ctx)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := e.asSystem(t, func(tx pgx.Tx) error {
|
||||
_, err := tx.Exec(ctx, `DELETE FROM agents WHERE id = $1`, hello.AgentID)
|
||||
return err
|
||||
}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := sp.Hello(ctx); !errors.Is(err, agentapi.ErrUnauthorized) {
|
||||
t.Errorf("Hello() with a revoked token error = %v, want unauthorized", err)
|
||||
}
|
||||
waitFor(t, 10*time.Second, "stream to close", func() bool { return !sp.Streaming() })
|
||||
}
|
||||
@@ -0,0 +1,445 @@
|
||||
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
|
||||
}
|
||||
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))
|
||||
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,242 @@
|
||||
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
|
||||
}
|
||||
|
||||
if code, html, _ := visit("GET", "/"+slug, ""); 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 code, html, _ := visit("POST", "/"+slug+"/subscribe", "email=not-an-address"); code != http.StatusUnprocessableEntity {
|
||||
t.Errorf("subscribing an invalid address = %d %.200s", code, html)
|
||||
}
|
||||
if code, _, _ := visit("POST", "/"+slug+"/subscribe", "email=Visitor@Example.test"); 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")
|
||||
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"); code != 200 {
|
||||
t.Errorf("subscription within the weekly limit = %d", code)
|
||||
}
|
||||
if code, _, _ := visit("POST", "/"+slug+"/subscribe", "email=third@example.test"); 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"); 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"); 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")
|
||||
}
|
||||
}
|
||||
@@ -152,7 +152,8 @@ func (s *Sessions) Get(ctx context.Context, token string) (*Session, error) {
|
||||
}
|
||||
// Sliding expiry, but never beyond the absolute lifetime.
|
||||
remaining := s.absolute - s.now().Sub(sess.CreatedAt)
|
||||
if err := s.rdb.Expire(ctx, k, min(s.idle, remaining)).Err(); err != nil {
|
||||
// PEXPIRE: the rest of the lifetime may be below a second.
|
||||
if err := s.rdb.PExpire(ctx, k, min(s.idle, remaining)).Err(); err != nil {
|
||||
return nil, fmt.Errorf("auth: touch session: %w", err)
|
||||
}
|
||||
return sess, nil
|
||||
|
||||
@@ -26,7 +26,9 @@ type API interface {
|
||||
}
|
||||
|
||||
const (
|
||||
pollWait = 20 * time.Second
|
||||
pollWait = 20 * time.Second
|
||||
// quickPoll is a long poll answered empty faster than any wait would.
|
||||
quickPoll = 200 * time.Millisecond
|
||||
flushInterval = 2 * time.Second
|
||||
// maxPending bounds results kept while the API is unreachable.
|
||||
maxPending = 50_000
|
||||
@@ -127,6 +129,12 @@ func (r *Runner) Run(ctx context.Context, drain time.Duration) error {
|
||||
|
||||
func (r *Runner) poll(ctx context.Context, running *sync.WaitGroup) error {
|
||||
backoff := time.Second
|
||||
// failing and failures track an outage, so its end is logged too: a log
|
||||
// whose last line is an error otherwise reads as a checker stuck.
|
||||
var (
|
||||
failing time.Time
|
||||
failures int
|
||||
)
|
||||
for ctx.Err() == nil {
|
||||
free := cap(r.slots) - len(r.slots)
|
||||
wait := pollWait
|
||||
@@ -134,6 +142,7 @@ func (r *Runner) poll(ctx context.Context, running *sync.WaitGroup) error {
|
||||
// Still poll as a heartbeat, but do not take work.
|
||||
wait = 0
|
||||
}
|
||||
asked := time.Now()
|
||||
jobs, err := r.api.Jobs(ctx, free, wait)
|
||||
switch {
|
||||
case errors.Is(err, agentapi.ErrUnauthorized):
|
||||
@@ -143,11 +152,19 @@ func (r *Runner) poll(ctx context.Context, running *sync.WaitGroup) error {
|
||||
return nil
|
||||
}
|
||||
r.log.Warn("polling for jobs failed", "error", err, "retry_in", backoff)
|
||||
if failing.IsZero() {
|
||||
failing = time.Now()
|
||||
}
|
||||
failures++
|
||||
sleep(ctx, backoff)
|
||||
backoff = min(backoff*2, 30*time.Second)
|
||||
continue
|
||||
}
|
||||
backoff = time.Second
|
||||
if !failing.IsZero() {
|
||||
r.log.Info("polling for jobs works again", "failed_for", time.Since(failing).Round(time.Second).String(), "failures", failures)
|
||||
failing, failures = time.Time{}, 0
|
||||
}
|
||||
r.lastPoll.Store(time.Now().UnixMilli())
|
||||
for _, j := range jobs {
|
||||
r.slots <- struct{}{}
|
||||
@@ -157,7 +174,9 @@ func (r *Runner) poll(ctx context.Context, running *sync.WaitGroup) error {
|
||||
r.results <- r.execute(ctx, j)
|
||||
}()
|
||||
}
|
||||
if free == 0 {
|
||||
// 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) {
|
||||
sleep(ctx, time.Second)
|
||||
}
|
||||
}
|
||||
@@ -188,15 +207,27 @@ func (r *Runner) execute(ctx context.Context, j agentapi.Job) agentapi.Result {
|
||||
func (r *Runner) report(ctx context.Context) {
|
||||
tick := time.NewTicker(flushInterval)
|
||||
defer tick.Stop()
|
||||
var pending []agentapi.Result
|
||||
var (
|
||||
pending []agentapi.Result
|
||||
// failing is when reporting started to fail, zero while it works.
|
||||
failing time.Time
|
||||
)
|
||||
flush := func(ctx context.Context) {
|
||||
sent := 0
|
||||
for len(pending) > 0 {
|
||||
n := min(len(pending), agentapi.MaxResults)
|
||||
if err := r.api.Report(ctx, pending[:n]); err != nil {
|
||||
r.log.Warn("reporting results failed", "error", err, "pending", len(pending))
|
||||
if failing.IsZero() {
|
||||
failing = time.Now()
|
||||
}
|
||||
return
|
||||
}
|
||||
pending = pending[n:]
|
||||
pending, sent = pending[n:], sent+n
|
||||
}
|
||||
if !failing.IsZero() {
|
||||
r.log.Info("reporting results works again", "failed_for", time.Since(failing).Round(time.Second).String(), "sent", sent)
|
||||
failing = time.Time{}
|
||||
}
|
||||
}
|
||||
for {
|
||||
|
||||
@@ -0,0 +1,108 @@
|
||||
package checker
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"errors"
|
||||
"log/slog"
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"git.zb-server.de/ZB-Server/uptimesebi/internal/agentapi"
|
||||
"git.zb-server.de/ZB-Server/uptimesebi/internal/check"
|
||||
)
|
||||
|
||||
// flakyAPI fails its first calls, like an API being rolled out.
|
||||
type flakyAPI struct {
|
||||
mu sync.Mutex
|
||||
jobFails int
|
||||
reportFails int
|
||||
gave bool
|
||||
reported int
|
||||
}
|
||||
|
||||
func (f *flakyAPI) Jobs(ctx context.Context, _ int, wait time.Duration) ([]agentapi.Job, error) {
|
||||
f.mu.Lock()
|
||||
if f.jobFails > 0 {
|
||||
f.jobFails--
|
||||
f.mu.Unlock()
|
||||
return nil, errors.New("504 Gateway Timeout")
|
||||
}
|
||||
if !f.gave {
|
||||
f.gave = true
|
||||
f.mu.Unlock()
|
||||
return []agentapi.Job{{MonitorID: uuid.New(), Type: "tcp", Target: "x:1"}}, nil
|
||||
}
|
||||
f.mu.Unlock()
|
||||
select {
|
||||
case <-time.After(min(wait, 50*time.Millisecond)):
|
||||
case <-ctx.Done():
|
||||
}
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
func (f *flakyAPI) Report(_ context.Context, rs []agentapi.Result) error {
|
||||
f.mu.Lock()
|
||||
defer f.mu.Unlock()
|
||||
if f.reportFails > 0 {
|
||||
f.reportFails--
|
||||
return errors.New("context deadline exceeded")
|
||||
}
|
||||
f.reported += len(rs)
|
||||
return nil
|
||||
}
|
||||
|
||||
func (f *flakyAPI) Release(context.Context) error { return nil }
|
||||
|
||||
type syncBuffer struct {
|
||||
mu sync.Mutex
|
||||
b bytes.Buffer
|
||||
}
|
||||
|
||||
func (s *syncBuffer) Write(p []byte) (int, error) {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
return s.b.Write(p)
|
||||
}
|
||||
|
||||
func (s *syncBuffer) String() string {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
return s.b.String()
|
||||
}
|
||||
|
||||
func TestRecoveryIsLogged(t *testing.T) {
|
||||
api := &flakyAPI{jobFails: 1, reportFails: 1}
|
||||
var logs syncBuffer
|
||||
r := New(api, 2, slog.New(slog.NewJSONHandler(&logs, nil)))
|
||||
r.run = func(context.Context, check.Spec) check.Outcome { return check.Outcome{OK: true} }
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
done := make(chan error, 1)
|
||||
go func() { done <- r.Run(ctx, time.Second) }()
|
||||
|
||||
deadline := time.Now().Add(10 * time.Second)
|
||||
for time.Now().Before(deadline) {
|
||||
out := logs.String()
|
||||
if strings.Contains(out, "polling for jobs works again") && strings.Contains(out, "reporting results works again") {
|
||||
break
|
||||
}
|
||||
time.Sleep(50 * time.Millisecond)
|
||||
}
|
||||
cancel()
|
||||
if err := <-done; err != nil {
|
||||
t.Errorf("Run() = %v", err)
|
||||
}
|
||||
out := logs.String()
|
||||
for _, want := range []string{`"msg":"polling for jobs works again"`, `"failures":1`, `"msg":"reporting results works again"`, `"sent":1`} {
|
||||
if !strings.Contains(out, want) {
|
||||
t.Errorf("log lacks %s:\n%s", want, out)
|
||||
}
|
||||
}
|
||||
if n := strings.Count(out, "works again"); n != 2 {
|
||||
t.Errorf("recovery logged %d times, want once each", n)
|
||||
}
|
||||
}
|
||||
@@ -101,7 +101,28 @@ type API struct {
|
||||
// AgentImage is the image name agents are installed and updated from;
|
||||
// "-checker" or "-statuspage" is appended. Change it for a mirror.
|
||||
AgentImage string `env:"UPTIME_AGENT_IMAGE" envDefault:"git.zb-server.de/zb-server/uptimesebi"`
|
||||
Retention Retention
|
||||
// RegionAlertAfter is how long a region with monitors may have no live
|
||||
// checker before its admins or owners are told; 0 disables it.
|
||||
RegionAlertAfter time.Duration `env:"UPTIME_REGION_ALERT_AFTER" envDefault:"5m"`
|
||||
// Certificates bounds the certificates status page servers may order
|
||||
// for custom domains.
|
||||
Certificates Certificates
|
||||
Retention Retention
|
||||
}
|
||||
|
||||
// Certificates limits new ACME orders for custom domains, so neither one
|
||||
// organization nor a flood of names uses up the CA's rate limits, which
|
||||
// apply per ACME account and so to all servers of an owner together.
|
||||
// Renewals are not counted.
|
||||
type Certificates struct {
|
||||
// PerOrgPerDay is for the domains of one organization.
|
||||
PerOrgPerDay int `env:"UPTIME_CERTS_PER_ORG_PER_DAY" envDefault:"20"`
|
||||
// PerOwnerPerHour is for all servers of the platform, or of one
|
||||
// organization, together.
|
||||
PerOwnerPerHour int `env:"UPTIME_CERTS_PER_HOUR" envDefault:"30"`
|
||||
// PerNamePerDay stops a domain whose orders keep failing from using
|
||||
// up the rest.
|
||||
PerNamePerDay int `env:"UPTIME_CERTS_PER_NAME_PER_DAY" envDefault:"5"`
|
||||
}
|
||||
|
||||
// Retention sets how long data is kept. Zero keeps it forever.
|
||||
|
||||
@@ -1,9 +1,11 @@
|
||||
// Package evaluate turns per-region check results into a monitor state.
|
||||
//
|
||||
// A monitor goes down only when every region it is assigned to has failed
|
||||
// the configured number of times in a row and reported recently. A region
|
||||
// without recent results counts as unknown and keeps the monitor up: one
|
||||
// checker losing its network must not page anyone. Any successful region
|
||||
// A monitor goes down when every region it is assigned to that reported
|
||||
// recently has failed the configured number of times in a row: one region
|
||||
// failing while another succeeds is the checker's problem, not the
|
||||
// target's. A region without recent results counts as unknown and is left
|
||||
// out, so a dead region neither keeps a monitor up nor takes it down; with
|
||||
// every region unknown nothing is judged at all. Any successful region
|
||||
// brings the monitor back up.
|
||||
//
|
||||
// The state lives in Redis and each observation is applied by one Lua
|
||||
@@ -53,9 +55,9 @@ type Observation struct {
|
||||
Regions []string
|
||||
}
|
||||
|
||||
// staleAfter is how old a region's last result may be before the region
|
||||
// StaleAfter is how old a region's last result may be before the region
|
||||
// counts as unknown.
|
||||
func staleAfter(interval time.Duration) time.Duration {
|
||||
func StaleAfter(interval time.Duration) time.Duration {
|
||||
return max(3*interval, 2*time.Minute)
|
||||
}
|
||||
|
||||
@@ -86,12 +88,17 @@ if state == 'down' then
|
||||
end
|
||||
return 'none'
|
||||
end
|
||||
local reporting = 0
|
||||
for i = 7, #ARGV do
|
||||
local r = ARGV[i]
|
||||
local fails = tonumber(redis.call('HGET', key, 'f:' .. r) or '0')
|
||||
local seen = tonumber(redis.call('HGET', key, 'a:' .. r) or '0')
|
||||
if fails < need or seen < stale then return 'none' end
|
||||
if seen >= stale then
|
||||
local fails = tonumber(redis.call('HGET', key, 'f:' .. r) or '0')
|
||||
if fails < need then return 'none' end
|
||||
reporting = reporting + 1
|
||||
end
|
||||
end
|
||||
if reporting == 0 then return 'none' end
|
||||
redis.call('HSET', key, 'state', 'down')
|
||||
return 'down'
|
||||
`)
|
||||
@@ -113,7 +120,7 @@ func (e *Evaluator) Observe(ctx context.Context, o Observation) (Transition, err
|
||||
if o.OK {
|
||||
ok = "1"
|
||||
}
|
||||
stale := e.now().Add(-staleAfter(o.Interval)).UnixMilli()
|
||||
stale := e.now().Add(-StaleAfter(o.Interval)).UnixMilli()
|
||||
args := []any{o.Region, ok, o.At.UnixMilli(), max(o.Confirmations, 1), stale, int(stateTTL.Seconds())}
|
||||
for _, r := range o.Regions {
|
||||
args = append(args, r)
|
||||
|
||||
@@ -55,9 +55,9 @@ func play(t *testing.T, e *Evaluator, now *time.Time, regions []string, confirma
|
||||
func TestDownOnlyWhenAllRegionsFail(t *testing.T) {
|
||||
e, now := newTest(t)
|
||||
play(t, e, now, []string{"eu", "us"}, 2, []step{
|
||||
{"eu", false, None},
|
||||
{"eu", false, None}, // eu confirmed down, us has not reported
|
||||
{"us", true, None},
|
||||
{"eu", false, None},
|
||||
{"eu", false, None}, // eu confirmed down, us still fine
|
||||
{"us", false, None},
|
||||
{"eu", false, None},
|
||||
{"us", false, Down}, // both regions failed twice in a row
|
||||
@@ -79,7 +79,7 @@ func TestSingleRegionWithConfirmations(t *testing.T) {
|
||||
})
|
||||
}
|
||||
|
||||
func TestSilentRegionBlocksAlert(t *testing.T) {
|
||||
func TestSilentRegionIsLeftOut(t *testing.T) {
|
||||
e, now := newTest(t)
|
||||
id := uuid.New()
|
||||
obs := func(region string, ok bool) Transition {
|
||||
@@ -92,12 +92,27 @@ func TestSilentRegionBlocksAlert(t *testing.T) {
|
||||
}
|
||||
return got
|
||||
}
|
||||
obs("us", false)
|
||||
// us stops reporting for longer than three intervals.
|
||||
obs("us", true)
|
||||
// us stops reporting for longer than three intervals: the failures of
|
||||
// eu alone decide.
|
||||
*now = now.Add(5 * time.Minute)
|
||||
if got := obs("eu", false); got != None {
|
||||
t.Errorf("eu failure with us silent = %v, want none", got)
|
||||
if got := obs("eu", false); got != Down {
|
||||
t.Errorf("eu failure with us silent = %v, want down", got)
|
||||
}
|
||||
// us reporting a success again brings the monitor back up.
|
||||
*now = now.Add(time.Second)
|
||||
if got := obs("us", true); got != Up {
|
||||
t.Errorf("us success after the outage = %v, want up", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestReportingRegionStillVetoes(t *testing.T) {
|
||||
e, now := newTest(t)
|
||||
play(t, e, now, []string{"eu", "us"}, 1, []step{
|
||||
{"us", true, None},
|
||||
{"eu", false, None}, // us reported recently and was fine
|
||||
{"eu", false, None},
|
||||
})
|
||||
}
|
||||
|
||||
func TestOutOfOrderResultIgnored(t *testing.T) {
|
||||
|
||||
@@ -107,6 +107,7 @@
|
||||
"audit.action.member.role_unassign": "Rolle entzogen",
|
||||
"audit.action.monitor.create": "Monitor erstellt",
|
||||
"audit.action.monitor.delete": "Monitor gelöscht",
|
||||
"audit.action.monitor.order": "Monitore angeordnet",
|
||||
"audit.action.monitor.update": "Monitor geändert",
|
||||
"audit.action.org.check_types_update": "Check-Typen geändert",
|
||||
"audit.action.org.create": "Organisation angelegt",
|
||||
@@ -514,8 +515,16 @@
|
||||
"console.sso_required_action": "Mit SSO anmelden",
|
||||
"console.suspended_reason": "Grund: {{.Reason}}",
|
||||
"console.totp_missing_action": "Jetzt einrichten",
|
||||
"email.domain_missing.body": "Die Statusseite {{.Page}} wird unter {{.Domain}} ausgeliefert, aber der DNS-Eintrag, der nachweist, dass die Domain zu ihr gehört, ist nicht mehr zu finden.\n\nIst er bis {{.Date}} nicht zurück, wird die Domain abgeschaltet und die Seite dort nicht mehr ausgeliefert. Den Eintrag, der wiederhergestellt werden muss, findest du hier:\n{{.Link}}",
|
||||
"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.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}}",
|
||||
"email.region_back.subject": "Region {{.Region}} prüft wieder",
|
||||
"email.region_down.body": "Region {{.Region}} hat seit {{.Minutes}} Minuten keinen aktiven Checker, seit {{.Since}}.\n\nMonitore, die nur von dort geprüft werden, werden gerade nicht geprüft: Sie fallen weder aus noch alarmieren sie. Monitore mit weiteren Regionen werden nur nach diesen beurteilt, bis diese Region wieder meldet.\n\nStarte einen Checker der Region oder sieh dir seine Logs an:\n{{.Link}}",
|
||||
"email.region_down.subject": "Region {{.Region}} hat keinen aktiven Checker",
|
||||
"email.resolved.body": "{{.Monitor}} ({{.Target}}) ist nach {{.Duration}} wieder erreichbar.",
|
||||
"email.resolved.subject": "[UP] {{.Monitor}}",
|
||||
"email.support_admin.body": "Hallo,\n\nein Support-Ticket wartet auf eine Antwort:\n\n{{.Subject}}\n\n{{.Link}}",
|
||||
@@ -539,7 +548,8 @@
|
||||
"error.confirmation_failed": "Die Bestätigung stimmt nicht.",
|
||||
"error.consent_outdated": "Die Dokumente haben sich inzwischen geändert. Lade die Seite neu und stimme der aktuellen Fassung zu.",
|
||||
"error.consent_required": "Bitte stimme zuerst Datenschutz und AGB zu.",
|
||||
"error.domain_not_verified": "Der TXT-Eintrag wurde noch nicht gefunden. DNS-Änderungen brauchen manchmal etwas Zeit.",
|
||||
"error.domain_changes_exceeded": "Die eigene Domain wurde heute schon {{.Count}}-mal geändert. Versuch es morgen wieder.",
|
||||
"error.domain_not_verified": "Weder der CNAME- noch der TXT-Eintrag wurde bisher gefunden. DNS-Änderungen brauchen manchmal etwas, bis sie sichtbar sind.",
|
||||
"error.domain_taken": "Diese Domain nutzt bereits eine andere Statuspage.",
|
||||
"error.email_not_configured": "E-Mail ist auf diesem Server nicht verfügbar.",
|
||||
"error.email_taken": "Diese E-Mail-Adresse ist bereits registriert.",
|
||||
@@ -610,6 +620,7 @@
|
||||
"error.owner_cannot_be_removed": "Owner können nicht entfernt werden. Entziehe zuerst die Owner-Rechte.",
|
||||
"error.owner_has_all_permissions": "Der Owner hat bereits alle Berechtigungen.",
|
||||
"error.owner_only": "Nur Owner können ändern, wem die Organisation gehört.",
|
||||
"error.page_monitor_limit": "Eine Statusseite darf höchstens {{.Max}} Monitore zeigen.",
|
||||
"error.password_too_short": "Das Passwort braucht mindestens {{.Min}} Zeichen.",
|
||||
"error.permission_escalation": "Du kannst keine Berechtigungen vergeben, die du selbst nicht hast.",
|
||||
"error.platform_region_limit": "Ein Monitor darf aus höchstens {{.Max}} Plattform-Regionen geprüft werden; eigene Checker-Regionen zählen nicht.",
|
||||
@@ -893,6 +904,7 @@
|
||||
"limits.default": "Standard: {{.Value}}",
|
||||
"limits.intro": "Gelten für jede Organisation und jeden Account ohne eigenen Wert, auch wenn du sie später änderst. 0 heißt unbegrenzt. Ein gesenktes Limit lässt alles Bestehende stehen; nur neue Monitore, Statusseiten, Regionen oder Organisationen werden abgelehnt.",
|
||||
"limits.monitors": "Monitore",
|
||||
"limits.monitors_per_page": "Monitore pro Statusseite",
|
||||
"limits.org_title": "Kontingent",
|
||||
"limits.orgs_per_account": "Organisationen pro Account",
|
||||
"limits.own_false": "zählen nicht",
|
||||
@@ -1010,6 +1022,9 @@
|
||||
"monitors.alertmanager_hint": "Ausgefallen, solange ein Alert feuert, der alle Matcher erfüllt. Alerts kommen über einen Empfänger:",
|
||||
"monitors.all": "Alle Monitore",
|
||||
"monitors.all_results": "Alle Ergebnisse",
|
||||
"monitors.arrange": "Monitore anordnen",
|
||||
"monitors.arrange_done": "Anordnen beenden",
|
||||
"monitors.arrange_hint": "Zieh die Monitore oder verschieb sie mit ↑ und ↓ in die gewünschte Reihenfolge innerhalb ihrer Gruppe. Jede Änderung wird sofort gespeichert und gilt für alle in der Organisation.",
|
||||
"monitors.assertion_op": "Operator",
|
||||
"monitors.assertion_path": "Pfad",
|
||||
"monitors.assertion_value": "Wert",
|
||||
@@ -1045,6 +1060,7 @@
|
||||
"monitors.db_tls_verify": "TLS mit geprüftem Zertifikat",
|
||||
"monitors.db_user": "Benutzer",
|
||||
"monitors.db_user_redis": "Benutzer (ACL, optional)",
|
||||
"monitors.dead_region": "Region {{.Region}} hat seit {{.Since}} keinen aktiven Checker.",
|
||||
"monitors.delete": "Monitor löschen",
|
||||
"monitors.delete_confirm": "Diesen Monitor samt Verlauf löschen?",
|
||||
"monitors.dns_expect": "Erwartete Antwort (optional)",
|
||||
@@ -1054,6 +1070,13 @@
|
||||
"monitors.docker_host": "Docker-Host (unix://-Socket oder tcp://host:2375)",
|
||||
"monitors.edit": "Monitor bearbeiten",
|
||||
"monitors.expect_status": "Erwarteter Status (z. B. 2xx, 301)",
|
||||
"monitors.filter_clear": "Alle Status anzeigen",
|
||||
"monitors.filter_label": "Monitore nach Status anzeigen",
|
||||
"monitors.filter_only": "Nur",
|
||||
"monitors.filter_show": {
|
||||
"one": "Nur den {{.Count}} Monitor mit Status „{{.Status}}“ anzeigen",
|
||||
"other": "Nur die {{.Count}} Monitore mit Status „{{.Status}}“ anzeigen"
|
||||
},
|
||||
"monitors.follow_redirects": "Weiterleitungen folgen",
|
||||
"monitors.game_min_free_slots": "Mindestens freie Plätze",
|
||||
"monitors.game_min_free_slots_hint": "0 prüft nur, ob der Server antwortet.",
|
||||
@@ -1080,9 +1103,13 @@
|
||||
"monitors.minecraft_edition": "Edition",
|
||||
"monitors.minecraft_hint": "Ziel ist host:port (Java meist 25565, Bedrock 19132). Pingt den Server wie die Serverliste im Spiel.",
|
||||
"monitors.minecraft_java": "Java Edition",
|
||||
"monitors.move_down": "{{.Name}} nach unten",
|
||||
"monitors.move_up": "{{.Name}} nach oben",
|
||||
"monitors.new": "Neuer Monitor",
|
||||
"monitors.no_data_since": "keine Daten seit {{.Time}}",
|
||||
"monitors.no_match": "Kein Monitor gefunden.",
|
||||
"monitors.no_results": "Noch keine Ergebnisse.",
|
||||
"monitors.no_status_match": "Gerade hat kein Monitor diesen Status.",
|
||||
"monitors.op_absent": "fehlt",
|
||||
"monitors.op_contains": "enthält",
|
||||
"monitors.op_eq": "gleich",
|
||||
@@ -1133,6 +1160,12 @@
|
||||
"monitors.snmp_oid": "OID",
|
||||
"monitors.snmp_value": "Wert",
|
||||
"monitors.snmp_version": "Version",
|
||||
"monitors.sort": "Sortierung",
|
||||
"monitors.sort_custom": "eigene Reihenfolge",
|
||||
"monitors.sort_latency": "Latenz",
|
||||
"monitors.sort_name": "Name",
|
||||
"monitors.sort_status": "Status",
|
||||
"monitors.sort_uptime": "Uptime",
|
||||
"monitors.stale_hours": "Verfällt nach (Stunden)",
|
||||
"monitors.stale_hours_hint": "Ein feuernder Alert, den Alertmanager nicht mehr wiederholt, gilt nach dieser Zeit als beendet. Halte sie über repeat_interval.",
|
||||
"monitors.steam_hint": "Ziel ist host:port des Query-Ports (meist der Spielport, z. B. 27015). Fragt den Server wie der Steam-Serverbrowser nach seinen Infos (A2S); funktioniert für Source- und die meisten Steam-Spiele.",
|
||||
@@ -1167,6 +1200,11 @@
|
||||
"monitors.type_steam": "Steam-Spieleserver",
|
||||
"monitors.type_tcp": "TCP-Port",
|
||||
"monitors.type_tls": "TLS-Zertifikat",
|
||||
"monitors.unchecked": "wird nicht geprüft",
|
||||
"monitors.unchecked_banner": {
|
||||
"one": "1 Monitor wird gerade nicht geprüft: Keine Region hat für ihn in letzter Zeit gemeldet. Er fällt weder aus noch alarmiert er, bis wieder ein Checker meldet.",
|
||||
"other": "{{.Count}} Monitore werden gerade nicht geprüft: Keine Region hat für sie in letzter Zeit gemeldet. Sie fallen weder aus noch alarmieren sie, bis wieder ein Checker meldet."
|
||||
},
|
||||
"monitors.ungrouped": "Ohne Gruppe",
|
||||
"monitors.uptime_chart": "Uptime pro Zeitraum",
|
||||
"monitors.verify_tls": "TLS-Zertifikat prüfen",
|
||||
@@ -1238,10 +1276,22 @@
|
||||
"pages.delete_confirm": "Diese Statuspage löschen?",
|
||||
"pages.description": "Beschreibung",
|
||||
"pages.domain": "Eigene Domain",
|
||||
"pages.domain_cname": "Richte die Domain (CNAME oder A-Record) auf deinen Statuspage-Server; er holt sich automatisch ein Zertifikat, wenn TLS aktiviert ist.",
|
||||
"pages.domain_instructions": "Lege diesen DNS-Eintrag an und prüfe ihn dann. Nur geprüfte Domains werden ausgeliefert.",
|
||||
"pages.domain_alt": "Dann ist der CNAME von außen nicht zu sehen. Weise die Domain stattdessen mit diesem TXT-Eintrag nach und lass die Domain oder den Origin deines Proxys auf {{.Target}} zeigen; für eine Domain ohne Subdomain nutze einen ALIAS- oder ANAME-Eintrag oder CNAME-Flattening.",
|
||||
"pages.domain_alt_summary": "Hinter einem Proxy wie Cloudflare oder eine Domain ohne Subdomain?",
|
||||
"pages.domain_apex": "Eine Domain ohne Subdomain (example.com) kann keinen CNAME-Eintrag haben. Nutze stattdessen den ALIAS- oder ANAME-Eintrag deines DNS-Anbieters oder A/AAAA-Einträge.",
|
||||
"pages.domain_cname_step": "Lege diesen CNAME-Eintrag an. Er lässt die Domain auf die Statusseiten-Server zeigen und weist zugleich nach, dass sie dir gehört, denn sein Ziel gehört nur zu dieser Seite. Wir sehen alle paar Minuten nach und prüfen die Domain von selbst; DNS-Änderungen brauchen manchmal etwas, bis sie sichtbar sind.",
|
||||
"pages.domain_intro": "Liefere diese Seite unter einer eigenen Domain aus, z. B. status.example.com. Meist reicht ein einziger DNS-Eintrag; HTTPS kommt von selbst.",
|
||||
"pages.domain_keep": "Lass den Eintrag bestehen: Er wird täglich geprüft, und eine Domain, deren Eintrag eine Woche lang fehlt, wird abgeschaltet, damit niemand anderes sie übernehmen kann.",
|
||||
"pages.domain_missing": "Der Eintrag dieser Domain ist seit {{.Since}} nicht mehr zu finden. Kommt er nicht zurück, wird die Domain am {{.Date}} abgeschaltet.",
|
||||
"pages.domain_name": "Domain",
|
||||
"pages.domain_step_cname_own": "Lass die Domain dann auf die eigenen Statusseiten-Server deiner Organisation zeigen: per CNAME-Eintrag auf deren Hostnamen oder per A/AAAA-Eintrag auf deren Adressen.",
|
||||
"pages.domain_step_cname_unknown": "Lass die Domain dann per CNAME-Eintrag auf die Statusseiten-Server der Plattform zeigen; das Ziel nennt dir der Betreiber dieser Installation.",
|
||||
"pages.domain_step_tls": "HTTPS: Das Zertifikat wird beim ersten Aufruf über HTTPS automatisch geholt, das kann bis zu einer Minute dauern. Zum Schutz der Limits der Zertifizierungsstelle, die sich alle Organisationen teilen, sind neue Zertifikate pro Tag begrenzt, und die Domain lässt sich höchstens {{.Count}}-mal am Tag ändern.",
|
||||
"pages.domain_step_verified": "1. Domain geprüft.",
|
||||
"pages.domain_step_verify": "Weise mit diesem TXT-Eintrag nach, dass die Domain dir gehört, und prüfe ihn dann. Bis dahin wird die Domain weder ausgeliefert noch bekommt sie ein Zertifikat.",
|
||||
"pages.domain_verified": "Domain geprüft.",
|
||||
"pages.domain_verified_by_cname": "Domain über ihren CNAME-Eintrag geprüft.",
|
||||
"pages.domain_verified_by_txt": "Domain über ihren TXT-Eintrag geprüft.",
|
||||
"pages.draft": "Entwurf",
|
||||
"pages.export": "Als HTML exportieren",
|
||||
"pages.group": "Gruppe",
|
||||
@@ -1254,8 +1304,14 @@
|
||||
"pages.intro": "Öffentliche Seiten mit dem Zustand ausgewählter Monitore. Jede Seite kann eine eigene Domain nutzen oder als einzelne HTML-Datei exportiert werden.",
|
||||
"pages.label": "Öffentlicher Name",
|
||||
"pages.logo": "Logo-URL (https)",
|
||||
"pages.monitor_limit": "Diese Seite darf höchstens {{.Max}} Monitore zeigen.",
|
||||
"pages.monitors_filter": "Monitore filtern",
|
||||
"pages.monitors_all": "Alle hinzufügen",
|
||||
"pages.monitors_none": "Alle entfernen",
|
||||
"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.",
|
||||
"pages.own_servers_short": "eigene Server",
|
||||
"pages.page_title": "Titel",
|
||||
"pages.published": "Veröffentlicht",
|
||||
"pages.section": "Abschnitt",
|
||||
@@ -1269,6 +1325,7 @@
|
||||
"pages.title": "Statuspages",
|
||||
"pages.value": "Wert",
|
||||
"pages.verify": "Prüfen",
|
||||
"pages.verify_now": "Jetzt prüfen",
|
||||
"perm.audit.read": "Audit-Log einsehen",
|
||||
"perm.incidents.read": "Incidents sehen",
|
||||
"perm.incidents.write": "Incidents verwalten",
|
||||
@@ -1499,5 +1556,55 @@
|
||||
"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.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"
|
||||
}
|
||||
@@ -107,6 +107,7 @@
|
||||
"audit.action.member.role_unassign": "Role removed",
|
||||
"audit.action.monitor.create": "Monitor created",
|
||||
"audit.action.monitor.delete": "Monitor deleted",
|
||||
"audit.action.monitor.order": "Monitors put in order",
|
||||
"audit.action.monitor.update": "Monitor changed",
|
||||
"audit.action.org.check_types_update": "Check types changed",
|
||||
"audit.action.org.create": "Organization created",
|
||||
@@ -514,8 +515,16 @@
|
||||
"console.sso_required_action": "Sign in with SSO",
|
||||
"console.suspended_reason": "Reason: {{.Reason}}",
|
||||
"console.totp_missing_action": "Set up now",
|
||||
"email.domain_missing.body": "The status page {{.Page}} is served at {{.Domain}}, but the DNS record proving that the domain belongs to it can no longer be found.\n\nUnless it is back by {{.Date}}, the domain is switched off and the page is no longer served there. The record to restore is shown here:\n{{.Link}}",
|
||||
"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.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}}",
|
||||
"email.region_back.subject": "Region {{.Region}} is checking again",
|
||||
"email.region_down.body": "Region {{.Region}} has had no active checker for {{.Minutes}} minutes, since {{.Since}}.\n\nMonitors checked only from there are not being checked right now: they neither go down nor alert. Monitors with other regions as well are judged by those alone until this one reports again.\n\nStart a checker of the region or look at its logs:\n{{.Link}}",
|
||||
"email.region_down.subject": "Region {{.Region}} has no active checker",
|
||||
"email.resolved.body": "{{.Monitor}} ({{.Target}}) is reachable again after {{.Duration}}.",
|
||||
"email.resolved.subject": "[UP] {{.Monitor}}",
|
||||
"email.support_admin.body": "Hello,\n\na support ticket waits for an answer:\n\n{{.Subject}}\n\n{{.Link}}",
|
||||
@@ -539,7 +548,8 @@
|
||||
"error.confirmation_failed": "The confirmation does not match.",
|
||||
"error.consent_outdated": "The documents changed in the meantime. Reload the page and accept the current version.",
|
||||
"error.consent_required": "Please accept the privacy policy and terms first.",
|
||||
"error.domain_not_verified": "The TXT record was not found yet. DNS changes can take a while to appear.",
|
||||
"error.domain_changes_exceeded": "The custom domain was changed {{.Count}} times today already. Try again tomorrow.",
|
||||
"error.domain_not_verified": "Neither the CNAME nor the TXT record was found yet. DNS changes can take a while to appear.",
|
||||
"error.domain_taken": "This domain is already used by another status page.",
|
||||
"error.email_not_configured": "Email is not available on this server.",
|
||||
"error.email_taken": "This email address is already registered.",
|
||||
@@ -610,6 +620,7 @@
|
||||
"error.owner_cannot_be_removed": "Owners cannot be removed. Take their ownership away first.",
|
||||
"error.owner_has_all_permissions": "The owner already has every permission.",
|
||||
"error.owner_only": "Only owners can change who owns the organization.",
|
||||
"error.page_monitor_limit": "A status page may show at most {{.Max}} monitors.",
|
||||
"error.password_too_short": "The password needs at least {{.Min}} characters.",
|
||||
"error.permission_escalation": "You cannot grant permissions you do not hold yourself.",
|
||||
"error.platform_region_limit": "A monitor may be checked from at most {{.Max}} platform regions; your own checker regions do not count.",
|
||||
@@ -893,6 +904,7 @@
|
||||
"limits.default": "default: {{.Value}}",
|
||||
"limits.intro": "Apply to every organization and account without an override of its own, also when you change them later. 0 means unlimited. Lowering a limit keeps everything that exists; only new monitors, status pages, regions or organizations are refused.",
|
||||
"limits.monitors": "Monitors",
|
||||
"limits.monitors_per_page": "Monitors per status page",
|
||||
"limits.org_title": "Usage",
|
||||
"limits.orgs_per_account": "Organizations per account",
|
||||
"limits.own_false": "do not count",
|
||||
@@ -1010,6 +1022,9 @@
|
||||
"monitors.alertmanager_hint": "Down while an alert matching all matchers fires. Alerts arrive through a receiver:",
|
||||
"monitors.all": "All monitors",
|
||||
"monitors.all_results": "All results",
|
||||
"monitors.arrange": "Arrange monitors",
|
||||
"monitors.arrange_done": "Done arranging",
|
||||
"monitors.arrange_hint": "Drag the monitors, or move them with ↑ and ↓, into the order you want within each group. Every change is saved at once and is the same for everybody in the organization.",
|
||||
"monitors.assertion_op": "Operator",
|
||||
"monitors.assertion_path": "Path",
|
||||
"monitors.assertion_value": "Value",
|
||||
@@ -1045,6 +1060,7 @@
|
||||
"monitors.db_tls_verify": "TLS with verified certificate",
|
||||
"monitors.db_user": "User",
|
||||
"monitors.db_user_redis": "User (ACL, optional)",
|
||||
"monitors.dead_region": "Region {{.Region}} has had no active checker since {{.Since}}.",
|
||||
"monitors.delete": "Delete monitor",
|
||||
"monitors.delete_confirm": "Delete this monitor and its history?",
|
||||
"monitors.dns_expect": "Expected answer (optional)",
|
||||
@@ -1054,6 +1070,13 @@
|
||||
"monitors.docker_host": "Docker host (unix:// socket or tcp://host:2375)",
|
||||
"monitors.edit": "Edit monitor",
|
||||
"monitors.expect_status": "Expected status (e.g. 2xx, 301)",
|
||||
"monitors.filter_clear": "Show all statuses",
|
||||
"monitors.filter_label": "Show monitors by status",
|
||||
"monitors.filter_only": "Only",
|
||||
"monitors.filter_show": {
|
||||
"one": "Show only the {{.Count}} monitor that is {{.Status}}",
|
||||
"other": "Show only the {{.Count}} monitors that are {{.Status}}"
|
||||
},
|
||||
"monitors.follow_redirects": "Follow redirects",
|
||||
"monitors.game_min_free_slots": "Minimum free slots",
|
||||
"monitors.game_min_free_slots_hint": "0 only checks that the server answers.",
|
||||
@@ -1080,9 +1103,13 @@
|
||||
"monitors.minecraft_edition": "Edition",
|
||||
"monitors.minecraft_hint": "Target is host:port (Java usually 25565, Bedrock 19132). Pings the server like the in-game server list.",
|
||||
"monitors.minecraft_java": "Java Edition",
|
||||
"monitors.move_down": "Move {{.Name}} down",
|
||||
"monitors.move_up": "Move {{.Name}} up",
|
||||
"monitors.new": "New monitor",
|
||||
"monitors.no_data_since": "no data since {{.Time}}",
|
||||
"monitors.no_match": "No monitor matches.",
|
||||
"monitors.no_results": "No results yet.",
|
||||
"monitors.no_status_match": "No monitor has this status right now.",
|
||||
"monitors.op_absent": "is absent",
|
||||
"monitors.op_contains": "contains",
|
||||
"monitors.op_eq": "equals",
|
||||
@@ -1133,6 +1160,12 @@
|
||||
"monitors.snmp_oid": "OID",
|
||||
"monitors.snmp_value": "Value",
|
||||
"monitors.snmp_version": "Version",
|
||||
"monitors.sort": "Sort order",
|
||||
"monitors.sort_custom": "own order",
|
||||
"monitors.sort_latency": "latency",
|
||||
"monitors.sort_name": "name",
|
||||
"monitors.sort_status": "status",
|
||||
"monitors.sort_uptime": "uptime",
|
||||
"monitors.stale_hours": "Stale after (hours)",
|
||||
"monitors.stale_hours_hint": "A firing alert Alertmanager stops repeating counts as over after this time. Keep it above repeat_interval.",
|
||||
"monitors.steam_hint": "Target is host:port of the query port (usually the game port, e.g. 27015). Asks the server for its info like the Steam server browser (A2S); works for Source and most Steam games.",
|
||||
@@ -1167,6 +1200,11 @@
|
||||
"monitors.type_steam": "Steam game server",
|
||||
"monitors.type_tcp": "TCP port",
|
||||
"monitors.type_tls": "TLS certificate",
|
||||
"monitors.unchecked": "not being checked",
|
||||
"monitors.unchecked_banner": {
|
||||
"one": "1 monitor is not being checked: no region has reported for it recently. It neither goes down nor alerts until a checker reports again.",
|
||||
"other": "{{.Count}} monitors are not being checked: no region has reported for them recently. They neither go down nor alert until a checker reports again."
|
||||
},
|
||||
"monitors.ungrouped": "Without group",
|
||||
"monitors.uptime_chart": "Uptime per period",
|
||||
"monitors.verify_tls": "Verify TLS certificate",
|
||||
@@ -1238,10 +1276,22 @@
|
||||
"pages.delete_confirm": "Delete this status page?",
|
||||
"pages.description": "Description",
|
||||
"pages.domain": "Custom domain",
|
||||
"pages.domain_cname": "Point the domain (CNAME or A record) at your status page server; it obtains a certificate automatically when TLS is enabled.",
|
||||
"pages.domain_instructions": "Create this DNS record, then verify. Only verified domains are served.",
|
||||
"pages.domain_alt": "Then the CNAME cannot be seen from outside. Prove the domain with this TXT record instead, and point the domain, or your proxy's origin, at {{.Target}}; for a domain without a subdomain use an ALIAS or ANAME record or CNAME flattening.",
|
||||
"pages.domain_alt_summary": "Behind a proxy such as Cloudflare, or a domain without a subdomain?",
|
||||
"pages.domain_apex": "A domain without a subdomain (example.com) cannot have a CNAME record. Use your DNS provider's ALIAS or ANAME record, or A/AAAA records, instead.",
|
||||
"pages.domain_cname_step": "Create this CNAME record. It points the domain at the status page servers and proves that the domain is yours, because its target belongs to this page alone. We look for it every few minutes and verify the domain on our own; DNS changes can take a while to appear.",
|
||||
"pages.domain_intro": "Serve this page under a domain of your own, e.g. status.example.com. One DNS record is usually all it takes; HTTPS follows by itself.",
|
||||
"pages.domain_keep": "Keep the record in place: it is checked daily, and a domain whose record has been gone for a week is switched off, so nobody else can take it over.",
|
||||
"pages.domain_missing": "The record of this domain has not been found since {{.Since}}. Unless it is back, the domain is switched off on {{.Date}}.",
|
||||
"pages.domain_name": "Domain",
|
||||
"pages.domain_step_cname_own": "Then point the domain at your organization's own status page servers: a CNAME record to their host name, or A/AAAA records to their addresses.",
|
||||
"pages.domain_step_cname_unknown": "Then point the domain at the platform's status page servers with a CNAME record; the operator of this installation tells you its target.",
|
||||
"pages.domain_step_tls": "HTTPS: the certificate is obtained automatically on the first visit over HTTPS, which can take up to a minute. To protect the certificate authority's limits that all organizations share, new certificates are limited per day, and the domain can be changed at most {{.Count}} times a day.",
|
||||
"pages.domain_step_verified": "1. Domain verified.",
|
||||
"pages.domain_step_verify": "Prove the domain is yours with this TXT record, then verify. Until then the domain is neither served nor given a certificate.",
|
||||
"pages.domain_verified": "Domain verified.",
|
||||
"pages.domain_verified_by_cname": "Domain verified by its CNAME record.",
|
||||
"pages.domain_verified_by_txt": "Domain verified by its TXT record.",
|
||||
"pages.draft": "draft",
|
||||
"pages.export": "Export as HTML",
|
||||
"pages.group": "Group",
|
||||
@@ -1254,8 +1304,14 @@
|
||||
"pages.intro": "Public pages showing the state of selected monitors. Each page can use its own domain or be exported as a single HTML file.",
|
||||
"pages.label": "Public name",
|
||||
"pages.logo": "Logo URL (https)",
|
||||
"pages.monitor_limit": "This page may show at most {{.Max}} monitors.",
|
||||
"pages.monitors_filter": "Filter monitors",
|
||||
"pages.monitors_all": "Add all",
|
||||
"pages.monitors_none": "Remove all",
|
||||
"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.",
|
||||
"pages.own_servers_short": "own servers",
|
||||
"pages.page_title": "Title",
|
||||
"pages.published": "Published",
|
||||
"pages.section": "Section",
|
||||
@@ -1269,6 +1325,7 @@
|
||||
"pages.title": "Status pages",
|
||||
"pages.value": "Value",
|
||||
"pages.verify": "Verify",
|
||||
"pages.verify_now": "Check now",
|
||||
"perm.audit.read": "View the audit log",
|
||||
"perm.incidents.read": "View incidents",
|
||||
"perm.incidents.write": "Manage incidents",
|
||||
@@ -1499,5 +1556,55 @@
|
||||
"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.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"
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
-- +goose Up
|
||||
-- Custom domains are verified by a CNAME to a target unique to the page, or
|
||||
-- by the TXT record, and checked again while they are in use: a domain that
|
||||
-- no longer points at the page is switched off after a grace period, so a
|
||||
-- record left behind cannot be taken over. Domains verified before this
|
||||
-- have no method and are not checked again.
|
||||
ALTER TABLE status_pages
|
||||
ADD COLUMN domain_set_at timestamptz,
|
||||
ADD COLUMN domain_checked_at timestamptz,
|
||||
ADD COLUMN domain_failing_since timestamptz,
|
||||
ADD COLUMN domain_verify_method text CHECK (domain_verify_method IN ('cname', 'txt'));
|
||||
UPDATE status_pages SET domain_set_at = updated_at WHERE custom_domain IS NOT NULL;
|
||||
|
||||
-- +goose Down
|
||||
ALTER TABLE status_pages
|
||||
DROP COLUMN domain_verify_method,
|
||||
DROP COLUMN domain_failing_since,
|
||||
DROP COLUMN domain_checked_at,
|
||||
DROP COLUMN domain_set_at;
|
||||
@@ -0,0 +1,7 @@
|
||||
-- +goose Up
|
||||
-- How many monitors one status page of the organization may show; NULL
|
||||
-- follows the platform default, 0 means unlimited.
|
||||
ALTER TABLE orgs ADD COLUMN limit_monitors_per_page integer CHECK (limit_monitors_per_page >= 0);
|
||||
|
||||
-- +goose Down
|
||||
ALTER TABLE orgs DROP COLUMN limit_monitors_per_page;
|
||||
@@ -0,0 +1,7 @@
|
||||
-- +goose Up
|
||||
-- The organization's own order of its monitors on the monitor list, within
|
||||
-- each group; NULL sorts after positioned monitors, by name.
|
||||
ALTER TABLE monitors ADD COLUMN position integer;
|
||||
|
||||
-- +goose Down
|
||||
ALTER TABLE monitors DROP COLUMN position;
|
||||
@@ -0,0 +1,41 @@
|
||||
-- +goose Up
|
||||
-- The newest result per monitor and region, kept up to date as results
|
||||
-- arrive. Finding it in check_results means reading a day of results of
|
||||
-- every monitor, which made every console page slow for organizations
|
||||
-- with many monitors.
|
||||
CREATE TABLE latest_results (
|
||||
monitor_id uuid NOT NULL,
|
||||
region text NOT NULL,
|
||||
org_id uuid NOT NULL,
|
||||
time timestamptz NOT NULL,
|
||||
ok boolean NOT NULL,
|
||||
latency_ms integer,
|
||||
status_code integer,
|
||||
error text,
|
||||
PRIMARY KEY (monitor_id, region),
|
||||
FOREIGN KEY (monitor_id, org_id) REFERENCES monitors (id, org_id) ON DELETE CASCADE
|
||||
);
|
||||
CREATE INDEX latest_results_org_idx ON latest_results (org_id);
|
||||
|
||||
INSERT INTO latest_results (monitor_id, region, org_id, time, ok, latency_ms, status_code, error)
|
||||
SELECT DISTINCT ON (r.monitor_id, r.region) r.monitor_id, r.region, r.org_id, r.time, r.ok, r.latency_ms, r.status_code, r.error
|
||||
FROM check_results r
|
||||
JOIN monitors m ON m.id = r.monitor_id AND m.org_id = r.org_id
|
||||
WHERE r.time > now() - INTERVAL '1 day'
|
||||
ORDER BY r.monitor_id, r.region, r.time DESC;
|
||||
|
||||
ALTER TABLE latest_results ENABLE ROW LEVEL SECURITY;
|
||||
ALTER TABLE latest_results FORCE ROW LEVEL SECURITY;
|
||||
CREATE POLICY latest_results_tenant ON latest_results FOR ALL
|
||||
USING (app_scope_system() OR org_id = app_org_id())
|
||||
WITH CHECK (app_scope_system() OR org_id = app_org_id());
|
||||
|
||||
-- Console queries name the organization so that these can be used; row
|
||||
-- security alone does not let the planner use an index.
|
||||
CREATE INDEX monitor_regions_org_idx ON monitor_regions (org_id);
|
||||
CREATE INDEX incidents_open_org_idx ON incidents (org_id) WHERE resolved_at IS NULL;
|
||||
|
||||
-- +goose Down
|
||||
DROP INDEX incidents_open_org_idx;
|
||||
DROP INDEX monitor_regions_org_idx;
|
||||
DROP TABLE latest_results;
|
||||
@@ -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;
|
||||
@@ -15,11 +15,13 @@ import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"maps"
|
||||
"mime"
|
||||
"net"
|
||||
"net/http"
|
||||
"net/smtp"
|
||||
"net/url"
|
||||
"slices"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
@@ -158,6 +160,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 +227,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()
|
||||
|
||||
@@ -3,6 +3,7 @@ package platform
|
||||
import (
|
||||
"context"
|
||||
"net/http"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"time"
|
||||
|
||||
@@ -17,15 +18,24 @@ type Probe func(context.Context) error
|
||||
type Health struct {
|
||||
probes map[string]Probe
|
||||
draining atomic.Bool
|
||||
drained chan struct{}
|
||||
once sync.Once
|
||||
}
|
||||
|
||||
// NewHealth returns a Health that is ready while all probes pass.
|
||||
func NewHealth(probes map[string]Probe) *Health {
|
||||
return &Health{probes: probes}
|
||||
return &Health{probes: probes, drained: make(chan struct{})}
|
||||
}
|
||||
|
||||
// Drain makes /readyz fail permanently. Call it before shutdown.
|
||||
func (h *Health) Drain() { h.draining.Store(true) }
|
||||
func (h *Health) Drain() {
|
||||
h.draining.Store(true)
|
||||
h.once.Do(func() { close(h.drained) })
|
||||
}
|
||||
|
||||
// Draining is closed once Drain is called, so long-running requests can
|
||||
// end early instead of holding up the shutdown.
|
||||
func (h *Health) Draining() <-chan struct{} { return h.drained }
|
||||
|
||||
// Register mounts /healthz (liveness) and /readyz (readiness).
|
||||
func (h *Health) Register(r gin.IRoutes) {
|
||||
|
||||
@@ -281,7 +281,7 @@ func (s *Scheduler) Take(ctx context.Context, instance uuid.UUID, max int, wait
|
||||
return nil, nil
|
||||
}
|
||||
// BLPOP blocks server side and ignores ctx, so wait in slices.
|
||||
first, err := s.rdb.BLPop(ctx, min(left, time.Second), q).Result()
|
||||
first, err := s.blpop(ctx, min(left, time.Second), q)
|
||||
if errors.Is(err, redis.Nil) {
|
||||
continue
|
||||
}
|
||||
@@ -306,6 +306,15 @@ func (s *Scheduler) Take(ctx context.Context, instance uuid.UUID, max int, wait
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// blpop is BLPOP with a timeout below a second, which go-redis would round
|
||||
// up to one (Redis takes fractions of seconds since 6.0).
|
||||
func (s *Scheduler) blpop(ctx context.Context, timeout time.Duration, key string) ([]string, error) {
|
||||
if timeout >= time.Second {
|
||||
return s.rdb.BLPop(ctx, timeout, key).Result()
|
||||
}
|
||||
return s.rdb.Do(ctx, "BLPOP", key, strconv.FormatFloat(timeout.Seconds(), 'f', 3, 64)).StringSlice()
|
||||
}
|
||||
|
||||
// Release returns instance's queued runs to its region and forgets it.
|
||||
func (s *Scheduler) Release(ctx context.Context, region string, instance uuid.UUID) error {
|
||||
// Marking the instance stale lets the dispatch script do the handover,
|
||||
|
||||
@@ -188,11 +188,26 @@ func TestTakeWaits(t *testing.T) {
|
||||
if err != nil || len(got) != 0 {
|
||||
t.Fatalf("Take() on empty queue = %v, %v", got, err)
|
||||
}
|
||||
if waited := time.Since(start); waited < 250*time.Millisecond {
|
||||
// Not rounded up to the second that BLPOP counts in.
|
||||
if waited := time.Since(start); waited < 250*time.Millisecond || waited > 800*time.Millisecond {
|
||||
t.Errorf("Take() returned after %v, want it to wait about 300ms", waited)
|
||||
}
|
||||
}
|
||||
|
||||
func TestTakeGetsAJobDuringAShortWait(t *testing.T) {
|
||||
s, _ := newTest(t)
|
||||
ctx := context.Background()
|
||||
in, monitor := uuid.New(), uuid.New()
|
||||
go func() {
|
||||
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)
|
||||
if err != nil || len(got) != 1 || got[0].MonitorID != monitor {
|
||||
t.Fatalf("Take() = %v, %v; want the job pushed while waiting", got, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestTakeReturnsWhenCancelled(t *testing.T) {
|
||||
s, _ := newTest(t)
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
|
||||
@@ -0,0 +1,416 @@
|
||||
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
|
||||
)
|
||||
|
||||
// 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) == 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:
|
||||
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),
|
||||
})
|
||||
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)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -35,14 +35,35 @@ import (
|
||||
const (
|
||||
// freshFor is how long a snapshot is used without asking the API.
|
||||
freshFor = 30 * time.Second
|
||||
// staleNoticeAfter is when visitors are told the state may be outdated.
|
||||
staleNoticeAfter = 5 * time.Minute
|
||||
refreshInterval = 30 * time.Second
|
||||
// refreshInterval is how often pages visited within recentFor are
|
||||
// refreshed.
|
||||
refreshInterval = 30 * time.Second
|
||||
recentFor = 10 * time.Minute
|
||||
// syncInterval is how often every page the API lists is fetched, so
|
||||
// each one is cached before its first visit.
|
||||
syncInterval = 5 * time.Minute
|
||||
// staleNoticeAfter is when visitors are told the state may be outdated;
|
||||
// a page nobody visited is up to syncInterval old.
|
||||
staleNoticeAfter = 2 * syncInterval
|
||||
// missFor is how long a host or slug without a page is answered
|
||||
// without asking the API again.
|
||||
missFor = time.Minute
|
||||
maxMissing = 10_000
|
||||
// refreshTimeout bounds fetching one page.
|
||||
refreshTimeout = 30 * time.Second
|
||||
// unknownPerSecond bounds the lookups of hosts and slugs that are
|
||||
// neither cached nor known to be missing, so a flood of made-up names
|
||||
// is not passed on to the API. Every page the API lists is cached by
|
||||
// the sync, so known pages are not affected.
|
||||
unknownPerSecond = 20
|
||||
)
|
||||
|
||||
// Source fetches snapshots; *agentapi.Client implements it.
|
||||
type Source interface {
|
||||
Page(ctx context.Context, host, slug string) (agentapi.PageSnapshot, error)
|
||||
// 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)
|
||||
}
|
||||
|
||||
// Server renders pages for one status page agent.
|
||||
@@ -60,6 +81,18 @@ type Server struct {
|
||||
mu sync.Mutex
|
||||
cache map[string]entry
|
||||
refreshing map[string]bool
|
||||
// again holds pages that changed while being refreshed, which are
|
||||
// fetched once more.
|
||||
again map[string]bool
|
||||
// visited holds when each cached page was last visited.
|
||||
visited map[string]time.Time
|
||||
// missing holds when a key was last found to have no page.
|
||||
missing map[string]time.Time
|
||||
// unknownSecond and unknownCount count lookups passed on to the API in
|
||||
// the current second.
|
||||
unknownSecond int64
|
||||
unknownCount int
|
||||
limits limiters
|
||||
// background tracks refreshes started by visits.
|
||||
background sync.WaitGroup
|
||||
}
|
||||
@@ -71,6 +104,9 @@ type entry struct {
|
||||
Slug string `json:"slug,omitempty"`
|
||||
Snap agentapi.PageSnapshot `json:"snapshot"`
|
||||
Fetched time.Time `json:"fetched"`
|
||||
// Checksum is the snapshot's, sent so the API can answer that nothing
|
||||
// changed instead of sending it again.
|
||||
Checksum string `json:"checksum,omitempty"`
|
||||
}
|
||||
|
||||
// Options configure a Server.
|
||||
@@ -88,7 +124,8 @@ type Options struct {
|
||||
func New(src Source, catalog *i18n.Catalog, log *slog.Logger, o Options) (*Server, error) {
|
||||
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{},
|
||||
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{}, limits: newLimiters(),
|
||||
}
|
||||
for _, h := range o.Hosts {
|
||||
s.ownHosts[strings.ToLower(h)] = true
|
||||
@@ -152,6 +189,7 @@ func (s *Server) persist(e entry) {
|
||||
func (s *Server) forget(key string) {
|
||||
s.mu.Lock()
|
||||
delete(s.cache, key)
|
||||
delete(s.visited, key)
|
||||
s.mu.Unlock()
|
||||
if s.dir != "" {
|
||||
_ = os.Remove(s.fileFor(key))
|
||||
@@ -189,53 +227,45 @@ func hostOnly(h string) string {
|
||||
}
|
||||
|
||||
func (s *Server) serve(c *gin.Context) {
|
||||
if c.Request.Method != http.MethodGet && c.Request.Method != http.MethodHead {
|
||||
host := hostOnly(c.Request.Host)
|
||||
var parts []string
|
||||
if trimmed := strings.Trim(c.Request.URL.Path, "/"); trimmed != "" {
|
||||
parts = strings.Split(trimmed, "/")
|
||||
}
|
||||
var key, slug, base string
|
||||
if s.IsCustomDomain(host) {
|
||||
key, base = "host:"+host, "/"
|
||||
} else {
|
||||
if len(parts) == 0 {
|
||||
c.Status(http.StatusNotFound)
|
||||
return
|
||||
}
|
||||
slug, parts = parts[0], parts[1:]
|
||||
key, host, base = "slug:"+slug, "", "/"+slug+"/"
|
||||
}
|
||||
rt, ok := routeOf(parts)
|
||||
if !ok {
|
||||
c.Status(http.StatusNotFound)
|
||||
return
|
||||
}
|
||||
switch m := c.Request.Method; {
|
||||
case m == http.MethodPost && rt.kind.posts():
|
||||
case m != http.MethodGet && m != http.MethodHead:
|
||||
c.Status(http.StatusMethodNotAllowed)
|
||||
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
|
||||
}
|
||||
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 {
|
||||
c.Status(http.StatusNotFound)
|
||||
return
|
||||
}
|
||||
if legal != "" {
|
||||
s.serveLegal(c, e, legal, base)
|
||||
if rt.kind == routeLegal {
|
||||
s.serveLegal(c, e, rt.arg, base)
|
||||
return
|
||||
}
|
||||
var staleSince time.Time
|
||||
@@ -249,8 +279,18 @@ 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:
|
||||
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:
|
||||
s.serveSubscription(c, e, rt.kind, host, slug, base, assets)
|
||||
return
|
||||
}
|
||||
s.localizeRequest(c)
|
||||
@@ -306,8 +346,15 @@ func (s *Server) localizeRequest(c *gin.Context) {
|
||||
// lookup answers from the cache whenever possible and refreshes in the
|
||||
// background; only unknown pages wait for the API.
|
||||
func (s *Server) lookup(ctx context.Context, key, host, slug string) (entry, bool) {
|
||||
now := s.now()
|
||||
s.mu.Lock()
|
||||
e, cached := s.cache[key]
|
||||
if cached {
|
||||
s.visited[key] = now
|
||||
} else if !s.mayAsk(key, now) {
|
||||
s.mu.Unlock()
|
||||
return entry{}, false
|
||||
}
|
||||
s.mu.Unlock()
|
||||
if cached {
|
||||
if s.now().Sub(e.Fetched) >= freshFor {
|
||||
@@ -315,14 +362,54 @@ func (s *Server) lookup(ctx context.Context, key, host, slug string) (entry, boo
|
||||
}
|
||||
return e, true
|
||||
}
|
||||
return s.fetch(ctx, key, host, slug)
|
||||
e, ok := s.fetch(ctx, key, host, slug)
|
||||
if ok {
|
||||
s.mu.Lock()
|
||||
s.visited[key] = now
|
||||
s.mu.Unlock()
|
||||
}
|
||||
return e, ok
|
||||
}
|
||||
|
||||
// mayAsk reports whether an uncached key may be looked up at the API: not
|
||||
// when it was just found missing, nor beyond unknownPerSecond. s.mu is held.
|
||||
func (s *Server) mayAsk(key string, now time.Time) bool {
|
||||
if t, ok := s.missing[key]; ok && now.Sub(t) < missFor {
|
||||
return false
|
||||
}
|
||||
if sec := now.Unix(); sec != s.unknownSecond {
|
||||
s.unknownSecond, s.unknownCount = sec, 0
|
||||
}
|
||||
if s.unknownCount >= unknownPerSecond {
|
||||
return false
|
||||
}
|
||||
s.unknownCount++
|
||||
return true
|
||||
}
|
||||
|
||||
func (s *Server) fetch(ctx context.Context, key, host, slug string) (entry, bool) {
|
||||
snap, err := s.src.Page(ctx, host, slug)
|
||||
s.mu.Lock()
|
||||
old, known := s.cache[key]
|
||||
s.mu.Unlock()
|
||||
snap, err := s.src.PageIfChanged(ctx, host, slug, old.Checksum)
|
||||
switch {
|
||||
case errors.Is(err, agentapi.ErrNotModified) && known:
|
||||
// Unchanged: the copy is current as of now.
|
||||
old.Fetched = s.now()
|
||||
old.Snap.GeneratedAt = old.Fetched
|
||||
s.mu.Lock()
|
||||
s.cache[key] = old
|
||||
s.mu.Unlock()
|
||||
s.persist(old)
|
||||
return old, true
|
||||
case errors.Is(err, agentapi.ErrNotFound):
|
||||
s.forget(key)
|
||||
s.mu.Lock()
|
||||
if len(s.missing) >= maxMissing {
|
||||
clear(s.missing)
|
||||
}
|
||||
s.missing[key] = s.now()
|
||||
s.mu.Unlock()
|
||||
return entry{}, false
|
||||
case err != nil:
|
||||
s.log.WarnContext(ctx, "fetching status page failed", "page", key, "error", err)
|
||||
@@ -331,15 +418,17 @@ func (s *Server) fetch(ctx context.Context, key, host, slug string) (entry, bool
|
||||
s.mu.Unlock()
|
||||
return e, ok
|
||||
}
|
||||
e := entry{Key: key, Host: host, Slug: slug, Snap: snap, Fetched: s.now()}
|
||||
e := entry{Key: key, Host: host, Slug: slug, Snap: snap, Fetched: s.now(), Checksum: snap.Checksum()}
|
||||
s.mu.Lock()
|
||||
s.cache[key] = e
|
||||
delete(s.missing, key)
|
||||
s.mu.Unlock()
|
||||
s.persist(e)
|
||||
return e, true
|
||||
}
|
||||
|
||||
// refresh fetches key unless another refresh of it is running.
|
||||
// refresh fetches key unless another refresh of it is running, and once
|
||||
// more if it changed meanwhile.
|
||||
func (s *Server) refresh(ctx context.Context, key, host, slug string) {
|
||||
s.mu.Lock()
|
||||
if s.refreshing[key] {
|
||||
@@ -348,38 +437,113 @@ func (s *Server) refresh(ctx context.Context, key, host, slug string) {
|
||||
}
|
||||
s.refreshing[key] = true
|
||||
s.mu.Unlock()
|
||||
defer func() {
|
||||
for {
|
||||
fctx, cancel := context.WithTimeout(ctx, refreshTimeout)
|
||||
s.fetch(fctx, key, host, slug)
|
||||
cancel()
|
||||
s.mu.Lock()
|
||||
delete(s.refreshing, key)
|
||||
again := s.again[key] && ctx.Err() == nil
|
||||
delete(s.again, key)
|
||||
if !again {
|
||||
delete(s.refreshing, key)
|
||||
s.mu.Unlock()
|
||||
return
|
||||
}
|
||||
s.mu.Unlock()
|
||||
}()
|
||||
ctx, cancel := context.WithTimeout(ctx, 15*time.Second)
|
||||
defer cancel()
|
||||
s.fetch(ctx, key, host, slug)
|
||||
}
|
||||
}
|
||||
|
||||
// OnEvent handles the events the API sends over its stream: pages that
|
||||
// changed are fetched at once instead of on their next refresh.
|
||||
func (s *Server) OnEvent(event string, body []byte) {
|
||||
if event != agentapi.EventPages {
|
||||
return
|
||||
}
|
||||
var ev agentapi.PagesEvent
|
||||
if err := json.Unmarshal(body, &ev); err != nil {
|
||||
s.log.Warn("ignoring unreadable event", "event", event, "error", err)
|
||||
return
|
||||
}
|
||||
for _, r := range ev.Pages {
|
||||
s.changed("slug:"+r.Slug, "", r.Slug)
|
||||
if r.Host != "" {
|
||||
s.changed("host:"+r.Host, r.Host, "")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (s *Server) changed(key, host, slug string) {
|
||||
s.mu.Lock()
|
||||
if s.refreshing[key] {
|
||||
s.again[key] = true
|
||||
s.mu.Unlock()
|
||||
return
|
||||
}
|
||||
s.mu.Unlock()
|
||||
s.background.Go(func() { s.refresh(context.Background(), key, host, slug) })
|
||||
}
|
||||
|
||||
// Wait returns once the background refreshes started by visits are done.
|
||||
func (s *Server) Wait() { s.background.Wait() }
|
||||
|
||||
// Run keeps every known page fresh until ctx ends, so pages stay current
|
||||
// even without visitors and the cache is warm when the API goes away.
|
||||
// Run keeps pages fresh until ctx ends: every page the API lists every
|
||||
// syncInterval, so all are cached before their first visit and survive an
|
||||
// outage of the API, and recently visited ones every refreshInterval.
|
||||
func (s *Server) Run(ctx context.Context) {
|
||||
tick := time.NewTicker(refreshInterval)
|
||||
defer tick.Stop()
|
||||
refresh := time.NewTicker(refreshInterval)
|
||||
defer refresh.Stop()
|
||||
listAll := time.NewTicker(syncInterval)
|
||||
defer listAll.Stop()
|
||||
s.Sync(ctx)
|
||||
for {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return
|
||||
case <-tick.C:
|
||||
case <-listAll.C:
|
||||
s.Sync(ctx)
|
||||
case <-refresh.C:
|
||||
s.mu.Lock()
|
||||
entries := make([]entry, 0, len(s.cache))
|
||||
for _, e := range s.cache {
|
||||
entries = append(entries, e)
|
||||
var recent []entry
|
||||
for key, e := range s.cache {
|
||||
if s.now().Sub(s.visited[key]) < recentFor {
|
||||
recent = append(recent, e)
|
||||
}
|
||||
}
|
||||
s.mu.Unlock()
|
||||
for _, e := range entries {
|
||||
for _, e := range recent {
|
||||
s.refresh(ctx, e.Key, e.Host, e.Slug)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Sync fetches every page the API lists and every cached one, which drops
|
||||
// those the API no longer serves. While the API is unreachable the cache
|
||||
// stays as it is.
|
||||
func (s *Server) Sync(ctx context.Context) {
|
||||
ctx, cancel := context.WithTimeout(ctx, syncInterval)
|
||||
defer cancel()
|
||||
refs, err := s.src.Pages(ctx)
|
||||
if err != nil {
|
||||
s.log.WarnContext(ctx, "listing status pages failed", "error", err)
|
||||
return
|
||||
}
|
||||
todo := map[string]entry{}
|
||||
s.mu.Lock()
|
||||
for key, e := range s.cache {
|
||||
todo[key] = e
|
||||
}
|
||||
s.mu.Unlock()
|
||||
for _, r := range refs {
|
||||
todo["slug:"+r.Slug] = entry{Key: "slug:" + r.Slug, Slug: r.Slug}
|
||||
if r.Host != "" {
|
||||
todo["host:"+r.Host] = entry{Key: "host:" + r.Host, Host: r.Host}
|
||||
}
|
||||
}
|
||||
for _, e := range todo {
|
||||
if ctx.Err() != nil {
|
||||
return
|
||||
}
|
||||
s.refresh(ctx, e.Key, e.Host, e.Slug)
|
||||
}
|
||||
}
|
||||
@@ -20,12 +20,27 @@ import (
|
||||
type fakeSource struct {
|
||||
mu sync.Mutex
|
||||
calls int
|
||||
err error
|
||||
delay time.Duration
|
||||
pages map[string]agentapi.PageSnapshot
|
||||
// unchanged counts the answers that the page had not changed.
|
||||
unchanged int
|
||||
err error
|
||||
delay time.Duration
|
||||
pages map[string]agentapi.PageSnapshot
|
||||
}
|
||||
|
||||
func (f *fakeSource) Page(ctx context.Context, host, slug string) (agentapi.PageSnapshot, error) {
|
||||
// PageIfChanged counts calls and answers like the API, sending pages
|
||||
// only when their checksum changed.
|
||||
func (f *fakeSource) PageIfChanged(ctx context.Context, host, slug, checksum string) (agentapi.PageSnapshot, error) {
|
||||
p, err := f.page(ctx, host, slug)
|
||||
if err == nil && checksum != "" && p.Checksum() == checksum {
|
||||
f.mu.Lock()
|
||||
f.unchanged++
|
||||
f.mu.Unlock()
|
||||
return agentapi.PageSnapshot{}, agentapi.ErrNotModified
|
||||
}
|
||||
return p, err
|
||||
}
|
||||
|
||||
func (f *fakeSource) page(ctx context.Context, host, slug string) (agentapi.PageSnapshot, error) {
|
||||
f.mu.Lock()
|
||||
f.calls++
|
||||
err, delay, p, ok := f.err, f.delay, f.pages[host+"|"+slug], false
|
||||
@@ -49,6 +64,21 @@ func (f *fakeSource) Page(ctx context.Context, host, slug string) (agentapi.Page
|
||||
return p, nil
|
||||
}
|
||||
|
||||
// Pages lists the fake's pages by their keys: "host|" or "|slug".
|
||||
func (f *fakeSource) Pages(context.Context) ([]agentapi.PageRef, error) {
|
||||
f.mu.Lock()
|
||||
defer f.mu.Unlock()
|
||||
if f.err != nil {
|
||||
return nil, f.err
|
||||
}
|
||||
var out []agentapi.PageRef
|
||||
for k := range f.pages {
|
||||
host, slug, _ := strings.Cut(k, "|")
|
||||
out = append(out, agentapi.PageRef{Host: host, Slug: slug})
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
func (f *fakeSource) set(fn func(*fakeSource)) {
|
||||
f.mu.Lock()
|
||||
defer f.mu.Unlock()
|
||||
@@ -464,3 +494,96 @@ func TestNestedGroupsAndComponentDetails(t *testing.T) {
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
func TestSyncCachesPagesBeforeTheirFirstVisit(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
now := time.Now()
|
||||
src := newSource()
|
||||
h := newHarness(t, src, dir, &now)
|
||||
h.srv.Sync(context.Background())
|
||||
|
||||
// Nobody visited them, yet both survive an outage and a restart.
|
||||
now = now.Add(syncInterval)
|
||||
restarted := newHarness(t, &fakeSource{err: errors.New("down")}, dir, &now)
|
||||
if code, body := restarted.get("status.example.test", "/acme"); code != 200 || !strings.Contains(body, "Acme status") || strings.Contains(body, "Live-Aktualisierung") {
|
||||
t.Errorf("GET of a synced page with the API down = %d, want it without stale notice", code)
|
||||
}
|
||||
if code, body := restarted.get("status.acme.test", "/"); code != 200 || !strings.Contains(body, "Acme on own domain") {
|
||||
t.Errorf("GET of a synced custom domain with the API down = %d", code)
|
||||
}
|
||||
restarted.srv.Sync(context.Background())
|
||||
if code, _ := restarted.get("status.example.test", "/acme"); code != 200 {
|
||||
t.Errorf("a failed sync dropped the cache: %d", code)
|
||||
}
|
||||
|
||||
// A page the API no longer lists is dropped by the next sync.
|
||||
src.set(func(f *fakeSource) { delete(f.pages, "|acme") })
|
||||
h.srv.Sync(context.Background())
|
||||
if code, _ := h.get("status.example.test", "/acme"); code != 404 {
|
||||
t.Errorf("GET after the page left the list = %d, want 404", code)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRefreshSkipsUnchangedPages(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
now := time.Now()
|
||||
src := newSource()
|
||||
h := newHarness(t, src, dir, &now)
|
||||
h.srv.Sync(context.Background())
|
||||
now = now.Add(syncInterval)
|
||||
h.srv.Sync(context.Background())
|
||||
src.mu.Lock()
|
||||
unchanged := src.unchanged
|
||||
src.mu.Unlock()
|
||||
if unchanged != 2 {
|
||||
t.Errorf("unchanged answers on the second sync = %d, want 2", unchanged)
|
||||
}
|
||||
if _, body := h.get("status.example.test", "/acme"); !strings.Contains(body, "Acme status") || strings.Contains(body, "Live-Aktualisierung") {
|
||||
t.Error("an unchanged page is not served as current")
|
||||
}
|
||||
|
||||
// A changed page is sent again, and the checksum survives a restart.
|
||||
src.set(func(f *fakeSource) {
|
||||
f.pages["|acme"] = agentapi.PageSnapshot{Title: "Renamed", Status: agentapi.PageOperational}
|
||||
})
|
||||
restarted := newHarness(t, src, dir, &now)
|
||||
restarted.srv.Sync(context.Background())
|
||||
src.mu.Lock()
|
||||
unchanged = src.unchanged
|
||||
src.mu.Unlock()
|
||||
if _, body := restarted.get("status.example.test", "/acme"); !strings.Contains(body, "Renamed") || unchanged != 3 {
|
||||
t.Errorf("after a change: renamed %t, unchanged answers %d, want 3", strings.Contains(body, "Renamed"), unchanged)
|
||||
}
|
||||
}
|
||||
|
||||
// Pages the API says changed are fetched at once, and once more when they
|
||||
// change during that fetch.
|
||||
func TestEventsRefreshPagesAtOnce(t *testing.T) {
|
||||
now := time.Now()
|
||||
src := newSource()
|
||||
h := newHarness(t, src, t.TempDir(), &now)
|
||||
if code, body := h.get("status.example.test", "/acme"); code != 200 || !strings.Contains(body, "Acme status") {
|
||||
t.Fatalf("first GET = %d", code)
|
||||
}
|
||||
src.set(func(f *fakeSource) {
|
||||
f.pages["|acme"] = agentapi.PageSnapshot{Title: "Acme renamed", Status: agentapi.PageOperational}
|
||||
f.delay = 200 * time.Millisecond
|
||||
f.calls = 0
|
||||
})
|
||||
event := []byte(`{"pages":[{"slug":"acme"}]}`)
|
||||
h.srv.OnEvent(agentapi.EventPages, event)
|
||||
time.Sleep(50 * time.Millisecond)
|
||||
// Arrives while the first fetch runs.
|
||||
h.srv.OnEvent(agentapi.EventPages, event)
|
||||
h.srv.OnEvent("unknown", nil)
|
||||
h.srv.Wait()
|
||||
if _, body := h.get("status.example.test", "/acme"); !strings.Contains(body, "Acme renamed") {
|
||||
t.Error("page not refreshed after the event")
|
||||
}
|
||||
src.mu.Lock()
|
||||
calls := src.calls
|
||||
src.mu.Unlock()
|
||||
if calls != 2 {
|
||||
t.Errorf("fetches = %d, want 2: one for the event, one for the change during it", calls)
|
||||
}
|
||||
}
|
||||
@@ -151,6 +151,40 @@ func (s CertStorage) Unlock(ctx context.Context, name string) error {
|
||||
return s.c.StorageUnlock(ctx, name)
|
||||
}
|
||||
|
||||
// CertificateGate is asked before a new certificate is ordered;
|
||||
// *agentapi.Client implements it.
|
||||
type CertificateGate interface {
|
||||
AllowCertificate(ctx context.Context, name string) error
|
||||
}
|
||||
|
||||
// OnCertEvent is certmagic's event hook. Before a new certificate for a
|
||||
// custom domain is ordered it asks the API, which allows verified domains
|
||||
// of pages this server serves within limits shared by all servers; that
|
||||
// keeps the CA's rate limits from being used up. Renewals and the default
|
||||
// hosts are not asked about.
|
||||
func (s *Server) OnCertEvent(ctx context.Context, event string, data map[string]any) error {
|
||||
if event != "cert_obtaining" || data["renewal"] == true {
|
||||
return nil
|
||||
}
|
||||
name, _ := data["identifier"].(string)
|
||||
host := hostOnly(name)
|
||||
gate, ok := s.src.(CertificateGate)
|
||||
if s.ownHosts[host] || !ok {
|
||||
return nil
|
||||
}
|
||||
switch err := gate.AllowCertificate(ctx, host); {
|
||||
case err == nil:
|
||||
return nil
|
||||
case errors.Is(err, agentapi.ErrRateLimited):
|
||||
s.log.WarnContext(ctx, "certificate order refused: limit reached", "domain", host)
|
||||
return fmt.Errorf("limit on new certificates reached for %s", host)
|
||||
case errors.Is(err, agentapi.ErrNotFound):
|
||||
return fmt.Errorf("no status page for %s", host)
|
||||
default:
|
||||
return fmt.Errorf("asking whether to order a certificate for %s: %w", host, err)
|
||||
}
|
||||
}
|
||||
|
||||
// AllowCertificate decides whether to obtain a certificate for name on
|
||||
// demand: only for the default hosts and for verified custom domains of
|
||||
// pages this server may serve. Anything else would let strangers make us
|
||||
|
||||
@@ -0,0 +1,115 @@
|
||||
package statuspage
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"git.zb-server.de/ZB-Server/uptimesebi/internal/agentapi"
|
||||
)
|
||||
|
||||
func (f *fakeSource) callCount() int {
|
||||
f.mu.Lock()
|
||||
defer f.mu.Unlock()
|
||||
return f.calls
|
||||
}
|
||||
|
||||
func TestUnknownNamesAreNotAskedAgainAtOnce(t *testing.T) {
|
||||
now := time.Now()
|
||||
src := newSource()
|
||||
h := newHarness(t, src, "", &now)
|
||||
for range 3 {
|
||||
if code, _ := h.get("nope.example.test", "/"); code != http.StatusNotFound {
|
||||
t.Fatalf("unknown host = %d, want 404", code)
|
||||
}
|
||||
}
|
||||
if n := src.callCount(); n != 1 {
|
||||
t.Errorf("the API was asked %d times about one unknown host, want 1", n)
|
||||
}
|
||||
now = now.Add(missFor)
|
||||
h.get("nope.example.test", "/")
|
||||
if n := src.callCount(); n != 2 {
|
||||
t.Errorf("after %v the API was asked %d times in all, want 2", missFor, n)
|
||||
}
|
||||
h.srv.mu.Lock()
|
||||
visited := len(h.srv.visited)
|
||||
h.srv.mu.Unlock()
|
||||
if visited != 0 {
|
||||
t.Errorf("unknown hosts were recorded as visited pages: %d", visited)
|
||||
}
|
||||
}
|
||||
|
||||
func TestFloodOfMadeUpNamesIsThrottled(t *testing.T) {
|
||||
now := time.Now()
|
||||
src := newSource()
|
||||
h := newHarness(t, src, "", &now)
|
||||
h.srv.Sync(context.Background())
|
||||
before := src.callCount()
|
||||
for i := range 200 {
|
||||
h.get(fmt.Sprintf("x%d.example.test", i), "/")
|
||||
}
|
||||
if n := src.callCount() - before; n > unknownPerSecond {
|
||||
t.Errorf("a flood of made-up hosts reached the API %d times in one second, want at most %d", n, unknownPerSecond)
|
||||
}
|
||||
// Pages the sync cached are still served during the flood.
|
||||
if code, _ := h.get("status.acme.test", "/"); code != http.StatusOK {
|
||||
t.Errorf("a known page during the flood = %d, want 200", code)
|
||||
}
|
||||
now = now.Add(time.Second)
|
||||
if err := h.srv.AllowCertificate(context.Background(), "status.acme.test"); err != nil {
|
||||
t.Errorf("a known custom domain after the flood: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
type gatedSource struct {
|
||||
*fakeSource
|
||||
asked []string
|
||||
err error
|
||||
}
|
||||
|
||||
func (g *gatedSource) AllowCertificate(_ context.Context, name string) error {
|
||||
g.asked = append(g.asked, name)
|
||||
return g.err
|
||||
}
|
||||
|
||||
func TestNewCertificatesAreOrderedOnlyWhenTheAPIAllows(t *testing.T) {
|
||||
now := time.Now()
|
||||
g := &gatedSource{fakeSource: newSource()}
|
||||
h := newHarness(t, g.fakeSource, "", &now)
|
||||
h.srv.src = g
|
||||
ctx := context.Background()
|
||||
obtain := func(name string, renewal bool) error {
|
||||
data := map[string]any{"identifier": name}
|
||||
if renewal {
|
||||
data["renewal"] = true
|
||||
}
|
||||
return h.srv.OnCertEvent(ctx, "cert_obtaining", data)
|
||||
}
|
||||
|
||||
if err := obtain("status.acme.test", false); err != nil {
|
||||
t.Errorf("allowed order: %v", err)
|
||||
}
|
||||
// Renewals, the default hosts and other events are not asked about.
|
||||
if err := obtain("status.acme.test", true); err != nil {
|
||||
t.Errorf("renewal: %v", err)
|
||||
}
|
||||
if err := obtain("status.example.test", false); err != nil {
|
||||
t.Errorf("default host: %v", err)
|
||||
}
|
||||
if err := h.srv.OnCertEvent(ctx, "cert_obtained", map[string]any{"identifier": "status.acme.test"}); err != nil {
|
||||
t.Errorf("other event: %v", err)
|
||||
}
|
||||
if len(g.asked) != 1 || g.asked[0] != "status.acme.test" {
|
||||
t.Errorf("asked about %v, want only the new order", g.asked)
|
||||
}
|
||||
|
||||
for _, refuse := range []error{agentapi.ErrRateLimited, agentapi.ErrNotFound, errors.New("api down")} {
|
||||
g.err = refuse
|
||||
if err := obtain("status.acme.test", false); err == nil {
|
||||
t.Errorf("order went ahead although the API answered %v", refuse)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -318,6 +318,92 @@ func (q *Queries) ListVisibleRegions(ctx context.Context) ([]Region, error) {
|
||||
return items, nil
|
||||
}
|
||||
|
||||
const orgOwnerEmails = `-- name: OrgOwnerEmails :many
|
||||
SELECT u.email FROM memberships m JOIN users u ON u.id = m.user_id
|
||||
WHERE m.org_id = $1 AND m.is_owner AND u.disabled_at IS NULL
|
||||
`
|
||||
|
||||
// System scope.
|
||||
func (q *Queries) OrgOwnerEmails(ctx context.Context, orgID uuid.UUID) ([]string, error) {
|
||||
rows, err := q.db.Query(ctx, orgOwnerEmails, orgID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
items := []string{}
|
||||
for rows.Next() {
|
||||
var email string
|
||||
if err := rows.Scan(&email); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
items = append(items, email)
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return items, nil
|
||||
}
|
||||
|
||||
const orgServesOwnPages = `-- name: OrgServesOwnPages :one
|
||||
SELECT EXISTS (
|
||||
SELECT 1 FROM agents
|
||||
WHERE org_id = $1 AND kind = 'statuspage' AND last_seen_at IS NOT NULL
|
||||
)
|
||||
`
|
||||
|
||||
// An organization serves its status pages itself once one of its own
|
||||
// status page servers has connected.
|
||||
func (q *Queries) OrgServesOwnPages(ctx context.Context, orgID *uuid.UUID) (bool, error) {
|
||||
row := q.db.QueryRow(ctx, orgServesOwnPages, orgID)
|
||||
var exists bool
|
||||
err := row.Scan(&exists)
|
||||
return exists, err
|
||||
}
|
||||
|
||||
const regionsToWatch = `-- name: RegionsToWatch :many
|
||||
SELECT r.id, r.name, r.org_id, o.name AS org_name
|
||||
FROM regions r
|
||||
LEFT JOIN orgs o ON o.id = r.org_id
|
||||
WHERE EXISTS (SELECT 1 FROM agents a WHERE a.kind = 'checker' AND a.region_id = r.id)
|
||||
AND EXISTS (SELECT 1 FROM monitor_regions mr JOIN monitors m ON m.id = mr.monitor_id
|
||||
WHERE mr.region_id = r.id AND m.enabled)
|
||||
ORDER BY r.name
|
||||
`
|
||||
|
||||
type RegionsToWatchRow struct {
|
||||
ID uuid.UUID
|
||||
Name string
|
||||
OrgID *uuid.UUID
|
||||
OrgName *string
|
||||
}
|
||||
|
||||
// System scope: regions that have checkers and enabled monitors, so a
|
||||
// region without a live checker leaves monitors unchecked.
|
||||
func (q *Queries) RegionsToWatch(ctx context.Context) ([]RegionsToWatchRow, error) {
|
||||
rows, err := q.db.Query(ctx, regionsToWatch)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
items := []RegionsToWatchRow{}
|
||||
for rows.Next() {
|
||||
var i RegionsToWatchRow
|
||||
if err := rows.Scan(
|
||||
&i.ID,
|
||||
&i.Name,
|
||||
&i.OrgID,
|
||||
&i.OrgName,
|
||||
); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
items = append(items, i)
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return items, nil
|
||||
}
|
||||
|
||||
const setAgentAllowPrivate = `-- name: SetAgentAllowPrivate :execrows
|
||||
UPDATE agents SET allow_private = $1
|
||||
WHERE id = $2 AND kind = 'checker' AND org_id = $3
|
||||
|
||||
@@ -124,22 +124,65 @@ 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
|
||||
WHERE org_id = $1
|
||||
WHERE org_id = $1 AND monitor_id = $2
|
||||
GROUP BY 1, 2
|
||||
`
|
||||
|
||||
type FirstDataDailyParams struct {
|
||||
OrgID uuid.UUID
|
||||
MonitorID uuid.UUID
|
||||
}
|
||||
|
||||
type FirstDataDailyRow struct {
|
||||
MonitorID uuid.UUID
|
||||
Region string
|
||||
First time.Time
|
||||
}
|
||||
|
||||
// When each monitor and region first reported, to the day.
|
||||
func (q *Queries) FirstDataDaily(ctx context.Context, orgID uuid.UUID) ([]FirstDataDailyRow, error) {
|
||||
rows, err := q.db.Query(ctx, firstDataDaily, orgID)
|
||||
// When each region of a monitor first reported, to the day.
|
||||
func (q *Queries) FirstDataDaily(ctx context.Context, arg FirstDataDailyParams) ([]FirstDataDailyRow, error) {
|
||||
rows, err := q.db.Query(ctx, firstDataDaily, arg.OrgID, arg.MonitorID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -161,13 +204,14 @@ func (q *Queries) FirstDataDaily(ctx context.Context, orgID uuid.UUID) ([]FirstD
|
||||
const firstDataRecent = `-- name: FirstDataRecent :many
|
||||
SELECT monitor_id, region, min(time)::timestamptz AS first
|
||||
FROM check_results
|
||||
WHERE org_id = $1 AND time >= $2
|
||||
WHERE org_id = $1 AND monitor_id = $2 AND time >= $3
|
||||
GROUP BY 1, 2
|
||||
`
|
||||
|
||||
type FirstDataRecentParams struct {
|
||||
OrgID uuid.UUID
|
||||
Time time.Time
|
||||
OrgID uuid.UUID
|
||||
MonitorID uuid.UUID
|
||||
Time time.Time
|
||||
}
|
||||
|
||||
type FirstDataRecentRow struct {
|
||||
@@ -176,10 +220,10 @@ type FirstDataRecentRow struct {
|
||||
First time.Time
|
||||
}
|
||||
|
||||
// When each monitor and region first reported since $2, exactly. Used for
|
||||
// When each region of a monitor first reported since $3, exactly. Used for
|
||||
// data younger than the daily aggregate's resolution.
|
||||
func (q *Queries) FirstDataRecent(ctx context.Context, arg FirstDataRecentParams) ([]FirstDataRecentRow, error) {
|
||||
rows, err := q.db.Query(ctx, firstDataRecent, arg.OrgID, arg.Time)
|
||||
rows, err := q.db.Query(ctx, firstDataRecent, arg.OrgID, arg.MonitorID, arg.Time)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -203,6 +247,7 @@ SELECT monitor_id, bucket::timestamptz AS bucket, sum(total)::bigint AS total, s
|
||||
coalesce(sum(avg_latency_ms * total) / nullif(sum(total), 0), 0)::real AS avg_latency_ms
|
||||
FROM check_results_1h
|
||||
WHERE org_id = $1 AND bucket >= $2
|
||||
AND ($3::uuid[] IS NULL OR monitor_id = ANY ($3::uuid[]))
|
||||
GROUP BY monitor_id, bucket
|
||||
ORDER BY monitor_id, bucket
|
||||
`
|
||||
@@ -210,6 +255,7 @@ ORDER BY monitor_id, bucket
|
||||
type HourlyBucketsParams struct {
|
||||
OrgID uuid.UUID
|
||||
Bucket interface{}
|
||||
Ids []uuid.UUID
|
||||
}
|
||||
|
||||
type HourlyBucketsRow struct {
|
||||
@@ -222,7 +268,7 @@ type HourlyBucketsRow struct {
|
||||
|
||||
// Per monitor and hour since $2, across all regions.
|
||||
func (q *Queries) HourlyBuckets(ctx context.Context, arg HourlyBucketsParams) ([]HourlyBucketsRow, error) {
|
||||
rows, err := q.db.Query(ctx, hourlyBuckets, arg.OrgID, arg.Bucket)
|
||||
rows, err := q.db.Query(ctx, hourlyBuckets, arg.OrgID, arg.Bucket, arg.Ids)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -259,52 +305,6 @@ type InsertCheckResultsParams struct {
|
||||
Error *string
|
||||
}
|
||||
|
||||
const latestResults = `-- name: LatestResults :many
|
||||
SELECT DISTINCT ON (monitor_id, region) monitor_id, region, time, ok, latency_ms, status_code, error
|
||||
FROM check_results
|
||||
WHERE org_id = $1 AND time > now() - interval '1 day'
|
||||
ORDER BY monitor_id, region, time DESC
|
||||
`
|
||||
|
||||
type LatestResultsRow struct {
|
||||
MonitorID uuid.UUID
|
||||
Region string
|
||||
Time time.Time
|
||||
Ok bool
|
||||
LatencyMs *int32
|
||||
StatusCode *int32
|
||||
Error *string
|
||||
}
|
||||
|
||||
// Newest result per monitor and region in the org.
|
||||
func (q *Queries) LatestResults(ctx context.Context, orgID uuid.UUID) ([]LatestResultsRow, error) {
|
||||
rows, err := q.db.Query(ctx, latestResults, orgID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
items := []LatestResultsRow{}
|
||||
for rows.Next() {
|
||||
var i LatestResultsRow
|
||||
if err := rows.Scan(
|
||||
&i.MonitorID,
|
||||
&i.Region,
|
||||
&i.Time,
|
||||
&i.Ok,
|
||||
&i.LatencyMs,
|
||||
&i.StatusCode,
|
||||
&i.Error,
|
||||
); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
items = append(items, i)
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return items, nil
|
||||
}
|
||||
|
||||
const latestResultsForMonitor = `-- name: LatestResultsForMonitor :many
|
||||
SELECT DISTINCT ON (region) region, ok, error
|
||||
FROM check_results
|
||||
@@ -425,16 +425,16 @@ SELECT monitor_id, time_bucket($2::text::interval, time)::timestamptz AS bucket,
|
||||
coalesce(avg(latency_ms), 0)::real AS avg_latency_ms
|
||||
FROM check_results
|
||||
WHERE org_id = $1 AND time >= $3
|
||||
AND ($4::uuid IS NULL OR monitor_id = $4)
|
||||
AND monitor_id = ANY ($4::uuid[])
|
||||
GROUP BY 1, 2
|
||||
ORDER BY 1, 2
|
||||
`
|
||||
|
||||
type RangeBucketsParams struct {
|
||||
OrgID uuid.UUID
|
||||
Width string
|
||||
Since time.Time
|
||||
MonitorID *uuid.UUID
|
||||
OrgID uuid.UUID
|
||||
Width string
|
||||
Since time.Time
|
||||
Ids []uuid.UUID
|
||||
}
|
||||
|
||||
type RangeBucketsRow struct {
|
||||
@@ -451,7 +451,7 @@ func (q *Queries) RangeBuckets(ctx context.Context, arg RangeBucketsParams) ([]R
|
||||
arg.OrgID,
|
||||
arg.Width,
|
||||
arg.Since,
|
||||
arg.MonitorID,
|
||||
arg.Ids,
|
||||
)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
@@ -483,16 +483,16 @@ SELECT monitor_id, time_bucket($2::text::interval, bucket)::timestamptz AS bucke
|
||||
coalesce(sum(avg_latency_ms * total) / nullif(sum(total), 0), 0)::real AS avg_latency_ms
|
||||
FROM check_results_1d
|
||||
WHERE org_id = $1 AND bucket >= $3
|
||||
AND ($4::uuid IS NULL OR monitor_id = $4)
|
||||
AND monitor_id = ANY ($4::uuid[])
|
||||
GROUP BY 1, 2
|
||||
ORDER BY 1, 2
|
||||
`
|
||||
|
||||
type RangeBucketsDailyParams struct {
|
||||
OrgID uuid.UUID
|
||||
Width string
|
||||
Since interface{}
|
||||
MonitorID *uuid.UUID
|
||||
OrgID uuid.UUID
|
||||
Width string
|
||||
Since interface{}
|
||||
Ids []uuid.UUID
|
||||
}
|
||||
|
||||
type RangeBucketsDailyRow struct {
|
||||
@@ -509,7 +509,7 @@ func (q *Queries) RangeBucketsDaily(ctx context.Context, arg RangeBucketsDailyPa
|
||||
arg.OrgID,
|
||||
arg.Width,
|
||||
arg.Since,
|
||||
arg.MonitorID,
|
||||
arg.Ids,
|
||||
)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
@@ -541,16 +541,16 @@ SELECT monitor_id, time_bucket($2::text::interval, bucket)::timestamptz AS bucke
|
||||
coalesce(sum(avg_latency_ms * total) / nullif(sum(total), 0), 0)::real AS avg_latency_ms
|
||||
FROM check_results_1h
|
||||
WHERE org_id = $1 AND bucket >= $3
|
||||
AND ($4::uuid IS NULL OR monitor_id = $4)
|
||||
AND monitor_id = ANY ($4::uuid[])
|
||||
GROUP BY 1, 2
|
||||
ORDER BY 1, 2
|
||||
`
|
||||
|
||||
type RangeBucketsHourlyParams struct {
|
||||
OrgID uuid.UUID
|
||||
Width string
|
||||
Since interface{}
|
||||
MonitorID *uuid.UUID
|
||||
OrgID uuid.UUID
|
||||
Width string
|
||||
Since interface{}
|
||||
Ids []uuid.UUID
|
||||
}
|
||||
|
||||
type RangeBucketsHourlyRow struct {
|
||||
@@ -567,7 +567,7 @@ func (q *Queries) RangeBucketsHourly(ctx context.Context, arg RangeBucketsHourly
|
||||
arg.OrgID,
|
||||
arg.Width,
|
||||
arg.Since,
|
||||
arg.MonitorID,
|
||||
arg.Ids,
|
||||
)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
|
||||
@@ -271,18 +271,19 @@ func (q *Queries) GetIncident(ctx context.Context, id uuid.UUID) (GetIncidentRow
|
||||
|
||||
const incidentsForMonitors = `-- name: IncidentsForMonitors :many
|
||||
SELECT id, org_id, monitor_id, started_at, resolved_at, cause, title, status, status_id FROM incidents
|
||||
WHERE monitor_id = ANY ($1::uuid[]) AND (resolved_at IS NULL OR resolved_at > $2)
|
||||
WHERE org_id = $1 AND monitor_id = ANY ($2::uuid[]) AND (resolved_at IS NULL OR resolved_at > $3)
|
||||
ORDER BY started_at DESC
|
||||
LIMIT 50
|
||||
`
|
||||
|
||||
type IncidentsForMonitorsParams struct {
|
||||
OrgID uuid.UUID
|
||||
Ids []uuid.UUID
|
||||
Since *time.Time
|
||||
}
|
||||
|
||||
func (q *Queries) IncidentsForMonitors(ctx context.Context, arg IncidentsForMonitorsParams) ([]Incident, error) {
|
||||
rows, err := q.db.Query(ctx, incidentsForMonitors, arg.Ids, arg.Since)
|
||||
rows, err := q.db.Query(ctx, incidentsForMonitors, arg.OrgID, arg.Ids, arg.Since)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -313,18 +314,23 @@ func (q *Queries) IncidentsForMonitors(ctx context.Context, arg IncidentsForMoni
|
||||
|
||||
const incidentsSince = `-- name: IncidentsSince :many
|
||||
SELECT monitor_id, started_at, resolved_at FROM incidents
|
||||
WHERE resolved_at IS NULL OR resolved_at > $1
|
||||
WHERE org_id = $1 AND (resolved_at IS NULL OR resolved_at > $2)
|
||||
`
|
||||
|
||||
type IncidentsSinceParams struct {
|
||||
OrgID uuid.UUID
|
||||
ResolvedAt *time.Time
|
||||
}
|
||||
|
||||
type IncidentsSinceRow struct {
|
||||
MonitorID uuid.UUID
|
||||
StartedAt time.Time
|
||||
ResolvedAt *time.Time
|
||||
}
|
||||
|
||||
// Incidents overlapping the time since $1, for SLA calculation.
|
||||
func (q *Queries) IncidentsSince(ctx context.Context, resolvedAt *time.Time) ([]IncidentsSinceRow, error) {
|
||||
rows, err := q.db.Query(ctx, incidentsSince, resolvedAt)
|
||||
// Incidents overlapping the time since $2, for SLA calculation.
|
||||
func (q *Queries) IncidentsSince(ctx context.Context, arg IncidentsSinceParams) ([]IncidentsSinceRow, error) {
|
||||
rows, err := q.db.Query(ctx, incidentsSince, arg.OrgID, arg.ResolvedAt)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -672,11 +678,11 @@ func (q *Queries) OpenIncident(ctx context.Context, arg OpenIncidentParams) (Inc
|
||||
}
|
||||
|
||||
const openIncidents = `-- name: OpenIncidents :many
|
||||
SELECT id, org_id, monitor_id, started_at, resolved_at, cause, title, status, status_id FROM incidents WHERE resolved_at IS NULL
|
||||
SELECT id, org_id, monitor_id, started_at, resolved_at, cause, title, status, status_id FROM incidents WHERE org_id = $1 AND resolved_at IS NULL
|
||||
`
|
||||
|
||||
func (q *Queries) OpenIncidents(ctx context.Context) ([]Incident, error) {
|
||||
rows, err := q.db.Query(ctx, openIncidents)
|
||||
func (q *Queries) OpenIncidents(ctx context.Context, orgID uuid.UUID) ([]Incident, error) {
|
||||
rows, err := q.db.Query(ctx, openIncidents, orgID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
@@ -0,0 +1,190 @@
|
||||
// Code generated by sqlc. DO NOT EDIT.
|
||||
// versions:
|
||||
// sqlc v1.31.1
|
||||
// source: latest_results.sql
|
||||
|
||||
package store
|
||||
|
||||
import (
|
||||
"context"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
const latestOK = `-- name: LatestOK :many
|
||||
|
||||
SELECT monitor_id, region, ok FROM latest_results WHERE monitor_id = ANY ($1::uuid[])
|
||||
`
|
||||
|
||||
type LatestOKRow struct {
|
||||
MonitorID uuid.UUID
|
||||
Region string
|
||||
Ok bool
|
||||
}
|
||||
|
||||
// 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.
|
||||
func (q *Queries) LatestOK(ctx context.Context, ids []uuid.UUID) ([]LatestOKRow, error) {
|
||||
rows, err := q.db.Query(ctx, latestOK, ids)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
items := []LatestOKRow{}
|
||||
for rows.Next() {
|
||||
var i LatestOKRow
|
||||
if err := rows.Scan(&i.MonitorID, &i.Region, &i.Ok); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
items = append(items, i)
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return items, nil
|
||||
}
|
||||
|
||||
const latestResults = `-- name: LatestResults :many
|
||||
SELECT monitor_id, region, time, ok, latency_ms, status_code, error
|
||||
FROM latest_results
|
||||
WHERE org_id = $1 AND time > now() - interval '1 day'
|
||||
`
|
||||
|
||||
type LatestResultsRow struct {
|
||||
MonitorID uuid.UUID
|
||||
Region string
|
||||
Time time.Time
|
||||
Ok bool
|
||||
LatencyMs *int32
|
||||
StatusCode *int32
|
||||
Error *string
|
||||
}
|
||||
|
||||
// Newest result per monitor and region in the org, of the last day.
|
||||
func (q *Queries) LatestResults(ctx context.Context, orgID uuid.UUID) ([]LatestResultsRow, error) {
|
||||
rows, err := q.db.Query(ctx, latestResults, orgID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
items := []LatestResultsRow{}
|
||||
for rows.Next() {
|
||||
var i LatestResultsRow
|
||||
if err := rows.Scan(
|
||||
&i.MonitorID,
|
||||
&i.Region,
|
||||
&i.Time,
|
||||
&i.Ok,
|
||||
&i.LatencyMs,
|
||||
&i.StatusCode,
|
||||
&i.Error,
|
||||
); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
items = append(items, i)
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return items, nil
|
||||
}
|
||||
|
||||
const latestResultsForMonitors = `-- name: LatestResultsForMonitors :many
|
||||
SELECT monitor_id, region, time, ok, latency_ms, status_code, error
|
||||
FROM latest_results
|
||||
WHERE org_id = $1 AND monitor_id = ANY ($2::uuid[]) AND time > now() - interval '1 day'
|
||||
`
|
||||
|
||||
type LatestResultsForMonitorsParams struct {
|
||||
OrgID uuid.UUID
|
||||
Ids []uuid.UUID
|
||||
}
|
||||
|
||||
type LatestResultsForMonitorsRow struct {
|
||||
MonitorID uuid.UUID
|
||||
Region string
|
||||
Time time.Time
|
||||
Ok bool
|
||||
LatencyMs *int32
|
||||
StatusCode *int32
|
||||
Error *string
|
||||
}
|
||||
|
||||
// LatestResults limited to the monitors ids.
|
||||
func (q *Queries) LatestResultsForMonitors(ctx context.Context, arg LatestResultsForMonitorsParams) ([]LatestResultsForMonitorsRow, error) {
|
||||
rows, err := q.db.Query(ctx, latestResultsForMonitors, arg.OrgID, arg.Ids)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
items := []LatestResultsForMonitorsRow{}
|
||||
for rows.Next() {
|
||||
var i LatestResultsForMonitorsRow
|
||||
if err := rows.Scan(
|
||||
&i.MonitorID,
|
||||
&i.Region,
|
||||
&i.Time,
|
||||
&i.Ok,
|
||||
&i.LatencyMs,
|
||||
&i.StatusCode,
|
||||
&i.Error,
|
||||
); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
items = append(items, i)
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return items, nil
|
||||
}
|
||||
|
||||
const upsertLatestResults = `-- name: UpsertLatestResults :many
|
||||
INSERT INTO latest_results (monitor_id, region, org_id, time, ok, latency_ms, status_code, error)
|
||||
SELECT DISTINCT ON (r.monitor_id, r.region) r.monitor_id, r.region, r.org_id, r.time, r.ok, r.latency_ms, r.status_code, r.error
|
||||
FROM jsonb_to_recordset($1::jsonb)
|
||||
AS r(monitor_id uuid, region text, org_id uuid, time timestamptz, ok boolean, latency_ms integer, status_code integer, error text)
|
||||
ORDER BY r.monitor_id, r.region, r.time DESC
|
||||
ON CONFLICT (monitor_id, region) DO UPDATE
|
||||
SET org_id = excluded.org_id, time = excluded.time, ok = excluded.ok, latency_ms = excluded.latency_ms,
|
||||
status_code = excluded.status_code, error = excluded.error
|
||||
WHERE latest_results.time <= excluded.time
|
||||
RETURNING monitor_id, region, org_id, ok
|
||||
`
|
||||
|
||||
type UpsertLatestResultsRow struct {
|
||||
MonitorID uuid.UUID
|
||||
Region string
|
||||
OrgID uuid.UUID
|
||||
Ok bool
|
||||
}
|
||||
|
||||
// Keeps the newest of results, a JSON array, per monitor and
|
||||
// region; results arriving late do not replace newer ones. It returns the
|
||||
// rows it wrote.
|
||||
func (q *Queries) UpsertLatestResults(ctx context.Context, results []byte) ([]UpsertLatestResultsRow, error) {
|
||||
rows, err := q.db.Query(ctx, upsertLatestResults, results)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
items := []UpsertLatestResultsRow{}
|
||||
for rows.Next() {
|
||||
var i UpsertLatestResultsRow
|
||||
if err := rows.Scan(
|
||||
&i.MonitorID,
|
||||
&i.Region,
|
||||
&i.OrgID,
|
||||
&i.Ok,
|
||||
); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
items = append(items, i)
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return items, nil
|
||||
}
|
||||
@@ -15,6 +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_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,
|
||||
@@ -51,25 +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
|
||||
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,
|
||||
@@ -102,6 +105,8 @@ func (q *Queries) AdminListOrgs(ctx context.Context, arg AdminListOrgsParams) ([
|
||||
&i.LimitStatusPages,
|
||||
&i.LimitRegionsPerMonitor,
|
||||
&i.LimitOwnRegionsCount,
|
||||
&i.LimitMonitorsPerPage,
|
||||
&i.LimitSubscribersPerWeek,
|
||||
&i.Monitors,
|
||||
&i.StatusPages,
|
||||
&i.OwnerID,
|
||||
@@ -133,6 +138,17 @@ func (q *Queries) CountMonitors(ctx context.Context, orgID uuid.UUID) (int64, er
|
||||
return count, err
|
||||
}
|
||||
|
||||
const countStatusPageMonitors = `-- name: CountStatusPageMonitors :one
|
||||
SELECT count(*) FROM status_page_monitors WHERE page_id = $1
|
||||
`
|
||||
|
||||
func (q *Queries) CountStatusPageMonitors(ctx context.Context, pageID uuid.UUID) (int64, error) {
|
||||
row := q.db.QueryRow(ctx, countStatusPageMonitors, pageID)
|
||||
var count int64
|
||||
err := row.Scan(&count)
|
||||
return count, err
|
||||
}
|
||||
|
||||
const countStatusPages = `-- name: CountStatusPages :one
|
||||
SELECT count(*) FROM status_pages WHERE org_id = $1
|
||||
`
|
||||
@@ -157,17 +173,20 @@ 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
|
||||
WHERE id = $5
|
||||
limit_regions_per_monitor = $3, limit_own_regions_count = $4,
|
||||
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
|
||||
ID uuid.UUID
|
||||
Monitors *int32
|
||||
StatusPages *int32
|
||||
RegionsPerMonitor *int32
|
||||
OwnRegionsCount *bool
|
||||
MonitorsPerPage *int32
|
||||
SubscribersPerWeek *int32
|
||||
ID uuid.UUID
|
||||
}
|
||||
|
||||
type SetOrgLimitsRow struct {
|
||||
@@ -181,6 +200,8 @@ func (q *Queries) SetOrgLimits(ctx context.Context, arg SetOrgLimitsParams) (Set
|
||||
arg.StatusPages,
|
||||
arg.RegionsPerMonitor,
|
||||
arg.OwnRegionsCount,
|
||||
arg.MonitorsPerPage,
|
||||
arg.SubscribersPerWeek,
|
||||
arg.ID,
|
||||
)
|
||||
var i SetOrgLimitsRow
|
||||
|
||||
+60
-15
@@ -197,6 +197,17 @@ type Invitation struct {
|
||||
CreatedAt time.Time
|
||||
}
|
||||
|
||||
type LatestResult struct {
|
||||
MonitorID uuid.UUID
|
||||
Region string
|
||||
OrgID uuid.UUID
|
||||
Time time.Time
|
||||
Ok bool
|
||||
LatencyMs *int32
|
||||
StatusCode *int32
|
||||
Error *string
|
||||
}
|
||||
|
||||
type LegalAcceptance struct {
|
||||
UserID uuid.UUID
|
||||
Kind string
|
||||
@@ -257,6 +268,7 @@ type Monitor struct {
|
||||
UpdatedAt time.Time
|
||||
Confirmations int32
|
||||
GroupID *uuid.UUID
|
||||
Position *int32
|
||||
}
|
||||
|
||||
type MonitorAlertGroup struct {
|
||||
@@ -306,21 +318,23 @@ 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
|
||||
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 PlatformIdentity struct {
|
||||
@@ -418,6 +432,11 @@ type StatusPage struct {
|
||||
ShowComponentDetails bool
|
||||
SuspendedAt *time.Time
|
||||
SuspendedReason string
|
||||
DomainSetAt *time.Time
|
||||
DomainCheckedAt *time.Time
|
||||
DomainFailingSince *time.Time
|
||||
DomainVerifyMethod *string
|
||||
Subscriptions bool
|
||||
}
|
||||
|
||||
type StatusPageGroup struct {
|
||||
@@ -441,6 +460,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
|
||||
|
||||
@@ -27,7 +27,7 @@ func (q *Queries) AddMonitorRegion(ctx context.Context, arg AddMonitorRegionPara
|
||||
}
|
||||
|
||||
const allMonitorRegions = `-- name: AllMonitorRegions :many
|
||||
SELECT monitor_id, region_id FROM monitor_regions
|
||||
SELECT monitor_id, region_id FROM monitor_regions WHERE org_id = $1
|
||||
`
|
||||
|
||||
type AllMonitorRegionsRow struct {
|
||||
@@ -35,8 +35,8 @@ type AllMonitorRegionsRow struct {
|
||||
RegionID uuid.UUID
|
||||
}
|
||||
|
||||
func (q *Queries) AllMonitorRegions(ctx context.Context) ([]AllMonitorRegionsRow, error) {
|
||||
rows, err := q.db.Query(ctx, allMonitorRegions)
|
||||
func (q *Queries) AllMonitorRegions(ctx context.Context, orgID uuid.UUID) ([]AllMonitorRegionsRow, error) {
|
||||
rows, err := q.db.Query(ctx, allMonitorRegions, orgID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -58,7 +58,7 @@ func (q *Queries) AllMonitorRegions(ctx context.Context) ([]AllMonitorRegionsRow
|
||||
const createMonitor = `-- name: CreateMonitor :one
|
||||
INSERT INTO monitors (org_id, name, type, target, interval_seconds, timeout_ms, config, enabled, confirmations, group_id)
|
||||
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10)
|
||||
RETURNING id, org_id, name, type, target, interval_seconds, timeout_ms, config, enabled, created_at, updated_at, confirmations, group_id
|
||||
RETURNING id, org_id, name, type, target, interval_seconds, timeout_ms, config, enabled, created_at, updated_at, confirmations, group_id, position
|
||||
`
|
||||
|
||||
type CreateMonitorParams struct {
|
||||
@@ -102,6 +102,7 @@ func (q *Queries) CreateMonitor(ctx context.Context, arg CreateMonitorParams) (M
|
||||
&i.UpdatedAt,
|
||||
&i.Confirmations,
|
||||
&i.GroupID,
|
||||
&i.Position,
|
||||
)
|
||||
return i, err
|
||||
}
|
||||
@@ -128,7 +129,7 @@ func (q *Queries) DeleteMonitorRegions(ctx context.Context, monitorID uuid.UUID)
|
||||
}
|
||||
|
||||
const getMonitor = `-- name: GetMonitor :one
|
||||
SELECT id, org_id, name, type, target, interval_seconds, timeout_ms, config, enabled, created_at, updated_at, confirmations, group_id FROM monitors WHERE id = $1
|
||||
SELECT id, org_id, name, type, target, interval_seconds, timeout_ms, config, enabled, created_at, updated_at, confirmations, group_id, position FROM monitors WHERE id = $1
|
||||
`
|
||||
|
||||
func (q *Queries) GetMonitor(ctx context.Context, id uuid.UUID) (Monitor, error) {
|
||||
@@ -148,6 +149,7 @@ func (q *Queries) GetMonitor(ctx context.Context, id uuid.UUID) (Monitor, error)
|
||||
&i.UpdatedAt,
|
||||
&i.Confirmations,
|
||||
&i.GroupID,
|
||||
&i.Position,
|
||||
)
|
||||
return i, err
|
||||
}
|
||||
@@ -190,11 +192,12 @@ func (q *Queries) ListEnabledMonitorsForSchedule(ctx context.Context) ([]ListEna
|
||||
}
|
||||
|
||||
const listMonitors = `-- name: ListMonitors :many
|
||||
SELECT id, org_id, name, type, target, interval_seconds, timeout_ms, config, enabled, created_at, updated_at, confirmations, group_id FROM monitors ORDER BY name
|
||||
SELECT id, org_id, name, type, target, interval_seconds, timeout_ms, config, enabled, created_at, updated_at, confirmations, group_id, position FROM monitors WHERE org_id = $1 ORDER BY name
|
||||
`
|
||||
|
||||
func (q *Queries) ListMonitors(ctx context.Context) ([]Monitor, error) {
|
||||
rows, err := q.db.Query(ctx, listMonitors)
|
||||
// The org filter, though row security implies it, lets the index be used.
|
||||
func (q *Queries) ListMonitors(ctx context.Context, orgID uuid.UUID) ([]Monitor, error) {
|
||||
rows, err := q.db.Query(ctx, listMonitors, orgID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -216,6 +219,7 @@ func (q *Queries) ListMonitors(ctx context.Context) ([]Monitor, error) {
|
||||
&i.UpdatedAt,
|
||||
&i.Confirmations,
|
||||
&i.GroupID,
|
||||
&i.Position,
|
||||
); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -228,7 +232,7 @@ func (q *Queries) ListMonitors(ctx context.Context) ([]Monitor, error) {
|
||||
}
|
||||
|
||||
const listMonitorsPage = `-- name: ListMonitorsPage :many
|
||||
SELECT id, org_id, name, type, target, interval_seconds, timeout_ms, config, enabled, created_at, updated_at, confirmations, group_id FROM monitors
|
||||
SELECT id, org_id, name, type, target, interval_seconds, timeout_ms, config, enabled, created_at, updated_at, confirmations, group_id, position FROM monitors
|
||||
WHERE true
|
||||
AND ($1::text IS NULL OR (name, id) > ($1, $2::uuid))
|
||||
AND ($3::text IS NULL OR (name, id) < ($3, $4::uuid))
|
||||
@@ -277,6 +281,7 @@ func (q *Queries) ListMonitorsPage(ctx context.Context, arg ListMonitorsPagePara
|
||||
&i.UpdatedAt,
|
||||
&i.Confirmations,
|
||||
&i.GroupID,
|
||||
&i.Position,
|
||||
); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -313,7 +318,7 @@ func (q *Queries) MonitorRegions(ctx context.Context, monitorID uuid.UUID) ([]uu
|
||||
}
|
||||
|
||||
const monitorsForJobs = `-- name: MonitorsForJobs :many
|
||||
SELECT m.id, m.org_id, m.name, m.type, m.target, m.interval_seconds, m.timeout_ms, m.config, m.enabled, m.created_at, m.updated_at, m.confirmations, m.group_id FROM monitors m
|
||||
SELECT m.id, m.org_id, m.name, m.type, m.target, m.interval_seconds, m.timeout_ms, m.config, m.enabled, m.created_at, m.updated_at, m.confirmations, m.group_id, m.position FROM monitors m
|
||||
JOIN monitor_regions r ON r.monitor_id = m.id AND r.region_id = $1
|
||||
JOIN orgs o ON o.id = m.org_id AND o.suspended_at IS NULL
|
||||
WHERE m.id = ANY ($2::uuid[]) AND m.enabled
|
||||
@@ -352,6 +357,7 @@ func (q *Queries) MonitorsForJobs(ctx context.Context, arg MonitorsForJobsParams
|
||||
&i.UpdatedAt,
|
||||
&i.Confirmations,
|
||||
&i.GroupID,
|
||||
&i.Position,
|
||||
); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -419,11 +425,28 @@ func (q *Queries) MonitorsForResults(ctx context.Context, arg MonitorsForResults
|
||||
return items, nil
|
||||
}
|
||||
|
||||
const setMonitorPosition = `-- name: SetMonitorPosition :execrows
|
||||
UPDATE monitors SET position = $1 WHERE id = $2
|
||||
`
|
||||
|
||||
type SetMonitorPositionParams struct {
|
||||
Position *int32
|
||||
ID uuid.UUID
|
||||
}
|
||||
|
||||
func (q *Queries) SetMonitorPosition(ctx context.Context, arg SetMonitorPositionParams) (int64, error) {
|
||||
result, err := q.db.Exec(ctx, setMonitorPosition, arg.Position, arg.ID)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
return result.RowsAffected(), nil
|
||||
}
|
||||
|
||||
const updateMonitor = `-- name: UpdateMonitor :one
|
||||
UPDATE monitors SET name = $2, type = $3, target = $4, interval_seconds = $5,
|
||||
timeout_ms = $6, config = $7, enabled = $8, confirmations = $9, group_id = $10, updated_at = now()
|
||||
WHERE id = $1
|
||||
RETURNING id, org_id, name, type, target, interval_seconds, timeout_ms, config, enabled, created_at, updated_at, confirmations, group_id
|
||||
RETURNING id, org_id, name, type, target, interval_seconds, timeout_ms, config, enabled, created_at, updated_at, confirmations, group_id, position
|
||||
`
|
||||
|
||||
type UpdateMonitorParams struct {
|
||||
@@ -467,6 +490,7 @@ func (q *Queries) UpdateMonitor(ctx context.Context, arg UpdateMonitorParams) (M
|
||||
&i.UpdatedAt,
|
||||
&i.Confirmations,
|
||||
&i.GroupID,
|
||||
&i.Position,
|
||||
)
|
||||
return i, 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
|
||||
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 {
|
||||
@@ -41,6 +41,8 @@ func (q *Queries) CreateOrg(ctx context.Context, arg CreateOrgParams) (Org, erro
|
||||
&i.LimitStatusPages,
|
||||
&i.LimitRegionsPerMonitor,
|
||||
&i.LimitOwnRegionsCount,
|
||||
&i.LimitMonitorsPerPage,
|
||||
&i.LimitSubscribersPerWeek,
|
||||
)
|
||||
return i, err
|
||||
}
|
||||
@@ -58,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 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) {
|
||||
@@ -80,12 +82,14 @@ func (q *Queries) GetOrg(ctx context.Context, id uuid.UUID) (Org, error) {
|
||||
&i.LimitStatusPages,
|
||||
&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 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) {
|
||||
@@ -107,12 +111,14 @@ func (q *Queries) GetOrgBySlug(ctx context.Context, slug string) (Org, error) {
|
||||
&i.LimitStatusPages,
|
||||
&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 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) {
|
||||
@@ -140,6 +146,8 @@ func (q *Queries) ListOrgs(ctx context.Context) ([]Org, error) {
|
||||
&i.LimitStatusPages,
|
||||
&i.LimitRegionsPerMonitor,
|
||||
&i.LimitOwnRegionsCount,
|
||||
&i.LimitMonitorsPerPage,
|
||||
&i.LimitSubscribersPerWeek,
|
||||
); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -168,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
|
||||
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 {
|
||||
@@ -202,6 +210,8 @@ func (q *Queries) UpdateOrgPolicy(ctx context.Context, arg UpdateOrgPolicyParams
|
||||
&i.LimitStatusPages,
|
||||
&i.LimitRegionsPerMonitor,
|
||||
&i.LimitOwnRegionsCount,
|
||||
&i.LimitMonitorsPerPage,
|
||||
&i.LimitSubscribersPerWeek,
|
||||
)
|
||||
return i, err
|
||||
}
|
||||
+80
-11
@@ -39,23 +39,31 @@ type Querier interface {
|
||||
// System scope: the receiver a webhook token belongs to.
|
||||
AlertmanagerReceiverByHash(ctx context.Context, tokenHash []byte) (AlertmanagerReceiverByHashRow, error)
|
||||
AllMonitorAlertGroups(ctx context.Context) ([]MonitorAlertGroup, error)
|
||||
AllMonitorRegions(ctx context.Context) ([]AllMonitorRegionsRow, error)
|
||||
AllMonitorRegions(ctx context.Context, orgID uuid.UUID) ([]AllMonitorRegionsRow, error)
|
||||
AnyUserExists(ctx context.Context) (bool, error)
|
||||
// How much one instance checked for the organization in the last hour.
|
||||
CheckerStats(ctx context.Context, arg CheckerStatsParams) (CheckerStatsRow, error)
|
||||
// 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; 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)
|
||||
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)
|
||||
CountSupportTicketsSince(ctx context.Context, arg CountSupportTicketsSinceParams) (int64, error)
|
||||
CountUnusedRecoveryCodes(ctx context.Context, userID uuid.UUID) (int64, error)
|
||||
@@ -74,6 +82,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)
|
||||
@@ -106,6 +115,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
|
||||
@@ -118,9 +128,23 @@ type Querier interface {
|
||||
DeleteSuccessEvidence(ctx context.Context, arg DeleteSuccessEvidenceParams) error
|
||||
DeleteUser(ctx context.Context, id uuid.UUID) (int64, error)
|
||||
DisableTOTP(ctx context.Context, id uuid.UUID) error
|
||||
// System scope: domains due for a look at their DNS records. A new one is
|
||||
// looked at every minute for a quarter of an hour, then every ten minutes
|
||||
// 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.
|
||||
@@ -133,9 +157,9 @@ type Querier interface {
|
||||
// FiringAlerts newest first, a page from a keyset cursor (see paging.go)
|
||||
// whose string key is the fingerprint.
|
||||
FiringAlertsPage(ctx context.Context, arg FiringAlertsPageParams) ([]FiringAlertsPageRow, error)
|
||||
// When each monitor and region first reported, to the day.
|
||||
FirstDataDaily(ctx context.Context, orgID uuid.UUID) ([]FirstDataDailyRow, error)
|
||||
// When each monitor and region first reported since $2, exactly. Used for
|
||||
// When each region of a monitor first reported, to the day.
|
||||
FirstDataDaily(ctx context.Context, arg FirstDataDailyParams) ([]FirstDataDailyRow, error)
|
||||
// When each region of a monitor first reported since $3, exactly. Used for
|
||||
// data younger than the daily aggregate's resolution.
|
||||
FirstDataRecent(ctx context.Context, arg FirstDataRecentParams) ([]FirstDataRecentRow, error)
|
||||
// Keeps organization and platform entries readable as "deleted user" but
|
||||
@@ -158,6 +182,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)
|
||||
@@ -178,8 +204,8 @@ type Querier interface {
|
||||
// Per monitor and hour since $2, across all regions.
|
||||
HourlyBuckets(ctx context.Context, arg HourlyBucketsParams) ([]HourlyBucketsRow, error)
|
||||
IncidentsForMonitors(ctx context.Context, arg IncidentsForMonitorsParams) ([]Incident, error)
|
||||
// Incidents overlapping the time since $1, for SLA calculation.
|
||||
IncidentsSince(ctx context.Context, resolvedAt *time.Time) ([]IncidentsSinceRow, error)
|
||||
// Incidents overlapping the time since $2, for SLA calculation.
|
||||
IncidentsSince(ctx context.Context, arg IncidentsSinceParams) ([]IncidentsSinceRow, error)
|
||||
InsertAuditEvent(ctx context.Context, arg InsertAuditEventParams) error
|
||||
// check_results and its aggregates have no row-level security (see
|
||||
// migration 00013). Every query here must filter by org_id.
|
||||
@@ -189,10 +215,16 @@ type Querier interface {
|
||||
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)
|
||||
// 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.
|
||||
LatestOK(ctx context.Context, ids []uuid.UUID) ([]LatestOKRow, error)
|
||||
LatestResultForMonitor(ctx context.Context, arg LatestResultForMonitorParams) (LatestResultForMonitorRow, error)
|
||||
// Newest result per monitor and region in the org.
|
||||
// Newest result per monitor and region in the org, of the last day.
|
||||
LatestResults(ctx context.Context, orgID uuid.UUID) ([]LatestResultsRow, error)
|
||||
LatestResultsForMonitor(ctx context.Context, arg LatestResultsForMonitorParams) ([]LatestResultsForMonitorRow, error)
|
||||
// LatestResults limited to the monitors ids.
|
||||
LatestResultsForMonitors(ctx context.Context, arg LatestResultsForMonitorsParams) ([]LatestResultsForMonitorsRow, error)
|
||||
LegalAcceptances(ctx context.Context, userID uuid.UUID) ([]LegalAcceptancesRow, error)
|
||||
// The organization's documents and the platform's, organization first.
|
||||
LegalDocuments(ctx context.Context, orgID *uuid.UUID) ([]LegalDocument, error)
|
||||
@@ -223,13 +255,16 @@ type Querier interface {
|
||||
// Latest start first, a page from a keyset cursor (see paging.go).
|
||||
ListMaintenancePage(ctx context.Context, arg ListMaintenancePageParams) ([]MaintenanceWindow, error)
|
||||
ListMaintenanceTargets(ctx context.Context) ([]MaintenanceTarget, error)
|
||||
ListMonitors(ctx context.Context) ([]Monitor, error)
|
||||
// The org filter, though row security implies it, lets the index be used.
|
||||
ListMonitors(ctx context.Context, orgID uuid.UUID) ([]Monitor, error)
|
||||
// By name, a page from a keyset cursor (see paging.go).
|
||||
ListMonitorsPage(ctx context.Context, arg ListMonitorsPageParams) ([]Monitor, error)
|
||||
ListOrgMembers(ctx context.Context, orgID uuid.UUID) ([]ListOrgMembersRow, error)
|
||||
// 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)
|
||||
@@ -261,11 +296,17 @@ type Querier interface {
|
||||
// their group or one of its ancestors.
|
||||
MaintenanceForMonitors(ctx context.Context, ids []uuid.UUID) ([]MaintenanceForMonitorsRow, error)
|
||||
MakeAdmin(ctx context.Context, id uuid.UUID) error
|
||||
MarkDomainVerified(ctx context.Context, id uuid.UUID) error
|
||||
// The record of a domain was not found. Returns since when it has not
|
||||
// been, for a verified domain.
|
||||
MarkDomainUnconfirmed(ctx context.Context, arg MarkDomainUnconfirmedParams) (*time.Time, error)
|
||||
// The domain's record was found: verified, or still in place.
|
||||
MarkDomainVerified(ctx context.Context, arg MarkDomainVerifiedParams) error
|
||||
MarkEmailVerified(ctx context.Context, id uuid.UUID) (User, error)
|
||||
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)
|
||||
@@ -281,7 +322,7 @@ type Querier interface {
|
||||
// System scope.
|
||||
NotificationDetails(ctx context.Context, ids []uuid.UUID) ([]NotificationDetailsRow, error)
|
||||
OpenIncident(ctx context.Context, arg OpenIncidentParams) (Incident, error)
|
||||
OpenIncidents(ctx context.Context) ([]Incident, error)
|
||||
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)
|
||||
OrgDailyStats(ctx context.Context, orgID uuid.UUID) ([]OrgDailyStatsRow, error)
|
||||
@@ -289,6 +330,11 @@ type Querier interface {
|
||||
OrgIncidentUpdatesExport(ctx context.Context, orgID uuid.UUID) ([]OrgIncidentUpdatesExportRow, error)
|
||||
OrgIncidentsExport(ctx context.Context, orgID uuid.UUID) ([]OrgIncidentsExportRow, error)
|
||||
OrgMembersExport(ctx context.Context, orgID uuid.UUID) ([]OrgMembersExportRow, error)
|
||||
// System scope.
|
||||
OrgOwnerEmails(ctx context.Context, orgID uuid.UUID) ([]string, error)
|
||||
// An organization serves its status pages itself once one of its own
|
||||
// status page servers has connected.
|
||||
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)
|
||||
// The public updates of incidents shown on a status page, newest first.
|
||||
@@ -304,6 +350,10 @@ type Querier interface {
|
||||
// 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
|
||||
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)
|
||||
// Raw results bucketed by width since a point in time, for short ranges.
|
||||
@@ -318,6 +368,9 @@ type Querier interface {
|
||||
RegionBuckets(ctx context.Context, arg RegionBucketsParams) ([]RegionBucketsRow, error)
|
||||
RegionBucketsDaily(ctx context.Context, arg RegionBucketsDailyParams) ([]RegionBucketsDailyRow, error)
|
||||
RegionBucketsHourly(ctx context.Context, arg RegionBucketsHourlyParams) ([]RegionBucketsHourlyRow, error)
|
||||
// System scope: regions that have checkers and enabled monitors, so a
|
||||
// region without a live checker leaves monitors unchecked.
|
||||
RegionsToWatch(ctx context.Context) ([]RegionsToWatchRow, error)
|
||||
RegroupMonitors(ctx context.Context, arg RegroupMonitorsParams) error
|
||||
RemoveMembership(ctx context.Context, arg RemoveMembershipParams) (int64, error)
|
||||
// Moves the subgroups of a group that is about to be deleted.
|
||||
@@ -334,14 +387,19 @@ type Querier interface {
|
||||
// page from a keyset cursor whose string key is monitor and region.
|
||||
ResultsByChecker(ctx context.Context, arg ResultsByCheckerParams) ([]ResultsByCheckerRow, error)
|
||||
ScrubAuditEmail(ctx context.Context, email string) error
|
||||
// System scope: the published pages a status page server serves, those
|
||||
// of agent_org for an organization's server; the platform's leave the
|
||||
// pages of organizations serving their own.
|
||||
ServablePages(ctx context.Context, agentOrg *uuid.UUID) ([]ServablePagesRow, error)
|
||||
SetAgentAllowPrivate(ctx context.Context, arg SetAgentAllowPrivateParams) (int64, error)
|
||||
SetIncidentTitle(ctx context.Context, arg SetIncidentTitleParams) (int64, error)
|
||||
SetMonitorPosition(ctx context.Context, arg SetMonitorPositionParams) (int64, error)
|
||||
SetOrgDisabledCheckTypes(ctx context.Context, arg SetOrgDisabledCheckTypesParams) error
|
||||
SetOrgLimits(ctx context.Context, arg SetOrgLimitsParams) (SetOrgLimitsRow, error)
|
||||
SetOwner(ctx context.Context, arg SetOwnerParams) (int64, error)
|
||||
SetPasswordHash(ctx context.Context, arg SetPasswordHashParams) error
|
||||
SetPlatformSetting(ctx context.Context, arg SetPlatformSettingParams) error
|
||||
// Changing the domain drops a previous verification.
|
||||
// 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
|
||||
SetSupportTicketStatus(ctx context.Context, arg SetSupportTicketStatusParams) (int64, error)
|
||||
@@ -358,6 +416,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)
|
||||
@@ -378,7 +438,12 @@ 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
|
||||
UpdateAlertGroup(ctx context.Context, arg UpdateAlertGroupParams) (AlertGroup, error)
|
||||
UpdateChannel(ctx context.Context, arg UpdateChannelParams) (NotificationChannel, error)
|
||||
UpdateGroup(ctx context.Context, arg UpdateGroupParams) (MonitorGroup, error)
|
||||
@@ -392,6 +457,10 @@ type Querier interface {
|
||||
UpdateStatusPage(ctx context.Context, arg UpdateStatusPageParams) (StatusPage, error)
|
||||
UpdateStatusPageGroup(ctx context.Context, arg UpdateStatusPageGroupParams) (StatusPageGroup, error)
|
||||
UpsertAlertmanagerAlert(ctx context.Context, arg UpsertAlertmanagerAlertParams) error
|
||||
// Keeps the newest of results, a JSON array, per monitor and
|
||||
// region; results arriving late do not replace newer ones. It returns the
|
||||
// rows it wrote.
|
||||
UpsertLatestResults(ctx context.Context, results []byte) ([]UpsertLatestResultsRow, error)
|
||||
// A new version starts when the document is created or when the edit asks
|
||||
// everyone to accept it again.
|
||||
UpsertLegalDocument(ctx context.Context, arg UpsertLegalDocumentParams) error
|
||||
|
||||
@@ -54,3 +54,27 @@ WHERE id = $1 AND (last_seen_at IS NULL OR last_seen_at < now() - interval '30 s
|
||||
-- name: SetAgentAllowPrivate :execrows
|
||||
UPDATE agents SET allow_private = sqlc.arg(allow_private)
|
||||
WHERE id = sqlc.arg(id) AND kind = 'checker' AND org_id = sqlc.arg(org_id);
|
||||
|
||||
-- name: OrgServesOwnPages :one
|
||||
-- An organization serves its status pages itself once one of its own
|
||||
-- status page servers has connected.
|
||||
SELECT EXISTS (
|
||||
SELECT 1 FROM agents
|
||||
WHERE org_id = $1 AND kind = 'statuspage' AND last_seen_at IS NOT NULL
|
||||
);
|
||||
|
||||
-- name: RegionsToWatch :many
|
||||
-- System scope: regions that have checkers and enabled monitors, so a
|
||||
-- region without a live checker leaves monitors unchecked.
|
||||
SELECT r.id, r.name, r.org_id, o.name AS org_name
|
||||
FROM regions r
|
||||
LEFT JOIN orgs o ON o.id = r.org_id
|
||||
WHERE EXISTS (SELECT 1 FROM agents a WHERE a.kind = 'checker' AND a.region_id = r.id)
|
||||
AND EXISTS (SELECT 1 FROM monitor_regions mr JOIN monitors m ON m.id = mr.monitor_id
|
||||
WHERE mr.region_id = r.id AND m.enabled)
|
||||
ORDER BY r.name;
|
||||
|
||||
-- name: OrgOwnerEmails :many
|
||||
-- System scope.
|
||||
SELECT u.email FROM memberships m JOIN users u ON u.id = m.user_id
|
||||
WHERE m.org_id = $1 AND m.is_owner AND u.disabled_at IS NULL;
|
||||
@@ -5,13 +5,6 @@
|
||||
INSERT INTO check_results (time, org_id, monitor_id, region, checker_id, ok, latency_ms, status_code, error)
|
||||
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9);
|
||||
|
||||
-- name: LatestResults :many
|
||||
-- Newest result per monitor and region in the org.
|
||||
SELECT DISTINCT ON (monitor_id, region) monitor_id, region, time, ok, latency_ms, status_code, error
|
||||
FROM check_results
|
||||
WHERE org_id = $1 AND time > now() - interval '1 day'
|
||||
ORDER BY monitor_id, region, time DESC;
|
||||
|
||||
-- name: ListResults :many
|
||||
-- A monitor's results newest first, a page from a keyset cursor (see
|
||||
-- paging.go) whose string key is region and checker.
|
||||
@@ -49,6 +42,7 @@ SELECT monitor_id, bucket::timestamptz AS bucket, sum(total)::bigint AS total, s
|
||||
coalesce(sum(avg_latency_ms * total) / nullif(sum(total), 0), 0)::real AS avg_latency_ms
|
||||
FROM check_results_1h
|
||||
WHERE org_id = $1 AND bucket >= $2
|
||||
AND (sqlc.narg(ids)::uuid[] IS NULL OR monitor_id = ANY (sqlc.narg(ids)::uuid[]))
|
||||
GROUP BY monitor_id, bucket
|
||||
ORDER BY monitor_id, bucket;
|
||||
|
||||
@@ -73,7 +67,7 @@ SELECT monitor_id, time_bucket(sqlc.arg(width)::text::interval, time)::timestamp
|
||||
coalesce(avg(latency_ms), 0)::real AS avg_latency_ms
|
||||
FROM check_results
|
||||
WHERE org_id = $1 AND time >= sqlc.arg(since)
|
||||
AND (sqlc.narg(monitor_id)::uuid IS NULL OR monitor_id = sqlc.narg(monitor_id))
|
||||
AND monitor_id = ANY (sqlc.arg(ids)::uuid[])
|
||||
GROUP BY 1, 2
|
||||
ORDER BY 1, 2;
|
||||
|
||||
@@ -84,7 +78,7 @@ SELECT monitor_id, time_bucket(sqlc.arg(width)::text::interval, bucket)::timesta
|
||||
coalesce(sum(avg_latency_ms * total) / nullif(sum(total), 0), 0)::real AS avg_latency_ms
|
||||
FROM check_results_1h
|
||||
WHERE org_id = $1 AND bucket >= sqlc.arg(since)
|
||||
AND (sqlc.narg(monitor_id)::uuid IS NULL OR monitor_id = sqlc.narg(monitor_id))
|
||||
AND monitor_id = ANY (sqlc.arg(ids)::uuid[])
|
||||
GROUP BY 1, 2
|
||||
ORDER BY 1, 2;
|
||||
|
||||
@@ -95,7 +89,7 @@ SELECT monitor_id, time_bucket(sqlc.arg(width)::text::interval, bucket)::timesta
|
||||
coalesce(sum(avg_latency_ms * total) / nullif(sum(total), 0), 0)::real AS avg_latency_ms
|
||||
FROM check_results_1d
|
||||
WHERE org_id = $1 AND bucket >= sqlc.arg(since)
|
||||
AND (sqlc.narg(monitor_id)::uuid IS NULL OR monitor_id = sqlc.narg(monitor_id))
|
||||
AND monitor_id = ANY (sqlc.arg(ids)::uuid[])
|
||||
GROUP BY 1, 2
|
||||
ORDER BY 1, 2;
|
||||
|
||||
@@ -125,18 +119,35 @@ GROUP BY 1, 2
|
||||
ORDER BY 1, 2;
|
||||
|
||||
-- name: FirstDataDaily :many
|
||||
-- When each monitor and region first reported, to the day.
|
||||
-- When each region of a monitor first reported, to the day.
|
||||
SELECT monitor_id, region, min(bucket)::timestamptz AS first
|
||||
FROM check_results_1d
|
||||
WHERE org_id = $1
|
||||
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 monitor and region first reported since $2, exactly. Used for
|
||||
-- When each region of a monitor first reported since $3, exactly. Used for
|
||||
-- data younger than the daily aggregate's resolution.
|
||||
SELECT monitor_id, region, min(time)::timestamptz AS first
|
||||
FROM check_results
|
||||
WHERE org_id = $1 AND time >= $2
|
||||
WHERE org_id = $1 AND monitor_id = $2 AND time >= $3
|
||||
GROUP BY 1, 2;
|
||||
|
||||
-- name: ResultsByChecker :many
|
||||
|
||||
@@ -84,18 +84,18 @@ SELECT * FROM notification_channels ORDER BY name;
|
||||
DELETE FROM notification_channels WHERE id = $1;
|
||||
|
||||
-- name: OpenIncidents :many
|
||||
SELECT * FROM incidents WHERE resolved_at IS NULL;
|
||||
SELECT * FROM incidents WHERE org_id = $1 AND resolved_at IS NULL;
|
||||
|
||||
-- name: IncidentsForMonitors :many
|
||||
SELECT * FROM incidents
|
||||
WHERE monitor_id = ANY (sqlc.arg(ids)::uuid[]) AND (resolved_at IS NULL OR resolved_at > sqlc.arg(since))
|
||||
WHERE org_id = sqlc.arg(org_id) AND monitor_id = ANY (sqlc.arg(ids)::uuid[]) AND (resolved_at IS NULL OR resolved_at > sqlc.arg(since))
|
||||
ORDER BY started_at DESC
|
||||
LIMIT 50;
|
||||
|
||||
-- name: IncidentsSince :many
|
||||
-- Incidents overlapping the time since $1, for SLA calculation.
|
||||
-- Incidents overlapping the time since $2, for SLA calculation.
|
||||
SELECT monitor_id, started_at, resolved_at FROM incidents
|
||||
WHERE resolved_at IS NULL OR resolved_at > $1;
|
||||
WHERE org_id = $1 AND (resolved_at IS NULL OR resolved_at > $2);
|
||||
|
||||
-- name: GetIncident :one
|
||||
SELECT i.*, m.name AS monitor_name, m.group_id AS monitor_group_id
|
||||
|
||||
@@ -0,0 +1,33 @@
|
||||
-- latest_results holds the newest check result per monitor and region
|
||||
-- (see migration 00055) and has row-level security.
|
||||
|
||||
-- name: LatestOK :many
|
||||
-- Whether the newest result of each region of the monitors ids succeeded.
|
||||
SELECT monitor_id, region, ok FROM latest_results WHERE monitor_id = ANY (sqlc.arg(ids)::uuid[]);
|
||||
|
||||
-- name: UpsertLatestResults :many
|
||||
-- Keeps the newest of results, a JSON array, per monitor and
|
||||
-- region; results arriving late do not replace newer ones. It returns the
|
||||
-- rows it wrote.
|
||||
INSERT INTO latest_results (monitor_id, region, org_id, time, ok, latency_ms, status_code, error)
|
||||
SELECT DISTINCT ON (r.monitor_id, r.region) r.monitor_id, r.region, r.org_id, r.time, r.ok, r.latency_ms, r.status_code, r.error
|
||||
FROM jsonb_to_recordset(sqlc.arg(results)::jsonb)
|
||||
AS r(monitor_id uuid, region text, org_id uuid, time timestamptz, ok boolean, latency_ms integer, status_code integer, error text)
|
||||
ORDER BY r.monitor_id, r.region, r.time DESC
|
||||
ON CONFLICT (monitor_id, region) DO UPDATE
|
||||
SET org_id = excluded.org_id, time = excluded.time, ok = excluded.ok, latency_ms = excluded.latency_ms,
|
||||
status_code = excluded.status_code, error = excluded.error
|
||||
WHERE latest_results.time <= excluded.time
|
||||
RETURNING monitor_id, region, org_id, ok;
|
||||
|
||||
-- name: LatestResults :many
|
||||
-- Newest result per monitor and region in the org, of the last day.
|
||||
SELECT monitor_id, region, time, ok, latency_ms, status_code, error
|
||||
FROM latest_results
|
||||
WHERE org_id = $1 AND time > now() - interval '1 day';
|
||||
|
||||
-- name: LatestResultsForMonitors :many
|
||||
-- LatestResults limited to the monitors ids.
|
||||
SELECT monitor_id, region, time, ok, latency_ms, status_code, error
|
||||
FROM latest_results
|
||||
WHERE org_id = $1 AND monitor_id = ANY (sqlc.arg(ids)::uuid[]) AND time > now() - interval '1 day';
|
||||
@@ -9,9 +9,13 @@ SELECT count(*) FROM monitors WHERE org_id = $1;
|
||||
-- name: CountStatusPages :one
|
||||
SELECT count(*) FROM status_pages WHERE org_id = $1;
|
||||
|
||||
-- name: CountStatusPageMonitors :one
|
||||
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_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_subscribers_per_week = sqlc.narg(subscribers_per_week)
|
||||
WHERE id = sqlc.arg(id)
|
||||
RETURNING id, slug;
|
||||
|
||||
@@ -25,6 +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_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,
|
||||
|
||||
@@ -16,13 +16,14 @@ DELETE FROM monitors WHERE id = $1;
|
||||
SELECT * FROM monitors WHERE id = $1;
|
||||
|
||||
-- name: ListMonitors :many
|
||||
SELECT * FROM monitors ORDER BY name;
|
||||
-- The org filter, though row security implies it, lets the index be used.
|
||||
SELECT * FROM monitors WHERE org_id = $1 ORDER BY name;
|
||||
|
||||
-- name: MonitorRegions :many
|
||||
SELECT region_id FROM monitor_regions WHERE monitor_id = $1 ORDER BY region_id;
|
||||
|
||||
-- name: AllMonitorRegions :many
|
||||
SELECT monitor_id, region_id FROM monitor_regions;
|
||||
SELECT monitor_id, region_id FROM monitor_regions WHERE org_id = $1;
|
||||
|
||||
-- name: DeleteMonitorRegions :exec
|
||||
DELETE FROM monitor_regions WHERE monitor_id = $1;
|
||||
@@ -72,3 +73,6 @@ ORDER BY
|
||||
CASE WHEN sqlc.narg(before_s)::text IS NULL THEN id END,
|
||||
name DESC, id DESC
|
||||
LIMIT sqlc.arg(max_rows);
|
||||
|
||||
-- name: SetMonitorPosition :execrows
|
||||
UPDATE monitors SET position = sqlc.arg(position) WHERE id = sqlc.arg(id);
|
||||
@@ -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,21 +11,69 @@ SET slug = $2,
|
||||
published = $5,
|
||||
show_component_details = $6,
|
||||
theme = $7,
|
||||
subscriptions = $8,
|
||||
updated_at = now()
|
||||
WHERE id = $1
|
||||
RETURNING *;
|
||||
|
||||
-- name: SetStatusPageDomain :one
|
||||
-- Changing the domain drops a previous verification.
|
||||
-- Changing the domain drops a previous verification and its checks.
|
||||
UPDATE status_pages SET
|
||||
custom_domain = sqlc.narg(custom_domain),
|
||||
domain_verified_at = CASE WHEN custom_domain IS NOT DISTINCT FROM sqlc.narg(custom_domain) THEN domain_verified_at END,
|
||||
domain_verify_method = CASE WHEN custom_domain IS NOT DISTINCT FROM sqlc.narg(custom_domain) THEN domain_verify_method END,
|
||||
domain_failing_since = CASE WHEN custom_domain IS NOT DISTINCT FROM sqlc.narg(custom_domain) THEN domain_failing_since END,
|
||||
domain_checked_at = CASE WHEN custom_domain IS NOT DISTINCT FROM sqlc.narg(custom_domain) THEN domain_checked_at END,
|
||||
domain_set_at = CASE WHEN custom_domain IS NOT DISTINCT FROM sqlc.narg(custom_domain) THEN domain_set_at ELSE now() END,
|
||||
custom_domain = sqlc.narg(custom_domain),
|
||||
updated_at = now()
|
||||
WHERE id = sqlc.arg(id)
|
||||
RETURNING *;
|
||||
|
||||
-- name: MarkDomainVerified :exec
|
||||
UPDATE status_pages SET domain_verified_at = now() WHERE id = $1;
|
||||
-- The domain's record was found: verified, or still in place.
|
||||
UPDATE status_pages SET
|
||||
domain_verified_at = coalesce(domain_verified_at, sqlc.arg(now)::timestamptz),
|
||||
domain_verify_method = sqlc.arg(method)::text,
|
||||
domain_checked_at = sqlc.arg(now)::timestamptz,
|
||||
domain_failing_since = NULL
|
||||
WHERE id = sqlc.arg(id);
|
||||
|
||||
-- name: MarkDomainUnconfirmed :one
|
||||
-- The record of a domain was not found. Returns since when it has not
|
||||
-- been, for a verified domain.
|
||||
UPDATE status_pages SET
|
||||
domain_checked_at = sqlc.arg(now)::timestamptz,
|
||||
domain_failing_since = CASE WHEN domain_verified_at IS NULL THEN NULL
|
||||
ELSE coalesce(domain_failing_since, sqlc.arg(now)::timestamptz) END
|
||||
WHERE id = sqlc.arg(id)
|
||||
RETURNING domain_failing_since;
|
||||
|
||||
-- name: UnverifyDomain :exec
|
||||
-- A verified domain whose record stayed missing past the grace period.
|
||||
UPDATE status_pages SET
|
||||
domain_verified_at = NULL, domain_verify_method = NULL, domain_failing_since = NULL
|
||||
WHERE id = $1;
|
||||
|
||||
-- name: DomainsToCheck :many
|
||||
-- System scope: domains due for a look at their DNS records. A new one is
|
||||
-- looked at every minute for a quarter of an hour, then every ten minutes
|
||||
-- for two days, after which only the verify button tries again. A verified
|
||||
-- one is checked daily, hourly once its record went missing.
|
||||
SELECT id, org_id, title, custom_domain::text AS domain, domain_token,
|
||||
domain_verified_at, domain_failing_since
|
||||
FROM status_pages
|
||||
WHERE custom_domain IS NOT NULL
|
||||
AND (sqlc.narg(page_id)::uuid IS NULL OR id = sqlc.narg(page_id))
|
||||
AND (
|
||||
(domain_verified_at IS NULL AND domain_set_at > sqlc.arg(now)::timestamptz - interval '48 hours'
|
||||
AND (domain_checked_at IS NULL OR domain_checked_at <= sqlc.arg(now)::timestamptz - CASE
|
||||
WHEN domain_set_at > sqlc.arg(now)::timestamptz - interval '15 minutes' THEN interval '50 seconds'
|
||||
ELSE interval '10 minutes' END))
|
||||
OR (domain_verified_at IS NOT NULL AND domain_verify_method IS NOT NULL
|
||||
AND (domain_checked_at IS NULL OR domain_checked_at <= sqlc.arg(now)::timestamptz - CASE
|
||||
WHEN domain_failing_since IS NULL THEN interval '24 hours' ELSE interval '1 hour' END)))
|
||||
ORDER BY domain_checked_at NULLS FIRST
|
||||
LIMIT 500;
|
||||
|
||||
-- name: GetStatusPage :one
|
||||
SELECT * FROM status_pages WHERE id = $1;
|
||||
@@ -38,7 +86,8 @@ DELETE FROM status_pages WHERE id = $1;
|
||||
|
||||
-- name: StatusPageMonitors :many
|
||||
SELECT spm.monitor_id, spm.section, spm.group_id, spm.label, spm.position,
|
||||
m.name AS monitor_name, m.enabled, m.group_id AS monitor_group_id
|
||||
m.name AS monitor_name, m.enabled, m.group_id AS monitor_group_id,
|
||||
m.type AS monitor_type, m.interval_seconds
|
||||
FROM status_page_monitors spm
|
||||
JOIN monitors m ON m.id = spm.monitor_id
|
||||
WHERE spm.page_id = $1
|
||||
@@ -93,3 +142,17 @@ 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 ((sqlc.narg(host)::citext IS NOT NULL AND custom_domain = sqlc.narg(host) AND domain_verified_at IS NOT NULL)
|
||||
OR (sqlc.narg(slug)::citext IS NOT NULL AND slug = sqlc.narg(slug)));
|
||||
|
||||
-- name: ServablePages :many
|
||||
-- System scope: the published pages a status page server serves, those
|
||||
-- of agent_org for an organization's server; the platform's leave the
|
||||
-- pages of organizations serving their own.
|
||||
SELECT p.slug, COALESCE(CASE WHEN p.domain_verified_at IS NOT NULL THEN p.custom_domain END, '')::text AS host, p.org_id
|
||||
FROM status_pages p
|
||||
JOIN orgs o ON o.id = p.org_id
|
||||
WHERE p.published AND p.suspended_at IS NULL AND o.suspended_at IS NULL
|
||||
AND CASE WHEN sqlc.narg(agent_org)::uuid IS NULL
|
||||
THEN NOT 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)
|
||||
ELSE p.org_id = sqlc.narg(agent_org)::uuid
|
||||
END
|
||||
ORDER BY p.slug;
|
||||
@@ -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;
|
||||
@@ -7,6 +7,7 @@ package store
|
||||
|
||||
import (
|
||||
"context"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
@@ -58,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
|
||||
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 {
|
||||
@@ -72,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) {
|
||||
@@ -84,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(
|
||||
@@ -102,6 +105,11 @@ func (q *Queries) CreateStatusPage(ctx context.Context, arg CreateStatusPagePara
|
||||
&i.ShowComponentDetails,
|
||||
&i.SuspendedAt,
|
||||
&i.SuspendedReason,
|
||||
&i.DomainSetAt,
|
||||
&i.DomainCheckedAt,
|
||||
&i.DomainFailingSince,
|
||||
&i.DomainVerifyMethod,
|
||||
&i.Subscriptions,
|
||||
)
|
||||
return i, err
|
||||
}
|
||||
@@ -171,8 +179,73 @@ func (q *Queries) DeleteStatusPageGroup(ctx context.Context, arg DeleteStatusPag
|
||||
return result.RowsAffected(), nil
|
||||
}
|
||||
|
||||
const domainsToCheck = `-- name: DomainsToCheck :many
|
||||
SELECT id, org_id, title, custom_domain::text AS domain, domain_token,
|
||||
domain_verified_at, domain_failing_since
|
||||
FROM status_pages
|
||||
WHERE custom_domain IS NOT NULL
|
||||
AND ($1::uuid IS NULL OR id = $1)
|
||||
AND (
|
||||
(domain_verified_at IS NULL AND domain_set_at > $2::timestamptz - interval '48 hours'
|
||||
AND (domain_checked_at IS NULL OR domain_checked_at <= $2::timestamptz - CASE
|
||||
WHEN domain_set_at > $2::timestamptz - interval '15 minutes' THEN interval '50 seconds'
|
||||
ELSE interval '10 minutes' END))
|
||||
OR (domain_verified_at IS NOT NULL AND domain_verify_method IS NOT NULL
|
||||
AND (domain_checked_at IS NULL OR domain_checked_at <= $2::timestamptz - CASE
|
||||
WHEN domain_failing_since IS NULL THEN interval '24 hours' ELSE interval '1 hour' END)))
|
||||
ORDER BY domain_checked_at NULLS FIRST
|
||||
LIMIT 500
|
||||
`
|
||||
|
||||
type DomainsToCheckParams struct {
|
||||
PageID *uuid.UUID
|
||||
Now time.Time
|
||||
}
|
||||
|
||||
type DomainsToCheckRow struct {
|
||||
ID uuid.UUID
|
||||
OrgID uuid.UUID
|
||||
Title string
|
||||
Domain string
|
||||
DomainToken string
|
||||
DomainVerifiedAt *time.Time
|
||||
DomainFailingSince *time.Time
|
||||
}
|
||||
|
||||
// System scope: domains due for a look at their DNS records. A new one is
|
||||
// looked at every minute for a quarter of an hour, then every ten minutes
|
||||
// for two days, after which only the verify button tries again. A verified
|
||||
// one is checked daily, hourly once its record went missing.
|
||||
func (q *Queries) DomainsToCheck(ctx context.Context, arg DomainsToCheckParams) ([]DomainsToCheckRow, error) {
|
||||
rows, err := q.db.Query(ctx, domainsToCheck, arg.PageID, arg.Now)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
items := []DomainsToCheckRow{}
|
||||
for rows.Next() {
|
||||
var i DomainsToCheckRow
|
||||
if err := rows.Scan(
|
||||
&i.ID,
|
||||
&i.OrgID,
|
||||
&i.Title,
|
||||
&i.Domain,
|
||||
&i.DomainToken,
|
||||
&i.DomainVerifiedAt,
|
||||
&i.DomainFailingSince,
|
||||
); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
items = append(items, i)
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return items, nil
|
||||
}
|
||||
|
||||
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 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)
|
||||
@@ -205,12 +278,17 @@ func (q *Queries) FindPublishedPage(ctx context.Context, arg FindPublishedPagePa
|
||||
&i.ShowComponentDetails,
|
||||
&i.SuspendedAt,
|
||||
&i.SuspendedReason,
|
||||
&i.DomainSetAt,
|
||||
&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 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) {
|
||||
@@ -232,6 +310,11 @@ func (q *Queries) GetStatusPage(ctx context.Context, id uuid.UUID) (StatusPage,
|
||||
&i.ShowComponentDetails,
|
||||
&i.SuspendedAt,
|
||||
&i.SuspendedReason,
|
||||
&i.DomainSetAt,
|
||||
&i.DomainCheckedAt,
|
||||
&i.DomainFailingSince,
|
||||
&i.DomainVerifyMethod,
|
||||
&i.Subscriptions,
|
||||
)
|
||||
return i, err
|
||||
}
|
||||
@@ -272,7 +355,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 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) {
|
||||
@@ -300,6 +383,11 @@ func (q *Queries) ListStatusPages(ctx context.Context) ([]StatusPage, error) {
|
||||
&i.ShowComponentDetails,
|
||||
&i.SuspendedAt,
|
||||
&i.SuspendedReason,
|
||||
&i.DomainSetAt,
|
||||
&i.DomainCheckedAt,
|
||||
&i.DomainFailingSince,
|
||||
&i.DomainVerifyMethod,
|
||||
&i.Subscriptions,
|
||||
); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -311,12 +399,47 @@ func (q *Queries) ListStatusPages(ctx context.Context) ([]StatusPage, error) {
|
||||
return items, nil
|
||||
}
|
||||
|
||||
const markDomainVerified = `-- name: MarkDomainVerified :exec
|
||||
UPDATE status_pages SET domain_verified_at = now() WHERE id = $1
|
||||
const markDomainUnconfirmed = `-- name: MarkDomainUnconfirmed :one
|
||||
UPDATE status_pages SET
|
||||
domain_checked_at = $1::timestamptz,
|
||||
domain_failing_since = CASE WHEN domain_verified_at IS NULL THEN NULL
|
||||
ELSE coalesce(domain_failing_since, $1::timestamptz) END
|
||||
WHERE id = $2
|
||||
RETURNING domain_failing_since
|
||||
`
|
||||
|
||||
func (q *Queries) MarkDomainVerified(ctx context.Context, id uuid.UUID) error {
|
||||
_, err := q.db.Exec(ctx, markDomainVerified, id)
|
||||
type MarkDomainUnconfirmedParams struct {
|
||||
Now time.Time
|
||||
ID uuid.UUID
|
||||
}
|
||||
|
||||
// The record of a domain was not found. Returns since when it has not
|
||||
// been, for a verified domain.
|
||||
func (q *Queries) MarkDomainUnconfirmed(ctx context.Context, arg MarkDomainUnconfirmedParams) (*time.Time, error) {
|
||||
row := q.db.QueryRow(ctx, markDomainUnconfirmed, arg.Now, arg.ID)
|
||||
var domain_failing_since *time.Time
|
||||
err := row.Scan(&domain_failing_since)
|
||||
return domain_failing_since, err
|
||||
}
|
||||
|
||||
const markDomainVerified = `-- name: MarkDomainVerified :exec
|
||||
UPDATE status_pages SET
|
||||
domain_verified_at = coalesce(domain_verified_at, $1::timestamptz),
|
||||
domain_verify_method = $2::text,
|
||||
domain_checked_at = $1::timestamptz,
|
||||
domain_failing_since = NULL
|
||||
WHERE id = $3
|
||||
`
|
||||
|
||||
type MarkDomainVerifiedParams struct {
|
||||
Now time.Time
|
||||
Method string
|
||||
ID uuid.UUID
|
||||
}
|
||||
|
||||
// The domain's record was found: verified, or still in place.
|
||||
func (q *Queries) MarkDomainVerified(ctx context.Context, arg MarkDomainVerifiedParams) error {
|
||||
_, err := q.db.Exec(ctx, markDomainVerified, arg.Now, arg.Method, arg.ID)
|
||||
return err
|
||||
}
|
||||
|
||||
@@ -352,13 +475,58 @@ func (q *Queries) ReparentStatusPageGroupMonitors(ctx context.Context, arg Repar
|
||||
return err
|
||||
}
|
||||
|
||||
const servablePages = `-- name: ServablePages :many
|
||||
SELECT p.slug, COALESCE(CASE WHEN p.domain_verified_at IS NOT NULL THEN p.custom_domain END, '')::text AS host, p.org_id
|
||||
FROM status_pages p
|
||||
JOIN orgs o ON o.id = p.org_id
|
||||
WHERE p.published AND p.suspended_at IS NULL AND o.suspended_at IS NULL
|
||||
AND CASE WHEN $1::uuid IS NULL
|
||||
THEN NOT 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)
|
||||
ELSE p.org_id = $1::uuid
|
||||
END
|
||||
ORDER BY p.slug
|
||||
`
|
||||
|
||||
type ServablePagesRow struct {
|
||||
Slug string
|
||||
Host string
|
||||
OrgID uuid.UUID
|
||||
}
|
||||
|
||||
// System scope: the published pages a status page server serves, those
|
||||
// of agent_org for an organization's server; the platform's leave the
|
||||
// pages of organizations serving their own.
|
||||
func (q *Queries) ServablePages(ctx context.Context, agentOrg *uuid.UUID) ([]ServablePagesRow, error) {
|
||||
rows, err := q.db.Query(ctx, servablePages, agentOrg)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
items := []ServablePagesRow{}
|
||||
for rows.Next() {
|
||||
var i ServablePagesRow
|
||||
if err := rows.Scan(&i.Slug, &i.Host, &i.OrgID); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
items = append(items, i)
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return items, nil
|
||||
}
|
||||
|
||||
const setStatusPageDomain = `-- name: SetStatusPageDomain :one
|
||||
UPDATE status_pages SET
|
||||
custom_domain = $1,
|
||||
domain_verified_at = CASE WHEN custom_domain IS NOT DISTINCT FROM $1 THEN domain_verified_at END,
|
||||
domain_verify_method = CASE WHEN custom_domain IS NOT DISTINCT FROM $1 THEN domain_verify_method END,
|
||||
domain_failing_since = CASE WHEN custom_domain IS NOT DISTINCT FROM $1 THEN domain_failing_since END,
|
||||
domain_checked_at = CASE WHEN custom_domain IS NOT DISTINCT FROM $1 THEN domain_checked_at END,
|
||||
domain_set_at = CASE WHEN custom_domain IS NOT DISTINCT FROM $1 THEN domain_set_at ELSE now() END,
|
||||
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
|
||||
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 {
|
||||
@@ -366,7 +534,7 @@ type SetStatusPageDomainParams struct {
|
||||
ID uuid.UUID
|
||||
}
|
||||
|
||||
// Changing the domain drops a previous verification.
|
||||
// Changing the domain drops a previous verification and its checks.
|
||||
func (q *Queries) SetStatusPageDomain(ctx context.Context, arg SetStatusPageDomainParams) (StatusPage, error) {
|
||||
row := q.db.QueryRow(ctx, setStatusPageDomain, arg.CustomDomain, arg.ID)
|
||||
var i StatusPage
|
||||
@@ -386,6 +554,11 @@ func (q *Queries) SetStatusPageDomain(ctx context.Context, arg SetStatusPageDoma
|
||||
&i.ShowComponentDetails,
|
||||
&i.SuspendedAt,
|
||||
&i.SuspendedReason,
|
||||
&i.DomainSetAt,
|
||||
&i.DomainCheckedAt,
|
||||
&i.DomainFailingSince,
|
||||
&i.DomainVerifyMethod,
|
||||
&i.Subscriptions,
|
||||
)
|
||||
return i, err
|
||||
}
|
||||
@@ -414,7 +587,8 @@ func (q *Queries) SetStatusPageMonitorGroup(ctx context.Context, arg SetStatusPa
|
||||
|
||||
const statusPageMonitors = `-- name: StatusPageMonitors :many
|
||||
SELECT spm.monitor_id, spm.section, spm.group_id, spm.label, spm.position,
|
||||
m.name AS monitor_name, m.enabled, m.group_id AS monitor_group_id
|
||||
m.name AS monitor_name, m.enabled, m.group_id AS monitor_group_id,
|
||||
m.type AS monitor_type, m.interval_seconds
|
||||
FROM status_page_monitors spm
|
||||
JOIN monitors m ON m.id = spm.monitor_id
|
||||
WHERE spm.page_id = $1
|
||||
@@ -422,14 +596,16 @@ ORDER BY spm.position, m.name
|
||||
`
|
||||
|
||||
type StatusPageMonitorsRow struct {
|
||||
MonitorID uuid.UUID
|
||||
Section string
|
||||
GroupID *uuid.UUID
|
||||
Label string
|
||||
Position int32
|
||||
MonitorName string
|
||||
Enabled bool
|
||||
MonitorGroupID *uuid.UUID
|
||||
MonitorID uuid.UUID
|
||||
Section string
|
||||
GroupID *uuid.UUID
|
||||
Label string
|
||||
Position int32
|
||||
MonitorName string
|
||||
Enabled bool
|
||||
MonitorGroupID *uuid.UUID
|
||||
MonitorType string
|
||||
IntervalSeconds int32
|
||||
}
|
||||
|
||||
func (q *Queries) StatusPageMonitors(ctx context.Context, pageID uuid.UUID) ([]StatusPageMonitorsRow, error) {
|
||||
@@ -450,6 +626,8 @@ func (q *Queries) StatusPageMonitors(ctx context.Context, pageID uuid.UUID) ([]S
|
||||
&i.MonitorName,
|
||||
&i.Enabled,
|
||||
&i.MonitorGroupID,
|
||||
&i.MonitorType,
|
||||
&i.IntervalSeconds,
|
||||
); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -461,6 +639,18 @@ func (q *Queries) StatusPageMonitors(ctx context.Context, pageID uuid.UUID) ([]S
|
||||
return items, nil
|
||||
}
|
||||
|
||||
const unverifyDomain = `-- name: UnverifyDomain :exec
|
||||
UPDATE status_pages SET
|
||||
domain_verified_at = NULL, domain_verify_method = NULL, domain_failing_since = NULL
|
||||
WHERE id = $1
|
||||
`
|
||||
|
||||
// A verified domain whose record stayed missing past the grace period.
|
||||
func (q *Queries) UnverifyDomain(ctx context.Context, id uuid.UUID) error {
|
||||
_, err := q.db.Exec(ctx, unverifyDomain, id)
|
||||
return err
|
||||
}
|
||||
|
||||
const updateStatusPage = `-- name: UpdateStatusPage :one
|
||||
UPDATE status_pages
|
||||
SET slug = $2,
|
||||
@@ -469,9 +659,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
|
||||
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 {
|
||||
@@ -482,6 +673,7 @@ type UpdateStatusPageParams struct {
|
||||
Published bool
|
||||
ShowComponentDetails bool
|
||||
Theme []byte
|
||||
Subscriptions bool
|
||||
}
|
||||
|
||||
func (q *Queries) UpdateStatusPage(ctx context.Context, arg UpdateStatusPageParams) (StatusPage, error) {
|
||||
@@ -493,6 +685,7 @@ func (q *Queries) UpdateStatusPage(ctx context.Context, arg UpdateStatusPagePara
|
||||
arg.Published,
|
||||
arg.ShowComponentDetails,
|
||||
arg.Theme,
|
||||
arg.Subscriptions,
|
||||
)
|
||||
var i StatusPage
|
||||
err := row.Scan(
|
||||
@@ -511,6 +704,11 @@ func (q *Queries) UpdateStatusPage(ctx context.Context, arg UpdateStatusPagePara
|
||||
&i.ShowComponentDetails,
|
||||
&i.SuspendedAt,
|
||||
&i.SuspendedReason,
|
||||
&i.DomainSetAt,
|
||||
&i.DomainCheckedAt,
|
||||
&i.DomainFailingSince,
|
||||
&i.DomainVerifyMethod,
|
||||
&i.Subscriptions,
|
||||
)
|
||||
return i, err
|
||||
}
|
||||
|
||||
@@ -0,0 +1,442 @@
|
||||
// Code generated by sqlc. DO NOT EDIT.
|
||||
// versions:
|
||||
// sqlc v1.31.1
|
||||
// source: subscribers.sql
|
||||
|
||||
package store
|
||||
|
||||
import (
|
||||
"context"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
const claimSubscriberNotifications = `-- name: ClaimSubscriberNotifications :many
|
||||
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 $1
|
||||
FOR UPDATE SKIP LOCKED
|
||||
)
|
||||
RETURNING id
|
||||
`
|
||||
|
||||
// System scope; leased like ClaimNotifications.
|
||||
func (q *Queries) ClaimSubscriberNotifications(ctx context.Context, max int32) ([]uuid.UUID, error) {
|
||||
rows, err := q.db.Query(ctx, claimSubscriberNotifications, max)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
items := []uuid.UUID{}
|
||||
for rows.Next() {
|
||||
var id uuid.UUID
|
||||
if err := rows.Scan(&id); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
items = append(items, id)
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return items, nil
|
||||
}
|
||||
|
||||
const confirmPageSubscriber = `-- name: ConfirmPageSubscriber :exec
|
||||
UPDATE status_page_subscribers SET confirmed_at = coalesce(confirmed_at, now()) WHERE id = $1
|
||||
`
|
||||
|
||||
func (q *Queries) ConfirmPageSubscriber(ctx context.Context, id uuid.UUID) error {
|
||||
_, err := q.db.Exec(ctx, confirmPageSubscriber, id)
|
||||
return err
|
||||
}
|
||||
|
||||
const countPageSubscribers = `-- 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
|
||||
`
|
||||
|
||||
type CountPageSubscribersRow struct {
|
||||
Confirmed int32
|
||||
Pending int32
|
||||
}
|
||||
|
||||
func (q *Queries) CountPageSubscribers(ctx context.Context, pageID uuid.UUID) (CountPageSubscribersRow, error) {
|
||||
row := q.db.QueryRow(ctx, countPageSubscribers, pageID)
|
||||
var i CountPageSubscribersRow
|
||||
err := row.Scan(&i.Confirmed, &i.Pending)
|
||||
return i, err
|
||||
}
|
||||
|
||||
const countRecentSubscribers = `-- name: CountRecentSubscribers :one
|
||||
SELECT count(*) FROM status_page_subscribers WHERE org_id = $1 AND created_at > $2
|
||||
`
|
||||
|
||||
type CountRecentSubscribersParams struct {
|
||||
OrgID uuid.UUID
|
||||
CreatedAt time.Time
|
||||
}
|
||||
|
||||
// Subscriptions the organization's pages gained since $2, confirmed or
|
||||
// not, for the weekly limit.
|
||||
func (q *Queries) CountRecentSubscribers(ctx context.Context, arg CountRecentSubscribersParams) (int64, error) {
|
||||
row := q.db.QueryRow(ctx, countRecentSubscribers, arg.OrgID, arg.CreatedAt)
|
||||
var count int64
|
||||
err := row.Scan(&count)
|
||||
return count, err
|
||||
}
|
||||
|
||||
const createPageSubscriber = `-- name: CreatePageSubscriber :one
|
||||
INSERT INTO status_page_subscribers (org_id, page_id, email, locale, page_url)
|
||||
VALUES ($1, $2, $3, $4, $5)
|
||||
RETURNING id, org_id, page_id, email, locale, page_url, created_at, confirmed_at
|
||||
`
|
||||
|
||||
type CreatePageSubscriberParams struct {
|
||||
OrgID uuid.UUID
|
||||
PageID uuid.UUID
|
||||
Email string
|
||||
Locale string
|
||||
PageUrl string
|
||||
}
|
||||
|
||||
func (q *Queries) CreatePageSubscriber(ctx context.Context, arg CreatePageSubscriberParams) (StatusPageSubscriber, error) {
|
||||
row := q.db.QueryRow(ctx, createPageSubscriber,
|
||||
arg.OrgID,
|
||||
arg.PageID,
|
||||
arg.Email,
|
||||
arg.Locale,
|
||||
arg.PageUrl,
|
||||
)
|
||||
var i StatusPageSubscriber
|
||||
err := row.Scan(
|
||||
&i.ID,
|
||||
&i.OrgID,
|
||||
&i.PageID,
|
||||
&i.Email,
|
||||
&i.Locale,
|
||||
&i.PageUrl,
|
||||
&i.CreatedAt,
|
||||
&i.ConfirmedAt,
|
||||
)
|
||||
return i, err
|
||||
}
|
||||
|
||||
const deletePageSubscriber = `-- name: DeletePageSubscriber :execrows
|
||||
DELETE FROM status_page_subscribers WHERE id = $1 AND page_id = $2
|
||||
`
|
||||
|
||||
type DeletePageSubscriberParams struct {
|
||||
ID uuid.UUID
|
||||
PageID uuid.UUID
|
||||
}
|
||||
|
||||
func (q *Queries) DeletePageSubscriber(ctx context.Context, arg DeletePageSubscriberParams) (int64, error) {
|
||||
result, err := q.db.Exec(ctx, deletePageSubscriber, arg.ID, arg.PageID)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
return result.RowsAffected(), nil
|
||||
}
|
||||
|
||||
const enqueueSubscriberNotifications = `-- name: EnqueueSubscriberNotifications :execrows
|
||||
INSERT INTO subscriber_notifications (org_id, subscriber_id, incident_id, update_id, event)
|
||||
SELECT s.org_id, s.id, i.id, $1::uuid, $2
|
||||
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 = $3 AND s.confirmed_at IS NOT NULL
|
||||
AND p.published AND p.subscriptions AND p.suspended_at IS NULL
|
||||
ON CONFLICT DO NOTHING
|
||||
`
|
||||
|
||||
type EnqueueSubscriberNotificationsParams struct {
|
||||
UpdateID *uuid.UUID
|
||||
Event string
|
||||
IncidentID uuid.UUID
|
||||
}
|
||||
|
||||
// Queues the event of incident for every confirmed subscriber of the
|
||||
// published pages showing its monitor that take subscriptions.
|
||||
func (q *Queries) EnqueueSubscriberNotifications(ctx context.Context, arg EnqueueSubscriberNotificationsParams) (int64, error) {
|
||||
result, err := q.db.Exec(ctx, enqueueSubscriberNotifications, arg.UpdateID, arg.Event, arg.IncidentID)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
return result.RowsAffected(), nil
|
||||
}
|
||||
|
||||
const getPageSubscriber = `-- name: GetPageSubscriber :one
|
||||
SELECT s.id, s.org_id, s.page_id, s.email, s.locale, s.page_url, s.created_at, s.confirmed_at, p.title AS page_title FROM status_page_subscribers s
|
||||
JOIN status_pages p ON p.id = s.page_id
|
||||
WHERE s.id = $1
|
||||
`
|
||||
|
||||
type GetPageSubscriberRow struct {
|
||||
ID uuid.UUID
|
||||
OrgID uuid.UUID
|
||||
PageID uuid.UUID
|
||||
Email string
|
||||
Locale string
|
||||
PageUrl string
|
||||
CreatedAt time.Time
|
||||
ConfirmedAt *time.Time
|
||||
PageTitle string
|
||||
}
|
||||
|
||||
func (q *Queries) GetPageSubscriber(ctx context.Context, id uuid.UUID) (GetPageSubscriberRow, error) {
|
||||
row := q.db.QueryRow(ctx, getPageSubscriber, id)
|
||||
var i GetPageSubscriberRow
|
||||
err := row.Scan(
|
||||
&i.ID,
|
||||
&i.OrgID,
|
||||
&i.PageID,
|
||||
&i.Email,
|
||||
&i.Locale,
|
||||
&i.PageUrl,
|
||||
&i.CreatedAt,
|
||||
&i.ConfirmedAt,
|
||||
&i.PageTitle,
|
||||
)
|
||||
return i, err
|
||||
}
|
||||
|
||||
const getPageSubscriberByEmail = `-- name: GetPageSubscriberByEmail :one
|
||||
SELECT id, org_id, page_id, email, locale, page_url, created_at, confirmed_at FROM status_page_subscribers WHERE page_id = $1 AND email = $2
|
||||
`
|
||||
|
||||
type GetPageSubscriberByEmailParams struct {
|
||||
PageID uuid.UUID
|
||||
Email string
|
||||
}
|
||||
|
||||
func (q *Queries) GetPageSubscriberByEmail(ctx context.Context, arg GetPageSubscriberByEmailParams) (StatusPageSubscriber, error) {
|
||||
row := q.db.QueryRow(ctx, getPageSubscriberByEmail, arg.PageID, arg.Email)
|
||||
var i StatusPageSubscriber
|
||||
err := row.Scan(
|
||||
&i.ID,
|
||||
&i.OrgID,
|
||||
&i.PageID,
|
||||
&i.Email,
|
||||
&i.Locale,
|
||||
&i.PageUrl,
|
||||
&i.CreatedAt,
|
||||
&i.ConfirmedAt,
|
||||
)
|
||||
return i, err
|
||||
}
|
||||
|
||||
const listPageSubscribers = `-- name: ListPageSubscribers :many
|
||||
SELECT id, email, locale, created_at, confirmed_at FROM status_page_subscribers
|
||||
WHERE page_id = $1
|
||||
ORDER BY created_at DESC, id
|
||||
LIMIT $2
|
||||
`
|
||||
|
||||
type ListPageSubscribersParams struct {
|
||||
PageID uuid.UUID
|
||||
MaxRows int32
|
||||
}
|
||||
|
||||
type ListPageSubscribersRow struct {
|
||||
ID uuid.UUID
|
||||
Email string
|
||||
Locale string
|
||||
CreatedAt time.Time
|
||||
ConfirmedAt *time.Time
|
||||
}
|
||||
|
||||
// The newest subscribers of a page first.
|
||||
func (q *Queries) ListPageSubscribers(ctx context.Context, arg ListPageSubscribersParams) ([]ListPageSubscribersRow, error) {
|
||||
rows, err := q.db.Query(ctx, listPageSubscribers, arg.PageID, arg.MaxRows)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
items := []ListPageSubscribersRow{}
|
||||
for rows.Next() {
|
||||
var i ListPageSubscribersRow
|
||||
if err := rows.Scan(
|
||||
&i.ID,
|
||||
&i.Email,
|
||||
&i.Locale,
|
||||
&i.CreatedAt,
|
||||
&i.ConfirmedAt,
|
||||
); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
items = append(items, i)
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return items, nil
|
||||
}
|
||||
|
||||
const markSubscriberNotificationFailed = `-- name: MarkSubscriberNotificationFailed :exec
|
||||
UPDATE subscriber_notifications SET attempts = attempts + 1, last_error = $1,
|
||||
status = CASE WHEN attempts + 1 >= $2::int THEN 'failed' ELSE 'pending' END,
|
||||
next_attempt_at = now() + make_interval(secs => $3::int)
|
||||
WHERE id = $4
|
||||
`
|
||||
|
||||
type MarkSubscriberNotificationFailedParams struct {
|
||||
LastError *string
|
||||
MaxAttempts int32
|
||||
RetryInSeconds int32
|
||||
ID uuid.UUID
|
||||
}
|
||||
|
||||
func (q *Queries) MarkSubscriberNotificationFailed(ctx context.Context, arg MarkSubscriberNotificationFailedParams) error {
|
||||
_, err := q.db.Exec(ctx, markSubscriberNotificationFailed,
|
||||
arg.LastError,
|
||||
arg.MaxAttempts,
|
||||
arg.RetryInSeconds,
|
||||
arg.ID,
|
||||
)
|
||||
return err
|
||||
}
|
||||
|
||||
const markSubscriberNotificationSent = `-- name: MarkSubscriberNotificationSent :exec
|
||||
UPDATE subscriber_notifications SET status = 'sent', sent_at = now(), attempts = attempts + 1, last_error = NULL
|
||||
WHERE id = $1
|
||||
`
|
||||
|
||||
func (q *Queries) MarkSubscriberNotificationSent(ctx context.Context, id uuid.UUID) error {
|
||||
_, err := q.db.Exec(ctx, markSubscriberNotificationSent, id)
|
||||
return err
|
||||
}
|
||||
|
||||
const purgeSubscriberNotifications = `-- name: PurgeSubscriberNotifications :execrows
|
||||
DELETE FROM subscriber_notifications WHERE status IN ('sent', 'failed') AND created_at < $1
|
||||
`
|
||||
|
||||
func (q *Queries) PurgeSubscriberNotifications(ctx context.Context, createdAt time.Time) (int64, error) {
|
||||
result, err := q.db.Exec(ctx, purgeSubscriberNotifications, createdAt)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
return result.RowsAffected(), nil
|
||||
}
|
||||
|
||||
const purgeUnconfirmedSubscribers = `-- name: PurgeUnconfirmedSubscribers :execrows
|
||||
DELETE FROM status_page_subscribers WHERE confirmed_at IS NULL AND created_at < $1
|
||||
`
|
||||
|
||||
// Unconfirmed subscriptions are kept for as long as they count towards the
|
||||
// weekly limit, so letting them lapse frees no room for more.
|
||||
func (q *Queries) PurgeUnconfirmedSubscribers(ctx context.Context, createdAt time.Time) (int64, error) {
|
||||
result, err := q.db.Exec(ctx, purgeUnconfirmedSubscribers, createdAt)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
return result.RowsAffected(), nil
|
||||
}
|
||||
|
||||
const subscriberNotificationDetails = `-- name: SubscriberNotificationDetails :many
|
||||
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 ($1::uuid[])
|
||||
`
|
||||
|
||||
type SubscriberNotificationDetailsRow struct {
|
||||
ID uuid.UUID
|
||||
Event string
|
||||
Attempts int32
|
||||
SubscriberID uuid.UUID
|
||||
Email string
|
||||
Locale string
|
||||
PageUrl string
|
||||
PageID uuid.UUID
|
||||
Slug string
|
||||
PageTitle string
|
||||
CustomDomain *string
|
||||
DomainVerifiedAt *time.Time
|
||||
OwnServers bool
|
||||
StartedAt time.Time
|
||||
ResolvedAt *time.Time
|
||||
IncidentTitle string
|
||||
Component string
|
||||
UpdateStatus string
|
||||
UpdateStatusName string
|
||||
UpdateMessage string
|
||||
}
|
||||
|
||||
// System scope: what a mail to a subscriber says.
|
||||
func (q *Queries) SubscriberNotificationDetails(ctx context.Context, ids []uuid.UUID) ([]SubscriberNotificationDetailsRow, error) {
|
||||
rows, err := q.db.Query(ctx, subscriberNotificationDetails, ids)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
items := []SubscriberNotificationDetailsRow{}
|
||||
for rows.Next() {
|
||||
var i SubscriberNotificationDetailsRow
|
||||
if err := rows.Scan(
|
||||
&i.ID,
|
||||
&i.Event,
|
||||
&i.Attempts,
|
||||
&i.SubscriberID,
|
||||
&i.Email,
|
||||
&i.Locale,
|
||||
&i.PageUrl,
|
||||
&i.PageID,
|
||||
&i.Slug,
|
||||
&i.PageTitle,
|
||||
&i.CustomDomain,
|
||||
&i.DomainVerifiedAt,
|
||||
&i.OwnServers,
|
||||
&i.StartedAt,
|
||||
&i.ResolvedAt,
|
||||
&i.IncidentTitle,
|
||||
&i.Component,
|
||||
&i.UpdateStatus,
|
||||
&i.UpdateStatusName,
|
||||
&i.UpdateMessage,
|
||||
); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
items = append(items, i)
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return items, nil
|
||||
}
|
||||
|
||||
const touchPendingSubscriber = `-- name: TouchPendingSubscriber :exec
|
||||
UPDATE status_page_subscribers SET locale = $2, page_url = $3
|
||||
WHERE id = $1 AND confirmed_at IS NULL
|
||||
`
|
||||
|
||||
type TouchPendingSubscriberParams struct {
|
||||
ID uuid.UUID
|
||||
Locale string
|
||||
PageUrl string
|
||||
}
|
||||
|
||||
// Keeps a pending subscription's language and link current when the
|
||||
// visitor asks again.
|
||||
func (q *Queries) TouchPendingSubscriber(ctx context.Context, arg TouchPendingSubscriberParams) error {
|
||||
_, err := q.db.Exec(ctx, touchPendingSubscriber, arg.ID, arg.Locale, arg.PageUrl)
|
||||
return err
|
||||
}
|
||||
@@ -14,6 +14,8 @@ type LimitsView struct {
|
||||
RegionsPerMonitor int
|
||||
OwnRegionsCount bool
|
||||
OrgsPerAccount int
|
||||
MonitorsPerPage int
|
||||
SubscribersPerWeek int
|
||||
}
|
||||
|
||||
// OrgsView lists organizations for platform admins.
|
||||
@@ -36,6 +38,8 @@ type OrgRow struct {
|
||||
StatusPagesOverride string
|
||||
RegionsOverride string
|
||||
OwnRegionsOverride string
|
||||
PerPageOverride string
|
||||
SubscribersOverride string
|
||||
Owner *ModeratedTarget
|
||||
OwnerOrgs int
|
||||
OwnerOrgLimit string
|
||||
@@ -62,6 +66,8 @@ templ limitsSection(d LimitsView) {
|
||||
@numberField(i18n.T(ctx, "limits.status_pages"), "status_pages", d.StatusPages, 0, 1000000, "")
|
||||
@numberField(i18n.T(ctx, "limits.regions_per_monitor"), "regions_per_monitor", d.RegionsPerMonitor, 0, 1000, "")
|
||||
@numberField(i18n.T(ctx, "limits.orgs_per_account"), "orgs_per_account", d.OrgsPerAccount, 0, 100000, "")
|
||||
@numberField(i18n.T(ctx, "limits.monitors_per_page"), "monitors_per_page", d.MonitorsPerPage, 0, 1000000, "")
|
||||
@numberField(i18n.T(ctx, "limits.subscribers_per_week"), "subscribers_per_week", d.SubscribersPerWeek, 0, 100000000, "")
|
||||
</div>
|
||||
@checkbox(i18n.T(ctx, "limits.own_regions_count"), "own_regions_count", d.OwnRegionsCount)
|
||||
<p class="mb-4 ml-6 text-xs text-muted">{ i18n.T(ctx, "limits.own_regions_count_hint") }</p>
|
||||
@@ -149,6 +155,8 @@ templ orgsSection(v OrgsView) {
|
||||
@overrideField(i18n.T(ctx, "limits.monitors"), "monitors", o.MonitorsOverride, v.Defaults.Monitors, 1000000)
|
||||
@overrideField(i18n.T(ctx, "limits.status_pages"), "status_pages", o.StatusPagesOverride, v.Defaults.StatusPages, 1000000)
|
||||
@overrideField(i18n.T(ctx, "limits.regions_per_monitor"), "regions_per_monitor", o.RegionsOverride, v.Defaults.RegionsPerMonitor, 1000)
|
||||
@overrideField(i18n.T(ctx, "limits.monitors_per_page"), "monitors_per_page", o.PerPageOverride, v.Defaults.MonitorsPerPage, 1000000)
|
||||
@overrideField(i18n.T(ctx, "limits.subscribers_per_week"), "subscribers_per_week", o.SubscribersOverride, v.Defaults.SubscribersPerWeek, 100000000)
|
||||
<label class="mb-3 block">
|
||||
<span class="mb-1 block text-xs font-medium uppercase tracking-wider text-muted">{ i18n.T(ctx, "limits.own_regions_count") }</span>
|
||||
<select name="own_regions_count" class="w-full border border-rule bg-transparent px-2 py-1 text-sm">
|
||||
@@ -207,6 +215,10 @@ templ usageSection(u UsageView) {
|
||||
<dd class="font-mono text-xs">@usage(u.StatusPages, u.Limits.StatusPages)</dd>
|
||||
<dt>{ i18n.T(ctx, "limits.regions_per_monitor") }</dt>
|
||||
<dd class="font-mono text-xs">{ limitText(ctx, u.Limits.RegionsPerMonitor) }</dd>
|
||||
<dt>{ i18n.T(ctx, "limits.monitors_per_page") }</dt>
|
||||
<dd class="font-mono text-xs">{ limitText(ctx, u.Limits.MonitorsPerPage) }</dd>
|
||||
<dt>{ i18n.T(ctx, "limits.subscribers_per_week") }</dt>
|
||||
<dd class="font-mono text-xs">{ limitText(ctx, u.Limits.SubscribersPerWeek) }</dd>
|
||||
</dl>
|
||||
if u.Limits.RegionsPerMonitor > 0 && !u.Limits.OwnRegionsCount {
|
||||
<p class="mt-2 text-xs text-muted">{ i18n.T(ctx, "limits.own_regions_free") }</p>
|
||||
|
||||
@@ -18,11 +18,13 @@ import (
|
||||
|
||||
// LimitsView holds limits; 0 means unlimited.
|
||||
type LimitsView struct {
|
||||
Monitors int
|
||||
StatusPages int
|
||||
RegionsPerMonitor int
|
||||
OwnRegionsCount bool
|
||||
OrgsPerAccount int
|
||||
Monitors int
|
||||
StatusPages int
|
||||
RegionsPerMonitor int
|
||||
OwnRegionsCount bool
|
||||
OrgsPerAccount int
|
||||
MonitorsPerPage int
|
||||
SubscribersPerWeek int
|
||||
}
|
||||
|
||||
// OrgsView lists organizations for platform admins.
|
||||
@@ -45,6 +47,8 @@ type OrgRow struct {
|
||||
StatusPagesOverride string
|
||||
RegionsOverride string
|
||||
OwnRegionsOverride string
|
||||
PerPageOverride string
|
||||
SubscribersOverride string
|
||||
Owner *ModeratedTarget
|
||||
OwnerOrgs int
|
||||
OwnerOrgLimit string
|
||||
@@ -92,7 +96,7 @@ func limitsSection(d LimitsView) templ.Component {
|
||||
var templ_7745c5c3_Var2 string
|
||||
templ_7745c5c3_Var2, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, "limits.intro"))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/admin_orgs.templ`, Line: 57, Col: 66}
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/admin_orgs.templ`, Line: 61, Col: 66}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var2))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
@@ -126,6 +130,14 @@ func limitsSection(d LimitsView) templ.Component {
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
templ_7745c5c3_Err = numberField(i18n.T(ctx, "limits.monitors_per_page"), "monitors_per_page", d.MonitorsPerPage, 0, 1000000, "").Render(ctx, templ_7745c5c3_Buffer)
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
templ_7745c5c3_Err = numberField(i18n.T(ctx, "limits.subscribers_per_week"), "subscribers_per_week", d.SubscribersPerWeek, 0, 100000000, "").Render(ctx, templ_7745c5c3_Buffer)
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 5, "</div>")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
@@ -141,7 +153,7 @@ func limitsSection(d LimitsView) templ.Component {
|
||||
var templ_7745c5c3_Var3 string
|
||||
templ_7745c5c3_Var3, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, "limits.own_regions_count_hint"))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/admin_orgs.templ`, Line: 67, Col: 89}
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/admin_orgs.templ`, Line: 73, Col: 89}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var3))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
@@ -154,7 +166,7 @@ func limitsSection(d LimitsView) templ.Component {
|
||||
var templ_7745c5c3_Var4 string
|
||||
templ_7745c5c3_Var4, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, "common.save"))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/admin_orgs.templ`, Line: 68, Col: 129}
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/admin_orgs.templ`, Line: 74, Col: 129}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var4))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
@@ -194,7 +206,7 @@ func overrideField(label, name, value string, def int, max int) templ.Component
|
||||
var templ_7745c5c3_Var6 string
|
||||
templ_7745c5c3_Var6, templ_7745c5c3_Err = templ.JoinStringErrs(label)
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/admin_orgs.templ`, Line: 77, Col: 90}
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/admin_orgs.templ`, Line: 83, Col: 90}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var6))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
@@ -207,7 +219,7 @@ func overrideField(label, name, value string, def int, max int) templ.Component
|
||||
var templ_7745c5c3_Var7 string
|
||||
templ_7745c5c3_Var7, templ_7745c5c3_Err = templruntime.NewAttributeExpression(name).Resolve(ctx)
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/admin_orgs.templ`, Line: 80, Col: 14}
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/admin_orgs.templ`, Line: 86, Col: 14}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ_7745c5c3_Var7)
|
||||
if templ_7745c5c3_Err != nil {
|
||||
@@ -220,7 +232,7 @@ func overrideField(label, name, value string, def int, max int) templ.Component
|
||||
var templ_7745c5c3_Var8 string
|
||||
templ_7745c5c3_Var8, templ_7745c5c3_Err = templruntime.NewAttributeExpression(strconv.Itoa(max)).Resolve(ctx)
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/admin_orgs.templ`, Line: 84, Col: 26}
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/admin_orgs.templ`, Line: 90, Col: 26}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ_7745c5c3_Var8)
|
||||
if templ_7745c5c3_Err != nil {
|
||||
@@ -233,7 +245,7 @@ func overrideField(label, name, value string, def int, max int) templ.Component
|
||||
var templ_7745c5c3_Var9 string
|
||||
templ_7745c5c3_Var9, templ_7745c5c3_Err = templruntime.NewAttributeExpression(value).Resolve(ctx)
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/admin_orgs.templ`, Line: 85, Col: 16}
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/admin_orgs.templ`, Line: 91, Col: 16}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ_7745c5c3_Var9)
|
||||
if templ_7745c5c3_Err != nil {
|
||||
@@ -246,7 +258,7 @@ func overrideField(label, name, value string, def int, max int) templ.Component
|
||||
var templ_7745c5c3_Var10 string
|
||||
templ_7745c5c3_Var10, templ_7745c5c3_Err = templruntime.NewAttributeExpression(i18n.T(ctx, "limits.default", "Value", limitText(ctx, def))).Resolve(ctx)
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/admin_orgs.templ`, Line: 86, Col: 76}
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/admin_orgs.templ`, Line: 92, Col: 76}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ_7745c5c3_Var10)
|
||||
if templ_7745c5c3_Err != nil {
|
||||
@@ -292,7 +304,7 @@ func orgsSection(v OrgsView) templ.Component {
|
||||
var templ_7745c5c3_Var12 string
|
||||
templ_7745c5c3_Var12, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, "orgs.intro"))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/admin_orgs.templ`, Line: 95, Col: 74}
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/admin_orgs.templ`, Line: 101, Col: 74}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var12))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
@@ -305,7 +317,7 @@ func orgsSection(v OrgsView) templ.Component {
|
||||
var templ_7745c5c3_Var13 string
|
||||
templ_7745c5c3_Var13, templ_7745c5c3_Err = templruntime.NewAttributeExpression(v.Search).Resolve(ctx)
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/admin_orgs.templ`, Line: 100, Col: 20}
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/admin_orgs.templ`, Line: 106, Col: 20}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ_7745c5c3_Var13)
|
||||
if templ_7745c5c3_Err != nil {
|
||||
@@ -318,7 +330,7 @@ func orgsSection(v OrgsView) templ.Component {
|
||||
var templ_7745c5c3_Var14 string
|
||||
templ_7745c5c3_Var14, templ_7745c5c3_Err = templruntime.NewAttributeExpression(i18n.T(ctx, "orgs.search")).Resolve(ctx)
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/admin_orgs.templ`, Line: 101, Col: 44}
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/admin_orgs.templ`, Line: 107, Col: 44}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ_7745c5c3_Var14)
|
||||
if templ_7745c5c3_Err != nil {
|
||||
@@ -331,7 +343,7 @@ func orgsSection(v OrgsView) templ.Component {
|
||||
var templ_7745c5c3_Var15 string
|
||||
templ_7745c5c3_Var15, templ_7745c5c3_Err = templruntime.NewAttributeExpression(i18n.T(ctx, "orgs.search")).Resolve(ctx)
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/admin_orgs.templ`, Line: 102, Col: 43}
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/admin_orgs.templ`, Line: 108, Col: 43}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ_7745c5c3_Var15)
|
||||
if templ_7745c5c3_Err != nil {
|
||||
@@ -344,7 +356,7 @@ func orgsSection(v OrgsView) templ.Component {
|
||||
var templ_7745c5c3_Var16 string
|
||||
templ_7745c5c3_Var16, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, "moderation.search_button"))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/admin_orgs.templ`, Line: 105, Col: 142}
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/admin_orgs.templ`, Line: 111, Col: 142}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var16))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
@@ -362,7 +374,7 @@ func orgsSection(v OrgsView) templ.Component {
|
||||
var templ_7745c5c3_Var17 string
|
||||
templ_7745c5c3_Var17, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, "orgs.none"))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/admin_orgs.templ`, Line: 108, Col: 59}
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/admin_orgs.templ`, Line: 114, Col: 59}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var17))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
@@ -380,7 +392,7 @@ func orgsSection(v OrgsView) templ.Component {
|
||||
var templ_7745c5c3_Var18 string
|
||||
templ_7745c5c3_Var18, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, "moderation.org"))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/admin_orgs.templ`, Line: 114, Col: 72}
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/admin_orgs.templ`, Line: 120, Col: 72}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var18))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
@@ -393,7 +405,7 @@ func orgsSection(v OrgsView) templ.Component {
|
||||
var templ_7745c5c3_Var19 string
|
||||
templ_7745c5c3_Var19, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, "moderation.owner"))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/admin_orgs.templ`, Line: 115, Col: 74}
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/admin_orgs.templ`, Line: 121, Col: 74}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var19))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
@@ -406,7 +418,7 @@ func orgsSection(v OrgsView) templ.Component {
|
||||
var templ_7745c5c3_Var20 string
|
||||
templ_7745c5c3_Var20, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, "limits.monitors"))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/admin_orgs.templ`, Line: 116, Col: 73}
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/admin_orgs.templ`, Line: 122, Col: 73}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var20))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
@@ -419,7 +431,7 @@ func orgsSection(v OrgsView) templ.Component {
|
||||
var templ_7745c5c3_Var21 string
|
||||
templ_7745c5c3_Var21, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, "limits.status_pages"))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/admin_orgs.templ`, Line: 117, Col: 77}
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/admin_orgs.templ`, Line: 123, Col: 77}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var21))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
@@ -432,7 +444,7 @@ func orgsSection(v OrgsView) templ.Component {
|
||||
var templ_7745c5c3_Var22 string
|
||||
templ_7745c5c3_Var22, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, "moderation.created"))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/admin_orgs.templ`, Line: 118, Col: 76}
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/admin_orgs.templ`, Line: 124, Col: 76}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var22))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
@@ -450,7 +462,7 @@ func orgsSection(v OrgsView) templ.Component {
|
||||
var templ_7745c5c3_Var23 string
|
||||
templ_7745c5c3_Var23, templ_7745c5c3_Err = templ.JoinStringErrs(o.Name)
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/admin_orgs.templ`, Line: 125, Col: 17}
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/admin_orgs.templ`, Line: 131, Col: 17}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var23))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
@@ -463,7 +475,7 @@ func orgsSection(v OrgsView) templ.Component {
|
||||
var templ_7745c5c3_Var24 string
|
||||
templ_7745c5c3_Var24, templ_7745c5c3_Err = templ.JoinStringErrs(o.Slug)
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/admin_orgs.templ`, Line: 126, Col: 66}
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/admin_orgs.templ`, Line: 132, Col: 66}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var24))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
@@ -489,7 +501,7 @@ func orgsSection(v OrgsView) templ.Component {
|
||||
var templ_7745c5c3_Var25 string
|
||||
templ_7745c5c3_Var25, templ_7745c5c3_Err = templ.JoinStringErrs(o.Owner.Name)
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/admin_orgs.templ`, Line: 131, Col: 48}
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/admin_orgs.templ`, Line: 137, Col: 48}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var25))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
@@ -532,7 +544,7 @@ func orgsSection(v OrgsView) templ.Component {
|
||||
var templ_7745c5c3_Var26 string
|
||||
templ_7745c5c3_Var26, templ_7745c5c3_Err = templ.JoinStringErrs(o.Created)
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/admin_orgs.templ`, Line: 139, Col: 72}
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/admin_orgs.templ`, Line: 145, Col: 72}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var26))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
@@ -545,7 +557,7 @@ func orgsSection(v OrgsView) templ.Component {
|
||||
var templ_7745c5c3_Var27 string
|
||||
templ_7745c5c3_Var27, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, "orgs.manage"))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/admin_orgs.templ`, Line: 144, Col: 96}
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/admin_orgs.templ`, Line: 150, Col: 96}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var27))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
@@ -558,7 +570,7 @@ func orgsSection(v OrgsView) templ.Component {
|
||||
var templ_7745c5c3_Var28 string
|
||||
templ_7745c5c3_Var28, templ_7745c5c3_Err = templruntime.NewAttributeExpression("/admin/orgs/" + o.ID + "/limits").Resolve(ctx)
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/admin_orgs.templ`, Line: 146, Col: 61}
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/admin_orgs.templ`, Line: 152, Col: 61}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ_7745c5c3_Var28)
|
||||
if templ_7745c5c3_Err != nil {
|
||||
@@ -571,7 +583,7 @@ func orgsSection(v OrgsView) templ.Component {
|
||||
var templ_7745c5c3_Var29 string
|
||||
templ_7745c5c3_Var29, templ_7745c5c3_Err = templruntime.NewAttributeExpression(v.next()).Resolve(ctx)
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/admin_orgs.templ`, Line: 146, Col: 102}
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/admin_orgs.templ`, Line: 152, Col: 102}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ_7745c5c3_Var29)
|
||||
if templ_7745c5c3_Err != nil {
|
||||
@@ -584,7 +596,7 @@ func orgsSection(v OrgsView) templ.Component {
|
||||
var templ_7745c5c3_Var30 string
|
||||
templ_7745c5c3_Var30, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, "orgs.limits"))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/admin_orgs.templ`, Line: 147, Col: 113}
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/admin_orgs.templ`, Line: 153, Col: 113}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var30))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
@@ -610,6 +622,14 @@ func orgsSection(v OrgsView) templ.Component {
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
templ_7745c5c3_Err = overrideField(i18n.T(ctx, "limits.monitors_per_page"), "monitors_per_page", o.PerPageOverride, v.Defaults.MonitorsPerPage, 1000000).Render(ctx, templ_7745c5c3_Buffer)
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
templ_7745c5c3_Err = overrideField(i18n.T(ctx, "limits.subscribers_per_week"), "subscribers_per_week", o.SubscribersOverride, v.Defaults.SubscribersPerWeek, 100000000).Render(ctx, templ_7745c5c3_Buffer)
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 45, "<label class=\"mb-3 block\"><span class=\"mb-1 block text-xs font-medium uppercase tracking-wider text-muted\">")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
@@ -617,7 +637,7 @@ func orgsSection(v OrgsView) templ.Component {
|
||||
var templ_7745c5c3_Var31 string
|
||||
templ_7745c5c3_Var31, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, "limits.own_regions_count"))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/admin_orgs.templ`, Line: 153, Col: 135}
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/admin_orgs.templ`, Line: 161, Col: 135}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var31))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
@@ -640,7 +660,7 @@ func orgsSection(v OrgsView) templ.Component {
|
||||
var templ_7745c5c3_Var32 string
|
||||
templ_7745c5c3_Var32, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, "limits.default", "Value", i18n.T(ctx, "limits.own_"+strconv.FormatBool(v.Defaults.OwnRegionsCount))))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/admin_orgs.templ`, Line: 155, Col: 187}
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/admin_orgs.templ`, Line: 163, Col: 187}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var32))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
@@ -663,7 +683,7 @@ func orgsSection(v OrgsView) templ.Component {
|
||||
var templ_7745c5c3_Var33 string
|
||||
templ_7745c5c3_Var33, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, "limits.own_true"))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/admin_orgs.templ`, Line: 156, Col: 112}
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/admin_orgs.templ`, Line: 164, Col: 112}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var33))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
@@ -686,7 +706,7 @@ func orgsSection(v OrgsView) templ.Component {
|
||||
var templ_7745c5c3_Var34 string
|
||||
templ_7745c5c3_Var34, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, "limits.own_false"))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/admin_orgs.templ`, Line: 157, Col: 115}
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/admin_orgs.templ`, Line: 165, Col: 115}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var34))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
@@ -699,7 +719,7 @@ func orgsSection(v OrgsView) templ.Component {
|
||||
var templ_7745c5c3_Var35 string
|
||||
templ_7745c5c3_Var35, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, "common.save"))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/admin_orgs.templ`, Line: 160, Col: 130}
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/admin_orgs.templ`, Line: 168, Col: 130}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var35))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
@@ -721,7 +741,7 @@ func orgsSection(v OrgsView) templ.Component {
|
||||
var templ_7745c5c3_Var36 string
|
||||
templ_7745c5c3_Var36, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, "moderation.owner_is_admin"))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/admin_orgs.templ`, Line: 164, Col: 84}
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/admin_orgs.templ`, Line: 172, Col: 84}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var36))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
@@ -739,7 +759,7 @@ func orgsSection(v OrgsView) templ.Component {
|
||||
var templ_7745c5c3_Var37 string
|
||||
templ_7745c5c3_Var37, templ_7745c5c3_Err = templruntime.NewAttributeExpression("/admin/users/" + o.Owner.ID + "/limits").Resolve(ctx)
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/admin_orgs.templ`, Line: 167, Col: 70}
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/admin_orgs.templ`, Line: 175, Col: 70}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ_7745c5c3_Var37)
|
||||
if templ_7745c5c3_Err != nil {
|
||||
@@ -752,7 +772,7 @@ func orgsSection(v OrgsView) templ.Component {
|
||||
var templ_7745c5c3_Var38 string
|
||||
templ_7745c5c3_Var38, templ_7745c5c3_Err = templruntime.NewAttributeExpression(v.next()).Resolve(ctx)
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/admin_orgs.templ`, Line: 167, Col: 111}
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/admin_orgs.templ`, Line: 175, Col: 111}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ_7745c5c3_Var38)
|
||||
if templ_7745c5c3_Err != nil {
|
||||
@@ -765,7 +785,7 @@ func orgsSection(v OrgsView) templ.Component {
|
||||
var templ_7745c5c3_Var39 string
|
||||
templ_7745c5c3_Var39, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, "moderation.target_owner"))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/admin_orgs.templ`, Line: 168, Col: 127}
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/admin_orgs.templ`, Line: 176, Col: 127}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var39))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
@@ -790,7 +810,7 @@ func orgsSection(v OrgsView) templ.Component {
|
||||
var templ_7745c5c3_Var40 string
|
||||
templ_7745c5c3_Var40, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, "common.save"))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/admin_orgs.templ`, Line: 171, Col: 132}
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/admin_orgs.templ`, Line: 179, Col: 132}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var40))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
@@ -892,7 +912,7 @@ func usage(used, max int) templ.Component {
|
||||
var templ_7745c5c3_Var44 string
|
||||
templ_7745c5c3_Var44, templ_7745c5c3_Err = templ.JoinStringErrs(strconv.Itoa(used))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/admin_orgs.templ`, Line: 191, Col: 83}
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/admin_orgs.templ`, Line: 199, Col: 83}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var44))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
@@ -905,7 +925,7 @@ func usage(used, max int) templ.Component {
|
||||
var templ_7745c5c3_Var45 string
|
||||
templ_7745c5c3_Var45, templ_7745c5c3_Err = templ.JoinStringErrs(limitText(ctx, max))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/admin_orgs.templ`, Line: 191, Col: 109}
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/admin_orgs.templ`, Line: 199, Col: 109}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var45))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
@@ -957,7 +977,7 @@ func usageSection(u UsageView) templ.Component {
|
||||
var templ_7745c5c3_Var47 string
|
||||
templ_7745c5c3_Var47, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, "limits.monitors"))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/admin_orgs.templ`, Line: 204, Col: 39}
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/admin_orgs.templ`, Line: 212, Col: 39}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var47))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
@@ -978,7 +998,7 @@ func usageSection(u UsageView) templ.Component {
|
||||
var templ_7745c5c3_Var48 string
|
||||
templ_7745c5c3_Var48, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, "limits.status_pages"))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/admin_orgs.templ`, Line: 206, Col: 43}
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/admin_orgs.templ`, Line: 214, Col: 43}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var48))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
@@ -999,7 +1019,7 @@ func usageSection(u UsageView) templ.Component {
|
||||
var templ_7745c5c3_Var49 string
|
||||
templ_7745c5c3_Var49, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, "limits.regions_per_monitor"))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/admin_orgs.templ`, Line: 208, Col: 50}
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/admin_orgs.templ`, Line: 216, Col: 50}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var49))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
@@ -1012,36 +1032,88 @@ func usageSection(u UsageView) templ.Component {
|
||||
var templ_7745c5c3_Var50 string
|
||||
templ_7745c5c3_Var50, templ_7745c5c3_Err = templ.JoinStringErrs(limitText(ctx, u.Limits.RegionsPerMonitor))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/admin_orgs.templ`, Line: 209, Col: 77}
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/admin_orgs.templ`, Line: 217, Col: 77}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var50))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 81, "</dd></dl>")
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 81, "</dd><dt>")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
var templ_7745c5c3_Var51 string
|
||||
templ_7745c5c3_Var51, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, "limits.monitors_per_page"))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/admin_orgs.templ`, Line: 218, Col: 48}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var51))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 82, "</dt><dd class=\"font-mono text-xs\">")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
var templ_7745c5c3_Var52 string
|
||||
templ_7745c5c3_Var52, templ_7745c5c3_Err = templ.JoinStringErrs(limitText(ctx, u.Limits.MonitorsPerPage))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/admin_orgs.templ`, Line: 219, Col: 75}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var52))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 83, "</dd><dt>")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
var templ_7745c5c3_Var53 string
|
||||
templ_7745c5c3_Var53, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, "limits.subscribers_per_week"))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/admin_orgs.templ`, Line: 220, Col: 51}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var53))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 84, "</dt><dd class=\"font-mono text-xs\">")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
var templ_7745c5c3_Var54 string
|
||||
templ_7745c5c3_Var54, templ_7745c5c3_Err = templ.JoinStringErrs(limitText(ctx, u.Limits.SubscribersPerWeek))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/admin_orgs.templ`, Line: 221, Col: 78}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var54))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 85, "</dd></dl>")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
if u.Limits.RegionsPerMonitor > 0 && !u.Limits.OwnRegionsCount {
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 82, "<p class=\"mt-2 text-xs text-muted\">")
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 86, "<p class=\"mt-2 text-xs text-muted\">")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
var templ_7745c5c3_Var51 string
|
||||
templ_7745c5c3_Var51, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, "limits.own_regions_free"))
|
||||
var templ_7745c5c3_Var55 string
|
||||
templ_7745c5c3_Var55, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, "limits.own_regions_free"))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/admin_orgs.templ`, Line: 212, Col: 78}
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/admin_orgs.templ`, Line: 224, Col: 78}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var51))
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var55))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 83, "</p>")
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 87, "</p>")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
}
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 84, "</section>")
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 88, "</section>")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
|
||||
@@ -178,6 +178,43 @@
|
||||
}
|
||||
});
|
||||
|
||||
// Saves the order of a list of monitors being arranged.
|
||||
const saveOrder = async (list) => {
|
||||
const ids = [...list.querySelectorAll(":scope > [data-sort-id]")].map((li) => li.dataset.sortId);
|
||||
try {
|
||||
await api.put(list.dataset.sortable, { monitor_ids: ids });
|
||||
} catch (err) {
|
||||
alert(message(err));
|
||||
location.reload();
|
||||
}
|
||||
};
|
||||
let dragged = null;
|
||||
document.addEventListener("dragstart", (ev) => {
|
||||
const item = ev.target.closest?.("[data-sortable] > [data-sort-id]");
|
||||
if (!item) return;
|
||||
dragged = item;
|
||||
ev.dataTransfer.effectAllowed = "move";
|
||||
item.style.opacity = "0.5";
|
||||
});
|
||||
document.addEventListener("dragover", (ev) => {
|
||||
const over = ev.target.closest?.("[data-sortable] > [data-sort-id]");
|
||||
if (!dragged || !over || over === dragged || over.parentElement !== dragged.parentElement) return;
|
||||
ev.preventDefault();
|
||||
const box = over.getBoundingClientRect();
|
||||
if (ev.clientY < box.top + box.height / 2) over.before(dragged);
|
||||
else over.after(dragged);
|
||||
});
|
||||
document.addEventListener("drop", (ev) => {
|
||||
if (dragged) ev.preventDefault();
|
||||
});
|
||||
document.addEventListener("dragend", async () => {
|
||||
if (!dragged) return;
|
||||
const list = dragged.parentElement;
|
||||
dragged.style.opacity = "";
|
||||
dragged = null;
|
||||
await saveOrder(list);
|
||||
});
|
||||
|
||||
document.addEventListener("click", async (ev) => {
|
||||
const navToggle = ev.target.closest("[data-nav-toggle]");
|
||||
if (navToggle) {
|
||||
@@ -186,6 +223,30 @@
|
||||
navToggle.setAttribute("aria-expanded", String(open));
|
||||
return;
|
||||
}
|
||||
// Moves a monitor up or down while arranging the monitor list.
|
||||
const move = ev.target.closest("[data-sort-move]");
|
||||
if (move) {
|
||||
const item = move.closest("[data-sort-id]");
|
||||
const other = move.dataset.sortMove === "up" ? item.previousElementSibling : item.nextElementSibling;
|
||||
if (!other) return;
|
||||
if (move.dataset.sortMove === "up") other.before(item);
|
||||
else other.after(item);
|
||||
move.focus();
|
||||
await saveOrder(item.closest("[data-sortable]"));
|
||||
return;
|
||||
}
|
||||
// Ticks or clears every checkbox named by data-check-all in its form,
|
||||
// of the rows a filter leaves visible.
|
||||
const checkAll = ev.target.closest("[data-check-all]");
|
||||
if (checkAll) {
|
||||
const on = checkAll.dataset.checkAll === "on";
|
||||
checkAll.closest("form")?.querySelectorAll(checkAll.dataset.checkTarget).forEach((box) => {
|
||||
if (box.closest("[data-row]")?.hidden) return;
|
||||
box.checked = on;
|
||||
if (on) addRowFields(box);
|
||||
});
|
||||
return;
|
||||
}
|
||||
const locale = ev.target.closest("[data-locale]");
|
||||
if (locale) {
|
||||
await api.post("/locale", { locale: locale.dataset.locale }).catch(() => {});
|
||||
@@ -268,6 +329,29 @@
|
||||
}
|
||||
});
|
||||
|
||||
// A row of a long list may come without its fields until it is ticked;
|
||||
// they are copied in from the form's template[data-row-fields].
|
||||
function addRowFields(box) {
|
||||
const row = box.closest("[data-row]");
|
||||
const tpl = row?.closest("form")?.querySelector("template[data-row-fields]");
|
||||
if (!tpl || row.querySelector("[data-row-extra]")) return;
|
||||
row.append(tpl.content.cloneNode(true));
|
||||
}
|
||||
document.addEventListener("change", (ev) => {
|
||||
if (ev.target.matches('[data-row] [data-field="include"]') && ev.target.checked) addRowFields(ev.target);
|
||||
});
|
||||
|
||||
// [data-filter-rows] hides the rows of the list it names whose text does
|
||||
// not contain what is typed.
|
||||
document.addEventListener("input", (ev) => {
|
||||
const input = ev.target.closest("[data-filter-rows]");
|
||||
if (!input) return;
|
||||
const needle = input.value.trim().toLowerCase();
|
||||
for (const row of document.querySelectorAll(input.dataset.filterRows + " > [data-row]")) {
|
||||
row.hidden = needle !== "" && !row.textContent.toLowerCase().includes(needle);
|
||||
}
|
||||
});
|
||||
|
||||
// Only the settings of the selected check type are shown and submitted.
|
||||
document.addEventListener("change", (ev) => {
|
||||
const sel = ev.target.closest("[data-type-select]");
|
||||
|
||||
+171
-18
@@ -28,6 +28,14 @@ type MonitorRow struct {
|
||||
Latency string
|
||||
Uptime string
|
||||
Bars []Bar
|
||||
// Unchecked is set when no region has reported recently: nobody is
|
||||
// checking the monitor.
|
||||
Unchecked bool
|
||||
// Position is the organization's own order, -1 when not set; Ratio
|
||||
// the uptime in the range, -1 without data; LatencyMS -1 without data.
|
||||
Position int
|
||||
Ratio float64
|
||||
LatencyMS int
|
||||
}
|
||||
|
||||
// GroupNode is a monitor group with its monitors and subgroups.
|
||||
@@ -62,8 +70,47 @@ type DashboardView struct {
|
||||
Empty bool
|
||||
CanWrite bool
|
||||
Counts map[Status]int
|
||||
Range string
|
||||
// Filters are the status counts, each linking to the monitors of
|
||||
// that status.
|
||||
Filters []StatusFilter
|
||||
// Filter, if set, lists Results of that status instead of the tree.
|
||||
Filter Status
|
||||
// AllURL leaves the status filter, keeping the search and range.
|
||||
AllURL string
|
||||
// Sorts switch the order of the list; Sort is the active one.
|
||||
Sorts []SortOption
|
||||
Sort string
|
||||
// Arrange shows the tree for putting monitors in order by hand;
|
||||
// ArrangeURL turns it on or off, empty when not offered.
|
||||
Arrange bool
|
||||
ArrangeURL string
|
||||
Range string
|
||||
Ranges []RangeOption
|
||||
// Unchecked counts the monitors no region has reported for recently.
|
||||
Unchecked int
|
||||
// DeadRegions are regions of the monitors without a live checker.
|
||||
DeadRegions []DeadRegion
|
||||
}
|
||||
|
||||
// SortOption is an entry of the sort switcher.
|
||||
type SortOption struct {
|
||||
Key string
|
||||
URL string
|
||||
Active bool
|
||||
}
|
||||
|
||||
// StatusFilter is one status count; URL shows only its monitors, or all
|
||||
// again when it is the active filter.
|
||||
type StatusFilter struct {
|
||||
Status Status
|
||||
Count int
|
||||
URL string
|
||||
Active bool
|
||||
}
|
||||
|
||||
// DeadRegion is a region without a live checker since Since.
|
||||
type DeadRegion struct {
|
||||
Name, Since string
|
||||
}
|
||||
|
||||
// RangeOption is an entry of the range switcher. Disabled ranges are not
|
||||
@@ -151,24 +198,48 @@ templ Dashboard(p Page, me Me, v DashboardView) {
|
||||
<h1 class="text-lg font-semibold">{ i18n.T(ctx, "console.monitors.title") }</h1>
|
||||
<div class="flex flex-wrap items-center gap-x-5 gap-y-3 font-mono text-xs text-muted">
|
||||
@rangeSwitch(v.Ranges)
|
||||
for _, s := range []Status{StatusUp, StatusDegraded, StatusDown, StatusMaintenance, StatusPaused} {
|
||||
if v.Counts[s] > 0 {
|
||||
<span class="flex items-center gap-1.5">
|
||||
@statusDot(s)
|
||||
<span>{ strconv.Itoa(v.Counts[s]) }</span>
|
||||
</span>
|
||||
@sortSwitch(v.Sorts)
|
||||
<nav class="flex flex-wrap items-center gap-x-1 gap-y-2" aria-label={ i18n.T(ctx, "monitors.filter_label") }>
|
||||
for _, f := range v.Filters {
|
||||
<a
|
||||
href={ templ.SafeURL(f.URL) }
|
||||
class={ "flex items-center gap-1.5 border px-1.5 py-0.5 hover:text-ink",
|
||||
templ.KV("border-ink text-ink", f.Active),
|
||||
templ.KV("border-transparent hover:border-rule", !f.Active) }
|
||||
title={ filterTitle(ctx, f) }
|
||||
aria-label={ filterTitle(ctx, f) }
|
||||
if f.Active {
|
||||
aria-current="true"
|
||||
}
|
||||
>
|
||||
@statusDot(f.Status)
|
||||
<span>{ strconv.Itoa(f.Count) }</span>
|
||||
</a>
|
||||
}
|
||||
}
|
||||
</nav>
|
||||
if v.CanWrite {
|
||||
<a href="/monitors/new" class="whitespace-nowrap bg-ink px-3 py-1.5 font-sans text-sm text-paper hover:opacity-90">{ i18n.T(ctx, "monitors.new") }</a>
|
||||
}
|
||||
</div>
|
||||
</div>
|
||||
if v.Unchecked > 0 || len(v.DeadRegions) > 0 {
|
||||
<div class="mb-6 border-l-2 border-unknown pl-3 text-sm" role="status">
|
||||
for _, r := range v.DeadRegions {
|
||||
<p>{ i18n.T(ctx, "monitors.dead_region", "Region", r.Name, "Since", r.Since) }</p>
|
||||
}
|
||||
if v.Unchecked > 0 {
|
||||
<p>{ i18n.T(ctx, "monitors.unchecked_banner", "Count", v.Unchecked) }</p>
|
||||
}
|
||||
</div>
|
||||
}
|
||||
if !v.Empty {
|
||||
<form method="get" action="/" class="mb-4 flex max-w-md gap-2">
|
||||
if v.Range != "" {
|
||||
<input type="hidden" name="range" value={ v.Range }/>
|
||||
}
|
||||
if v.Filter != "" {
|
||||
<input type="hidden" name="status" value={ string(v.Filter) }/>
|
||||
}
|
||||
<input
|
||||
type="search"
|
||||
name="q"
|
||||
@@ -183,10 +254,24 @@ templ Dashboard(p Page, me Me, v DashboardView) {
|
||||
switch {
|
||||
case v.Empty:
|
||||
<p class="border-y border-rule py-10 text-center text-sm text-muted">{ i18n.T(ctx, "console.monitors.empty") }</p>
|
||||
case v.Search != "":
|
||||
<p class="mb-3 text-sm"><a href="/" class="text-muted hover:text-ink">← { i18n.T(ctx, "monitors.all") }</a></p>
|
||||
case v.Search != "" || v.Filter != "":
|
||||
<p class="mb-3 flex flex-wrap items-center gap-x-4 gap-y-1 text-sm">
|
||||
<a href="/" class="text-muted hover:text-ink">← { i18n.T(ctx, "monitors.all") }</a>
|
||||
if v.Filter != "" {
|
||||
<span class="flex items-center gap-1.5">
|
||||
{ i18n.T(ctx, "monitors.filter_only") }
|
||||
@statusDot(v.Filter)
|
||||
<span class="font-medium">{ i18n.T(ctx, "status."+string(v.Filter)) }</span>
|
||||
<a href={ templ.SafeURL(v.AllURL) } class="ml-1 text-muted hover:text-ink" aria-label={ i18n.T(ctx, "monitors.filter_clear") } title={ i18n.T(ctx, "monitors.filter_clear") }>×</a>
|
||||
</span>
|
||||
}
|
||||
</p>
|
||||
if len(v.Results) == 0 {
|
||||
<p class="border-y border-rule py-10 text-center text-sm text-muted">{ i18n.T(ctx, "monitors.no_match") }</p>
|
||||
if v.Search == "" {
|
||||
<p class="border-y border-rule py-10 text-center text-sm text-muted">{ i18n.T(ctx, "monitors.no_status_match") }</p>
|
||||
} else {
|
||||
<p class="border-y border-rule py-10 text-center text-sm text-muted">{ i18n.T(ctx, "monitors.no_match") }</p>
|
||||
}
|
||||
} else {
|
||||
<div class="border-t border-rule">
|
||||
@monitorList(v.Results)
|
||||
@@ -201,17 +286,31 @@ templ Dashboard(p Page, me Me, v DashboardView) {
|
||||
<span class="font-medium">{ v.Focus }</span>
|
||||
</p>
|
||||
}
|
||||
if v.Arrange {
|
||||
<p class="mb-3 border-l-2 border-ink pl-3 text-sm">{ i18n.T(ctx, "monitors.arrange_hint") }</p>
|
||||
}
|
||||
<div class="border-t border-rule">
|
||||
@monitorList(v.Root.Monitors)
|
||||
@treeList(v.Root.Monitors, v.Arrange)
|
||||
@moreLink(v.Root)
|
||||
for _, g := range v.Root.Children {
|
||||
@groupBlock(g)
|
||||
@groupBlock(g, v.Arrange)
|
||||
}
|
||||
</div>
|
||||
@pager(v.Pager, "previous", "next")
|
||||
<p class="mt-3 text-right text-xs text-muted">{ i18n.T(ctx, "monitors.range_note", "Range", v.Range) }</p>
|
||||
}
|
||||
<p class="mt-8 text-sm"><a href="/groups" class="text-muted hover:text-ink">{ i18n.T(ctx, "groups.manage") }</a></p>
|
||||
<p class="mt-8 flex flex-wrap gap-x-6 gap-y-2 text-sm">
|
||||
<a href="/groups" class="text-muted hover:text-ink">{ i18n.T(ctx, "groups.manage") }</a>
|
||||
if v.ArrangeURL != "" {
|
||||
<a href={ templ.SafeURL(v.ArrangeURL) } class="text-muted hover:text-ink">
|
||||
if v.Arrange {
|
||||
{ i18n.T(ctx, "monitors.arrange_done") }
|
||||
} else {
|
||||
{ i18n.T(ctx, "monitors.arrange") }
|
||||
}
|
||||
</a>
|
||||
}
|
||||
</p>
|
||||
}
|
||||
}
|
||||
|
||||
@@ -229,7 +328,11 @@ templ monitorList(ms []MonitorRow) {
|
||||
</span>
|
||||
</span>
|
||||
<span class="col-span-2 md:col-span-1">@bars(m.Bars, 18)</span>
|
||||
<span class="hidden text-right font-mono text-xs text-muted md:block">{ m.Latency }</span>
|
||||
if m.Unchecked {
|
||||
<span class="hidden text-right font-mono text-xs text-unknown md:block">{ i18n.T(ctx, "monitors.unchecked") }</span>
|
||||
} else {
|
||||
<span class="hidden text-right font-mono text-xs text-muted md:block">{ m.Latency }</span>
|
||||
}
|
||||
<span class="col-start-2 row-start-1 text-right font-mono text-sm md:col-auto md:row-auto">{ m.Uptime }</span>
|
||||
</a>
|
||||
</li>
|
||||
@@ -247,7 +350,7 @@ templ moreLink(g GroupNode) {
|
||||
|
||||
// groupBlock renders a group and, recursively, its subgroups. <details>
|
||||
// makes groups collapsible without JavaScript.
|
||||
templ groupBlock(g GroupNode) {
|
||||
templ groupBlock(g GroupNode, arrange bool) {
|
||||
<details open class="border-b border-rule">
|
||||
<summary class="flex cursor-pointer items-center gap-2.5 py-2.5 text-sm font-medium select-none hover:bg-rule/30">
|
||||
@statusDot(g.Status)
|
||||
@@ -255,10 +358,10 @@ templ groupBlock(g GroupNode) {
|
||||
<span class="font-mono text-xs font-normal text-muted">{ strconv.Itoa(g.Total) }</span>
|
||||
</summary>
|
||||
<div class="ml-4 border-l border-rule pl-4">
|
||||
@monitorList(g.Monitors)
|
||||
@treeList(g.Monitors, arrange)
|
||||
@moreLink(g)
|
||||
for _, c := range g.Children {
|
||||
@groupBlock(c)
|
||||
@groupBlock(c, arrange)
|
||||
}
|
||||
</div>
|
||||
</details>
|
||||
@@ -350,6 +453,9 @@ templ MonitorDetail(p Page, me Me, v MonitorDetailView) {
|
||||
<a href={ templ.SafeURL("/monitors/" + v.Row.ID + "/edit") } class="border border-ink px-3 py-1.5 text-sm hover:bg-ink hover:text-paper">{ i18n.T(ctx, "sso.action.edit") }</a>
|
||||
}
|
||||
</div>
|
||||
if v.Row.Unchecked {
|
||||
<p class="mb-8 border-l-2 border-unknown pl-3 text-sm" role="status">{ i18n.T(ctx, "monitors.unchecked_banner", "Count", 1) }</p>
|
||||
}
|
||||
<section class="mb-10">
|
||||
<div class="mb-3 flex flex-wrap items-center justify-between gap-x-4 gap-y-2">
|
||||
<h2 class="text-xs font-medium uppercase tracking-wider text-muted">{ i18n.T(ctx, "monitors.history", "Range", v.Range) }</h2>
|
||||
@@ -1560,3 +1666,50 @@ templ IncidentStatusesPage(p Page, me Me, statuses []CustomIncidentStatus, canMa
|
||||
</section>
|
||||
}
|
||||
}
|
||||
|
||||
func filterTitle(ctx context.Context, f StatusFilter) string {
|
||||
if f.Active {
|
||||
return i18n.T(ctx, "monitors.filter_clear")
|
||||
}
|
||||
return i18n.T(ctx, "monitors.filter_show", "Status", i18n.T(ctx, "status."+string(f.Status)), "Count", f.Count)
|
||||
}
|
||||
|
||||
templ sortSwitch(opts []SortOption) {
|
||||
<nav class="flex min-w-0 max-w-full overflow-x-auto border border-rule font-mono text-xs" aria-label={ i18n.T(ctx, "monitors.sort") }>
|
||||
for _, o := range opts {
|
||||
if o.Active {
|
||||
<span class="whitespace-nowrap bg-ink px-2 py-1 text-paper" aria-current="true">{ i18n.T(ctx, "monitors.sort_"+o.Key) }</span>
|
||||
} else {
|
||||
<a href={ templ.SafeURL(o.URL) } class="whitespace-nowrap px-2 py-1 text-muted hover:text-ink">{ i18n.T(ctx, "monitors.sort_"+o.Key) }</a>
|
||||
}
|
||||
}
|
||||
</nav>
|
||||
}
|
||||
|
||||
// treeList is a group's own monitors, as links or, while arranging, as
|
||||
// rows to put in order.
|
||||
templ treeList(ms []MonitorRow, arrange bool) {
|
||||
if arrange {
|
||||
@arrangeList(ms)
|
||||
} else {
|
||||
@monitorList(ms)
|
||||
}
|
||||
}
|
||||
|
||||
// arrangeList lets monitors be dragged or moved up and down; every change
|
||||
// is saved at once.
|
||||
templ arrangeList(ms []MonitorRow) {
|
||||
if len(ms) > 0 {
|
||||
<ul data-sortable="/org/monitors/order" class="divide-y divide-rule border-b border-rule text-sm">
|
||||
for _, m := range ms {
|
||||
<li data-sort-id={ m.ID } draggable="true" class="flex cursor-move items-center gap-3 py-2.5">
|
||||
<span class="select-none text-muted" aria-hidden="true">⠿</span>
|
||||
@statusDot(m.Status)
|
||||
<span class="min-w-0 flex-1 truncate">{ m.Name }</span>
|
||||
<button type="button" data-sort-move="up" class="px-1.5 text-muted hover:text-ink" aria-label={ i18n.T(ctx, "monitors.move_up", "Name", m.Name) } title={ i18n.T(ctx, "monitors.move_up", "Name", m.Name) }>↑</button>
|
||||
<button type="button" data-sort-move="down" class="px-1.5 text-muted hover:text-ink" aria-label={ i18n.T(ctx, "monitors.move_down", "Name", m.Name) } title={ i18n.T(ctx, "monitors.move_down", "Name", m.Name) }>↓</button>
|
||||
</li>
|
||||
}
|
||||
</ul>
|
||||
}
|
||||
}
|
||||
+2662
-1957
File diff suppressed because it is too large.
Load diff
Loaded 100 of 105 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user