Compare commits

...
8 Commits
Author SHA1 Message Date
Sebi 383b63bc0e Merge pull request 'perf(console): faster dashboard for organizations with thousands of monitors' (#164) from perf/dashboard-large-orgs into main
ci / test (push) Successful in 9m37s
ci / build (push) Successful in 19m46s
release / release (push) Successful in 37m56s
ci / image (push) Successful in 5m43s
ci / lint (push) Successful in 12m27s
2026-11-26 20:55:38 +00:00
Sebi 42d741846d Merge pull request 'feat(statuspages): error page linking a home page set by admins' (#163) from feat/statuspage-not-found into main
ci / test (push) Canceled after 15s
ci / image (push) Canceled after 0s
ci / lint (push) Canceled after 27s
ci / build (push) Canceled after 0s
2026-11-26 20:54:49 +00:00
Sebastian UnterschützandClaude Opus 5.5 4fd11cb45b perf(console): 24 h bars from the hourly aggregate
ci / lint (push) Skipped
ci / image (push) Skipped
ci / image (pull_request) Successful in 5m30s
ci / test (push) Skipped
ci / build (push) Skipped
ci / lint (pull_request) Successful in 7m5s
ci / test (pull_request) Successful in 13m31s
ci / build (pull_request) Successful in 10m50s
The default range bucketed raw results by 30 minutes: for the hundred or
so monitors a dashboard shows, half a million rows on every request. It
shows 24 hourly bars from the real-time hourly aggregate now (bars 150-230
ms to 18 ms locally, the page 570 KB to 335 KB for 3,500 monitors).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_017GpWAskjmYtZpuQ5JwYTX3
2026-11-26 21:49:50 +01:00
Sebastian UnterschützandClaude Opus 5.5 ec33ef5c56 perf(console): faster dashboard for organizations with thousands of monitors
ci / build (pull_request) Canceled after 1m41s
ci / image (push) Skipped
ci / lint (push) Skipped
ci / build (push) Skipped
ci / test (push) Skipped
ci / lint (pull_request) Successful in 11m12s
ci / test (pull_request) Successful in 12m47s
ci / image (pull_request) Canceled after 0s
- The range picker no longer looks for the first result: on the real-time
  daily aggregate that aggregated the organization's recent raw results
  on every request. The oldest monitor's creation bounds the ranges now.
- Sorting worked out each row's key per comparison; it does so once now
  and moves each row once (40-60 ms to 5 ms for 3,500 monitors).
- The queries behind the monitor list run in parallel.
- The monitor API reads the latest results of the page's monitors only.
- The dashboard reports its steps in a Server-Timing header and logs
  them when it takes a second or more.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_017GpWAskjmYtZpuQ5JwYTX3
2026-11-26 21:35:09 +01:00
Sebastian UnterschützandClaude Opus 5.5 1f90fe8470 feat(statuspages): error page linking a home page set by admins
ci / build (pull_request) Successful in 16m56s
ci / test (pull_request) Successful in 15m30s
ci / image (pull_request) Successful in 6m1s
ci / lint (push) Skipped
ci / test (push) Skipped
ci / build (push) Skipped
ci / image (push) Skipped
ci / lint (pull_request) Successful in 6m52s
The bare status page domain and pages that do not exist answered with a
plain "404 page not found". They now show an error page with a button to
the platform's home page, which platform admins set under Admin. The
status page servers receive it with the page index and keep it across
restarts.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_017GpWAskjmYtZpuQ5JwYTX3
2026-11-26 20:37:59 +01:00
Sebi af992409ef Merge pull request 'feat(statuspages): email subscriptions, RSS feed and a JSON API' (#162) from feat/statuspage-subscriptions into main
ci / build (push) Successful in 18m11s
ci / lint (push) Successful in 12m23s
ci / test (push) Successful in 9m58s
release / release (push) Successful in 34m55s
ci / image (push) Successful in 3m56s
2026-11-26 19:19:42 +00:00
Sebastian UnterschützandClaude Opus 5.5 2d4bd10c9b feat(notify): name regions and link the console in alerts; consent to subscribe
ci / build (pull_request) Successful in 19m0s
ci / image (pull_request) Successful in 6m5s
ci / lint (push) Skipped
ci / test (push) Skipped
ci / build (push) Skipped
ci / image (push) Skipped
ci / lint (pull_request) Successful in 11m8s
ci / test (pull_request) Successful in 13m45s
Alert mails and chat messages named regions by id. They now show the
region's name and mails link the monitor in the console.

Visitors of a status page accept the platform's terms and the page's
privacy policy, where set, before they can subscribe to it; the status
page server and the API both check it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_017GpWAskjmYtZpuQ5JwYTX3
2026-11-26 20:16:28 +01:00
Sebastian UnterschützandClaude Opus 5.5 cca4e80e54 feat(statuspages): email subscriptions, RSS feed and a JSON API
ci / test (push) Skipped
ci / image (push) Skipped
ci / build (pull_request) Successful in 18m10s
ci / image (pull_request) Successful in 5m16s
ci / lint (push) Skipped
ci / build (push) Skipped
ci / test (pull_request) Successful in 9m5s
ci / lint (pull_request) Successful in 10m24s
Visitors can subscribe to a page's incidents by email where the
organization allows it. They confirm their address first; confirmation
and unsubscribe links only show a button, so mail scanners do not act on
them, and mails carry RFC 8058 one-click unsubscribe headers. Subscribers
get a mail when an incident opens or resolves and for every public
update.

Every page also has an RSS feed of incidents and planned maintenance and
a read-only JSON API (status, summary, components, incidents), both
served from the cached snapshot.

Abuse protection: status page servers limit feed and API reads,
subscription requests and link actions per visitor; the API limits
subscription requests per visitor, mailbox and page, and a new limit caps
the subscriptions an organization's pages gain in seven days (platform
default and per-organization override, 1000 in the cloud). Unconfirmed
subscriptions count towards it and are deleted after a week.

The fixed cap of 200 monitors per status page is gone; the configurable
limit alone decides.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_017GpWAskjmYtZpuQ5JwYTX3
2026-11-26 18:18:08 +01:00
57 changed files with 5581 additions and 1942 deletions

No files matched your search

+1 -1
View File
@@ -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). - **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). - **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. - **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. - **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. - **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. - **Operations:** three stateless binaries, horizontally scalable; TimescaleDB and Redis (Sentinel supported); OpenAPI documentation.
+2
View File
@@ -164,6 +164,8 @@ func (c *Client) doWith(ctx context.Context, method, path string, header http.He
return ErrNotModified return ErrNotModified
case resp.StatusCode == http.StatusTooManyRequests: case resp.StatusCode == http.StatusTooManyRequests:
return ErrRateLimited return ErrRateLimited
case resp.StatusCode == http.StatusUnprocessableEntity:
return ErrInvalidInput
case resp.StatusCode >= 300: case resp.StatusCode >= 300:
msg, _ := io.ReadAll(io.LimitReader(resp.Body, 1024)) msg, _ := io.ReadAll(io.LimitReader(resp.Body, 1024))
return fmt.Errorf("agentapi: %s %s: %d %s", method, path, resp.StatusCode, bytes.TrimSpace(msg)) return fmt.Errorf("agentapi: %s %s: %d %s", method, path, resp.StatusCode, bytes.TrimSpace(msg))
+21 -11
View File
@@ -88,6 +88,8 @@ type Section struct {
// PageIncident is an incident of a listed component. // PageIncident is an incident of a listed component.
type PageIncident struct { type PageIncident struct {
// ID identifies the incident in feeds; empty from APIs before it.
ID string `json:"id,omitempty"`
Component string `json:"component"` Component string `json:"component"`
StartedAt time.Time `json:"started_at"` StartedAt time.Time `json:"started_at"`
ResolvedAt *time.Time `json:"resolved_at,omitempty"` ResolvedAt *time.Time `json:"resolved_at,omitempty"`
@@ -115,12 +117,14 @@ type PageIncidentUpdate struct {
// PageSnapshot is everything needed to render a status page. // PageSnapshot is everything needed to render a status page.
type PageSnapshot struct { type PageSnapshot struct {
Slug string `json:"slug"` Slug string `json:"slug"`
Title string `json:"title"` Title string `json:"title"`
Description string `json:"description"` Description string `json:"description"`
Theme Theme `json:"theme"` Theme Theme `json:"theme"`
Status string `json:"status"` Status string `json:"status"`
ShowDetails bool `json:"show_details,omitempty"` ShowDetails bool `json:"show_details,omitempty"`
// Subscribe offers visitors email subscriptions to incidents.
Subscribe bool `json:"subscribe,omitempty"`
Sections []Section `json:"sections"` Sections []Section `json:"sections"`
Incidents []PageIncident `json:"incidents"` Incidents []PageIncident `json:"incidents"`
GeneratedAt time.Time `json:"generated_at"` GeneratedAt time.Time `json:"generated_at"`
@@ -358,14 +362,20 @@ type PageRef struct {
Host string `json:"host,omitempty"` Host string `json:"host,omitempty"`
} }
// PageIndex lists the pages a status page server serves.
type PageIndex struct {
Pages []PageRef `json:"pages"`
// HomeURL is the platform's home page, which the server links from
// its error page; empty for none.
HomeURL string `json:"home_url,omitempty"`
}
// Pages lists every page this status page server serves, so it can keep // Pages lists every page this status page server serves, so it can keep
// them all cached before anyone visits. // them all cached before anyone visits.
func (c *Client) Pages(ctx context.Context) ([]PageRef, error) { func (c *Client) Pages(ctx context.Context) (PageIndex, error) {
var out struct { var out PageIndex
Pages []PageRef `json:"pages"`
}
err := c.do(ctx, http.MethodGet, "/pages/index", nil, &out) err := c.do(ctx, http.MethodGet, "/pages/index", nil, &out)
return out.Pages, err return out, err
} }
// ErrNotFound means no published page matches. // ErrNotFound means no published page matches.
+66
View File
@@ -0,0 +1,66 @@
package agentapi
import (
"context"
"errors"
"net/http"
)
// Visitors of a status page subscribe to its incidents by email. The status
// page server passes their requests on; the API checks its limits, mails
// the confirmation and later the incidents.
// SubscribeRequest asks for an email subscription to the page at Host, or
// Slug if Host is empty.
type SubscribeRequest struct {
Host string `json:"host,omitempty"`
Slug string `json:"slug,omitempty"`
Email string `json:"email"`
// IP is the visitor's address, for rate limits.
IP string `json:"ip"`
// Locale is the language of the mails, as the visitor's browser asks.
Locale string `json:"locale,omitempty"`
// PageURL is where the visitor saw the page, ending in "/". The API
// uses it for the links in mails only where it does not know the
// page's address itself.
PageURL string `json:"page_url,omitempty"`
// Accepted says the visitor accepted the terms and privacy policy the
// page links in its form, if it links any.
Accepted bool `json:"accepted"`
}
// SubscriptionInfo describes a subscription that was confirmed or ended.
type SubscriptionInfo struct {
PageTitle string `json:"page_title"`
Email string `json:"email"`
}
// ErrInvalidInput means the API refused the request's content, e.g. an
// email address that is none.
var ErrInvalidInput = errors.New("agentapi: invalid input")
type tokenRequest struct {
Token string `json:"token"`
}
// Subscribe asks for a subscription and has the confirmation mailed. It
// succeeds whether or not the address was subscribed already, so it tells
// nobody who is. ErrRateLimited means a limit was reached, ErrNotFound
// that the page takes no subscriptions.
func (c *Client) Subscribe(ctx context.Context, r SubscribeRequest) error {
return c.do(ctx, http.MethodPost, "/subscriptions", r, nil)
}
// ConfirmSubscription confirms the subscription token was mailed for.
func (c *Client) ConfirmSubscription(ctx context.Context, token string) (SubscriptionInfo, error) {
var out SubscriptionInfo
err := c.do(ctx, http.MethodPost, "/subscriptions/confirm", tokenRequest{token}, &out)
return out, err
}
// Unsubscribe ends the subscription of an unsubscribe token.
func (c *Client) Unsubscribe(ctx context.Context, token string) (SubscriptionInfo, error) {
var out SubscriptionInfo
err := c.do(ctx, http.MethodPost, "/subscriptions/unsubscribe", tokenRequest{token}, &out)
return out, err
}
+3
View File
@@ -53,6 +53,9 @@ func (s *Server) mountAgentAPI(r gin.IRouter) {
sp.POST("/storage/lock", s.storageLock) sp.POST("/storage/lock", s.storageLock)
sp.DELETE("/storage/lock", s.storageUnlock) sp.DELETE("/storage/lock", s.storageUnlock)
sp.POST("/certificates", s.agentCertificate) 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 := g.Group("", requireAgentKind("checker"))
checker.POST("/jobs", s.agentJobs) checker.POST("/jobs", s.agentJobs)
checker.POST("/results", s.agentResults) checker.POST("/results", s.agentResults)
+43 -7
View File
@@ -15,6 +15,7 @@ import (
"git.zb-server.de/ZB-Server/uptimesebi/internal/agentapi" "git.zb-server.de/ZB-Server/uptimesebi/internal/agentapi"
"git.zb-server.de/ZB-Server/uptimesebi/internal/evaluate" "git.zb-server.de/ZB-Server/uptimesebi/internal/evaluate"
"git.zb-server.de/ZB-Server/uptimesebi/internal/i18n"
"git.zb-server.de/ZB-Server/uptimesebi/internal/notify" "git.zb-server.de/ZB-Server/uptimesebi/internal/notify"
"git.zb-server.de/ZB-Server/uptimesebi/internal/store" "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/tenant"
@@ -99,6 +100,9 @@ func (s *Server) transition(ctx context.Context, m store.MonitorsForResultsRow,
if err != nil { if err != nil {
return err 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) routes, err := q.MonitorAlertRoutes(ctx, m.ID)
if err != nil { if err != nil {
return err return err
@@ -140,6 +144,8 @@ func (s *Server) RunNotifier(ctx context.Context) {
case <-tick.C: case <-tick.C:
for s.deliverBatch(ctx) == notifyBatch && ctx.Err() == nil { for s.deliverBatch(ctx) == notifyBatch && ctx.Err() == nil {
} }
for s.deliverSubscriberBatch(ctx) == subscriberBatch && ctx.Err() == nil {
}
} }
} }
} }
@@ -192,9 +198,40 @@ func eventOf(n store.NotificationDetailsRow) notify.Event {
Monitor: notify.Monitor{ID: n.MonitorID, Name: n.MonitorName, Type: n.MonitorType, Target: n.MonitorTarget}, Monitor: notify.Monitor{ID: n.MonitorID, Name: n.MonitorName, Type: n.MonitorType, Target: n.MonitorTarget},
} }
_ = json.Unmarshal(n.Cause, &ev.Cause) _ = json.Unmarshal(n.Cause, &ev.Cause)
_ = json.Unmarshal(n.RegionNames, &ev.RegionNames)
return ev return ev
} }
// causeLines describes the errors of ev per region, sorted, naming each
// region as people know it.
func causeLines(ev notify.Event, l *i18n.Localizer) []string {
var out []string
for region, msg := range ev.Cause {
name, ok := ev.RegionNames[region]
switch {
case ok:
case region == heartbeatRegion:
name = l.T("monitors.type_heartbeat", nil)
case region == alertmanagerRegion:
name = "Alertmanager"
default:
name = region
}
out = append(out, name+": "+msg)
}
slices.Sort(out)
return out
}
// monitorLink is the address of ev's monitor in the console, or "" if
// the platform's own address is unknown.
func (s *Server) monitorLink(ev notify.Event) string {
if ev.Monitor.ID == (uuid.UUID{}) || !absoluteURL(s.cfg.PublicURL) {
return ""
}
return strings.TrimSuffix(s.cfg.PublicURL, "/") + "/monitors/" + ev.Monitor.ID.String()
}
// webhookConfig is stored for webhook channels; Secret is sealed. // webhookConfig is stored for webhook channels; Secret is sealed.
type webhookConfig struct { type webhookConfig struct {
URL string `json:"url"` URL string `json:"url"`
@@ -252,18 +289,17 @@ func (s *Server) mailFor(ev notify.Event, to []string, locale string) notify.Mai
"Target": ev.Monitor.Target, "Target": ev.Monitor.Target,
"Since": ev.StartedAt.UTC().Format("2006-01-02 15:04 MST"), "Since": ev.StartedAt.UTC().Format("2006-01-02 15:04 MST"),
} }
var cause []string data["Cause"] = strings.Join(causeLines(ev, l), "\n")
for region, msg := range ev.Cause {
cause = append(cause, region+": "+msg)
}
slices.Sort(cause)
data["Cause"] = strings.Join(cause, "\n")
if ev.ResolvedAt != nil { if ev.ResolvedAt != nil {
data["Duration"] = ev.ResolvedAt.Sub(ev.StartedAt).Round(time.Second).String() data["Duration"] = ev.ResolvedAt.Sub(ev.StartedAt).Round(time.Second).String()
} }
body := l.T("email."+ev.Kind+".body", data)
if link := s.monitorLink(ev); link != "" {
body += "\n\n" + l.T("email.monitor_link", map[string]any{"Link": link})
}
return notify.Mail{ return notify.Mail{
To: to, To: to,
Subject: l.T("email."+ev.Kind+".subject", data), Subject: l.T("email."+ev.Kind+".subject", data),
Body: l.T("email."+ev.Kind+".body", data), Body: body,
} }
} }
+2
View File
@@ -128,6 +128,8 @@ func TestAlerting(t *testing.T) {
} }
if msg := mail.Messages()[0].Data; !strings.Contains(msg, "Subject: [DOWN] Shop") || !strings.Contains(msg, "ist in allen Regionen nicht erreichbar") { if msg := mail.Messages()[0].Data; !strings.Contains(msg, "Subject: [DOWN] Shop") || !strings.Contains(msg, "ist in allen Regionen nicht erreichbar") {
t.Errorf("down mail = %q, want German down notice", msg) t.Errorf("down mail = %q, want German down notice", msg)
} else if strings.Contains(msg, eu) || strings.Contains(msg, us) || !strings.Contains(msg, "/monitors/"+monitorID) {
t.Errorf("down mail = %q, want region names instead of ids and a link to the monitor", msg)
} }
healthy.Store(true) healthy.Store(true)
+9
View File
@@ -188,6 +188,10 @@ var endpoints = []endpoint{
description: "Verify it with a TXT record before it is served.", req: domainRequest{}, resp: statusPageView{}}, 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", {method: "POST", path: "/api/v1/org/statuspages/:id/domain/verify", tag: "Status pages", summary: "Verify the custom domain", perm: "statuspages.write",
status: http.StatusNoContent}, 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", {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"}, media: "text/html"},
@@ -314,6 +318,11 @@ var endpoints = []endpoint{
{method: "PUT", path: "/api/v1/admin/checker-network", tag: "Platform", summary: "Let platform checkers check private addresses or not", {method: "PUT", path: "/api/v1/admin/checker-network", tag: "Platform", summary: "Let platform checkers check private addresses or not",
description: "Unset, they may on self-hosted installations and may not in the cloud edition. Applies from each checker's next poll.", description: "Unset, they may on self-hosted installations and may not in the cloud edition. Applies from each checker's next poll.",
perm: "platform admin", req: checkerNetwork{}, status: http.StatusNoContent}, perm: "platform admin", req: checkerNetwork{}, status: http.StatusNoContent},
{method: "GET", path: "/api/v1/admin/statuspage-home", tag: "Platform", summary: "The home page linked from the status page servers' error page", perm: "platform admin",
resp: statusPageHome{}},
{method: "PUT", path: "/api/v1/admin/statuspage-home", tag: "Platform", summary: "Set the home page linked from the status page servers' error page",
description: "Visitors of the bare status page domain and of pages that do not exist see an error page with a link to this URL. Empty links none.",
perm: "platform admin", req: statusPageHome{}, status: http.StatusNoContent},
{method: "GET", path: "/api/v1/admin/identity-providers", tag: "Platform", summary: "Identity providers for signing up and in", {method: "GET", path: "/api/v1/admin/identity-providers", tag: "Platform", summary: "Identity providers for signing up and in",
description: "With the callback URL to register at each provider. Secrets are never returned.", perm: "platform admin", description: "With the callback URL to register at each provider. Secrets are never returned.", perm: "platform admin",
resp: obj{"providers": []idpView{}, "callback_url": ""}}, resp: obj{"providers": []idpView{}, "callback_url": ""}},
+46 -44
View File
@@ -61,55 +61,57 @@ var auditActions = map[string]string{
"POST /api/v1/invitations/:token/accept": "member.join", "POST /api/v1/invitations/:token/accept": "member.join",
"POST /api/v1/invitations/:token/signup": "member.join", "POST /api/v1/invitations/:token/signup": "member.join",
"PUT /api/v1/org/policy": "org.policy_update", "PUT /api/v1/org/policy": "org.policy_update",
"POST /api/v1/org/monitors": "monitor.create", "POST /api/v1/org/monitors": "monitor.create",
"PUT /api/v1/org/monitors/:id": "monitor.update", "PUT /api/v1/org/monitors/:id": "monitor.update",
"PUT /api/v1/org/monitors/order": "monitor.order", "PUT /api/v1/org/monitors/order": "monitor.order",
"DELETE /api/v1/org/monitors/:id": "monitor.delete", "DELETE /api/v1/org/monitors/:id": "monitor.delete",
"POST /api/v1/org/alertmanager/receivers": "alertmanager.receiver_create", "POST /api/v1/org/alertmanager/receivers": "alertmanager.receiver_create",
"DELETE /api/v1/org/alertmanager/receivers/:id": "alertmanager.receiver_delete", "DELETE /api/v1/org/alertmanager/receivers/:id": "alertmanager.receiver_delete",
"POST /api/v1/org/maintenance": "maintenance.create", "POST /api/v1/org/maintenance": "maintenance.create",
"PUT /api/v1/org/maintenance/:id": "maintenance.update", "PUT /api/v1/org/maintenance/:id": "maintenance.update",
"DELETE /api/v1/org/maintenance/:id": "maintenance.delete", "DELETE /api/v1/org/maintenance/:id": "maintenance.delete",
"POST /api/v1/org/groups": "group.create", "POST /api/v1/org/groups": "group.create",
"PUT /api/v1/org/groups/:id": "group.update", "PUT /api/v1/org/groups/:id": "group.update",
"DELETE /api/v1/org/groups/:id": "group.delete", "DELETE /api/v1/org/groups/:id": "group.delete",
"POST /api/v1/org/regions": "region.create", "POST /api/v1/org/regions": "region.create",
"DELETE /api/v1/org/regions/:id": "region.delete", "DELETE /api/v1/org/regions/:id": "region.delete",
"POST /api/v1/org/agents": "agent.create", "POST /api/v1/org/agents": "agent.create",
"DELETE /api/v1/org/agents/:id": "agent.delete", "DELETE /api/v1/org/agents/:id": "agent.delete",
"POST /api/v1/org/statuspages": "statuspage.create", "POST /api/v1/org/statuspages": "statuspage.create",
"PUT /api/v1/org/statuspages/:id": "statuspage.update", "PUT /api/v1/org/statuspages/:id": "statuspage.update",
"DELETE /api/v1/org/statuspages/:id": "statuspage.delete", "DELETE /api/v1/org/statuspages/:id": "statuspage.delete",
"POST /api/v1/org/statuspages/:id/groups": "statuspage.group_create", "POST /api/v1/org/statuspages/:id/groups": "statuspage.group_create",
"PUT /api/v1/org/statuspages/:id/groups/:group_id": "statuspage.group_update", "PUT /api/v1/org/statuspages/:id/groups/:group_id": "statuspage.group_update",
"DELETE /api/v1/org/statuspages/:id/groups/:group_id": "statuspage.group_delete", "DELETE /api/v1/org/statuspages/:id/groups/:group_id": "statuspage.group_delete",
"POST /api/v1/org/statuspages/:id/groups/import": "statuspage.groups_import", "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/monitors": "statuspage.monitors_update",
"PUT /api/v1/org/statuspages/:id/domain": "statuspage.domain_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/statuspages/:id/domain/verify": "statuspage.domain_verify",
"POST /api/v1/org/channels": "channel.create", "DELETE /api/v1/org/statuspages/:id/subscribers/:subscriber": "statuspage.subscriber_delete",
"PUT /api/v1/org/channels/:id": "channel.update", "POST /api/v1/org/channels": "channel.create",
"DELETE /api/v1/org/channels/:id": "channel.delete", "PUT /api/v1/org/channels/:id": "channel.update",
"POST /api/v1/org/channels/:id/test": "channel.test", "DELETE /api/v1/org/channels/:id": "channel.delete",
"POST /api/v1/org/sso": "sso.create", "POST /api/v1/org/channels/:id/test": "channel.test",
"PUT /api/v1/org/sso/:id": "sso.update", "POST /api/v1/org/sso": "sso.create",
"DELETE /api/v1/org/sso/:id": "sso.delete", "PUT /api/v1/org/sso/:id": "sso.update",
"DELETE /api/v1/org/members/:user": "member.remove", "DELETE /api/v1/org/sso/:id": "sso.delete",
"POST /api/v1/org/members/:user/roles": "member.role_assign", "DELETE /api/v1/org/members/:user": "member.remove",
"DELETE /api/v1/org/assignments/:id": "member.role_unassign", "POST /api/v1/org/members/:user/roles": "member.role_assign",
"POST /api/v1/org/invitations": "invitation.create", "DELETE /api/v1/org/assignments/:id": "member.role_unassign",
"DELETE /api/v1/org/invitations/:id": "invitation.delete", "POST /api/v1/org/invitations": "invitation.create",
"POST /api/v1/org/roles": "role.create", "DELETE /api/v1/org/invitations/:id": "invitation.delete",
"PUT /api/v1/org/roles/:id": "role.update", "POST /api/v1/org/roles": "role.create",
"DELETE /api/v1/org/roles/:id": "role.delete", "PUT /api/v1/org/roles/:id": "role.update",
"POST /api/v1/org/tokens": "token.create", "DELETE /api/v1/org/roles/:id": "role.delete",
"DELETE /api/v1/org/tokens/:id": "token.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/admin/legal/:kind": "platform.legal_update",
"PUT /api/v1/org/legal/:kind": "org.legal_update", "PUT /api/v1/org/legal/:kind": "org.legal_update",
"PUT /api/v1/admin/check-types": "platform.check_types_update", "PUT /api/v1/admin/check-types": "platform.check_types_update",
"PUT /api/v1/admin/checker-network": "platform.checker_network_update", "PUT /api/v1/admin/checker-network": "platform.checker_network_update",
"PUT /api/v1/admin/statuspage-home": "platform.statuspage_home_update",
"PUT /api/v1/admin/limits": "platform.limits_update", "PUT /api/v1/admin/limits": "platform.limits_update",
"POST /api/v1/admin/identity-providers": "platform.idp_create", "POST /api/v1/admin/identity-providers": "platform.idp_create",
"PUT /api/v1/admin/identity-providers/:id": "platform.idp_update", "PUT /api/v1/admin/identity-providers/:id": "platform.idp_update",
+83 -56
View File
@@ -19,6 +19,7 @@ import (
"github.com/gin-gonic/gin" "github.com/gin-gonic/gin"
"github.com/google/uuid" "github.com/google/uuid"
"github.com/jackc/pgx/v5" "github.com/jackc/pgx/v5"
"golang.org/x/sync/errgroup"
"git.zb-server.de/ZB-Server/uptimesebi/internal/auth" "git.zb-server.de/ZB-Server/uptimesebi/internal/auth"
"git.zb-server.de/ZB-Server/uptimesebi/internal/authz" "git.zb-server.de/ZB-Server/uptimesebi/internal/authz"
@@ -72,8 +73,10 @@ func (s *Server) dashboard(c *gin.Context) {
return return
} }
v := web.DashboardView{Counts: map[web.Status]int{}, Empty: true} v := web.DashboardView{Counts: map[web.Status]int{}, Empty: true}
timer := newStepTimer()
if p != nil && me.Policy == "" { if p != nil && me.Policy == "" {
data, err := s.loadMonitorData(c.Request.Context(), p, web.RangeByKey(c.Query("range"))) data, err := s.loadMonitorData(c.Request.Context(), p, web.RangeByKey(c.Query("range")))
timer.done("load")
if err != nil { if err != nil {
internalError(c, err) internalError(c, err)
return return
@@ -84,21 +87,14 @@ func (s *Server) dashboard(c *gin.Context) {
if !s.dashboardPage(c, &v, data) { if !s.dashboardPage(c, &v, data) {
return return
} }
timer.done("arrange")
if err := s.dashboardBars(c.Request.Context(), p, &v, &data); err != nil { if err := s.dashboardBars(c.Request.Context(), p, &v, &data); err != nil {
internalError(c, err) internalError(c, err)
return return
} }
timer.done("bars")
v.Range = data.rng.Key v.Range = data.rng.Key
var earliest time.Time v.Ranges = rangeOptions(c, data.rng, data.firstCreated, data.now)
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 { for _, m := range data.rows {
v.Counts[m.Status]++ v.Counts[m.Status]++
if m.Unchecked { if m.Unchecked {
@@ -111,7 +107,11 @@ func (s *Server) dashboard(c *gin.Context) {
} }
slices.SortFunc(v.DeadRegions, func(a, b web.DeadRegion) int { return strings.Compare(a.Name, b.Name) }) slices.SortFunc(v.DeadRegions, func(a, b web.DeadRegion) int { return strings.Compare(a.Name, b.Name) })
} }
timer.done("rest")
timer.header(c)
web.Render(c, http.StatusOK, web.Dashboard(s.pageFor(c, "console.monitors.title"), me, v)) web.Render(c, http.StatusOK, web.Dashboard(s.pageFor(c, "console.monitors.title"), me, v))
timer.done("render")
timer.logIfSlow(c, s.log)
} }
// dashboardBars loads the bars of the monitors v shows, and only those. // dashboardBars loads the bars of the monitors v shows, and only those.
@@ -218,13 +218,28 @@ func (o monitorSort) key(m web.MonitorRow) cursor {
} }
func (o monitorSort) sort(ms []web.MonitorRow) { func (o monitorSort) sort(ms []web.MonitorRow) {
slices.SortFunc(ms, func(a, b web.MonitorRow) int { // Keys are worked out once per row, not per comparison, and the rows
ka, kb := o.key(a), o.key(b) // moved once: with thousands of monitors sorting was a good part of
if c := strings.Compare(ka.S, kb.S); c != 0 { // the dashboard's time.
type keyed struct {
key, id string
i int
}
keys := make([]keyed, len(ms))
for i, m := range ms {
keys[i] = keyed{o.key(m).S, m.ID, i}
}
slices.SortFunc(keys, func(a, b keyed) int {
if c := strings.Compare(a.key, b.key); c != 0 {
return c return c
} }
return strings.Compare(a.ID, b.ID) return strings.Compare(a.id, b.id)
}) })
sorted := make([]web.MonitorRow, len(ms))
for i, k := range keys {
sorted[i] = ms[k.i]
}
copy(ms, sorted)
} }
// dashboardStatuses are the statuses the dashboard counts, in order. // dashboardStatuses are the statuses the dashboard counts, in order.
@@ -379,6 +394,11 @@ type monitorData struct {
regionOf map[uuid.UUID]store.Region regionOf map[uuid.UUID]store.Region
rng web.TimeRange rng web.TimeRange
now time.Time now time.Time
// firstCreated is when the oldest monitor was created: the monitor
// list offers no ranges reaching far before it. (Finding the first
// result instead read results of every monitor, slow for large
// organizations.)
firstCreated time.Time
// first is when the monitor of a detail page first reported, from // first is when the monitor of a detail page first reported, from
// any region; firstRegion the same per region. // any region; firstRegion the same per region.
first time.Time first time.Time
@@ -423,25 +443,6 @@ func loadFirstData(ctx context.Context, q *store.Queries, org, monitor uuid.UUID
return first, perRegion, nil return first, perRegion, nil
} }
// earliestData finds when any monitor of org first reported, for the
// ranges the monitor list offers: to the day if that was over two days
// ago, otherwise exactly.
func earliestData(ctx context.Context, q *store.Queries, org uuid.UUID, now time.Time) (time.Time, error) {
none := func(t time.Time, err error) (time.Time, bool, error) {
if errors.Is(err, pgx.ErrNoRows) {
return time.Time{}, false, nil
}
return t, err == nil, err
}
recentSince := now.Add(-2 * 24 * time.Hour)
daily, ok, err := none(q.EarliestDataDaily(ctx, org))
if err != nil || (ok && daily.Before(recentSince)) {
return daily, err
}
exact, _, err := none(q.EarliestDataRecent(ctx, store.EarliestDataRecentParams{OrgID: org, Time: recentSince}))
return exact, err
}
// rangeBuckets loads the selected range for the monitors ids. // 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) { 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{} out := map[uuid.UUID][]web.Bucket{}
@@ -498,39 +499,50 @@ func (s *Server) loadMonitorData(ctx context.Context, p *principal, rng web.Time
spans []store.IncidentsSinceRow spans []store.IncidentsSinceRow
) )
var groups []store.MonitorGroup var groups []store.MonitorGroup
err := s.db.Tx(ctx, p.scope(), func(q *store.Queries) error { // The queries run in parallel: for large organizations each takes a
// while, mostly to move its rows.
g, gctx := errgroup.WithContext(ctx)
tx := func(f func(q *store.Queries) error) {
g.Go(func() error { return s.db.Tx(gctx, p.scope(), f) })
}
tx(func(q *store.Queries) error {
var err error var err error
if groups, err = q.ListGroups(ctx); err != nil { if groups, err = q.ListGroups(gctx); err != nil {
return err return err
} }
if monitors, err = q.ListMonitors(ctx, p.Org.ID); err != nil { if monitors, err = q.ListMonitors(gctx, p.Org.ID); err != nil {
return err
}
if assigned, err = q.AllMonitorRegions(ctx, p.Org.ID); err != nil {
return err
}
if regions, err = q.ListVisibleRegions(ctx); err != nil {
return err
}
if latest, err = q.LatestResults(ctx, p.Org.ID); err != nil {
return err
}
if open, err = q.OpenIncidents(ctx, p.Org.ID); err != nil {
return err
}
if spans, err = q.IncidentsSince(ctx, store.IncidentsSinceParams{OrgID: p.Org.ID, ResolvedAt: ptr(now.Add(-web.SLAWindows[len(web.SLAWindows)-1].Window))}); err != nil {
return err
}
if d.statuses, err = loadCustomStatuses(ctx, q); err != nil {
return err return err
} }
ids := make([]uuid.UUID, len(monitors)) ids := make([]uuid.UUID, len(monitors))
for i, m := range monitors { for i, m := range monitors {
ids[i] = m.ID ids[i] = m.ID
} }
d.maint, err = maintenanceFor(ctx, q, ids) d.maint, err = maintenanceFor(gctx, q, ids)
return err return err
}) })
tx(func(q *store.Queries) (err error) {
assigned, err = q.AllMonitorRegions(gctx, p.Org.ID)
return err
})
tx(func(q *store.Queries) (err error) {
latest, err = q.LatestResults(gctx, p.Org.ID)
return err
})
tx(func(q *store.Queries) error {
var err error
if regions, err = q.ListVisibleRegions(gctx); err != nil {
return err
}
if open, err = q.OpenIncidents(gctx, p.Org.ID); err != nil {
return err
}
if spans, err = q.IncidentsSince(gctx, store.IncidentsSinceParams{OrgID: p.Org.ID, ResolvedAt: ptr(now.Add(-web.SLAWindows[len(web.SLAWindows)-1].Window))}); err != nil {
return err
}
d.statuses, err = loadCustomStatuses(gctx, q)
return err
})
err := g.Wait()
if err != nil { if err != nil {
return d, err return d, err
} }
@@ -553,6 +565,9 @@ func (s *Server) loadMonitorData(ctx context.Context, p *principal, rng web.Time
if m.Enabled { if m.Enabled {
d.usedRegions = append(d.usedRegions, regionsOf[m.ID]...) d.usedRegions = append(d.usedRegions, regionsOf[m.ID]...)
} }
if d.firstCreated.IsZero() || m.CreatedAt.Before(d.firstCreated) {
d.firstCreated = m.CreatedAt
}
} }
slices.SortFunc(d.usedRegions, func(a, b uuid.UUID) int { return strings.Compare(a.String(), b.String()) }) slices.SortFunc(d.usedRegions, func(a, b uuid.UUID) int { return strings.Compare(a.String(), b.String()) })
d.usedRegions = slices.Compact(d.usedRegions) d.usedRegions = slices.Compact(d.usedRegions)
@@ -1318,6 +1333,7 @@ func (s *Server) statusPageEditor(c *gin.Context, p *principal, page web.Page, m
pageGroups []store.StatusPageGroup pageGroups []store.StatusPageGroup
orgGroups []store.MonitorGroup orgGroups []store.MonitorGroup
monitors []store.Monitor monitors []store.Monitor
subs subscribersView
own bool own bool
) )
err = s.db.Tx(ctx, p.scope(), func(q *store.Queries) error { err = s.db.Tx(ctx, p.scope(), func(q *store.Queries) error {
@@ -1337,6 +1353,9 @@ func (s *Server) statusPageEditor(c *gin.Context, p *principal, page web.Page, m
if monitors, err = q.ListMonitors(ctx, p.Org.ID); err != nil { if monitors, err = q.ListMonitors(ctx, p.Org.ID); err != nil {
return err return err
} }
if subs, err = s.pageSubscribers(ctx, q, id); err != nil {
return err
}
own, err = q.OrgServesOwnPages(ctx, &p.Org.ID) own, err = q.OrgServesOwnPages(ctx, &p.Org.ID)
return err return err
}) })
@@ -1359,7 +1378,15 @@ func (s *Server) statusPageEditor(c *gin.Context, p *principal, page web.Page, m
e.RecordName, e.RecordValue = v.DomainRecord.Name, v.DomainRecord.Value e.RecordName, e.RecordValue = v.DomainRecord.Name, v.DomainRecord.Value
} }
e.DomainChangesPerDay = domainChangesPerDay e.DomainChangesPerDay = domainChangesPerDay
e.MonitorLimit = s.orgLimits(c.Request.Context(), p.Org).MonitorsPerPage limits := s.orgLimits(c.Request.Context(), p.Org)
e.MonitorLimit = limits.MonitorsPerPage
e.Subscriptions, e.MailAvailable, e.SubscriberLimit = row.Subscriptions, s.smtp != nil, limits.SubscribersPerWeek
e.SubscribersConfirmed, e.SubscribersPending = subs.Confirmed, subs.Pending
for _, sub := range subs.Subscribers {
e.Subscribers = append(e.Subscribers, web.PageSubscriberRow{
ID: sub.ID.String(), Email: sub.Email, Since: sub.CreatedAt.Local().Format("2006-01-02"), Pending: sub.ConfirmedAt == nil,
})
}
if v.CNAMERecord != nil { if v.CNAMERecord != nil {
e.CNAMEValue = v.CNAMERecord.Value e.CNAMEValue = v.CNAMERecord.Value
} }
+12
View File
@@ -6,6 +6,7 @@ import (
"encoding/json" "encoding/json"
"errors" "errors"
"fmt" "fmt"
"math"
"net/http" "net/http"
"time" "time"
@@ -335,6 +336,8 @@ type exportStatusPage struct {
CustomDomain *string `json:"custom_domain"` CustomDomain *string `json:"custom_domain"`
Groups []pageGroupView `json:"groups"` Groups []pageGroupView `json:"groups"`
Monitors []exportPageMember `json:"monitors"` Monitors []exportPageMember `json:"monitors"`
Subscriptions bool `json:"subscriptions"`
Subscribers []subscriberView `json:"subscribers"`
} }
type exportPageMember struct { type exportPageMember struct {
@@ -529,10 +532,19 @@ func (s *Server) buildOrgExport(ctx context.Context, p *principal) (orgExport, e
MonitorID: m.MonitorID, GroupID: m.GroupID, Section: m.Section, Label: m.Label, 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{ x.StatusPages = append(x.StatusPages, exportStatusPage{
ID: pg.ID, Slug: pg.Slug, Title: pg.Title, Description: pg.Description, ID: pg.ID, Slug: pg.Slug, Title: pg.Title, Description: pg.Description,
Published: pg.Published, ShowComponentDetails: pg.ShowComponentDetails, Published: pg.Published, ShowComponentDetails: pg.ShowComponentDetails,
CustomDomain: pg.CustomDomain, Groups: exportedGroups, Monitors: members, CustomDomain: pg.CustomDomain, Groups: exportedGroups, Monitors: members,
Subscriptions: pg.Subscriptions, Subscribers: subscribers,
}) })
} }
+11 -3
View File
@@ -47,7 +47,7 @@ func (s *Server) RunHousekeeping(ctx context.Context) {
// tokens and incidents older than the daily aggregate. // tokens and incidents older than the daily aggregate.
func (s *Server) Housekeep(ctx context.Context, now time.Time) error { func (s *Server) Housekeep(ctx context.Context, now time.Time) error {
keep := s.cfg.Retention keep := s.cfg.Retention
var counts [7]int64 var counts [9]int64
err := s.db.Tx(ctx, tenant.System(), func(q *store.Queries) error { err := s.db.Tx(ctx, tenant.System(), func(q *store.Queries) error {
var err error var err error
if keep.Housekeeping > 0 { 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 { if counts[6], err = q.PurgeUnverifiedUsers(ctx, now.Add(-unverifiedKeep)); err != nil {
return err 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 { if keep.Daily > 0 {
before := now.Add(-keep.Daily) before := now.Add(-keep.Daily)
counts[3], err = q.PurgeIncidents(ctx, &before) counts[3], err = q.PurgeIncidents(ctx, &before)
} }
return err return err
}) })
if err == nil && counts != [7]int64{} { if err == nil && counts != [9]int64{} {
s.log.InfoContext(ctx, "housekeeping purged rows", 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], "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 return err
} }
+7
View File
@@ -268,6 +268,13 @@ func (s *Server) addIncidentUpdate(c *gin.Context) {
if err != nil { if err != nil {
return err 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) return q.RefreshIncidentStatus(ctx, d.inc.ID)
}); err != nil { }); err != nil {
internalError(c, err) internalError(c, err)
+25 -15
View File
@@ -38,11 +38,14 @@ type Limits struct {
OrgsPerAccount int `json:"orgs_per_account"` OrgsPerAccount int `json:"orgs_per_account"`
// MonitorsPerPage limits the monitors one status page shows. // MonitorsPerPage limits the monitors one status page shows.
MonitorsPerPage int `json:"monitors_per_page"` 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 { func (s *Server) defaultLimits() Limits {
if s.cloud() { if s.cloud() {
return Limits{OrgsPerAccount: 3} return Limits{OrgsPerAccount: 3, SubscribersPerWeek: 1000}
} }
return Limits{} return Limits{}
} }
@@ -82,6 +85,7 @@ func (s *Server) orgLimits(ctx context.Context, org store.Org) Limits {
override(&l.StatusPages, org.LimitStatusPages) override(&l.StatusPages, org.LimitStatusPages)
override(&l.RegionsPerMonitor, org.LimitRegionsPerMonitor) override(&l.RegionsPerMonitor, org.LimitRegionsPerMonitor)
override(&l.MonitorsPerPage, org.LimitMonitorsPerPage) override(&l.MonitorsPerPage, org.LimitMonitorsPerPage)
override(&l.SubscribersPerWeek, org.LimitSubscribersPerWeek)
if org.LimitOwnRegionsCount != nil { if org.LimitOwnRegionsCount != nil {
l.OwnRegionsCount = *org.LimitOwnRegionsCount l.OwnRegionsCount = *org.LimitOwnRegionsCount
} }
@@ -192,7 +196,10 @@ type limitsRequest struct {
RegionsPerMonitor int `json:"regions_per_monitor" binding:"min=0,max=1000"` RegionsPerMonitor int `json:"regions_per_monitor" binding:"min=0,max=1000"`
OwnRegionsCount bool `json:"own_regions_count"` OwnRegionsCount bool `json:"own_regions_count"`
OrgsPerAccount int `json:"orgs_per_account" binding:"min=0,max=100000"` OrgsPerAccount int `json:"orgs_per_account" binding:"min=0,max=100000"`
MonitorsPerPage int `json:"monitors_per_page" binding:"min=0,max=200"` MonitorsPerPage int `json:"monitors_per_page" binding:"min=0,max=1000000"`
// SubscribersPerWeek is new email subscriptions per organization and
// seven days.
SubscribersPerWeek int `json:"subscribers_per_week" binding:"min=0,max=100000000"`
} }
func (s *Server) adminSetLimits(c *gin.Context) { func (s *Server) adminSetLimits(c *gin.Context) {
@@ -243,11 +250,12 @@ func (o optBool) MarshalJSON() ([]byte, error) { return json.Marshal(o.v) }
// orgLimitsRequest overrides limits for one organization; null follows the // orgLimitsRequest overrides limits for one organization; null follows the
// platform default. // platform default.
type orgLimitsRequest struct { type orgLimitsRequest struct {
Monitors *int32 `json:"monitors" binding:"omitempty,min=0,max=1000000"` Monitors *int32 `json:"monitors" binding:"omitempty,min=0,max=1000000"`
StatusPages *int32 `json:"status_pages" 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"` RegionsPerMonitor *int32 `json:"regions_per_monitor" binding:"omitempty,min=0,max=1000"`
OwnRegionsCount optBool `json:"own_regions_count"` OwnRegionsCount optBool `json:"own_regions_count"`
MonitorsPerPage *int32 `json:"monitors_per_page" binding:"omitempty,min=0,max=200"` 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) { func (s *Server) adminSetOrgLimits(c *gin.Context) {
@@ -266,7 +274,7 @@ func (s *Server) adminSetOrgLimits(c *gin.Context) {
row, err := q.SetOrgLimits(ctx, store.SetOrgLimitsParams{ row, err := q.SetOrgLimits(ctx, store.SetOrgLimitsParams{
ID: id, Monitors: req.Monitors, StatusPages: req.StatusPages, ID: id, Monitors: req.Monitors, StatusPages: req.StatusPages,
RegionsPerMonitor: req.RegionsPerMonitor, OwnRegionsCount: req.OwnRegionsCount.v, RegionsPerMonitor: req.RegionsPerMonitor, OwnRegionsCount: req.OwnRegionsCount.v,
MonitorsPerPage: req.MonitorsPerPage, MonitorsPerPage: req.MonitorsPerPage, SubscribersPerWeek: req.SubscribersPerWeek,
}) })
auditDetail(c, "slug", row.Slug) auditDetail(c, "slug", row.Slug)
return err return err
@@ -318,11 +326,12 @@ type adminOrg struct {
} }
type orgLimitsView struct { type orgLimitsView struct {
Monitors *int32 `json:"monitors"` Monitors *int32 `json:"monitors"`
StatusPages *int32 `json:"status_pages"` StatusPages *int32 `json:"status_pages"`
RegionsPerMonitor *int32 `json:"regions_per_monitor"` RegionsPerMonitor *int32 `json:"regions_per_monitor"`
OwnRegionsCount *bool `json:"own_regions_count"` OwnRegionsCount *bool `json:"own_regions_count"`
MonitorsPerPage *int32 `json:"monitors_per_page"` MonitorsPerPage *int32 `json:"monitors_per_page"`
SubscribersPerWeek *int32 `json:"subscribers_per_week"`
} }
type adminOwner struct { type adminOwner struct {
@@ -349,10 +358,10 @@ func (s *Server) adminOrgs(ctx context.Context, search string, pg pageReq) ([]ad
o := &out[i] o := &out[i]
o.moderatedOrg = moderatedOrg{r.ID, r.Slug, r.Name, r.SuspendedAt, r.SuspendedReason} o.moderatedOrg = moderatedOrg{r.ID, r.Slug, r.Name, r.SuspendedAt, r.SuspendedReason}
o.Created = r.CreatedAt.Format("2006-01-02") o.Created = r.CreatedAt.Format("2006-01-02")
o.Overrides = orgLimitsView{r.LimitMonitors, r.LimitStatusPages, r.LimitRegionsPerMonitor, r.LimitOwnRegionsCount, r.LimitMonitorsPerPage} o.Overrides = orgLimitsView{r.LimitMonitors, r.LimitStatusPages, r.LimitRegionsPerMonitor, r.LimitOwnRegionsCount, r.LimitMonitorsPerPage, r.LimitSubscribersPerWeek}
o.Limits = s.orgLimits(ctx, store.Org{LimitMonitors: r.LimitMonitors, LimitStatusPages: r.LimitStatusPages, 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}) LimitMonitorsPerPage: r.LimitMonitorsPerPage, LimitSubscribersPerWeek: r.LimitSubscribersPerWeek})
o.Limits.OrgsPerAccount = defaults.OrgsPerAccount o.Limits.OrgsPerAccount = defaults.OrgsPerAccount
o.Usage.Monitors, o.Usage.StatusPages = int(r.Monitors), int(r.StatusPages) o.Usage.Monitors, o.Usage.StatusPages = int(r.Monitors), int(r.StatusPages)
if r.OwnerID != uuid.Nil { if r.OwnerID != uuid.Nil {
@@ -412,6 +421,7 @@ func (s *Server) orgsView(c *gin.Context, pg pageReq) (web.OrgsView, error) {
Monitors: o.Usage.Monitors, StatusPages: o.Usage.StatusPages, Limits: webLimits(o.Limits), Monitors: o.Usage.Monitors, StatusPages: o.Usage.StatusPages, Limits: webLimits(o.Limits),
MonitorsOverride: optInt(o.Overrides.Monitors), StatusPagesOverride: optInt(o.Overrides.StatusPages), MonitorsOverride: optInt(o.Overrides.Monitors), StatusPagesOverride: optInt(o.Overrides.StatusPages),
RegionsOverride: optInt(o.Overrides.RegionsPerMonitor), PerPageOverride: optInt(o.Overrides.MonitorsPerPage), RegionsOverride: optInt(o.Overrides.RegionsPerMonitor), PerPageOverride: optInt(o.Overrides.MonitorsPerPage),
SubscribersOverride: optInt(o.Overrides.SubscribersPerWeek),
} }
if o.Overrides.OwnRegionsCount != nil { if o.Overrides.OwnRegionsCount != nil {
row.OwnRegionsOverride = strconv.FormatBool(*o.Overrides.OwnRegionsCount) row.OwnRegionsOverride = strconv.FormatBool(*o.Overrides.OwnRegionsCount)
+5 -1
View File
@@ -224,7 +224,11 @@ func (s *Server) listMonitors(c *gin.Context) {
if err != nil { if err != nil {
return err return err
} }
latest, err := q.LatestResults(ctx, p.Org.ID) ids := make([]uuid.UUID, len(monitors))
for i, m := range monitors {
ids[i] = m.ID
}
latest, err := q.LatestResultsForMonitors(ctx, store.LatestResultsForMonitorsParams{OrgID: p.Org.ID, Ids: ids})
if err != nil { if err != nil {
return err return err
} }
+1 -1
View File
@@ -625,7 +625,7 @@ func (s *Server) adminPage(c *gin.Context) {
for _, t := range check.Types { for _, t := range check.Types {
types = append(types, web.CheckTypeOption{Type: string(t), Enabled: !off[string(t)]}) types = append(types, web.CheckTypeOption{Type: string(t), Enabled: !off[string(t)]})
} }
web.Render(c, http.StatusOK, web.AdminPage(s.pageFor(c, "admin.title"), me, v, storageView(c, stats), types, s.platformPrivate(ctx), webLimits(s.platformLimits(ctx)), s.idpAdminView(ctx))) web.Render(c, http.StatusOK, web.AdminPage(s.pageFor(c, "admin.title"), me, v, storageView(c, stats), types, s.platformPrivate(ctx), s.statusPageHome(ctx), webLimits(s.platformLimits(ctx)), s.idpAdminView(ctx)))
} }
func (s *Server) adminStatusPagesPage(c *gin.Context) { func (s *Server) adminStatusPagesPage(c *gin.Context) {
+2 -7
View File
@@ -134,10 +134,7 @@ func (s *Server) messageFor(ev notify.Event, locale string) notify.Message {
switch ev.Kind { switch ev.Kind {
case notify.Opened: case notify.Opened:
m.Title = l.T("notify.title_opened", data) m.Title = l.T("notify.title_opened", data)
for region, msg := range ev.Cause { lines = causeLines(ev, l)
lines = append(lines, region+": "+msg)
}
slices.Sort(lines)
case notify.Resolved: case notify.Resolved:
m.Title = l.T("notify.title_resolved", data) m.Title = l.T("notify.title_resolved", data)
if ev.ResolvedAt != nil { if ev.ResolvedAt != nil {
@@ -151,8 +148,6 @@ func (s *Server) messageFor(ev notify.Event, locale string) notify.Message {
lines = append([]string{ev.Monitor.Type + " · " + ev.Monitor.Target}, lines...) lines = append([]string{ev.Monitor.Type + " · " + ev.Monitor.Target}, lines...)
} }
m.Body = strings.Join(lines, "\n") m.Body = strings.Join(lines, "\n")
if ev.Monitor.ID != [16]byte{} { m.URL = s.monitorLink(ev)
m.URL = strings.TrimSuffix(s.cfg.PublicURL, "/") + "/monitors/" + ev.Monitor.ID.String()
}
return m return m
} }
+10 -2
View File
@@ -8,6 +8,7 @@ import (
"time" "time"
"github.com/google/uuid" "github.com/google/uuid"
"github.com/jackc/pgx/v5"
) )
func TestTimeRangesAndSLA(t *testing.T) { func TestTimeRangesAndSLA(t *testing.T) {
@@ -53,7 +54,7 @@ func TestTimeRangesAndSLA(t *testing.T) {
} }
} }
bars := map[string]int{"1h": 60, "3h": 36, "12h": 48, "24h": 48, "7d": 42, "30d": 60, "90d": 45, "180d": 45, "1y": 52} bars := map[string]int{"1h": 60, "3h": 36, "12h": 48, "24h": 24, "7d": 42, "30d": 60, "90d": 45, "180d": 45, "1y": 52}
for key, n := range bars { for key, n := range bars {
st, _, html := owner.page("/?range=" + key) st, _, html := owner.page("/?range=" + key)
if st != http.StatusOK { if st != http.StatusOK {
@@ -99,9 +100,16 @@ func TestRangeAvailabilityAndRegions(t *testing.T) {
id := uuid.MustParse(body["id"].(string)) id := uuid.MustParse(body["id"].(string))
org := uuid.MustParse(owner.orgID()) org := uuid.MustParse(owner.orgID())
// Two hours of results: eu always fine, us always failing. // Two hours of results: eu always fine, us always failing. (The
// monitor is as old as its results.)
ctx := context.Background() ctx := context.Background()
now := time.Now() now := time.Now()
if err := e.asSystem(t, func(tx pgx.Tx) error {
_, err := tx.Exec(ctx, `UPDATE monitors SET created_at = $1 WHERE id = $2`, now.Add(-121*time.Minute), id)
return err
}); err != nil {
t.Fatal(err)
}
checker := uuid.New() checker := uuid.New()
for m := 0; m <= 120; m += 5 { for m := 0; m <= 120; m += 5 {
at := now.Add(-time.Duration(m) * time.Minute) at := now.Add(-time.Duration(m) * time.Minute)
+7
View File
@@ -56,6 +56,8 @@ type Server struct {
limits *versioned[Limits] limits *versioned[Limits]
// support caches how the platform runs support tickets. // support caches how the platform runs support tickets.
support *versioned[supportSettings] support *versioned[supportSettings]
// pageHome caches the home page the status page servers link.
pageHome *versioned[string]
// draining, once closed, ends the long polls of checkers. // draining, once closed, ends the long polls of checkers.
draining <-chan struct{} draining <-chan struct{}
// handler serves the requests agents send over their streams. // handler serves the requests agents send over their streams.
@@ -99,6 +101,7 @@ func New(cfg config.API, d Deps) *Server {
checkerNet: newVersioned[bool]("checker-network"), checkerNet: newVersioned[bool]("checker-network"),
limits: newVersioned[Limits]("limits"), limits: newVersioned[Limits]("limits"),
support: newVersioned[supportSettings]("support"), support: newVersioned[supportSettings]("support"),
pageHome: newVersioned[string]("statuspage-home"),
} }
} }
@@ -224,6 +227,8 @@ func (s *Server) Mount(r gin.IRouter) {
admin.PUT("/users/:id/suspension", s.adminSuspendUser) admin.PUT("/users/:id/suspension", s.adminSuspendUser)
admin.DELETE("/users/:id", s.adminDeleteUser) admin.DELETE("/users/:id", s.adminDeleteUser)
admin.PUT("/checker-network", s.adminSetCheckerNetwork) admin.PUT("/checker-network", s.adminSetCheckerNetwork)
admin.GET("/statuspage-home", s.adminGetStatusPageHome)
admin.PUT("/statuspage-home", s.adminSetStatusPageHome)
admin.GET("/legal", s.adminListLegal) admin.GET("/legal", s.adminListLegal)
admin.PUT("/legal/:kind", s.adminSaveLegal) admin.PUT("/legal/:kind", s.adminSaveLegal)
admin.GET("/regions", s.adminListRegions) admin.GET("/regions", s.adminListRegions)
@@ -251,6 +256,8 @@ func (s *Server) Mount(r gin.IRouter) {
page.POST("/groups/import", canPage(authz.StatusPagesWrite), s.importStatusPageGroups) page.POST("/groups/import", canPage(authz.StatusPagesWrite), s.importStatusPageGroups)
page.PUT("/monitors", canPage(authz.StatusPagesWrite), s.setPageMonitors) page.PUT("/monitors", canPage(authz.StatusPagesWrite), s.setPageMonitors)
page.PUT("/domain", canPage(authz.StatusPagesWrite), s.setPageDomain) 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.POST("/domain/verify", canPage(authz.StatusPagesWrite), s.verifyPageDomain)
page.GET("/export", canPage(authz.StatusPagesRead), s.exportStatusPage) page.GET("/export", canPage(authz.StatusPagesRead), s.exportStatusPage)
+77
View File
@@ -0,0 +1,77 @@
package api
import (
"context"
"encoding/json"
"errors"
"net/http"
"strings"
"github.com/gin-gonic/gin"
"github.com/jackc/pgx/v5"
"git.zb-server.de/ZB-Server/uptimesebi/internal/store"
"git.zb-server.de/ZB-Server/uptimesebi/internal/tenant"
)
// The status page servers answer visitors of pages that do not exist, and
// of their bare domain, with a page linking the platform's home page.
const settingStatusPageHome = "statuspage_home"
type statusPageHome struct {
// URL is the home page linked from the status page servers' error
// page; empty links none.
URL string `json:"url" binding:"max=2000"`
}
func (s *Server) statusPageHome(ctx context.Context) string {
v, err := s.pageHome.get(ctx, s.rdb, func(ctx context.Context) (string, error) {
var v statusPageHome
err := s.db.Tx(ctx, tenant.System(), func(q *store.Queries) error {
raw, err := q.GetPlatformSetting(ctx, settingStatusPageHome)
if errors.Is(err, pgx.ErrNoRows) {
return nil
}
if err != nil {
return err
}
return json.Unmarshal(raw, &v)
})
return v.URL, err
})
if err != nil {
s.log.WarnContext(ctx, "loading the status page home failed", "error", err)
return ""
}
return v
}
func (s *Server) adminGetStatusPageHome(c *gin.Context) {
c.JSON(http.StatusOK, statusPageHome{URL: s.statusPageHome(c.Request.Context())})
}
func (s *Server) adminSetStatusPageHome(c *gin.Context) {
var req statusPageHome
if !bind(c, &req) {
return
}
req.URL = strings.TrimSpace(req.URL)
if req.URL != "" && !validLegalURL(req.URL) {
fail(c, http.StatusUnprocessableEntity, "invalid_legal_url")
return
}
ctx := c.Request.Context()
raw, _ := json.Marshal(req)
auditDetail(c, "url", req.URL)
if err := s.db.Tx(ctx, tenant.System(), func(q *store.Queries) error {
return q.SetPlatformSetting(ctx, store.SetPlatformSettingParams{Key: settingStatusPageHome, Value: raw})
}); err != nil {
internalError(c, err)
return
}
if err := s.pageHome.bump(ctx, s.rdb); err != nil {
s.log.ErrorContext(ctx, "announcing the status page home failed", "error", err)
}
c.Status(http.StatusNoContent)
}
+46
View File
@@ -0,0 +1,46 @@
package api_test
import (
"context"
"net/http"
"strings"
"testing"
"git.zb-server.de/ZB-Server/uptimesebi/internal/store"
"git.zb-server.de/ZB-Server/uptimesebi/internal/tenant"
)
func TestStatusPageHome(t *testing.T) {
e := newEnv(t)
admin := e.browser(t)
admin.signup("a@"+uniq("home")+".test", uniq("home-"))
if err := tenant.New(e.dbPool).Tx(context.Background(), tenant.Global(), func(q *store.Queries) error {
return q.MakeAdmin(context.Background(), admin.userIDSelf())
}); err != nil {
t.Fatal(err)
}
t.Cleanup(func() { admin.do("PUT", "/api/v1/admin/statuspage-home", map[string]any{"url": ""}) })
pages := e.statuspageClient(t, nil)
st, body := admin.do("PUT", "/api/v1/admin/statuspage-home", map[string]any{"url": "javascript:alert(1)"})
expect(t, "script link", st, body, http.StatusUnprocessableEntity, "invalid_legal_url")
if st, body := admin.do("PUT", "/api/v1/admin/statuspage-home", map[string]any{"url": " https://example.test/ "}); st != http.StatusNoContent {
t.Fatalf("set home = %d %v", st, body)
}
if _, body := admin.do("GET", "/api/v1/admin/statuspage-home", nil); body["url"] != "https://example.test/" {
t.Errorf("home = %v", body)
}
index, err := pages.Pages(context.Background())
if err != nil || index.HomeURL != "https://example.test/" {
t.Errorf("page index home = %q %v", index.HomeURL, err)
}
if _, _, html := admin.page("/admin"); !strings.Contains(html, `value="https://example.test/"`) {
t.Error("the admin page does not show the home page")
}
owner := e.browser(t)
owner.signup("o@"+uniq("home")+".test", uniq("home-"))
if st, _ := owner.do("PUT", "/api/v1/admin/statuspage-home", map[string]any{"url": "https://evil.test/"}); st != http.StatusForbidden {
t.Errorf("non-admin sets the home page = %d, want 403", st)
}
}
+21 -13
View File
@@ -53,6 +53,7 @@ func (s *Server) buildSnapshot(ctx context.Context, page store.StatusPage) (agen
Title: page.Title, Title: page.Title,
Description: page.Description, Description: page.Description,
ShowDetails: page.ShowComponentDetails, ShowDetails: page.ShowComponentDetails,
Subscribe: page.Subscriptions && s.smtp != nil,
Sections: []agentapi.Section{}, Sections: []agentapi.Section{},
Incidents: []agentapi.PageIncident{}, Incidents: []agentapi.PageIncident{},
GeneratedAt: time.Now(), GeneratedAt: time.Now(),
@@ -127,8 +128,9 @@ func (s *Server) buildSnapshot(ctx context.Context, page store.StatusPage) (agen
return err return err
} }
docs, err := q.LegalDocuments(ctx, &page.OrgID) docs, err := q.LegalDocuments(ctx, &page.OrgID)
// Visitors of status pages accept no terms. // Visitors of status pages accept the platform's terms only when
snap.Legal = slices.DeleteFunc(mergeLegal(docs), func(d agentapi.LegalDoc) bool { return d.Kind == "terms" }) // they subscribe to it.
snap.Legal = slices.DeleteFunc(mergeLegal(docs), func(d agentapi.LegalDoc) bool { return d.Kind == "terms" && !snap.Subscribe })
return err return err
}) })
if err != nil { if err != nil {
@@ -234,7 +236,7 @@ func (s *Server) buildSnapshot(ctx context.Context, page store.StatusPage) (agen
for _, i := range incidents { for _, i := range incidents {
st := statuses.of(i) st := statuses.of(i)
snap.Incidents = append(snap.Incidents, agentapi.PageIncident{ 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], Title: i.Title, Status: st.Key, StatusName: st.Name, StatusColor: st.Color, Updates: updatesOf[i.ID],
}) })
} }
@@ -459,16 +461,18 @@ func (s *Server) agentPageIndex(c *gin.Context) {
for i, r := range rows { for i, r := range rows {
out[i] = agentapi.PageRef{Slug: r.Slug, Host: r.Host} out[i] = agentapi.PageRef{Slug: r.Slug, Host: r.Host}
} }
c.JSON(http.StatusOK, gin.H{"pages": out}) c.JSON(http.StatusOK, agentapi.PageIndex{Pages: out, HomeURL: s.statusPageHome(ctx)})
} }
type statusPageRequest struct { type statusPageRequest struct {
Slug string `json:"slug" binding:"required,max=63"` Slug string `json:"slug" binding:"required,max=63"`
Title string `json:"title" binding:"required,max=200"` Title string `json:"title" binding:"required,max=200"`
Description string `json:"description" binding:"max=10000"` Description string `json:"description" binding:"max=10000"`
Published bool `json:"published"` Published bool `json:"published"`
ShowComponentDetails bool `json:"show_component_details"` ShowComponentDetails bool `json:"show_component_details"`
Theme agentapi.Theme `json:"theme"` // Subscriptions lets visitors subscribe to incidents by email.
Subscriptions bool `json:"subscriptions"`
Theme agentapi.Theme `json:"theme"`
} }
func (r *statusPageRequest) normalize() string { func (r *statusPageRequest) normalize() string {
@@ -504,6 +508,7 @@ type statusPageView struct {
Description string `json:"description"` Description string `json:"description"`
Published bool `json:"published"` Published bool `json:"published"`
ShowComponentDetails bool `json:"show_component_details"` ShowComponentDetails bool `json:"show_component_details"`
Subscriptions bool `json:"subscriptions"`
Theme agentapi.Theme `json:"theme"` Theme agentapi.Theme `json:"theme"`
CustomDomain *string `json:"custom_domain"` CustomDomain *string `json:"custom_domain"`
DomainVerified bool `json:"domain_verified"` DomainVerified bool `json:"domain_verified"`
@@ -531,7 +536,7 @@ type dnsRecord struct {
func (s *Server) viewStatusPage(p store.StatusPage) statusPageView { func (s *Server) viewStatusPage(p store.StatusPage) statusPageView {
v := statusPageView{ v := statusPageView{
ID: p.ID, Slug: p.Slug, Title: p.Title, Description: p.Description, 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, CustomDomain: p.CustomDomain, DomainVerified: p.DomainVerifiedAt != nil,
Suspended: p.SuspendedAt != nil, SuspendedReason: p.SuspendedReason, Suspended: p.SuspendedAt != nil, SuspendedReason: p.SuspendedReason,
} }
@@ -607,7 +612,7 @@ func (s *Server) createStatusPage(c *gin.Context) {
row, err = q.CreateStatusPage(ctx, store.CreateStatusPageParams{ row, err = q.CreateStatusPage(ctx, store.CreateStatusPageParams{
OrgID: p.Org.ID, Slug: req.Slug, Title: req.Title, Description: req.Description, OrgID: p.Org.ID, Slug: req.Slug, Title: req.Title, Description: req.Description,
Published: req.Published, ShowComponentDetails: req.ShowComponentDetails, Published: req.Published, ShowComponentDetails: req.ShowComponentDetails,
DomainToken: newDomainToken(), Theme: theme, DomainToken: newDomainToken(), Theme: theme, Subscriptions: req.Subscriptions,
}) })
return err return err
}) })
@@ -650,6 +655,7 @@ func (s *Server) updateStatusPage(c *gin.Context) {
row, err = q.UpdateStatusPage(ctx, store.UpdateStatusPageParams{ row, err = q.UpdateStatusPage(ctx, store.UpdateStatusPageParams{
ID: id, Slug: req.Slug, Title: req.Title, Description: req.Description, ID: id, Slug: req.Slug, Title: req.Title, Description: req.Description,
Published: req.Published, ShowComponentDetails: req.ShowComponentDetails, Theme: theme, Published: req.Published, ShowComponentDetails: req.ShowComponentDetails, Theme: theme,
Subscriptions: req.Subscriptions,
}) })
return err return err
}) })
@@ -694,7 +700,9 @@ type pageMonitor struct {
} }
type pageMonitorsRequest 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 // setPageMonitors replaces the page's components; their order is the
+2 -1
View File
@@ -205,7 +205,8 @@ func TestStatusPages(t *testing.T) {
own := e.statuspageClient(t, &org) own := e.statuspageClient(t, &org)
lists := func(c *agentapi.Client) bool { lists := func(c *agentapi.Client) bool {
t.Helper() t.Helper()
refs, err := c.Pages(context.Background()) index, err := c.Pages(context.Background())
refs := index.Pages
if err != nil { if err != nil {
t.Fatal(err) t.Fatal(err)
} }
+449
View File
@@ -0,0 +1,449 @@
package api
import (
"context"
"crypto/sha256"
"encoding/base64"
"encoding/binary"
"encoding/hex"
"errors"
"net/http"
"net/mail"
"net/netip"
"net/url"
"strings"
"time"
"github.com/gin-gonic/gin"
"github.com/google/uuid"
"github.com/jackc/pgx/v5"
"git.zb-server.de/ZB-Server/uptimesebi/internal/agentapi"
"git.zb-server.de/ZB-Server/uptimesebi/internal/notify"
"git.zb-server.de/ZB-Server/uptimesebi/internal/store"
"git.zb-server.de/ZB-Server/uptimesebi/internal/tenant"
)
// Visitors subscribe to a status page's incidents by email. A subscription
// counts towards the organization's weekly limit as soon as it is asked
// for, and nothing but the confirmation is mailed until the address
// confirms it, so the form cannot be used to flood strangers' inboxes.
const (
// confirmTTL is how long a confirmation link works.
confirmTTL = 48 * time.Hour
// subscriberWindow is the window of the weekly limit; unconfirmed
// subscriptions are kept as long, so they keep counting.
subscriberWindow = 7 * 24 * time.Hour
subscriberBatch = 50
// maxSubscriberAttempts bounds retries of one mail.
maxSubscriberAttempts = 6
// maxSubscriberList bounds the subscribers listed in the console.
maxSubscriberList = 1000
)
// Rate limits of subscription requests, per visitor address, mailbox and
// page, on top of the organization's weekly limit.
const (
subscribePerIP = 5
subscribePerEmail = 3
subscribePerPage = 100
subscribeIPWindow = time.Hour
subscribeMailboxIn = 24 * time.Hour
)
// Token purposes; a token of one is never accepted as the other.
const (
tokenConfirm = "confirm"
tokenUnsubscribe = "unsubscribe"
)
// subscriberToken seals the subscriber's ID and an expiry (zero for none),
// so links need no table of their own and an unsubscribe link can be put
// into every mail.
func (s *Server) subscriberToken(id uuid.UUID, purpose string, expires time.Time) string {
b := make([]byte, 24)
copy(b, id[:])
if !expires.IsZero() {
binary.BigEndian.PutUint64(b[16:], uint64(expires.Unix()))
}
return base64.RawURLEncoding.EncodeToString(s.keys.Seal(b, []byte("subscriber:"+purpose)))
}
func (s *Server) openSubscriberToken(token, purpose string, now time.Time) (uuid.UUID, bool) {
raw, err := base64.RawURLEncoding.DecodeString(token)
if err != nil || len(token) > 300 {
return uuid.Nil, false
}
b, err := s.keys.Open(raw, []byte("subscriber:"+purpose))
if err != nil || len(b) != 24 {
return uuid.Nil, false
}
if exp := binary.BigEndian.Uint64(b[16:]); exp != 0 && now.Unix() > int64(exp) {
return uuid.Nil, false
}
id, err := uuid.FromBytes(b[:16])
return id, err == nil
}
// subscriberEmail returns the address in normalized form, or false if it
// is none.
func subscriberEmail(raw string) (string, bool) {
e := normalizeEmail(raw)
a, err := mail.ParseAddress(e)
if err != nil || a.Address != e || len(e) > 254 || !strings.Contains(e[strings.LastIndexByte(e, '@')+1:], ".") {
return "", false
}
return e, true
}
func mailboxKey(email string) string {
sum := sha256.Sum256([]byte(email))
return hex.EncodeToString(sum[:12])
}
// subscriberPageURL is the page address for links in mails, ending in "/":
// the platform's own where it knows it, else the one the visitor used.
func (s *Server) subscriberPageURL(page store.StatusPage, ownServers bool, given string) string {
if known := s.pageURL(page, ownServers); absoluteURL(known) {
return strings.TrimSuffix(known, "/") + "/"
}
if !absoluteURL(given) || len(given) > 500 {
return ""
}
u, _ := url.Parse(given)
u.RawQuery, u.Fragment = "", ""
return strings.TrimSuffix(u.String(), "/") + "/"
}
func absoluteURL(raw string) bool {
u, err := url.Parse(raw)
return err == nil && (u.Scheme == "https" || u.Scheme == "http") && u.Host != ""
}
// agentSubscribe asks for a subscription for a visitor of a status page
// server and mails the confirmation. It answers the same whether the
// address was subscribed already or not.
func (s *Server) agentSubscribe(c *gin.Context) {
var req agentapi.SubscribeRequest
if !bind(c, &req) {
return
}
email, ok := subscriberEmail(req.Email)
if !ok {
fail(c, http.StatusUnprocessableEntity, "invalid_email")
return
}
if !req.Accepted {
fail(c, http.StatusUnprocessableEntity, "consent_required")
return
}
ctx := c.Request.Context()
a := agentOf(c)
var host, slug *string
if h := strings.ToLower(strings.TrimSpace(req.Host)); h != "" {
host = &h
} else if sl := strings.ToLower(strings.TrimSpace(req.Slug)); sl != "" {
slug = &sl
} else {
fail(c, http.StatusBadRequest, "invalid_input")
return
}
page, ok, err := s.agentServes(ctx, a, host, slug)
if err != nil {
internalError(c, err)
return
}
if !ok || !page.Subscriptions || s.smtp == nil {
fail(c, http.StatusNotFound, "not_found")
return
}
ip := c.ClientIP()
if addr, err := netip.ParseAddr(req.IP); err == nil {
ip = addr.String()
}
if !s.limit(c, "subscribe:ip:"+ip, subscribePerIP, subscribeIPWindow) ||
!s.limit(c, "subscribe:mailbox:"+mailboxKey(email), subscribePerEmail, subscribeMailboxIn) ||
!s.limit(c, "subscribe:page:"+page.ID.String(), subscribePerPage, time.Hour) {
return
}
locale := s.catalog.Match(req.Locale).Lang()
pageURL := s.subscriberPageURL(page, a.OrgID != nil, req.PageURL)
var (
sub store.StatusPageSubscriber
send bool
)
err = s.db.Tx(ctx, tenant.Org(page.OrgID, uuid.Nil), func(q *store.Queries) error {
org, err := q.GetOrg(ctx, page.OrgID)
if err != nil {
return err
}
if err := q.LockOrgUsage(ctx, page.OrgID); err != nil {
return err
}
existing, err := q.GetPageSubscriberByEmail(ctx, store.GetPageSubscriberByEmailParams{PageID: page.ID, Email: email})
switch {
case err == nil && existing.ConfirmedAt != nil:
return nil
case err == nil:
sub, send = existing, true
return q.TouchPendingSubscriber(ctx, store.TouchPendingSubscriberParams{ID: existing.ID, Locale: locale, PageUrl: pageURL})
case !errors.Is(err, pgx.ErrNoRows):
return err
}
if max := s.orgLimits(ctx, org).SubscribersPerWeek; max > 0 {
n, err := q.CountRecentSubscribers(ctx, store.CountRecentSubscribersParams{OrgID: page.OrgID, CreatedAt: time.Now().Add(-subscriberWindow)})
if err != nil {
return err
}
if n >= int64(max) {
return limitError{"subscriber_limit", max}
}
}
sub, err = q.CreatePageSubscriber(ctx, store.CreatePageSubscriberParams{
OrgID: page.OrgID, PageID: page.ID, Email: email, Locale: locale, PageUrl: pageURL,
})
send = err == nil
return err
})
var le limitError
switch {
case errors.As(err, &le):
s.log.WarnContext(ctx, "status page subscriptions reached the weekly limit", "org", page.OrgID, "page", page.ID, "max", le.max)
c.Header("Retry-After", "3600")
fail(c, http.StatusTooManyRequests, le.code)
return
case err != nil:
internalError(c, err)
return
}
if send {
if err := s.sendSubscriberConfirmation(ctx, sub, page.Title, pageURL); err != nil {
s.log.WarnContext(ctx, "mailing a subscription confirmation failed", "page", page.ID, "error", err)
internalError(c, err)
return
}
}
c.Status(http.StatusAccepted)
}
func (s *Server) sendSubscriberConfirmation(ctx context.Context, sub store.StatusPageSubscriber, title, pageURL string) error {
if pageURL == "" {
return errors.New("api: no address of the status page for the confirmation link")
}
token := s.subscriberToken(sub.ID, tokenConfirm, time.Now().Add(confirmTTL))
l := s.catalog.Match(sub.Locale)
data := map[string]any{"Page": title, "Link": pageURL + "subscribe/confirm?token=" + url.QueryEscape(token), "Hours": int(confirmTTL.Hours())}
return s.smtp.Send(ctx, notify.Mail{
To: []string{sub.Email}, Subject: l.T("email.subscribe.subject", data), Body: l.T("email.subscribe.body", data),
})
}
type subscriptionTokenRequest struct {
Token string `json:"token" binding:"required,max=300"`
}
// agentConfirmSubscription confirms a subscription from its mailed link.
func (s *Server) agentConfirmSubscription(c *gin.Context) {
s.subscriptionByToken(c, tokenConfirm, func(ctx context.Context, q *store.Queries, sub store.GetPageSubscriberRow) error {
return q.ConfirmPageSubscriber(ctx, sub.ID)
})
}
// agentUnsubscribe ends a subscription from the link in a mail.
func (s *Server) agentUnsubscribe(c *gin.Context) {
s.subscriptionByToken(c, tokenUnsubscribe, func(ctx context.Context, q *store.Queries, sub store.GetPageSubscriberRow) error {
_, err := q.DeletePageSubscriber(ctx, store.DeletePageSubscriberParams{ID: sub.ID, PageID: sub.PageID})
return err
})
}
func (s *Server) subscriptionByToken(c *gin.Context, purpose string, act func(context.Context, *store.Queries, store.GetPageSubscriberRow) error) {
var req subscriptionTokenRequest
if !bind(c, &req) {
return
}
id, ok := s.openSubscriberToken(req.Token, purpose, time.Now())
if !ok {
fail(c, http.StatusNotFound, "not_found")
return
}
ctx := c.Request.Context()
a := agentOf(c)
var sub store.GetPageSubscriberRow
err := s.db.Tx(ctx, tenant.System(), func(q *store.Queries) error {
var err error
if sub, err = q.GetPageSubscriber(ctx, id); err != nil {
return err
}
// An organization's server acts only on its own pages.
if a.OrgID != nil && *a.OrgID != sub.OrgID {
return pgx.ErrNoRows
}
return act(ctx, q, sub)
})
switch {
case errors.Is(err, pgx.ErrNoRows):
fail(c, http.StatusNotFound, "not_found")
case err != nil:
internalError(c, err)
default:
c.JSON(http.StatusOK, agentapi.SubscriptionInfo{PageTitle: sub.PageTitle, Email: sub.Email})
}
}
// deliverSubscriberBatch mails queued incident events to subscribers.
func (s *Server) deliverSubscriberBatch(ctx context.Context) int {
if s.smtp == nil {
return 0
}
var rows []store.SubscriberNotificationDetailsRow
err := s.db.Tx(ctx, tenant.System(), func(q *store.Queries) error {
ids, err := q.ClaimSubscriberNotifications(ctx, subscriberBatch)
if err != nil || len(ids) == 0 {
return err
}
rows, err = q.SubscriberNotificationDetails(ctx, ids)
return err
})
if err != nil {
if ctx.Err() == nil {
s.log.WarnContext(ctx, "claiming subscriber notifications failed", "error", err)
}
return 0
}
for _, n := range rows {
sendErr := s.smtp.Send(ctx, s.subscriberMail(n))
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)
}
}
+257
View File
@@ -0,0 +1,257 @@
package api_test
import (
"context"
"encoding/json"
"log/slog"
"net/http"
"net/http/httptest"
"net/url"
"regexp"
"strings"
"sync/atomic"
"testing"
"time"
"github.com/gin-gonic/gin"
"github.com/jackc/pgx/v5"
"git.zb-server.de/ZB-Server/uptimesebi/internal/config"
"git.zb-server.de/ZB-Server/uptimesebi/internal/i18n"
"git.zb-server.de/ZB-Server/uptimesebi/internal/notify/notifytest"
"git.zb-server.de/ZB-Server/uptimesebi/internal/statuspage"
)
var tokenRE = regexp.MustCompile(`token=([A-Za-z0-9_%-]+)`)
func TestStatusPageSubscriptions(t *testing.T) {
mail := notifytest.NewSMTP(t)
e := newEnvWith(t, func(c *config.API) { c.SMTPURL, c.SignupVerify = mail.URL(), "off" })
ctx, cancel := context.WithCancel(context.Background())
t.Cleanup(cancel)
go e.api.RunScheduler(ctx)
go e.api.RunNotifier(ctx)
var healthy atomic.Bool
healthy.Store(true)
target := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
if !healthy.Load() {
w.WriteHeader(http.StatusServiceUnavailable)
}
}))
defer target.Close()
tok, region := e.platformChecker(t, uniq("eu-"))
e.startChecker(t, tok)
owner := e.browser(t)
owner.signup("o@"+uniq("sub")+".test", uniq("sub-"))
_, body := owner.do("POST", "/api/v1/org/monitors", map[string]any{
"name": "Shop", "type": "http", "target": target.URL, "interval_seconds": 10, "confirmations": 1, "regions": []string{region},
})
monitorID := body["id"].(string)
slug := uniq("subs-")
_, body = owner.do("POST", "/api/v1/org/statuspages", map[string]any{"slug": slug, "title": "Shop Status"})
pageID := body["id"].(string)
page := map[string]any{"slug": slug, "title": "Shop Status", "published": true, "subscriptions": true}
st, body := owner.do("PUT", "/api/v1/org/statuspages/"+pageID, page)
if st != http.StatusOK || body["subscriptions"] != true {
t.Fatalf("enable subscriptions = %d %v", st, body)
}
owner.do("PUT", "/api/v1/org/statuspages/"+pageID+"/monitors", map[string]any{"monitors": []map[string]any{{"monitor_id": monitorID}}})
cat, _ := i18n.Load()
pages, err := statuspage.New(e.statuspageClient(t, nil), cat, slog.New(slog.DiscardHandler), statuspage.Options{Hosts: []string{"status.test"}})
if err != nil {
t.Fatal(err)
}
gin.SetMode(gin.TestMode)
router := gin.New()
pages.Mount(router)
visitor := "198.51.100.7:1234"
visit := func(method, path, form string) (int, string, http.Header) {
t.Helper()
req := httptest.NewRequest(method, path, strings.NewReader(form))
req.Host = "status.test"
req.RemoteAddr = visitor
if form != "" {
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
}
w := httptest.NewRecorder()
router.ServeHTTP(w, req)
pages.Wait()
return w.Code, w.Body.String(), w.Header()
}
subscribers := func() (int, int) {
_, body := owner.do("GET", "/api/v1/org/statuspages/"+pageID+"/subscribers", nil)
return int(body["confirmed"].(float64)), int(body["pending"].(float64))
}
mailsTo := func(addr string) []string {
var out []string
for _, m := range mail.Messages() {
if len(m.To) == 1 && m.To[0] == addr {
out = append(out, m.Data)
}
}
return out
}
// Subscribers accept the page's privacy policy.
if st, body := owner.do("PUT", "/api/v1/org/legal/privacy", map[string]any{"url": "https://shop.example/privacy"}); st != http.StatusNoContent {
t.Fatalf("set privacy policy = %d %v", st, body)
}
t.Cleanup(func() { owner.do("PUT", "/api/v1/org/legal/privacy", map[string]any{}) })
pages.Sync(ctx)
code, html, _ := visit("GET", "/"+slug, "")
if code != 200 || !strings.Contains(html, `action="/`+slug+`/subscribe"`) || !strings.Contains(html, "feed.rss") {
t.Fatalf("page = %d, want the subscription form and the feed link", code)
}
if !strings.Contains(html, `name="accept"`) || !strings.Contains(html, `href="https://shop.example/privacy"`) {
t.Error("the subscription form does not ask to accept the privacy policy")
}
if code, html, _ := visit("POST", "/"+slug+"/subscribe", "email=not-an-address&accept=1"); code != http.StatusUnprocessableEntity {
t.Errorf("subscribing an invalid address = %d %.200s", code, html)
}
visitor = "198.51.100.9:1234" // (not to use up the subscription requests of the first)
if code, _, _ := visit("POST", "/"+slug+"/subscribe", "email=visitor@example.test"); code != http.StatusUnprocessableEntity {
t.Errorf("subscribing without accepting the privacy policy = %d, want 422", code)
}
visitor = "198.51.100.7:1234"
if code, _, _ := visit("POST", "/"+slug+"/subscribe", "email=Visitor@Example.test&accept=1"); code != 200 {
t.Fatalf("subscribe = %d", code)
}
if c, p := subscribers(); c != 0 || p != 1 {
t.Errorf("subscribers after subscribing = %d confirmed, %d pending; want 0, 1", c, p)
}
sent := mailsTo("visitor@example.test")
if len(sent) != 1 || !strings.Contains(sent[0], "Shop Status") {
t.Fatalf("confirmation mails = %d", len(sent))
}
m := tokenRE.FindStringSubmatch(sent[0])
if m == nil {
t.Fatal("no token in the confirmation mail")
}
confirm, _ := url.QueryUnescape(m[1])
// Opening the link only shows a button.
if code, html, _ := visit("GET", "/"+slug+"/subscribe/confirm?token="+url.QueryEscape(confirm), ""); code != 200 || !strings.Contains(html, `name="token"`) {
t.Errorf("confirmation link = %d", code)
}
if c, _ := subscribers(); c != 0 {
t.Error("opening the confirmation link confirmed the subscription")
}
if code, _, _ := visit("POST", "/"+slug+"/unsubscribe", "token="+url.QueryEscape(confirm)); code != http.StatusNotFound {
t.Errorf("unsubscribing with the confirmation token = %d, want 404", code)
}
if code, html, _ := visit("POST", "/"+slug+"/subscribe/confirm", "token="+url.QueryEscape(confirm)); code != 200 || !strings.Contains(html, "visitor@example.test") {
t.Fatalf("confirm = %d %.300s", code, html)
}
if c, p := subscribers(); c != 1 || p != 0 {
t.Errorf("subscribers after confirming = %d, %d; want 1, 0", c, p)
}
// Asking again for a confirmed address mails nothing.
visit("POST", "/"+slug+"/subscribe", "email=visitor@example.test&accept=1")
if n := len(mailsTo("visitor@example.test")); n != 1 {
t.Errorf("mails after subscribing a confirmed address again = %d, want 1", n)
}
healthy.Store(false)
waitFor(t, 30*time.Second, "outage mail to the subscriber", func() bool { return len(mailsTo("visitor@example.test")) == 2 })
outage := mailsTo("visitor@example.test")[1]
if !strings.Contains(outage, "Shop") || !strings.Contains(outage, "List-Unsubscribe: <http") || !strings.Contains(outage, "List-Unsubscribe-Post: List-Unsubscribe=One-Click") {
t.Errorf("outage mail = %.600s", outage)
}
_, body = owner.do("GET", "/api/v1/org/incidents", nil)
incidentID := body["incidents"].([]any)[0].(map[string]any)["id"].(string)
owner.do("POST", "/api/v1/org/incidents/"+incidentID+"/updates", map[string]any{"status": "identified", "message": "Payment provider down", "public": false})
owner.do("POST", "/api/v1/org/incidents/"+incidentID+"/updates", map[string]any{"status": "identified", "message": "We found the cause", "public": true})
waitFor(t, 10*time.Second, "update mail", func() bool { return len(mailsTo("visitor@example.test")) == 3 })
if upd := mailsTo("visitor@example.test")[2]; !strings.Contains(upd, "We found the cause") {
t.Errorf("update mail = %.400s", upd)
}
time.Sleep(3 * time.Second)
for _, m := range mailsTo("visitor@example.test") {
if strings.Contains(m, "Payment provider down") {
t.Error("a private update was mailed to a subscriber")
}
}
// Feed and API come from the snapshot.
pages.Sync(ctx)
code, feed, hdr := visit("GET", "/"+slug+"/feed.rss", "")
if code != 200 || !strings.HasPrefix(hdr.Get("Content-Type"), "application/rss+xml") || !strings.Contains(feed, "<rss") ||
!strings.Contains(feed, "incident-"+incidentID) || !strings.Contains(feed, "We found the cause") {
t.Errorf("feed = %d %.600s", code, feed)
}
code, raw, hdr := visit("GET", "/"+slug+"/api/v1/summary", "")
var summary struct {
Page struct{ Title, Status string }
Components []struct{ Name, Status string }
Incidents []struct{ ID string }
}
if err := json.Unmarshal([]byte(raw), &summary); code != 200 || err != nil || hdr.Get("Access-Control-Allow-Origin") != "*" ||
summary.Page.Title != "Shop Status" || len(summary.Components) != 1 || len(summary.Incidents) != 1 || summary.Incidents[0].ID != incidentID {
t.Errorf("summary = %d %v %s", code, err, raw)
}
if code, _, _ := visit("GET", "/"+slug+"/api/v1/nope", ""); code != 404 {
t.Errorf("unknown API resource = %d", code)
}
// The unsubscribe link of mails works with one click, as mail
// programs post it.
m = tokenRE.FindStringSubmatch(outage)
unsub, _ := url.QueryUnescape(m[1])
if code, html, _ := visit("POST", "/"+slug+"/unsubscribe?token="+url.QueryEscape(unsub), "List-Unsubscribe=One-Click"); code != 200 {
t.Errorf("one-click unsubscribe = %d %.300s", code, html)
}
if c, p := subscribers(); c != 0 || p != 0 {
t.Errorf("subscribers after unsubscribing = %d, %d", c, p)
}
// The weekly limit counts every subscription asked for.
if err := e.asSystem(t, func(tx pgx.Tx) error {
_, err := tx.Exec(ctx, `UPDATE orgs SET limit_subscribers_per_week = 1 WHERE id = $1`, owner.orgID())
return err
}); err != nil {
t.Fatal(err)
}
if code, _, _ := visit("POST", "/"+slug+"/subscribe", "email=second@example.test&accept=1"); code != 200 {
t.Errorf("subscription within the weekly limit = %d", code)
}
if code, _, _ := visit("POST", "/"+slug+"/subscribe", "email=third@example.test&accept=1"); code != http.StatusTooManyRequests {
t.Errorf("subscription beyond the weekly limit = %d, want 429", code)
}
if n := len(mailsTo("third@example.test")); n != 0 {
t.Errorf("mails beyond the weekly limit = %d", n)
}
// Pages without subscriptions take none. (Another visitor: this one
// used up its subscription requests.)
visitor = "198.51.100.8:1234"
page["subscriptions"] = false
owner.do("PUT", "/api/v1/org/statuspages/"+pageID, page)
pages.Sync(ctx)
if code, html, _ := visit("GET", "/"+slug, ""); code != 200 || strings.Contains(html, "/subscribe\"") {
t.Errorf("page without subscriptions = %d, still offers the form", code)
}
if code, _, _ := visit("POST", "/"+slug+"/subscribe", "email=fourth@example.test&accept=1"); code != http.StatusNotFound {
t.Errorf("subscribing where it is off = %d, want 404", code)
}
// This visitor used up its subscription requests on the server.
visitor = "198.51.100.7:1234"
if code, _, _ := visit("POST", "/"+slug+"/subscribe", "email=fifth@example.test&accept=1"); code != http.StatusTooManyRequests {
t.Errorf("sixth subscription request of a visitor = %d, want 429", code)
}
// Polling the API is rate limited per visitor.
limited := false
for range 70 {
if code, _, _ := visit("GET", "/"+slug+"/api/v1/status", ""); code == http.StatusTooManyRequests {
limited = true
break
}
}
if !limited {
t.Error("70 API requests within a minute were all answered")
}
}
+61
View File
@@ -0,0 +1,61 @@
package api
import (
"fmt"
"log/slog"
"strings"
"time"
"github.com/gin-gonic/gin"
)
// slowPage is when a console page logs how long its steps took.
const slowPage = time.Second
// stepTimer measures the steps of a request. It reports them to the
// browser in a Server-Timing header and, when the request was slow, in
// the log.
type stepTimer struct {
start, last time.Time
steps []step
}
type step struct {
name string
d time.Duration
}
func newStepTimer() *stepTimer {
now := time.Now()
return &stepTimer{start: now, last: now}
}
// done ends the step name.
func (t *stepTimer) done(name string) {
now := time.Now()
t.steps = append(t.steps, step{name, now.Sub(t.last)})
t.last = now
}
// header sets the Server-Timing header of the steps so far; call it
// before the body is written.
func (t *stepTimer) header(c *gin.Context) {
parts := make([]string, len(t.steps))
for i, s := range t.steps {
parts[i] = fmt.Sprintf("%s;dur=%.1f", s.name, float64(s.d.Microseconds())/1000)
}
c.Header("Server-Timing", strings.Join(parts, ", "))
}
// logIfSlow logs the steps when the request took slowPage or longer.
func (t *stepTimer) logIfSlow(c *gin.Context, log *slog.Logger) {
total := time.Since(t.start)
if total < slowPage {
return
}
attrs := []any{"path", c.Request.URL.Path, "total_ms", total.Milliseconds()}
for _, s := range t.steps {
attrs = append(attrs, s.name+"_ms", s.d.Milliseconds())
}
log.WarnContext(c.Request.Context(), "slow console page", attrs...)
}
+64 -1
View File
@@ -519,6 +519,7 @@
"email.domain_missing.subject": "Der DNS-Eintrag von {{.Domain}} fehlt", "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.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.domain_off.subject": "{{.Domain}} wurde abgeschaltet",
"email.monitor_link": "In UptimeSebi öffnen: {{.Link}}",
"email.opened.body": "{{.Monitor}} ({{.Target}}) ist in allen Regionen nicht erreichbar seit {{.Since}}.\n\nLetzte Fehler:\n{{.Cause}}\n\nDu erhältst diese Nachricht, weil ein Benachrichtigungskanal deiner Organisation diese Adresse nutzt.", "email.opened.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.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.body": "Region {{.Region}} hat wieder einen aktiven Checker; seit {{.Since}} hatte sie keinen. Überfällige Prüfungen laufen sofort.\n\n{{.Link}}",
@@ -571,6 +572,7 @@
"error.invalid_credentials": "E-Mail oder Passwort falsch.", "error.invalid_credentials": "E-Mail oder Passwort falsch.",
"error.invalid_cursor": "Dieser Seitenlink ist ungültig; beginne bei der ersten Seite.", "error.invalid_cursor": "Dieser Seitenlink ist ungültig; beginne bei der ersten Seite.",
"error.invalid_domain": "Eine der Domains ist ungültig.", "error.invalid_domain": "Eine der Domains ist ungültig.",
"error.consent_required": "Bitte stimme den Bedingungen zu, um zu abonnieren.",
"error.invalid_email": "Bitte eine gültige E-Mail-Adresse eingeben.", "error.invalid_email": "Bitte eine gültige E-Mail-Adresse eingeben.",
"error.invalid_expect_status": "Erwartete Statuscodes müssen Codes wie 200 oder Klassen wie 2xx sein.", "error.invalid_expect_status": "Erwartete Statuscodes müssen Codes wie 200 oder Klassen wie 2xx sein.",
"error.invalid_grace": "Die Toleranz muss zwischen 0 Sekunden und einem Tag liegen.", "error.invalid_grace": "Die Toleranz muss zwischen 0 Sekunden und einem Tag liegen.",
@@ -1556,5 +1558,66 @@
"weekday.3": "Mi", "weekday.3": "Mi",
"weekday.4": "Do", "weekday.4": "Do",
"weekday.5": "Fr", "weekday.5": "Fr",
"weekday.6": "Sa" "weekday.6": "Sa",
"limits.subscribers_per_week": "Neue Abonnenten pro Woche",
"error.subscriber_limit": "Die Statusseiten dieser Organisation haben ihr Limit von {{.Max}} neuen Abonnenten pro Woche erreicht.",
"email.subscribe.subject": "Bestätige dein Abo für {{.Page}}",
"email.subscribe.body": "Hallo,\n\njemand, hoffentlich du, möchte E-Mails zu Störungen auf der Statusseite {{.Page}} erhalten. Bestätige das hier:\n\n{{.Link}}\n\nDer Link ist {{.Hours}} Stunden gültig. Wenn du das nicht warst, ignoriere diese E-Mail: Du bekommst sonst nichts zugeschickt.",
"email.subscriber.opened.subject": "[{{.Page}}] {{.Title}}: Störung",
"email.subscriber.opened.body": "{{.Title}} ist seit {{.Time}} nicht erreichbar.\n\nAktueller Status: {{.Link}}",
"email.subscriber.resolved.subject": "[{{.Page}}] {{.Title}}: behoben",
"email.subscriber.resolved.body": "{{.Title}} funktioniert seit {{.Time}} wieder, nach {{.Duration}}.\n\nAktueller Status: {{.Link}}",
"email.subscriber.update.subject": "[{{.Page}}] {{.Title}}: {{.Status}}",
"email.subscriber.update.body": "{{.Status}}: {{.Message}}\n\nAktueller Status: {{.Link}}",
"email.subscriber.footer": "\n\n--\nDu bekommst diese E-Mail, weil du {{.Page}} abonniert hast. Abmelden: {{.Unsubscribe}}",
"page.subscribe.title": "Benachrichtigungen erhalten",
"page.subscribe.intro": "Erhalte eine E-Mail, wenn eine Störung beginnt, sich ändert oder endet.",
"page.subscribe.email": "E-Mail-Adresse",
"page.subscribe.submit": "Abonnieren",
"page.subscribe.privacy": "Deine Adresse wird nur für diese E-Mails verwendet. Jede E-Mail enthält einen Link zum Abmelden.",
"page.subscribe.accept_both": "Ich akzeptiere die AGB und habe die Datenschutzerklärung gelesen:",
"page.subscribe.accept_terms": "Ich akzeptiere die AGB:",
"page.subscribe.accept_privacy": "Ich habe die Datenschutzerklärung gelesen:",
"page.subscribe.accept_required": "Bitte stimme den Bedingungen zu, um zu abonnieren.",
"page.subscribe.sent_title": "Schau in dein Postfach",
"page.subscribe.sent": "Wenn die Adresse abonniert werden kann, ist ein Link zum Bestätigen unterwegs. Er ist 48 Stunden gültig.",
"page.subscribe.invalid": "Das ist keine gültige E-Mail-Adresse.",
"page.subscribe.limited": "Gerade zu viele Anfragen. Bitte versuche es später noch einmal.",
"page.subscribe.failed": "Abonnieren ist gerade nicht möglich. Bitte versuche es später noch einmal.",
"page.subscribe.confirm_title": "Abo bestätigen",
"page.subscribe.confirm_intro": "Bestätige, dass du E-Mails zu Störungen auf {{.Page}} erhalten möchtest.",
"page.subscribe.confirm_button": "Abo bestätigen",
"page.subscribe.confirmed_title": "Abo bestätigt",
"page.subscribe.confirmed": "{{.Email}} erhält jetzt E-Mails zu Störungen auf {{.Page}}.",
"page.subscribe.link_invalid": "Dieser Link ist ungültig oder abgelaufen.",
"page.unsubscribe.title": "Abmelden",
"page.unsubscribe.intro": "Keine E-Mails mehr zu Störungen auf {{.Page}} erhalten?",
"page.unsubscribe.button": "Abmelden",
"page.unsubscribe.done_title": "Abgemeldet",
"page.unsubscribe.done": "{{.Email}} erhält keine E-Mails mehr von {{.Page}}.",
"page.back": "Zurück zur Statusseite",
"page.feed": "RSS-Feed",
"page.api": "API",
"page.feed.description": "Störungen und geplante Wartungen von {{.Page}}",
"page.feed.maintenance": "Geplante Wartung: {{.Title}}",
"pages.subscriptions": "E-Mail-Abos",
"pages.subscriptions_hint": "Besucher können Störungen per E-Mail abonnieren. Sie bestätigen zuerst ihre Adresse, und jede E-Mail enthält einen Link zum Abmelden.",
"pages.subscriptions_no_mail": "Braucht einen Mailserver (UPTIME_SMTP_URL) auf der Plattform.",
"pages.subscribers": "Abonnenten",
"pages.subscribers_counts": "{{.Confirmed}} bestätigt · {{.Pending}} warten auf Bestätigung",
"pages.subscribers_none": "Noch keine Abonnenten.",
"pages.subscribers_more": "Die neuesten {{.Count}} werden angezeigt.",
"pages.subscriber_pending": "unbestätigt",
"pages.subscriber_remove": "Entfernen",
"pages.subscribers_limit": "Neue Abos pro Woche für die Organisation: {{.Max}}",
"pages.feeds": "Feed und API",
"pages.feeds_hint": "Jede veröffentlichte Seite hat einen RSS-Feed und eine JSON-API zum Lesen, pro Besucher begrenzt:",
"audit.action.statuspage.subscriber_delete": "Abonnent einer Statusseite entfernt",
"page.not_found_title": "Seite nicht gefunden",
"page.not_found": "Unter dieser Adresse gibt es keine Statusseite, oder sie ist nicht veröffentlicht.",
"page.not_found_home": "Zur Hauptseite",
"admin.statuspage_home": "Hauptseite der Statusseiten",
"admin.statuspage_home_hint": "Wer die Statusseiten-Domain ohne Pfad oder eine Seite aufruft, die es nicht gibt, sieht eine Fehlerseite. Sie verlinkt diese Adresse, z. B. eure Website. Leer: kein Link.",
"admin.statuspage_home_url": "Adresse der Hauptseite",
"audit.action.platform.statuspage_home_update": "Hauptseite der Statusseiten geändert"
} }
+64 -1
View File
@@ -519,6 +519,7 @@
"email.domain_missing.subject": "The DNS record of {{.Domain}} is gone", "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.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.domain_off.subject": "{{.Domain}} has been switched off",
"email.monitor_link": "Open in UptimeSebi: {{.Link}}",
"email.opened.body": "{{.Monitor}} ({{.Target}}) is down in all of its regions since {{.Since}}.\n\nLast errors:\n{{.Cause}}\n\nYou receive this because a notification channel of your organization is set up for this address.", "email.opened.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.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.body": "Region {{.Region}} has an active checker again; it had none since {{.Since}}. Overdue checks run right away.\n\n{{.Link}}",
@@ -571,6 +572,7 @@
"error.invalid_credentials": "Wrong email or password.", "error.invalid_credentials": "Wrong email or password.",
"error.invalid_cursor": "This page link is invalid; start from the first page.", "error.invalid_cursor": "This page link is invalid; start from the first page.",
"error.invalid_domain": "One of the domains is not valid.", "error.invalid_domain": "One of the domains is not valid.",
"error.consent_required": "Please accept the terms to subscribe.",
"error.invalid_email": "Please enter a valid email address.", "error.invalid_email": "Please enter a valid email address.",
"error.invalid_expect_status": "Expected status codes must be codes like 200 or classes like 2xx.", "error.invalid_expect_status": "Expected status codes must be codes like 200 or classes like 2xx.",
"error.invalid_grace": "The grace period must be between 0 seconds and one day.", "error.invalid_grace": "The grace period must be between 0 seconds and one day.",
@@ -1556,5 +1558,66 @@
"weekday.3": "Wed", "weekday.3": "Wed",
"weekday.4": "Thu", "weekday.4": "Thu",
"weekday.5": "Fri", "weekday.5": "Fri",
"weekday.6": "Sat" "weekday.6": "Sat",
"limits.subscribers_per_week": "New subscribers per week",
"error.subscriber_limit": "The status pages of this organization have reached their limit of {{.Max}} new subscribers per week.",
"email.subscribe.subject": "Confirm your subscription to {{.Page}}",
"email.subscribe.body": "Hello,\n\nsomeone, hopefully you, asked to receive emails about incidents on the status page {{.Page}}. Confirm it here:\n\n{{.Link}}\n\nThe link is valid for {{.Hours}} hours. If you did not ask for this, ignore this email: nothing else will be sent to you.",
"email.subscriber.opened.subject": "[{{.Page}}] {{.Title}}: outage",
"email.subscriber.opened.body": "{{.Title}} has been unavailable since {{.Time}}.\n\nCurrent status: {{.Link}}",
"email.subscriber.resolved.subject": "[{{.Page}}] {{.Title}}: resolved",
"email.subscriber.resolved.body": "{{.Title}} is working again since {{.Time}}, after {{.Duration}}.\n\nCurrent status: {{.Link}}",
"email.subscriber.update.subject": "[{{.Page}}] {{.Title}}: {{.Status}}",
"email.subscriber.update.body": "{{.Status}}: {{.Message}}\n\nCurrent status: {{.Link}}",
"email.subscriber.footer": "\n\n--\nYou receive this email because you subscribed to {{.Page}}. Unsubscribe: {{.Unsubscribe}}",
"page.subscribe.title": "Get notified",
"page.subscribe.intro": "Receive an email when an incident starts, changes or ends.",
"page.subscribe.email": "Email address",
"page.subscribe.submit": "Subscribe",
"page.subscribe.privacy": "Your address is used for these emails only. Every email contains a link to unsubscribe.",
"page.subscribe.accept_both": "I accept the terms of service and have read the privacy policy:",
"page.subscribe.accept_terms": "I accept the terms of service:",
"page.subscribe.accept_privacy": "I have read the privacy policy:",
"page.subscribe.accept_required": "Please accept the terms to subscribe.",
"page.subscribe.sent_title": "Check your inbox",
"page.subscribe.sent": "If the address can be subscribed, a link to confirm it is on its way. The link is valid for 48 hours.",
"page.subscribe.invalid": "That is not a valid email address.",
"page.subscribe.limited": "Too many requests right now. Please try again later.",
"page.subscribe.failed": "Subscribing is not possible right now. Please try again later.",
"page.subscribe.confirm_title": "Confirm subscription",
"page.subscribe.confirm_intro": "Confirm that you want to receive emails about incidents on {{.Page}}.",
"page.subscribe.confirm_button": "Confirm subscription",
"page.subscribe.confirmed_title": "Subscription confirmed",
"page.subscribe.confirmed": "{{.Email}} now receives emails about incidents on {{.Page}}.",
"page.subscribe.link_invalid": "This link is invalid or has expired.",
"page.unsubscribe.title": "Unsubscribe",
"page.unsubscribe.intro": "Stop receiving emails about incidents on {{.Page}}?",
"page.unsubscribe.button": "Unsubscribe",
"page.unsubscribe.done_title": "Unsubscribed",
"page.unsubscribe.done": "{{.Email}} no longer receives emails from {{.Page}}.",
"page.back": "Back to the status page",
"page.feed": "RSS feed",
"page.api": "API",
"page.feed.description": "Incidents and planned maintenance of {{.Page}}",
"page.feed.maintenance": "Planned maintenance: {{.Title}}",
"pages.subscriptions": "Email subscriptions",
"pages.subscriptions_hint": "Visitors can subscribe to incidents by email. They confirm their address first, and every email has a link to unsubscribe.",
"pages.subscriptions_no_mail": "Needs a mail server (UPTIME_SMTP_URL) on the platform.",
"pages.subscribers": "Subscribers",
"pages.subscribers_counts": "{{.Confirmed}} confirmed · {{.Pending}} waiting for confirmation",
"pages.subscribers_none": "No subscribers yet.",
"pages.subscribers_more": "Showing the newest {{.Count}}.",
"pages.subscriber_pending": "unconfirmed",
"pages.subscriber_remove": "Remove",
"pages.subscribers_limit": "New subscriptions per week for the organization: {{.Max}}",
"pages.feeds": "Feed and API",
"pages.feeds_hint": "Every published page has an RSS feed and a read-only JSON API, rate limited per visitor:",
"audit.action.statuspage.subscriber_delete": "Status page subscriber removed",
"page.not_found_title": "Page not found",
"page.not_found": "There is no status page at this address, or it is not published.",
"page.not_found_home": "Go to the home page",
"admin.statuspage_home": "Status page home",
"admin.statuspage_home_hint": "Visitors of the bare status page domain and of pages that do not exist see an error page. It links this address, e.g. your website. Empty: no link.",
"admin.statuspage_home_url": "Home page URL",
"audit.action.platform.statuspage_home_update": "Status page home changed"
} }
@@ -0,0 +1,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;
+13
View File
@@ -15,11 +15,13 @@ import (
"errors" "errors"
"fmt" "fmt"
"io" "io"
"maps"
"mime" "mime"
"net" "net"
"net/http" "net/http"
"net/smtp" "net/smtp"
"net/url" "net/url"
"slices"
"strconv" "strconv"
"strings" "strings"
"time" "time"
@@ -53,6 +55,9 @@ type Event struct {
ResolvedAt *time.Time `json:"resolved_at,omitempty"` ResolvedAt *time.Time `json:"resolved_at,omitempty"`
Cause map[string]string `json:"cause,omitempty"` Cause map[string]string `json:"cause,omitempty"`
Monitor Monitor `json:"monitor"` Monitor Monitor `json:"monitor"`
// RegionNames names the regions Cause has by id, for messages to
// people.
RegionNames map[string]string `json:"-"`
} }
// Webhook signs requests so receivers can verify they came from us: the // Webhook signs requests so receivers can verify they came from us: the
@@ -158,6 +163,8 @@ type Mail struct {
To []string To []string
Subject string Subject string
Body string Body string
// Headers are added to the message, e.g. List-Unsubscribe.
Headers map[string]string
} }
// Send delivers m. // Send delivers m.
@@ -223,6 +230,12 @@ func compose(from string, m Mail) []byte {
fmt.Fprintf(&b, "Subject: %s\r\n", encodeHeader(m.Subject)) fmt.Fprintf(&b, "Subject: %s\r\n", encodeHeader(m.Subject))
fmt.Fprintf(&b, "Date: %s\r\n", time.Now().Format(time.RFC1123Z)) fmt.Fprintf(&b, "Date: %s\r\n", time.Now().Format(time.RFC1123Z))
fmt.Fprintf(&b, "Message-ID: <%s@uptimesebi>\r\n", uuid.NewString()) 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("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")) b.WriteString(strings.ReplaceAll(m.Body, "\n", "\r\n"))
return b.Bytes() return b.Bytes()
+418
View File
@@ -0,0 +1,418 @@
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 && c.PostForm("accept") == "" && len(web.SubscribeConsent(snap, base)) > 0:
notice(http.StatusUnprocessableEntity, i18n.T(ctx, "page.subscribe.title"), i18n.T(ctx, "page.subscribe.accept_required"), nil)
case kind == routeSubscribe:
err := subs.Subscribe(ctx, agentapi.SubscribeRequest{
Host: host, Slug: slug, Email: c.PostForm("email"), IP: c.ClientIP(),
Locale: c.GetHeader("Accept-Language"), PageURL: pageURL(c, base), Accepted: true,
})
switch {
case err == nil:
notice(http.StatusOK, i18n.T(ctx, "page.subscribe.sent_title"), i18n.T(ctx, "page.subscribe.sent"), nil)
case errors.Is(err, agentapi.ErrInvalidInput):
notice(http.StatusUnprocessableEntity, i18n.T(ctx, "page.subscribe.title"), i18n.T(ctx, "page.subscribe.invalid"), nil)
case errors.Is(err, agentapi.ErrRateLimited):
notice(http.StatusTooManyRequests, i18n.T(ctx, "page.subscribe.title"), i18n.T(ctx, "page.subscribe.limited"), nil)
default:
if !errors.Is(err, agentapi.ErrNotFound) {
s.log.WarnContext(ctx, "passing on a subscription failed", "error", err)
}
notice(http.StatusServiceUnavailable, i18n.T(ctx, "page.subscribe.title"), i18n.T(ctx, "page.subscribe.failed"), nil)
}
case token == "":
notice(http.StatusNotFound, i18n.T(ctx, "page.subscribe.title"), i18n.T(ctx, "page.subscribe.link_invalid"), nil)
case kind == routeConfirm && c.Request.Method != http.MethodPost:
notice(http.StatusOK, i18n.T(ctx, "page.subscribe.confirm_title"), i18n.T(ctx, "page.subscribe.confirm_intro", "Page", snap.Title),
&web.NoticeForm{Action: base + "subscribe/confirm", Token: token, Button: i18n.T(ctx, "page.subscribe.confirm_button")})
case kind == routeUnsubscribe && c.Request.Method != http.MethodPost:
notice(http.StatusOK, i18n.T(ctx, "page.unsubscribe.title"), i18n.T(ctx, "page.unsubscribe.intro", "Page", snap.Title),
&web.NoticeForm{Action: base + "unsubscribe", Token: token, Button: i18n.T(ctx, "page.unsubscribe.button")})
default:
act, title, done := subs.ConfirmSubscription, "page.subscribe.confirmed_title", "page.subscribe.confirmed"
if kind == routeUnsubscribe {
// Also the one-click unsubscribe of mail programs (RFC 8058),
// which posts to the link itself.
act, title, done = subs.Unsubscribe, "page.unsubscribe.done_title", "page.unsubscribe.done"
}
info, err := act(ctx, token)
switch {
case err == nil:
notice(http.StatusOK, i18n.T(ctx, title), i18n.T(ctx, done, "Email", info.Email, "Page", info.PageTitle), nil)
case errors.Is(err, agentapi.ErrNotFound):
notice(http.StatusNotFound, i18n.T(ctx, "page.subscribe.title"), i18n.T(ctx, "page.subscribe.link_invalid"), nil)
case errors.Is(err, agentapi.ErrRateLimited):
notice(http.StatusTooManyRequests, i18n.T(ctx, "page.subscribe.title"), i18n.T(ctx, "page.subscribe.limited"), nil)
default:
s.log.WarnContext(ctx, "passing on a subscription link failed", "error", err)
notice(http.StatusServiceUnavailable, i18n.T(ctx, "page.subscribe.title"), i18n.T(ctx, "page.subscribe.failed"), nil)
}
}
}
+88 -47
View File
@@ -63,7 +63,7 @@ type Source interface {
// PageIfChanged answers agentapi.ErrNotModified when the page still // PageIfChanged answers agentapi.ErrNotModified when the page still
// has checksum. // has checksum.
PageIfChanged(ctx context.Context, host, slug, checksum string) (agentapi.PageSnapshot, error) PageIfChanged(ctx context.Context, host, slug, checksum string) (agentapi.PageSnapshot, error)
Pages(ctx context.Context) ([]agentapi.PageRef, error) Pages(ctx context.Context) (agentapi.PageIndex, error)
} }
// Server renders pages for one status page agent. // Server renders pages for one status page agent.
@@ -78,7 +78,9 @@ type Server struct {
dir string dir string
now func() time.Time now func() time.Time
mu sync.Mutex mu sync.Mutex
// home is the platform's home page, linked from the error page.
home string
cache map[string]entry cache map[string]entry
refreshing map[string]bool refreshing map[string]bool
// again holds pages that changed while being refreshed, which are // again holds pages that changed while being refreshed, which are
@@ -92,6 +94,7 @@ type Server struct {
// the current second. // the current second.
unknownSecond int64 unknownSecond int64
unknownCount int unknownCount int
limits limiters
// background tracks refreshes started by visits. // background tracks refreshes started by visits.
background sync.WaitGroup background sync.WaitGroup
} }
@@ -124,7 +127,7 @@ func New(src Source, catalog *i18n.Catalog, log *slog.Logger, o Options) (*Serve
s := &Server{ s := &Server{
src: src, catalog: catalog, log: log, ownHosts: map[string]bool{}, dir: o.CacheDir, src: src, catalog: catalog, log: log, ownHosts: map[string]bool{}, dir: o.CacheDir,
now: time.Now, cache: map[string]entry{}, refreshing: map[string]bool{}, again: map[string]bool{}, visited: map[string]time.Time{}, now: time.Now, cache: map[string]entry{}, refreshing: map[string]bool{}, again: map[string]bool{}, visited: map[string]time.Time{},
missing: map[string]time.Time{}, missing: map[string]time.Time{}, limits: newLimiters(),
} }
for _, h := range o.Hosts { for _, h := range o.Hosts {
s.ownHosts[strings.ToLower(h)] = true s.ownHosts[strings.ToLower(h)] = true
@@ -160,9 +163,39 @@ func (s *Server) loadDisk() error {
if len(s.cache) > 0 { if len(s.cache) > 0 {
s.log.Info("loaded cached status pages", "count", len(s.cache)) s.log.Info("loaded cached status pages", "count", len(s.cache))
} }
if raw, err := os.ReadFile(filepath.Join(s.dir, homeFile)); err == nil {
s.home = string(raw)
}
return nil return nil
} }
// homeFile keeps the home page across restarts; not .json, which are pages.
const homeFile = "home.url"
// setHome records the home page the error page links.
func (s *Server) setHome(url string) {
s.mu.Lock()
changed := s.home != url
s.home = url
s.mu.Unlock()
if changed && s.dir != "" {
if err := os.WriteFile(filepath.Join(s.dir, homeFile), []byte(url), 0o600); err != nil {
s.log.Warn("saving the home page failed", "error", err)
}
}
}
// notFound answers visitors of a page that does not exist with a page
// leading to the platform's home page.
func (s *Server) notFound(c *gin.Context) {
s.localizeRequest(c)
s.mu.Lock()
home := s.home
s.mu.Unlock()
c.Header("Cache-Control", "no-store")
web.Render(c, http.StatusNotFound, web.PublicNotFoundPage("/static/dist/app.css", home))
}
func (s *Server) fileFor(key string) string { func (s *Server) fileFor(key string) string {
sum := sha256.Sum256([]byte(key)) sum := sha256.Sum256([]byte(key))
return filepath.Join(s.dir, hex.EncodeToString(sum[:16])+".json") return filepath.Join(s.dir, hex.EncodeToString(sum[:16])+".json")
@@ -226,53 +259,49 @@ func hostOnly(h string) string {
} }
func (s *Server) serve(c *gin.Context) { func (s *Server) serve(c *gin.Context) {
if c.Request.Method != http.MethodGet && c.Request.Method != http.MethodHead {
c.Status(http.StatusMethodNotAllowed)
return
}
host := hostOnly(c.Request.Host) host := hostOnly(c.Request.Host)
trimmed := strings.Trim(c.Request.URL.Path, "/") var parts []string
parts := strings.Split(trimmed, "/") if trimmed := strings.Trim(c.Request.URL.Path, "/"); trimmed != "" {
var key, slug, base, legal, compID string parts = strings.Split(trimmed, "/")
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
}
} }
e, ok := s.lookup(c.Request.Context(), key, host, slug) var key, slug, base string
if s.IsCustomDomain(host) {
key, base = "host:"+host, "/"
} else {
if len(parts) == 0 {
s.notFound(c)
return
}
slug, parts = parts[0], parts[1:]
key, host, base = "slug:"+slug, "", "/"+slug+"/"
}
rt, ok := routeOf(parts)
if !ok { if !ok {
c.Status(http.StatusNotFound) c.Status(http.StatusNotFound)
return return
} }
if legal != "" { switch m := c.Request.Method; {
s.serveLegal(c, e, legal, base) case m == http.MethodPost && rt.kind.posts():
case m != http.MethodGet && m != http.MethodHead:
c.Status(http.StatusMethodNotAllowed)
return
}
if limit := s.limiterFor(rt.kind); limit != nil && !limit.allow(c.ClientIP(), s.now()) {
c.Header("Retry-After", "60")
c.Status(http.StatusTooManyRequests)
return
}
e, ok := s.lookup(c.Request.Context(), key, host, slug)
if !ok {
if rt.kind == routeFeed || rt.kind == routeAPI {
c.Status(http.StatusNotFound)
} else {
s.notFound(c)
}
return
}
if rt.kind == routeLegal {
s.serveLegal(c, e, rt.arg, base)
return return
} }
var staleSince time.Time var staleSince time.Time
@@ -286,8 +315,18 @@ func (s *Server) serve(c *gin.Context) {
ComponentBase: base, ComponentBase: base,
Now: s.now(), Now: s.now(),
} }
if compID != "" { switch rt.kind {
s.serveComponent(c, e, compID, assets) 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 return
} }
s.localizeRequest(c) s.localizeRequest(c)
@@ -520,11 +559,13 @@ func (s *Server) Run(ctx context.Context) {
func (s *Server) Sync(ctx context.Context) { func (s *Server) Sync(ctx context.Context) {
ctx, cancel := context.WithTimeout(ctx, syncInterval) ctx, cancel := context.WithTimeout(ctx, syncInterval)
defer cancel() defer cancel()
refs, err := s.src.Pages(ctx) index, err := s.src.Pages(ctx)
if err != nil { if err != nil {
s.log.WarnContext(ctx, "listing status pages failed", "error", err) s.log.WarnContext(ctx, "listing status pages failed", "error", err)
return return
} }
s.setHome(index.HomeURL)
refs := index.Pages
todo := map[string]entry{} todo := map[string]entry{}
s.mu.Lock() s.mu.Lock()
for key, e := range s.cache { for key, e := range s.cache {
+27 -6
View File
@@ -25,6 +25,7 @@ type fakeSource struct {
err error err error
delay time.Duration delay time.Duration
pages map[string]agentapi.PageSnapshot pages map[string]agentapi.PageSnapshot
home string
} }
// PageIfChanged counts calls and answers like the API, sending pages // PageIfChanged counts calls and answers like the API, sending pages
@@ -65,16 +66,16 @@ func (f *fakeSource) page(ctx context.Context, host, slug string) (agentapi.Page
} }
// Pages lists the fake's pages by their keys: "host|" or "|slug". // Pages lists the fake's pages by their keys: "host|" or "|slug".
func (f *fakeSource) Pages(context.Context) ([]agentapi.PageRef, error) { func (f *fakeSource) Pages(context.Context) (agentapi.PageIndex, error) {
f.mu.Lock() f.mu.Lock()
defer f.mu.Unlock() defer f.mu.Unlock()
if f.err != nil { if f.err != nil {
return nil, f.err return agentapi.PageIndex{}, f.err
} }
var out []agentapi.PageRef out := agentapi.PageIndex{HomeURL: f.home}
for k := range f.pages { for k := range f.pages {
host, slug, _ := strings.Cut(k, "|") host, slug, _ := strings.Cut(k, "|")
out = append(out, agentapi.PageRef{Host: host, Slug: slug}) out.Pages = append(out.Pages, agentapi.PageRef{Host: host, Slug: slug})
} }
return out, nil return out, nil
} }
@@ -128,6 +129,26 @@ func (h harness) get(host, path string) (int, string) {
return w.Code, w.Body.String() return w.Code, w.Body.String()
} }
// The error page links the platform's home page, also after a restart
// while the API is down.
func TestNotFoundLinksHome(t *testing.T) {
dir := t.TempDir()
now := time.Now()
src := newSource()
h := newHarness(t, src, dir, &now)
if code, body := h.get("status.example.test", "/"); code != 404 || strings.Contains(body, "Zur Hauptseite") {
t.Errorf("error page without a home page = %d, links one: %t", code, strings.Contains(body, "Zur Hauptseite"))
}
src.home = "https://example.test/"
h.srv.Sync(context.Background())
restarted := newHarness(t, &fakeSource{err: errors.New("connection refused")}, dir, &now)
for _, hs := range []harness{h, restarted} {
if code, body := hs.get("status.example.test", "/gone"); code != 404 || !strings.Contains(body, `href="https://example.test/"`) {
t.Errorf("error page = %d, lacks the link to the home page", code)
}
}
}
func TestRouting(t *testing.T) { func TestRouting(t *testing.T) {
now := time.Now() now := time.Now()
h := newHarness(t, newSource(), t.TempDir(), &now) h := newHarness(t, newSource(), t.TempDir(), &now)
@@ -138,8 +159,8 @@ func TestRouting(t *testing.T) {
}{ }{
{"status.example.test", "/acme", 200, "Acme status"}, {"status.example.test", "/acme", 200, "Acme status"},
{"status.example.test:8082", "/acme", 200, "Alle Systeme funktionieren"}, {"status.example.test:8082", "/acme", 200, "Alle Systeme funktionieren"},
{"status.example.test", "/missing", 404, ""}, {"status.example.test", "/missing", 404, "Seite nicht gefunden"},
{"status.example.test", "/", 404, ""}, {"status.example.test", "/", 404, "Seite nicht gefunden"},
{"status.acme.test", "/", 200, "Acme on own domain"}, {"status.acme.test", "/", 200, "Acme on own domain"},
{"status.acme.test", "/acme", 404, ""}, {"status.acme.test", "/acme", 404, ""},
{"other.test", "/", 404, ""}, {"other.test", "/", 404, ""},
-38
View File
@@ -124,44 +124,6 @@ func (q *Queries) DailyBucketsForMonitors(ctx context.Context, arg DailyBucketsF
return items, nil 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 const firstDataDaily = `-- name: FirstDataDaily :many
SELECT monitor_id, region, min(bucket)::timestamptz AS first SELECT monitor_id, region, min(bucket)::timestamptz AS first
FROM check_results_1d FROM check_results_1d
+6 -1
View File
@@ -578,7 +578,10 @@ const notificationDetails = `-- name: NotificationDetails :many
SELECT n.id, n.org_id, n.event, n.attempts, SELECT n.id, n.org_id, n.event, n.attempts,
c.type AS channel_type, c.config AS channel_config, c.id AS channel_id, c.type AS channel_type, c.config AS channel_config, c.id AS channel_id,
i.id AS incident_id, i.started_at, i.resolved_at, i.cause, i.id AS incident_id, i.started_at, i.resolved_at, i.cause,
m.id AS monitor_id, m.name AS monitor_name, m.target AS monitor_target, m.type AS monitor_type m.id AS monitor_id, m.name AS monitor_name, m.target AS monitor_target, m.type AS monitor_type,
-- The names of the regions the cause names by id.
coalesce((SELECT jsonb_object_agg(r.id::text, r.name) FROM regions r
WHERE jsonb_typeof(i.cause) = 'object' AND i.cause ? r.id::text), '{}')::jsonb AS region_names
FROM notifications n FROM notifications n
JOIN notification_channels c ON c.id = n.channel_id JOIN notification_channels c ON c.id = n.channel_id
JOIN incidents i ON i.id = n.incident_id JOIN incidents i ON i.id = n.incident_id
@@ -602,6 +605,7 @@ type NotificationDetailsRow struct {
MonitorName string MonitorName string
MonitorTarget string MonitorTarget string
MonitorType string MonitorType string
RegionNames []byte
} }
// System scope. // System scope.
@@ -630,6 +634,7 @@ func (q *Queries) NotificationDetails(ctx context.Context, ids []uuid.UUID) ([]N
&i.MonitorName, &i.MonitorName,
&i.MonitorTarget, &i.MonitorTarget,
&i.MonitorType, &i.MonitorType,
&i.RegionNames,
); err != nil { ); err != nil {
return nil, err return nil, err
} }
+33 -29
View File
@@ -15,7 +15,7 @@ import (
const adminListOrgs = `-- name: AdminListOrgs :many const adminListOrgs = `-- name: AdminListOrgs :many
SELECT o.id, o.slug, o.name, o.created_at, o.suspended_at, o.suspended_reason, 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, o.limit_status_pages, o.limit_regions_per_monitor, o.limit_own_regions_count,
o.limit_monitors_per_page, o.limit_monitors_per_page, o.limit_subscribers_per_week,
(SELECT count(*) FROM monitors m WHERE m.org_id = o.id)::integer AS monitors, (SELECT count(*) FROM 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, (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, coalesce(ow.id, '00000000-0000-0000-0000-000000000000'::uuid)::uuid AS owner_id,
@@ -52,26 +52,27 @@ type AdminListOrgsParams struct {
} }
type AdminListOrgsRow struct { type AdminListOrgsRow struct {
ID uuid.UUID ID uuid.UUID
Slug string Slug string
Name string Name string
CreatedAt time.Time CreatedAt time.Time
SuspendedAt *time.Time SuspendedAt *time.Time
SuspendedReason string SuspendedReason string
LimitMonitors *int32 LimitMonitors *int32
LimitStatusPages *int32 LimitStatusPages *int32
LimitRegionsPerMonitor *int32 LimitRegionsPerMonitor *int32
LimitOwnRegionsCount *bool LimitOwnRegionsCount *bool
LimitMonitorsPerPage *int32 LimitMonitorsPerPage *int32
Monitors int32 LimitSubscribersPerWeek *int32
StatusPages int32 Monitors int32
OwnerID uuid.UUID StatusPages int32
OwnerEmail string OwnerID uuid.UUID
OwnerDisabledAt *time.Time OwnerEmail string
OwnerDisabledReason string OwnerDisabledAt *time.Time
OwnerIsAdmin bool OwnerDisabledReason string
OwnerLimitOrgs *int32 OwnerIsAdmin bool
OwnerOrgs int32 OwnerLimitOrgs *int32
OwnerOrgs int32
} }
// System scope: organizations with their usage, limit overrides and owner, // System scope: organizations with their usage, limit overrides and owner,
@@ -105,6 +106,7 @@ func (q *Queries) AdminListOrgs(ctx context.Context, arg AdminListOrgsParams) ([
&i.LimitRegionsPerMonitor, &i.LimitRegionsPerMonitor,
&i.LimitOwnRegionsCount, &i.LimitOwnRegionsCount,
&i.LimitMonitorsPerPage, &i.LimitMonitorsPerPage,
&i.LimitSubscribersPerWeek,
&i.Monitors, &i.Monitors,
&i.StatusPages, &i.StatusPages,
&i.OwnerID, &i.OwnerID,
@@ -172,18 +174,19 @@ func (q *Queries) LockOrgUsage(ctx context.Context, orgID uuid.UUID) error {
const setOrgLimits = `-- name: SetOrgLimits :one const setOrgLimits = `-- name: SetOrgLimits :one
UPDATE orgs SET limit_monitors = $1, limit_status_pages = $2, UPDATE orgs SET limit_monitors = $1, limit_status_pages = $2,
limit_regions_per_monitor = $3, limit_own_regions_count = $4, limit_regions_per_monitor = $3, limit_own_regions_count = $4,
limit_monitors_per_page = $5 limit_monitors_per_page = $5, limit_subscribers_per_week = $6
WHERE id = $6 WHERE id = $7
RETURNING id, slug RETURNING id, slug
` `
type SetOrgLimitsParams struct { type SetOrgLimitsParams struct {
Monitors *int32 Monitors *int32
StatusPages *int32 StatusPages *int32
RegionsPerMonitor *int32 RegionsPerMonitor *int32
OwnRegionsCount *bool OwnRegionsCount *bool
MonitorsPerPage *int32 MonitorsPerPage *int32
ID uuid.UUID SubscribersPerWeek *int32
ID uuid.UUID
} }
type SetOrgLimitsRow struct { type SetOrgLimitsRow struct {
@@ -198,6 +201,7 @@ func (q *Queries) SetOrgLimits(ctx context.Context, arg SetOrgLimitsParams) (Set
arg.RegionsPerMonitor, arg.RegionsPerMonitor,
arg.OwnRegionsCount, arg.OwnRegionsCount,
arg.MonitorsPerPage, arg.MonitorsPerPage,
arg.SubscribersPerWeek,
arg.ID, arg.ID,
) )
var i SetOrgLimitsRow var i SetOrgLimitsRow
+44 -16
View File
@@ -318,22 +318,23 @@ type NotificationChannel struct {
} }
type Org struct { type Org struct {
ID uuid.UUID ID uuid.UUID
Slug string Slug string
Name string Name string
CreatedAt time.Time CreatedAt time.Time
UpdatedAt time.Time UpdatedAt time.Time
RequireTotp bool RequireTotp bool
RequireSso bool RequireSso bool
ApiTokenMaxDays *int32 ApiTokenMaxDays *int32
DisabledCheckTypes []string DisabledCheckTypes []string
SuspendedAt *time.Time SuspendedAt *time.Time
SuspendedReason string SuspendedReason string
LimitMonitors *int32 LimitMonitors *int32
LimitStatusPages *int32 LimitStatusPages *int32
LimitRegionsPerMonitor *int32 LimitRegionsPerMonitor *int32
LimitOwnRegionsCount *bool LimitOwnRegionsCount *bool
LimitMonitorsPerPage *int32 LimitMonitorsPerPage *int32
LimitSubscribersPerWeek *int32
} }
type PlatformIdentity struct { type PlatformIdentity struct {
@@ -435,6 +436,7 @@ type StatusPage struct {
DomainCheckedAt *time.Time DomainCheckedAt *time.Time
DomainFailingSince *time.Time DomainFailingSince *time.Time
DomainVerifyMethod *string DomainVerifyMethod *string
Subscriptions bool
} }
type StatusPageGroup struct { type StatusPageGroup struct {
@@ -458,6 +460,32 @@ type StatusPageMonitor struct {
GroupID *uuid.UUID 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 { type SupportMessage struct {
ID uuid.UUID ID uuid.UUID
TicketID uuid.UUID TicketID uuid.UUID
+10 -5
View File
@@ -13,7 +13,7 @@ import (
const createOrg = `-- name: CreateOrg :one const createOrg = `-- name: CreateOrg :one
INSERT INTO orgs (id, slug, name) VALUES ($1, $2, $3) INSERT INTO orgs (id, slug, name) VALUES ($1, $2, $3)
RETURNING id, slug, name, created_at, updated_at, require_totp, require_sso, api_token_max_days, disabled_check_types, suspended_at, suspended_reason, limit_monitors, limit_status_pages, limit_regions_per_monitor, limit_own_regions_count, limit_monitors_per_page RETURNING id, slug, name, created_at, updated_at, require_totp, require_sso, api_token_max_days, disabled_check_types, suspended_at, suspended_reason, limit_monitors, limit_status_pages, limit_regions_per_monitor, limit_own_regions_count, limit_monitors_per_page, limit_subscribers_per_week
` `
type CreateOrgParams struct { type CreateOrgParams struct {
@@ -42,6 +42,7 @@ func (q *Queries) CreateOrg(ctx context.Context, arg CreateOrgParams) (Org, erro
&i.LimitRegionsPerMonitor, &i.LimitRegionsPerMonitor,
&i.LimitOwnRegionsCount, &i.LimitOwnRegionsCount,
&i.LimitMonitorsPerPage, &i.LimitMonitorsPerPage,
&i.LimitSubscribersPerWeek,
) )
return i, err return i, err
} }
@@ -59,7 +60,7 @@ func (q *Queries) DeleteOrg(ctx context.Context, id uuid.UUID) (int64, error) {
} }
const getOrg = `-- name: GetOrg :one const getOrg = `-- name: GetOrg :one
SELECT id, slug, name, created_at, updated_at, require_totp, require_sso, api_token_max_days, disabled_check_types, suspended_at, suspended_reason, limit_monitors, limit_status_pages, limit_regions_per_monitor, limit_own_regions_count, limit_monitors_per_page FROM orgs WHERE id = $1 SELECT id, slug, name, created_at, updated_at, require_totp, require_sso, api_token_max_days, disabled_check_types, suspended_at, suspended_reason, limit_monitors, limit_status_pages, limit_regions_per_monitor, limit_own_regions_count, limit_monitors_per_page, limit_subscribers_per_week FROM orgs WHERE id = $1
` `
func (q *Queries) GetOrg(ctx context.Context, id uuid.UUID) (Org, error) { func (q *Queries) GetOrg(ctx context.Context, id uuid.UUID) (Org, error) {
@@ -82,12 +83,13 @@ func (q *Queries) GetOrg(ctx context.Context, id uuid.UUID) (Org, error) {
&i.LimitRegionsPerMonitor, &i.LimitRegionsPerMonitor,
&i.LimitOwnRegionsCount, &i.LimitOwnRegionsCount,
&i.LimitMonitorsPerPage, &i.LimitMonitorsPerPage,
&i.LimitSubscribersPerWeek,
) )
return i, err return i, err
} }
const getOrgBySlug = `-- name: GetOrgBySlug :one const getOrgBySlug = `-- name: GetOrgBySlug :one
SELECT id, slug, name, created_at, updated_at, require_totp, require_sso, api_token_max_days, disabled_check_types, suspended_at, suspended_reason, limit_monitors, limit_status_pages, limit_regions_per_monitor, limit_own_regions_count, limit_monitors_per_page FROM orgs WHERE slug = $1 SELECT id, slug, name, created_at, updated_at, require_totp, require_sso, api_token_max_days, disabled_check_types, suspended_at, suspended_reason, limit_monitors, limit_status_pages, limit_regions_per_monitor, limit_own_regions_count, limit_monitors_per_page, limit_subscribers_per_week FROM orgs WHERE slug = $1
` `
func (q *Queries) GetOrgBySlug(ctx context.Context, slug string) (Org, error) { func (q *Queries) GetOrgBySlug(ctx context.Context, slug string) (Org, error) {
@@ -110,12 +112,13 @@ func (q *Queries) GetOrgBySlug(ctx context.Context, slug string) (Org, error) {
&i.LimitRegionsPerMonitor, &i.LimitRegionsPerMonitor,
&i.LimitOwnRegionsCount, &i.LimitOwnRegionsCount,
&i.LimitMonitorsPerPage, &i.LimitMonitorsPerPage,
&i.LimitSubscribersPerWeek,
) )
return i, err return i, err
} }
const listOrgs = `-- name: ListOrgs :many const listOrgs = `-- name: ListOrgs :many
SELECT id, slug, name, created_at, updated_at, require_totp, require_sso, api_token_max_days, disabled_check_types, suspended_at, suspended_reason, limit_monitors, limit_status_pages, limit_regions_per_monitor, limit_own_regions_count, limit_monitors_per_page FROM orgs ORDER BY name SELECT id, slug, name, created_at, updated_at, require_totp, require_sso, api_token_max_days, disabled_check_types, suspended_at, suspended_reason, limit_monitors, limit_status_pages, limit_regions_per_monitor, limit_own_regions_count, limit_monitors_per_page, limit_subscribers_per_week FROM orgs ORDER BY name
` `
func (q *Queries) ListOrgs(ctx context.Context) ([]Org, error) { func (q *Queries) ListOrgs(ctx context.Context) ([]Org, error) {
@@ -144,6 +147,7 @@ func (q *Queries) ListOrgs(ctx context.Context) ([]Org, error) {
&i.LimitRegionsPerMonitor, &i.LimitRegionsPerMonitor,
&i.LimitOwnRegionsCount, &i.LimitOwnRegionsCount,
&i.LimitMonitorsPerPage, &i.LimitMonitorsPerPage,
&i.LimitSubscribersPerWeek,
); err != nil { ); err != nil {
return nil, err return nil, err
} }
@@ -172,7 +176,7 @@ func (q *Queries) SetOrgDisabledCheckTypes(ctx context.Context, arg SetOrgDisabl
const updateOrgPolicy = `-- name: UpdateOrgPolicy :one const updateOrgPolicy = `-- name: UpdateOrgPolicy :one
UPDATE orgs SET require_totp = $2, require_sso = $3, api_token_max_days = $4, updated_at = now() UPDATE orgs SET require_totp = $2, require_sso = $3, api_token_max_days = $4, updated_at = now()
WHERE id = $1 WHERE id = $1
RETURNING id, slug, name, created_at, updated_at, require_totp, require_sso, api_token_max_days, disabled_check_types, suspended_at, suspended_reason, limit_monitors, limit_status_pages, limit_regions_per_monitor, limit_own_regions_count, limit_monitors_per_page RETURNING id, slug, name, created_at, updated_at, require_totp, require_sso, api_token_max_days, disabled_check_types, suspended_at, suspended_reason, limit_monitors, limit_status_pages, limit_regions_per_monitor, limit_own_regions_count, limit_monitors_per_page, limit_subscribers_per_week
` `
type UpdateOrgPolicyParams struct { type UpdateOrgPolicyParams struct {
@@ -207,6 +211,7 @@ func (q *Queries) UpdateOrgPolicy(ctx context.Context, arg UpdateOrgPolicyParams
&i.LimitRegionsPerMonitor, &i.LimitRegionsPerMonitor,
&i.LimitOwnRegionsCount, &i.LimitOwnRegionsCount,
&i.LimitMonitorsPerPage, &i.LimitMonitorsPerPage,
&i.LimitSubscribersPerWeek,
) )
return i, err return i, err
} }
+27 -6
View File
@@ -46,15 +46,22 @@ type Querier interface {
// System scope. Leases due rows for five minutes so a crashed sender's rows // 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. // come back; SKIP LOCKED lets every API replica work the outbox.
ClaimNotifications(ctx context.Context, max int32) ([]uuid.UUID, error) 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. // Shortens tokens that would outlive a newly set maximum lifetime.
ClampAPITokenExpiry(ctx context.Context, arg ClampAPITokenExpiryParams) (int64, error) ClampAPITokenExpiry(ctx context.Context, arg ClampAPITokenExpiryParams) (int64, error)
ClearMaintenanceTargets(ctx context.Context, windowID uuid.UUID) error ClearMaintenanceTargets(ctx context.Context, windowID uuid.UUID) error
ClearStatusPageGroups(ctx context.Context, pageID uuid.UUID) error ClearStatusPageGroups(ctx context.Context, pageID uuid.UUID) error
ClearStatusPageMonitors(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) CountMonitors(ctx context.Context, orgID uuid.UUID) (int64, error)
CountOpenSupportTickets(ctx context.Context, userID uuid.UUID) (int64, error) CountOpenSupportTickets(ctx context.Context, userID uuid.UUID) (int64, error)
CountOwnedOrgs(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) 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) CountRoleAssignments(ctx context.Context, roleID uuid.UUID) (int64, error)
CountStatusPageMonitors(ctx context.Context, pageID uuid.UUID) (int64, error) CountStatusPageMonitors(ctx context.Context, pageID uuid.UUID) (int64, error)
CountStatusPages(ctx context.Context, orgID uuid.UUID) (int64, error) CountStatusPages(ctx context.Context, orgID uuid.UUID) (int64, error)
@@ -75,6 +82,7 @@ type Querier interface {
CreateMaintenance(ctx context.Context, arg CreateMaintenanceParams) (MaintenanceWindow, error) CreateMaintenance(ctx context.Context, arg CreateMaintenanceParams) (MaintenanceWindow, error)
CreateMonitor(ctx context.Context, arg CreateMonitorParams) (Monitor, error) CreateMonitor(ctx context.Context, arg CreateMonitorParams) (Monitor, error)
CreateOrg(ctx context.Context, arg CreateOrgParams) (Org, 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) CreatePlatformIDP(ctx context.Context, arg CreatePlatformIDPParams) (PlatformIdentityProvider, error)
CreatePlatformIdentity(ctx context.Context, arg CreatePlatformIdentityParams) error CreatePlatformIdentity(ctx context.Context, arg CreatePlatformIdentityParams) error
CreateRegion(ctx context.Context, arg CreateRegionParams) (Region, error) CreateRegion(ctx context.Context, arg CreateRegionParams) (Region, error)
@@ -107,6 +115,7 @@ type Querier interface {
DeleteMonitorRegions(ctx context.Context, monitorID uuid.UUID) error DeleteMonitorRegions(ctx context.Context, monitorID uuid.UUID) error
DeleteOrg(ctx context.Context, id uuid.UUID) (int64, error) DeleteOrg(ctx context.Context, id uuid.UUID) (int64, error)
DeleteOrgStorage(ctx context.Context, orgID uuid.UUID) 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) DeletePlatformIDP(ctx context.Context, id uuid.UUID) (int64, error)
DeletePlatformIdentity(ctx context.Context, arg DeletePlatformIdentityParams) (int64, error) DeletePlatformIdentity(ctx context.Context, arg DeletePlatformIdentityParams) (int64, error)
DeleteRecoveryCodes(ctx context.Context, userID uuid.UUID) error DeleteRecoveryCodes(ctx context.Context, userID uuid.UUID) error
@@ -124,15 +133,12 @@ type Querier interface {
// for two days, after which only the verify button tries again. A verified // for two days, after which only the verify button tries again. A verified
// one is checked daily, hourly once its record went missing. // one is checked daily, hourly once its record went missing.
DomainsToCheck(ctx context.Context, arg DomainsToCheckParams) ([]DomainsToCheckRow, error) 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) EmailKeyTaken(ctx context.Context, emailKey *string) (bool, error)
EnableTOTP(ctx context.Context, arg EnableTOTPParams) error EnableTOTP(ctx context.Context, arg EnableTOTPParams) error
EnqueueNotification(ctx context.Context, arg EnqueueNotificationParams) 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. // An empty name names a new region after its key and keeps an existing name.
EnsurePlatformRegion(ctx context.Context, arg EnsurePlatformRegionParams) (Region, error) EnsurePlatformRegion(ctx context.Context, arg EnsurePlatformRegionParams) (Region, error)
// Evidence of a monitor in a time span, to link results to it. // Evidence of a monitor in a time span, to link results to it.
@@ -170,6 +176,8 @@ type Querier interface {
GetMonitor(ctx context.Context, id uuid.UUID) (Monitor, error) GetMonitor(ctx context.Context, id uuid.UUID) (Monitor, error)
GetOrg(ctx context.Context, id uuid.UUID) (Org, error) GetOrg(ctx context.Context, id uuid.UUID) (Org, error)
GetOrgBySlug(ctx context.Context, slug string) (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) GetPlatformIDP(ctx context.Context, id uuid.UUID) (PlatformIdentityProvider, error)
GetPlatformIdentity(ctx context.Context, arg GetPlatformIdentityParams) (PlatformIdentity, error) GetPlatformIdentity(ctx context.Context, arg GetPlatformIdentityParams) (PlatformIdentity, error)
GetPlatformSetting(ctx context.Context, key string) ([]byte, error) GetPlatformSetting(ctx context.Context, key string) ([]byte, error)
@@ -249,6 +257,8 @@ type Querier interface {
// By email, a page from a keyset cursor (see paging.go). // By email, a page from a keyset cursor (see paging.go).
ListOrgMembersPage(ctx context.Context, arg ListOrgMembersPageParams) ([]ListOrgMembersPageRow, error) ListOrgMembersPage(ctx context.Context, arg ListOrgMembersPageParams) ([]ListOrgMembersPageRow, error)
ListOrgs(ctx context.Context) ([]Org, 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) ListPendingInvitations(ctx context.Context) ([]ListPendingInvitationsRow, error)
ListPlatformIDPs(ctx context.Context) ([]PlatformIdentityProvider, error) ListPlatformIDPs(ctx context.Context) ([]PlatformIdentityProvider, error)
ListPlatformRegions(ctx context.Context) ([]Region, error) ListPlatformRegions(ctx context.Context) ([]Region, error)
@@ -289,6 +299,8 @@ type Querier interface {
MarkInvitationAccepted(ctx context.Context, id uuid.UUID) (int64, error) MarkInvitationAccepted(ctx context.Context, id uuid.UUID) (int64, error)
MarkNotificationFailed(ctx context.Context, arg MarkNotificationFailedParams) error MarkNotificationFailed(ctx context.Context, arg MarkNotificationFailedParams) error
MarkNotificationSent(ctx context.Context, id uuid.UUID) 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. // Every role a member holds, with the scope it applies to.
MemberGrants(ctx context.Context, arg MemberGrantsParams) ([]MemberGrantsRow, error) MemberGrants(ctx context.Context, arg MemberGrantsParams) ([]MemberGrantsRow, error)
MonitorAlertGroups(ctx context.Context, monitorID uuid.UUID) ([]uuid.UUID, error) MonitorAlertGroups(ctx context.Context, monitorID uuid.UUID) ([]uuid.UUID, error)
@@ -332,6 +344,10 @@ type Querier interface {
// Delivered and given-up notifications; pending ones are still being worked. // Delivered and given-up notifications; pending ones are still being worked.
PurgeNotifications(ctx context.Context, createdAt time.Time) (int64, error) PurgeNotifications(ctx context.Context, createdAt time.Time) (int64, error)
PurgeOrgCheckData(ctx context.Context, org uuid.UUID) 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. // Accounts never confirmed; they belong to no organization.
PurgeUnverifiedUsers(ctx context.Context, createdAt time.Time) (int64, error) PurgeUnverifiedUsers(ctx context.Context, createdAt time.Time) (int64, error)
// Raw results bucketed by width since a point in time, for short ranges. // Raw results bucketed by width since a point in time, for short ranges.
@@ -394,6 +410,8 @@ type Querier interface {
StorageGet(ctx context.Context, arg StorageGetParams) (StorageGetRow, error) StorageGet(ctx context.Context, arg StorageGetParams) (StorageGetRow, error)
StorageList(ctx context.Context, arg StorageListParams) ([]StorageListRow, error) StorageList(ctx context.Context, arg StorageListParams) ([]StorageListRow, error)
StoragePut(ctx context.Context, arg StoragePutParams) 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) SupportMessages(ctx context.Context, ticketID uuid.UUID) ([]SupportMessagesRow, error)
SupportOptionsAlertGroups(ctx context.Context, orgID uuid.UUID) ([]SupportOptionsAlertGroupsRow, error) SupportOptionsAlertGroups(ctx context.Context, orgID uuid.UUID) ([]SupportOptionsAlertGroupsRow, error)
SupportOptionsChannels(ctx context.Context, orgID uuid.UUID) ([]SupportOptionsChannelsRow, error) SupportOptionsChannels(ctx context.Context, orgID uuid.UUID) ([]SupportOptionsChannelsRow, error)
@@ -414,6 +432,9 @@ type Querier interface {
// Writes at most once a minute per instance; agents poll far more often. // Writes at most once a minute per instance; agents poll far more often.
TouchAgentInstance(ctx context.Context, arg TouchAgentInstanceParams) error TouchAgentInstance(ctx context.Context, arg TouchAgentInstanceParams) error
TouchIdentity(ctx context.Context, arg TouchIdentityParams) 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 TouchPlatformIdentity(ctx context.Context, arg TouchPlatformIdentityParams) error
// A verified domain whose record stayed missing past the grace period. // A verified domain whose record stayed missing past the grace period.
UnverifyDomain(ctx context.Context, id uuid.UUID) error UnverifyDomain(ctx context.Context, id uuid.UUID) error
-17
View File
@@ -125,23 +125,6 @@ FROM check_results_1d
WHERE org_id = $1 AND monitor_id = $2 WHERE org_id = $1 AND monitor_id = $2
GROUP BY 1, 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 -- name: FirstDataRecent :many
-- When each region of a monitor first reported since $3, exactly. Used for -- When each region of a monitor first reported since $3, exactly. Used for
-- data younger than the daily aggregate's resolution. -- data younger than the daily aggregate's resolution.
+4 -1
View File
@@ -47,7 +47,10 @@ RETURNING id;
SELECT n.id, n.org_id, n.event, n.attempts, SELECT n.id, n.org_id, n.event, n.attempts,
c.type AS channel_type, c.config AS channel_config, c.id AS channel_id, c.type AS channel_type, c.config AS channel_config, c.id AS channel_id,
i.id AS incident_id, i.started_at, i.resolved_at, i.cause, i.id AS incident_id, i.started_at, i.resolved_at, i.cause,
m.id AS monitor_id, m.name AS monitor_name, m.target AS monitor_target, m.type AS monitor_type m.id AS monitor_id, m.name AS monitor_name, m.target AS monitor_target, m.type AS monitor_type,
-- The names of the regions the cause names by id.
coalesce((SELECT jsonb_object_agg(r.id::text, r.name) FROM regions r
WHERE jsonb_typeof(i.cause) = 'object' AND i.cause ? r.id::text), '{}')::jsonb AS region_names
FROM notifications n FROM notifications n
JOIN notification_channels c ON c.id = n.channel_id JOIN notification_channels c ON c.id = n.channel_id
JOIN incidents i ON i.id = n.incident_id JOIN incidents i ON i.id = n.incident_id
+2 -2
View File
@@ -15,7 +15,7 @@ SELECT count(*) FROM status_page_monitors WHERE page_id = $1;
-- name: SetOrgLimits :one -- name: SetOrgLimits :one
UPDATE orgs SET limit_monitors = sqlc.narg(monitors), limit_status_pages = sqlc.narg(status_pages), 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_monitors_per_page = sqlc.narg(monitors_per_page), limit_subscribers_per_week = sqlc.narg(subscribers_per_week)
WHERE id = sqlc.arg(id) WHERE id = sqlc.arg(id)
RETURNING id, slug; RETURNING id, slug;
@@ -29,7 +29,7 @@ RETURNING id, email;
-- keyset cursor. -- keyset cursor.
SELECT o.id, o.slug, o.name, o.created_at, o.suspended_at, o.suspended_reason, 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, o.limit_status_pages, o.limit_regions_per_monitor, o.limit_own_regions_count,
o.limit_monitors_per_page, o.limit_monitors_per_page, o.limit_subscribers_per_week,
(SELECT count(*) FROM monitors m WHERE m.org_id = o.id)::integer AS monitors, (SELECT count(*) FROM 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, (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, coalesce(ow.id, '00000000-0000-0000-0000-000000000000'::uuid)::uuid AS owner_id,
+3 -2
View File
@@ -1,6 +1,6 @@
-- name: CreateStatusPage :one -- name: CreateStatusPage :one
INSERT INTO status_pages (org_id, slug, title, description, published, show_component_details, domain_token, theme) 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) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9)
RETURNING *; RETURNING *;
-- name: UpdateStatusPage :one -- name: UpdateStatusPage :one
@@ -11,6 +11,7 @@ SET slug = $2,
published = $5, published = $5,
show_component_details = $6, show_component_details = $6,
theme = $7, theme = $7,
subscriptions = $8,
updated_at = now() updated_at = now()
WHERE id = $1 WHERE id = $1
RETURNING *; RETURNING *;
+104
View File
@@ -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;
+19 -8
View File
@@ -59,9 +59,9 @@ func (q *Queries) ClearStatusPageMonitors(ctx context.Context, pageID uuid.UUID)
} }
const createStatusPage = `-- name: CreateStatusPage :one const createStatusPage = `-- name: CreateStatusPage :one
INSERT INTO status_pages (org_id, slug, title, description, published, show_component_details, domain_token, theme) 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) 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 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 { type CreateStatusPageParams struct {
@@ -73,6 +73,7 @@ type CreateStatusPageParams struct {
ShowComponentDetails bool ShowComponentDetails bool
DomainToken string DomainToken string
Theme []byte Theme []byte
Subscriptions bool
} }
func (q *Queries) CreateStatusPage(ctx context.Context, arg CreateStatusPageParams) (StatusPage, error) { func (q *Queries) CreateStatusPage(ctx context.Context, arg CreateStatusPageParams) (StatusPage, error) {
@@ -85,6 +86,7 @@ func (q *Queries) CreateStatusPage(ctx context.Context, arg CreateStatusPagePara
arg.ShowComponentDetails, arg.ShowComponentDetails,
arg.DomainToken, arg.DomainToken,
arg.Theme, arg.Theme,
arg.Subscriptions,
) )
var i StatusPage var i StatusPage
err := row.Scan( err := row.Scan(
@@ -107,6 +109,7 @@ func (q *Queries) CreateStatusPage(ctx context.Context, arg CreateStatusPagePara
&i.DomainCheckedAt, &i.DomainCheckedAt,
&i.DomainFailingSince, &i.DomainFailingSince,
&i.DomainVerifyMethod, &i.DomainVerifyMethod,
&i.Subscriptions,
) )
return i, err return i, err
} }
@@ -242,7 +245,7 @@ func (q *Queries) DomainsToCheck(ctx context.Context, arg DomainsToCheckParams)
} }
const findPublishedPage = `-- name: FindPublishedPage :one const findPublishedPage = `-- name: FindPublishedPage :one
SELECT id, org_id, slug, title, description, published, custom_domain, domain_token, domain_verified_at, theme, created_at, updated_at, show_component_details, suspended_at, suspended_reason, domain_set_at, domain_checked_at, domain_failing_since, domain_verify_method FROM status_pages SELECT id, org_id, slug, title, description, published, custom_domain, domain_token, domain_verified_at, theme, created_at, updated_at, show_component_details, suspended_at, suspended_reason, domain_set_at, domain_checked_at, domain_failing_since, domain_verify_method, subscriptions FROM status_pages
WHERE published AND suspended_at IS NULL 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 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) AND (($1::citext IS NOT NULL AND custom_domain = $1 AND domain_verified_at IS NOT NULL)
@@ -279,12 +282,13 @@ func (q *Queries) FindPublishedPage(ctx context.Context, arg FindPublishedPagePa
&i.DomainCheckedAt, &i.DomainCheckedAt,
&i.DomainFailingSince, &i.DomainFailingSince,
&i.DomainVerifyMethod, &i.DomainVerifyMethod,
&i.Subscriptions,
) )
return i, err return i, err
} }
const getStatusPage = `-- name: GetStatusPage :one const getStatusPage = `-- name: GetStatusPage :one
SELECT id, org_id, slug, title, description, published, custom_domain, domain_token, domain_verified_at, theme, created_at, updated_at, show_component_details, suspended_at, suspended_reason, domain_set_at, domain_checked_at, domain_failing_since, domain_verify_method FROM status_pages WHERE id = $1 SELECT id, org_id, slug, title, description, published, custom_domain, domain_token, domain_verified_at, theme, created_at, updated_at, show_component_details, suspended_at, suspended_reason, domain_set_at, domain_checked_at, domain_failing_since, domain_verify_method, subscriptions FROM status_pages WHERE id = $1
` `
func (q *Queries) GetStatusPage(ctx context.Context, id uuid.UUID) (StatusPage, error) { func (q *Queries) GetStatusPage(ctx context.Context, id uuid.UUID) (StatusPage, error) {
@@ -310,6 +314,7 @@ func (q *Queries) GetStatusPage(ctx context.Context, id uuid.UUID) (StatusPage,
&i.DomainCheckedAt, &i.DomainCheckedAt,
&i.DomainFailingSince, &i.DomainFailingSince,
&i.DomainVerifyMethod, &i.DomainVerifyMethod,
&i.Subscriptions,
) )
return i, err return i, err
} }
@@ -350,7 +355,7 @@ func (q *Queries) ListStatusPageGroups(ctx context.Context, pageID uuid.UUID) ([
} }
const listStatusPages = `-- name: ListStatusPages :many const listStatusPages = `-- name: ListStatusPages :many
SELECT id, org_id, slug, title, description, published, custom_domain, domain_token, domain_verified_at, theme, created_at, updated_at, show_component_details, suspended_at, suspended_reason, domain_set_at, domain_checked_at, domain_failing_since, domain_verify_method FROM status_pages ORDER BY title SELECT id, org_id, slug, title, description, published, custom_domain, domain_token, domain_verified_at, theme, created_at, updated_at, show_component_details, suspended_at, suspended_reason, domain_set_at, domain_checked_at, domain_failing_since, domain_verify_method, subscriptions FROM status_pages ORDER BY title
` `
func (q *Queries) ListStatusPages(ctx context.Context) ([]StatusPage, error) { func (q *Queries) ListStatusPages(ctx context.Context) ([]StatusPage, error) {
@@ -382,6 +387,7 @@ func (q *Queries) ListStatusPages(ctx context.Context) ([]StatusPage, error) {
&i.DomainCheckedAt, &i.DomainCheckedAt,
&i.DomainFailingSince, &i.DomainFailingSince,
&i.DomainVerifyMethod, &i.DomainVerifyMethod,
&i.Subscriptions,
); err != nil { ); err != nil {
return nil, err return nil, err
} }
@@ -520,7 +526,7 @@ UPDATE status_pages SET
custom_domain = $1, custom_domain = $1,
updated_at = now() updated_at = now()
WHERE id = $2 WHERE id = $2
RETURNING id, org_id, slug, title, description, published, custom_domain, domain_token, domain_verified_at, theme, created_at, updated_at, show_component_details, suspended_at, suspended_reason, domain_set_at, domain_checked_at, domain_failing_since, domain_verify_method RETURNING id, org_id, slug, title, description, published, custom_domain, domain_token, domain_verified_at, theme, created_at, updated_at, show_component_details, suspended_at, suspended_reason, domain_set_at, domain_checked_at, domain_failing_since, domain_verify_method, subscriptions
` `
type SetStatusPageDomainParams struct { type SetStatusPageDomainParams struct {
@@ -552,6 +558,7 @@ func (q *Queries) SetStatusPageDomain(ctx context.Context, arg SetStatusPageDoma
&i.DomainCheckedAt, &i.DomainCheckedAt,
&i.DomainFailingSince, &i.DomainFailingSince,
&i.DomainVerifyMethod, &i.DomainVerifyMethod,
&i.Subscriptions,
) )
return i, err return i, err
} }
@@ -652,9 +659,10 @@ SET slug = $2,
published = $5, published = $5,
show_component_details = $6, show_component_details = $6,
theme = $7, theme = $7,
subscriptions = $8,
updated_at = now() updated_at = now()
WHERE id = $1 WHERE id = $1
RETURNING id, org_id, slug, title, description, published, custom_domain, domain_token, domain_verified_at, theme, created_at, updated_at, show_component_details, suspended_at, suspended_reason, domain_set_at, domain_checked_at, domain_failing_since, domain_verify_method RETURNING id, org_id, slug, title, description, published, custom_domain, domain_token, domain_verified_at, theme, created_at, updated_at, show_component_details, suspended_at, suspended_reason, domain_set_at, domain_checked_at, domain_failing_since, domain_verify_method, subscriptions
` `
type UpdateStatusPageParams struct { type UpdateStatusPageParams struct {
@@ -665,6 +673,7 @@ type UpdateStatusPageParams struct {
Published bool Published bool
ShowComponentDetails bool ShowComponentDetails bool
Theme []byte Theme []byte
Subscriptions bool
} }
func (q *Queries) UpdateStatusPage(ctx context.Context, arg UpdateStatusPageParams) (StatusPage, error) { func (q *Queries) UpdateStatusPage(ctx context.Context, arg UpdateStatusPageParams) (StatusPage, error) {
@@ -676,6 +685,7 @@ func (q *Queries) UpdateStatusPage(ctx context.Context, arg UpdateStatusPagePara
arg.Published, arg.Published,
arg.ShowComponentDetails, arg.ShowComponentDetails,
arg.Theme, arg.Theme,
arg.Subscriptions,
) )
var i StatusPage var i StatusPage
err := row.Scan( err := row.Scan(
@@ -698,6 +708,7 @@ func (q *Queries) UpdateStatusPage(ctx context.Context, arg UpdateStatusPagePara
&i.DomainCheckedAt, &i.DomainCheckedAt,
&i.DomainFailingSince, &i.DomainFailingSince,
&i.DomainVerifyMethod, &i.DomainVerifyMethod,
&i.Subscriptions,
) )
return i, err return i, err
} }
+442
View File
@@ -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
}
+8 -2
View File
@@ -15,6 +15,7 @@ type LimitsView struct {
OwnRegionsCount bool OwnRegionsCount bool
OrgsPerAccount int OrgsPerAccount int
MonitorsPerPage int MonitorsPerPage int
SubscribersPerWeek int
} }
// OrgsView lists organizations for platform admins. // OrgsView lists organizations for platform admins.
@@ -38,6 +39,7 @@ type OrgRow struct {
RegionsOverride string RegionsOverride string
OwnRegionsOverride string OwnRegionsOverride string
PerPageOverride string PerPageOverride string
SubscribersOverride string
Owner *ModeratedTarget Owner *ModeratedTarget
OwnerOrgs int OwnerOrgs int
OwnerOrgLimit string OwnerOrgLimit string
@@ -64,7 +66,8 @@ templ limitsSection(d LimitsView) {
@numberField(i18n.T(ctx, "limits.status_pages"), "status_pages", d.StatusPages, 0, 1000000, "") @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.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.orgs_per_account"), "orgs_per_account", d.OrgsPerAccount, 0, 100000, "")
@numberField(i18n.T(ctx, "limits.monitors_per_page"), "monitors_per_page", d.MonitorsPerPage, 0, 200, "") @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> </div>
@checkbox(i18n.T(ctx, "limits.own_regions_count"), "own_regions_count", d.OwnRegionsCount) @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> <p class="mb-4 ml-6 text-xs text-muted">{ i18n.T(ctx, "limits.own_regions_count_hint") }</p>
@@ -152,7 +155,8 @@ templ orgsSection(v OrgsView) {
@overrideField(i18n.T(ctx, "limits.monitors"), "monitors", o.MonitorsOverride, v.Defaults.Monitors, 1000000) @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.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.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, 200) @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"> <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> <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"> <select name="own_regions_count" class="w-full border border-rule bg-transparent px-2 py-1 text-sm">
@@ -213,6 +217,8 @@ templ usageSection(u UsageView) {
<dd class="font-mono text-xs">{ limitText(ctx, u.Limits.RegionsPerMonitor) }</dd> <dd class="font-mono text-xs">{ limitText(ctx, u.Limits.RegionsPerMonitor) }</dd>
<dt>{ i18n.T(ctx, "limits.monitors_per_page") }</dt> <dt>{ i18n.T(ctx, "limits.monitors_per_page") }</dt>
<dd class="font-mono text-xs">{ limitText(ctx, u.Limits.MonitorsPerPage) }</dd> <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> </dl>
if u.Limits.RegionsPerMonitor > 0 && !u.Limits.OwnRegionsCount { if u.Limits.RegionsPerMonitor > 0 && !u.Limits.OwnRegionsCount {
<p class="mt-2 text-xs text-muted">{ i18n.T(ctx, "limits.own_regions_free") }</p> <p class="mt-2 text-xs text-muted">{ i18n.T(ctx, "limits.own_regions_free") }</p>
+97 -61
View File
@@ -18,12 +18,13 @@ import (
// LimitsView holds limits; 0 means unlimited. // LimitsView holds limits; 0 means unlimited.
type LimitsView struct { type LimitsView struct {
Monitors int Monitors int
StatusPages int StatusPages int
RegionsPerMonitor int RegionsPerMonitor int
OwnRegionsCount bool OwnRegionsCount bool
OrgsPerAccount int OrgsPerAccount int
MonitorsPerPage int MonitorsPerPage int
SubscribersPerWeek int
} }
// OrgsView lists organizations for platform admins. // OrgsView lists organizations for platform admins.
@@ -47,6 +48,7 @@ type OrgRow struct {
RegionsOverride string RegionsOverride string
OwnRegionsOverride string OwnRegionsOverride string
PerPageOverride string PerPageOverride string
SubscribersOverride string
Owner *ModeratedTarget Owner *ModeratedTarget
OwnerOrgs int OwnerOrgs int
OwnerOrgLimit string OwnerOrgLimit string
@@ -94,7 +96,7 @@ func limitsSection(d LimitsView) templ.Component {
var templ_7745c5c3_Var2 string var templ_7745c5c3_Var2 string
templ_7745c5c3_Var2, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, "limits.intro")) templ_7745c5c3_Var2, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, "limits.intro"))
if templ_7745c5c3_Err != nil { if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/admin_orgs.templ`, Line: 59, 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)) _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var2))
if templ_7745c5c3_Err != nil { if templ_7745c5c3_Err != nil {
@@ -128,7 +130,11 @@ func limitsSection(d LimitsView) templ.Component {
if templ_7745c5c3_Err != nil { if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err return templ_7745c5c3_Err
} }
templ_7745c5c3_Err = numberField(i18n.T(ctx, "limits.monitors_per_page"), "monitors_per_page", d.MonitorsPerPage, 0, 200, "").Render(ctx, templ_7745c5c3_Buffer) 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 { if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err return templ_7745c5c3_Err
} }
@@ -147,7 +153,7 @@ func limitsSection(d LimitsView) templ.Component {
var templ_7745c5c3_Var3 string var templ_7745c5c3_Var3 string
templ_7745c5c3_Var3, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, "limits.own_regions_count_hint")) templ_7745c5c3_Var3, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, "limits.own_regions_count_hint"))
if templ_7745c5c3_Err != nil { if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/admin_orgs.templ`, Line: 70, 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)) _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var3))
if templ_7745c5c3_Err != nil { if templ_7745c5c3_Err != nil {
@@ -160,7 +166,7 @@ func limitsSection(d LimitsView) templ.Component {
var templ_7745c5c3_Var4 string var templ_7745c5c3_Var4 string
templ_7745c5c3_Var4, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, "common.save")) templ_7745c5c3_Var4, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, "common.save"))
if templ_7745c5c3_Err != nil { if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/admin_orgs.templ`, Line: 71, 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)) _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var4))
if templ_7745c5c3_Err != nil { if templ_7745c5c3_Err != nil {
@@ -200,7 +206,7 @@ func overrideField(label, name, value string, def int, max int) templ.Component
var templ_7745c5c3_Var6 string var templ_7745c5c3_Var6 string
templ_7745c5c3_Var6, templ_7745c5c3_Err = templ.JoinStringErrs(label) templ_7745c5c3_Var6, templ_7745c5c3_Err = templ.JoinStringErrs(label)
if templ_7745c5c3_Err != nil { if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/admin_orgs.templ`, Line: 80, 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)) _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var6))
if templ_7745c5c3_Err != nil { if templ_7745c5c3_Err != nil {
@@ -213,7 +219,7 @@ func overrideField(label, name, value string, def int, max int) templ.Component
var templ_7745c5c3_Var7 string var templ_7745c5c3_Var7 string
templ_7745c5c3_Var7, templ_7745c5c3_Err = templruntime.NewAttributeExpression(name).Resolve(ctx) templ_7745c5c3_Var7, templ_7745c5c3_Err = templruntime.NewAttributeExpression(name).Resolve(ctx)
if templ_7745c5c3_Err != nil { if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/admin_orgs.templ`, Line: 83, 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) _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ_7745c5c3_Var7)
if templ_7745c5c3_Err != nil { if templ_7745c5c3_Err != nil {
@@ -226,7 +232,7 @@ func overrideField(label, name, value string, def int, max int) templ.Component
var templ_7745c5c3_Var8 string var templ_7745c5c3_Var8 string
templ_7745c5c3_Var8, templ_7745c5c3_Err = templruntime.NewAttributeExpression(strconv.Itoa(max)).Resolve(ctx) templ_7745c5c3_Var8, templ_7745c5c3_Err = templruntime.NewAttributeExpression(strconv.Itoa(max)).Resolve(ctx)
if templ_7745c5c3_Err != nil { if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/admin_orgs.templ`, Line: 87, 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) _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ_7745c5c3_Var8)
if templ_7745c5c3_Err != nil { if templ_7745c5c3_Err != nil {
@@ -239,7 +245,7 @@ func overrideField(label, name, value string, def int, max int) templ.Component
var templ_7745c5c3_Var9 string var templ_7745c5c3_Var9 string
templ_7745c5c3_Var9, templ_7745c5c3_Err = templruntime.NewAttributeExpression(value).Resolve(ctx) templ_7745c5c3_Var9, templ_7745c5c3_Err = templruntime.NewAttributeExpression(value).Resolve(ctx)
if templ_7745c5c3_Err != nil { if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/admin_orgs.templ`, Line: 88, 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) _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ_7745c5c3_Var9)
if templ_7745c5c3_Err != nil { if templ_7745c5c3_Err != nil {
@@ -252,7 +258,7 @@ func overrideField(label, name, value string, def int, max int) templ.Component
var templ_7745c5c3_Var10 string var templ_7745c5c3_Var10 string
templ_7745c5c3_Var10, templ_7745c5c3_Err = templruntime.NewAttributeExpression(i18n.T(ctx, "limits.default", "Value", limitText(ctx, def))).Resolve(ctx) templ_7745c5c3_Var10, templ_7745c5c3_Err = templruntime.NewAttributeExpression(i18n.T(ctx, "limits.default", "Value", limitText(ctx, def))).Resolve(ctx)
if templ_7745c5c3_Err != nil { if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/admin_orgs.templ`, Line: 89, 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) _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ_7745c5c3_Var10)
if templ_7745c5c3_Err != nil { if templ_7745c5c3_Err != nil {
@@ -298,7 +304,7 @@ func orgsSection(v OrgsView) templ.Component {
var templ_7745c5c3_Var12 string var templ_7745c5c3_Var12 string
templ_7745c5c3_Var12, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, "orgs.intro")) templ_7745c5c3_Var12, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, "orgs.intro"))
if templ_7745c5c3_Err != nil { if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/admin_orgs.templ`, Line: 98, 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)) _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var12))
if templ_7745c5c3_Err != nil { if templ_7745c5c3_Err != nil {
@@ -311,7 +317,7 @@ func orgsSection(v OrgsView) templ.Component {
var templ_7745c5c3_Var13 string var templ_7745c5c3_Var13 string
templ_7745c5c3_Var13, templ_7745c5c3_Err = templruntime.NewAttributeExpression(v.Search).Resolve(ctx) templ_7745c5c3_Var13, templ_7745c5c3_Err = templruntime.NewAttributeExpression(v.Search).Resolve(ctx)
if templ_7745c5c3_Err != nil { if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/admin_orgs.templ`, Line: 103, 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) _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ_7745c5c3_Var13)
if templ_7745c5c3_Err != nil { if templ_7745c5c3_Err != nil {
@@ -324,7 +330,7 @@ func orgsSection(v OrgsView) templ.Component {
var templ_7745c5c3_Var14 string var templ_7745c5c3_Var14 string
templ_7745c5c3_Var14, templ_7745c5c3_Err = templruntime.NewAttributeExpression(i18n.T(ctx, "orgs.search")).Resolve(ctx) templ_7745c5c3_Var14, templ_7745c5c3_Err = templruntime.NewAttributeExpression(i18n.T(ctx, "orgs.search")).Resolve(ctx)
if templ_7745c5c3_Err != nil { if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/admin_orgs.templ`, Line: 104, 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) _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ_7745c5c3_Var14)
if templ_7745c5c3_Err != nil { if templ_7745c5c3_Err != nil {
@@ -337,7 +343,7 @@ func orgsSection(v OrgsView) templ.Component {
var templ_7745c5c3_Var15 string var templ_7745c5c3_Var15 string
templ_7745c5c3_Var15, templ_7745c5c3_Err = templruntime.NewAttributeExpression(i18n.T(ctx, "orgs.search")).Resolve(ctx) templ_7745c5c3_Var15, templ_7745c5c3_Err = templruntime.NewAttributeExpression(i18n.T(ctx, "orgs.search")).Resolve(ctx)
if templ_7745c5c3_Err != nil { if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/admin_orgs.templ`, Line: 105, 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) _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ_7745c5c3_Var15)
if templ_7745c5c3_Err != nil { if templ_7745c5c3_Err != nil {
@@ -350,7 +356,7 @@ func orgsSection(v OrgsView) templ.Component {
var templ_7745c5c3_Var16 string var templ_7745c5c3_Var16 string
templ_7745c5c3_Var16, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, "moderation.search_button")) templ_7745c5c3_Var16, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, "moderation.search_button"))
if templ_7745c5c3_Err != nil { if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/admin_orgs.templ`, Line: 108, 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)) _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var16))
if templ_7745c5c3_Err != nil { if templ_7745c5c3_Err != nil {
@@ -368,7 +374,7 @@ func orgsSection(v OrgsView) templ.Component {
var templ_7745c5c3_Var17 string var templ_7745c5c3_Var17 string
templ_7745c5c3_Var17, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, "orgs.none")) templ_7745c5c3_Var17, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, "orgs.none"))
if templ_7745c5c3_Err != nil { if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/admin_orgs.templ`, Line: 111, 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)) _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var17))
if templ_7745c5c3_Err != nil { if templ_7745c5c3_Err != nil {
@@ -386,7 +392,7 @@ func orgsSection(v OrgsView) templ.Component {
var templ_7745c5c3_Var18 string var templ_7745c5c3_Var18 string
templ_7745c5c3_Var18, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, "moderation.org")) templ_7745c5c3_Var18, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, "moderation.org"))
if templ_7745c5c3_Err != nil { if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/admin_orgs.templ`, Line: 117, 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)) _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var18))
if templ_7745c5c3_Err != nil { if templ_7745c5c3_Err != nil {
@@ -399,7 +405,7 @@ func orgsSection(v OrgsView) templ.Component {
var templ_7745c5c3_Var19 string var templ_7745c5c3_Var19 string
templ_7745c5c3_Var19, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, "moderation.owner")) templ_7745c5c3_Var19, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, "moderation.owner"))
if templ_7745c5c3_Err != nil { if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/admin_orgs.templ`, Line: 118, 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)) _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var19))
if templ_7745c5c3_Err != nil { if templ_7745c5c3_Err != nil {
@@ -412,7 +418,7 @@ func orgsSection(v OrgsView) templ.Component {
var templ_7745c5c3_Var20 string var templ_7745c5c3_Var20 string
templ_7745c5c3_Var20, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, "limits.monitors")) templ_7745c5c3_Var20, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, "limits.monitors"))
if templ_7745c5c3_Err != nil { if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/admin_orgs.templ`, Line: 119, 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)) _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var20))
if templ_7745c5c3_Err != nil { if templ_7745c5c3_Err != nil {
@@ -425,7 +431,7 @@ func orgsSection(v OrgsView) templ.Component {
var templ_7745c5c3_Var21 string var templ_7745c5c3_Var21 string
templ_7745c5c3_Var21, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, "limits.status_pages")) templ_7745c5c3_Var21, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, "limits.status_pages"))
if templ_7745c5c3_Err != nil { if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/admin_orgs.templ`, Line: 120, 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)) _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var21))
if templ_7745c5c3_Err != nil { if templ_7745c5c3_Err != nil {
@@ -438,7 +444,7 @@ func orgsSection(v OrgsView) templ.Component {
var templ_7745c5c3_Var22 string var templ_7745c5c3_Var22 string
templ_7745c5c3_Var22, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, "moderation.created")) templ_7745c5c3_Var22, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, "moderation.created"))
if templ_7745c5c3_Err != nil { if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/admin_orgs.templ`, Line: 121, 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)) _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var22))
if templ_7745c5c3_Err != nil { if templ_7745c5c3_Err != nil {
@@ -456,7 +462,7 @@ func orgsSection(v OrgsView) templ.Component {
var templ_7745c5c3_Var23 string var templ_7745c5c3_Var23 string
templ_7745c5c3_Var23, templ_7745c5c3_Err = templ.JoinStringErrs(o.Name) templ_7745c5c3_Var23, templ_7745c5c3_Err = templ.JoinStringErrs(o.Name)
if templ_7745c5c3_Err != nil { if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/admin_orgs.templ`, Line: 128, 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)) _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var23))
if templ_7745c5c3_Err != nil { if templ_7745c5c3_Err != nil {
@@ -469,7 +475,7 @@ func orgsSection(v OrgsView) templ.Component {
var templ_7745c5c3_Var24 string var templ_7745c5c3_Var24 string
templ_7745c5c3_Var24, templ_7745c5c3_Err = templ.JoinStringErrs(o.Slug) templ_7745c5c3_Var24, templ_7745c5c3_Err = templ.JoinStringErrs(o.Slug)
if templ_7745c5c3_Err != nil { if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/admin_orgs.templ`, Line: 129, 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)) _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var24))
if templ_7745c5c3_Err != nil { if templ_7745c5c3_Err != nil {
@@ -495,7 +501,7 @@ func orgsSection(v OrgsView) templ.Component {
var templ_7745c5c3_Var25 string var templ_7745c5c3_Var25 string
templ_7745c5c3_Var25, templ_7745c5c3_Err = templ.JoinStringErrs(o.Owner.Name) templ_7745c5c3_Var25, templ_7745c5c3_Err = templ.JoinStringErrs(o.Owner.Name)
if templ_7745c5c3_Err != nil { if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/admin_orgs.templ`, Line: 134, 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)) _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var25))
if templ_7745c5c3_Err != nil { if templ_7745c5c3_Err != nil {
@@ -538,7 +544,7 @@ func orgsSection(v OrgsView) templ.Component {
var templ_7745c5c3_Var26 string var templ_7745c5c3_Var26 string
templ_7745c5c3_Var26, templ_7745c5c3_Err = templ.JoinStringErrs(o.Created) templ_7745c5c3_Var26, templ_7745c5c3_Err = templ.JoinStringErrs(o.Created)
if templ_7745c5c3_Err != nil { if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/admin_orgs.templ`, Line: 142, 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)) _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var26))
if templ_7745c5c3_Err != nil { if templ_7745c5c3_Err != nil {
@@ -551,7 +557,7 @@ func orgsSection(v OrgsView) templ.Component {
var templ_7745c5c3_Var27 string var templ_7745c5c3_Var27 string
templ_7745c5c3_Var27, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, "orgs.manage")) templ_7745c5c3_Var27, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, "orgs.manage"))
if templ_7745c5c3_Err != nil { if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/admin_orgs.templ`, Line: 147, 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)) _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var27))
if templ_7745c5c3_Err != nil { if templ_7745c5c3_Err != nil {
@@ -564,7 +570,7 @@ func orgsSection(v OrgsView) templ.Component {
var templ_7745c5c3_Var28 string var templ_7745c5c3_Var28 string
templ_7745c5c3_Var28, templ_7745c5c3_Err = templruntime.NewAttributeExpression("/admin/orgs/" + o.ID + "/limits").Resolve(ctx) templ_7745c5c3_Var28, templ_7745c5c3_Err = templruntime.NewAttributeExpression("/admin/orgs/" + o.ID + "/limits").Resolve(ctx)
if templ_7745c5c3_Err != nil { if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/admin_orgs.templ`, Line: 149, 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) _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ_7745c5c3_Var28)
if templ_7745c5c3_Err != nil { if templ_7745c5c3_Err != nil {
@@ -577,7 +583,7 @@ func orgsSection(v OrgsView) templ.Component {
var templ_7745c5c3_Var29 string var templ_7745c5c3_Var29 string
templ_7745c5c3_Var29, templ_7745c5c3_Err = templruntime.NewAttributeExpression(v.next()).Resolve(ctx) templ_7745c5c3_Var29, templ_7745c5c3_Err = templruntime.NewAttributeExpression(v.next()).Resolve(ctx)
if templ_7745c5c3_Err != nil { if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/admin_orgs.templ`, Line: 149, 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) _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ_7745c5c3_Var29)
if templ_7745c5c3_Err != nil { if templ_7745c5c3_Err != nil {
@@ -590,7 +596,7 @@ func orgsSection(v OrgsView) templ.Component {
var templ_7745c5c3_Var30 string var templ_7745c5c3_Var30 string
templ_7745c5c3_Var30, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, "orgs.limits")) templ_7745c5c3_Var30, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, "orgs.limits"))
if templ_7745c5c3_Err != nil { if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/admin_orgs.templ`, Line: 150, 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)) _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var30))
if templ_7745c5c3_Err != nil { if templ_7745c5c3_Err != nil {
@@ -616,7 +622,11 @@ func orgsSection(v OrgsView) templ.Component {
if templ_7745c5c3_Err != nil { if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err return templ_7745c5c3_Err
} }
templ_7745c5c3_Err = overrideField(i18n.T(ctx, "limits.monitors_per_page"), "monitors_per_page", o.PerPageOverride, v.Defaults.MonitorsPerPage, 200).Render(ctx, templ_7745c5c3_Buffer) 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 { if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err return templ_7745c5c3_Err
} }
@@ -627,7 +637,7 @@ func orgsSection(v OrgsView) templ.Component {
var templ_7745c5c3_Var31 string var templ_7745c5c3_Var31 string
templ_7745c5c3_Var31, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, "limits.own_regions_count")) templ_7745c5c3_Var31, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, "limits.own_regions_count"))
if templ_7745c5c3_Err != nil { if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/admin_orgs.templ`, Line: 157, 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)) _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var31))
if templ_7745c5c3_Err != nil { if templ_7745c5c3_Err != nil {
@@ -650,7 +660,7 @@ func orgsSection(v OrgsView) templ.Component {
var templ_7745c5c3_Var32 string 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)))) 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 { if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/admin_orgs.templ`, Line: 159, 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)) _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var32))
if templ_7745c5c3_Err != nil { if templ_7745c5c3_Err != nil {
@@ -673,7 +683,7 @@ func orgsSection(v OrgsView) templ.Component {
var templ_7745c5c3_Var33 string var templ_7745c5c3_Var33 string
templ_7745c5c3_Var33, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, "limits.own_true")) templ_7745c5c3_Var33, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, "limits.own_true"))
if templ_7745c5c3_Err != nil { if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/admin_orgs.templ`, Line: 160, 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)) _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var33))
if templ_7745c5c3_Err != nil { if templ_7745c5c3_Err != nil {
@@ -696,7 +706,7 @@ func orgsSection(v OrgsView) templ.Component {
var templ_7745c5c3_Var34 string var templ_7745c5c3_Var34 string
templ_7745c5c3_Var34, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, "limits.own_false")) templ_7745c5c3_Var34, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, "limits.own_false"))
if templ_7745c5c3_Err != nil { if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/admin_orgs.templ`, Line: 161, 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)) _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var34))
if templ_7745c5c3_Err != nil { if templ_7745c5c3_Err != nil {
@@ -709,7 +719,7 @@ func orgsSection(v OrgsView) templ.Component {
var templ_7745c5c3_Var35 string var templ_7745c5c3_Var35 string
templ_7745c5c3_Var35, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, "common.save")) templ_7745c5c3_Var35, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, "common.save"))
if templ_7745c5c3_Err != nil { if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/admin_orgs.templ`, Line: 164, 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)) _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var35))
if templ_7745c5c3_Err != nil { if templ_7745c5c3_Err != nil {
@@ -731,7 +741,7 @@ func orgsSection(v OrgsView) templ.Component {
var templ_7745c5c3_Var36 string var templ_7745c5c3_Var36 string
templ_7745c5c3_Var36, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, "moderation.owner_is_admin")) templ_7745c5c3_Var36, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, "moderation.owner_is_admin"))
if templ_7745c5c3_Err != nil { if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/admin_orgs.templ`, Line: 168, 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)) _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var36))
if templ_7745c5c3_Err != nil { if templ_7745c5c3_Err != nil {
@@ -749,7 +759,7 @@ func orgsSection(v OrgsView) templ.Component {
var templ_7745c5c3_Var37 string var templ_7745c5c3_Var37 string
templ_7745c5c3_Var37, templ_7745c5c3_Err = templruntime.NewAttributeExpression("/admin/users/" + o.Owner.ID + "/limits").Resolve(ctx) templ_7745c5c3_Var37, templ_7745c5c3_Err = templruntime.NewAttributeExpression("/admin/users/" + o.Owner.ID + "/limits").Resolve(ctx)
if templ_7745c5c3_Err != nil { if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/admin_orgs.templ`, Line: 171, 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) _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ_7745c5c3_Var37)
if templ_7745c5c3_Err != nil { if templ_7745c5c3_Err != nil {
@@ -762,7 +772,7 @@ func orgsSection(v OrgsView) templ.Component {
var templ_7745c5c3_Var38 string var templ_7745c5c3_Var38 string
templ_7745c5c3_Var38, templ_7745c5c3_Err = templruntime.NewAttributeExpression(v.next()).Resolve(ctx) templ_7745c5c3_Var38, templ_7745c5c3_Err = templruntime.NewAttributeExpression(v.next()).Resolve(ctx)
if templ_7745c5c3_Err != nil { if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/admin_orgs.templ`, Line: 171, 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) _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ_7745c5c3_Var38)
if templ_7745c5c3_Err != nil { if templ_7745c5c3_Err != nil {
@@ -775,7 +785,7 @@ func orgsSection(v OrgsView) templ.Component {
var templ_7745c5c3_Var39 string var templ_7745c5c3_Var39 string
templ_7745c5c3_Var39, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, "moderation.target_owner")) templ_7745c5c3_Var39, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, "moderation.target_owner"))
if templ_7745c5c3_Err != nil { if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/admin_orgs.templ`, Line: 172, 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)) _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var39))
if templ_7745c5c3_Err != nil { if templ_7745c5c3_Err != nil {
@@ -800,7 +810,7 @@ func orgsSection(v OrgsView) templ.Component {
var templ_7745c5c3_Var40 string var templ_7745c5c3_Var40 string
templ_7745c5c3_Var40, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, "common.save")) templ_7745c5c3_Var40, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, "common.save"))
if templ_7745c5c3_Err != nil { if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/admin_orgs.templ`, Line: 175, 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)) _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var40))
if templ_7745c5c3_Err != nil { if templ_7745c5c3_Err != nil {
@@ -902,7 +912,7 @@ func usage(used, max int) templ.Component {
var templ_7745c5c3_Var44 string var templ_7745c5c3_Var44 string
templ_7745c5c3_Var44, templ_7745c5c3_Err = templ.JoinStringErrs(strconv.Itoa(used)) templ_7745c5c3_Var44, templ_7745c5c3_Err = templ.JoinStringErrs(strconv.Itoa(used))
if templ_7745c5c3_Err != nil { if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/admin_orgs.templ`, Line: 195, 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)) _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var44))
if templ_7745c5c3_Err != nil { if templ_7745c5c3_Err != nil {
@@ -915,7 +925,7 @@ func usage(used, max int) templ.Component {
var templ_7745c5c3_Var45 string var templ_7745c5c3_Var45 string
templ_7745c5c3_Var45, templ_7745c5c3_Err = templ.JoinStringErrs(limitText(ctx, max)) templ_7745c5c3_Var45, templ_7745c5c3_Err = templ.JoinStringErrs(limitText(ctx, max))
if templ_7745c5c3_Err != nil { if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/admin_orgs.templ`, Line: 195, 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)) _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var45))
if templ_7745c5c3_Err != nil { if templ_7745c5c3_Err != nil {
@@ -967,7 +977,7 @@ func usageSection(u UsageView) templ.Component {
var templ_7745c5c3_Var47 string var templ_7745c5c3_Var47 string
templ_7745c5c3_Var47, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, "limits.monitors")) templ_7745c5c3_Var47, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, "limits.monitors"))
if templ_7745c5c3_Err != nil { if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/admin_orgs.templ`, Line: 208, 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)) _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var47))
if templ_7745c5c3_Err != nil { if templ_7745c5c3_Err != nil {
@@ -988,7 +998,7 @@ func usageSection(u UsageView) templ.Component {
var templ_7745c5c3_Var48 string var templ_7745c5c3_Var48 string
templ_7745c5c3_Var48, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, "limits.status_pages")) templ_7745c5c3_Var48, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, "limits.status_pages"))
if templ_7745c5c3_Err != nil { if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/admin_orgs.templ`, Line: 210, 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)) _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var48))
if templ_7745c5c3_Err != nil { if templ_7745c5c3_Err != nil {
@@ -1009,7 +1019,7 @@ func usageSection(u UsageView) templ.Component {
var templ_7745c5c3_Var49 string var templ_7745c5c3_Var49 string
templ_7745c5c3_Var49, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, "limits.regions_per_monitor")) templ_7745c5c3_Var49, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, "limits.regions_per_monitor"))
if templ_7745c5c3_Err != nil { if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/admin_orgs.templ`, Line: 212, 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)) _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var49))
if templ_7745c5c3_Err != nil { if templ_7745c5c3_Err != nil {
@@ -1022,7 +1032,7 @@ func usageSection(u UsageView) templ.Component {
var templ_7745c5c3_Var50 string var templ_7745c5c3_Var50 string
templ_7745c5c3_Var50, templ_7745c5c3_Err = templ.JoinStringErrs(limitText(ctx, u.Limits.RegionsPerMonitor)) templ_7745c5c3_Var50, templ_7745c5c3_Err = templ.JoinStringErrs(limitText(ctx, u.Limits.RegionsPerMonitor))
if templ_7745c5c3_Err != nil { if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/admin_orgs.templ`, Line: 213, 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)) _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var50))
if templ_7745c5c3_Err != nil { if templ_7745c5c3_Err != nil {
@@ -1035,7 +1045,7 @@ func usageSection(u UsageView) templ.Component {
var templ_7745c5c3_Var51 string var templ_7745c5c3_Var51 string
templ_7745c5c3_Var51, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, "limits.monitors_per_page")) templ_7745c5c3_Var51, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, "limits.monitors_per_page"))
if templ_7745c5c3_Err != nil { if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/admin_orgs.templ`, Line: 214, Col: 48} 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)) _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var51))
if templ_7745c5c3_Err != nil { if templ_7745c5c3_Err != nil {
@@ -1048,36 +1058,62 @@ func usageSection(u UsageView) templ.Component {
var templ_7745c5c3_Var52 string var templ_7745c5c3_Var52 string
templ_7745c5c3_Var52, templ_7745c5c3_Err = templ.JoinStringErrs(limitText(ctx, u.Limits.MonitorsPerPage)) templ_7745c5c3_Var52, templ_7745c5c3_Err = templ.JoinStringErrs(limitText(ctx, u.Limits.MonitorsPerPage))
if templ_7745c5c3_Err != nil { if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/admin_orgs.templ`, Line: 215, Col: 75} 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)) _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var52))
if templ_7745c5c3_Err != nil { if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err return templ_7745c5c3_Err
} }
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 83, "</dd></dl>") 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 { if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err return templ_7745c5c3_Err
} }
if u.Limits.RegionsPerMonitor > 0 && !u.Limits.OwnRegionsCount { if u.Limits.RegionsPerMonitor > 0 && !u.Limits.OwnRegionsCount {
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 84, "<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 { if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err return templ_7745c5c3_Err
} }
var templ_7745c5c3_Var53 string var templ_7745c5c3_Var55 string
templ_7745c5c3_Var53, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, "limits.own_regions_free")) templ_7745c5c3_Var55, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, "limits.own_regions_free"))
if templ_7745c5c3_Err != nil { if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/admin_orgs.templ`, Line: 218, 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_Var53)) _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var55))
if templ_7745c5c3_Err != nil { if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err return templ_7745c5c3_Err
} }
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 85, "</p>") templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 87, "</p>")
if templ_7745c5c3_Err != nil { if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err return templ_7745c5c3_Err
} }
} }
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 86, "</section>") templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 88, "</section>")
if templ_7745c5c3_Err != nil { if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err return templ_7745c5c3_Err
} }
+26 -2
View File
@@ -2,6 +2,7 @@ package web
import ( import (
"bytes" "bytes"
"slices"
"github.com/yuin/goldmark" "github.com/yuin/goldmark"
"github.com/yuin/goldmark/ast" "github.com/yuin/goldmark/ast"
@@ -80,7 +81,30 @@ func LegalLinks(docs []agentapi.LegalDoc, base string) []LegalLink {
return out return out
} }
// PageLegalLinks returns the legal links of a status page. // PageLegalLinks returns the legal links of a status page's footer. The
// terms are not among them: visitors accept them only when subscribing.
func PageLegalLinks(s agentapi.PageSnapshot, base string) []LegalLink { func PageLegalLinks(s agentapi.PageSnapshot, base string) []LegalLink {
return LegalLinks(s.Legal, base) return slices.DeleteFunc(LegalLinks(s.Legal, base), func(l LegalLink) bool { return l.Kind == "terms" })
}
// SubscribeConsent returns the documents a visitor of a status page
// accepts by subscribing: the terms and the privacy policy, where set.
func SubscribeConsent(s agentapi.PageSnapshot, base string) []LegalLink {
return slices.DeleteFunc(LegalLinks(s.Legal, base), func(l LegalLink) bool { return l.Kind == "imprint" })
}
// ConsentLabelID names the message of the subscription checkbox for links.
func ConsentLabelID(links []LegalLink) string {
var terms, privacy bool
for _, l := range links {
terms = terms || l.Kind == "terms"
privacy = privacy || l.Kind == "privacy"
}
switch {
case terms && privacy:
return "page.subscribe.accept_both"
case terms:
return "page.subscribe.accept_terms"
}
return "page.subscribe.accept_privacy"
} }
+8
View File
@@ -28,6 +28,14 @@ type PublicAssets struct {
// Now is the moment the page shows, deciding which maintenance is in // Now is the moment the page shows, deciding which maintenance is in
// progress. // progress.
Now time.Time Now time.Time
// NoRefresh leaves out the periodic reload, on pages with a form.
NoRefresh bool
}
// NoticeForm is the button of a notice page that acts on a mailed link,
// so mail scanners opening the link do not act on it themselves.
type NoticeForm struct {
Action, Token, Button string
} }
// Markdown renders src for display, or returns "" when it cannot. // Markdown renders src for display, or returns "" when it cannot.
+94 -1
View File
@@ -15,7 +15,12 @@ templ publicShell(s agentapi.PageSnapshot, a PublicAssets, docTitle string) {
<head> <head>
<meta charset="utf-8"/> <meta charset="utf-8"/>
<meta name="viewport" content="width=device-width, initial-scale=1"/> <meta name="viewport" content="width=device-width, initial-scale=1"/>
<meta http-equiv="refresh" content="60"/> if !a.NoRefresh {
<meta http-equiv="refresh" content="60"/>
}
if a.ComponentBase != "" {
<link rel="alternate" type="application/rss+xml" title={ s.Title } href={ a.ComponentBase + "feed.rss" }/>
}
<title>{ docTitle }</title> <title>{ docTitle }</title>
if a.InlineCSS == "" { if a.InlineCSS == "" {
@faviconLinks() @faviconLinks()
@@ -38,6 +43,10 @@ templ publicShell(s agentapi.PageSnapshot, a PublicAssets, docTitle string) {
<footer class="flex flex-wrap justify-between gap-x-4 gap-y-2 border-t border-rule pt-4 font-mono text-xs text-muted"> <footer class="flex flex-wrap justify-between gap-x-4 gap-y-2 border-t border-rule pt-4 font-mono text-xs text-muted">
<span>{ i18n.T(ctx, "page.updated", "Time", s.GeneratedAt.UTC().Format(time.DateTime)+" UTC") }</span> <span>{ i18n.T(ctx, "page.updated", "Time", s.GeneratedAt.UTC().Format(time.DateTime)+" UTC") }</span>
<span class="flex flex-wrap justify-end gap-x-4 gap-y-1"> <span class="flex flex-wrap justify-end gap-x-4 gap-y-1">
if a.ComponentBase != "" {
<a href={ templ.SafeURL(a.ComponentBase + "feed.rss") } class="hover:text-ink">{ i18n.T(ctx, "page.feed") }</a>
<a href={ templ.SafeURL(a.ComponentBase + "api/v1/summary") } class="hover:text-ink">{ i18n.T(ctx, "page.api") }</a>
}
for _, l := range PageLegalLinks(s, a.LegalBase) { for _, l := range PageLegalLinks(s, a.LegalBase) {
@legalLink(l) @legalLink(l)
} }
@@ -94,6 +103,58 @@ templ PublicStatusPage(s agentapi.PageSnapshot, a PublicAssets) {
} }
@publicIncidents(s.Incidents) @publicIncidents(s.Incidents)
@pageMaintenance(i18n.T(ctx, "page.maintenance_upcoming"), s.Upcoming(a.Now)) @pageMaintenance(i18n.T(ctx, "page.maintenance_upcoming"), s.Upcoming(a.Now))
if s.Subscribe && a.ComponentBase != "" {
@publicSubscribe(s, a)
}
}
}
// publicSubscribe offers email subscriptions to the page's incidents.
templ publicSubscribe(s agentapi.PageSnapshot, a PublicAssets) {
<section id="subscribe" class="mb-12 border-t border-rule pt-6">
<h2 class="mb-1 text-xs font-medium uppercase tracking-wider text-muted">{ i18n.T(ctx, "page.subscribe.title") }</h2>
<p class="mb-3 text-sm">{ i18n.T(ctx, "page.subscribe.intro") }</p>
<form method="post" action={ templ.SafeURL(a.ComponentBase + "subscribe") } class="max-w-md">
<div class="flex flex-wrap gap-2">
<label class="sr-only" for="subscribe-email">{ i18n.T(ctx, "page.subscribe.email") }</label>
<input id="subscribe-email" type="email" name="email" required maxlength="254" autocomplete="email" placeholder={ i18n.T(ctx, "page.subscribe.email") } class="min-w-0 flex-1 border border-rule bg-transparent px-2 py-1.5 text-sm"/>
<button type="submit" class="border border-ink px-3 py-1.5 text-sm hover:bg-ink hover:text-paper">{ i18n.T(ctx, "page.subscribe.submit") }</button>
</div>
if consent := SubscribeConsent(s, a.LegalBase); len(consent) > 0 {
<label class="mt-3 flex items-start gap-2 text-sm">
<input type="checkbox" name="accept" value="1" required class="mt-1"/>
<span>
{ i18n.T(ctx, ConsentLabelID(consent)) }
for i, l := range consent {
if i > 0 {
<span aria-hidden="true">·</span>
}
<a href={ templ.SafeURL(l.Href) } target="_blank" rel="noopener" class="underline underline-offset-2">{ i18n.T(ctx, LegalTitleID(l.Kind)) }</a>
}
</span>
</label>
}
</form>
<p class="mt-2 text-xs text-muted">{ i18n.T(ctx, "page.subscribe.privacy") }</p>
</section>
}
// PublicNoticePage tells a visitor of the page the outcome of a
// subscription request, or asks to confirm one with form.
templ PublicNoticePage(s agentapi.PageSnapshot, a PublicAssets, title, message string, form *NoticeForm) {
@publicShell(s, a, title+" · "+s.Title) {
<header class="mb-10">
<p class="mb-2 font-mono text-xs text-muted">{ s.Title }</p>
<h1 class="text-2xl font-semibold" style="color:var(--page-accent,inherit)">{ title }</h1>
</header>
<p class="mb-8 max-w-xl">{ message }</p>
if form != nil {
<form method="post" action={ templ.SafeURL(form.Action) } class="mb-8">
<input type="hidden" name="token" value={ form.Token }/>
<button type="submit" class="border border-ink px-3 py-1.5 text-sm hover:bg-ink hover:text-paper">{ form.Button }</button>
</form>
}
<p class="mb-12 text-sm"><a href={ templ.SafeURL(a.ComponentBase) } class="underline underline-offset-2">{ i18n.T(ctx, "page.back") }</a></p>
} }
} }
@@ -385,3 +446,35 @@ templ pageMaintenance(heading string, items []agentapi.PageMaintenance) {
</section> </section>
} }
} }
// PublicNotFoundPage answers visitors of a status page that does not exist,
// and of the bare status page domain, with a link to the home page if set.
templ PublicNotFoundPage(cssHref, home string) {
<!DOCTYPE html>
<html lang={ i18n.Lang(ctx) }>
<head>
<meta charset="utf-8"/>
<meta name="viewport" content="width=device-width, initial-scale=1"/>
<meta name="robots" content="noindex"/>
<title>{ i18n.T(ctx, "page.not_found_title") }</title>
@faviconLinks()
<link rel="stylesheet" href={ cssHref }/>
</head>
<body class="min-h-screen">
<main class="mx-auto flex min-h-screen max-w-xl flex-col justify-center px-4 py-14 sm:px-6">
<p class="mb-3 font-mono text-xs text-muted">404</p>
<h1 class="mb-3 text-2xl font-semibold">{ i18n.T(ctx, "page.not_found_title") }</h1>
<p class="mb-8 text-muted">{ i18n.T(ctx, "page.not_found") }</p>
if home != "" {
<p>
<a href={ templ.SafeURL(home) } class="inline-block border border-ink px-4 py-2 text-sm hover:bg-ink hover:text-paper">{ i18n.T(ctx, "page.not_found_home") }</a>
</p>
}
<p class="mt-14 flex items-center gap-1 font-mono text-xs text-muted">
@brandMark("h-3.5 w-3.5")
UptimeSebi
</p>
</main>
</body>
</html>
}
File diff suppressed because it is too large. Load diff
+1 -1
View File
@@ -33,7 +33,7 @@ var Ranges = []TimeRange{
{Key: "1h", Window: time.Hour, Bucket: time.Minute, Layout: "15:04"}, {Key: "1h", Window: time.Hour, Bucket: time.Minute, Layout: "15:04"},
{Key: "3h", Window: 3 * time.Hour, Bucket: 5 * time.Minute, Layout: "15:04"}, {Key: "3h", Window: 3 * time.Hour, Bucket: 5 * time.Minute, Layout: "15:04"},
{Key: "12h", Window: 12 * time.Hour, Bucket: 15 * time.Minute, Layout: "15:04"}, {Key: "12h", Window: 12 * time.Hour, Bucket: 15 * time.Minute, Layout: "15:04"},
{Key: "24h", Window: day, Bucket: 30 * time.Minute, Layout: "01-02 15:04"}, {Key: "24h", Window: day, Bucket: time.Hour, Source: SourceHourly, Layout: "01-02 15:04"},
{Key: "7d", Window: 7 * day, Bucket: 4 * time.Hour, Source: SourceHourly, Layout: "01-02 15:04"}, {Key: "7d", Window: 7 * day, Bucket: 4 * time.Hour, Source: SourceHourly, Layout: "01-02 15:04"},
{Key: "30d", Window: 30 * day, Bucket: 12 * time.Hour, Source: SourceHourly, Layout: "2006-01-02 15:04"}, {Key: "30d", Window: 30 * day, Bucket: 12 * time.Hour, Source: SourceHourly, Layout: "2006-01-02 15:04"},
{Key: "90d", Window: 90 * day, Bucket: 2 * day, Source: SourceDaily, Layout: "2006-01-02"}, {Key: "90d", Window: 90 * day, Bucket: 2 * day, Source: SourceDaily, Layout: "2006-01-02"},
+19 -1
View File
@@ -195,7 +195,7 @@ templ RegionsPage(p Page, me Me, v RegionsView) {
} }
} }
templ AdminPage(p Page, me Me, v RegionsView, storage StorageView, checkTypes []CheckTypeOption, platformPrivate bool, limits LimitsView, idps IDPAdminView) { templ AdminPage(p Page, me Me, v RegionsView, storage StorageView, checkTypes []CheckTypeOption, platformPrivate bool, pageHome string, limits LimitsView, idps IDPAdminView) {
@consoleShell(p, me) { @consoleShell(p, me) {
@settingsHeading("admin.title", "admin.intro") @settingsHeading("admin.title", "admin.intro")
@adminLinks() @adminLinks()
@@ -203,6 +203,7 @@ templ AdminPage(p Page, me Me, v RegionsView, storage StorageView, checkTypes []
@limitsSection(limits) @limitsSection(limits)
@regionsBody(v) @regionsBody(v)
@checkerNetworkSection(platformPrivate) @checkerNetworkSection(platformPrivate)
@statusPageHomeSection(pageHome)
@checkTypesSection(checkTypes, "/admin/check-types", "/admin", "admin.check_types_intro") @checkTypesSection(checkTypes, "/admin/check-types", "/admin", "admin.check_types_intro")
@storageSection(storage) @storageSection(storage)
} }
@@ -228,6 +229,23 @@ templ checkerNetworkSection(allow bool) {
</section> </section>
} }
// statusPageHomeSection sets the home page the status page servers link
// from their error page.
templ statusPageHomeSection(url string) {
<section class="mt-12 max-w-3xl">
@sectionHeading("admin.statuspage_home")
<p class="mb-4 text-sm text-muted">{ i18n.T(ctx, "admin.statuspage_home_hint") }</p>
<form data-api="/admin/statuspage-home" data-method="put" data-next="/admin">
@formError()
<label class="mb-4 block">
<span class="mb-1 block text-xs font-medium uppercase tracking-wider text-muted">{ i18n.T(ctx, "admin.statuspage_home_url") }</span>
<input class="w-full border border-rule bg-transparent px-2.5 py-1.5 outline-none focus:border-ink" type="url" name="url" value={ url } maxlength="2000" placeholder="https://example.com"/>
</label>
<button type="submit" class="border border-ink px-3 py-1.5 text-sm hover:bg-ink hover:text-paper">{ i18n.T(ctx, "common.save") }</button>
</form>
</section>
}
// checkTypesSection lets the platform or an organization choose the // checkTypesSection lets the platform or an organization choose the
// check types it offers. // check types it offers.
templ checkTypesSection(types []CheckTypeOption, api, next, introID string) { templ checkTypesSection(types []CheckTypeOption, api, next, introID string) {
File diff suppressed because it is too large. Load diff
+66
View File
@@ -2,6 +2,7 @@ package web
import ( import (
"strconv" "strconv"
"strings"
"git.zb-server.de/ZB-Server/uptimesebi/internal/i18n" "git.zb-server.de/ZB-Server/uptimesebi/internal/i18n"
) )
@@ -120,6 +121,15 @@ type PageEditor struct {
DomainChangesPerDay int DomainChangesPerDay int
// MonitorLimit is how many monitors the page may show; 0 is any. // MonitorLimit is how many monitors the page may show; 0 is any.
MonitorLimit int MonitorLimit int
// Subscriptions lets visitors subscribe by email; MailAvailable says
// whether the platform can send mail at all.
Subscriptions bool
MailAvailable bool
// SubscriberLimit is the organization's weekly limit; 0 is any.
SubscriberLimit int
SubscribersConfirmed int
SubscribersPending int
Subscribers []PageSubscriberRow
RecordName string RecordName string
RecordValue string RecordValue string
Suspended bool Suspended bool
@@ -166,6 +176,13 @@ templ StatusPageEditor(p Page, me Me, e PageEditor) {
@checkbox(i18n.T(ctx, "pages.published"), "published", e.Published) @checkbox(i18n.T(ctx, "pages.published"), "published", e.Published)
@checkbox(i18n.T(ctx, "pages.show_details"), "show_component_details", e.ShowDetails) @checkbox(i18n.T(ctx, "pages.show_details"), "show_component_details", e.ShowDetails)
<p class="-mt-2 mb-4 text-xs text-muted">{ i18n.T(ctx, "pages.show_details_hint") }</p> <p class="-mt-2 mb-4 text-xs text-muted">{ i18n.T(ctx, "pages.show_details_hint") }</p>
@checkbox(i18n.T(ctx, "pages.subscriptions"), "subscriptions", e.Subscriptions)
<p class="-mt-2 mb-4 text-xs text-muted">
{ i18n.T(ctx, "pages.subscriptions_hint") }
if !e.MailAvailable {
{ " " + i18n.T(ctx, "pages.subscriptions_no_mail") }
}
</p>
<h3 class="mt-6 mb-3 text-xs font-medium uppercase tracking-wider text-muted">{ i18n.T(ctx, "pages.theme") }</h3> <h3 class="mt-6 mb-3 text-xs font-medium uppercase tracking-wider text-muted">{ i18n.T(ctx, "pages.theme") }</h3>
@valueField(i18n.T(ctx, "pages.accent"), "theme.accent", e.Accent, "#1f6feb", false) @valueField(i18n.T(ctx, "pages.accent"), "theme.accent", e.Accent, "#1f6feb", false)
@valueField(i18n.T(ctx, "pages.logo"), "theme.logo_url", e.LogoURL, "https://example.com/logo.svg", false) @valueField(i18n.T(ctx, "pages.logo"), "theme.logo_url", e.LogoURL, "https://example.com/logo.svg", false)
@@ -182,6 +199,20 @@ templ StatusPageEditor(p Page, me Me, e PageEditor) {
data-next="/statuspages" data-next="/statuspages"
class="mt-6 text-sm text-down hover:underline" class="mt-6 text-sm text-down hover:underline"
>{ i18n.T(ctx, "pages.delete") }</button> >{ i18n.T(ctx, "pages.delete") }</button>
if e.URL != "" {
<section class="mt-12">
@sectionHeading("pages.feeds")
<p class="mb-2 text-sm text-muted">{ i18n.T(ctx, "pages.feeds_hint") }</p>
<ul class="space-y-1 font-mono text-xs">
for _, path := range []string{"feed.rss", "api/v1/status", "api/v1/summary", "api/v1/components", "api/v1/incidents"} {
<li><a href={ templ.SafeURL(strings.TrimSuffix(e.URL, "/") + "/" + path) } target="_blank" rel="noopener" class="hover:underline">{ strings.TrimSuffix(e.URL, "/") + "/" + path }</a></li>
}
</ul>
</section>
}
if e.Subscriptions || e.SubscribersConfirmed+e.SubscribersPending > 0 {
@pageSubscribers(e)
}
</section> </section>
<div> <div>
<section class="mb-12"> <section class="mb-12">
@@ -398,3 +429,38 @@ templ pageMonitorFields(e PageEditor, m PageMonitorOption) {
<input data-field="label" value={ m.Label } placeholder={ i18n.T(ctx, "pages.label") } class="w-1/2 border border-rule bg-transparent px-2 py-1 text-xs outline-none focus:border-ink"/> <input data-field="label" value={ m.Label } placeholder={ i18n.T(ctx, "pages.label") } class="w-1/2 border border-rule bg-transparent px-2 py-1 text-xs outline-none focus:border-ink"/>
</span> </span>
} }
// PageSubscriberRow is an email subscriber of a page.
type PageSubscriberRow struct {
ID, Email, Since string
Pending bool
}
templ pageSubscribers(e PageEditor) {
<section id="subscribers" class="mt-12">
@sectionHeading("pages.subscribers")
<p class="mb-2 text-sm">{ i18n.T(ctx, "pages.subscribers_counts", "Confirmed", e.SubscribersConfirmed, "Pending", e.SubscribersPending) }</p>
if e.SubscriberLimit > 0 {
<p class="mb-3 text-xs text-muted">{ i18n.T(ctx, "pages.subscribers_limit", "Max", e.SubscriberLimit) }</p>
}
if len(e.Subscribers) == 0 {
<p class="text-sm text-muted">{ i18n.T(ctx, "pages.subscribers_none") }</p>
} else {
<ul class="divide-y divide-rule border-y border-rule text-sm">
for _, sub := range e.Subscribers {
<li class="flex flex-wrap items-baseline gap-x-3 gap-y-1 py-2">
<span class="font-mono text-xs">{ sub.Email }</span>
if sub.Pending {
<span class="text-xs text-muted">{ i18n.T(ctx, "pages.subscriber_pending") }</span>
}
<span class="ml-auto font-mono text-xs text-muted">{ sub.Since }</span>
<button type="button" data-delete={ "/org/statuspages/" + e.ID + "/subscribers/" + sub.ID } data-next={ "/statuspages/" + e.ID + "#subscribers" } class="text-xs text-muted hover:text-down">{ i18n.T(ctx, "pages.subscriber_remove") }</button>
</li>
}
</ul>
if len(e.Subscribers) < e.SubscribersConfirmed+e.SubscribersPending {
<p class="mt-2 text-xs text-muted">{ i18n.T(ctx, "pages.subscribers_more", "Count", len(e.Subscribers)) }</p>
}
}
</section>
}
File diff suppressed because it is too large. Load diff