Compare commits

...
Author SHA1 Message Date
Sebastian UnterschützandClaude Opus 5.5 1138d555aa perf: load console pages in time for organizations with many monitors
ci / lint (push) Skipped
ci / image (push) Skipped
ci / test (push) Skipped
ci / build (push) Skipped
ci / test (pull_request) Successful in 12m19s
ci / lint (pull_request) Successful in 11m10s
ci / build (pull_request) Successful in 18m13s
ci / image (pull_request) Successful in 5m20s
Every console page that shows monitor status (monitors, incidents,
monitor details, evidence) went through one loader that read, for all of
the organization's monitors:

- the newest result per monitor and region, by scanning a day of raw
  results;
- the bars of the selected range, from raw results for ranges up to 24h,
  though only one page of monitors is shown;
- when each monitor first reported, scanning two days of results.

With 3000 monitors that took about a second, growing with the number of
results. Now:

- latest_results keeps the newest result per monitor and region,
  updated as results are stored (migration 00055 fills it from the last
  day);
- bars are loaded only for the monitors a page shows;
- first data is loaded per monitor on its page, and the monitor list asks
  only for the organization's earliest data, by index;
- monitor, region and incident queries name the organization, so their
  indexes are used instead of row security filtering whole tables.

Public status pages also read only their own monitors' latest results
and hourly buckets instead of the whole organization's.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_017GpWAskjmYtZpuQ5JwYTX3
2026-11-26 08:00:38 +01:00
Sebastian UnterschützandClaude Opus 5.5 2a440b9c5e perf(console): keep the status page editor light with many monitors
The editor rendered a group select and label field for every monitor of
the organization, about 2 MB of HTML for 3000 monitors. Only monitors on
the page carry their fields now; others get them from a template when
ticked. A filter field narrows long lists, and "Add all" ticks only the
monitors it leaves visible.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_017GpWAskjmYtZpuQ5JwYTX3
2026-11-26 08:00:38 +01:00
Sebi b88ed4bfd2 Merge pull request 'test(checker): check the runner's error in the recovery test' (#159) from fix/lint-recovery-test into main
ci / image (push) Successful in 3m33s
ci / build (push) Successful in 11m12s
release / release (push) Successful in 30m28s
ci / lint (push) Successful in 6m32s
ci / test (push) Successful in 15m19s
2026-11-25 23:27:42 +00:00
Sebastian UnterschützandClaude Opus 5.5 1dcb1531d0 test(checker): check the runner's error in the recovery test
ci / build (pull_request) Successful in 18m3s
ci / image (pull_request) Successful in 5m18s
ci / build (push) Skipped
ci / image (push) Skipped
ci / lint (push) Skipped
ci / test (push) Skipped
ci / test (pull_request) Successful in 9m12s
ci / lint (pull_request) Successful in 11m24s
golangci-lint's errcheck failed the v0.7.1 build on the unchecked result
of the runner in TestRecoveryIsLogged.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_017GpWAskjmYtZpuQ5JwYTX3
2026-11-26 00:27:14 +01:00
Sebi 87918eff80 Merge pull request 'fix: smoother rollouts for checkers, and say when they recover' (#158) from fix/checker-recovery-and-rollouts into main
ci / lint (push) Failing after 11m16s
release / release (push) Canceled after 18m19s
ci / build (push) Skipped
ci / image (push) Skipped
ci / test (push) Successful in 9m45s
2026-11-25 23:02:01 +00:00
Sebastian UnterschützandClaude Opus 5.5 963c677e1c fix: roll the API out without cutting off checkers
ci / lint (push) Skipped
ci / image (push) Skipped
ci / test (push) Skipped
ci / test (pull_request) Canceled after 4m25s
ci / build (push) Skipped
ci / lint (pull_request) Canceled after 4m26s
ci / build (pull_request) Canceled after 0s
ci / image (pull_request) Canceled after 0s
Checkers long-poll the API for up to 25 seconds, longer than a shutdown
waits for requests, so a rollout cut their polls off (GOAWAY, timeouts).
A draining API now ends long polls within about a second, empty, and the
checker's next poll reaches another instance.

The chart rolls the API and status page servers one pod at a time with
maxUnavailable 0, and a new pod serves for 5 seconds before an old one
goes, so the ingress has picked it up.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_017GpWAskjmYtZpuQ5JwYTX3
2026-11-26 00:00:11 +01:00
Sebastian UnterschützandClaude Opus 5.5 a6bc50b39d fix(checker): log when the API works again after failures
A checker logged only failures, so after an outage of the API, as during a
rollout, its log ended on an error and read as stuck although it had
recovered. Polling and reporting now log once when they work again, with
how long they failed and how many results the backlog delivered. A long
poll answered empty at once is not repeated at once either.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_017GpWAskjmYtZpuQ5JwYTX3
2026-11-26 00:00:11 +01:00
Sebi 15aad53d3d Merge pull request 'feat(console): status filter, own monitor order, page limits and smaller fixes' (#157) from feat/dashboard-status-filter into main
ci / build (push) Successful in 12m14s
release / release (push) Successful in 33m52s
ci / lint (push) Successful in 9m20s
ci / test (push) Successful in 13m33s
ci / image (push) Successful in 4m14s
2026-11-25 22:43:00 +00:00
Sebastian UnterschützandClaude Opus 5.5 b0d4bcc002 feat(console): sort the monitor list and put monitors in an order of one's own
ci / build (push) Skipped
ci / lint (push) Skipped
ci / image (push) Skipped
ci / test (push) Skipped
ci / lint (pull_request) Successful in 10m49s
ci / test (pull_request) Successful in 14m39s
ci / build (pull_request) Canceled after 14m22s
ci / image (pull_request) Canceled after 0s
The monitor list gets a sort switcher: the organization's own order, by
default, or by name, status (problems first), uptime (worst first) or
latency (slowest first). The choice is remembered in a cookie; paging
follows it.

"Arrange monitors" shows the whole tree with each group's monitors to
drag, or move with up and down, into the order wanted; every change is
saved at once through PUT /api/v1/org/monitors/order, which needs write
access to every monitor given and is audited. Monitors without a position
follow the positioned ones, by name.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_017GpWAskjmYtZpuQ5JwYTX3
2026-11-25 23:35:02 +01:00
Sebastian UnterschützandClaude Opus 5.5 ca852c8299 feat(limits): limit the monitors shown on one status page
Platform admins set a default for how many monitors a status page may
show, and an override per organization, like the other limits. Saving a
page with more gives 422 page_monitor_limit; a page beyond a lowered
limit keeps its monitors but cannot grow. The page editor names the
limit and the organization's usage lists it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_017GpWAskjmYtZpuQ5JwYTX3
2026-11-25 23:21:26 +01:00
Sebastian UnterschützandClaude Opus 5.5 4cde0f7e56 feat(console): add or remove all monitors of a status page, skip signup when signed in
The status page editor gets "Add all" and "Remove all" above its monitor
list. Opening the signup page while signed in leads to the monitor list,
as the login page already did.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_017GpWAskjmYtZpuQ5JwYTX3
2026-11-25 23:19:27 +01:00
Sebastian UnterschützandClaude Opus 5.5 feaa1e930d feat(console): filter the monitor list by status
The status counts above the monitor list are now links: one shows only
the monitors of that status as a flat list, the active one shows all
again. The filter combines with the search and the range and is kept by
the search form and the pager; an unknown status shows everything.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_017GpWAskjmYtZpuQ5JwYTX3
2026-11-25 23:18:09 +01:00
Sebi ebfada4b2c Merge pull request 'feat: custom domains by a unique CNAME, limited certificate orders' (#156) from feat/custom-domain-abuse into main
release / release (push) Successful in 37m35s
ci / lint (push) Successful in 11m20s
ci / build (push) Successful in 19m33s
ci / image (push) Canceled after 4m51s
ci / test (push) Successful in 15m26s
2026-11-25 22:02:50 +00:00
Sebastian UnterschützandClaude Opus 5.5 5934bd74e8 feat: verify custom domains by a CNAME unique to the page
ci / test (push) Skipped
ci / test (pull_request) Successful in 12m52s
ci / lint (push) Skipped
ci / lint (pull_request) Successful in 7m28s
ci / build (push) Skipped
ci / image (push) Skipped
ci / build (pull_request) Successful in 11m21s
ci / image (pull_request) Successful in 4m38s
A custom domain now needs a single record: a CNAME to
<label>.<status page host>, where the label is derived from the page's
domain token. The wildcard record of the status page host routes it, and
since the target belongs to one page alone it also proves who set it up;
a CNAME to the shared host would not, as any organization could then
claim a domain pointing at the platform. The TXT record stays for domains
whose CNAME cannot be seen, behind a proxy or without a subdomain.

- The domain watch looks for the records of a new domain every minute for
  a quarter of an hour, then every ten minutes for two days, and verifies
  it on its own; "Check now" still works.
- Verified domains are checked daily. When the record is gone the owners
  are told, and a week later the domain is switched off, so a record left
  behind cannot be taken over. Domains verified before keep working
  without checks.
- The editor shows the CNAME record first, the TXT way for proxies and
  apex domains, how the domain was verified and when a missing record will
  switch it off. The API returns cname_record and domain_missing_since.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_017GpWAskjmYtZpuQ5JwYTX3
2026-11-25 22:58:54 +01:00
Sebastian UnterschützandClaude Opus 5.5 66537f4e65 fix: keep Redis timeouts below a second exact
A checker's long poll ends with BLPOP waiting the rest of it, often below
a second, which go-redis rounded up to one second with a warning in the
log; the poll then ran up to a second too long. Such waits now pass BLPOP
a fraction of a second, which Redis takes since 6.0. A session's sliding
expiry, which can be below a second near its absolute end, uses PEXPIRE.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_017GpWAskjmYtZpuQ5JwYTX3
2026-11-25 22:58:54 +01:00
Sebastian UnterschützandClaude Opus 5.5 db36d918fe feat: guard certificate orders for custom domains and explain the setup
ci / lint (push) Skipped
ci / test (push) Skipped
ci / build (push) Skipped
ci / image (push) Skipped
ci / test (pull_request) Successful in 8m21s
ci / lint (pull_request) Successful in 11m0s
ci / build (pull_request) Canceled after 8m49s
ci / image (pull_request) Canceled after 0s
Status page servers order certificates on demand. Verified domains were
already the only ones they would order for, but nothing bounded how many:
an organization switching domains, or many organizations at once, could use
up the CA's rate limits that all servers sharing an ACME account depend on,
and every handshake or request for a made-up name was passed on to the API.

- Before a new order (not a renewal) the server asks the API
  (POST /agent/v1/certificates). It allows verified domains of pages that
  server serves, within limits per domain and day, per organization and
  day, and per ACME account owner and hour (UPTIME_CERTS_*), counted
  across all instances.
- An organization can set a new custom domain at most 10 times a day.
- The server remembers names without a page for a minute and passes at
  most 20 unknown names a second on to the API; pages the sync cached are
  not affected. Only real pages are recorded as visited.
- The page editor explains the three steps: the TXT record, the CNAME
  record with the platform's status page host as its target (or the
  organization's own servers), apex domains, and when HTTPS follows.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_017GpWAskjmYtZpuQ5JwYTX3
2026-11-25 22:39:01 +01:00
Sebi 7509b8c429 Merge pull request 'fix(release): publish the Helm chart only once the images exist' (#155) from fix/release-wait-for-images into main
ci / test (push) Successful in 15m18s
ci / lint (push) Successful in 6m41s
ci / build (push) Successful in 19m56s
ci / image (push) Successful in 5m40s
2026-11-25 19:08:31 +00:00
Sebastian UnterschützandClaude Opus 5.5 8cc5c0266a fix(release): publish the Helm chart only once the images exist
ci / test (pull_request) Successful in 9m11s
ci / lint (push) Skipped
ci / test (push) Skipped
ci / build (push) Skipped
ci / image (push) Skipped
ci / build (pull_request) Canceled after 0s
ci / lint (pull_request) Successful in 12m40s
ci / image (pull_request) Canceled after 0s
The release job finished about 20 minutes before the ci workflow had
pushed the tag's images. Clusters following the chart repository then
rolled out a release whose image did not exist yet: the migrate hook
sat in ImagePullBackOff until its deadline and the upgrade failed
(0.2.1, 0.3.0 and 0.4.0 on app.uptimesebi.net).

Wait up to 90 minutes for the API, checker and status page images of
the tag before publishing the chart.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-25 19:59:29 +01:00
Sebi 87ab065e24 Merge pull request 'feat(helm): redirect plain HTTP to HTTPS on the ingresses' (#154) from feat/helm-https-redirect into main
ci / test (push) Successful in 16m57s
release / release (push) Successful in 16m55s
ci / lint (push) Successful in 8m9s
ci / build (push) Successful in 16m27s
ci / image (push) Successful in 5m2s
2026-11-25 18:52:46 +00:00
Sebastian UnterschützandClaude Opus 5.5 25829671a5 feat(helm): redirect plain HTTP to HTTPS on the ingresses
ci / lint (push) Skipped
ci / test (push) Skipped
ci / build (push) Skipped
ci / image (push) Skipped
ci / test (pull_request) Successful in 12m11s
ci / lint (pull_request) Successful in 11m42s
ci / build (pull_request) Successful in 16m4s
ci / image (pull_request) Successful in 3m19s
With TLS on, the console's and the status pages' ingresses now send HTTP to
HTTPS: through a redirectScheme middleware the chart creates for Traefik,
which is chained before any middlewares already annotated, and by
annotation for ingress-nginx and HAProxy. ingress.tls.redirect and
statuspage.ingress.tls.redirect turn it off.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_017GpWAskjmYtZpuQ5JwYTX3
2026-11-25 19:43:37 +01:00
Sebi 673e93f4bb Merge pull request 'fix(evaluate): a region without results no longer keeps a monitor up' (#153) from fix/silent-region-no-block into main
release / release (push) Successful in 16m37s
ci / image (push) Successful in 3m36s
ci / test (push) Successful in 14m47s
ci / build (push) Successful in 16m50s
ci / lint (push) Successful in 10m4s
2026-11-24 22:43:33 +00:00
Sebastian UnterschützandClaude Opus 5.5 2054660625 fix(evaluate): a region without results no longer keeps a monitor up
ci / image (pull_request) Successful in 3m16s
ci / test (pull_request) Successful in 9m3s
ci / lint (pull_request) Successful in 10m9s
ci / build (pull_request) Successful in 9m54s
ci / lint (push) Skipped
ci / build (push) Skipped
ci / test (push) Skipped
ci / image (push) Skipped
A monitor went down only when every assigned region had failed and
reported recently, so one region whose checkers were gone kept a monitor
up for good, even while all other regions reported its target failing.
Regions without recent results are now left out: a monitor goes down
when every region that reported recently has failed. One region failing
while another succeeds still does not alert, and with every region
silent nothing is judged.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_017GpWAskjmYtZpuQ5JwYTX3
2026-11-24 23:43:02 +01:00
Sebi 4d03a86614 Merge pull request 'feat: show unchecked monitors and tell about regions without checkers' (#152) from feat/unchecked-monitors into main
ci / lint (push) Canceled after 6m57s
ci / test (push) Canceled after 6m57s
ci / build (push) Canceled after 0s
ci / image (push) Canceled after 0s
2026-11-24 22:36:18 +00:00
Sebastian UnterschützandClaude Opus 5.5 dc2e21f964 feat: show unchecked monitors and tell about regions without checkers
ci / build (pull_request) Successful in 19m34s
ci / image (pull_request) Successful in 3m15s
ci / test (push) Skipped
ci / build (push) Skipped
ci / image (push) Skipped
ci / lint (push) Skipped
ci / lint (pull_request) Successful in 6m17s
ci / test (pull_request) Successful in 12m7s
A region whose checkers had all gone left its monitors looking up: the
console and status pages took the last result, however old, and nobody
was told.

- A region's last result counts only while it is younger than the
  evaluator's staleness (3 intervals, at least 2 minutes); older ones
  show as "no data since …" in the console and leave status page
  components unknown instead of operational.
- A monitor no region has reported for recently is marked "not being
  checked", counted on the dashboard with an explanation, and noted on
  its page.
- A region watch on every API replica emails the platform's admins
  (platform regions) or the organization's owners (own regions) once a
  region with checkers and enabled monitors has had no live checker for
  UPTIME_REGION_ALERT_AFTER (default 5m), and again when one is back.
  The dashboard names such regions at once.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_017GpWAskjmYtZpuQ5JwYTX3
2026-11-24 23:35:43 +01:00
Sebi f3d0a4c844 Merge pull request 'feat: status pages served by the right servers, cached before their first visit' (#151) from feat/own-statuspage-servers into main
ci / image (push) Successful in 3m53s
release / release (push) Successful in 11m16s
ci / build (push) Successful in 16m30s
ci / test (push) Successful in 12m0s
ci / lint (push) Successful in 10m11s
2026-11-24 22:08:02 +00:00
Sebastian UnterschützandClaude Opus 5.5 fcf615dce7 feat(statuspage): refresh pages by checksum
ci / lint (push) Skipped
ci / build (push) Skipped
ci / image (push) Skipped
ci / lint (pull_request) Successful in 6m46s
ci / test (push) Skipped
ci / image (pull_request) Successful in 3m24s
ci / test (pull_request) Successful in 14m46s
ci / build (pull_request) Successful in 18m49s
Each refresh sent the whole page again even when nothing had changed.
Status page servers now send the checksum of their copy (If-None-Match)
and the API answers 304 when the page, leaving out when it was
generated, is unchanged; the server then only marks its copy current.
The checksum is kept on disk with the page, so it survives restarts.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_017GpWAskjmYtZpuQ5JwYTX3
2026-11-24 22:57:22 +01:00
Sebastian UnterschützandClaude Opus 5.5 4e9a198b2f feat(statuspage): fetch every served page every five minutes
ci / lint (push) Skipped
ci / test (push) Skipped
ci / build (push) Skipped
ci / image (push) Skipped
ci / test (pull_request) Canceled after 5m23s
ci / lint (pull_request) Canceled after 5m23s
ci / build (pull_request) Canceled after 0s
ci / image (pull_request) Canceled after 0s
A status page server only knew the pages visitors had asked it for, so
during an API outage a server that had never seen a page could not
serve it. The agent API now lists the pages a server serves
(GET /agent/v1/pages/index), following the same rule as single pages,
and status page servers fetch all of them on start and every five
minutes, also dropping those no longer listed. Pages visited within the
last ten minutes are still refreshed every 30 seconds; the outdated
notice now appears after ten minutes, twice the sync interval.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_017GpWAskjmYtZpuQ5JwYTX3
2026-11-24 22:51:46 +01:00
Sebastian UnterschützandClaude Opus 5.5 c0239e15bb feat(api): organizations with own status page servers serve their pages alone
ci / lint (push) Skipped
ci / test (push) Skipped
ci / build (push) Skipped
ci / lint (pull_request) Canceled after 6m3s
ci / test (pull_request) Canceled after 6m2s
ci / build (pull_request) Canceled after 0s
ci / image (pull_request) Canceled after 0s
ci / image (push) Skipped
The platform's status page servers handed out every published page,
including those of organizations running their own servers. Once one of
an organization's own status page servers has connected, the agent API
now answers the platform's servers 404 for its pages, so they drop them
from their cache, and only the organization's servers serve them. A
created but never connected token changes nothing, so moving over does
not take the pages offline.

The console no longer links such pages to the platform's address,
which would not serve them; the editor says who does.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_017GpWAskjmYtZpuQ5JwYTX3
2026-11-24 22:45:37 +01:00
Sebi 20874a5a87 Merge pull request 'fix(web): space between the documents in the consent text' (#150) from fix/consent-spacing into main
ci / image (push) Successful in 4m59s
release / release (push) Successful in 16m24s
ci / build (push) Successful in 16m42s
ci / lint (push) Successful in 6m58s
ci / test (push) Successful in 14m16s
2026-11-24 21:31:31 +00:00
Sebastian UnterschützandClaude Opus 5.5 135209fe79 fix(web): space between the documents in the consent text
ci / lint (push) Skipped
ci / test (push) Skipped
ci / build (push) Skipped
ci / image (push) Skipped
ci / lint (pull_request) Successful in 10m59s
ci / test (pull_request) Successful in 12m30s
ci / image (pull_request) Successful in 5m54s
ci / build (pull_request) Successful in 18m22s
The sign-up and consent pages ran the first document's link into the
word joining it to the next, as in "Datenschutzerklärungund die AGB".

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_017GpWAskjmYtZpuQ5JwYTX3
2026-11-24 22:29:37 +01:00
Sebi acd8c2252d Merge pull request 'fix(api): platform check type switch binds the platform's checkers only' (#149) from fix/check-types-own-checkers into main
release / release (push) Successful in 16m31s
ci / build (push) Successful in 16m29s
ci / image (push) Successful in 5m2s
ci / lint (push) Successful in 6m58s
ci / test (push) Successful in 13m59s
2026-11-24 20:48:44 +00:00
Sebastian UnterschützandClaude Opus 5.5 bd887523de fix(api): platform check type switch binds the platform's checkers only
ci / lint (push) Skipped
ci / build (push) Skipped
ci / image (push) Skipped
ci / test (push) Skipped
ci / lint (pull_request) Successful in 11m25s
ci / test (pull_request) Successful in 12m34s
ci / image (pull_request) Successful in 5m22s
ci / build (pull_request) Successful in 18m7s
Switching a check type off in the admin area removed it for every
organization, own checkers included, and hid it from the organization's
own choice. The platform switch now only keeps such monitors off the
platform's regions: organizations with regions of their own still create
them there (422 check_type_own_checkers_only on a platform region), and
the editor marks them "own checkers only". Passive types, which no
checker runs, stay switched off entirely.

The organization's check types are chosen independently of the
platform's: its settings list every type, and the platform switch no
longer rewrites that choice.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_017GpWAskjmYtZpuQ5JwYTX3
2026-11-24 21:46:07 +01:00
Sebi 12e6de77aa Merge pull request 'feat: support tickets between accounts and platform admins' (#148) from feat/support-tickets into main
ci / lint (push) Successful in 10m3s
ci / test (push) Successful in 13m50s
ci / build (push) Successful in 16m48s
ci / image (push) Successful in 4m2s
2026-11-24 17:04:36 +00:00
Sebastian UnterschützandClaude Opus 5.5 f3d402705e feat: support tickets between accounts and platform admins
ci / build (push) Skipped
ci / lint (push) Skipped
ci / test (push) Skipped
ci / image (push) Skipped
ci / lint (pull_request) Successful in 7m0s
ci / test (pull_request) Successful in 12m1s
ci / build (pull_request) Successful in 18m14s
ci / image (pull_request) Successful in 5m9s
Accounts open tickets under Support and admins answer them under Admin →
Support tickets.

- A ticket is open while it waits for the admins and answered while it
  waits for the account. Either side can close or reopen it, and a reply
  reopens it.
- The admins are mailed about new tickets and replies, and the account
  about answers.
- A ticket can name the active organization and point at a monitor,
  notification channel, alert group, status page or incident in it.
  Each must be something the account can read.
- Next to the conversation, admins see the account at a glance: state,
  sign-in, organizations with their limits and usage, and open tickets.
- Admins switch support off and limit how many tickets an account has
  open at once.
- Suspended accounts and those yet to accept the terms reach support too;
  a suspended account opens one ticket.
- Tickets are part of the account export and are deleted with the
  account.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_017GpWAskjmYtZpuQ5JwYTX3
2026-11-24 18:01:50 +01:00
Sebi 9fc3c6b050 Merge pull request 'feat(web): fit the console and status pages to phones and tablets' (#147) from feat/responsive into main
ci / build (push) Canceled after 17m4s
ci / image (push) Canceled after 0s
ci / lint (push) Successful in 6m29s
ci / test (push) Successful in 11m57s
2026-11-24 16:35:25 +00:00
Sebastian UnterschützandClaude Opus 5.5 670dde40b6 feat(web): fit the console and status pages to phones and tablets
ci / lint (push) Skipped
ci / test (push) Skipped
ci / build (push) Skipped
ci / image (push) Skipped
ci / lint (pull_request) Successful in 6m4s
ci / test (pull_request) Successful in 11m52s
ci / build (pull_request) Successful in 17m48s
ci / image (pull_request) Successful in 5m28s
- The console header folds its navigation into a menu below 1024px.
- Pages use narrower gutters on phones.
- Monitor rows keep name and uptime in place on narrow screens.
- Toolbars and the range switch wrap.
- Tables scroll sideways instead of squeezing their columns.
- Form fields keep 16px text on touch screens so iOS does not zoom in.
- The status page footer wraps.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_017GpWAskjmYtZpuQ5JwYTX3
2026-11-24 17:09:50 +01:00
116 changed files with 14769 additions and 4750 deletions

No files matched your search

+14
View File
@@ -44,6 +44,20 @@ UPTIME_TEST_REDIS_URL=redis://localhost:6379/15
# Reverse proxies allowed to set X-Forwarded-For (comma-separated IPs/CIDRs). # Reverse proxies allowed to set X-Forwarded-For (comma-separated IPs/CIDRs).
# UPTIME_TRUSTED_PROXIES=10.0.0.0/8 # UPTIME_TRUSTED_PROXIES=10.0.0.0/8
# How long a region with monitors may have no live checker before the
# platform's admins (platform regions) or the organization's owners (own
# regions) get an email; 0 switches it off.
# UPTIME_REGION_ALERT_AFTER=5m
# Status page servers ask before ordering a certificate for a custom domain.
# New orders (not renewals) are limited per organization and day, per hour
# for all servers sharing an ACME account (the platform's, or one
# organization's), and per domain and day. Let's Encrypt allows 300 new
# orders per account in 3 hours.
# UPTIME_CERTS_PER_ORG_PER_DAY=20
# UPTIME_CERTS_PER_HOUR=30
# UPTIME_CERTS_PER_NAME_PER_DAY=5
# Data retention (0 keeps forever). Raw results feed charts up to 24h, the # Data retention (0 keeps forever). Raw results feed charts up to 24h, the
# hourly aggregate 7d and 30d, the daily aggregate up to a year; resolved # hourly aggregate 7d and 30d, the daily aggregate up to a year; resolved
# incidents follow the daily aggregate. # incidents follow the daily aggregate.
+35
View File
@@ -83,6 +83,41 @@ jobs:
curl -fsS -o /dev/null -X POST -H "Authorization: token $TOKEN" \ curl -fsS -o /dev/null -X POST -H "Authorization: token $TOKEN" \
-F "attachment=@$f" "$api/releases/$id/assets?name=$(basename "$f")" -F "attachment=@$f" "$api/releases/$id/assets?name=$(basename "$f")"
done done
# The ci workflow builds the images of this tag after lint and tests,
# which takes longer than this job. A chart published before them makes
# clusters that follow the chart repository roll out a release whose
# images do not exist yet (ImagePullBackOff in the migrate hook).
- name: Wait for the images
env:
PACKAGE_TOKEN: ${{ secrets.PACKAGE_TOKEN }}
run: |
set -eu
if [ -z "$PACKAGE_TOKEN" ]; then
echo "::warning::PACKAGE_TOKEN is not set; not waiting for the images."
exit 0
fi
host="${GITHUB_SERVER_URL#*://}"
owner="$(printf '%s' "${GITHUB_REPOSITORY%/*}" | tr 'A-Z' 'a-z')"
tag="${GITHUB_REF_NAME#v}"
accept="application/vnd.oci.image.index.v1+json,application/vnd.oci.image.manifest.v1+json,application/vnd.docker.distribution.manifest.list.v2+json,application/vnd.docker.distribution.manifest.v2+json"
deadline=$(( $(date +%s) + 90 * 60 ))
for repo in uptimesebi uptimesebi-checker uptimesebi-statuspage; do
until
token="$(curl -fsS --user "$GITHUB_ACTOR:$PACKAGE_TOKEN" \
"$GITHUB_SERVER_URL/v2/token?service=container_registry&scope=repository:$owner/$repo:pull" \
| sed -n 's/.*"token":"\([^"]*\)".*/\1/p')"
curl -fsS -o /dev/null -I -H "Authorization: Bearer $token" -H "Accept: $accept" \
"$GITHUB_SERVER_URL/v2/$owner/$repo/manifests/$tag"
do
if [ "$(date +%s)" -ge "$deadline" ]; then
echo "::error::$host/$owner/$repo:$tag did not appear within 90 minutes; the chart is not published."
exit 1
fi
echo "waiting for $host/$owner/$repo:$tag"
sleep 30
done
echo "$host/$owner/$repo:$tag is there"
done
# helm repo add uptimesebi <server>/api/packages/<owner>/helm # helm repo add uptimesebi <server>/api/packages/<owner>/helm
- name: Publish Helm chart - name: Publish Helm chart
env: env:
+2 -2
View File
@@ -4,7 +4,7 @@
[![ci](https://git.zb-server.de/ZB-Server/uptimesebi/actions/workflows/ci.yaml/badge.svg?branch=main)](https://git.zb-server.de/ZB-Server/uptimesebi/actions?workflow=ci.yaml) · License: AGPL-3.0-only [![ci](https://git.zb-server.de/ZB-Server/uptimesebi/actions/workflows/ci.yaml/badge.svg?branch=main)](https://git.zb-server.de/ZB-Server/uptimesebi/actions?workflow=ci.yaml) · License: AGPL-3.0-only
UptimeSebi monitors websites, APIs and services from several regions and tells you when they are down, without false alarms from a single checker losing its network: a monitor only counts as down when **every** region it is checked from fails. It publishes status pages that stay online even while UptimeSebi itself is not, and it can run entirely on your own infrastructure. UptimeSebi monitors websites, APIs and services from several regions and tells you when they are down, without false alarms from a single checker losing its network: a monitor only counts as down when **every** region it is checked from fails. A region whose checkers are gone is left out rather than holding the monitor up, and its admins are told. It publishes status pages that stay online even while UptimeSebi itself is not, and it can run entirely on your own infrastructure.
It is built for teams and hosting providers: organizations with members, roles and SSO, run either as a shared cloud service or self-hosted. It is built for teams and hosting providers: organizations with members, roles and SSO, run either as a shared cloud service or self-hosted.
@@ -159,7 +159,7 @@ Run as many API, checker and status page instances as you need; they share no lo
| Hybrid | hosted | at the customer | at the customer | | Hybrid | hosted | at the customer | at the customer |
| Self-hosted | at the customer | at the customer | at the customer | | Self-hosted | at the customer | at the customer | at the customer |
Checkers and status page servers reach the API over HTTPS and never the database, so they can run in other networks. Checkers and status page servers reach the API over HTTPS and never the database, so they can run in other networks. Status page servers fetch every page they serve every five minutes, so each one is cached before its first visit and keeps being served while the API is unreachable. Once one of an organization's own status page servers has connected, only its own servers serve its pages; the platform's no longer do.
## Usage ## Usage
+3
View File
@@ -89,9 +89,12 @@ func run(log *slog.Logger, level *slog.LevelVar, args []string) error {
health.Register(r) health.Register(r)
r.StaticFS("/static", web.Static()) r.StaticFS("/static", web.Static())
srv.Mount(r) srv.Mount(r)
srv.EndLongPollsOn(health.Draining())
go srv.RunScheduler(ctx) go srv.RunScheduler(ctx)
go srv.RunNotifier(ctx) go srv.RunNotifier(ctx)
go srv.RunHousekeeping(ctx) go srv.RunHousekeeping(ctx)
go srv.RunRegionWatch(ctx)
go srv.RunDomainWatch(ctx)
go srv.RunHeartbeats(ctx) go srv.RunHeartbeats(ctx)
return platform.Serve(ctx, log, platform.NewHTTPServer(cfg.Listen, r), health, 5*time.Second, cfg.ShutdownTimeout) return platform.Serve(ctx, log, platform.NewHTTPServer(cfg.Listen, r), health, 5*time.Second, cfg.ShutdownTimeout)
+1
View File
@@ -119,6 +119,7 @@ func certificates(ctx context.Context, cfg config.StatusPage, client *agentapi.C
magic = certmagic.New(cache, certmagic.Config{ magic = certmagic.New(cache, certmagic.Config{
Storage: statuspage.NewCertStorage(client, certDir), Storage: statuspage.NewCertStorage(client, certDir),
OnDemand: &certmagic.OnDemandConfig{DecisionFunc: pages.AllowCertificate}, OnDemand: &certmagic.OnDemandConfig{DecisionFunc: pages.AllowCertificate},
OnEvent: pages.OnCertEvent,
Logger: zap.NewNop(), Logger: zap.NewNop(),
}) })
issuer := certmagic.NewACMEIssuer(magic, certmagic.ACMEIssuer{CA: cfg.ACMECA, Email: cfg.ACMEEmail, Agreed: true}) issuer := certmagic.NewACMEIssuer(magic, certmagic.ACMEIssuer{CA: cfg.ACMECA, Email: cfg.ACMEEmail, Agreed: true})
@@ -170,3 +170,53 @@ $secret being the chart secret to read values from.
medium: Memory medium: Memory
sizeLimit: 64Mi sizeLimit: 64Mi
{{- end -}} {{- end -}}
{{/*
HTTPS redirect of an ingress: include with (dict "root" . "ingress" <values>
"name" <ingress name>). Traefik needs a redirectScheme middleware, other
controllers an annotation. */}}
{{- define "uptimesebi.redirects" -}}
{{- $i := .ingress -}}
{{- if and $i.tls.enabled $i.tls.redirect }}true{{ end -}}
{{- end -}}
{{- define "uptimesebi.traefik" -}}
{{- $i := .ingress -}}
{{- if contains "traefik" ($i.className | default "") -}}true
{{- else if and (not $i.className) (.root.Capabilities.APIVersions.Has "traefik.io/v1alpha1/Middleware") -}}true
{{- end -}}
{{- end -}}
{{/* the ingress's annotations, with those the redirect needs. */}}
{{- define "uptimesebi.ingressAnnotations" -}}
{{- $a := deepCopy (.ingress.annotations | default dict) -}}
{{- if include "uptimesebi.redirects" . -}}
{{- if include "uptimesebi.traefik" . -}}
{{- $key := "traefik.ingress.kubernetes.io/router.middlewares" -}}
{{- $mw := printf "%s-%s-https@kubernetescrd" .root.Release.Namespace .name -}}
{{- with get $a $key }}{{ $mw = printf "%s,%s" $mw . }}{{ end -}}
{{- $_ := set $a $key $mw -}}
{{- else -}}
{{- $_ := set $a "nginx.ingress.kubernetes.io/ssl-redirect" "true" -}}
{{- $_ := set $a "haproxy.org/ssl-redirect" "true" -}}
{{- end -}}
{{- end -}}
{{- with $a }}{{ toYaml . }}{{ end -}}
{{- end -}}
{{/* the Traefik middleware the redirect uses, if it needs one. */}}
{{- define "uptimesebi.redirectMiddleware" -}}
{{- if and (include "uptimesebi.redirects" .) (include "uptimesebi.traefik" .) }}
---
apiVersion: traefik.io/v1alpha1
kind: Middleware
metadata:
name: {{ .name }}-https
labels:
{{- include "uptimesebi.labels" .root | nindent 4 }}
spec:
redirectScheme:
scheme: https
permanent: true
{{- end }}
{{- end -}}
@@ -8,6 +8,15 @@ metadata:
app.kubernetes.io/component: api app.kubernetes.io/component: api
spec: spec:
replicas: {{ .Values.api.replicas }} replicas: {{ .Values.api.replicas }}
# Roll one pod at a time without ever having fewer ready than wanted;
# a new pod serves a few seconds before an old one goes, so the ingress
# has picked it up.
strategy:
type: RollingUpdate
rollingUpdate:
maxUnavailable: 0
maxSurge: 1
minReadySeconds: 5
selector: selector:
matchLabels: matchLabels:
{{- include "uptimesebi.selector" (list . "api") | nindent 6 }} {{- include "uptimesebi.selector" (list . "api") | nindent 6 }}
@@ -1,13 +1,14 @@
{{- if .Values.ingress.enabled }} {{- if .Values.ingress.enabled }}
{{- $ing := dict "root" . "ingress" .Values.ingress "name" (include "uptimesebi.fullname" .) }}
apiVersion: networking.k8s.io/v1 apiVersion: networking.k8s.io/v1
kind: Ingress kind: Ingress
metadata: metadata:
name: {{ include "uptimesebi.fullname" . }} name: {{ include "uptimesebi.fullname" . }}
labels: labels:
{{- include "uptimesebi.labels" . | nindent 4 }} {{- include "uptimesebi.labels" . | nindent 4 }}
{{- with .Values.ingress.annotations }} {{- with include "uptimesebi.ingressAnnotations" $ing }}
annotations: annotations:
{{- toYaml . | nindent 4 }} {{- . | nindent 4 }}
{{- end }} {{- end }}
spec: spec:
{{- with .Values.ingress.className }} {{- with .Values.ingress.className }}
@@ -29,4 +30,5 @@ spec:
name: {{ include "uptimesebi.fullname" . }}-api name: {{ include "uptimesebi.fullname" . }}-api
port: port:
name: http name: http
{{- include "uptimesebi.redirectMiddleware" $ing }}
{{- end }} {{- end }}
@@ -9,6 +9,15 @@ metadata:
app.kubernetes.io/component: statuspage app.kubernetes.io/component: statuspage
spec: spec:
replicas: {{ .Values.statuspage.replicas }} replicas: {{ .Values.statuspage.replicas }}
# Roll one pod at a time without ever having fewer ready than wanted;
# a new pod serves a few seconds before an old one goes, so the ingress
# has picked it up.
strategy:
type: RollingUpdate
rollingUpdate:
maxUnavailable: 0
maxSurge: 1
minReadySeconds: 5
selector: selector:
matchLabels: matchLabels:
{{- include "uptimesebi.selector" (list . "statuspage") | nindent 6 }} {{- include "uptimesebi.selector" (list . "statuspage") | nindent 6 }}
@@ -118,6 +127,7 @@ spec:
{{- include "uptimesebi.selector" (list . "statuspage") | nindent 6 }} {{- include "uptimesebi.selector" (list . "statuspage") | nindent 6 }}
{{- end }} {{- end }}
{{- if .Values.statuspage.ingress.enabled }} {{- if .Values.statuspage.ingress.enabled }}
{{- $ing := dict "root" . "ingress" .Values.statuspage.ingress "name" $name }}
--- ---
apiVersion: networking.k8s.io/v1 apiVersion: networking.k8s.io/v1
kind: Ingress kind: Ingress
@@ -125,9 +135,9 @@ metadata:
name: {{ $name }} name: {{ $name }}
labels: labels:
{{- include "uptimesebi.labels" . | nindent 4 }} {{- include "uptimesebi.labels" . | nindent 4 }}
{{- with .Values.statuspage.ingress.annotations }} {{- with include "uptimesebi.ingressAnnotations" $ing }}
annotations: annotations:
{{- toYaml . | nindent 4 }} {{- . | nindent 4 }}
{{- end }} {{- end }}
spec: spec:
{{- with .Values.statuspage.ingress.className }} {{- with .Values.statuspage.ingress.className }}
@@ -152,5 +162,6 @@ spec:
port: port:
name: http name: http
{{- end }} {{- end }}
{{- include "uptimesebi.redirectMiddleware" $ing }}
{{- end }} {{- end }}
{{- end }} {{- end }}
+5
View File
@@ -144,6 +144,9 @@ ingress:
enabled: false enabled: false
# Secret with the certificate, e.g. made by cert-manager. # Secret with the certificate, e.g. made by cert-manager.
secretName: "" secretName: ""
# Send plain HTTP to HTTPS: through a redirectScheme middleware with
# Traefik, by annotation with ingress-nginx and HAProxy.
redirect: true
# -- Checker -- # -- Checker --
# A checker in the cluster, for checks from the cluster's region. Create # A checker in the cluster, for checks from the cluster's region. Create
@@ -197,6 +200,8 @@ statuspage:
tls: tls:
enabled: false enabled: false
secretName: "" secretName: ""
# Send plain HTTP to HTTPS, as for the console.
redirect: true
resources: resources:
requests: requests:
cpu: 50m cpu: 50m
+12
View File
@@ -125,6 +125,11 @@ func (c *Client) WithHTTPClient(hc *http.Client) *Client {
func (c *Client) Instance() uuid.UUID { return c.instance } func (c *Client) Instance() uuid.UUID { return c.instance }
func (c *Client) do(ctx context.Context, method, path string, in, out any) error { func (c *Client) do(ctx context.Context, method, path string, in, out any) error {
return c.doWith(ctx, method, path, nil, in, out)
}
// doWith is do with extra request headers.
func (c *Client) doWith(ctx context.Context, method, path string, header http.Header, in, out any) error {
var body io.Reader var body io.Reader
if in != nil { if in != nil {
b, err := json.Marshal(in) b, err := json.Marshal(in)
@@ -142,6 +147,9 @@ func (c *Client) do(ctx context.Context, method, path string, in, out any) error
req.Header.Set(VersionHeader, fmt.Sprint(Version)) req.Header.Set(VersionHeader, fmt.Sprint(Version))
req.Header.Set(InstanceHeader, c.instance.String()) req.Header.Set(InstanceHeader, c.instance.String())
req.Header.Set(ReleaseHeader, c.release) req.Header.Set(ReleaseHeader, c.release)
for k, v := range header {
req.Header[k] = v
}
resp, err := c.hc.Do(req) resp, err := c.hc.Do(req)
if err != nil { if err != nil {
return err return err
@@ -152,6 +160,10 @@ func (c *Client) do(ctx context.Context, method, path string, in, out any) error
return ErrUnauthorized return ErrUnauthorized
case resp.StatusCode == http.StatusNotFound: case resp.StatusCode == http.StatusNotFound:
return ErrNotFound return ErrNotFound
case resp.StatusCode == http.StatusNotModified:
return ErrNotModified
case resp.StatusCode == http.StatusTooManyRequests:
return ErrRateLimited
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))
+42 -1
View File
@@ -2,6 +2,9 @@ package agentapi
import ( import (
"context" "context"
"crypto/sha256"
"encoding/hex"
"encoding/json"
"errors" "errors"
"net/http" "net/http"
"net/url" "net/url"
@@ -348,19 +351,57 @@ func (s PageSnapshot) LegalDocByKind(kind string) (LegalDoc, bool) {
return LegalDoc{}, false return LegalDoc{}, false
} }
// PageRef names a page a status page server serves: by Slug on its own
// hosts and, when Host is set, by that verified custom domain.
type PageRef struct {
Slug string `json:"slug"`
Host string `json:"host,omitempty"`
}
// Pages lists every page this status page server serves, so it can keep
// them all cached before anyone visits.
func (c *Client) Pages(ctx context.Context) ([]PageRef, error) {
var out struct {
Pages []PageRef `json:"pages"`
}
err := c.do(ctx, http.MethodGet, "/pages/index", nil, &out)
return out.Pages, err
}
// ErrNotFound means no published page matches. // ErrNotFound means no published page matches.
var ErrNotFound = errors.New("agentapi: not found") var ErrNotFound = errors.New("agentapi: not found")
// ErrNotModified means the page still matches the checksum sent.
var ErrNotModified = errors.New("agentapi: not modified")
// Checksum identifies the content of s, leaving out when it was generated.
func (s PageSnapshot) Checksum() string {
s.GeneratedAt = time.Time{}
raw, _ := json.Marshal(s)
sum := sha256.Sum256(raw)
return hex.EncodeToString(sum[:])
}
// Page fetches the published page for a custom domain host, or for slug if // Page fetches the published page for a custom domain host, or for slug if
// host is empty. // host is empty.
func (c *Client) Page(ctx context.Context, host, slug string) (PageSnapshot, error) { func (c *Client) Page(ctx context.Context, host, slug string) (PageSnapshot, error) {
return c.PageIfChanged(ctx, host, slug, "")
}
// PageIfChanged is Page, but answers ErrNotModified instead of sending the
// page again when it still has the checksum given.
func (c *Client) PageIfChanged(ctx context.Context, host, slug, checksum string) (PageSnapshot, error) {
q := url.Values{} q := url.Values{}
if host != "" { if host != "" {
q.Set("host", host) q.Set("host", host)
} else { } else {
q.Set("slug", slug) q.Set("slug", slug)
} }
var h http.Header
if checksum != "" {
h = http.Header{"If-None-Match": {`"` + checksum + `"`}}
}
var p PageSnapshot var p PageSnapshot
err := c.do(ctx, http.MethodGet, "/pages?"+q.Encode(), nil, &p) err := c.doWith(ctx, http.MethodGet, "/pages?"+q.Encode(), h, nil, &p)
return p, err return p, err
} }
+10
View File
@@ -106,3 +106,13 @@ func (c *Client) StorageUnlock(ctx context.Context, name string) error {
_, err := c.raw(ctx, http.MethodDelete, "/storage/lock"+keyQuery("name", name), nil) _, err := c.raw(ctx, http.MethodDelete, "/storage/lock"+keyQuery("name", name), nil)
return err return err
} }
// ErrRateLimited means the API refused because a limit was reached.
var ErrRateLimited = errors.New("agentapi: rate limited")
// AllowCertificate asks whether this server may order a new certificate
// for name. ErrNotFound means it serves no page there, ErrRateLimited that
// a limit on orders was reached.
func (c *Client) AllowCertificate(ctx context.Context, name string) error {
return c.do(ctx, http.MethodPost, "/certificates", map[string]string{"name": name}, nil)
}
+27 -5
View File
@@ -32,7 +32,9 @@ const (
ctxAgent = "api.agent" ctxAgent = "api.agent"
ctxInstance = "api.instance" ctxInstance = "api.instance"
maxJobWait = 25 * time.Second maxJobWait = 25 * time.Second
maxJobBatch = 200 // drainingPollHold is how long a draining instance still holds a poll.
drainingPollHold = time.Second
maxJobBatch = 200
) )
func (s *Server) mountAgentAPI(r gin.IRouter) { func (s *Server) mountAgentAPI(r gin.IRouter) {
@@ -41,6 +43,7 @@ func (s *Server) mountAgentAPI(r gin.IRouter) {
g.GET("/update", s.agentUpdate) g.GET("/update", s.agentUpdate)
sp := g.Group("", requireAgentKind("statuspage")) sp := g.Group("", requireAgentKind("statuspage"))
sp.GET("/pages", s.agentPage) sp.GET("/pages", s.agentPage)
sp.GET("/pages/index", s.agentPageIndex)
sp.GET("/storage", s.storageGet) sp.GET("/storage", s.storageGet)
sp.PUT("/storage", s.storagePut) sp.PUT("/storage", s.storagePut)
sp.DELETE("/storage", s.storageDelete) sp.DELETE("/storage", s.storageDelete)
@@ -48,6 +51,7 @@ func (s *Server) mountAgentAPI(r gin.IRouter) {
sp.GET("/storage/list", s.storageList) sp.GET("/storage/list", s.storageList)
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)
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)
@@ -195,8 +199,27 @@ func (s *Server) agentJobs(c *gin.Context) {
return return
} }
wait := min(time.Duration(req.WaitMS)*time.Millisecond, maxJobWait) wait := min(time.Duration(req.WaitMS)*time.Millisecond, maxJobWait)
entries, err := s.sched.Take(ctx, instance, min(req.Max, maxJobBatch), wait) // A draining instance ends long polls within a second or so, empty, so
if err != nil && ctx.Err() == nil { // the shutdown is not held up and the checker's next poll reaches
// another instance. It still holds them that second, so checkers that
// poll again at once do not spin against it.
pollCtx, stop := context.WithCancel(ctx)
defer stop()
if s.draining != nil {
go func() {
select {
case <-s.draining:
select {
case <-time.After(drainingPollHold):
case <-pollCtx.Done():
}
stop()
case <-pollCtx.Done():
}
}()
}
entries, err := s.sched.Take(pollCtx, instance, min(req.Max, maxJobBatch), wait)
if err != nil && pollCtx.Err() == nil {
internalError(c, err) internalError(c, err)
return return
} }
@@ -314,8 +337,7 @@ func (s *Server) agentResults(c *gin.Context) {
if len(params) == 0 { if len(params) == 0 {
return nil return nil
} }
_, err = q.InsertCheckResults(ctx, params) return insertResults(ctx, q, params)
return err
}) })
if err != nil { if err != nil {
// Unclaimed, the checker's retry is stored instead. // Unclaimed, the checker's retry is stored instead.
+33 -6
View File
@@ -65,6 +65,17 @@ var endpoints = []endpoint{
{method: "POST", path: "/api/v1/consent", tag: "Account", summary: "Accept the platform's privacy policy and terms", sessionOnly: true, {method: "POST", path: "/api/v1/consent", tag: "Account", summary: "Accept the platform's privacy policy and terms", sessionOnly: true,
description: "`versions` are the versions shown, e.g. `privacy:12,terms:14`; `409 consent_outdated` when a document changed meanwhile. Until an account accepted the current versions, other requests of its sessions get `403 consent_required`.", description: "`versions` are the versions shown, e.g. `privacy:12,terms:14`; `409 consent_outdated` when a document changed meanwhile. Until an account accepted the current versions, other requests of its sessions get `403 consent_required`.",
req: consentRequest{}, resp: obj{"redirect": ""}}, req: consentRequest{}, resp: obj{"redirect": ""}},
{method: "GET", path: "/api/v1/support/tickets", tag: "Support", summary: "The account's support tickets", sessionOnly: true,
description: "Newest activity first. Open to suspended accounts and to those that have not accepted the terms.", resp: obj{"tickets": []supportTicketView{}}},
{method: "POST", path: "/api/v1/support/tickets", tag: "Support", summary: "Ask the platform's admins for help", sessionOnly: true,
description: "`message` is Markdown; the admins are mailed. `attach_org` names the active organization; `monitor_id`, `channel_id`, `alert_group_id`, `status_page_id` and `incident_id` point at things in it the account can read, and name it too. `409 too_many_tickets` beyond the platform's limit of open tickets per account, `409 suspended_ticket_limit` for a second ticket of a suspended account; `403 support_disabled` while the admins switched support off.",
req: supportTicketRequest{}, resp: supportTicketView{}, status: http.StatusCreated},
{method: "GET", path: "/api/v1/support/tickets/:id", tag: "Support", summary: "A support ticket with its messages", sessionOnly: true,
resp: supportTicketView{}},
{method: "POST", path: "/api/v1/support/tickets/:id/messages", tag: "Support", summary: "Reply to a support ticket", sessionOnly: true,
description: "Moves the ticket to `open`, also out of `closed`.", req: supportMessageRequest{}, resp: obj{"status": ""}, status: http.StatusCreated},
{method: "PUT", path: "/api/v1/support/tickets/:id/status", tag: "Support", summary: "Close or reopen a support ticket", sessionOnly: true,
description: "`status` is `closed` or `open`.", req: supportStatusRequest{}, status: http.StatusNoContent},
{method: "POST", path: "/api/v1/markdown/preview", tag: "Account", summary: "Render Markdown as pages will show it", {method: "POST", path: "/api/v1/markdown/preview", tag: "Account", summary: "Render Markdown as pages will show it",
req: previewRequest{}, resp: obj{"html": ""}}, req: previewRequest{}, resp: obj{"html": ""}},
{method: "POST", path: "/api/v1/invitations/:token/accept", tag: "Account", summary: "Accept an invitation with the signed-in account", sessionOnly: true, {method: "POST", path: "/api/v1/invitations/:token/accept", tag: "Account", summary: "Accept an invitation with the signed-in account", sessionOnly: true,
@@ -79,6 +90,9 @@ var endpoints = []endpoint{
{method: "POST", path: "/api/v1/org/monitors", tag: "Monitors", summary: "Create a monitor", {method: "POST", path: "/api/v1/org/monitors", tag: "Monitors", summary: "Create a monitor",
description: "`type` is one of http, json, prometheus, tcp, tls, dns, icmp, postgres, mysql, mssql, mongodb, redis, mqtt, kafka, rabbitmq, grpc, smtp, radius, snmp, steam, minecraft, docker, heartbeat or alertmanager (GET /api/v1/org/check-types lists those offered); `config` depends on it (see HTTPConfig, JSONConfig, PrometheusConfig, DNSConfig, TLSConfig, DBConfig, BrokerConfig, GRPCConfig, SMTPConfig, RADIUSConfig, SNMPConfig, GameConfig, DockerConfig, HeartbeatConfig, AlertmanagerConfig). Passwords, RADIUS secrets and SNMP communities are stored encrypted and never returned: `secrets_set` names those set, and an update that leaves one empty keeps it. Heartbeat and alertmanager monitors take neither target nor regions; heartbeats return their `ping_url`. Omit `alert_group_ids` to assign the default alert group; an empty array disables notifications.", description: "`type` is one of http, json, prometheus, tcp, tls, dns, icmp, postgres, mysql, mssql, mongodb, redis, mqtt, kafka, rabbitmq, grpc, smtp, radius, snmp, steam, minecraft, docker, heartbeat or alertmanager (GET /api/v1/org/check-types lists those offered); `config` depends on it (see HTTPConfig, JSONConfig, PrometheusConfig, DNSConfig, TLSConfig, DBConfig, BrokerConfig, GRPCConfig, SMTPConfig, RADIUSConfig, SNMPConfig, GameConfig, DockerConfig, HeartbeatConfig, AlertmanagerConfig). Passwords, RADIUS secrets and SNMP communities are stored encrypted and never returned: `secrets_set` names those set, and an update that leaves one empty keeps it. Heartbeat and alertmanager monitors take neither target nor regions; heartbeats return their `ping_url`. Omit `alert_group_ids` to assign the default alert group; an empty array disables notifications.",
perm: "monitors.write", req: monitorRequest{}, status: http.StatusCreated, resp: monitorView{}}, perm: "monitors.write", req: monitorRequest{}, status: http.StatusCreated, resp: monitorView{}},
{method: "PUT", path: "/api/v1/org/monitors/order", tag: "Monitors", summary: "Put monitors in the organization's own order", perm: "monitors.write",
description: "Positions follow the order of monitor_ids, usually the monitors of one group; the monitor list sorted by its own order shows positioned monitors first, the rest by name. Needs write access to every monitor given.",
req: monitorOrderRequest{}},
{method: "PUT", path: "/api/v1/org/monitors/:id", tag: "Monitors", summary: "Change a monitor", perm: "monitors.write", {method: "PUT", path: "/api/v1/org/monitors/:id", tag: "Monitors", summary: "Change a monitor", perm: "monitors.write",
description: "Omitting alert_group_ids preserves existing assignments; an empty array removes all alert groups.", description: "Omitting alert_group_ids preserves existing assignments; an empty array removes all alert groups.",
req: monitorRequest{}, resp: monitorView{}}, req: monitorRequest{}, resp: monitorView{}},
@@ -95,12 +109,13 @@ var endpoints = []endpoint{
description: "Platform checkers serve every organization; other organizations' work appears only as a count. `recent` is paged, newest first; a page may hold fewer results than `limit` when some belong to monitors you cannot read.", description: "Platform checkers serve every organization; other organizations' work appears only as a count. `recent` is paged, newest first; a page may hold fewer results than `limit` when some belong to monitors you cannot read.",
resp: checkerActivity{}}, resp: checkerActivity{}},
{method: "GET", path: "/api/v1/org/limits", tag: "Organization", summary: "Limits in effect for the organization and its usage", {method: "GET", path: "/api/v1/org/limits", tag: "Organization", summary: "Limits in effect for the organization and its usage",
description: "0 means unlimited. Creating beyond a limit gives 422 monitor_limit, status_page_limit, region_limit or platform_region_limit.", description: "0 means unlimited. Creating beyond a limit gives 422 monitor_limit, status_page_limit, page_monitor_limit, region_limit or platform_region_limit.",
resp: usageView{}}, resp: usageView{}},
{method: "GET", path: "/api/v1/org/check-types", tag: "Monitors", summary: "Monitor types this installation offers", {method: "GET", path: "/api/v1/org/check-types", tag: "Monitors", summary: "Monitor types members can create",
resp: obj{"types": []string{}}}, description: "`own_checkers_only` are the types the platform's checkers do not run: monitors of them use the organization's own regions only, or 422 check_type_own_checkers_only.",
resp: obj{"types": []string{}, "own_checkers_only": []string{}}},
{method: "PUT", path: "/api/v1/org/check-types", tag: "Monitors", summary: "Choose the monitor types offered to members", {method: "PUT", path: "/api/v1/org/check-types", tag: "Monitors", summary: "Choose the monitor types offered to members",
description: "Out of the types the platform offers; types left out are not offered for new monitors or type changes, existing monitors keep running.", description: "Independent of the types the platform's checkers run; types left out are not offered for new monitors or type changes, existing monitors keep running.",
perm: "org.manage", sessionOnly: true, req: checkTypesRequest{}, status: http.StatusNoContent}, perm: "org.manage", sessionOnly: true, req: checkTypesRequest{}, status: http.StatusNoContent},
{method: "GET", path: "/api/v1/org/groups", tag: "Monitors", summary: "List monitor groups", resp: obj{"groups": []groupView{}}}, {method: "GET", path: "/api/v1/org/groups", tag: "Monitors", summary: "List monitor groups", resp: obj{"groups": []groupView{}}},
{method: "POST", path: "/api/v1/org/groups", tag: "Monitors", summary: "Create a group", perm: "monitors.write", {method: "POST", path: "/api/v1/org/groups", tag: "Monitors", summary: "Create a group", perm: "monitors.write",
@@ -273,14 +288,26 @@ var endpoints = []endpoint{
// Platform // Platform
{method: "GET", path: "/api/v1/admin/audit", tag: "Platform", summary: "Platform audit log", perm: "platform admin", {method: "GET", path: "/api/v1/admin/audit", tag: "Platform", summary: "Platform audit log", perm: "platform admin",
description: "Paged, newest first.", resp: paged(obj{"events": []auditEventView{}})}, description: "Paged, newest first.", resp: paged(obj{"events": []auditEventView{}})},
{method: "GET", path: "/api/v1/admin/support/settings", tag: "Platform", summary: "How the platform runs support tickets", perm: "platform admin",
resp: supportSettings{}},
{method: "PUT", path: "/api/v1/admin/support/settings", tag: "Platform", summary: "Switch support tickets on or off and limit open tickets per account", perm: "platform admin",
description: "`max_open_tickets` of 0 means unlimited.", req: supportSettings{}, status: http.StatusNoContent},
{method: "GET", path: "/api/v1/admin/support/tickets", tag: "Platform", summary: "Support tickets of every account", perm: "platform admin",
description: "`?status=open` (default), `answered`, `closed` or `all`; the latest 200, those waiting for the admins first.", resp: obj{"tickets": []supportTicketView{}}},
{method: "GET", path: "/api/v1/admin/support/tickets/:id", tag: "Platform", summary: "A support ticket with its messages", perm: "platform admin",
resp: supportTicketView{}},
{method: "POST", path: "/api/v1/admin/support/tickets/:id/messages", tag: "Platform", summary: "Answer a support ticket", perm: "platform admin",
description: "Moves the ticket to `answered` and mails the account.", req: supportMessageRequest{}, resp: obj{"status": ""}, status: http.StatusCreated},
{method: "PUT", path: "/api/v1/admin/support/tickets/:id/status", tag: "Platform", summary: "Set a support ticket's status", perm: "platform admin",
req: supportStatusRequest{}, status: http.StatusNoContent},
{method: "GET", path: "/api/v1/admin/legal", tag: "Platform", summary: "Platform legal notice and privacy policy", perm: "platform admin", {method: "GET", path: "/api/v1/admin/legal", tag: "Platform", summary: "Platform legal notice and privacy policy", perm: "platform admin",
resp: obj{"documents": []legalView{}}}, resp: obj{"documents": []legalView{}}},
{method: "PUT", path: "/api/v1/admin/legal/:kind", tag: "Platform", summary: "Set a platform legal document", perm: "platform admin", {method: "PUT", path: "/api/v1/admin/legal/:kind", tag: "Platform", summary: "Set a platform legal document", perm: "platform admin",
req: legalRequest{}, status: http.StatusNoContent}, req: legalRequest{}, status: http.StatusNoContent},
{method: "GET", path: "/api/v1/admin/check-types", tag: "Platform", summary: "Check types and whether they are offered", perm: "platform admin", {method: "GET", path: "/api/v1/admin/check-types", tag: "Platform", summary: "Check types and whether they are offered", perm: "platform admin",
resp: obj{"types": []checkTypeView{}}}, resp: obj{"types": []checkTypeView{}}},
{method: "PUT", path: "/api/v1/admin/check-types", tag: "Platform", summary: "Choose the check types offered for new monitors", {method: "PUT", path: "/api/v1/admin/check-types", tag: "Platform", summary: "Choose the check types the platform's checkers run",
description: "Types left out are switched off: not offered for new monitors or type changes; existing monitors keep running.", description: "Types left out are switched off for the platform's regions: new monitors and type changes may use them on the organizations' own regions only (passive types not at all); existing monitors keep running.",
perm: "platform admin", req: checkTypesRequest{}, status: http.StatusNoContent}, perm: "platform admin", req: checkTypesRequest{}, status: http.StatusNoContent},
{method: "GET", path: "/api/v1/admin/checker-network", tag: "Platform", summary: "Whether platform checkers may check private addresses", perm: "platform admin", {method: "GET", path: "/api/v1/admin/checker-network", tag: "Platform", summary: "Whether platform checkers may check private addresses", perm: "platform admin",
resp: checkerNetwork{}}, resp: checkerNetwork{}},
+7
View File
@@ -38,6 +38,12 @@ var auditActions = map[string]string{
"POST /api/v1/auth/login/totp": "auth.login", "POST /api/v1/auth/login/totp": "auth.login",
"POST /api/v1/auth/logout": "auth.logout", "POST /api/v1/auth/logout": "auth.logout",
"POST /api/v1/consent": "account.consent", "POST /api/v1/consent": "account.consent",
"POST /api/v1/support/tickets": "support.create",
"POST /api/v1/support/tickets/:id/messages": "support.reply",
"PUT /api/v1/support/tickets/:id/status": "support.status",
"POST /api/v1/admin/support/tickets/:id/messages": "support.answer",
"PUT /api/v1/admin/support/tickets/:id/status": "support.status",
"PUT /api/v1/admin/support/settings": "support.settings",
"PUT /api/v1/org/members/:user/owner": "member.owner", "PUT /api/v1/org/members/:user/owner": "member.owner",
"PATCH /api/v1/org/incidents/:id": "incident.title", "PATCH /api/v1/org/incidents/:id": "incident.title",
"POST /api/v1/org/incidents/:id/updates": "incident.update", "POST /api/v1/org/incidents/:id/updates": "incident.update",
@@ -58,6 +64,7 @@ var auditActions = map[string]string{
"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",
"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",
+47
View File
@@ -0,0 +1,47 @@
package api
import (
"net/http"
"strings"
"time"
"github.com/gin-gonic/gin"
)
// A status page server obtains certificates for custom domains on demand,
// on the first visit over HTTPS. Before it orders a new one from its CA it
// asks here: only for a verified domain of a page it serves, and within the
// limits of UPTIME_CERTS_*. The limits count across all instances and keep
// one organization, or a flood of handshakes for many names, from using up
// the CA's rate limits that the other organizations share.
type certificateRequest struct {
Name string `json:"name" binding:"required,max=253"`
}
func (s *Server) agentCertificate(c *gin.Context) {
var req certificateRequest
if !bind(c, &req) {
return
}
name := strings.TrimSuffix(strings.ToLower(strings.TrimSpace(req.Name)), ".")
ctx := c.Request.Context()
page, ok, err := s.agentServes(ctx, agentOf(c), &name, nil)
if err != nil {
internalError(c, err)
return
}
if !ok {
fail(c, http.StatusNotFound, "not_found")
return
}
lim := s.cfg.Certificates
if !s.limit(c, "acme:name:"+name, lim.PerNamePerDay, 24*time.Hour) ||
!s.limit(c, "acme:org:"+page.OrgID.String(), lim.PerOrgPerDay, 24*time.Hour) ||
!s.limit(c, "acme:owner:"+storageOwner(c), lim.PerOwnerPerHour, time.Hour) {
s.log.WarnContext(ctx, "certificate order refused by limit", "domain", name, "org", page.OrgID, "agent", agentOf(c).ID)
return
}
s.log.InfoContext(ctx, "certificate order allowed", "domain", name, "org", page.OrgID, "agent", agentOf(c).ID)
c.Status(http.StatusNoContent)
}
+108
View File
@@ -0,0 +1,108 @@
package api_test
import (
"context"
"errors"
"net/http"
"strings"
"testing"
"github.com/google/uuid"
"git.zb-server.de/ZB-Server/uptimesebi/internal/agentapi"
"git.zb-server.de/ZB-Server/uptimesebi/internal/config"
)
func TestCertificateOrdersAreLimited(t *testing.T) {
e := newEnvWith(t, func(c *config.API) {
c.StatusPageURL = "https://status.platform.test"
c.Certificates = config.Certificates{PerOrgPerDay: 3, PerOwnerPerHour: 100, PerNamePerDay: 2}
})
ctx := context.Background()
owner := e.browser(t)
owner.signup("o@"+uniq("cert")+".test", uniq("cert-"))
platform := e.statuspageClient(t, nil)
page := func(domain string) (string, map[string]any) {
t.Helper()
slug := uniq("cert-")
_, p := owner.do("POST", "/api/v1/org/statuspages", map[string]any{"slug": slug, "title": "Status"})
id := p["id"].(string)
owner.do("PUT", "/api/v1/org/statuspages/"+id, map[string]any{"slug": slug, "title": "Status", "published": true})
st, body := owner.do("PUT", "/api/v1/org/statuspages/"+id+"/domain", map[string]any{"domain": domain})
if st != http.StatusOK {
t.Fatalf("set domain = %d %v", st, body)
}
return id, body["domain_record"].(map[string]any)
}
// An unverified domain gets no certificate, nor does a made-up name.
d1 := uniq("a") + ".example.test"
id1, rec1 := page(d1)
if err := platform.AllowCertificate(ctx, d1); !errors.Is(err, agentapi.ErrNotFound) {
t.Errorf("unverified domain: %v, want not found", err)
}
if err := platform.AllowCertificate(ctx, uniq("random")+".example.test"); !errors.Is(err, agentapi.ErrNotFound) {
t.Errorf("unknown name: %v, want not found", err)
}
// The editor explains the records, with the platform's servers as the
// CNAME target.
_, _, html := owner.page("/statuspages/" + id1)
for _, want := range []string{"Create this CNAME record", ".status.platform.test.", "Prove the domain with this TXT record", "ALIAS or ANAME", "at most 10 times a day"} {
if !strings.Contains(html, want) {
t.Errorf("the editor lacks %q", want)
}
}
verifyDomain(t, owner, id1, rec1)
if err := platform.AllowCertificate(ctx, strings.ToUpper(d1)+"."); err != nil {
t.Fatalf("verified domain: %v", err)
}
// A domain whose orders keep failing stops at its own limit.
_ = platform.AllowCertificate(ctx, d1)
if err := platform.AllowCertificate(ctx, d1); !errors.Is(err, agentapi.ErrRateLimited) {
t.Errorf("third order for one domain: %v, want rate limited", err)
}
// The organization's limit covers all its domains.
d2 := uniq("b") + ".example.test"
id2, rec2 := page(d2)
verifyDomain(t, owner, id2, rec2)
if err := platform.AllowCertificate(ctx, d2); err != nil {
t.Fatalf("second domain: %v", err)
}
if err := platform.AllowCertificate(ctx, d2); !errors.Is(err, agentapi.ErrRateLimited) {
t.Errorf("order beyond the organization's limit: %v, want rate limited", err)
}
// Another organization's server is not allowed the domain at all.
other := e.browser(t)
other.signup("x@"+uniq("cert")+".test", uniq("cert-"))
otherOrg := uuid.MustParse(other.orgID())
if err := e.statuspageClient(t, &otherOrg).AllowCertificate(ctx, d2); !errors.Is(err, agentapi.ErrNotFound) {
t.Errorf("another organization's server: %v, want not found", err)
}
}
func TestDomainChangesAreLimited(t *testing.T) {
e := newEnv(t)
owner := e.browser(t)
owner.signup("o@"+uniq("dom")+".test", uniq("dom-"))
_, p := owner.do("POST", "/api/v1/org/statuspages", map[string]any{"slug": uniq("dom-"), "title": "Status"})
id := p["id"].(string)
base := uniq("d")
for i := range 10 {
st, body := owner.do("PUT", "/api/v1/org/statuspages/"+id+"/domain", map[string]any{"domain": base + string(rune('a'+i)) + ".example.test"})
if st != http.StatusOK {
t.Fatalf("change %d = %d %v", i+1, st, body)
}
// Saving the same domain again does not count.
owner.do("PUT", "/api/v1/org/statuspages/"+id+"/domain", map[string]any{"domain": base + string(rune('a'+i)) + ".example.test"})
}
st, body := owner.do("PUT", "/api/v1/org/statuspages/"+id+"/domain", map[string]any{"domain": base + "z.example.test"})
expect(t, "eleventh change", st, body, http.StatusTooManyRequests, "domain_changes_exceeded")
// Removing the domain is always possible.
st, body = owner.do("PUT", "/api/v1/org/statuspages/"+id+"/domain", map[string]any{"domain": ""})
expect(t, "remove domain", st, body, http.StatusOK, "")
}
+1 -1
View File
@@ -182,7 +182,7 @@ func (s *Server) loadCheckerActivity(ctx context.Context, p *principal, instance
a.Siblings = append(a.Siblings, sb.ID) a.Siblings = append(a.Siblings, sb.ID)
} }
} }
monitors, err := q.ListMonitors(ctx) monitors, err := q.ListMonitors(ctx, p.Org.ID)
if err != nil { if err != nil {
return err return err
} }
+115 -27
View File
@@ -8,6 +8,7 @@ import (
"slices" "slices"
"github.com/gin-gonic/gin" "github.com/gin-gonic/gin"
"github.com/google/uuid"
"github.com/jackc/pgx/v5" "github.com/jackc/pgx/v5"
"git.zb-server.de/ZB-Server/uptimesebi/internal/check" "git.zb-server.de/ZB-Server/uptimesebi/internal/check"
@@ -15,10 +16,12 @@ import (
"git.zb-server.de/ZB-Server/uptimesebi/internal/tenant" "git.zb-server.de/ZB-Server/uptimesebi/internal/tenant"
) )
// Platform admins can switch off check types the installation cannot // Platform admins can switch off check types the platform's checkers
// offer, such as Docker on shared cloud checkers. Switched-off types are // cannot offer, such as Docker on shared cloud checkers. That only binds
// not offered for new monitors; existing ones keep running and stay // the platform's checkers: organizations keep such types for their own.
// editable. // Organizations separately choose the types they offer their members.
// Switched-off types are not offered for new monitors; existing ones keep
// running and stay editable.
const settingDisabledChecks = "disabled_check_types" const settingDisabledChecks = "disabled_check_types"
@@ -48,34 +51,87 @@ func (s *Server) disabledChecks(ctx context.Context) map[string]bool {
return set return set
} }
// offered reports whether org may create monitors of type t: neither the // checkTypeChoice is a type an organization can pick for a monitor.
// platform nor the organization switched it off. type checkTypeChoice struct {
func (s *Server) offered(ctx context.Context, org store.Org, t string) bool { Type string
return slices.Contains(s.enabledCheckTypes(ctx, org, ""), t) // OwnOnly is set when the platform switched the type off for its
// checkers, leaving the organization's own.
OwnOnly bool
} }
// enabledCheckTypes lists the types offered to org for new monitors, plus // checkTypeChoices lists the types offered to org, plus keep when a
// keep when a monitor of a switched-off type is being edited. The // monitor of a switched-off type is being edited. Types the platform
// organization's choice is ignored if it would leave nothing, which can // switched off for its checkers are offered only to organizations with
// happen when the platform later switches off what it kept. // regions of their own; passive ones, which no checker runs, not at all.
func (s *Server) enabledCheckTypes(ctx context.Context, org store.Org, keep string) []string { func (s *Server) checkTypeChoices(ctx context.Context, org store.Org, keep string, ownRegions bool) []checkTypeChoice {
off := s.disabledChecks(ctx) off := s.disabledChecks(ctx)
var platform, out []string var out, platform []checkTypeChoice
for _, t := range check.Types { for _, ty := range check.Types {
if off[string(t)] && string(t) != keep { t := string(ty)
passive := check.Passive(ty)
if off[t] && t != keep && (passive || !ownRegions) {
continue continue
} }
platform = append(platform, string(t)) choice := checkTypeChoice{Type: t, OwnOnly: off[t] && !passive}
if !slices.Contains(org.DisabledCheckTypes, string(t)) || string(t) == keep { if !off[t] || t == keep {
out = append(out, string(t)) platform = append(platform, choice)
}
if !slices.Contains(org.DisabledCheckTypes, t) || t == keep {
out = append(out, choice)
} }
} }
// The organization's choice can leave nothing usable when it only
// kept types the platform's checkers no longer run.
if len(out) == 0 { if len(out) == 0 {
return platform return platform
} }
return out return out
} }
var (
errCheckTypeDisabled = errors.New("api: check type switched off")
errOwnCheckersOnly = errors.New("api: check type switched off for platform checkers")
)
// checkTypeAllowed fails unless org may give a monitor, previously of
// type keep in the regions previous, type t in regions; platform marks
// the platform's regions. Monitors of a type the platform switched off
// keep the platform regions they had but gain none.
func (s *Server) checkTypeAllowed(ctx context.Context, org store.Org, t, keep string, regions, previous []uuid.UUID, platform map[uuid.UUID]bool) error {
own := false
for _, p := range platform {
own = own || !p
}
choices := s.checkTypeChoices(ctx, org, keep, own)
i := slices.IndexFunc(choices, func(c checkTypeChoice) bool { return c.Type == t })
if i < 0 {
return errCheckTypeDisabled
}
if !s.disabledChecks(ctx)[t] || check.Passive(check.Type(t)) {
return nil
}
for _, r := range regions {
if platform[r] && (t != keep || !slices.Contains(previous, r)) {
return errOwnCheckersOnly
}
}
return nil
}
// failCheckType answers a checkTypeAllowed error and reports whether it
// did.
func failCheckType(c *gin.Context, err error) bool {
switch {
case errors.Is(err, errCheckTypeDisabled):
fail(c, http.StatusUnprocessableEntity, "check_type_disabled")
case errors.Is(err, errOwnCheckersOnly):
fail(c, http.StatusUnprocessableEntity, "check_type_own_checkers_only")
default:
return false
}
return true
}
type checkTypeView struct { type checkTypeView struct {
Type string `json:"type"` Type string `json:"type"`
Enabled bool `json:"enabled"` Enabled bool `json:"enabled"`
@@ -132,13 +188,40 @@ func (s *Server) adminSetCheckTypes(c *gin.Context) {
c.Status(http.StatusNoContent) c.Status(http.StatusNoContent)
} }
// orgCheckTypes tells API clients which monitor types they can create. // orgCheckTypes tells API clients which monitor types they can create;
// own_checkers_only are those the platform's checkers do not run.
func (s *Server) orgCheckTypes(c *gin.Context) { func (s *Server) orgCheckTypes(c *gin.Context) {
c.JSON(http.StatusOK, gin.H{"types": s.enabledCheckTypes(c.Request.Context(), current(c).Org, "")}) p := current(c)
ctx := c.Request.Context()
own, err := s.hasOwnRegions(ctx, p)
if err != nil {
internalError(c, err)
return
}
types, ownOnly := []string{}, []string{}
for _, ch := range s.checkTypeChoices(ctx, p.Org, "", own) {
types = append(types, ch.Type)
if ch.OwnOnly {
ownOnly = append(ownOnly, ch.Type)
}
}
c.JSON(http.StatusOK, gin.H{"types": types, "own_checkers_only": ownOnly})
} }
// orgSetCheckTypes chooses which of the platform's types the organization func (s *Server) hasOwnRegions(ctx context.Context, p *principal) (bool, error) {
// offers its members. var own bool
err := s.db.Tx(ctx, p.scope(), func(q *store.Queries) error {
regions, err := q.ListVisibleRegions(ctx)
own = slices.ContainsFunc(regions, func(r store.Region) bool { return r.OrgID != nil })
return err
})
return own, err
}
// orgSetCheckTypes chooses which types the organization offers its
// members, independently of what the platform's checkers run. Passive
// types the platform switched off cannot be chosen and keep their
// setting.
func (s *Server) orgSetCheckTypes(c *gin.Context) { func (s *Server) orgSetCheckTypes(c *gin.Context) {
var req checkTypesRequest var req checkTypesRequest
if !bind(c, &req) { if !bind(c, &req) {
@@ -149,12 +232,17 @@ func (s *Server) orgSetCheckTypes(c *gin.Context) {
off := s.disabledChecks(ctx) off := s.disabledChecks(ctx)
disabled := []string{} disabled := []string{}
enabled := 0 enabled := 0
for _, t := range check.Types { for _, ty := range check.Types {
t := string(ty)
switch { switch {
case slices.Contains(req.Enabled, string(t)): case off[t] && check.Passive(ty):
if slices.Contains(p.Org.DisabledCheckTypes, t) {
disabled = append(disabled, t)
}
case slices.Contains(req.Enabled, t):
enabled++ enabled++
case !off[string(t)]: default:
disabled = append(disabled, string(t)) disabled = append(disabled, t)
} }
} }
for _, t := range req.Enabled { for _, t := range req.Enabled {
+25
View File
@@ -74,4 +74,29 @@ func TestCheckTypesCanBeSwitchedOff(t *testing.T) {
if _, _, page := admin.page("/monitors/" + hb["id"].(string) + "/edit"); !strings.Contains(page, `value="heartbeat" selected`) { if _, _, page := admin.page("/monitors/" + hb["id"].(string) + "/edit"); !strings.Contains(page, `value="heartbeat" selected`) {
t.Error("editing a monitor of a switched-off type does not keep its type") t.Error("editing a monitor of a switched-off type does not keep its type")
} }
// The switch binds the platform's checkers only: with a region of its
// own the organization keeps the type there.
st, own := member.do("POST", "/api/v1/org/regions", map[string]any{"key": uniq("own-"), "name": "Own"})
if st != http.StatusCreated {
t.Fatalf("own region = %d %v", st, own)
}
ownID := own["id"].(string)
if _, types := member.do("GET", "/api/v1/org/check-types", nil); !strings.Contains(mustJSON(types["types"]), `"icmp"`) || mustJSON(types["own_checkers_only"]) != `["icmp"]` {
t.Errorf("offered types with an own region = %v", types)
}
if _, _, page := member.page("/monitors/new"); !strings.Contains(page, `value="icmp"`) || !strings.Contains(page, "own checkers only") {
t.Error("the editor does not offer the type for own checkers")
}
st, body = member.do("POST", "/api/v1/org/monitors", map[string]any{"name": "Ping", "type": "icmp", "target": "example.com", "interval_seconds": 60, "regions": []string{ownID, region}})
expect(t, "switched-off type on a platform region", st, body, http.StatusUnprocessableEntity, "check_type_own_checkers_only")
st, ping := member.do("POST", "/api/v1/org/monitors", map[string]any{"name": "Ping", "type": "icmp", "target": "example.com", "interval_seconds": 60, "regions": []string{ownID}})
expect(t, "switched-off type on an own region", st, ping, http.StatusCreated, "")
st, body = member.do("PUT", "/api/v1/org/monitors/"+ping["id"].(string), map[string]any{"name": "Ping", "type": "icmp", "target": "example.com", "interval_seconds": 60, "regions": []string{ownID, region}})
expect(t, "adding a platform region", st, body, http.StatusUnprocessableEntity, "check_type_own_checkers_only")
st, body = member.do("POST", "/api/v1/org/monitors", map[string]any{"name": "Cron", "type": "heartbeat", "interval_seconds": 3600})
expect(t, "switched-off passive type", st, body, http.StatusUnprocessableEntity, "check_type_disabled")
if _, _, page := member.page("/settings/org"); !strings.Contains(page, `value="icmp"`) || strings.Contains(page, `value="heartbeat"`) {
t.Error("the organization settings do not offer the types for own checkers")
}
} }
+5 -2
View File
@@ -132,11 +132,13 @@ func (s *Server) accessOf(ctx context.Context, user uuid.UUID) (access, error) {
} }
// restrictedPaths stay open to accounts that are suspended or have yet to // restrictedPaths stay open to accounts that are suspended or have yet to
// accept the documents. Admins keep editing the documents, which they may // accept the documents, support included: a suspended account may want to
// be publishing one after the other; the handlers still check they are. // ask why. Admins keep editing the documents, which they may be publishing
// one after the other; the handlers still check they are.
var restrictedPaths = []string{ var restrictedPaths = []string{
"/consent", "/account/suspended", "/legal/", "/consent", "/account/suspended", "/legal/",
"/api/v1/auth/", "/api/v1/consent", "/api/v1/me/export", "/api/v1/me/delete", "/api/v1/locale", "/api/v1/auth/", "/api/v1/consent", "/api/v1/me/export", "/api/v1/me/delete", "/api/v1/locale",
"/support", "/support/", "/api/v1/support/",
"/admin/legal", "/api/v1/admin/legal/", "/admin/legal", "/api/v1/admin/legal/",
} }
@@ -249,6 +251,7 @@ func (s *Server) restrictedMe(c *gin.Context, sess *auth.Session) (web.Me, error
return web.Me{}, err return web.Me{}, err
} }
me := toWebMe(m) me := toWebMe(m)
me.Support = s.supportSettings(c.Request.Context()).Enabled
me.DeletesOrgs, err = s.lastOwnedOrgs(c.Request.Context(), sess.UserID) me.DeletesOrgs, err = s.lastOwnedOrgs(c.Request.Context(), sess.UserID)
return me, err return me, err
} }
+3
View File
@@ -48,6 +48,9 @@ func TestConsent(t *testing.T) {
if !strings.Contains(versions, "privacy:") || !strings.Contains(versions, "terms:") || !strings.Contains(form, `name="consent" required`) { if !strings.Contains(versions, "privacy:") || !strings.Contains(versions, "terms:") || !strings.Contains(form, `name="consent" required`) {
t.Fatalf("sign-up form lacks the consent box: versions %q", versions) t.Fatalf("sign-up form lacks the consent box: versions %q", versions)
} }
if !strings.Contains(form, "</a> and the <a") {
t.Error("the consent text runs the documents' names into the words between them")
}
signup := func(consent bool, versions string) (int, map[string]any) { signup := func(consent bool, versions string) (int, map[string]any) {
return e.browser(t).do("POST", "/api/v1/auth/signup", map[string]any{ return e.browser(t).do("POST", "/api/v1/auth/signup", map[string]any{
"email": uniq("n") + "@example.test", "password": password, "consent": consent, "consent_versions": versions, "email": uniq("n") + "@example.test", "password": password, "consent": consent, "consent_versions": versions,
+358 -78
View File
@@ -6,6 +6,8 @@ import (
"encoding/json" "encoding/json"
"errors" "errors"
"fmt" "fmt"
"math"
"net"
"net/http" "net/http"
"net/url" "net/url"
"slices" "slices"
@@ -21,6 +23,7 @@ import (
"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"
"git.zb-server.de/ZB-Server/uptimesebi/internal/check" "git.zb-server.de/ZB-Server/uptimesebi/internal/check"
"git.zb-server.de/ZB-Server/uptimesebi/internal/evaluate"
"git.zb-server.de/ZB-Server/uptimesebi/internal/i18n" "git.zb-server.de/ZB-Server/uptimesebi/internal/i18n"
"git.zb-server.de/ZB-Server/uptimesebi/internal/maintenance" "git.zb-server.de/ZB-Server/uptimesebi/internal/maintenance"
"git.zb-server.de/ZB-Server/uptimesebi/internal/notify" "git.zb-server.de/ZB-Server/uptimesebi/internal/notify"
@@ -77,25 +80,81 @@ func (s *Server) dashboard(c *gin.Context) {
} }
v.Root = buildGroupNodes(data.tree, data.rows) v.Root = buildGroupNodes(data.tree, data.rows)
v.Empty = len(data.rows) == 0 && len(v.Root.Children) == 0 v.Empty = len(data.rows) == 0 && len(v.Root.Children) == 0
v.CanWrite = writableAnywhere(p, data.tree)
if !s.dashboardPage(c, &v, data) { if !s.dashboardPage(c, &v, data) {
return return
} }
v.CanWrite = writableAnywhere(p, data.tree) if err := s.dashboardBars(c.Request.Context(), p, &v, &data); err != nil {
internalError(c, err)
return
}
v.Range = data.rng.Key v.Range = data.rng.Key
var earliest time.Time var earliest time.Time
for _, m := range data.byID { if err := s.db.Tx(c.Request.Context(), p.scope(), func(q *store.Queries) error {
if f, ok := data.first[m.ID]; ok && (earliest.IsZero() || f.Before(earliest)) { var err error
earliest = f earliest, err = earliestData(c.Request.Context(), q, p.Org.ID, data.now)
} return err
}); err != nil {
internalError(c, err)
return
} }
v.Ranges = rangeOptions(c, data.rng, earliest, data.now) v.Ranges = rangeOptions(c, data.rng, earliest, data.now)
for _, m := range data.rows { for _, m := range data.rows {
v.Counts[m.Status]++ v.Counts[m.Status]++
if m.Unchecked {
v.Unchecked++
}
} }
v.Filters = statusFilters(c, v.Counts, v.Filter)
for id, since := range s.regionsWithoutChecker(c.Request.Context(), data.usedRegions) {
v.DeadRegions = append(v.DeadRegions, web.DeadRegion{Name: data.regionOf[id].Name, Since: since.Local().Format("2006-01-02 15:04")})
}
slices.SortFunc(v.DeadRegions, func(a, b web.DeadRegion) int { return strings.Compare(a.Name, b.Name) })
} }
web.Render(c, http.StatusOK, web.Dashboard(s.pageFor(c, "console.monitors.title"), me, v)) web.Render(c, http.StatusOK, web.Dashboard(s.pageFor(c, "console.monitors.title"), me, v))
} }
// dashboardBars loads the bars of the monitors v shows, and only those.
func (s *Server) dashboardBars(ctx context.Context, p *principal, v *web.DashboardView, data *monitorData) error {
var ids []uuid.UUID
walk := func(rows []web.MonitorRow, set bool) {
for i := range rows {
id, err := uuid.Parse(rows[i].ID)
if err != nil {
continue
}
if set {
rows[i].Bars = data.bars(id)
} else {
ids = append(ids, id)
}
}
}
var tree func(n *web.GroupNode, set bool)
tree = func(n *web.GroupNode, set bool) {
walk(n.Monitors, set)
for i := range n.Children {
tree(&n.Children[i], set)
}
}
// A search or filter lists Results instead of the tree.
listing := v.Search != "" || v.Filter != ""
if listing {
walk(v.Results, false)
} else {
tree(&v.Root, false)
}
if err := s.loadBars(ctx, p, data, ids); err != nil {
return err
}
if listing {
walk(v.Results, true)
} else {
tree(&v.Root, true)
}
return nil
}
// groupMonitorsShown is how many of its own monitors a group shows on the // groupMonitorsShown is how many of its own monitors a group shows on the
// dashboard before linking to all of them. // dashboard before linking to all of them.
const groupMonitorsShown = 50 const groupMonitorsShown = 50
@@ -103,14 +162,64 @@ const groupMonitorsShown = 50
// ungrouped names the pseudo-group of monitors outside any group. // ungrouped names the pseudo-group of monitors outside any group.
const ungrouped = "none" const ungrouped = "none"
func monitorKey(m web.MonitorRow) cursor { // monitorSort is an order of the monitor list: the organization's own,
id, _ := uuid.Parse(m.ID) // or by name, status (problems first), uptime (worst first) or latency
return cursor{S: strings.ToLower(m.Name), ID: id} // (slowest first). Monitors without a position or data come last.
type monitorSort string
var monitorSorts = []monitorSort{"custom", "name", "status", "uptime", "latency"}
const sortCookie = "monitor_sort"
// sortOf returns the order asked for, remembering it in a cookie, or the
// one remembered, or the organization's own.
func sortOf(c *gin.Context) monitorSort {
if q := monitorSort(c.Query("sort")); slices.Contains(monitorSorts, q) {
c.SetSameSite(http.SameSiteLaxMode)
c.SetCookie(sortCookie, string(q), 365*24*3600, "/", "", c.Request.TLS != nil, true)
return q
}
if v, err := c.Cookie(sortCookie); err == nil && slices.Contains(monitorSorts, monitorSort(v)) {
return monitorSort(v)
}
return "custom"
} }
func sortMonitors(ms []web.MonitorRow) { // key orders m by o as a string, so pages can continue after it.
func (o monitorSort) key(m web.MonitorRow) cursor {
id, _ := uuid.Parse(m.ID)
name := strings.ToLower(m.Name)
var k string
switch o {
case "name":
k = name
case "status":
k = fmt.Sprintf("%d|%s", statusRank[m.Status], name)
case "uptime":
if m.Ratio < 0 {
k = "1|" + name
} else {
k = fmt.Sprintf("0|%.9f|%s", m.Ratio, name)
}
case "latency":
if m.LatencyMS < 0 {
k = "1|" + name
} else {
k = fmt.Sprintf("0|%010d|%s", math.MaxInt32-m.LatencyMS, name)
}
default:
if m.Position < 0 {
k = "1|" + name
} else {
k = fmt.Sprintf("0|%010d|%s", m.Position, name)
}
}
return cursor{S: k, ID: id}
}
func (o monitorSort) sort(ms []web.MonitorRow) {
slices.SortFunc(ms, func(a, b web.MonitorRow) int { slices.SortFunc(ms, func(a, b web.MonitorRow) int {
ka, kb := monitorKey(a), monitorKey(b) ka, kb := o.key(a), o.key(b)
if c := strings.Compare(ka.S, kb.S); c != 0 { if c := strings.Compare(ka.S, kb.S); c != 0 {
return c return c
} }
@@ -118,6 +227,46 @@ func sortMonitors(ms []web.MonitorRow) {
}) })
} }
// dashboardStatuses are the statuses the dashboard counts, in order.
var dashboardStatuses = []web.Status{web.StatusUp, web.StatusDegraded, web.StatusDown, web.StatusUnknown, web.StatusMaintenance, web.StatusPaused}
// dashboardURL is the dashboard with key set to value, or removed when
// value is empty, keeping the search and range but not the page.
func dashboardURL(c *gin.Context, key, value string) string {
q := url.Values{}
for _, k := range []string{"q", "range", "status", "arrange"} {
if v := c.Query(k); v != "" {
q.Set(k, v)
}
}
if value == "" {
q.Del(key)
} else {
q.Set(key, value)
}
if len(q) == 0 {
return "/"
}
return "/?" + q.Encode()
}
// statusFilters are the counts of the statuses present, each linking to
// its monitors, the active one back to all.
func statusFilters(c *gin.Context, counts map[web.Status]int, active web.Status) []web.StatusFilter {
var out []web.StatusFilter
for _, st := range dashboardStatuses {
if counts[st] == 0 && st != active {
continue
}
f := web.StatusFilter{Status: st, Count: counts[st], Active: st == active, URL: dashboardURL(c, "status", string(st))}
if f.Active {
f.URL = dashboardURL(c, "status", "")
}
out = append(out, f)
}
return out
}
// dashboardPage narrows the dashboard to a search or one group, pages it // dashboardPage narrows the dashboard to a search or one group, pages it
// and caps every group's own monitors. It reports false after answering // and caps every group's own monitors. It reports false after answering
// with an error. // with an error.
@@ -126,6 +275,20 @@ func (s *Server) dashboardPage(c *gin.Context, v *web.DashboardView, data monito
if !ok { if !ok {
return false return false
} }
order := sortOf(c)
v.Sort = string(order)
for _, o := range monitorSorts {
v.Sorts = append(v.Sorts, web.SortOption{Key: string(o), Active: o == order, URL: dashboardURL(c, "sort", string(o))})
}
// Arranging by hand shows the whole tree in the organization's order.
arranging := order == "custom" && v.CanWrite && c.Query("q") == "" && c.Query("status") == "" && c.Query("group") == ""
v.Arrange = arranging && c.Query("arrange") == "1"
if arranging {
v.ArrangeURL = dashboardURL(c, "arrange", "1")
if v.Arrange {
v.ArrangeURL = dashboardURL(c, "arrange", "")
}
}
link := func(group string) string { link := func(group string) string {
q := url.Values{"group": {group}} q := url.Values{"group": {group}}
if r := c.Query("range"); r != "" { if r := c.Query("range"); r != "" {
@@ -135,8 +298,8 @@ func (s *Server) dashboardPage(c *gin.Context, v *web.DashboardView, data monito
} }
var capNode func(n *web.GroupNode) var capNode func(n *web.GroupNode)
capNode = func(n *web.GroupNode) { capNode = func(n *web.GroupNode) {
sortMonitors(n.Monitors) order.sort(n.Monitors)
if len(n.Monitors) > groupMonitorsShown { if len(n.Monitors) > groupMonitorsShown && !v.Arrange {
n.More = len(n.Monitors) - groupMonitorsShown n.More = len(n.Monitors) - groupMonitorsShown
n.Monitors = n.Monitors[:groupMonitorsShown] n.Monitors = n.Monitors[:groupMonitorsShown]
n.MoreURL = link(cmp.Or(n.ID, ungrouped)) n.MoreURL = link(cmp.Or(n.ID, ungrouped))
@@ -146,18 +309,25 @@ func (s *Server) dashboardPage(c *gin.Context, v *web.DashboardView, data monito
} }
} }
var info pageInfo var info pageInfo
if f := web.Status(c.Query("status")); slices.Contains(dashboardStatuses, f) {
v.Filter = f
v.AllURL = dashboardURL(c, "status", "")
}
switch group := c.Query("group"); { switch group := c.Query("group"); {
case strings.TrimSpace(c.Query("q")) != "": case strings.TrimSpace(c.Query("q")) != "" || v.Filter != "":
v.Search = strings.TrimSpace(c.Query("q")) v.Search = strings.TrimSpace(c.Query("q"))
needle := strings.ToLower(v.Search) needle := strings.ToLower(v.Search)
var hits []web.MonitorRow var hits []web.MonitorRow
for _, m := range data.rows { for _, m := range data.rows {
if v.Filter != "" && m.Status != v.Filter {
continue
}
if strings.Contains(strings.ToLower(m.Name), needle) || strings.Contains(strings.ToLower(m.Target), needle) { if strings.Contains(strings.ToLower(m.Name), needle) || strings.Contains(strings.ToLower(m.Target), needle) {
hits = append(hits, m) hits = append(hits, m)
} }
} }
sortMonitors(hits) order.sort(hits)
v.Results, info = pageSlice(hits, pg, monitorKey) v.Results, info = pageSlice(hits, pg, order.key)
case group != "": case group != "":
var focus web.GroupNode var focus web.GroupNode
found := false found := false
@@ -182,8 +352,8 @@ func (s *Server) dashboardPage(c *gin.Context, v *web.DashboardView, data monito
c.Redirect(http.StatusSeeOther, "/") c.Redirect(http.StatusSeeOther, "/")
return false return false
} }
sortMonitors(focus.Monitors) order.sort(focus.Monitors)
focus.Monitors, info = pageSlice(focus.Monitors, pg, monitorKey) focus.Monitors, info = pageSlice(focus.Monitors, pg, order.key)
for i := range focus.Children { for i := range focus.Children {
capNode(&focus.Children[i]) capNode(&focus.Children[i])
} }
@@ -202,78 +372,96 @@ type monitorData struct {
maint map[uuid.UUID][]store.MaintenanceWindow maint map[uuid.UUID][]store.MaintenanceWindow
rows []web.MonitorRow rows []web.MonitorRow
byID map[uuid.UUID]store.Monitor byID map[uuid.UUID]store.Monitor
// buckets cover the selected range at its resolution. // buckets cover the selected range at its resolution, for the
// monitors loadBars was asked for.
buckets map[uuid.UUID][]web.Bucket buckets map[uuid.UUID][]web.Bucket
down map[uuid.UUID][]web.Span down map[uuid.UUID][]web.Span
regionOf map[uuid.UUID]store.Region regionOf map[uuid.UUID]store.Region
rng web.TimeRange rng web.TimeRange
now time.Time now time.Time
// first is when each monitor first reported, from any region; // first is when the monitor of a detail page first reported, from
// firstRegion the same per region. // any region; firstRegion the same per region.
first map[uuid.UUID]time.Time first time.Time
firstRegion map[uuid.UUID]map[string]time.Time firstRegion map[string]time.Time
// statuses are the organization's own incident statuses. // statuses are the organization's own incident statuses.
statuses customStatuses statuses customStatuses
// usedRegions are the regions the enabled monitors are checked from.
usedRegions []uuid.UUID
} }
// loadFirstData finds when monitors and their regions first reported. The // loadFirstData finds when monitor and its regions first reported. The
// daily aggregate answers to the day, which is precise enough for anything // daily aggregate answers to the day, which is precise enough for anything
// older than two days; younger data is looked up in the raw results. // older than two days; younger data is looked up exactly.
func loadFirstData(ctx context.Context, q *store.Queries, org uuid.UUID, now time.Time) (map[uuid.UUID]time.Time, map[uuid.UUID]map[string]time.Time, error) { func loadFirstData(ctx context.Context, q *store.Queries, org, monitor uuid.UUID, now time.Time) (time.Time, map[string]time.Time, error) {
first := map[uuid.UUID]time.Time{} var first time.Time
perRegion := map[uuid.UUID]map[string]time.Time{} perRegion := map[string]time.Time{}
note := func(m uuid.UUID, region string, t time.Time) { note := func(region string, t time.Time) {
if perRegion[m] == nil { if cur, ok := perRegion[region]; !ok || t.Before(cur) {
perRegion[m] = map[string]time.Time{} perRegion[region] = t
} }
if cur, ok := perRegion[m][region]; !ok || t.Before(cur) { if first.IsZero() || t.Before(first) {
perRegion[m][region] = t first = t
}
if cur, ok := first[m]; !ok || t.Before(cur) {
first[m] = t
} }
} }
recentSince := now.Add(-2 * 24 * time.Hour) recentSince := now.Add(-2 * 24 * time.Hour)
daily, err := q.FirstDataDaily(ctx, org) daily, err := q.FirstDataDaily(ctx, store.FirstDataDailyParams{OrgID: org, MonitorID: monitor})
if err != nil { if err != nil {
return nil, nil, err return first, nil, err
} }
for _, r := range daily { for _, r := range daily {
if r.First.Before(recentSince) { if r.First.Before(recentSince) {
note(r.MonitorID, r.Region, r.First) note(r.Region, r.First)
} }
} }
recent, err := q.FirstDataRecent(ctx, store.FirstDataRecentParams{OrgID: org, Time: recentSince}) recent, err := q.FirstDataRecent(ctx, store.FirstDataRecentParams{OrgID: org, MonitorID: monitor, Time: recentSince})
if err != nil { if err != nil {
return nil, nil, err return first, nil, err
} }
for _, r := range recent { for _, r := range recent {
note(r.MonitorID, r.Region, r.First) note(r.Region, r.First)
} }
return first, perRegion, nil return first, perRegion, nil
} }
// rangeBuckets loads the selected range for all monitors, or one if // earliestData finds when any monitor of org first reported, for the
// monitor is set. // ranges the monitor list offers: to the day if that was over two days
func rangeBuckets(ctx context.Context, q *store.Queries, org uuid.UUID, monitor *uuid.UUID, rng web.TimeRange, now time.Time) (map[uuid.UUID][]web.Bucket, error) { // ago, otherwise exactly.
func earliestData(ctx context.Context, q *store.Queries, org uuid.UUID, now time.Time) (time.Time, error) {
none := func(t time.Time, err error) (time.Time, bool, error) {
if errors.Is(err, pgx.ErrNoRows) {
return time.Time{}, false, nil
}
return t, err == nil, err
}
recentSince := now.Add(-2 * 24 * time.Hour)
daily, ok, err := none(q.EarliestDataDaily(ctx, org))
if err != nil || (ok && daily.Before(recentSince)) {
return daily, err
}
exact, _, err := none(q.EarliestDataRecent(ctx, store.EarliestDataRecentParams{OrgID: org, Time: recentSince}))
return exact, err
}
// rangeBuckets loads the selected range for the monitors ids.
func rangeBuckets(ctx context.Context, q *store.Queries, org uuid.UUID, ids []uuid.UUID, rng web.TimeRange, now time.Time) (map[uuid.UUID][]web.Bucket, error) {
out := map[uuid.UUID][]web.Bucket{} out := map[uuid.UUID][]web.Bucket{}
since := now.Add(-rng.Window).Truncate(rng.Bucket) since := now.Add(-rng.Window).Truncate(rng.Bucket)
width := fmt.Sprintf("%d seconds", int(rng.Bucket.Seconds())) width := fmt.Sprintf("%d seconds", int(rng.Bucket.Seconds()))
switch rng.Source { switch rng.Source {
case web.SourceHourly: case web.SourceHourly:
rows, err := q.RangeBucketsHourly(ctx, store.RangeBucketsHourlyParams{OrgID: org, Width: width, Since: since, MonitorID: monitor}) rows, err := q.RangeBucketsHourly(ctx, store.RangeBucketsHourlyParams{OrgID: org, Width: width, Since: since, Ids: ids})
for _, r := range rows { for _, r := range rows {
out[r.MonitorID] = append(out[r.MonitorID], web.Bucket{Start: r.Bucket, Total: r.Total, OK: r.OkCount, Latency: r.AvgLatencyMs}) out[r.MonitorID] = append(out[r.MonitorID], web.Bucket{Start: r.Bucket, Total: r.Total, OK: r.OkCount, Latency: r.AvgLatencyMs})
} }
return out, err return out, err
case web.SourceDaily: case web.SourceDaily:
rows, err := q.RangeBucketsDaily(ctx, store.RangeBucketsDailyParams{OrgID: org, Width: width, Since: since, MonitorID: monitor}) rows, err := q.RangeBucketsDaily(ctx, store.RangeBucketsDailyParams{OrgID: org, Width: width, Since: since, Ids: ids})
for _, r := range rows { for _, r := range rows {
out[r.MonitorID] = append(out[r.MonitorID], web.Bucket{Start: r.Bucket, Total: r.Total, OK: r.OkCount, Latency: r.AvgLatencyMs}) out[r.MonitorID] = append(out[r.MonitorID], web.Bucket{Start: r.Bucket, Total: r.Total, OK: r.OkCount, Latency: r.AvgLatencyMs})
} }
return out, err return out, err
} }
rows, err := q.RangeBuckets(ctx, store.RangeBucketsParams{OrgID: org, Width: width, Since: since, MonitorID: monitor}) rows, err := q.RangeBuckets(ctx, store.RangeBucketsParams{OrgID: org, Width: width, Since: since, Ids: ids})
for _, r := range rows { for _, r := range rows {
out[r.MonitorID] = append(out[r.MonitorID], web.Bucket{Start: r.Bucket, Total: r.Total, OK: r.OkCount, Latency: r.AvgLatencyMs}) out[r.MonitorID] = append(out[r.MonitorID], web.Bucket{Start: r.Bucket, Total: r.Total, OK: r.OkCount, Latency: r.AvgLatencyMs})
} }
@@ -290,9 +478,10 @@ func (d monitorData) slaFor(m store.Monitor, window time.Duration) float64 {
return web.SLA(d.down[m.ID], from, d.now) return web.SLA(d.down[m.ID], from, d.now)
} }
// loadMonitorData assembles everything the monitor list shows. // loadMonitorData assembles the status of every monitor for rng.
// loadMonitorData assembles everything the monitor list shows for rng. // Incidents are loaded far enough back for every SLA window. The bars of
// Incidents are loaded far enough back for every SLA window. // rng are left to loadBars, for the monitors shown: an organization may
// have thousands.
func (s *Server) loadMonitorData(ctx context.Context, p *principal, rng web.TimeRange) (monitorData, error) { func (s *Server) loadMonitorData(ctx context.Context, p *principal, rng web.TimeRange) (monitorData, error) {
now := time.Now() now := time.Now()
d := monitorData{ d := monitorData{
@@ -314,10 +503,10 @@ func (s *Server) loadMonitorData(ctx context.Context, p *principal, rng web.Time
if groups, err = q.ListGroups(ctx); err != nil { if groups, err = q.ListGroups(ctx); err != nil {
return err return err
} }
if monitors, err = q.ListMonitors(ctx); err != nil { if monitors, err = q.ListMonitors(ctx, p.Org.ID); err != nil {
return err return err
} }
if assigned, err = q.AllMonitorRegions(ctx); err != nil { if assigned, err = q.AllMonitorRegions(ctx, p.Org.ID); err != nil {
return err return err
} }
if regions, err = q.ListVisibleRegions(ctx); err != nil { if regions, err = q.ListVisibleRegions(ctx); err != nil {
@@ -326,13 +515,10 @@ func (s *Server) loadMonitorData(ctx context.Context, p *principal, rng web.Time
if latest, err = q.LatestResults(ctx, p.Org.ID); err != nil { if latest, err = q.LatestResults(ctx, p.Org.ID); err != nil {
return err return err
} }
if open, err = q.OpenIncidents(ctx); err != nil { if open, err = q.OpenIncidents(ctx, p.Org.ID); err != nil {
return err return err
} }
if spans, err = q.IncidentsSince(ctx, ptr(now.Add(-web.SLAWindows[len(web.SLAWindows)-1].Window))); err != nil { if spans, err = q.IncidentsSince(ctx, store.IncidentsSinceParams{OrgID: p.Org.ID, ResolvedAt: ptr(now.Add(-web.SLAWindows[len(web.SLAWindows)-1].Window))}); err != nil {
return err
}
if d.first, d.firstRegion, err = loadFirstData(ctx, q, p.Org.ID, now); err != nil {
return err return err
} }
if d.statuses, err = loadCustomStatuses(ctx, q); err != nil { if d.statuses, err = loadCustomStatuses(ctx, q); err != nil {
@@ -342,10 +528,7 @@ func (s *Server) loadMonitorData(ctx context.Context, p *principal, rng web.Time
for i, m := range monitors { for i, m := range monitors {
ids[i] = m.ID ids[i] = m.ID
} }
if d.maint, err = maintenanceFor(ctx, q, ids); err != nil { d.maint, err = maintenanceFor(ctx, q, ids)
return err
}
d.buckets, err = rangeBuckets(ctx, q, p.Org.ID, nil, rng, now)
return err return err
}) })
if err != nil { if err != nil {
@@ -366,6 +549,13 @@ func (s *Server) loadMonitorData(ctx context.Context, p *principal, rng web.Time
for _, a := range assigned { for _, a := range assigned {
regionsOf[a.MonitorID] = append(regionsOf[a.MonitorID], a.RegionID) regionsOf[a.MonitorID] = append(regionsOf[a.MonitorID], a.RegionID)
} }
for _, m := range monitors {
if m.Enabled {
d.usedRegions = append(d.usedRegions, regionsOf[m.ID]...)
}
}
slices.SortFunc(d.usedRegions, func(a, b uuid.UUID) int { return strings.Compare(a.String(), b.String()) })
d.usedRegions = slices.Compact(d.usedRegions)
latestOf := map[uuid.UUID]map[string]store.LatestResultsRow{} latestOf := map[uuid.UUID]map[string]store.LatestResultsRow{}
for _, l := range latest { for _, l := range latest {
if latestOf[l.MonitorID] == nil { if latestOf[l.MonitorID] == nil {
@@ -382,7 +572,10 @@ func (s *Server) loadMonitorData(ctx context.Context, p *principal, rng web.Time
continue continue
} }
d.byID[m.ID] = m d.byID[m.ID] = m
row := web.MonitorRow{ID: m.ID.String(), Name: m.Name, Type: m.Type, Target: m.Target, Latency: "–", Uptime: "–"} row := web.MonitorRow{ID: m.ID.String(), Name: m.Name, Type: m.Type, Target: m.Target, Latency: "–", Uptime: "–", Position: -1, LatencyMS: -1}
if m.Position != nil {
row.Position = int(*m.Position)
}
keys := idStrings(regionsOf[m.ID]) keys := idStrings(regionsOf[m.ID])
if check.Passive(check.Type(m.Type)) { if check.Passive(check.Type(m.Type)) {
// The target of a heartbeat is its secret ping token. // The target of a heartbeat is its secret ping token.
@@ -393,9 +586,18 @@ func (s *Server) loadMonitorData(ctx context.Context, p *principal, rng web.Time
} }
var latencies []int32 var latencies []int32
failing, reported := 0, 0 failing, reported := 0, 0
// A region that has not reported for longer than the evaluator
// waits is unknown, whatever its last result said; passive monitors
// judge their own lateness.
staleBefore := now.Add(-evaluate.StaleAfter(time.Duration(m.IntervalSeconds) * time.Second))
for _, key := range keys { for _, key := range keys {
rs := web.RegionStatus{Name: d.regionNameString(key), Status: web.StatusUnknown, Detail: "–"} rs := web.RegionStatus{Name: d.regionNameString(key), Status: web.StatusUnknown, Detail: "–"}
if l, ok := latestOf[m.ID][key]; ok { l, ok := latestOf[m.ID][key]
if ok && !check.Passive(check.Type(m.Type)) && l.Time.Before(staleBefore) {
rs.Detail = i18n.T(ctx, "monitors.no_data_since", "Time", l.Time.Format("15:04"))
ok = false
}
if ok {
reported++ reported++
rs.Detail = l.Time.Format("15:04:05") rs.Detail = l.Time.Format("15:04:05")
if l.Ok { if l.Ok {
@@ -421,6 +623,8 @@ func (s *Server) loadMonitorData(ctx context.Context, p *principal, rng web.Time
row.Status = web.StatusDown row.Status = web.StatusDown
case reported == 0: case reported == 0:
row.Status = web.StatusUnknown row.Status = web.StatusUnknown
// Nobody is checking it, unless it is too new to have results.
row.Unchecked = !check.Passive(check.Type(m.Type)) && m.CreatedAt.Before(staleBefore)
case failing > 0: case failing > 0:
row.Status = web.StatusDegraded row.Status = web.StatusDegraded
default: default:
@@ -432,9 +636,10 @@ func (s *Server) loadMonitorData(ctx context.Context, p *principal, rng web.Time
sum += l sum += l
} }
row.Latency = fmt.Sprintf("%d ms", sum/int32(len(latencies))) row.Latency = fmt.Sprintf("%d ms", sum/int32(len(latencies)))
row.LatencyMS = int(sum / int32(len(latencies)))
} }
row.Uptime = web.SLAText(d.slaFor(m, rng.Window)) row.Ratio = d.slaFor(m, rng.Window)
row.Bars = web.UptimeBars(d.buckets[m.ID], now, rng.Bucket, rng.Bars(), rng.Layout) row.Uptime = web.SLAText(row.Ratio)
d.rows = append(d.rows, row) d.rows = append(d.rows, row)
} }
// Problems first, then by name. // Problems first, then by name.
@@ -442,6 +647,23 @@ func (s *Server) loadMonitorData(ctx context.Context, p *principal, rng web.Time
return d, nil return d, nil
} }
// loadBars loads the bars of the selected range for the monitors ids.
func (s *Server) loadBars(ctx context.Context, p *principal, d *monitorData, ids []uuid.UUID) error {
if len(ids) == 0 {
return nil
}
return s.db.Tx(ctx, p.scope(), func(q *store.Queries) error {
var err error
d.buckets, err = rangeBuckets(ctx, q, p.Org.ID, ids, d.rng, d.now)
return err
})
}
// bars are the monitor's bars of the selected range, from loadBars.
func (d monitorData) bars(id uuid.UUID) []web.Bar {
return web.UptimeBars(d.buckets[id], d.now, d.rng.Bucket, d.rng.Bars(), d.rng.Layout)
}
func (d monitorData) regionName(id uuid.UUID) string { func (d monitorData) regionName(id uuid.UUID) string {
if r, ok := d.regionOf[id]; ok { if r, ok := d.regionOf[id]; ok {
return r.Name return r.Name
@@ -464,6 +686,16 @@ func (s *Server) monitorDetail(c *gin.Context, p *principal, page web.Page, me w
if !ok { if !ok {
return notFoundPage(c) return notFoundPage(c)
} }
if err := s.loadBars(ctx, p, &d, []uuid.UUID{id}); err != nil {
return nil, err
}
if err := s.db.Tx(ctx, p.scope(), func(q *store.Queries) error {
var err error
d.first, d.firstRegion, err = loadFirstData(ctx, q, p.Org.ID, id, d.now)
return err
}); err != nil {
return nil, err
}
v := web.MonitorDetailView{ v := web.MonitorDetailView{
Interval: (time.Duration(m.IntervalSeconds) * time.Second).String(), Interval: (time.Duration(m.IntervalSeconds) * time.Second).String(),
PingURL: s.detailPingURL(p, d, m), PingURL: s.detailPingURL(p, d, m),
@@ -471,7 +703,7 @@ func (s *Server) monitorDetail(c *gin.Context, p *principal, page web.Page, me w
Latency: web.Latency(d.buckets[id], d.now.Add(-d.rng.Window).Truncate(d.rng.Bucket), d.now, 480, 96), Latency: web.Latency(d.buckets[id], d.now.Add(-d.rng.Window).Truncate(d.rng.Bucket), d.now, 480, 96),
Maintenance: maintenanceItems(d.maint[id], d.now), Maintenance: maintenanceItems(d.maint[id], d.now),
Range: d.rng.Key, Range: d.rng.Key,
Ranges: rangeOptions(c, d.rng, d.first[id], d.now), Ranges: rangeOptions(c, d.rng, d.first, d.now),
Uptime90: "–", Uptime90: "–",
} }
for _, r := range d.rows { for _, r := range d.rows {
@@ -479,6 +711,7 @@ func (s *Server) monitorDetail(c *gin.Context, p *principal, page web.Page, me w
v.Row = r v.Row = r
} }
} }
v.Row.Bars = d.bars(id)
var ( var (
daily []store.DailyBucketsRow daily []store.DailyBucketsRow
recent []store.ListResultsRow recent []store.ListResultsRow
@@ -507,7 +740,7 @@ func (s *Server) monitorDetail(c *gin.Context, p *principal, page web.Page, me w
for _, w := range web.SLAWindows { for _, w := range web.SLAWindows {
v.SLAs = append(v.SLAs, web.SLAEntry{ v.SLAs = append(v.SLAs, web.SLAEntry{
Label: w.Key, Value: web.SLAText(d.slaFor(m, w.Window)), Label: w.Key, Value: web.SLAText(d.slaFor(m, w.Window)),
Partial: !web.HasEnoughData(d.first[id], d.now, w.Window), Partial: !web.HasEnoughData(d.first, d.now, w.Window),
}) })
} }
regions, err := s.regionHistory(ctx, p, d, m) regions, err := s.regionHistory(ctx, p, d, m)
@@ -674,9 +907,16 @@ func (s *Server) monitorEditor(c *gin.Context, p *principal, page web.Page, me w
if err != nil { if err != nil {
return nil, err return nil, err
} }
f.Types = s.enabledCheckTypes(ctx, p.Org, f.Type) keep := ""
if !slices.Contains(f.Types, f.Type) { if idParam != "" {
f.Type = f.Types[0] keep = f.Type
}
own := slices.ContainsFunc(regions, func(r store.Region) bool { return r.OrgID != nil })
for _, ch := range s.checkTypeChoices(ctx, p.Org, keep, own) {
f.Types = append(f.Types, web.TypeOption{Type: ch.Type, OwnOnly: ch.OwnOnly})
}
if !slices.ContainsFunc(f.Types, func(t web.TypeOption) bool { return t.Type == f.Type }) {
f.Type = f.Types[0].Type
} }
for i, r := range regions { for i, r := range regions {
live, err := s.sched.Instances(ctx, r.ID.String()) live, err := s.sched.Instances(ctx, r.ID.String())
@@ -1009,19 +1249,45 @@ func (s *Server) channelsView(c *gin.Context, p *principal, page web.Page, me we
return web.ChannelsPage(page, me, v), nil return web.ChannelsPage(page, me, v), nil
} }
func (s *Server) pageURL(p store.StatusPage) string { // cnameTarget is the host custom domains point at to reach the platform's
// status page servers, unless that is not known.
func (s *Server) cnameTarget() string {
u, err := url.Parse(s.cfg.StatusPageURL)
if err != nil {
return ""
}
h := u.Hostname()
if h == "" || h == "localhost" || net.ParseIP(h) != nil || !strings.Contains(h, ".") {
return ""
}
return h
}
// pageURL is where p is reachable, or empty when only the organization's
// own status page servers serve it, at an address the platform does not
// know.
func (s *Server) pageURL(p store.StatusPage, ownServers bool) string {
if p.CustomDomain != nil && p.DomainVerifiedAt != nil { if p.CustomDomain != nil && p.DomainVerifiedAt != nil {
return "https://" + *p.CustomDomain + "/" return "https://" + *p.CustomDomain + "/"
} }
if ownServers {
return ""
}
return strings.TrimSuffix(s.cfg.StatusPageURL, "/") + "/" + p.Slug return strings.TrimSuffix(s.cfg.StatusPageURL, "/") + "/" + p.Slug
} }
func (s *Server) statusPagesView(c *gin.Context, p *principal, page web.Page, me web.Me) (templ.Component, error) { func (s *Server) statusPagesView(c *gin.Context, p *principal, page web.Page, me web.Me) (templ.Component, error) {
ctx := c.Request.Context() ctx := c.Request.Context()
var rows []store.StatusPage var (
rows []store.StatusPage
own bool
)
err := s.db.Tx(ctx, p.scope(), func(q *store.Queries) error { err := s.db.Tx(ctx, p.scope(), func(q *store.Queries) error {
var err error var err error
rows, err = q.ListStatusPages(ctx) if rows, err = q.ListStatusPages(ctx); err != nil {
return err
}
own, err = q.OrgServesOwnPages(ctx, &p.Org.ID)
return err return err
}) })
if err != nil { if err != nil {
@@ -1034,7 +1300,7 @@ func (s *Server) statusPagesView(c *gin.Context, p *principal, page web.Page, me
} }
v.Pages = append(v.Pages, web.PageRow{ v.Pages = append(v.Pages, web.PageRow{
ID: r.ID.String(), Title: r.Title, Slug: r.Slug, Published: r.Published, ID: r.ID.String(), Title: r.Title, Slug: r.Slug, Published: r.Published,
URL: s.pageURL(r), Domain: deref(r.CustomDomain), Suspended: r.SuspendedAt != nil, URL: s.pageURL(r, own), Domain: deref(r.CustomDomain), Suspended: r.SuspendedAt != nil,
}) })
} }
return web.StatusPagesPage(page, me, v), nil return web.StatusPagesPage(page, me, v), nil
@@ -1052,6 +1318,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
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 {
var err error var err error
@@ -1067,7 +1334,10 @@ func (s *Server) statusPageEditor(c *gin.Context, p *principal, page web.Page, m
if orgGroups, err = q.ListGroups(ctx); err != nil { if orgGroups, err = q.ListGroups(ctx); err != nil {
return err return err
} }
monitors, err = q.ListMonitors(ctx) if monitors, err = q.ListMonitors(ctx, p.Org.ID); err != nil {
return err
}
own, err = q.OrgServesOwnPages(ctx, &p.Org.ID)
return err return err
}) })
if errors.Is(err, pgx.ErrNoRows) { if errors.Is(err, pgx.ErrNoRows) {
@@ -1076,18 +1346,28 @@ func (s *Server) statusPageEditor(c *gin.Context, p *principal, page web.Page, m
if err != nil { if err != nil {
return nil, err return nil, err
} }
v := viewStatusPage(row) v := s.viewStatusPage(row)
e := web.PageEditor{ e := web.PageEditor{
ID: row.ID.String(), Title: row.Title, Slug: row.Slug, Description: row.Description, ID: row.ID.String(), Title: row.Title, Slug: row.Slug, Description: row.Description,
Published: row.Published, ShowDetails: row.ShowComponentDetails, Published: row.Published, ShowDetails: row.ShowComponentDetails,
Suspended: row.SuspendedAt != nil, SuspendedReason: row.SuspendedReason, Suspended: row.SuspendedAt != nil, SuspendedReason: row.SuspendedReason,
Accent: v.Theme.Accent, LogoURL: v.Theme.LogoURL, CSS: v.Theme.CSS, Accent: v.Theme.Accent, LogoURL: v.Theme.LogoURL, CSS: v.Theme.CSS,
URL: s.pageURL(row), Domain: deref(row.CustomDomain), DomainVerified: v.DomainVerified, URL: s.pageURL(row, own), OwnServers: own, Domain: deref(row.CustomDomain), DomainVerified: v.DomainVerified,
HasOrgGroups: len(orgGroups) > 0, HasOrgGroups: len(orgGroups) > 0,
} }
if v.DomainRecord != nil { if v.DomainRecord != nil {
e.RecordName, e.RecordValue = v.DomainRecord.Name, v.DomainRecord.Value e.RecordName, e.RecordValue = v.DomainRecord.Name, v.DomainRecord.Value
} }
e.DomainChangesPerDay = domainChangesPerDay
e.MonitorLimit = s.orgLimits(c.Request.Context(), p.Org).MonitorsPerPage
if v.CNAMERecord != nil {
e.CNAMEValue = v.CNAMERecord.Value
}
e.VerifiedBy = deref(row.DomainVerifyMethod)
if f := row.DomainFailingSince; f != nil {
e.MissingSince = f.Local().Format("2006-01-02 15:04")
e.SwitchOffAt = f.Add(domainGrace).Local().Format("2006-01-02 15:04")
}
newPageGroupTree(pageGroups).walk(func(g store.StatusPageGroup, depth int) { newPageGroupTree(pageGroups).walk(func(g store.StatusPageGroup, depth int) {
var parentID string var parentID string
if g.ParentID != nil { if g.ParentID != nil {
@@ -1285,7 +1565,7 @@ func (s *Server) regionHistory(ctx context.Context, p *principal, d monitorData,
Name: d.regionNameString(r), Name: d.regionNameString(r),
Bars: web.UptimeBars(byRegion[r], d.now, rng.Bucket, rng.Bars(), rng.Layout), Bars: web.UptimeBars(byRegion[r], d.now, rng.Bucket, rng.Bars(), rng.Layout),
Uptime: "–", Uptime: "–",
Enough: web.HasEnoughData(d.firstRegion[m.ID][r], d.now, rng.Window), Enough: web.HasEnoughData(d.firstRegion[r], d.now, rng.Window),
} }
if u := web.Uptime(byRegion[r]); u >= 0 { if u := web.Uptime(byRegion[r]); u >= 0 {
h.Uptime = web.PercentPrecise(u) h.Uptime = web.PercentPrecise(u)
+161
View File
@@ -0,0 +1,161 @@
package api_test
import (
"net/http"
"strings"
"testing"
)
func TestDashboardFiltersByStatus(t *testing.T) {
e := newEnv(t)
_, region := e.platformChecker(t, uniq("eu-"))
owner := e.browser(t)
owner.signup("o@"+uniq("flt")+".test", uniq("flt-"))
create := func(name string) string {
t.Helper()
st, m := owner.do("POST", "/api/v1/org/monitors", map[string]any{"name": name, "type": "http", "target": "https://" + strings.ToLower(name) + ".test", "interval_seconds": 60, "regions": []string{region}})
if st != http.StatusCreated {
t.Fatalf("create %s = %d %v", name, st, m)
}
return m["id"].(string)
}
create("Alpha")
create("Beta")
gamma := create("Gamma")
owner.do("PUT", "/api/v1/org/monitors/"+gamma, map[string]any{"name": "Gamma", "type": "http", "target": "https://gamma.test", "interval_seconds": 60, "regions": []string{region}, "enabled": false})
_, _, all := owner.page("/")
for _, want := range []string{`href="/?status=unknown"`, `href="/?status=paused"`, "Show only the 2 monitors that are no data", "Show only the 1 monitor that is paused"} {
if !strings.Contains(all, want) {
t.Errorf("the dashboard lacks %q", want)
}
}
_, _, paused := owner.page("/?status=paused")
if !strings.Contains(paused, "Gamma") || strings.Contains(paused, "Alpha") || strings.Contains(paused, "Beta") {
t.Error("?status=paused does not show only the paused monitor")
}
// The active filter links back to all, and the search keeps it.
if !strings.Contains(paused, `aria-current="true"`) || !strings.Contains(paused, `title="Show all statuses"`) {
t.Error("the active filter is not marked")
}
if !strings.Contains(paused, `name="status" value="paused"`) {
t.Error("the search form drops the status filter")
}
_, _, both := owner.page("/?status=unknown&q=alp")
if !strings.Contains(both, "Alpha") || strings.Contains(both, "Beta") || strings.Contains(both, "Gamma") {
t.Error("status filter and search do not combine")
}
if _, _, none := owner.page("/?status=down"); !strings.Contains(none, "No monitor has this status right now.") {
t.Error("an empty filter does not say so")
}
// An unknown status shows everything.
if _, _, bogus := owner.page("/?status=bogus"); !strings.Contains(bogus, "Alpha") || !strings.Contains(bogus, "Gamma") {
t.Error("an unknown status filter hides monitors")
}
}
func TestSignupSendsSignedInUsersToTheMonitors(t *testing.T) {
e := newEnv(t)
visitor := e.browser(t)
if st, path, _ := visitor.page("/signup"); st != http.StatusOK || path != "/signup" {
t.Fatalf("signup for a visitor = %d at %s", st, path)
}
owner := e.browser(t)
owner.signup("o@"+uniq("su")+".test", uniq("su-"))
if st, path, html := owner.page("/signup"); st != http.StatusOK || path != "/" || !strings.Contains(html, "Monitors") {
t.Errorf("signup when signed in ended at %s (%d), want the monitor list", path, st)
}
}
func TestPageEditorOffersAddAndRemoveAll(t *testing.T) {
e := newEnv(t)
_, region := e.platformChecker(t, uniq("eu-"))
owner := e.browser(t)
owner.signup("o@"+uniq("pa")+".test", uniq("pa-"))
_, mon := owner.do("POST", "/api/v1/org/monitors", map[string]any{"name": "Shop", "type": "http", "target": "https://shop.test", "interval_seconds": 60, "regions": []string{region}})
shop := mon["id"].(string)
_, p := owner.do("POST", "/api/v1/org/statuspages", map[string]any{"slug": uniq("pa-"), "title": "Status"})
_, _, html := owner.page("/statuspages/" + p["id"].(string))
for _, want := range []string{`data-check-all="on"`, `data-check-all="off"`, "Add all", "Remove all"} {
if !strings.Contains(html, want) {
t.Errorf("the page editor lacks %q", want)
}
}
// Monitors not on the page get their fields from the template only
// when ticked, so thousands of them stay light.
if n := strings.Count(html, `data-field="label"`); n != 1 || !strings.Contains(html, "<template data-row-fields>") {
t.Errorf("the page editor renders %d label fields, want only the template's", n)
}
owner.do("PUT", "/api/v1/org/statuspages/"+p["id"].(string)+"/monitors", map[string]any{"monitors": []map[string]any{{"monitor_id": shop, "label": "Webshop"}}})
if _, _, html := owner.page("/statuspages/" + p["id"].(string)); strings.Count(html, `data-field="label"`) != 2 || !strings.Contains(html, `value="Webshop"`) {
t.Error("a monitor on the page lacks its fields")
}
}
func TestMonitorOrder(t *testing.T) {
e := newEnv(t)
_, region := e.platformChecker(t, uniq("eu-"))
owner := e.browser(t)
owner.signup("o@"+uniq("ord")+".test", uniq("ord-"))
ids := map[string]string{}
for _, n := range []string{"Alpha", "Bravo", "Charlie"} {
_, m := owner.do("POST", "/api/v1/org/monitors", map[string]any{"name": n, "type": "http", "target": "https://" + strings.ToLower(n) + ".test", "interval_seconds": 60, "regions": []string{region}})
ids[n] = m["id"].(string)
}
order := func(html string, names ...string) bool {
last := -1
for _, n := range names {
i := strings.Index(html, ">"+n+"<")
if i < last || i < 0 {
return false
}
last = i
}
return true
}
// Without an order of its own, by name.
if _, _, html := owner.page("/"); !order(html, "Alpha", "Bravo", "Charlie") {
t.Error("monitors without positions are not by name")
}
st, body := owner.do("PUT", "/api/v1/org/monitors/order", map[string]any{"monitor_ids": []string{ids["Charlie"], ids["Alpha"]}})
if st != http.StatusNoContent {
t.Fatalf("order = %d %v", st, body)
}
// Positioned ones first, in their order; the rest after, by name.
_, _, html := owner.page("/")
if !order(html, "Charlie", "Alpha", "Bravo") {
t.Error("the list does not follow the organization's order")
}
if !strings.Contains(html, "?arrange=1") || !strings.Contains(html, "?sort=name") {
t.Error("the dashboard offers neither arranging nor sorting")
}
if _, _, arr := owner.page("/?arrange=1"); !strings.Contains(arr, `data-sortable="/org/monitors/order"`) || !strings.Contains(arr, `data-sort-id="`+ids["Charlie"]+`"`) {
t.Error("arranging does not show the sortable list")
}
// Sorting by name is remembered until changed.
if _, _, byName := owner.page("/?sort=name"); !order(byName, "Alpha", "Bravo", "Charlie") {
t.Error("?sort=name does not sort by name")
}
if _, _, again := owner.page("/"); !order(again, "Alpha", "Bravo", "Charlie") || strings.Contains(again, "?arrange=1") {
t.Error("the sort order is not remembered, or arranging is offered outside the own order")
}
owner.page("/?sort=custom")
// Unknown and duplicate monitors are refused, and nothing changes.
st, body = owner.do("PUT", "/api/v1/org/monitors/order", map[string]any{"monitor_ids": []string{ids["Bravo"], "00000000-0000-0000-0000-000000000001"}})
expect(t, "unknown monitor", st, body, http.StatusUnprocessableEntity, "invalid_monitor")
st, body = owner.do("PUT", "/api/v1/org/monitors/order", map[string]any{"monitor_ids": []string{ids["Bravo"], ids["Bravo"]}})
expect(t, "duplicate monitor", st, body, http.StatusUnprocessableEntity, "invalid_monitor")
if _, _, html := owner.page("/"); !order(html, "Charlie", "Alpha", "Bravo") {
t.Error("a refused order changed the list")
}
// Another organization cannot touch them.
other := e.browser(t)
other.signup("x@"+uniq("ord")+".test", uniq("ord-"))
st, body = other.do("PUT", "/api/v1/org/monitors/order", map[string]any{"monitor_ids": []string{ids["Alpha"]}})
expect(t, "another organization's monitor", st, body, http.StatusUnprocessableEntity, "invalid_monitor")
}
+176
View File
@@ -0,0 +1,176 @@
package api
import (
"context"
"crypto/sha256"
"encoding/base32"
"net"
"slices"
"strings"
"time"
"github.com/google/uuid"
"git.zb-server.de/ZB-Server/uptimesebi/internal/notify"
"git.zb-server.de/ZB-Server/uptimesebi/internal/store"
"git.zb-server.de/ZB-Server/uptimesebi/internal/tenant"
)
// A custom domain proves it belongs to its page in one of two ways:
//
// - a CNAME to <label>.<status page host>, where the label is unique to
// the page. The platform's status page host has a wildcard record, so
// the CNAME also routes the domain; one record does both. A CNAME to
// the shared host alone would not do: it proves the domain points at
// the platform, not which organization put it there.
// - the TXT record _uptimesebi.<domain>, for domains whose CNAME cannot be
// seen: behind a proxy such as Cloudflare's, or a domain without a
// subdomain using ALIAS or CNAME flattening.
//
// The domain watch looks for them on its own after a domain is set, and
// checks verified domains daily. One whose record has been missing for
// domainGrace is switched off, so a record left behind after a page is
// gone or moved cannot be claimed by anybody else.
const (
domainWatchEvery = time.Minute
domainGrace = 7 * 24 * time.Hour
keyDomainWatch = "domainwatch:lock"
)
// lookupCNAME is replaced in tests.
var lookupCNAME = net.DefaultResolver.LookupCNAME
var labelEncoding = base32.NewEncoding("abcdefghijklmnopqrstuvwxyz234567").WithPadding(base32.NoPadding)
// cnameLabel is the page's label below the status page host, derived from
// its domain token.
func cnameLabel(token string) string {
sum := sha256.Sum256([]byte("cname\x00" + token))
return "p" + labelEncoding.EncodeToString(sum[:10])
}
// cnameFor is the CNAME target of the page with token, or empty when the
// platform's status page host is not known.
func (s *Server) cnameFor(token string) string {
host := s.cnameTarget()
if host == "" {
return ""
}
return cnameLabel(token) + "." + host
}
// checkDomain looks for the records proving domain belongs to the page
// with token and returns "cname", "txt" or "" for neither.
func (s *Server) checkDomain(ctx context.Context, domain, token string) string {
if target := s.cnameFor(token); target != "" {
if c, err := lookupCNAME(ctx, domain); err == nil && strings.EqualFold(strings.TrimSuffix(c, "."), target) {
return "cname"
}
}
if records, err := lookupTXT(ctx, verifyPrefix+domain); err == nil && slices.Contains(records, token) {
return "txt"
}
return ""
}
// RunDomainWatch checks custom domains until ctx ends. Replicas take
// turns through a lock in Redis.
func (s *Server) RunDomainWatch(ctx context.Context) {
tick := time.NewTicker(domainWatchEvery)
defer tick.Stop()
for {
if ok, err := s.rdb.SetNX(ctx, keyDomainWatch, 1, domainWatchEvery-5*time.Second).Result(); err == nil && ok {
if err := s.WatchDomains(ctx, time.Now()); err != nil && ctx.Err() == nil {
s.log.WarnContext(ctx, "checking custom domains failed", "error", err)
}
}
select {
case <-ctx.Done():
return
case <-tick.C:
}
}
}
// WatchDomains checks the domains that are due once.
func (s *Server) WatchDomains(ctx context.Context, now time.Time) error {
return s.watchDomains(ctx, now, nil)
}
// watchDomains is WatchDomains limited to the page only, unless it is nil.
func (s *Server) watchDomains(ctx context.Context, now time.Time, only *uuid.UUID) error {
var due []store.DomainsToCheckRow
if err := s.db.Tx(ctx, tenant.System(), func(q *store.Queries) error {
var err error
due, err = q.DomainsToCheck(ctx, store.DomainsToCheckParams{Now: now, PageID: only})
return err
}); err != nil {
return err
}
for _, d := range due {
if err := s.watchDomain(ctx, d, now); err != nil {
return err
}
}
return nil
}
func (s *Server) watchDomain(ctx context.Context, d store.DomainsToCheckRow, now time.Time) error {
method := s.checkDomain(ctx, d.Domain, d.DomainToken)
var (
failing *time.Time
off bool
)
err := s.db.Tx(ctx, tenant.System(), func(q *store.Queries) error {
if method != "" {
return q.MarkDomainVerified(ctx, store.MarkDomainVerifiedParams{ID: d.ID, Now: now, Method: method})
}
var err error
if failing, err = q.MarkDomainUnconfirmed(ctx, store.MarkDomainUnconfirmedParams{ID: d.ID, Now: now}); err != nil || failing == nil {
return err
}
if now.Sub(*failing) >= domainGrace {
off = true
return q.UnverifyDomain(ctx, d.ID)
}
return nil
})
if err != nil {
return err
}
switch {
case method != "" && d.DomainVerifiedAt == nil:
s.log.InfoContext(ctx, "custom domain verified", "page", d.ID, "domain", d.Domain, "method", method)
case off:
s.log.InfoContext(ctx, "custom domain switched off: its record is gone", "page", d.ID, "domain", d.Domain)
s.mailDomain(ctx, d, "email.domain_off", now)
case failing != nil && d.DomainFailingSince == nil:
s.log.InfoContext(ctx, "custom domain record missing", "page", d.ID, "domain", d.Domain)
s.mailDomain(ctx, d, "email.domain_missing", now.Add(domainGrace))
}
return nil
}
// mailDomain tells the organization's owners about d.
func (s *Server) mailDomain(ctx context.Context, d store.DomainsToCheckRow, kind string, at time.Time) {
if s.smtp == nil {
return
}
var to []string
if err := s.db.Tx(ctx, tenant.System(), func(q *store.Queries) error {
var err error
to, err = q.OrgOwnerEmails(ctx, d.OrgID)
return err
}); err != nil || len(to) == 0 {
return
}
l := s.catalog.Match("")
data := map[string]any{
"Domain": d.Domain, "Page": d.Title, "Link": s.ticketLink("/statuspages/" + d.ID.String()),
"Date": at.UTC().Format("2006-01-02 15:04 MST"),
}
if err := s.smtp.Send(ctx, notify.Mail{To: to, Subject: l.T(kind+".subject", data), Body: l.T(kind+".body", data)}); err != nil {
s.log.WarnContext(ctx, "mail about a custom domain failed", "page", d.ID, "error", err)
}
}
+205
View File
@@ -0,0 +1,205 @@
package api_test
import (
"context"
"errors"
"net/http"
"strings"
"sync"
"testing"
"time"
"github.com/google/uuid"
"github.com/jackc/pgx/v5"
"git.zb-server.de/ZB-Server/uptimesebi/internal/api"
"git.zb-server.de/ZB-Server/uptimesebi/internal/config"
"git.zb-server.de/ZB-Server/uptimesebi/internal/notify/notifytest"
)
// fakeDNS answers CNAME lookups from a map, and TXT lookups with nothing.
type fakeDNS struct {
mu sync.Mutex
cname map[string]string
}
func (d *fakeDNS) set(name, target string) {
d.mu.Lock()
defer d.mu.Unlock()
if target == "" {
delete(d.cname, name)
} else {
d.cname[name] = target
}
}
func useFakeDNS(t *testing.T) *fakeDNS {
d := &fakeDNS{cname: map[string]string{}}
savedC, savedT := *api.LookupCNAME, *api.LookupTXT
t.Cleanup(func() { *api.LookupCNAME, *api.LookupTXT = savedC, savedT })
*api.LookupCNAME = func(_ context.Context, name string) (string, error) {
d.mu.Lock()
defer d.mu.Unlock()
if c, ok := d.cname[name]; ok {
return c, nil
}
return "", errors.New("no such host")
}
*api.LookupTXT = func(context.Context, string) ([]string, error) { return nil, errors.New("no such record") }
return d
}
func TestCustomDomainByCNAME(t *testing.T) {
mail := notifytest.NewSMTP(t)
e := newEnvWith(t, func(c *config.API) {
c.SMTPURL, c.SignupVerify = mail.URL(), "off"
c.StatusPageURL = "https://status.platform.test"
})
ctx := context.Background()
dns := useFakeDNS(t)
platform := e.statuspageClient(t, nil)
newPage := func(b *browser) uuid.UUID {
slug := uniq("cn-")
_, p := b.do("POST", "/api/v1/org/statuspages", map[string]any{"slug": slug, "title": "Shop status"})
b.do("PUT", "/api/v1/org/statuspages/"+p["id"].(string), map[string]any{"slug": slug, "title": "Shop status", "published": true})
return uuid.MustParse(p["id"].(string))
}
setDomain := func(b *browser, id uuid.UUID, domain string) string {
t.Helper()
st, body := b.do("PUT", "/api/v1/org/statuspages/"+id.String()+"/domain", map[string]any{"domain": domain})
if st != http.StatusOK {
t.Fatalf("set domain = %d %v", st, body)
}
rec, _ := body["cname_record"].(map[string]any)
if rec == nil || rec["name"] != domain {
t.Fatalf("cname_record = %v", body["cname_record"])
}
return rec["value"].(string)
}
served := func(domain string) bool {
_, err := platform.Page(ctx, domain, "")
return err == nil
}
a := e.browser(t)
aEmail := "a@" + uniq("cn") + ".test"
a.signup(aEmail, uniq("cn-"))
pageA := newPage(a)
domain := uniq("status") + ".shop.test"
target := setDomain(a, pageA, domain)
if !strings.HasSuffix(target, ".status.platform.test") || len(target) < 30 {
t.Errorf("CNAME target %q is not unique to the page below the status host", target)
}
if _, _, html := a.page("/statuspages/" + pageA.String()); !strings.Contains(html, target+".") || !strings.Contains(html, "Check now") {
t.Error("the editor does not show the page's CNAME record")
}
// A CNAME to the shared host alone proves nothing.
now := time.Now()
dns.set(domain, "status.platform.test.")
if err := e.api.WatchDomainOf(ctx, now, pageA); err != nil {
t.Fatal(err)
}
if served(domain) {
t.Fatal("a CNAME to the shared host verified the domain")
}
// The page's own target verifies it, without anybody pressing a button.
dns.set(domain, strings.ToUpper(target)+".")
if err := e.api.WatchDomainOf(ctx, now.Add(time.Minute), pageA); err != nil {
t.Fatal(err)
}
if !served(domain) {
t.Fatal("the watch did not verify the domain by its CNAME")
}
if _, _, html := a.page("/statuspages/" + pageA.String()); !strings.Contains(html, "verified by its CNAME record") {
t.Error("the editor does not say how the domain was verified")
}
// Another organization taking the domain over, while the CNAME still
// points at the first page, gets nowhere.
a.do("PUT", "/api/v1/org/statuspages/"+pageA.String()+"/domain", map[string]any{"domain": ""})
b := e.browser(t)
b.signup("b@"+uniq("cn")+".test", uniq("cn-"))
pageB := newPage(b)
setDomain(b, pageB, domain)
if err := e.api.WatchDomainOf(ctx, now.Add(2*time.Minute), pageB); err != nil {
t.Fatal(err)
}
if st, _ := b.do("POST", "/api/v1/org/statuspages/"+pageB.String()+"/domain/verify", nil); st != http.StatusUnprocessableEntity || served(domain) {
t.Fatalf("a record left by another page verified the domain (verify = %d)", st)
}
b.do("PUT", "/api/v1/org/statuspages/"+pageB.String()+"/domain", map[string]any{"domain": ""})
// Once verified, the record is checked daily. Gone, the owners are told
// and, a week later, the domain is switched off.
setDomain(a, pageA, domain)
if st, body := a.do("POST", "/api/v1/org/statuspages/"+pageA.String()+"/domain/verify", nil); st != http.StatusNoContent {
t.Fatalf("verify = %d %v", st, body)
}
dns.set(domain, "")
day := now.Add(25 * time.Hour)
if err := e.api.WatchDomainOf(ctx, day, pageA); err != nil {
t.Fatal(err)
}
waitFor(t, 5*time.Second, "a mail that the record is gone", func() bool {
return mailedTo(mail, aEmail, "is gone", domain)
})
if !served(domain) {
t.Error("the domain was switched off at once")
}
if _, _, html := a.page("/statuspages/" + pageA.String()); !strings.Contains(html, "has not been found since") {
t.Error("the editor does not warn about the missing record")
}
if err := e.api.WatchDomainOf(ctx, day.Add(8*24*time.Hour), pageA); err != nil {
t.Fatal(err)
}
if served(domain) {
t.Error("the domain is still served a week after its record went")
}
waitFor(t, 5*time.Second, "a mail that the domain was switched off", func() bool {
return mailedTo(mail, aEmail, "switched off", domain)
})
}
func TestDomainsVerifiedBeforeAreNotCheckedAgain(t *testing.T) {
e := newEnvWith(t, func(c *config.API) { c.StatusPageURL = "https://status.platform.test" })
ctx := context.Background()
useFakeDNS(t)
owner := e.browser(t)
owner.signup("o@"+uniq("old")+".test", uniq("old-"))
slug := uniq("old-")
_, p := owner.do("POST", "/api/v1/org/statuspages", map[string]any{"slug": slug, "title": "Status"})
id := p["id"].(string)
owner.do("PUT", "/api/v1/org/statuspages/"+id, map[string]any{"slug": slug, "title": "Status", "published": true})
domain := uniq("old") + ".example.test"
owner.do("PUT", "/api/v1/org/statuspages/"+id+"/domain", map[string]any{"domain": domain})
if err := e.asSystem(t, func(tx pgx.Tx) error {
_, err := tx.Exec(ctx, `UPDATE status_pages SET domain_verified_at = now() - interval '1 year', domain_set_at = now() - interval '1 year' WHERE id = $1`, id)
return err
}); err != nil {
t.Fatal(err)
}
if err := e.api.WatchDomainOf(ctx, time.Now().Add(30*24*time.Hour), uuid.MustParse(id)); err != nil {
t.Fatal(err)
}
if _, err := e.statuspageClient(t, nil).Page(ctx, domain, ""); err != nil {
t.Errorf("a domain verified before the checks was switched off: %v", err)
}
}
func mailedTo(mail *notifytest.SMTP, to string, want ...string) bool {
for _, m := range mail.Messages() {
if !strings.Contains(strings.Join(m.To, ","), to) {
continue
}
ok := true
for _, w := range want {
ok = ok && strings.Contains(m.Data, w)
}
if ok {
return true
}
}
return false
}
+34
View File
@@ -0,0 +1,34 @@
package api_test
import (
"context"
"testing"
"time"
"github.com/google/uuid"
"git.zb-server.de/ZB-Server/uptimesebi/internal/agentapi"
)
func TestLongPollsEndWhenDraining(t *testing.T) {
e := newEnv(t)
tok, _ := e.platformChecker(t, uniq("eu-"))
drain := make(chan struct{})
e.api.EndLongPollsOn(drain)
client := agentapi.NewClient(e.srv.URL, tok, uuid.New(), "test").WithHTTPClient(e.srv.Client())
go func() { time.Sleep(300 * time.Millisecond); close(drain) }()
start := time.Now()
jobs, err := client.Jobs(context.Background(), 10, 20*time.Second)
if err != nil || len(jobs) != 0 {
t.Fatalf("Jobs() while draining = %v, %v; want no jobs and no error", jobs, err)
}
if took := time.Since(start); took > 3*time.Second {
t.Errorf("a long poll ran %v after draining began, want it to end within about a second", took)
}
// Once draining, polls answer at once.
start = time.Now()
if _, err := client.Jobs(context.Background(), 10, 20*time.Second); err != nil || time.Since(start) > 2*time.Second {
t.Errorf("a poll on a draining instance took %v (%v)", time.Since(start), err)
}
}
+21
View File
@@ -1,5 +1,12 @@
package api package api
import (
"context"
"time"
"github.com/google/uuid"
)
// LookupTXT lets tests replace DNS lookups for domain verification. // LookupTXT lets tests replace DNS lookups for domain verification.
var LookupTXT = &lookupTXT var LookupTXT = &lookupTXT
@@ -17,3 +24,17 @@ func DocumentedRoutes() []string {
// OpenAPI builds the OpenAPI document. // OpenAPI builds the OpenAPI document.
func OpenAPI() map[string]any { return buildOpenAPI("https://uptime.example") } func OpenAPI() map[string]any { return buildOpenAPI("https://uptime.example") }
// WatchRegionsOf runs the region watch for the regions given only, so
// tests are not slowed down by the regions other tests left behind.
func (s *Server) WatchRegionsOf(ctx context.Context, now time.Time, ids ...uuid.UUID) error {
return s.watchRegions(ctx, now, ids)
}
// LookupCNAME lets tests replace DNS lookups for domain verification.
var LookupCNAME = &lookupCNAME
// WatchDomainOf runs the domain watch for one page only.
func (s *Server) WatchDomainOf(ctx context.Context, now time.Time, page uuid.UUID) error {
return s.watchDomains(ctx, now, &page)
}
+33 -2
View File
@@ -32,9 +32,24 @@ type accountExport struct {
Identities []exportIdentity `json:"sso_identities"` Identities []exportIdentity `json:"sso_identities"`
Tokens []exportToken `json:"api_tokens"` Tokens []exportToken `json:"api_tokens"`
Consents []exportConsent `json:"consents"` Consents []exportConsent `json:"consents"`
Support []exportTicket `json:"support_tickets"`
Activity []exportActivity `json:"activity"` Activity []exportActivity `json:"activity"`
} }
type exportTicket struct {
Subject string `json:"subject"`
Status string `json:"status"`
CreatedAt time.Time `json:"created_at"`
Messages []exportTicketMessage `json:"messages"`
}
// exportTicketMessage leaves out which admin answered: that is about them.
type exportTicketMessage struct {
Time time.Time `json:"time"`
FromStaff bool `json:"from_staff"`
Body string `json:"body"`
}
// exportConsent is an accepted version of the privacy policy or terms. // exportConsent is an accepted version of the privacy policy or terms.
type exportConsent struct { type exportConsent struct {
Kind string `json:"kind"` Kind string `json:"kind"`
@@ -156,6 +171,22 @@ func (s *Server) buildAccountExport(ctx context.Context, userID uuid.UUID) (acco
ExpiresAt: t.ExpiresAt, LastUsedAt: t.LastUsedAt, CreatedAt: t.CreatedAt, ExpiresAt: t.ExpiresAt, LastUsedAt: t.LastUsedAt, CreatedAt: t.CreatedAt,
}) })
} }
tickets, err := q.ListUserSupportTickets(ctx, userID)
if err != nil {
return err
}
x.Support = []exportTicket{}
for _, t := range tickets {
msgs, err := q.SupportMessages(ctx, t.ID)
if err != nil {
return err
}
et := exportTicket{Subject: t.Subject, Status: t.Status, CreatedAt: t.CreatedAt, Messages: []exportTicketMessage{}}
for _, m := range msgs {
et.Messages = append(et.Messages, exportTicketMessage{Time: m.CreatedAt, FromStaff: m.FromStaff, Body: m.Body})
}
x.Support = append(x.Support, et)
}
events, err := q.UserAuditEvents(ctx, &userID) events, err := q.UserAuditEvents(ctx, &userID)
if err != nil { if err != nil {
return err return err
@@ -441,7 +472,7 @@ func (s *Server) buildOrgExport(ctx context.Context, p *principal) (orgExport, e
for _, a := range alertAssignments { for _, a := range alertAssignments {
alertGroupsByMonitor[a.MonitorID] = append(alertGroupsByMonitor[a.MonitorID], a.GroupID) alertGroupsByMonitor[a.MonitorID] = append(alertGroupsByMonitor[a.MonitorID], a.GroupID)
} }
regionRows, err := q.AllMonitorRegions(ctx) regionRows, err := q.AllMonitorRegions(ctx, p.Org.ID)
if err != nil { if err != nil {
return err return err
} }
@@ -449,7 +480,7 @@ func (s *Server) buildOrgExport(ctx context.Context, p *principal) (orgExport, e
for _, r := range regionRows { for _, r := range regionRows {
regions[r.MonitorID] = append(regions[r.MonitorID], r.RegionID) regions[r.MonitorID] = append(regions[r.MonitorID], r.RegionID)
} }
monitors, err := q.ListMonitors(ctx) monitors, err := q.ListMonitors(ctx, p.Org.ID)
if err != nil { if err != nil {
return err return err
} }
+1 -2
View File
@@ -93,8 +93,7 @@ func (s *Server) recordPassive(ctx context.Context, region string, id, org uuid.
row.Error = ptr(truncateValid(msg, 500)) row.Error = ptr(truncateValid(msg, 500))
} }
err := s.db.Tx(ctx, tenant.System(), func(q *store.Queries) error { err := s.db.Tx(ctx, tenant.System(), func(q *store.Queries) error {
_, err := q.InsertCheckResults(ctx, []store.InsertCheckResultsParams{row}) return insertResults(ctx, q, []store.InsertCheckResultsParams{row})
return err
}) })
if err != nil { if err != nil {
return err return err
+69
View File
@@ -0,0 +1,69 @@
package api_test
import (
"context"
"encoding/json"
"strings"
"testing"
"time"
"github.com/google/uuid"
"github.com/jackc/pgx/v5"
"git.zb-server.de/ZB-Server/uptimesebi/internal/store"
)
// TestLatestResultsKeepTheNewest checks that a result arriving late does
// not replace a newer one, and that a batch keeps its newest per region.
func TestLatestResultsKeepTheNewest(t *testing.T) {
e := newEnv(t)
_, region := e.platformChecker(t, uniq("eu-"))
owner := e.browser(t)
owner.signup("o@"+uniq("lr")+".test", uniq("lr-"))
_, m := owner.do("POST", "/api/v1/org/monitors", map[string]any{"name": "Shop", "type": "http", "target": "https://shop.test", "interval_seconds": 60, "regions": []string{region}})
id, org := uuid.MustParse(m["id"].(string)), uuid.MustParse(owner.orgID())
now := time.Now().Truncate(time.Millisecond)
upsert := func(rows ...map[string]any) {
t.Helper()
for _, r := range rows {
r["monitor_id"], r["org_id"], r["region"] = id, org, region
}
b, _ := json.Marshal(rows)
if err := e.asSystem(t, func(tx pgx.Tx) error { return store.New(tx).UpsertLatestResults(context.Background(), b) }); err != nil {
t.Fatal(err)
}
}
latest := func() (time.Time, bool) {
t.Helper()
var (
at time.Time
ok bool
)
if err := e.asSystem(t, func(tx pgx.Tx) error {
return tx.QueryRow(context.Background(), `SELECT time, ok FROM latest_results WHERE monitor_id = $1`, id).Scan(&at, &ok)
}); err != nil {
t.Fatal(err)
}
return at, ok
}
upsert(map[string]any{"time": now.Add(-time.Minute), "ok": true}, map[string]any{"time": now, "ok": false, "error": "down"})
if at, ok := latest(); !at.Equal(now) || ok {
t.Errorf("after a batch latest = %v ok=%t, want the newest (%v, failed)", at, ok, now)
}
upsert(map[string]any{"time": now.Add(-30 * time.Second), "ok": true})
if at, _ := latest(); !at.Equal(now) {
t.Errorf("a late result replaced the newest: %v", at)
}
upsert(map[string]any{"time": now.Add(time.Minute), "ok": true, "latency_ms": 12})
if at, ok := latest(); !at.Equal(now.Add(time.Minute)) || !ok {
t.Errorf("a newer result was not kept: %v ok=%t", at, ok)
}
_, body := owner.do("GET", "/api/v1/org/monitors", nil)
if got := body["monitors"].([]any)[0].(map[string]any)["latest"].([]any); len(got) != 1 {
t.Errorf("the API lists %d latest results, want 1", len(got))
}
if _, _, html := owner.page("/monitors/" + id.String()); !strings.Contains(html, "12 ms") {
t.Error("the monitor page does not show the latest result")
}
}
+11 -3
View File
@@ -36,6 +36,8 @@ type Limits struct {
OwnRegionsCount bool `json:"own_regions_count"` OwnRegionsCount bool `json:"own_regions_count"`
// OrgsPerAccount limits the organizations an account owns. // OrgsPerAccount limits the organizations an account owns.
OrgsPerAccount int `json:"orgs_per_account"` OrgsPerAccount int `json:"orgs_per_account"`
// MonitorsPerPage limits the monitors one status page shows.
MonitorsPerPage int `json:"monitors_per_page"`
} }
func (s *Server) defaultLimits() Limits { func (s *Server) defaultLimits() Limits {
@@ -79,6 +81,7 @@ func (s *Server) orgLimits(ctx context.Context, org store.Org) Limits {
override(&l.Monitors, org.LimitMonitors) override(&l.Monitors, org.LimitMonitors)
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)
if org.LimitOwnRegionsCount != nil { if org.LimitOwnRegionsCount != nil {
l.OwnRegionsCount = *org.LimitOwnRegionsCount l.OwnRegionsCount = *org.LimitOwnRegionsCount
} }
@@ -189,6 +192,7 @@ 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"`
} }
func (s *Server) adminSetLimits(c *gin.Context) { func (s *Server) adminSetLimits(c *gin.Context) {
@@ -243,6 +247,7 @@ type orgLimitsRequest struct {
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"`
} }
func (s *Server) adminSetOrgLimits(c *gin.Context) { func (s *Server) adminSetOrgLimits(c *gin.Context) {
@@ -261,6 +266,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,
}) })
auditDetail(c, "slug", row.Slug) auditDetail(c, "slug", row.Slug)
return err return err
@@ -316,6 +322,7 @@ type orgLimitsView struct {
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"`
} }
type adminOwner struct { type adminOwner struct {
@@ -342,9 +349,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} o.Overrides = orgLimitsView{r.LimitMonitors, r.LimitStatusPages, r.LimitRegionsPerMonitor, r.LimitOwnRegionsCount, r.LimitMonitorsPerPage}
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})
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 {
@@ -403,7 +411,7 @@ func (s *Server) orgsView(c *gin.Context, pg pageReq) (web.OrgsView, error) {
ID: o.ID.String(), Name: o.Name, Slug: o.Slug, Created: o.Created, Suspended: state(o.SuspendedAt, o.Reason), ID: o.ID.String(), Name: o.Name, Slug: o.Slug, Created: o.Created, Suspended: state(o.SuspendedAt, o.Reason),
Monitors: o.Usage.Monitors, StatusPages: o.Usage.StatusPages, Limits: webLimits(o.Limits), 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), RegionsOverride: optInt(o.Overrides.RegionsPerMonitor), PerPageOverride: optInt(o.Overrides.MonitorsPerPage),
} }
if o.Overrides.OwnRegionsCount != nil { if o.Overrides.OwnRegionsCount != nil {
row.OwnRegionsOverride = strconv.FormatBool(*o.Overrides.OwnRegionsCount) row.OwnRegionsOverride = strconv.FormatBool(*o.Overrides.OwnRegionsCount)
+65
View File
@@ -155,3 +155,68 @@ func TestLimits(t *testing.T) {
t.Error("the organization settings lack the usage") t.Error("the organization settings lack the usage")
} }
} }
func TestMonitorsPerStatusPageLimit(t *testing.T) {
e := newEnv(t)
ctx := context.Background()
reset := func() {
_ = e.asSystem(t, func(tx pgx.Tx) error {
_, err := tx.Exec(ctx, `DELETE FROM platform_settings WHERE key = 'limits'`)
return err
})
}
reset()
t.Cleanup(reset)
admin := e.browser(t)
admin.signup("admin@"+uniq("mpp")+".test", uniq("mpp-admin-"))
if err := tenant.New(e.dbPool).Tx(ctx, tenant.Global(), func(q *store.Queries) error {
return q.MakeAdmin(ctx, admin.userIDSelf())
}); err != nil {
t.Fatal(err)
}
if st, body := admin.do("PUT", "/api/v1/admin/limits", map[string]any{"monitors_per_page": 2}); st != http.StatusNoContent {
t.Fatalf("set defaults = %d %v", st, body)
}
owner := e.browser(t)
owner.signup("o@"+uniq("mpp")+".test", uniq("mpp-"))
var ids []map[string]any
for range 3 {
_, m := owner.do("POST", "/api/v1/org/monitors", map[string]any{"name": "hb", "type": "heartbeat", "interval_seconds": 3600})
ids = append(ids, map[string]any{"monitor_id": m["id"]})
}
_, page := owner.do("POST", "/api/v1/org/statuspages", map[string]any{"slug": uniq("mpp-"), "title": "Status"})
set := func(n int) (int, map[string]any) {
return owner.do("PUT", "/api/v1/org/statuspages/"+page["id"].(string)+"/monitors", map[string]any{"monitors": ids[:n]})
}
if st, body := set(2); st != http.StatusNoContent {
t.Fatalf("two monitors = %d %v", st, body)
}
st, body := set(3)
expect(t, "three monitors", st, body, http.StatusUnprocessableEntity, "page_monitor_limit")
if _, _, html := owner.page("/statuspages/" + page["id"].(string)); !strings.Contains(html, "at most 2 monitors") {
t.Error("the editor does not name the limit")
}
// An override for the organization raises it; lowered again, the page
// keeps its monitors but cannot grow.
org := owner.orgID()
if st, body := admin.do("PUT", "/api/v1/admin/orgs/"+org+"/limits", map[string]any{"monitors_per_page": 3}); st != http.StatusNoContent {
t.Fatalf("override = %d %v", st, body)
}
if st, body := set(3); st != http.StatusNoContent {
t.Fatalf("three monitors with the override = %d %v", st, body)
}
admin.do("PUT", "/api/v1/admin/orgs/"+org+"/limits", map[string]any{"monitors_per_page": 1})
if st, body := set(3); st != http.StatusNoContent {
t.Errorf("saving a page beyond a lowered limit = %d %v", st, body)
}
if st, body := set(2); st != http.StatusNoContent {
t.Errorf("shrinking a page beyond a lowered limit = %d %v", st, body)
}
st, body = set(3)
expect(t, "growing again beyond the lowered limit", st, body, http.StatusUnprocessableEntity, "page_monitor_limit")
if _, _, html := admin.page("/admin"); !strings.Contains(html, "Monitors per status page") {
t.Error("the admin page does not offer the limit")
}
}
+1 -1
View File
@@ -234,7 +234,7 @@ func (s *Server) loadMaintenanceScope(ctx context.Context, p *principal) (mainte
return ms, err return ms, err
} }
err = s.db.Tx(ctx, p.scope(), func(q *store.Queries) error { err = s.db.Tx(ctx, p.scope(), func(q *store.Queries) error {
rows, err := q.ListMonitors(ctx) rows, err := q.ListMonitors(ctx, p.Org.ID)
for _, m := range rows { for _, m := range rows {
ms.monitors[m.ID] = m ms.monitors[m.ID] = m
} }
+66
View File
@@ -0,0 +1,66 @@
package api
import (
"errors"
"net/http"
"github.com/gin-gonic/gin"
"github.com/google/uuid"
"github.com/jackc/pgx/v5"
"git.zb-server.de/ZB-Server/uptimesebi/internal/authz"
"git.zb-server.de/ZB-Server/uptimesebi/internal/store"
)
type monitorOrderRequest struct {
// MonitorIDs in the order wanted; usually the monitors of one group.
MonitorIDs []uuid.UUID `json:"monitor_ids" binding:"required,min=1,max=1000"`
}
// orderMonitors stores the organization's own order of the monitors given,
// which the monitor list follows when sorted by its own order. It needs
// write access to every one of them.
func (s *Server) orderMonitors(c *gin.Context) {
var req monitorOrderRequest
if !bind(c, &req) {
return
}
p := current(c)
ctx := c.Request.Context()
t, err := s.loadGroupTree(ctx, p.scope())
if err != nil {
internalError(c, err)
return
}
errDenied := errors.New("denied")
seen := map[uuid.UUID]bool{}
err = s.db.Tx(ctx, p.scope(), func(q *store.Queries) error {
for i, id := range req.MonitorIDs {
if seen[id] {
return pgx.ErrNoRows
}
seen[id] = true
m, err := q.GetMonitor(ctx, id)
if err != nil {
return err
}
if !canInGroup(p, authz.MonitorsWrite, t, m.GroupID) {
return errDenied
}
if _, err := q.SetMonitorPosition(ctx, store.SetMonitorPositionParams{ID: id, Position: new(int32(i))}); err != nil {
return err
}
}
return nil
})
switch {
case errors.Is(err, errDenied):
fail(c, http.StatusForbidden, "forbidden")
case errors.Is(err, pgx.ErrNoRows):
fail(c, http.StatusUnprocessableEntity, "invalid_monitor")
case err != nil:
internalError(c, err)
default:
c.Status(http.StatusNoContent)
}
}
+5 -9
View File
@@ -220,7 +220,7 @@ func (s *Server) listMonitors(c *gin.Context) {
for _, a := range assignments { for _, a := range assignments {
alertGroups[a.MonitorID] = append(alertGroups[a.MonitorID], a.GroupID) alertGroups[a.MonitorID] = append(alertGroups[a.MonitorID], a.GroupID)
} }
regions, err := q.AllMonitorRegions(ctx) regions, err := q.AllMonitorRegions(ctx, p.Org.ID)
if err != nil { if err != nil {
return err return err
} }
@@ -280,8 +280,7 @@ func (s *Server) createMonitor(c *gin.Context) {
if !s.validateMonitor(c, &req, t) { if !s.validateMonitor(c, &req, t) {
return return
} }
if !s.offered(ctx, p.Org, req.Type) { if failCheckType(c, s.checkTypeAllowed(ctx, p.Org, req.Type, "", req.Regions, nil, req.platform)) {
fail(c, http.StatusUnprocessableEntity, "check_type_disabled")
return return
} }
req.Target = passiveTarget(check.Type(req.Type), req.Target) req.Target = passiveTarget(check.Type(req.Type), req.Target)
@@ -403,8 +402,8 @@ func (s *Server) updateMonitor(c *gin.Context) {
if previous, err = q.MonitorRegions(ctx, id); err != nil { if previous, err = q.MonitorRegions(ctx, id); err != nil {
return err return err
} }
if old.Type != req.Type && !s.offered(ctx, p.Org, req.Type) { if err := s.checkTypeAllowed(ctx, p.Org, req.Type, old.Type, req.Regions, previous, req.platform); err != nil {
return errCheckTypeDisabled return err
} }
if err := checkRegions(s.orgLimits(ctx, p.Org), req.Regions, previous, req.platform); err != nil { if err := checkRegions(s.orgLimits(ctx, p.Org), req.Regions, previous, req.platform); err != nil {
return err return err
@@ -443,8 +442,7 @@ func (s *Server) updateMonitor(c *gin.Context) {
fail(c, http.StatusUnprocessableEntity, "invalid_alert_group") fail(c, http.StatusUnprocessableEntity, "invalid_alert_group")
return return
} }
if errors.Is(err, errCheckTypeDisabled) { if failCheckType(c, err) {
fail(c, http.StatusUnprocessableEntity, "check_type_disabled")
return return
} }
if failLimit(c, err) { if failLimit(c, err) {
@@ -611,5 +609,3 @@ func passiveRegion(t check.Type) string {
} }
return heartbeatRegion return heartbeatRegion
} }
var errCheckTypeDisabled = errors.New("api: check type switched off")
+17 -2
View File
@@ -46,6 +46,10 @@ func (s *Server) registerPages(r gin.IRouter) {
r.GET("/admin/status-pages", s.adminStatusPagesPage) r.GET("/admin/status-pages", s.adminStatusPagesPage)
r.GET("/admin/orgs", s.adminOrgsPage) r.GET("/admin/orgs", s.adminOrgsPage)
r.GET("/admin/legal", s.adminLegalPage) r.GET("/admin/legal", s.adminLegalPage)
r.GET("/admin/support", s.adminSupportPage)
r.GET("/admin/support/:id", s.adminSupportTicketPage)
r.GET("/support", s.supportPage)
r.GET("/support/:id", s.supportTicketPage)
r.GET("/settings/legal", s.orgPage("legal.org_title", authz.OrgManage, s.orgLegalView)) r.GET("/settings/legal", s.orgPage("legal.org_title", authz.OrgManage, s.orgLegalView))
r.GET("/incidents/:id", s.orgPage("incidents.title", authz.IncidentsRead, s.incidentDetailView)) r.GET("/incidents/:id", s.orgPage("incidents.title", authz.IncidentsRead, s.incidentDetailView))
r.GET("/settings/incident-statuses", s.orgPage("incident_statuses.title", authz.IncidentsRead, s.incidentStatusesView)) r.GET("/settings/incident-statuses", s.orgPage("incident_statuses.title", authz.IncidentsRead, s.incidentStatusesView))
@@ -118,6 +122,11 @@ func (s *Server) signupOptions(ctx context.Context) (bool, []web.IDPButton, erro
} }
func (s *Server) signupPage(c *gin.Context) { func (s *Server) signupPage(c *gin.Context) {
// Signed in already: straight to the monitors.
if auth.Current(c) != nil {
c.Redirect(http.StatusSeeOther, "/")
return
}
email, providers, err := s.signupOptions(c.Request.Context()) email, providers, err := s.signupOptions(c.Request.Context())
if err != nil { if err != nil {
internalError(c, err) internalError(c, err)
@@ -176,6 +185,7 @@ func (s *Server) consoleMe(c *gin.Context, sess *auth.Session) (web.Me, *princip
} }
me := toWebMe(m) me := toWebMe(m)
me.Can = map[string]bool{} me.Can = map[string]bool{}
me.Support = s.supportSettings(ctx).Enabled
if sess.OrgID == uuid.Nil { if sess.OrgID == uuid.Nil {
return me, nil, nil return me, nil, nil
} }
@@ -378,9 +388,14 @@ func (s *Server) orgSettingsView(c *gin.Context, p *principal, page web.Page, me
v.Usage = web.UsageView{Limits: webLimits(u.Limits), Monitors: u.Usage.Monitors, StatusPages: u.Usage.StatusPages} v.Usage = web.UsageView{Limits: webLimits(u.Limits), Monitors: u.Usage.Monitors, StatusPages: u.Usage.StatusPages}
off := s.disabledChecks(c.Request.Context()) off := s.disabledChecks(c.Request.Context())
for _, t := range check.Types { for _, t := range check.Types {
if !off[string(t)] { o := web.CheckTypeOption{Type: string(t), Enabled: !slices.Contains(p.Org.DisabledCheckTypes, string(t))}
v.CheckTypes = append(v.CheckTypes, web.CheckTypeOption{Type: string(t), Enabled: !slices.Contains(p.Org.DisabledCheckTypes, string(t))}) if off[string(t)] {
if check.Passive(t) {
continue
}
o.Note = "org.check_type_own_only"
} }
v.CheckTypes = append(v.CheckTypes, o)
} }
if p.Org.ApiTokenMaxDays != nil { if p.Org.ApiTokenMaxDays != nil {
v.TokenMaxDays = int(*p.Org.ApiTokenMaxDays) v.TokenMaxDays = int(*p.Org.ApiTokenMaxDays)
+164
View File
@@ -0,0 +1,164 @@
package api
import (
"context"
"errors"
"slices"
"time"
"github.com/google/uuid"
"github.com/redis/go-redis/v9"
"git.zb-server.de/ZB-Server/uptimesebi/internal/notify"
"git.zb-server.de/ZB-Server/uptimesebi/internal/store"
"git.zb-server.de/ZB-Server/uptimesebi/internal/tenant"
)
// A region whose checkers have all gone leaves its monitors unchecked:
// they neither go down nor alert. The region watch tells those who run the
// region, the platform's admins for platform regions and the owners for an
// organization's own, once it has had no live checker for
// UPTIME_REGION_ALERT_AFTER, and again when one is back. Every replica runs
// it; Redis decides which one sends.
const (
regionWatchEvery = 30 * time.Second
// regionWatchTTL bounds the state of a region; one dead for longer is
// announced again.
regionWatchTTL = 30 * 24 * time.Hour
)
func keyRegionDeadSince(id uuid.UUID) string { return "regionwatch:since:" + id.String() }
func keyRegionAlerted(id uuid.UUID) string { return "regionwatch:alerted:" + id.String() }
// RunRegionWatch watches the regions until ctx ends.
func (s *Server) RunRegionWatch(ctx context.Context) {
if s.cfg.RegionAlertAfter <= 0 {
return
}
tick := time.NewTicker(regionWatchEvery)
defer tick.Stop()
for {
if err := s.WatchRegions(ctx, time.Now()); err != nil && ctx.Err() == nil {
s.log.WarnContext(ctx, "watching regions failed", "error", err)
}
select {
case <-ctx.Done():
return
case <-tick.C:
}
}
}
// WatchRegions checks every region with checkers and enabled monitors once.
func (s *Server) WatchRegions(ctx context.Context, now time.Time) error {
return s.watchRegions(ctx, now, nil)
}
// watchRegions is WatchRegions limited to only, unless only is nil.
func (s *Server) watchRegions(ctx context.Context, now time.Time, only []uuid.UUID) error {
var regions []store.RegionsToWatchRow
if err := s.db.Tx(ctx, tenant.System(), func(q *store.Queries) error {
var err error
regions, err = q.RegionsToWatch(ctx)
return err
}); err != nil {
return err
}
for _, r := range regions {
if only != nil && !slices.Contains(only, r.ID) {
continue
}
live, err := s.sched.Instances(ctx, r.ID.String())
if err != nil {
return err
}
if live > 0 {
since, _ := s.rdb.GetDel(ctx, keyRegionDeadSince(r.ID)).Time()
// Only the replica that clears the alert announces the return.
if n, err := s.rdb.Del(ctx, keyRegionAlerted(r.ID)).Result(); err == nil && n > 0 {
s.mailRegion(ctx, r, since, now, false)
}
continue
}
if err := s.rdb.SetNX(ctx, keyRegionDeadSince(r.ID), now, regionWatchTTL).Err(); err != nil {
return err
}
since, err := s.rdb.Get(ctx, keyRegionDeadSince(r.ID)).Time()
if err != nil {
return err
}
if now.Sub(since) < s.cfg.RegionAlertAfter {
continue
}
if first, err := s.rdb.SetNX(ctx, keyRegionAlerted(r.ID), 1, regionWatchTTL).Result(); err == nil && first {
if !s.mailRegion(ctx, r, since, now, true) {
// Tried again on the next round.
s.rdb.Del(ctx, keyRegionAlerted(r.ID))
}
}
}
return nil
}
// regionsWithoutChecker returns since when each of ids has had no live
// checker, for those the watch found without one.
func (s *Server) regionsWithoutChecker(ctx context.Context, ids []uuid.UUID) map[uuid.UUID]time.Time {
out := map[uuid.UUID]time.Time{}
for _, id := range ids {
since, err := s.rdb.Get(ctx, keyRegionDeadSince(id)).Time()
if err == nil {
out[id] = since
} else if !errors.Is(err, redis.Nil) {
s.log.WarnContext(ctx, "reading region watch failed", "region", id, "error", err)
}
}
return out
}
// mailRegion tells the admins or the owners that r has no live checker
// since since, or, when down is false, that it has one again. It reports
// false if the mail could not be sent and should be tried again.
func (s *Server) mailRegion(ctx context.Context, r store.RegionsToWatchRow, since, now time.Time, down bool) bool {
if s.smtp == nil {
return true
}
var to []string
link := "/admin"
err := s.db.Tx(ctx, tenant.System(), func(q *store.Queries) error {
var err error
if r.OrgID == nil {
to, err = q.AdminEmails(ctx)
} else {
link = "/settings/regions"
to, err = q.OrgOwnerEmails(ctx, *r.OrgID)
}
return err
})
if err != nil || len(to) == 0 {
if err != nil {
s.log.WarnContext(ctx, "finding whom to tell about a region failed", "region", r.ID, "error", err)
return false
}
return true
}
l := s.catalog.Match("")
data := map[string]any{
"Region": r.Name, "Org": deref(r.OrgName), "Link": s.ticketLink(link),
"Since": since.UTC().Format("2006-01-02 15:04 MST"),
"Minutes": int(now.Sub(since).Minutes()),
}
kind := "email.region_back"
if down {
kind = "email.region_down"
}
if since.IsZero() {
data["Since"], data["Minutes"] = "–", 0
}
if err := s.smtp.Send(ctx, notify.Mail{To: to, Subject: l.T(kind+".subject", data), Body: l.T(kind+".body", data)}); err != nil {
s.log.WarnContext(ctx, "mail about a region failed", "region", r.ID, "error", err)
return false
}
s.log.InfoContext(ctx, "told about a region", "region", r.ID, "down", down, "recipients", len(to))
return true
}
+135
View File
@@ -0,0 +1,135 @@
package api_test
import (
"context"
"net/http"
"strings"
"testing"
"time"
"github.com/google/uuid"
"github.com/jackc/pgx/v5"
"git.zb-server.de/ZB-Server/uptimesebi/internal/agentapi"
"git.zb-server.de/ZB-Server/uptimesebi/internal/config"
"git.zb-server.de/ZB-Server/uptimesebi/internal/notify/notifytest"
)
func TestUncheckedMonitorsAndRegionsWithoutChecker(t *testing.T) {
mail := notifytest.NewSMTP(t)
e := newEnvWith(t, func(c *config.API) {
c.SMTPURL, c.SignupVerify, c.RegionAlertAfter = mail.URL(), "off", 3*time.Minute
})
ctx := context.Background()
owner := e.browser(t)
ownerEmail := "o@" + uniq("rw") + ".test"
owner.signup(ownerEmail, uniq("rw-"))
// An organization's own region: its owners hear about it.
regionName := uniq("Office ")
_, reg := owner.do("POST", "/api/v1/org/regions", map[string]any{"key": uniq("office-"), "name": regionName})
region := reg["id"].(string)
regionID := uuid.MustParse(region)
st, agent := owner.do("POST", "/api/v1/org/agents", map[string]any{"kind": "checker", "name": "office-1", "region_id": region})
if st != http.StatusCreated {
t.Fatalf("create agent = %d %v", st, agent)
}
tok := agent["token"].(string)
mailed := func(to, want string) {
t.Helper()
waitFor(t, 5*time.Second, "a mail saying "+want, func() bool {
for _, m := range mail.Messages() {
if strings.Contains(strings.Join(m.To, ","), to) && strings.Contains(m.Data, want) && strings.Contains(m.Data, regionName) {
return true
}
}
return false
})
}
// A monitor whose only region last reported ten minutes ago is not
// up: nobody is checking it.
_, mon := owner.do("POST", "/api/v1/org/monitors", map[string]any{"name": "Shop", "type": "http", "target": "https://example.test", "interval_seconds": 60, "regions": []string{region}})
id := mon["id"].(string)
org := uuid.MustParse(owner.orgID())
if err := e.asSystem(t, func(tx pgx.Tx) error {
if _, err := tx.Exec(ctx, `UPDATE monitors SET created_at = now() - interval '1 hour' WHERE id = $1`, id); err != nil {
return err
}
if _, err := tx.Exec(ctx, `INSERT INTO check_results (time, org_id, monitor_id, region, checker_id, ok, latency_ms) VALUES (now() - interval '10 minutes', $1, $2, $3, $4, true, 10)`,
org, id, region, uuid.New()); err != nil {
return err
}
// As the API keeps it when the result arrives.
_, err := tx.Exec(ctx, `INSERT INTO latest_results (time, org_id, monitor_id, region, ok, latency_ms) VALUES (now() - interval '10 minutes', $1, $2, $3, true, 10)`,
org, id, region)
return err
}); err != nil {
t.Fatal(err)
}
_, _, dash := owner.page("/")
for _, want := range []string{"not being checked", "1 monitor is not being checked"} {
if !strings.Contains(dash, want) {
t.Errorf("dashboard lacks %q", want)
}
}
if _, _, detail := owner.page("/monitors/" + id); !strings.Contains(detail, "no data since") || !strings.Contains(detail, "1 monitor is not being checked") {
t.Error("the monitor page does not say the region has no recent data")
}
// On a status page it shows as unknown, not as operational.
slug := uniq("rw-")
_, page := owner.do("POST", "/api/v1/org/statuspages", map[string]any{"slug": slug, "title": "Shop status"})
owner.do("PUT", "/api/v1/org/statuspages/"+page["id"].(string)+"/monitors", map[string]any{"monitors": []map[string]any{{"monitor_id": id}}})
owner.do("PUT", "/api/v1/org/statuspages/"+page["id"].(string), map[string]any{"slug": slug, "title": "Shop status", "published": true})
snap, err := e.statuspageClient(t, &org).Page(ctx, "", slug)
if err != nil || len(snap.Sections) != 1 || snap.Sections[0].Components[0].Status != agentapi.PageUnknown {
t.Errorf("status page = %+v, %v; want the component unknown", snap.Sections, err)
}
// The region has a checker but no live instance: the watch notes it at
// once and tells the owners once it has lasted.
now := time.Now()
if err := e.api.WatchRegionsOf(ctx, now, regionID); err != nil {
t.Fatal(err)
}
if _, _, dash := owner.page("/"); !strings.Contains(dash, "Region "+regionName+" has had no active checker since") {
t.Error("the dashboard does not name the region without a checker")
}
if err := e.api.WatchRegionsOf(ctx, now.Add(5*time.Minute), regionID); err != nil {
t.Fatal(err)
}
mailed(ownerEmail, "has no active checker")
sent := len(mail.Messages())
if err := e.api.WatchRegionsOf(ctx, now.Add(10*time.Minute), regionID); err != nil {
t.Fatal(err)
}
time.Sleep(200 * time.Millisecond)
if n := countMails(mail.Messages()[sent:], regionName); n != 0 {
t.Errorf("the region was announced %d more times", n)
}
// A checker coming back is announced too.
e.startChecker(t, tok)
waitFor(t, 15*time.Second, "the checker to count as live", func() bool {
_ = e.api.WatchRegionsOf(ctx, time.Now(), regionID)
for _, m := range mail.Messages() {
if strings.Contains(m.Data, "is checking again") && strings.Contains(m.Data, regionName) {
return true
}
}
return false
})
if _, _, dash := owner.page("/"); strings.Contains(dash, "Region "+regionName+" has had no active checker") {
t.Error("the dashboard still names the region")
}
}
func countMails(ms []notifytest.Message, about string) int {
n := 0
for _, m := range ms {
if strings.Contains(m.Data, about) {
n++
}
}
return n
}
+44
View File
@@ -0,0 +1,44 @@
package api
import (
"context"
"encoding/json"
"time"
"github.com/google/uuid"
"git.zb-server.de/ZB-Server/uptimesebi/internal/store"
)
// latestRow is a result as UpsertLatestResults reads it.
type latestRow struct {
MonitorID uuid.UUID `json:"monitor_id"`
Region string `json:"region"`
OrgID uuid.UUID `json:"org_id"`
Time time.Time `json:"time"`
OK bool `json:"ok"`
LatencyMS *int32 `json:"latency_ms"`
StatusCode *int32 `json:"status_code"`
Error *string `json:"error"`
}
// insertResults stores results and keeps the newest per monitor and
// region in latest_results, which the console reads instead of a day of
// results.
func insertResults(ctx context.Context, q *store.Queries, rows []store.InsertCheckResultsParams) error {
if _, err := q.InsertCheckResults(ctx, rows); err != nil {
return err
}
latest := make([]latestRow, len(rows))
for i, r := range rows {
latest[i] = latestRow{
MonitorID: r.MonitorID, Region: r.Region, OrgID: r.OrgID, Time: r.Time, OK: r.Ok,
LatencyMS: r.LatencyMs, StatusCode: r.StatusCode, Error: r.Error,
}
}
b, err := json.Marshal(latest)
if err != nil {
return err
}
return q.UpsertLatestResults(ctx, b)
}
+23
View File
@@ -53,6 +53,10 @@ type Server struct {
checkerNet *versioned[bool] checkerNet *versioned[bool]
// limits caches the platform's default limits. // limits caches the platform's default limits.
limits *versioned[Limits] limits *versioned[Limits]
// support caches how the platform runs support tickets.
support *versioned[supportSettings]
// draining, once closed, ends the long polls of checkers.
draining <-chan struct{}
} }
// Deps are the external resources a Server needs. // Deps are the external resources a Server needs.
@@ -88,9 +92,14 @@ func New(cfg config.API, d Deps) *Server {
checkTypes: newVersioned[map[string]bool]("check-types"), checkTypes: newVersioned[map[string]bool]("check-types"),
checkerNet: newVersioned[bool]("checker-network"), checkerNet: newVersioned[bool]("checker-network"),
limits: newVersioned[Limits]("limits"), limits: newVersioned[Limits]("limits"),
support: newVersioned[supportSettings]("support"),
} }
} }
// EndLongPollsOn makes the checkers' long polls return as soon as ch is
// closed, as when the instance starts draining for a shutdown.
func (s *Server) EndLongPollsOn(ch <-chan struct{}) { s.draining = ch }
// Mount installs session loading, locale resolution and CSRF protection and // Mount installs session loading, locale resolution and CSRF protection and
// registers the JSON API and the console pages below them. // registers the JSON API and the console pages below them.
func (s *Server) Mount(r gin.IRouter) { func (s *Server) Mount(r gin.IRouter) {
@@ -132,6 +141,13 @@ func (s *Server) Mount(r gin.IRouter) {
me.GET("/export", s.exportAccount) me.GET("/export", s.exportAccount)
me.POST("/delete", s.deleteAccount) me.POST("/delete", s.deleteAccount)
support := v1.Group("/support", auth.Require(), s.requireSupport())
support.GET("/tickets", s.listMyTickets)
support.POST("/tickets", s.createTicket)
support.GET("/tickets/:id", s.getMyTicket)
support.POST("/tickets/:id/messages", s.replyMyTicket)
support.PUT("/tickets/:id/status", s.setMyTicketStatus)
v1.POST("/invitations/:token/accept", auth.Require(), s.acceptInvitation) v1.POST("/invitations/:token/accept", auth.Require(), s.acceptInvitation)
v1.POST("/invitations/:token/signup", s.inviteSignup) v1.POST("/invitations/:token/signup", s.inviteSignup)
@@ -146,6 +162,7 @@ func (s *Server) Mount(r gin.IRouter) {
// scoped to a group grant access below that group only. // scoped to a group grant access below that group only.
org.GET("/monitors", s.listMonitors) org.GET("/monitors", s.listMonitors)
org.POST("/monitors", s.createMonitor) org.POST("/monitors", s.createMonitor)
org.PUT("/monitors/order", s.orderMonitors)
org.PUT("/monitors/:id", s.updateMonitor) org.PUT("/monitors/:id", s.updateMonitor)
org.DELETE("/monitors/:id", s.deleteMonitor) org.DELETE("/monitors/:id", s.deleteMonitor)
org.GET("/monitors/:id/evidence", s.listEvidence) org.GET("/monitors/:id/evidence", s.listEvidence)
@@ -203,6 +220,12 @@ func (s *Server) Mount(r gin.IRouter) {
admin.GET("/regions", s.adminListRegions) admin.GET("/regions", s.adminListRegions)
admin.POST("/regions", s.adminCreateRegion) admin.POST("/regions", s.adminCreateRegion)
admin.DELETE("/regions/:id", s.adminDeleteRegion) admin.DELETE("/regions/:id", s.adminDeleteRegion)
admin.GET("/support/settings", s.adminGetSupportSettings)
admin.PUT("/support/settings", s.adminSetSupportSettings)
admin.GET("/support/tickets", s.adminListTickets)
admin.GET("/support/tickets/:id", s.adminGetTicket)
admin.POST("/support/tickets/:id/messages", s.adminReplyTicket)
admin.PUT("/support/tickets/:id/status", s.adminSetTicketStatus)
admin.GET("/agents", s.adminListAgents) admin.GET("/agents", s.adminListAgents)
admin.POST("/agents", s.adminCreateAgent) admin.POST("/agents", s.adminCreateAgent)
admin.DELETE("/agents/:id", s.adminDeleteAgent) admin.DELETE("/agents/:id", s.adminDeleteAgent)
+135 -24
View File
@@ -22,6 +22,8 @@ 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/authz" "git.zb-server.de/ZB-Server/uptimesebi/internal/authz"
"git.zb-server.de/ZB-Server/uptimesebi/internal/check"
"git.zb-server.de/ZB-Server/uptimesebi/internal/evaluate"
"git.zb-server.de/ZB-Server/uptimesebi/internal/store" "git.zb-server.de/ZB-Server/uptimesebi/internal/store"
"git.zb-server.de/ZB-Server/uptimesebi/internal/tenant" "git.zb-server.de/ZB-Server/uptimesebi/internal/tenant"
"git.zb-server.de/ZB-Server/uptimesebi/internal/web" "git.zb-server.de/ZB-Server/uptimesebi/internal/web"
@@ -33,6 +35,9 @@ const (
// verifyPrefix is the label under which customers publish the TXT record // verifyPrefix is the label under which customers publish the TXT record
// proving control of a custom domain. // proving control of a custom domain.
verifyPrefix = "_uptimesebi." verifyPrefix = "_uptimesebi."
// domainChangesPerDay bounds how often an organization may set a new
// custom domain.
domainChangesPerDay = 10
) )
var ( var (
@@ -79,10 +84,15 @@ func (s *Server) buildSnapshot(ctx context.Context, page store.StatusPage) (agen
for i, m := range listed { for i, m := range listed {
ids[i] = m.MonitorID ids[i] = m.MonitorID
} }
if latest, err = q.LatestResults(ctx, page.OrgID); err != nil { rows, err := q.LatestResultsForMonitors(ctx, store.LatestResultsForMonitorsParams{OrgID: page.OrgID, Ids: ids})
if err != nil {
return err return err
} }
if open, err = q.OpenIncidents(ctx); err != nil { latest = make([]store.LatestResultsRow, len(rows))
for i, r := range rows {
latest[i] = store.LatestResultsRow(r)
}
if open, err = q.OpenIncidents(ctx, page.OrgID); err != nil {
return err return err
} }
if daily, err = q.DailyBucketsForMonitors(ctx, store.DailyBucketsForMonitorsParams{ if daily, err = q.DailyBucketsForMonitors(ctx, store.DailyBucketsForMonitorsParams{
@@ -92,7 +102,7 @@ func (s *Server) buildSnapshot(ctx context.Context, page store.StatusPage) (agen
} }
if page.ShowComponentDetails { if page.ShowComponentDetails {
if hourly, err = q.HourlyBuckets(ctx, store.HourlyBucketsParams{ if hourly, err = q.HourlyBuckets(ctx, store.HourlyBucketsParams{
OrgID: page.OrgID, Bucket: now.UTC().Add(-24 * time.Hour), OrgID: page.OrgID, Bucket: now.UTC().Add(-24 * time.Hour), Ids: ids,
}); err != nil { }); err != nil {
return err return err
} }
@@ -127,7 +137,18 @@ func (s *Server) buildSnapshot(ctx context.Context, page store.StatusPage) (agen
failing := map[uuid.UUID]int{} failing := map[uuid.UUID]int{}
reported := map[uuid.UUID]int{} reported := map[uuid.UUID]int{}
latestByMonitor := map[uuid.UUID][]store.LatestResultsRow{} latestByMonitor := map[uuid.UUID][]store.LatestResultsRow{}
// A region that has not reported for longer than the evaluator waits
// is unknown, whatever its last result said.
staleBefore := map[uuid.UUID]time.Time{}
for _, m := range listed {
if !check.Passive(check.Type(m.MonitorType)) {
staleBefore[m.MonitorID] = now.Add(-evaluate.StaleAfter(time.Duration(m.IntervalSeconds) * time.Second))
}
}
for _, l := range latest { for _, l := range latest {
if cut, ok := staleBefore[l.MonitorID]; ok && l.Time.Before(cut) {
continue
}
reported[l.MonitorID]++ reported[l.MonitorID]++
if !l.Ok { if !l.Ok {
failing[l.MonitorID]++ failing[l.MonitorID]++
@@ -346,29 +367,77 @@ func (s *Server) agentPage(c *gin.Context) {
fail(c, http.StatusBadRequest, "invalid_input") fail(c, http.StatusBadRequest, "invalid_input")
return return
} }
var page store.StatusPage page, ok, err := s.agentServes(ctx, agentOf(c), host, slug)
err := s.db.Tx(ctx, tenant.System(), func(q *store.Queries) error {
var err error
page, err = q.FindPublishedPage(ctx, store.FindPublishedPageParams{Host: host, Slug: slug})
return err
})
a := agentOf(c)
if errors.Is(err, pgx.ErrNoRows) || (err == nil && a.OrgID != nil && *a.OrgID != page.OrgID) {
fail(c, http.StatusNotFound, "not_found")
return
}
if err != nil { if err != nil {
internalError(c, err) internalError(c, err)
return return
} }
if !ok {
fail(c, http.StatusNotFound, "not_found")
return
}
snap, err := s.buildSnapshot(ctx, page) snap, err := s.buildSnapshot(ctx, page)
if err != nil { if err != nil {
internalError(c, err) internalError(c, err)
return return
} }
// The server sends the checksum of its copy; an unchanged page is not
// sent again.
etag := `"` + snap.Checksum() + `"`
c.Header("ETag", etag)
if c.GetHeader("If-None-Match") == etag {
c.Status(http.StatusNotModified)
return
}
c.JSON(http.StatusOK, snap) c.JSON(http.StatusOK, snap)
} }
// agentServes finds the published page a status page agent serves at host
// or slug. The platform's servers leave the pages of organizations that
// serve them on their own servers to those, which receive only their own
// organization's pages.
func (s *Server) agentServes(ctx context.Context, a store.GetAgentByHashRow, host, slug *string) (store.StatusPage, bool, error) {
var (
page store.StatusPage
own bool
)
err := s.db.Tx(ctx, tenant.System(), func(q *store.Queries) error {
var err error
if page, err = q.FindPublishedPage(ctx, store.FindPublishedPageParams{Host: host, Slug: slug}); err != nil || a.OrgID != nil {
return err
}
own, err = q.OrgServesOwnPages(ctx, &page.OrgID)
return err
})
switch {
case errors.Is(err, pgx.ErrNoRows):
return page, false, nil
case err != nil:
return page, false, err
}
return page, !own && (a.OrgID == nil || *a.OrgID == page.OrgID), nil
}
// agentPageIndex lists the pages the status page server serves.
func (s *Server) agentPageIndex(c *gin.Context) {
ctx := c.Request.Context()
var rows []store.ServablePagesRow
err := s.db.Tx(ctx, tenant.System(), func(q *store.Queries) error {
var err error
rows, err = q.ServablePages(ctx, agentOf(c).OrgID)
return err
})
if err != nil {
internalError(c, err)
return
}
out := make([]agentapi.PageRef, len(rows))
for i, r := range rows {
out[i] = agentapi.PageRef{Slug: r.Slug, Host: r.Host}
}
c.JSON(http.StatusOK, gin.H{"pages": out})
}
type statusPageRequest struct { 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"`
@@ -416,6 +485,13 @@ type statusPageView struct {
DomainVerified bool `json:"domain_verified"` DomainVerified bool `json:"domain_verified"`
// DomainRecord is the TXT record that proves control of CustomDomain. // DomainRecord is the TXT record that proves control of CustomDomain.
DomainRecord *dnsRecord `json:"domain_record,omitempty"` DomainRecord *dnsRecord `json:"domain_record,omitempty"`
// CNAMERecord points CustomDomain at the platform's status page
// servers and proves control of it in one, where the platform knows
// their host.
CNAMERecord *dnsRecord `json:"cname_record,omitempty"`
// DomainMissingSince is set when the record of a verified domain has
// not been found since then; it is switched off a week later.
DomainMissingSince *time.Time `json:"domain_missing_since,omitempty"`
// Suspended is set when platform admins took the page offline; it is // Suspended is set when platform admins took the page offline; it is
// not served whatever Published says. // not served whatever Published says.
Suspended bool `json:"suspended,omitempty"` Suspended bool `json:"suspended,omitempty"`
@@ -428,7 +504,7 @@ type dnsRecord struct {
Value string `json:"value"` Value string `json:"value"`
} }
func 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,
@@ -438,6 +514,10 @@ func viewStatusPage(p store.StatusPage) statusPageView {
_ = json.Unmarshal(p.Theme, &v.Theme) _ = json.Unmarshal(p.Theme, &v.Theme)
if p.CustomDomain != nil { if p.CustomDomain != nil {
v.DomainRecord = &dnsRecord{Name: verifyPrefix + *p.CustomDomain, Type: "TXT", Value: p.DomainToken} v.DomainRecord = &dnsRecord{Name: verifyPrefix + *p.CustomDomain, Type: "TXT", Value: p.DomainToken}
if target := s.cnameFor(p.DomainToken); target != "" {
v.CNAMERecord = &dnsRecord{Name: *p.CustomDomain, Type: "CNAME", Value: target}
}
v.DomainMissingSince = p.DomainFailingSince
} }
return v return v
} }
@@ -476,7 +556,7 @@ func (s *Server) listStatusPages(c *gin.Context) {
out := []statusPageView{} out := []statusPageView{}
for _, r := range rows { for _, r := range rows {
if p.Grants.Can(authz.StatusPagesRead, pageResource(r.ID)) { if p.Grants.Can(authz.StatusPagesRead, pageResource(r.ID)) {
out = append(out, viewStatusPage(r)) out = append(out, s.viewStatusPage(r))
} }
} }
c.JSON(http.StatusOK, gin.H{"pages": out}) c.JSON(http.StatusOK, gin.H{"pages": out})
@@ -518,7 +598,7 @@ func (s *Server) createStatusPage(c *gin.Context) {
internalError(c, err) internalError(c, err)
return return
} }
c.JSON(http.StatusCreated, viewStatusPage(row)) c.JSON(http.StatusCreated, s.viewStatusPage(row))
} }
func newDomainToken() string { func newDomainToken() string {
@@ -557,7 +637,7 @@ func (s *Server) updateStatusPage(c *gin.Context) {
case err != nil: case err != nil:
internalError(c, err) internalError(c, err)
default: default:
c.JSON(http.StatusOK, viewStatusPage(row)) c.JSON(http.StatusOK, s.viewStatusPage(row))
} }
} }
@@ -623,6 +703,16 @@ func (s *Server) setPageMonitors(c *gin.Context) {
} }
} }
} }
// A page beyond a lowered limit may keep its monitors but not add any.
if max := s.orgLimits(ctx, p.Org).MonitorsPerPage; max > 0 && len(req.Monitors) > max {
had, err := q.CountStatusPageMonitors(ctx, id)
if err != nil {
return err
}
if int64(len(req.Monitors)) > had {
return limitError{"page_monitor_limit", max}
}
}
if err := q.ClearStatusPageMonitors(ctx, id); err != nil { if err := q.ClearStatusPageMonitors(ctx, id); err != nil {
return err return err
} }
@@ -650,6 +740,7 @@ func (s *Server) setPageMonitors(c *gin.Context) {
case isForeignKeyViolation(err), isUniqueViolation(err, "status_page_monitors_pkey"): case isForeignKeyViolation(err), isUniqueViolation(err, "status_page_monitors_pkey"):
// Unknown monitors, monitors of other orgs and duplicates. // Unknown monitors, monitors of other orgs and duplicates.
fail(c, http.StatusUnprocessableEntity, "invalid_monitor") fail(c, http.StatusUnprocessableEntity, "invalid_monitor")
case failLimit(c, err):
case err != nil: case err != nil:
internalError(c, err) internalError(c, err)
default: default:
@@ -675,12 +766,30 @@ func (s *Server) setPageDomain(c *gin.Context) {
p := current(c) p := current(c)
ctx := c.Request.Context() ctx := c.Request.Context()
var row store.StatusPage var row store.StatusPage
limited := false
err := s.db.Tx(ctx, p.scope(), func(q *store.Queries) error { err := s.db.Tx(ctx, p.scope(), func(q *store.Queries) error {
var err error cur, err := q.GetStatusPage(ctx, id)
if err != nil {
return err
}
// Every new domain may end in a certificate order; switching domains
// over and over would use up the CA's limits for everyone.
if domain != "" && domain != deref(cur.CustomDomain) {
ok, err := s.limiter.Allow(ctx, "domain_change:"+p.Org.ID.String(), domainChangesPerDay, 24*time.Hour)
if err != nil {
return err
}
if !ok {
limited = true
return nil
}
}
row, err = q.SetStatusPageDomain(ctx, store.SetStatusPageDomainParams{ID: id, CustomDomain: nonEmpty(domain)}) row, err = q.SetStatusPageDomain(ctx, store.SetStatusPageDomainParams{ID: id, CustomDomain: nonEmpty(domain)})
return err return err
}) })
switch { switch {
case limited:
fail(c, http.StatusTooManyRequests, "domain_changes_exceeded", "Count", domainChangesPerDay)
case isUniqueViolation(err, "status_pages_custom_domain_key"): case isUniqueViolation(err, "status_pages_custom_domain_key"):
fail(c, http.StatusConflict, "domain_taken") fail(c, http.StatusConflict, "domain_taken")
case errors.Is(err, pgx.ErrNoRows): case errors.Is(err, pgx.ErrNoRows):
@@ -688,14 +797,14 @@ func (s *Server) setPageDomain(c *gin.Context) {
case err != nil: case err != nil:
internalError(c, err) internalError(c, err)
default: default:
c.JSON(http.StatusOK, viewStatusPage(row)) c.JSON(http.StatusOK, s.viewStatusPage(row))
} }
} }
// lookupTXT is replaced in tests. // lookupTXT is replaced in tests.
var lookupTXT = net.DefaultResolver.LookupTXT var lookupTXT = net.DefaultResolver.LookupTXT
// verifyPageDomain checks the TXT record. Only verified domains are served, // verifyPageDomain looks for the CNAME or the TXT record now. Only verified domains are served,
// so nobody can claim a domain they do not control. // so nobody can claim a domain they do not control.
func (s *Server) verifyPageDomain(c *gin.Context) { func (s *Server) verifyPageDomain(c *gin.Context) {
id := uuid.MustParse(c.Param("id")) id := uuid.MustParse(c.Param("id"))
@@ -722,12 +831,14 @@ func (s *Server) verifyPageDomain(c *gin.Context) {
fail(c, http.StatusConflict, "no_domain") fail(c, http.StatusConflict, "no_domain")
return return
} }
records, err := lookupTXT(ctx, verifyPrefix+*row.CustomDomain) method := s.checkDomain(ctx, *row.CustomDomain, row.DomainToken)
if err != nil || !slices.Contains(records, row.DomainToken) { if method == "" {
fail(c, http.StatusUnprocessableEntity, "domain_not_verified") fail(c, http.StatusUnprocessableEntity, "domain_not_verified")
return return
} }
err = s.db.Tx(ctx, p.scope(), func(q *store.Queries) error { return q.MarkDomainVerified(ctx, id) }) err = s.db.Tx(ctx, p.scope(), func(q *store.Queries) error {
return q.MarkDomainVerified(ctx, store.MarkDomainVerifiedParams{ID: id, Now: time.Now(), Method: method})
})
if err != nil { if err != nil {
internalError(c, err) internalError(c, err)
return return
+38
View File
@@ -8,6 +8,7 @@ import (
"log/slog" "log/slog"
"net/http" "net/http"
"net/http/httptest" "net/http/httptest"
"slices"
"strings" "strings"
"testing" "testing"
"time" "time"
@@ -95,6 +96,12 @@ func TestStatusPages(t *testing.T) {
snap.Sections[1].Components[0].Name != "Public API" { snap.Sections[1].Components[0].Name != "Public API" {
t.Errorf("snapshot = %+v, want degraded page with the Public API in outage", snap) t.Errorf("snapshot = %+v, want degraded page with the Public API in outage", snap)
} }
if _, err := platform.PageIfChanged(context.Background(), "", slug, snap.Checksum()); !errors.Is(err, agentapi.ErrNotModified) {
t.Errorf("PageIfChanged(current checksum) error = %v, want not modified", err)
}
if again, err := platform.PageIfChanged(context.Background(), "", slug, "stale"); err != nil || again.Title != "Acme Status" {
t.Errorf("PageIfChanged(stale checksum) = %v, %v", again.Title, err)
}
raw, _ := json.Marshal(snap) raw, _ := json.Marshal(snap)
for _, secret := range []string{up.URL, down.URL, "unexpected status"} { for _, secret := range []string{up.URL, down.URL, "unexpected status"} {
if strings.Contains(string(raw), secret) { if strings.Contains(string(raw), secret) {
@@ -192,6 +199,37 @@ func TestStatusPages(t *testing.T) {
st, body = editor.do("PUT", "/api/v1/org/statuspages/"+second, map[string]any{"slug": "x-second", "title": "x"}) st, body = editor.do("PUT", "/api/v1/org/statuspages/"+second, map[string]any{"slug": "x-second", "title": "x"})
expect(t, "edit page out of scope", st, body, http.StatusNotFound, "not_found") expect(t, "edit page out of scope", st, body, http.StatusNotFound, "not_found")
}) })
t.Run("own servers replace the platform's", func(t *testing.T) {
org := uuid.MustParse(owner.orgID())
own := e.statuspageClient(t, &org)
lists := func(c *agentapi.Client) bool {
t.Helper()
refs, err := c.Pages(context.Background())
if err != nil {
t.Fatal(err)
}
return slices.ContainsFunc(refs, func(r agentapi.PageRef) bool { return r.Slug == slug && r.Host != "" })
}
if _, err := platform.Page(context.Background(), "", slug); err != nil || !lists(platform) {
t.Fatalf("platform server before the own one connected: %v", err)
}
if _, err := own.Hello(context.Background()); err != nil {
t.Fatal(err)
}
if _, err := platform.Page(context.Background(), "", slug); !errors.Is(err, agentapi.ErrNotFound) {
t.Errorf("platform server still gets the page: %v", err)
}
if snap, err := own.Page(context.Background(), "", slug); err != nil || snap.Title != "Acme Status" {
t.Errorf("own server Page() = %v, %v", snap.Title, err)
}
if lists(platform) || !lists(own) {
t.Error("the page lists do not follow who serves the page")
}
if _, _, html := owner.page("/statuspages/" + pageID); !strings.Contains(html, "own status page servers serve its pages") {
t.Error("the editor does not say who serves the pages")
}
})
} }
func editorEmail(b *browser) string { func editorEmail(b *browser) string {
+6
View File
@@ -119,6 +119,12 @@ func TestAllowCertificate(t *testing.T) {
t.Error("AllowCertificate(unknown name) = nil, want refusal") t.Error("AllowCertificate(unknown name) = nil, want refusal")
} }
verifyDomain(t, owner, pageID, record) verifyDomain(t, owner, pageID, record)
// A name just found without a page is not asked about again for a
// while; the sync picks the newly verified domain up.
if err := srv.AllowCertificate(ctx, domain); err == nil {
t.Error("AllowCertificate(domain just found missing) = nil, want the miss remembered")
}
srv.Sync(ctx)
if err := srv.AllowCertificate(ctx, domain); err != nil { if err := srv.AllowCertificate(ctx, domain); err != nil {
t.Errorf("AllowCertificate(verified domain) = %v", err) t.Errorf("AllowCertificate(verified domain) = %v", err)
} }
+860
View File
@@ -0,0 +1,860 @@
package api
import (
"context"
"errors"
"log/slog"
"net/http"
"slices"
"strings"
"time"
"github.com/gin-gonic/gin"
"github.com/google/uuid"
"github.com/jackc/pgx/v5"
"git.zb-server.de/ZB-Server/uptimesebi/internal/auth"
"git.zb-server.de/ZB-Server/uptimesebi/internal/authz"
"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"
"git.zb-server.de/ZB-Server/uptimesebi/internal/web"
)
// Support tickets: an account asks the platform's admins for help, also
// while it is suspended or has yet to accept the terms. A ticket is open
// while it waits for the admins and answered while it waits for the
// account; a reply from either side moves it accordingly, also out of
// closed.
const (
ticketOpen = "open"
ticketAnswered = "answered"
ticketClosed = "closed"
)
type supportTicketRequest struct {
Subject string `json:"subject" binding:"required,max=200"`
Message string `json:"message" binding:"required,max=10000"`
// AttachOrg names the active organization in the ticket. Anything else
// attached comes from it and names it too.
AttachOrg bool `json:"attach_org"`
Monitor string `json:"monitor_id" binding:"max=36"`
Channel string `json:"channel_id" binding:"max=36"`
AlertGroup string `json:"alert_group_id" binding:"max=36"`
StatusPage string `json:"status_page_id" binding:"max=36"`
Incident string `json:"incident_id" binding:"max=36"`
}
// supportReference is something a ticket points at, by kind: org,
// monitor, channel, alert_group, status_page or incident.
type supportReference struct {
Kind string `json:"kind"`
Name string `json:"name"`
}
type supportMessageRequest struct {
Message string `json:"message" binding:"required,max=10000"`
}
type supportStatusRequest struct {
Status string `json:"status" binding:"required,oneof=open answered closed"`
}
type supportMessageView struct {
ID uuid.UUID `json:"id"`
FromStaff bool `json:"from_staff"`
// Author is the admin who answered, shown to admins only.
Author string `json:"author,omitempty"`
Body string `json:"body"`
CreatedAt time.Time `json:"created_at"`
}
type supportTicketView struct {
ID uuid.UUID `json:"id"`
Subject string `json:"subject"`
Status string `json:"status"`
// Org is the organization the account was in when it opened the ticket.
Org *string `json:"org,omitempty"`
// User is the account's email, shown to admins only.
User string `json:"user,omitempty"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
References []supportReference `json:"references,omitempty"`
Messages []supportMessageView `json:"messages,omitempty"`
}
// cleanSupportText trims text and reports whether anything is left.
func cleanSupportText(c *gin.Context, texts ...*string) bool {
for _, t := range texts {
*t = strings.TrimSpace(*t)
if *t == "" {
fail(c, http.StatusUnprocessableEntity, "invalid_input")
return false
}
}
return true
}
// loadTicket reads a ticket with its messages in scope, which decides
// whose tickets are visible.
func (s *Server) loadTicket(ctx context.Context, scope tenant.Scope, id uuid.UUID, staff bool) (supportTicketView, error) {
var v supportTicketView
err := s.db.Tx(ctx, scope, func(q *store.Queries) error {
t, err := q.GetSupportTicket(ctx, id)
if err != nil {
return err
}
v = supportTicketView{ID: t.ID, Subject: t.Subject, Status: t.Status, Org: t.OrgName, CreatedAt: t.CreatedAt, UpdatedAt: t.UpdatedAt}
if staff {
v.User = t.UserEmail
}
msgs, err := q.SupportMessages(ctx, id)
for _, m := range msgs {
mv := supportMessageView{ID: m.ID, FromStaff: m.FromStaff, Body: m.Body, CreatedAt: m.CreatedAt}
if staff && m.FromStaff {
mv.Author = m.AuthorEmail
}
v.Messages = append(v.Messages, mv)
}
return err
})
if err != nil {
return v, err
}
v.References, err = s.ticketReferences(ctx, id)
return v, err
}
// ticketReferences names what a ticket points at. The account may no
// longer see those things, so this reads past row-level security, after
// the caller saw the ticket itself.
func (s *Server) ticketReferences(ctx context.Context, id uuid.UUID) ([]supportReference, error) {
var out []supportReference
err := s.db.Tx(ctx, tenant.System(), func(q *store.Queries) error {
r, err := q.SupportTicketReferences(ctx, id)
if err != nil {
return err
}
add := func(kind string, name *string, extra ...*string) {
if name == nil {
return
}
n := *name
for _, e := range extra {
if e != nil && *e != "" {
n += " (" + *e + ")"
}
}
out = append(out, supportReference{Kind: kind, Name: n})
}
add("org", r.OrgName, r.OrgSlug)
add("monitor", r.MonitorName, r.MonitorType)
add("channel", r.ChannelName, r.ChannelType)
add("alert_group", r.AlertGroupName)
add("status_page", r.StatusPageTitle, r.StatusPageSlug)
if r.IncidentStartedAt != nil {
name := deref(r.IncidentMonitor)
if t := deref(r.IncidentTitle); t != "" {
name = t + " · " + name
}
name += " · " + r.IncidentStartedAt.UTC().Format(timeLayout)
add("incident", &name)
}
return nil
})
return out, err
}
func ticketID(c *gin.Context) (uuid.UUID, bool) {
id, err := uuid.Parse(c.Param("id"))
if err != nil {
fail(c, http.StatusNotFound, "not_found")
}
return id, err == nil
}
func (s *Server) listMyTickets(c *gin.Context) {
sess := auth.Current(c)
ctx := c.Request.Context()
var rows []store.SupportTicket
if err := s.db.Tx(ctx, tenant.User(sess.UserID), func(q *store.Queries) error {
var err error
rows, err = q.ListUserSupportTickets(ctx, sess.UserID)
return err
}); err != nil {
internalError(c, err)
return
}
out := make([]supportTicketView, len(rows))
for i, t := range rows {
out[i] = supportTicketView{ID: t.ID, Subject: t.Subject, Status: t.Status, CreatedAt: t.CreatedAt, UpdatedAt: t.UpdatedAt}
}
c.JSON(http.StatusOK, gin.H{"tickets": out})
}
// optionalID parses a form's optional reference; empty is none.
func optionalID(v string) (*uuid.UUID, bool) {
if v = strings.TrimSpace(v); v == "" {
return nil, true
}
id, err := uuid.Parse(v)
return &id, err == nil
}
// ticketRefs resolves what a new ticket points at. Everything comes from
// the active organization, which the account has to be able to read.
func (s *Server) ticketRefs(c *gin.Context, req supportTicketRequest) (store.CreateSupportTicketParams, bool) {
var p store.CreateSupportTicketParams
ids := []struct {
raw string
dst **uuid.UUID
perm authz.Permission
}{
{req.Monitor, &p.MonitorID, authz.MonitorsRead},
{req.Channel, &p.ChannelID, authz.NotificationsRead},
{req.AlertGroup, &p.AlertGroupID, authz.NotificationsRead},
{req.StatusPage, &p.StatusPageID, authz.StatusPagesRead},
{req.Incident, &p.IncidentID, authz.IncidentsRead},
}
any := req.AttachOrg
for _, r := range ids {
id, ok := optionalID(r.raw)
if !ok {
fail(c, http.StatusUnprocessableEntity, "invalid_input")
return p, false
}
*r.dst = id
any = any || id != nil
}
if !any {
return p, true
}
sess := auth.Current(c)
_, principal, err := s.consoleMe(c, sess)
if err != nil {
internalError(c, err)
return p, false
}
if principal == nil {
fail(c, http.StatusUnprocessableEntity, "invalid_input")
return p, false
}
for _, r := range ids {
if *r.dst != nil && !principal.Grants.Can(r.perm) {
fail(c, http.StatusUnprocessableEntity, "invalid_input")
return p, false
}
}
ctx := c.Request.Context()
var exists *bool
if err := s.db.Tx(ctx, principal.scope(), func(q *store.Queries) error {
var err error
exists, err = q.SupportReferencesExist(ctx, store.SupportReferencesExistParams{
OrgID: principal.Org.ID, MonitorID: p.MonitorID, ChannelID: p.ChannelID,
AlertGroupID: p.AlertGroupID, StatusPageID: p.StatusPageID, IncidentID: p.IncidentID,
})
return err
}); err != nil {
internalError(c, err)
return p, false
}
if exists == nil || !*exists {
fail(c, http.StatusUnprocessableEntity, "invalid_input")
return p, false
}
p.OrgID = &principal.Org.ID
return p, true
}
// errTicketLimit and errSuspendedTicket refuse tickets beyond what the
// platform allows; the error code says which.
var (
errTicketLimit = errors.New("api: too many open tickets")
errSuspendedTicket = errors.New("api: suspended accounts open one ticket")
)
// checkTicketLimits refuses another open ticket for user: more than the
// platform allows at the same time, or a second since a suspension.
func checkTicketLimits(ctx context.Context, q *store.Queries, user uuid.UUID, maxOpen int, newTicket bool) error {
if newTicket {
u, err := q.GetUser(ctx, user)
if err != nil {
return err
}
if u.DisabledAt != nil {
n, err := q.CountSupportTicketsSince(ctx, store.CountSupportTicketsSinceParams{UserID: user, CreatedAt: *u.DisabledAt})
if err != nil {
return err
}
if n > 0 {
return errSuspendedTicket
}
}
}
if maxOpen <= 0 {
return nil
}
n, err := q.CountOpenSupportTickets(ctx, user)
if err != nil {
return err
}
if n >= int64(maxOpen) {
return errTicketLimit
}
return nil
}
// failTicketLimit answers err if it is one of the ticket limits.
func failTicketLimit(c *gin.Context, err error, maxOpen int) bool {
switch {
case errors.Is(err, errSuspendedTicket):
fail(c, http.StatusConflict, "suspended_ticket_limit")
case errors.Is(err, errTicketLimit):
fail(c, http.StatusConflict, "too_many_tickets", "Count", maxOpen)
default:
return false
}
return true
}
func (s *Server) createTicket(c *gin.Context) {
var req supportTicketRequest
if !bind(c, &req) || !cleanSupportText(c, &req.Subject, &req.Message) {
return
}
sess := auth.Current(c)
if !s.limit(c, "support:user:"+sess.UserID.String(), 10, time.Hour) {
return
}
params, ok := s.ticketRefs(c, req)
if !ok {
return
}
params.UserID, params.Subject = sess.UserID, req.Subject
ctx := c.Request.Context()
maxOpen := s.supportSettings(ctx).MaxOpen
var t store.SupportTicket
err := s.db.Tx(ctx, tenant.User(sess.UserID), func(q *store.Queries) error {
if err := checkTicketLimits(ctx, q, sess.UserID, maxOpen, true); err != nil {
return err
}
var err error
if t, err = q.CreateSupportTicket(ctx, params); err != nil {
return err
}
_, err = q.AddSupportMessage(ctx, store.AddSupportMessageParams{TicketID: t.ID, AuthorID: &sess.UserID, Body: req.Message})
return err
})
if failTicketLimit(c, err, maxOpen) {
return
}
if err != nil {
internalError(c, err)
return
}
auditDetail(c, "ticket", t.ID.String())
s.mailAdmins(ctx, t.ID, t.Subject)
c.JSON(http.StatusCreated, supportTicketView{ID: t.ID, Subject: t.Subject, Status: t.Status, CreatedAt: t.CreatedAt, UpdatedAt: t.UpdatedAt})
}
func (s *Server) getMyTicket(c *gin.Context) {
id, ok := ticketID(c)
if !ok {
return
}
v, err := s.loadTicket(c.Request.Context(), tenant.User(auth.Current(c).UserID), id, false)
s.respondTicket(c, v, err)
}
func (s *Server) respondTicket(c *gin.Context, v supportTicketView, err error) {
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)
}
}
// replyTicket adds a message and moves the ticket to the side that has to
// answer next.
func (s *Server) replyTicket(c *gin.Context, scope tenant.Scope, author uuid.UUID, staff bool) (store.GetSupportTicketRow, bool) {
maxOpen := 0
if !staff {
maxOpen = s.supportSettings(c.Request.Context()).MaxOpen
}
id, ok := ticketID(c)
if !ok {
return store.GetSupportTicketRow{}, false
}
var req supportMessageRequest
if !bind(c, &req) || !cleanSupportText(c, &req.Message) {
return store.GetSupportTicketRow{}, false
}
status := ticketOpen
if staff {
status = ticketAnswered
}
ctx := c.Request.Context()
var t store.GetSupportTicketRow
err := s.db.Tx(ctx, scope, func(q *store.Queries) error {
var err error
if t, err = q.GetSupportTicket(ctx, id); err != nil {
return err
}
if !staff && t.Status == ticketClosed {
if err := checkTicketLimits(ctx, q, t.UserID, maxOpen, false); err != nil {
return err
}
}
if _, err = q.AddSupportMessage(ctx, store.AddSupportMessageParams{TicketID: id, AuthorID: &author, FromStaff: staff, Body: req.Message}); err != nil {
return err
}
_, err = q.SetSupportTicketStatus(ctx, store.SetSupportTicketStatusParams{ID: id, Status: status})
return err
})
switch {
case errors.Is(err, pgx.ErrNoRows):
fail(c, http.StatusNotFound, "not_found")
return t, false
case failTicketLimit(c, err, maxOpen):
return t, false
case err != nil:
internalError(c, err)
return t, false
}
auditDetail(c, "ticket", id.String())
c.JSON(http.StatusCreated, gin.H{"status": status})
return t, true
}
func (s *Server) replyMyTicket(c *gin.Context) {
sess := auth.Current(c)
if !s.limit(c, "support:reply:"+sess.UserID.String(), 60, time.Hour) {
return
}
if t, ok := s.replyTicket(c, tenant.User(sess.UserID), sess.UserID, false); ok {
s.mailAdmins(c.Request.Context(), t.ID, t.Subject)
}
}
// setTicketStatus closes or reopens a ticket in scope; accounts can only
// close theirs or reopen them for the admins.
func (s *Server) setTicketStatus(c *gin.Context, scope tenant.Scope, maxOpen int, allowed ...string) {
id, ok := ticketID(c)
if !ok {
return
}
var req supportStatusRequest
if !bind(c, &req) {
return
}
if len(allowed) > 0 && !slices.Contains(allowed, req.Status) {
fail(c, http.StatusUnprocessableEntity, "invalid_input")
return
}
ctx := c.Request.Context()
var n int64
err := s.db.Tx(ctx, scope, func(q *store.Queries) error {
if req.Status != ticketClosed && maxOpen > 0 {
cur, err := q.SupportTicketStatus(ctx, id)
if errors.Is(err, pgx.ErrNoRows) {
return nil
}
if err != nil {
return err
}
if cur == ticketClosed {
if err := checkTicketLimits(ctx, q, auth.Current(c).UserID, maxOpen, false); err != nil {
return err
}
}
}
var err error
n, err = q.SetSupportTicketStatus(ctx, store.SetSupportTicketStatusParams{ID: id, Status: req.Status})
return err
})
switch {
case failTicketLimit(c, err, maxOpen):
case err != nil:
internalError(c, err)
case n == 0:
fail(c, http.StatusNotFound, "not_found")
default:
auditDetail(c, "status", req.Status)
c.Status(http.StatusNoContent)
}
}
func (s *Server) setMyTicketStatus(c *gin.Context) {
s.setTicketStatus(c, tenant.User(auth.Current(c).UserID), s.supportSettings(c.Request.Context()).MaxOpen, ticketOpen, ticketClosed)
}
// supportStatusFilter reads the status filter of the admins' list; empty
// lists every ticket.
func supportStatusFilter(c *gin.Context) *string {
switch st := c.Query("status"); st {
case ticketOpen, ticketAnswered, ticketClosed:
return &st
case "all":
return nil
default:
open := ticketOpen
return &open
}
}
func (s *Server) adminListTickets(c *gin.Context) {
rows, err := s.supportTickets(c.Request.Context(), supportStatusFilter(c))
if err != nil {
internalError(c, err)
return
}
out := make([]supportTicketView, len(rows))
for i, t := range rows {
out[i] = supportTicketView{ID: t.ID, Subject: t.Subject, Status: t.Status, Org: t.OrgName, User: t.UserEmail, CreatedAt: t.CreatedAt, UpdatedAt: t.UpdatedAt}
}
c.JSON(http.StatusOK, gin.H{"tickets": out})
}
// supportTickets lists the latest 200 tickets with status, or all.
func (s *Server) supportTickets(ctx context.Context, status *string) ([]store.ListSupportTicketsRow, error) {
var rows []store.ListSupportTicketsRow
err := s.db.Tx(ctx, tenant.System(), func(q *store.Queries) error {
var err error
rows, err = q.ListSupportTickets(ctx, status)
return err
})
return rows, err
}
func (s *Server) adminGetTicket(c *gin.Context) {
id, ok := ticketID(c)
if !ok {
return
}
v, err := s.loadTicket(c.Request.Context(), tenant.System(), id, true)
s.respondTicket(c, v, err)
}
func (s *Server) adminReplyTicket(c *gin.Context) {
sess := auth.Current(c)
if t, ok := s.replyTicket(c, tenant.System(), sess.UserID, true); ok {
s.mailTicketOwner(c.Request.Context(), t)
}
}
func (s *Server) adminSetTicketStatus(c *gin.Context) {
s.setTicketStatus(c, tenant.System(), 0)
}
func (s *Server) ticketLink(path string) string {
return strings.TrimSuffix(s.cfg.PublicURL, "/") + path
}
// mailAdmins tells the platform's admins that a ticket waits for them.
// Mail is a courtesy: the ticket stands without it.
func (s *Server) mailAdmins(ctx context.Context, id uuid.UUID, subject string) {
if s.smtp == nil {
return
}
var to []string
if err := s.db.Tx(ctx, tenant.Global(), func(q *store.Queries) error {
var err error
to, err = q.AdminEmails(ctx)
return err
}); err != nil || len(to) == 0 {
return
}
l := s.catalog.Match("")
data := map[string]any{"Subject": subject, "Link": s.ticketLink("/admin/support/" + id.String())}
if err := s.smtp.Send(ctx, notify.Mail{To: to, Subject: l.T("email.support_admin.subject", data), Body: l.T("email.support_admin.body", data)}); err != nil {
slog.WarnContext(ctx, "support: mail to admins failed", "ticket", id, "err", err)
}
}
// mailTicketOwner tells the account that its ticket was answered.
func (s *Server) mailTicketOwner(ctx context.Context, t store.GetSupportTicketRow) {
if s.smtp == nil {
return
}
var locale string
_ = s.db.Tx(ctx, tenant.Global(), func(q *store.Queries) error {
u, err := q.GetUser(ctx, t.UserID)
locale = deref(u.Locale)
return err
})
l := s.catalog.Match(locale)
data := map[string]any{"Subject": t.Subject, "Link": s.ticketLink("/support/" + t.ID.String())}
if err := s.smtp.Send(ctx, notify.Mail{To: []string{t.UserEmail}, Subject: l.T("email.support_reply.subject", data), Body: l.T("email.support_reply.body", data)}); err != nil {
slog.WarnContext(ctx, "support: mail to account failed", "ticket", t.ID, "err", err)
}
}
// Pages.
func toWebTicket(v supportTicketView) web.SupportTicket {
t := web.SupportTicket{ID: v.ID.String(), Subject: v.Subject, Status: v.Status, User: v.User, Updated: v.UpdatedAt.UTC().Format(timeLayout)}
if v.Org != nil {
t.Org = *v.Org
}
for _, r := range v.References {
t.References = append(t.References, web.SupportReference{Kind: r.Kind, Name: r.Name})
}
for _, m := range v.Messages {
html, err := web.RenderMarkdown(m.Body)
if err != nil {
html = ""
}
t.Messages = append(t.Messages, web.SupportMessage{FromStaff: m.FromStaff, Author: m.Author, HTML: html, At: m.CreatedAt.UTC().Format(timeLayout)})
}
return t
}
// supportMe is the console frame of the support pages, which accounts
// reach also while restricted.
func (s *Server) supportMe(c *gin.Context) (*auth.Session, web.Me, *principal, bool) {
sess := auth.Current(c)
if sess == nil {
c.Redirect(http.StatusSeeOther, "/login?next="+c.Request.URL.Path)
return nil, web.Me{}, nil, false
}
me, p, err := s.consoleMe(c, sess)
if err != nil {
internalError(c, err)
return nil, web.Me{}, nil, false
}
if !me.Support {
web.Render(c, http.StatusOK, web.SupportDisabledPage(s.pageFor(c, "support.title"), me))
return nil, web.Me{}, nil, false
}
return sess, me, p, true
}
// supportOptions lists what of the active organization a new ticket can
// point at, as far as the account may read it.
func (s *Server) supportOptions(ctx context.Context, p *principal) (web.SupportOptions, error) {
var o web.SupportOptions
if p == nil {
return o, nil
}
o.Org = p.Org.Name
err := s.db.Tx(ctx, p.scope(), func(q *store.Queries) error {
if p.Grants.Can(authz.MonitorsRead) {
rows, err := q.SupportOptionsMonitors(ctx, p.Org.ID)
if err != nil {
return err
}
for _, r := range rows {
o.Monitors = append(o.Monitors, web.SupportOption{ID: r.ID.String(), Name: r.Name})
}
}
if p.Grants.Can(authz.NotificationsRead) {
chans, err := q.SupportOptionsChannels(ctx, p.Org.ID)
if err != nil {
return err
}
for _, r := range chans {
o.Channels = append(o.Channels, web.SupportOption{ID: r.ID.String(), Name: r.Name + " (" + r.Type + ")"})
}
groups, err := q.SupportOptionsAlertGroups(ctx, p.Org.ID)
if err != nil {
return err
}
for _, r := range groups {
o.AlertGroups = append(o.AlertGroups, web.SupportOption{ID: r.ID.String(), Name: r.Name})
}
}
if p.Grants.Can(authz.StatusPagesRead) {
rows, err := q.SupportOptionsStatusPages(ctx, p.Org.ID)
if err != nil {
return err
}
for _, r := range rows {
o.StatusPages = append(o.StatusPages, web.SupportOption{ID: r.ID.String(), Name: r.Title})
}
}
if p.Grants.Can(authz.IncidentsRead) {
rows, err := q.SupportOptionsIncidents(ctx, p.Org.ID)
if err != nil {
return err
}
for _, r := range rows {
name := r.MonitorName
if r.Title != "" {
name = r.Title + " · " + name
}
o.Incidents = append(o.Incidents, web.SupportOption{ID: r.ID.String(), Name: name + " · " + r.StartedAt.UTC().Format(timeLayout)})
}
}
return nil
})
return o, err
}
func (s *Server) supportPage(c *gin.Context) {
sess, me, p, ok := s.supportMe(c)
if !ok {
return
}
ctx := c.Request.Context()
opts, err := s.supportOptions(ctx, p)
if err != nil {
internalError(c, err)
return
}
var rows []store.SupportTicket
if err := s.db.Tx(ctx, tenant.User(sess.UserID), func(q *store.Queries) error {
var err error
rows, err = q.ListUserSupportTickets(ctx, sess.UserID)
return err
}); err != nil {
internalError(c, err)
return
}
tickets := make([]web.SupportTicket, len(rows))
for i, t := range rows {
tickets[i] = toWebTicket(supportTicketView{ID: t.ID, Subject: t.Subject, Status: t.Status, UpdatedAt: t.UpdatedAt})
}
web.Render(c, http.StatusOK, web.SupportPage(s.pageFor(c, "support.title"), me, tickets, opts))
}
func (s *Server) supportTicketPage(c *gin.Context) {
sess, me, _, ok := s.supportMe(c)
if !ok {
return
}
s.renderTicket(c, me, tenant.User(sess.UserID), false)
}
func (s *Server) renderTicket(c *gin.Context, me web.Me, scope tenant.Scope, staff bool) {
id, err := uuid.Parse(c.Param("id"))
var v supportTicketView
if err == nil {
v, err = s.loadTicket(c.Request.Context(), scope, id, staff)
}
if err != nil && !errors.Is(err, pgx.ErrNoRows) {
internalError(c, err)
return
}
if err != nil {
back := "/support"
if staff {
back = "/admin/support"
}
c.Redirect(http.StatusSeeOther, back)
return
}
var account *web.SupportAccount
if staff {
a, err := s.ticketAccount(c.Request.Context(), id)
if err != nil {
internalError(c, err)
return
}
account = &a
}
web.Render(c, http.StatusOK, web.SupportTicketPage(s.pageFor(c, "support.title"), me, toWebTicket(v), account))
}
func (s *Server) adminSupportPage(c *gin.Context) {
me, ok := s.adminMe(c)
if !ok {
return
}
status := supportStatusFilter(c)
rows, err := s.supportTickets(c.Request.Context(), status)
if err != nil {
internalError(c, err)
return
}
tickets := make([]web.SupportTicket, len(rows))
for i, t := range rows {
tickets[i] = toWebTicket(supportTicketView{ID: t.ID, Subject: t.Subject, Status: t.Status, Org: t.OrgName, User: t.UserEmail, UpdatedAt: t.UpdatedAt})
}
filter := "all"
if status != nil {
filter = *status
}
settings := s.supportSettings(c.Request.Context())
web.Render(c, http.StatusOK, web.AdminSupportPage(s.pageFor(c, "support.admin_title"), me, tickets, filter, web.SupportSettings{Enabled: settings.Enabled, MaxOpen: settings.MaxOpen}))
}
func (s *Server) adminSupportTicketPage(c *gin.Context) {
me, ok := s.adminMe(c)
if !ok {
return
}
s.renderTicket(c, me, tenant.System(), true)
}
// ticketAccount gathers what admins need to answer a ticket: the account,
// its organizations with their limits and usage, and its other tickets.
func (s *Server) ticketAccount(ctx context.Context, ticket uuid.UUID) (web.SupportAccount, error) {
var a web.SupportAccount
platform := s.platformLimits(ctx)
err := s.db.Tx(ctx, tenant.System(), func(q *store.Queries) error {
t, err := q.GetSupportTicket(ctx, ticket)
if err != nil {
return err
}
u, err := q.GetUser(ctx, t.UserID)
if err != nil {
return err
}
a = web.SupportAccount{
ID: u.ID.String(), Email: u.Email, Name: u.DisplayName, Created: u.CreatedAt.UTC().Format(timeLayout),
Verified: u.EmailVerifiedAt != nil, TOTP: u.TotpEnabledAt != nil, Password: u.PasswordHash != nil,
Admin: u.IsAdmin, Locale: deref(u.Locale),
}
if u.DisabledAt != nil {
a.Suspended = true
a.SuspendedReason = u.DisabledReason
}
a.OrgLimit = platform.OrgsPerAccount
if u.LimitOrgs != nil {
a.OrgLimit = int(*u.LimitOrgs)
}
owned, err := q.CountOwnedOrgs(ctx, u.ID)
if err != nil {
return err
}
a.OrgsOwned = int(owned)
if a.OpenTickets, err = q.CountOpenSupportTickets(ctx, u.ID); err != nil {
return err
}
ms, err := q.UserMemberships(ctx, u.ID)
if err != nil {
return err
}
for _, m := range ms {
o, err := q.GetOrg(ctx, m.ID)
if err != nil {
return err
}
mon, err := q.CountMonitors(ctx, o.ID)
if err != nil {
return err
}
pages, err := q.CountStatusPages(ctx, o.ID)
if err != nil {
return err
}
l := s.orgLimits(ctx, o)
org := web.SupportOrg{
Name: o.Name, Slug: o.Slug, Owner: m.IsOwner, Current: t.OrgID != nil && *t.OrgID == o.ID,
Monitors: int(mon), MonitorLimit: l.Monitors, StatusPages: int(pages), StatusPageLimit: l.StatusPages,
RegionsPerMonitor: l.RegionsPerMonitor,
}
if o.SuspendedAt != nil {
org.Suspended = true
org.SuspendedReason = o.SuspendedReason
}
a.Orgs = append(a.Orgs, org)
}
return nil
})
return a, err
}
+85
View File
@@ -0,0 +1,85 @@
package api
import (
"context"
"encoding/json"
"errors"
"net/http"
"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"
)
const settingSupport = "support"
// supportSettings are how the platform runs its support tickets.
type supportSettings struct {
Enabled bool `json:"enabled"`
// MaxOpen limits the tickets an account has open, answered ones
// included, at the same time; 0 means unlimited.
MaxOpen int `json:"max_open_tickets" binding:"min=0,max=1000"`
}
func defaultSupportSettings() supportSettings { return supportSettings{Enabled: true, MaxOpen: 3} }
func (s *Server) supportSettings(ctx context.Context) supportSettings {
v, err := s.support.get(ctx, s.rdb, func(ctx context.Context) (supportSettings, error) {
v := defaultSupportSettings()
err := s.db.Tx(ctx, tenant.System(), func(q *store.Queries) error {
raw, err := q.GetPlatformSetting(ctx, settingSupport)
if errors.Is(err, pgx.ErrNoRows) {
return nil
}
if err != nil {
return err
}
return json.Unmarshal(raw, &v)
})
return v, err
})
if err != nil {
s.log.WarnContext(ctx, "loading support settings failed", "error", err)
return defaultSupportSettings()
}
return v
}
// requireSupport answers for accounts only while support is enabled; the
// admins keep their tickets either way.
func (s *Server) requireSupport() gin.HandlerFunc {
return func(c *gin.Context) {
if !s.supportSettings(c.Request.Context()).Enabled {
fail(c, http.StatusForbidden, "support_disabled")
c.Abort()
return
}
c.Next()
}
}
func (s *Server) adminGetSupportSettings(c *gin.Context) {
c.JSON(http.StatusOK, s.supportSettings(c.Request.Context()))
}
func (s *Server) adminSetSupportSettings(c *gin.Context) {
var req supportSettings
if !bind(c, &req) {
return
}
ctx := c.Request.Context()
raw, _ := json.Marshal(req)
auditDetail(c, "settings", req)
if err := s.db.Tx(ctx, tenant.System(), func(q *store.Queries) error {
return q.SetPlatformSetting(ctx, store.SetPlatformSettingParams{Key: settingSupport, Value: raw})
}); err != nil {
internalError(c, err)
return
}
if err := s.support.bump(ctx, s.rdb); err != nil {
s.log.ErrorContext(ctx, "announcing support settings failed", "error", err)
}
c.Status(http.StatusNoContent)
}
+190
View File
@@ -0,0 +1,190 @@
package api_test
import (
"context"
"net/http"
"strings"
"testing"
"time"
"git.zb-server.de/ZB-Server/uptimesebi/internal/config"
"git.zb-server.de/ZB-Server/uptimesebi/internal/notify/notifytest"
"git.zb-server.de/ZB-Server/uptimesebi/internal/store"
"git.zb-server.de/ZB-Server/uptimesebi/internal/tenant"
)
func TestSupportTickets(t *testing.T) {
mail := notifytest.NewSMTP(t)
e := newEnvWith(t, func(c *config.API) { c.SMTPURL, c.SignupVerify = mail.URL(), "off" })
ctx := context.Background()
admin := e.browser(t)
admin.signup("a@"+uniq("sup")+".test", uniq("sup-"))
if err := tenant.New(e.dbPool).Tx(ctx, tenant.Global(), func(q *store.Queries) error {
return q.MakeAdmin(ctx, admin.userIDSelf())
}); err != nil {
t.Fatal(err)
}
userEmail := "u@" + uniq("sup") + ".test"
user := e.browser(t)
user.signup(userEmail, uniq("sup-"))
userID := user.userIDSelf()
mailed := func(to, link string) {
t.Helper()
waitFor(t, 5*time.Second, "a mail with "+link, func() bool {
for _, m := range mail.Messages() {
if strings.Contains(strings.Join(m.To, ","), to) && strings.Contains(m.Data, link) {
return true
}
}
return false
})
}
st, body := user.do("POST", "/api/v1/support/tickets", map[string]any{"subject": " ", "message": "x"})
expect(t, "ticket without subject", st, body, http.StatusUnprocessableEntity, "invalid_input")
st, created := user.do("POST", "/api/v1/support/tickets", map[string]any{"subject": "Checks are late", "message": "Since **Monday**."})
if st != http.StatusCreated || created["status"] != "open" {
t.Fatalf("open ticket = %d %v", st, created)
}
id := created["id"].(string)
mailed(adminEmailOf(t, admin), "/admin/support/"+id)
// Only the account and the admins see it.
other := e.browser(t)
other.signup("o@"+uniq("sup")+".test", uniq("sup-"))
if st, _ := other.do("GET", "/api/v1/support/tickets/"+id, nil); st != http.StatusNotFound {
t.Errorf("another account reads the ticket = %d", st)
}
if st, _ := other.do("POST", "/api/v1/support/tickets/"+id+"/messages", map[string]any{"message": "me too"}); st != http.StatusNotFound {
t.Errorf("another account replies = %d", st)
}
if st, _ := user.do("GET", "/api/v1/admin/support/tickets", nil); st != http.StatusForbidden && st != http.StatusNotFound {
t.Errorf("an account lists every ticket = %d", st)
}
_, list := admin.do("GET", "/api/v1/admin/support/tickets", nil)
if !strings.Contains(mustJSON(list), id) || !strings.Contains(mustJSON(list), userEmail) {
t.Errorf("open tickets for the admins lack it: %v", list)
}
// Answering moves it to the account and mails it; its reply moves it back.
if st, body := admin.do("POST", "/api/v1/admin/support/tickets/"+id+"/messages", map[string]any{"message": "Fixed, sorry!"}); st != http.StatusCreated || body["status"] != "answered" {
t.Fatalf("answer = %d %v", st, body)
}
mailed(userEmail, "/support/"+id)
_, ticket := user.do("GET", "/api/v1/support/tickets/"+id, nil)
msgs, _ := ticket["messages"].([]any)
if ticket["status"] != "answered" || len(msgs) != 2 || msgs[1].(map[string]any)["from_staff"] != true || msgs[1].(map[string]any)["author"] != nil {
t.Errorf("ticket for the account = %v", ticket)
}
_, _, html := user.page("/support/" + id)
for _, want := range []string{"Checks are late", "<strong>Monday</strong>", "Fixed, sorry!", "Close ticket"} {
if !strings.Contains(html, want) {
t.Errorf("ticket page lacks %q", want)
}
}
if _, _, html := admin.page("/admin/support/" + id); !strings.Contains(html, userEmail) {
t.Error("the admins' ticket page does not name the account")
}
user.do("POST", "/api/v1/support/tickets/"+id+"/messages", map[string]any{"message": "Thanks!"})
if _, tk := user.do("GET", "/api/v1/support/tickets/"+id, nil); tk["status"] != "open" {
t.Errorf("after the account's reply status = %v", tk["status"])
}
// Accounts close and reopen theirs, nothing else.
st, body = user.do("PUT", "/api/v1/support/tickets/"+id+"/status", map[string]any{"status": "answered"})
expect(t, "account marks answered", st, body, http.StatusUnprocessableEntity, "invalid_input")
if st, _ := user.do("PUT", "/api/v1/support/tickets/"+id+"/status", map[string]any{"status": "closed"}); st != http.StatusNoContent {
t.Errorf("close = %d", st)
}
_, closed := admin.do("GET", "/api/v1/admin/support/tickets?status=closed", nil)
if !strings.Contains(mustJSON(closed), id) {
t.Error("the closed filter lacks the ticket")
}
if _, _, html := user.page("/support"); !strings.Contains(html, "Checks are late") || !strings.Contains(html, "closed") {
t.Error("the support page lacks the closed ticket")
}
// Tickets point at things of the active organization the account can
// read, never at another's; the admins see the account at a glance.
_, mon := user.do("POST", "/api/v1/org/monitors", map[string]any{"name": "Checkout API", "type": "heartbeat", "interval_seconds": 3600})
_, foreign := other.do("POST", "/api/v1/org/monitors", map[string]any{"name": "Theirs", "type": "heartbeat", "interval_seconds": 3600})
st, body = user.do("POST", "/api/v1/support/tickets", map[string]any{"subject": "Peek", "message": "x", "monitor_id": foreign["id"]})
expect(t, "ticket about another organization's monitor", st, body, http.StatusUnprocessableEntity, "invalid_input")
if _, _, page := user.page("/support"); !strings.Contains(page, `name="monitor_id"`) || !strings.Contains(page, "Checkout API") {
t.Error("the new ticket form does not offer the monitors")
}
st, withRef := user.do("POST", "/api/v1/support/tickets", map[string]any{"subject": "Heartbeat missing", "message": "x", "monitor_id": mon["id"], "channel_id": ""})
if st != http.StatusCreated {
t.Fatalf("ticket about a monitor = %d %v", st, withRef)
}
refID := withRef["id"].(string)
_, got := user.do("GET", "/api/v1/support/tickets/"+refID, nil)
if refs := mustJSON(got["references"]); !strings.Contains(refs, "Checkout API") || !strings.Contains(refs, `"org"`) {
t.Errorf("references = %s", refs)
}
if _, _, page := admin.page("/admin/support/" + refID); !strings.Contains(page, "Checkout API") || !strings.Contains(page, "Organizations owned") || !strings.Contains(page, "1 / ") {
t.Error("the admins' ticket page lacks the references or the account's details")
}
// The admins limit open tickets per account and can switch support off.
t.Cleanup(func() {
admin.do("PUT", "/api/v1/admin/support/settings", map[string]any{"enabled": true, "max_open_tickets": 3})
})
if st, body := admin.do("PUT", "/api/v1/admin/support/settings", map[string]any{"enabled": true, "max_open_tickets": 2}); st != http.StatusNoContent {
t.Fatalf("set support settings = %d %v", st, body)
}
if st, body := user.do("POST", "/api/v1/support/tickets", map[string]any{"subject": "Second", "message": "x"}); st != http.StatusCreated {
t.Fatalf("second open ticket = %d %v", st, body)
}
st, body = user.do("POST", "/api/v1/support/tickets", map[string]any{"subject": "Third", "message": "x"})
expect(t, "third open ticket", st, body, http.StatusConflict, "too_many_tickets")
st, body = user.do("PUT", "/api/v1/support/tickets/"+id+"/status", map[string]any{"status": "open"})
expect(t, "reopen beyond the limit", st, body, http.StatusConflict, "too_many_tickets")
st, body = user.do("POST", "/api/v1/support/tickets/"+id+"/messages", map[string]any{"message": "again"})
expect(t, "reply to a closed ticket beyond the limit", st, body, http.StatusConflict, "too_many_tickets")
admin.do("PUT", "/api/v1/admin/support/settings", map[string]any{"enabled": false, "max_open_tickets": 0})
st, body = user.do("POST", "/api/v1/support/tickets", map[string]any{"subject": "Off", "message": "x"})
expect(t, "ticket while support is off", st, body, http.StatusForbidden, "support_disabled")
if _, _, page := user.page("/support"); !strings.Contains(page, "switched off") || strings.Contains(page, `href="/support"`) {
t.Error("the support page or the menu still offers support while it is off")
}
if st, _, _ := admin.page("/admin/support/" + refID); st != http.StatusOK {
t.Errorf("admins read tickets while support is off = %d", st)
}
admin.do("PUT", "/api/v1/admin/support/settings", map[string]any{"enabled": true, "max_open_tickets": 0})
// A suspended account can still ask why, and its export holds the
// conversation.
if st, body := admin.do("PUT", "/api/v1/admin/users/"+userID.String()+"/suspension", map[string]any{"suspended": true, "reason": "Abuse"}); st != http.StatusNoContent {
t.Fatalf("suspend = %d %v", st, body)
}
user = e.browser(t)
if st, body := user.do("POST", "/api/v1/auth/login", map[string]any{"email": userEmail, "password": password}); st != http.StatusOK {
t.Fatalf("suspended account signs in = %d %v", st, body)
}
if _, _, page := user.page("/account/suspended"); !strings.Contains(page, `href="/support"`) {
t.Error("the suspension page does not lead to support")
}
if st, body := user.do("POST", "/api/v1/support/tickets", map[string]any{"subject": "Why?", "message": "I did nothing."}); st != http.StatusCreated {
t.Errorf("suspended account opens a ticket = %d %v", st, body)
}
st, body = user.do("POST", "/api/v1/support/tickets", map[string]any{"subject": "Why, again?", "message": "Hello?"})
expect(t, "second ticket of a suspended account", st, body, http.StatusConflict, "suspended_ticket_limit")
if st, _, _ := user.page("/support"); st != http.StatusOK {
t.Errorf("support page of a suspended account = %d", st)
}
_, _, export := user.download("/api/v1/me/export")
if !strings.Contains(string(export), "Checks are late") || !strings.Contains(string(export), "Fixed, sorry!") {
t.Error("the account export lacks the tickets")
}
}
func adminEmailOf(t *testing.T, b *browser) string {
t.Helper()
_, me := b.do("GET", "/api/v1/me", nil)
email, _ := me["email"].(string)
if email == "" {
t.Fatalf("no email in %v", me)
}
return email
}
+2 -1
View File
@@ -152,7 +152,8 @@ func (s *Sessions) Get(ctx context.Context, token string) (*Session, error) {
} }
// Sliding expiry, but never beyond the absolute lifetime. // Sliding expiry, but never beyond the absolute lifetime.
remaining := s.absolute - s.now().Sub(sess.CreatedAt) remaining := s.absolute - s.now().Sub(sess.CreatedAt)
if err := s.rdb.Expire(ctx, k, min(s.idle, remaining)).Err(); err != nil { // PEXPIRE: the rest of the lifetime may be below a second.
if err := s.rdb.PExpire(ctx, k, min(s.idle, remaining)).Err(); err != nil {
return nil, fmt.Errorf("auth: touch session: %w", err) return nil, fmt.Errorf("auth: touch session: %w", err)
} }
return sess, nil return sess, nil
+35 -4
View File
@@ -26,7 +26,9 @@ type API interface {
} }
const ( const (
pollWait = 20 * time.Second pollWait = 20 * time.Second
// quickPoll is a long poll answered empty faster than any wait would.
quickPoll = 200 * time.Millisecond
flushInterval = 2 * time.Second flushInterval = 2 * time.Second
// maxPending bounds results kept while the API is unreachable. // maxPending bounds results kept while the API is unreachable.
maxPending = 50_000 maxPending = 50_000
@@ -127,6 +129,12 @@ func (r *Runner) Run(ctx context.Context, drain time.Duration) error {
func (r *Runner) poll(ctx context.Context, running *sync.WaitGroup) error { func (r *Runner) poll(ctx context.Context, running *sync.WaitGroup) error {
backoff := time.Second backoff := time.Second
// failing and failures track an outage, so its end is logged too: a log
// whose last line is an error otherwise reads as a checker stuck.
var (
failing time.Time
failures int
)
for ctx.Err() == nil { for ctx.Err() == nil {
free := cap(r.slots) - len(r.slots) free := cap(r.slots) - len(r.slots)
wait := pollWait wait := pollWait
@@ -134,6 +142,7 @@ func (r *Runner) poll(ctx context.Context, running *sync.WaitGroup) error {
// Still poll as a heartbeat, but do not take work. // Still poll as a heartbeat, but do not take work.
wait = 0 wait = 0
} }
asked := time.Now()
jobs, err := r.api.Jobs(ctx, free, wait) jobs, err := r.api.Jobs(ctx, free, wait)
switch { switch {
case errors.Is(err, agentapi.ErrUnauthorized): case errors.Is(err, agentapi.ErrUnauthorized):
@@ -143,11 +152,19 @@ func (r *Runner) poll(ctx context.Context, running *sync.WaitGroup) error {
return nil return nil
} }
r.log.Warn("polling for jobs failed", "error", err, "retry_in", backoff) r.log.Warn("polling for jobs failed", "error", err, "retry_in", backoff)
if failing.IsZero() {
failing = time.Now()
}
failures++
sleep(ctx, backoff) sleep(ctx, backoff)
backoff = min(backoff*2, 30*time.Second) backoff = min(backoff*2, 30*time.Second)
continue continue
} }
backoff = time.Second backoff = time.Second
if !failing.IsZero() {
r.log.Info("polling for jobs works again", "failed_for", time.Since(failing).Round(time.Second).String(), "failures", failures)
failing, failures = time.Time{}, 0
}
r.lastPoll.Store(time.Now().UnixMilli()) r.lastPoll.Store(time.Now().UnixMilli())
for _, j := range jobs { for _, j := range jobs {
r.slots <- struct{}{} r.slots <- struct{}{}
@@ -157,7 +174,9 @@ func (r *Runner) poll(ctx context.Context, running *sync.WaitGroup) error {
r.results <- r.execute(ctx, j) r.results <- r.execute(ctx, j)
}() }()
} }
if free == 0 { // A long poll answered empty at once, as by an instance shutting
// down, is not repeated at once either.
if free == 0 || (len(jobs) == 0 && wait > 0 && time.Since(asked) < quickPoll) {
sleep(ctx, time.Second) sleep(ctx, time.Second)
} }
} }
@@ -188,15 +207,27 @@ func (r *Runner) execute(ctx context.Context, j agentapi.Job) agentapi.Result {
func (r *Runner) report(ctx context.Context) { func (r *Runner) report(ctx context.Context) {
tick := time.NewTicker(flushInterval) tick := time.NewTicker(flushInterval)
defer tick.Stop() defer tick.Stop()
var pending []agentapi.Result var (
pending []agentapi.Result
// failing is when reporting started to fail, zero while it works.
failing time.Time
)
flush := func(ctx context.Context) { flush := func(ctx context.Context) {
sent := 0
for len(pending) > 0 { for len(pending) > 0 {
n := min(len(pending), agentapi.MaxResults) n := min(len(pending), agentapi.MaxResults)
if err := r.api.Report(ctx, pending[:n]); err != nil { if err := r.api.Report(ctx, pending[:n]); err != nil {
r.log.Warn("reporting results failed", "error", err, "pending", len(pending)) r.log.Warn("reporting results failed", "error", err, "pending", len(pending))
if failing.IsZero() {
failing = time.Now()
}
return return
} }
pending = pending[n:] pending, sent = pending[n:], sent+n
}
if !failing.IsZero() {
r.log.Info("reporting results works again", "failed_for", time.Since(failing).Round(time.Second).String(), "sent", sent)
failing = time.Time{}
} }
} }
for { for {
+108
View File
@@ -0,0 +1,108 @@
package checker
import (
"bytes"
"context"
"errors"
"log/slog"
"strings"
"sync"
"testing"
"time"
"github.com/google/uuid"
"git.zb-server.de/ZB-Server/uptimesebi/internal/agentapi"
"git.zb-server.de/ZB-Server/uptimesebi/internal/check"
)
// flakyAPI fails its first calls, like an API being rolled out.
type flakyAPI struct {
mu sync.Mutex
jobFails int
reportFails int
gave bool
reported int
}
func (f *flakyAPI) Jobs(ctx context.Context, _ int, wait time.Duration) ([]agentapi.Job, error) {
f.mu.Lock()
if f.jobFails > 0 {
f.jobFails--
f.mu.Unlock()
return nil, errors.New("504 Gateway Timeout")
}
if !f.gave {
f.gave = true
f.mu.Unlock()
return []agentapi.Job{{MonitorID: uuid.New(), Type: "tcp", Target: "x:1"}}, nil
}
f.mu.Unlock()
select {
case <-time.After(min(wait, 50*time.Millisecond)):
case <-ctx.Done():
}
return nil, nil
}
func (f *flakyAPI) Report(_ context.Context, rs []agentapi.Result) error {
f.mu.Lock()
defer f.mu.Unlock()
if f.reportFails > 0 {
f.reportFails--
return errors.New("context deadline exceeded")
}
f.reported += len(rs)
return nil
}
func (f *flakyAPI) Release(context.Context) error { return nil }
type syncBuffer struct {
mu sync.Mutex
b bytes.Buffer
}
func (s *syncBuffer) Write(p []byte) (int, error) {
s.mu.Lock()
defer s.mu.Unlock()
return s.b.Write(p)
}
func (s *syncBuffer) String() string {
s.mu.Lock()
defer s.mu.Unlock()
return s.b.String()
}
func TestRecoveryIsLogged(t *testing.T) {
api := &flakyAPI{jobFails: 1, reportFails: 1}
var logs syncBuffer
r := New(api, 2, slog.New(slog.NewJSONHandler(&logs, nil)))
r.run = func(context.Context, check.Spec) check.Outcome { return check.Outcome{OK: true} }
ctx, cancel := context.WithCancel(context.Background())
done := make(chan error, 1)
go func() { done <- r.Run(ctx, time.Second) }()
deadline := time.Now().Add(10 * time.Second)
for time.Now().Before(deadline) {
out := logs.String()
if strings.Contains(out, "polling for jobs works again") && strings.Contains(out, "reporting results works again") {
break
}
time.Sleep(50 * time.Millisecond)
}
cancel()
if err := <-done; err != nil {
t.Errorf("Run() = %v", err)
}
out := logs.String()
for _, want := range []string{`"msg":"polling for jobs works again"`, `"failures":1`, `"msg":"reporting results works again"`, `"sent":1`} {
if !strings.Contains(out, want) {
t.Errorf("log lacks %s:\n%s", want, out)
}
}
if n := strings.Count(out, "works again"); n != 2 {
t.Errorf("recovery logged %d times, want once each", n)
}
}
+22 -1
View File
@@ -101,7 +101,28 @@ type API struct {
// AgentImage is the image name agents are installed and updated from; // AgentImage is the image name agents are installed and updated from;
// "-checker" or "-statuspage" is appended. Change it for a mirror. // "-checker" or "-statuspage" is appended. Change it for a mirror.
AgentImage string `env:"UPTIME_AGENT_IMAGE" envDefault:"git.zb-server.de/zb-server/uptimesebi"` AgentImage string `env:"UPTIME_AGENT_IMAGE" envDefault:"git.zb-server.de/zb-server/uptimesebi"`
Retention Retention // RegionAlertAfter is how long a region with monitors may have no live
// checker before its admins or owners are told; 0 disables it.
RegionAlertAfter time.Duration `env:"UPTIME_REGION_ALERT_AFTER" envDefault:"5m"`
// Certificates bounds the certificates status page servers may order
// for custom domains.
Certificates Certificates
Retention Retention
}
// Certificates limits new ACME orders for custom domains, so neither one
// organization nor a flood of names uses up the CA's rate limits, which
// apply per ACME account and so to all servers of an owner together.
// Renewals are not counted.
type Certificates struct {
// PerOrgPerDay is for the domains of one organization.
PerOrgPerDay int `env:"UPTIME_CERTS_PER_ORG_PER_DAY" envDefault:"20"`
// PerOwnerPerHour is for all servers of the platform, or of one
// organization, together.
PerOwnerPerHour int `env:"UPTIME_CERTS_PER_HOUR" envDefault:"30"`
// PerNamePerDay stops a domain whose orders keep failing from using
// up the rest.
PerNamePerDay int `env:"UPTIME_CERTS_PER_NAME_PER_DAY" envDefault:"5"`
} }
// Retention sets how long data is kept. Zero keeps it forever. // Retention sets how long data is kept. Zero keeps it forever.
+16 -9
View File
@@ -1,9 +1,11 @@
// Package evaluate turns per-region check results into a monitor state. // Package evaluate turns per-region check results into a monitor state.
// //
// A monitor goes down only when every region it is assigned to has failed // A monitor goes down when every region it is assigned to that reported
// the configured number of times in a row and reported recently. A region // recently has failed the configured number of times in a row: one region
// without recent results counts as unknown and keeps the monitor up: one // failing while another succeeds is the checker's problem, not the
// checker losing its network must not page anyone. Any successful region // target's. A region without recent results counts as unknown and is left
// out, so a dead region neither keeps a monitor up nor takes it down; with
// every region unknown nothing is judged at all. Any successful region
// brings the monitor back up. // brings the monitor back up.
// //
// The state lives in Redis and each observation is applied by one Lua // The state lives in Redis and each observation is applied by one Lua
@@ -53,9 +55,9 @@ type Observation struct {
Regions []string Regions []string
} }
// staleAfter is how old a region's last result may be before the region // StaleAfter is how old a region's last result may be before the region
// counts as unknown. // counts as unknown.
func staleAfter(interval time.Duration) time.Duration { func StaleAfter(interval time.Duration) time.Duration {
return max(3*interval, 2*time.Minute) return max(3*interval, 2*time.Minute)
} }
@@ -86,12 +88,17 @@ if state == 'down' then
end end
return 'none' return 'none'
end end
local reporting = 0
for i = 7, #ARGV do for i = 7, #ARGV do
local r = ARGV[i] local r = ARGV[i]
local fails = tonumber(redis.call('HGET', key, 'f:' .. r) or '0')
local seen = tonumber(redis.call('HGET', key, 'a:' .. r) or '0') local seen = tonumber(redis.call('HGET', key, 'a:' .. r) or '0')
if fails < need or seen < stale then return 'none' end if seen >= stale then
local fails = tonumber(redis.call('HGET', key, 'f:' .. r) or '0')
if fails < need then return 'none' end
reporting = reporting + 1
end
end end
if reporting == 0 then return 'none' end
redis.call('HSET', key, 'state', 'down') redis.call('HSET', key, 'state', 'down')
return 'down' return 'down'
`) `)
@@ -113,7 +120,7 @@ func (e *Evaluator) Observe(ctx context.Context, o Observation) (Transition, err
if o.OK { if o.OK {
ok = "1" ok = "1"
} }
stale := e.now().Add(-staleAfter(o.Interval)).UnixMilli() stale := e.now().Add(-StaleAfter(o.Interval)).UnixMilli()
args := []any{o.Region, ok, o.At.UnixMilli(), max(o.Confirmations, 1), stale, int(stateTTL.Seconds())} args := []any{o.Region, ok, o.At.UnixMilli(), max(o.Confirmations, 1), stale, int(stateTTL.Seconds())}
for _, r := range o.Regions { for _, r := range o.Regions {
args = append(args, r) args = append(args, r)
+22 -7
View File
@@ -55,9 +55,9 @@ func play(t *testing.T, e *Evaluator, now *time.Time, regions []string, confirma
func TestDownOnlyWhenAllRegionsFail(t *testing.T) { func TestDownOnlyWhenAllRegionsFail(t *testing.T) {
e, now := newTest(t) e, now := newTest(t)
play(t, e, now, []string{"eu", "us"}, 2, []step{ play(t, e, now, []string{"eu", "us"}, 2, []step{
{"eu", false, None},
{"eu", false, None}, // eu confirmed down, us has not reported
{"us", true, None}, {"us", true, None},
{"eu", false, None},
{"eu", false, None}, // eu confirmed down, us still fine
{"us", false, None}, {"us", false, None},
{"eu", false, None}, {"eu", false, None},
{"us", false, Down}, // both regions failed twice in a row {"us", false, Down}, // both regions failed twice in a row
@@ -79,7 +79,7 @@ func TestSingleRegionWithConfirmations(t *testing.T) {
}) })
} }
func TestSilentRegionBlocksAlert(t *testing.T) { func TestSilentRegionIsLeftOut(t *testing.T) {
e, now := newTest(t) e, now := newTest(t)
id := uuid.New() id := uuid.New()
obs := func(region string, ok bool) Transition { obs := func(region string, ok bool) Transition {
@@ -92,12 +92,27 @@ func TestSilentRegionBlocksAlert(t *testing.T) {
} }
return got return got
} }
obs("us", false) obs("us", true)
// us stops reporting for longer than three intervals. // us stops reporting for longer than three intervals: the failures of
// eu alone decide.
*now = now.Add(5 * time.Minute) *now = now.Add(5 * time.Minute)
if got := obs("eu", false); got != None { if got := obs("eu", false); got != Down {
t.Errorf("eu failure with us silent = %v, want none", got) t.Errorf("eu failure with us silent = %v, want down", got)
} }
// us reporting a success again brings the monitor back up.
*now = now.Add(time.Second)
if got := obs("us", true); got != Up {
t.Errorf("us success after the outage = %v, want up", got)
}
}
func TestReportingRegionStillVetoes(t *testing.T) {
e, now := newTest(t)
play(t, e, now, []string{"eu", "us"}, 1, []step{
{"us", true, None},
{"eu", false, None}, // us reported recently and was fine
{"eu", false, None},
})
} }
func TestOutOfOrderResultIgnored(t *testing.T) { func TestOutOfOrderResultIgnored(t *testing.T) {
+152 -5
View File
@@ -1,6 +1,6 @@
{ {
"admin.check_types": "Check-Typen", "admin.check_types": "Check-Typen",
"admin.check_types_intro": "Schalte Typen ab, die diese Installation nicht anbieten kann, etwa Docker auf geteilten Cloud-Checkern oder ICMP ohne die nötigen Rechte. Sie verschwinden für neue Monitore; bestehende laufen weiter.", "admin.check_types_intro": "Schalte Typen ab, die die Checker der Plattform nicht anbieten können, etwa Docker auf geteilten Cloud-Checkern oder ICMP ohne die nötigen Rechte. Organisationen behalten sie für ihre eigenen Checker; bestehende Monitore laufen weiter.",
"admin.checker_network": "Checker-Netzwerk", "admin.checker_network": "Checker-Netzwerk",
"admin.intro": "Hier angelegte Regionen, Checker und Statuspage-Server stehen allen Organisationen zur Verfügung. Organisationen legen ihre eigenen unter Regionen & Checker an.", "admin.intro": "Hier angelegte Regionen, Checker und Statuspage-Server stehen allen Organisationen zur Verfügung. Organisationen legen ihre eigenen unter Regionen & Checker an.",
"admin.platform_private": "Plattform-Checker dürfen private Adressen prüfen", "admin.platform_private": "Plattform-Checker dürfen private Adressen prüfen",
@@ -107,6 +107,7 @@
"audit.action.member.role_unassign": "Rolle entzogen", "audit.action.member.role_unassign": "Rolle entzogen",
"audit.action.monitor.create": "Monitor erstellt", "audit.action.monitor.create": "Monitor erstellt",
"audit.action.monitor.delete": "Monitor gelöscht", "audit.action.monitor.delete": "Monitor gelöscht",
"audit.action.monitor.order": "Monitore angeordnet",
"audit.action.monitor.update": "Monitor geändert", "audit.action.monitor.update": "Monitor geändert",
"audit.action.org.check_types_update": "Check-Typen geändert", "audit.action.org.check_types_update": "Check-Typen geändert",
"audit.action.org.create": "Organisation angelegt", "audit.action.org.create": "Organisation angelegt",
@@ -151,6 +152,11 @@
"audit.action.statuspage.groups_import": "Statusseiten-Gruppen aus Monitor-Gruppen übernommen", "audit.action.statuspage.groups_import": "Statusseiten-Gruppen aus Monitor-Gruppen übernommen",
"audit.action.statuspage.monitors_update": "Monitore der Statusseite geändert", "audit.action.statuspage.monitors_update": "Monitore der Statusseite geändert",
"audit.action.statuspage.update": "Statusseite geändert", "audit.action.statuspage.update": "Statusseite geändert",
"audit.action.support.answer": "Support-Ticket beantwortet",
"audit.action.support.create": "Support-Ticket eröffnet",
"audit.action.support.reply": "Auf Support-Ticket geantwortet",
"audit.action.support.settings": "Support-Einstellungen geändert",
"audit.action.support.status": "Status eines Support-Tickets geändert",
"audit.action.token.create": "API-Token erstellt", "audit.action.token.create": "API-Token erstellt",
"audit.action.token.delete": "API-Token widerrufen", "audit.action.token.delete": "API-Token widerrufen",
"audit.deleted_user": "Gelöschter Benutzer", "audit.deleted_user": "Gelöschter Benutzer",
@@ -497,6 +503,7 @@
"console.nav.admin": "Admin", "console.nav.admin": "Admin",
"console.nav.logout": "Abmelden", "console.nav.logout": "Abmelden",
"console.nav.members": "Mitglieder", "console.nav.members": "Mitglieder",
"console.nav.menu": "Menü",
"console.nav.org": "Organisation", "console.nav.org": "Organisation",
"console.nav.regions": "Regionen & Checker", "console.nav.regions": "Regionen & Checker",
"console.nav.roles": "Rollen", "console.nav.roles": "Rollen",
@@ -508,10 +515,22 @@
"console.sso_required_action": "Mit SSO anmelden", "console.sso_required_action": "Mit SSO anmelden",
"console.suspended_reason": "Grund: {{.Reason}}", "console.suspended_reason": "Grund: {{.Reason}}",
"console.totp_missing_action": "Jetzt einrichten", "console.totp_missing_action": "Jetzt einrichten",
"email.domain_missing.body": "Die Statusseite {{.Page}} wird unter {{.Domain}} ausgeliefert, aber der DNS-Eintrag, der nachweist, dass die Domain zu ihr gehört, ist nicht mehr zu finden.\n\nIst er bis {{.Date}} nicht zurück, wird die Domain abgeschaltet und die Seite dort nicht mehr ausgeliefert. Den Eintrag, der wiederhergestellt werden muss, findest du hier:\n{{.Link}}",
"email.domain_missing.subject": "Der DNS-Eintrag von {{.Domain}} fehlt",
"email.domain_off.body": "Der DNS-Eintrag von {{.Domain}} fehlt seit einer Woche, deshalb wird die Statusseite {{.Page}} dort nicht mehr ausgeliefert.\n\nStelle den Eintrag wieder her und prüfe die Domain erneut:\n{{.Link}}",
"email.domain_off.subject": "{{.Domain}} wurde abgeschaltet",
"email.opened.body": "{{.Monitor}} ({{.Target}}) ist in allen Regionen nicht erreichbar seit {{.Since}}.\n\nLetzte Fehler:\n{{.Cause}}\n\nDu erhältst diese Nachricht, weil ein Benachrichtigungskanal deiner Organisation diese Adresse nutzt.", "email.opened.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.subject": "Region {{.Region}} prüft wieder",
"email.region_down.body": "Region {{.Region}} hat seit {{.Minutes}} Minuten keinen aktiven Checker, seit {{.Since}}.\n\nMonitore, die nur von dort geprüft werden, werden gerade nicht geprüft: Sie fallen weder aus noch alarmieren sie. Monitore mit weiteren Regionen werden nur nach diesen beurteilt, bis diese Region wieder meldet.\n\nStarte einen Checker der Region oder sieh dir seine Logs an:\n{{.Link}}",
"email.region_down.subject": "Region {{.Region}} hat keinen aktiven Checker",
"email.resolved.body": "{{.Monitor}} ({{.Target}}) ist nach {{.Duration}} wieder erreichbar.", "email.resolved.body": "{{.Monitor}} ({{.Target}}) ist nach {{.Duration}} wieder erreichbar.",
"email.resolved.subject": "[UP] {{.Monitor}}", "email.resolved.subject": "[UP] {{.Monitor}}",
"email.support_admin.body": "Hallo,\n\nein Support-Ticket wartet auf eine Antwort:\n\n{{.Subject}}\n\n{{.Link}}",
"email.support_admin.subject": "Support-Ticket: {{.Subject}}",
"email.support_reply.body": "Hallo,\n\nder Support hat dein Ticket „{{.Subject}}“ beantwortet:\n\n{{.Link}}\n\nWenn du weitere Fragen hast, antworte einfach dort.",
"email.support_reply.subject": "Antwort auf dein Support-Ticket: {{.Subject}}",
"email.test.body": "Dies ist ein Test. Wenn du ihn lesen kannst, funktioniert der Kanal.", "email.test.body": "Dies ist ein Test. Wenn du ihn lesen kannst, funktioniert der Kanal.",
"email.test.subject": "Testbenachrichtigung von UptimeSebi", "email.test.subject": "Testbenachrichtigung von UptimeSebi",
"email.verify.body": "Hallo,\n\nbitte bestätige deine E-Mail-Adresse, um die Registrierung abzuschließen:\n\n{{.Link}}\n\nDer Link ist {{.Hours}} Stunden gültig. Wenn du dich nicht registriert hast, ignoriere diese E-Mail; das Konto wird nach einer Woche gelöscht.", "email.verify.body": "Hallo,\n\nbitte bestätige deine E-Mail-Adresse, um die Registrierung abzuschließen:\n\n{{.Link}}\n\nDer Link ist {{.Hours}} Stunden gültig. Wenn du dich nicht registriert hast, ignoriere diese E-Mail; das Konto wird nach einer Woche gelöscht.",
@@ -525,10 +544,12 @@
"error.channel_test_failed": "Die Testbenachrichtigung konnte nicht zugestellt werden.", "error.channel_test_failed": "Die Testbenachrichtigung konnte nicht zugestellt werden.",
"error.channel_type_immutable": "Der Typ eines Kanals kann nicht geändert werden.", "error.channel_type_immutable": "Der Typ eines Kanals kann nicht geändert werden.",
"error.check_type_disabled": "Dieser Check-Typ ist für diese Organisation oder Installation abgeschaltet.", "error.check_type_disabled": "Dieser Check-Typ ist für diese Organisation oder Installation abgeschaltet.",
"error.check_type_own_checkers_only": "Die Checker der Plattform führen diesen Check-Typ nicht aus. Wähle nur eigene Regionen deiner Organisation.",
"error.confirmation_failed": "Die Bestätigung stimmt nicht.", "error.confirmation_failed": "Die Bestätigung stimmt nicht.",
"error.consent_outdated": "Die Dokumente haben sich inzwischen geändert. Lade die Seite neu und stimme der aktuellen Fassung zu.", "error.consent_outdated": "Die Dokumente haben sich inzwischen geändert. Lade die Seite neu und stimme der aktuellen Fassung zu.",
"error.consent_required": "Bitte stimme zuerst Datenschutz und AGB zu.", "error.consent_required": "Bitte stimme zuerst Datenschutz und AGB zu.",
"error.domain_not_verified": "Der TXT-Eintrag wurde noch nicht gefunden. DNS-Änderungen brauchen manchmal etwas Zeit.", "error.domain_changes_exceeded": "Die eigene Domain wurde heute schon {{.Count}}-mal geändert. Versuch es morgen wieder.",
"error.domain_not_verified": "Weder der CNAME- noch der TXT-Eintrag wurde bisher gefunden. DNS-Änderungen brauchen manchmal etwas, bis sie sichtbar sind.",
"error.domain_taken": "Diese Domain nutzt bereits eine andere Statuspage.", "error.domain_taken": "Diese Domain nutzt bereits eine andere Statuspage.",
"error.email_not_configured": "E-Mail ist auf diesem Server nicht verfügbar.", "error.email_not_configured": "E-Mail ist auf diesem Server nicht verfügbar.",
"error.email_taken": "Diese E-Mail-Adresse ist bereits registriert.", "error.email_taken": "Diese E-Mail-Adresse ist bereits registriert.",
@@ -599,6 +620,7 @@
"error.owner_cannot_be_removed": "Owner können nicht entfernt werden. Entziehe zuerst die Owner-Rechte.", "error.owner_cannot_be_removed": "Owner können nicht entfernt werden. Entziehe zuerst die Owner-Rechte.",
"error.owner_has_all_permissions": "Der Owner hat bereits alle Berechtigungen.", "error.owner_has_all_permissions": "Der Owner hat bereits alle Berechtigungen.",
"error.owner_only": "Nur Owner können ändern, wem die Organisation gehört.", "error.owner_only": "Nur Owner können ändern, wem die Organisation gehört.",
"error.page_monitor_limit": "Eine Statusseite darf höchstens {{.Max}} Monitore zeigen.",
"error.password_too_short": "Das Passwort braucht mindestens {{.Min}} Zeichen.", "error.password_too_short": "Das Passwort braucht mindestens {{.Min}} Zeichen.",
"error.permission_escalation": "Du kannst keine Berechtigungen vergeben, die du selbst nicht hast.", "error.permission_escalation": "Du kannst keine Berechtigungen vergeben, die du selbst nicht hast.",
"error.platform_region_limit": "Ein Monitor darf aus höchstens {{.Max}} Plattform-Regionen geprüft werden; eigene Checker-Regionen zählen nicht.", "error.platform_region_limit": "Ein Monitor darf aus höchstens {{.Max}} Plattform-Regionen geprüft werden; eigene Checker-Regionen zählen nicht.",
@@ -632,11 +654,14 @@
"error.status_in_use": "Updates benutzen diesen Status; er bleibt, damit ihr Verlauf verständlich bleibt. Benenne ihn um oder ändere die Farbe.", "error.status_in_use": "Updates benutzen diesen Status; er bleibt, damit ihr Verlauf verständlich bleibt. Benenne ihn um oder ändere die Farbe.",
"error.status_name_taken": "Einen Status mit diesem Namen gibt es schon.", "error.status_name_taken": "Einen Status mit diesem Namen gibt es schon.",
"error.status_page_limit": "Deine Organisation hat ihr Limit von {{.Max}} Statusseiten erreicht.", "error.status_page_limit": "Deine Organisation hat ihr Limit von {{.Max}} Statusseiten erreicht.",
"error.support_disabled": "Support-Tickets sind auf dieser Plattform abgeschaltet.",
"error.suspended_ticket_limit": "Solange dein Konto gesperrt ist, kannst du ein Ticket eröffnen. Antworte stattdessen darauf.",
"error.target_is_admin": "Plattform-Admins können hier nicht gesperrt oder gelöscht werden.", "error.target_is_admin": "Plattform-Admins können hier nicht gesperrt oder gelöscht werden.",
"error.token_lifetime_exceeds_policy": { "error.token_lifetime_exceeds_policy": {
"one": "Tokens in dieser Organisation müssen innerhalb von {{.Count}} Tag ablaufen.", "one": "Tokens in dieser Organisation müssen innerhalb von {{.Count}} Tag ablaufen.",
"other": "Tokens in dieser Organisation müssen innerhalb von {{.Count}} Tagen ablaufen." "other": "Tokens in dieser Organisation müssen innerhalb von {{.Count}} Tagen ablaufen."
}, },
"error.too_many_tickets": "Du kannst {{.Count}} offene Tickets gleichzeitig haben. Schließe eins oder antworte stattdessen darauf.",
"error.totp_already_enabled": "TOTP ist bereits aktiv.", "error.totp_already_enabled": "TOTP ist bereits aktiv.",
"error.totp_required_by_org": "Eine deiner Organisationen verlangt TOTP.", "error.totp_required_by_org": "Eine deiner Organisationen verlangt TOTP.",
"error.totp_setup_expired": "Einrichtung abgelaufen, bitte neu starten.", "error.totp_setup_expired": "Einrichtung abgelaufen, bitte neu starten.",
@@ -695,6 +720,7 @@
"export.field.api_tokens": "API-Tokens", "export.field.api_tokens": "API-Tokens",
"export.field.audit_log": "Audit-Log", "export.field.audit_log": "Audit-Log",
"export.field.avg_latency_ms": "Mittlere Latenz (ms)", "export.field.avg_latency_ms": "Mittlere Latenz (ms)",
"export.field.body": "Text",
"export.field.cause": "Ursache", "export.field.cause": "Ursache",
"export.field.client_id": "Client-ID", "export.field.client_id": "Client-ID",
"export.field.config": "Konfiguration", "export.field.config": "Konfiguration",
@@ -711,6 +737,7 @@
"export.field.email": "E-Mail", "export.field.email": "E-Mail",
"export.field.enabled": "Aktiv", "export.field.enabled": "Aktiv",
"export.field.expires_at": "Läuft ab", "export.field.expires_at": "Läuft ab",
"export.field.from_staff": "Vom Support",
"export.field.generated_at": "Erstellt am", "export.field.generated_at": "Erstellt am",
"export.field.group_id": "Gruppe", "export.field.group_id": "Gruppe",
"export.field.has_password": "Passwort gesetzt", "export.field.has_password": "Passwort gesetzt",
@@ -727,6 +754,7 @@
"export.field.member_since": "Mitglied seit", "export.field.member_since": "Mitglied seit",
"export.field.members": "Mitglieder", "export.field.members": "Mitglieder",
"export.field.message": "Nachricht", "export.field.message": "Nachricht",
"export.field.messages": "Nachrichten",
"export.field.monitor": "Monitor", "export.field.monitor": "Monitor",
"export.field.monitor_groups": "Monitorgruppen", "export.field.monitor_groups": "Monitorgruppen",
"export.field.monitor_id": "Monitor-ID", "export.field.monitor_id": "Monitor-ID",
@@ -762,6 +790,7 @@
"export.field.status": "Status", "export.field.status": "Status",
"export.field.status_pages": "Statusseiten", "export.field.status_pages": "Statusseiten",
"export.field.subject": "Subjekt", "export.field.subject": "Subjekt",
"export.field.support_tickets": "Support-Tickets",
"export.field.target": "Ziel", "export.field.target": "Ziel",
"export.field.target_id": "Ziel", "export.field.target_id": "Ziel",
"export.field.time": "Zeit", "export.field.time": "Zeit",
@@ -875,6 +904,7 @@
"limits.default": "Standard: {{.Value}}", "limits.default": "Standard: {{.Value}}",
"limits.intro": "Gelten für jede Organisation und jeden Account ohne eigenen Wert, auch wenn du sie später änderst. 0 heißt unbegrenzt. Ein gesenktes Limit lässt alles Bestehende stehen; nur neue Monitore, Statusseiten, Regionen oder Organisationen werden abgelehnt.", "limits.intro": "Gelten für jede Organisation und jeden Account ohne eigenen Wert, auch wenn du sie später änderst. 0 heißt unbegrenzt. Ein gesenktes Limit lässt alles Bestehende stehen; nur neue Monitore, Statusseiten, Regionen oder Organisationen werden abgelehnt.",
"limits.monitors": "Monitore", "limits.monitors": "Monitore",
"limits.monitors_per_page": "Monitore pro Statusseite",
"limits.org_title": "Kontingent", "limits.org_title": "Kontingent",
"limits.orgs_per_account": "Organisationen pro Account", "limits.orgs_per_account": "Organisationen pro Account",
"limits.own_false": "zählen nicht", "limits.own_false": "zählen nicht",
@@ -992,6 +1022,9 @@
"monitors.alertmanager_hint": "Ausgefallen, solange ein Alert feuert, der alle Matcher erfüllt. Alerts kommen über einen Empfänger:", "monitors.alertmanager_hint": "Ausgefallen, solange ein Alert feuert, der alle Matcher erfüllt. Alerts kommen über einen Empfänger:",
"monitors.all": "Alle Monitore", "monitors.all": "Alle Monitore",
"monitors.all_results": "Alle Ergebnisse", "monitors.all_results": "Alle Ergebnisse",
"monitors.arrange": "Monitore anordnen",
"monitors.arrange_done": "Anordnen beenden",
"monitors.arrange_hint": "Zieh die Monitore oder verschieb sie mit ↑ und ↓ in die gewünschte Reihenfolge innerhalb ihrer Gruppe. Jede Änderung wird sofort gespeichert und gilt für alle in der Organisation.",
"monitors.assertion_op": "Operator", "monitors.assertion_op": "Operator",
"monitors.assertion_path": "Pfad", "monitors.assertion_path": "Pfad",
"monitors.assertion_value": "Wert", "monitors.assertion_value": "Wert",
@@ -1027,6 +1060,7 @@
"monitors.db_tls_verify": "TLS mit geprüftem Zertifikat", "monitors.db_tls_verify": "TLS mit geprüftem Zertifikat",
"monitors.db_user": "Benutzer", "monitors.db_user": "Benutzer",
"monitors.db_user_redis": "Benutzer (ACL, optional)", "monitors.db_user_redis": "Benutzer (ACL, optional)",
"monitors.dead_region": "Region {{.Region}} hat seit {{.Since}} keinen aktiven Checker.",
"monitors.delete": "Monitor löschen", "monitors.delete": "Monitor löschen",
"monitors.delete_confirm": "Diesen Monitor samt Verlauf löschen?", "monitors.delete_confirm": "Diesen Monitor samt Verlauf löschen?",
"monitors.dns_expect": "Erwartete Antwort (optional)", "monitors.dns_expect": "Erwartete Antwort (optional)",
@@ -1036,6 +1070,13 @@
"monitors.docker_host": "Docker-Host (unix://-Socket oder tcp://host:2375)", "monitors.docker_host": "Docker-Host (unix://-Socket oder tcp://host:2375)",
"monitors.edit": "Monitor bearbeiten", "monitors.edit": "Monitor bearbeiten",
"monitors.expect_status": "Erwarteter Status (z. B. 2xx, 301)", "monitors.expect_status": "Erwarteter Status (z. B. 2xx, 301)",
"monitors.filter_clear": "Alle Status anzeigen",
"monitors.filter_label": "Monitore nach Status anzeigen",
"monitors.filter_only": "Nur",
"monitors.filter_show": {
"one": "Nur den {{.Count}} Monitor mit Status „{{.Status}}“ anzeigen",
"other": "Nur die {{.Count}} Monitore mit Status „{{.Status}}“ anzeigen"
},
"monitors.follow_redirects": "Weiterleitungen folgen", "monitors.follow_redirects": "Weiterleitungen folgen",
"monitors.game_min_free_slots": "Mindestens freie Plätze", "monitors.game_min_free_slots": "Mindestens freie Plätze",
"monitors.game_min_free_slots_hint": "0 prüft nur, ob der Server antwortet.", "monitors.game_min_free_slots_hint": "0 prüft nur, ob der Server antwortet.",
@@ -1062,9 +1103,13 @@
"monitors.minecraft_edition": "Edition", "monitors.minecraft_edition": "Edition",
"monitors.minecraft_hint": "Ziel ist host:port (Java meist 25565, Bedrock 19132). Pingt den Server wie die Serverliste im Spiel.", "monitors.minecraft_hint": "Ziel ist host:port (Java meist 25565, Bedrock 19132). Pingt den Server wie die Serverliste im Spiel.",
"monitors.minecraft_java": "Java Edition", "monitors.minecraft_java": "Java Edition",
"monitors.move_down": "{{.Name}} nach unten",
"monitors.move_up": "{{.Name}} nach oben",
"monitors.new": "Neuer Monitor", "monitors.new": "Neuer Monitor",
"monitors.no_data_since": "keine Daten seit {{.Time}}",
"monitors.no_match": "Kein Monitor gefunden.", "monitors.no_match": "Kein Monitor gefunden.",
"monitors.no_results": "Noch keine Ergebnisse.", "monitors.no_results": "Noch keine Ergebnisse.",
"monitors.no_status_match": "Gerade hat kein Monitor diesen Status.",
"monitors.op_absent": "fehlt", "monitors.op_absent": "fehlt",
"monitors.op_contains": "enthält", "monitors.op_contains": "enthält",
"monitors.op_eq": "gleich", "monitors.op_eq": "gleich",
@@ -1115,6 +1160,12 @@
"monitors.snmp_oid": "OID", "monitors.snmp_oid": "OID",
"monitors.snmp_value": "Wert", "monitors.snmp_value": "Wert",
"monitors.snmp_version": "Version", "monitors.snmp_version": "Version",
"monitors.sort": "Sortierung",
"monitors.sort_custom": "eigene Reihenfolge",
"monitors.sort_latency": "Latenz",
"monitors.sort_name": "Name",
"monitors.sort_status": "Status",
"monitors.sort_uptime": "Uptime",
"monitors.stale_hours": "Verfällt nach (Stunden)", "monitors.stale_hours": "Verfällt nach (Stunden)",
"monitors.stale_hours_hint": "Ein feuernder Alert, den Alertmanager nicht mehr wiederholt, gilt nach dieser Zeit als beendet. Halte sie über repeat_interval.", "monitors.stale_hours_hint": "Ein feuernder Alert, den Alertmanager nicht mehr wiederholt, gilt nach dieser Zeit als beendet. Halte sie über repeat_interval.",
"monitors.steam_hint": "Ziel ist host:port des Query-Ports (meist der Spielport, z. B. 27015). Fragt den Server wie der Steam-Serverbrowser nach seinen Infos (A2S); funktioniert für Source- und die meisten Steam-Spiele.", "monitors.steam_hint": "Ziel ist host:port des Query-Ports (meist der Spielport, z. B. 27015). Fragt den Server wie der Steam-Serverbrowser nach seinen Infos (A2S); funktioniert für Source- und die meisten Steam-Spiele.",
@@ -1138,6 +1189,7 @@
"monitors.type_mqtt": "MQTT", "monitors.type_mqtt": "MQTT",
"monitors.type_mssql": "Microsoft SQL Server", "monitors.type_mssql": "Microsoft SQL Server",
"monitors.type_mysql": "MySQL / MariaDB", "monitors.type_mysql": "MySQL / MariaDB",
"monitors.type_own_only": "nur eigene Checker",
"monitors.type_postgres": "PostgreSQL", "monitors.type_postgres": "PostgreSQL",
"monitors.type_prometheus": "Prometheus", "monitors.type_prometheus": "Prometheus",
"monitors.type_rabbitmq": "RabbitMQ", "monitors.type_rabbitmq": "RabbitMQ",
@@ -1148,6 +1200,11 @@
"monitors.type_steam": "Steam-Spieleserver", "monitors.type_steam": "Steam-Spieleserver",
"monitors.type_tcp": "TCP-Port", "monitors.type_tcp": "TCP-Port",
"monitors.type_tls": "TLS-Zertifikat", "monitors.type_tls": "TLS-Zertifikat",
"monitors.unchecked": "wird nicht geprüft",
"monitors.unchecked_banner": {
"one": "1 Monitor wird gerade nicht geprüft: Keine Region hat für ihn in letzter Zeit gemeldet. Er fällt weder aus noch alarmiert er, bis wieder ein Checker meldet.",
"other": "{{.Count}} Monitore werden gerade nicht geprüft: Keine Region hat für sie in letzter Zeit gemeldet. Sie fallen weder aus noch alarmieren sie, bis wieder ein Checker meldet."
},
"monitors.ungrouped": "Ohne Gruppe", "monitors.ungrouped": "Ohne Gruppe",
"monitors.uptime_chart": "Uptime pro Zeitraum", "monitors.uptime_chart": "Uptime pro Zeitraum",
"monitors.verify_tls": "TLS-Zertifikat prüfen", "monitors.verify_tls": "TLS-Zertifikat prüfen",
@@ -1156,7 +1213,8 @@
"notify.title_opened": "{{.Monitor}} ist ausgefallen", "notify.title_opened": "{{.Monitor}} ist ausgefallen",
"notify.title_resolved": "{{.Monitor}} ist wieder erreichbar", "notify.title_resolved": "{{.Monitor}} ist wieder erreichbar",
"notify.title_test": "Test von UptimeSebi", "notify.title_test": "Test von UptimeSebi",
"org.check_types_intro": "Monitor-Typen, die den Mitgliedern dieser Organisation angeboten werden, aus denen, die diese Installation anbietet. Bestehende Monitore eines abgeschalteten Typs laufen weiter.", "org.check_type_own_only": "nur eigene Checker",
"org.check_types_intro": "Monitor-Typen, die den Mitgliedern dieser Organisation angeboten werden. Typen, die die Checker der Plattform nicht ausführen, laufen nur auf euren eigenen Checkern. Bestehende Monitore eines abgeschalteten Typs laufen weiter.",
"org.policy": "Anmelderichtlinie", "org.policy": "Anmelderichtlinie",
"org.require_sso": "SSO verlangen", "org.require_sso": "SSO verlangen",
"org.require_sso_hint": "Mitglieder müssen sich über den Identity Provider dieser Organisation anmelden. Der Owner kann weiterhin ein Passwort nutzen, damit ein defekter IdP euch nicht aussperrt.", "org.require_sso_hint": "Mitglieder müssen sich über den Identity Provider dieser Organisation anmelden. Der Owner kann weiterhin ein Passwort nutzen, damit ein defekter IdP euch nicht aussperrt.",
@@ -1218,10 +1276,22 @@
"pages.delete_confirm": "Diese Statuspage löschen?", "pages.delete_confirm": "Diese Statuspage löschen?",
"pages.description": "Beschreibung", "pages.description": "Beschreibung",
"pages.domain": "Eigene Domain", "pages.domain": "Eigene Domain",
"pages.domain_cname": "Richte die Domain (CNAME oder A-Record) auf deinen Statuspage-Server; er holt sich automatisch ein Zertifikat, wenn TLS aktiviert ist.", "pages.domain_alt": "Dann ist der CNAME von außen nicht zu sehen. Weise die Domain stattdessen mit diesem TXT-Eintrag nach und lass die Domain oder den Origin deines Proxys auf {{.Target}} zeigen; für eine Domain ohne Subdomain nutze einen ALIAS- oder ANAME-Eintrag oder CNAME-Flattening.",
"pages.domain_instructions": "Lege diesen DNS-Eintrag an und prüfe ihn dann. Nur geprüfte Domains werden ausgeliefert.", "pages.domain_alt_summary": "Hinter einem Proxy wie Cloudflare oder eine Domain ohne Subdomain?",
"pages.domain_apex": "Eine Domain ohne Subdomain (example.com) kann keinen CNAME-Eintrag haben. Nutze stattdessen den ALIAS- oder ANAME-Eintrag deines DNS-Anbieters oder A/AAAA-Einträge.",
"pages.domain_cname_step": "Lege diesen CNAME-Eintrag an. Er lässt die Domain auf die Statusseiten-Server zeigen und weist zugleich nach, dass sie dir gehört, denn sein Ziel gehört nur zu dieser Seite. Wir sehen alle paar Minuten nach und prüfen die Domain von selbst; DNS-Änderungen brauchen manchmal etwas, bis sie sichtbar sind.",
"pages.domain_intro": "Liefere diese Seite unter einer eigenen Domain aus, z. B. status.example.com. Meist reicht ein einziger DNS-Eintrag; HTTPS kommt von selbst.",
"pages.domain_keep": "Lass den Eintrag bestehen: Er wird täglich geprüft, und eine Domain, deren Eintrag eine Woche lang fehlt, wird abgeschaltet, damit niemand anderes sie übernehmen kann.",
"pages.domain_missing": "Der Eintrag dieser Domain ist seit {{.Since}} nicht mehr zu finden. Kommt er nicht zurück, wird die Domain am {{.Date}} abgeschaltet.",
"pages.domain_name": "Domain", "pages.domain_name": "Domain",
"pages.domain_step_cname_own": "Lass die Domain dann auf die eigenen Statusseiten-Server deiner Organisation zeigen: per CNAME-Eintrag auf deren Hostnamen oder per A/AAAA-Eintrag auf deren Adressen.",
"pages.domain_step_cname_unknown": "Lass die Domain dann per CNAME-Eintrag auf die Statusseiten-Server der Plattform zeigen; das Ziel nennt dir der Betreiber dieser Installation.",
"pages.domain_step_tls": "HTTPS: Das Zertifikat wird beim ersten Aufruf über HTTPS automatisch geholt, das kann bis zu einer Minute dauern. Zum Schutz der Limits der Zertifizierungsstelle, die sich alle Organisationen teilen, sind neue Zertifikate pro Tag begrenzt, und die Domain lässt sich höchstens {{.Count}}-mal am Tag ändern.",
"pages.domain_step_verified": "1. Domain geprüft.",
"pages.domain_step_verify": "Weise mit diesem TXT-Eintrag nach, dass die Domain dir gehört, und prüfe ihn dann. Bis dahin wird die Domain weder ausgeliefert noch bekommt sie ein Zertifikat.",
"pages.domain_verified": "Domain geprüft.", "pages.domain_verified": "Domain geprüft.",
"pages.domain_verified_by_cname": "Domain über ihren CNAME-Eintrag geprüft.",
"pages.domain_verified_by_txt": "Domain über ihren TXT-Eintrag geprüft.",
"pages.draft": "Entwurf", "pages.draft": "Entwurf",
"pages.export": "Als HTML exportieren", "pages.export": "Als HTML exportieren",
"pages.group": "Gruppe", "pages.group": "Gruppe",
@@ -1234,8 +1304,14 @@
"pages.intro": "Öffentliche Seiten mit dem Zustand ausgewählter Monitore. Jede Seite kann eine eigene Domain nutzen oder als einzelne HTML-Datei exportiert werden.", "pages.intro": "Öffentliche Seiten mit dem Zustand ausgewählter Monitore. Jede Seite kann eine eigene Domain nutzen oder als einzelne HTML-Datei exportiert werden.",
"pages.label": "Öffentlicher Name", "pages.label": "Öffentlicher Name",
"pages.logo": "Logo-URL (https)", "pages.logo": "Logo-URL (https)",
"pages.monitor_limit": "Diese Seite darf höchstens {{.Max}} Monitore zeigen.",
"pages.monitors_filter": "Monitore filtern",
"pages.monitors_all": "Alle hinzufügen",
"pages.monitors_none": "Alle entfernen",
"pages.no_group": "Ohne Gruppe", "pages.no_group": "Ohne Gruppe",
"pages.open": "Öffnen", "pages.open": "Öffnen",
"pages.own_servers": "Die Statusseiten dieser Organisation liefern nur ihre eigenen Statusseiten-Server aus, nicht die der Plattform. Ruf sie über die Adresse deiner Server auf oder verbinde eine eigene Domain, die auf sie zeigt.",
"pages.own_servers_short": "eigene Server",
"pages.page_title": "Titel", "pages.page_title": "Titel",
"pages.published": "Veröffentlicht", "pages.published": "Veröffentlicht",
"pages.section": "Abschnitt", "pages.section": "Abschnitt",
@@ -1249,6 +1325,7 @@
"pages.title": "Statuspages", "pages.title": "Statuspages",
"pages.value": "Wert", "pages.value": "Wert",
"pages.verify": "Prüfen", "pages.verify": "Prüfen",
"pages.verify_now": "Jetzt prüfen",
"perm.audit.read": "Audit-Log einsehen", "perm.audit.read": "Audit-Log einsehen",
"perm.incidents.read": "Incidents sehen", "perm.incidents.read": "Incidents sehen",
"perm.incidents.write": "Incidents verwalten", "perm.incidents.write": "Incidents verwalten",
@@ -1379,6 +1456,76 @@
"storage.retention": "Löschen nach", "storage.retention": "Löschen nach",
"storage.size": "Größe", "storage.size": "Größe",
"storage.title": "Datenspeicher", "storage.title": "Datenspeicher",
"support.account": "Konto",
"support.account.active": "aktiv",
"support.account.created": "Erstellt",
"support.account.email": "E-Mail",
"support.account.email_verified": "E-Mail bestätigt",
"support.account.locale": "Sprache",
"support.account.monitors": "Monitore",
"support.account.name": "Name",
"support.account.open_tickets": "Offene Tickets",
"support.account.org_suspended": "Organisation gesperrt",
"support.account.orgs": "Organisationen",
"support.account.orgs_owned": "Eigene Organisationen",
"support.account.owner": "Owner",
"support.account.password": "Passwort",
"support.account.regions": "Regionen pro Monitor",
"support.account.role": "Rolle",
"support.account.sign_in": "Anmeldung",
"support.account.sso_only": "nur SSO",
"support.account.state": "Zustand",
"support.account.status_pages": "Statusseiten",
"support.account.suspended": "gesperrt",
"support.account.this_ticket": "im Ticket genannt",
"support.admin_intro": "Tickets aller Konten. Eine Antwort wird dem Konto per E-Mail angekündigt; schreibt es zurück, ist das Ticket wieder offen.",
"support.admin_title": "Support-Tickets",
"support.all": "Alle Tickets",
"support.attach": "Details anhängen (optional)",
"support.attach_hint": "Zeig dem Support, worum es geht – aus der aktiven Organisation.",
"support.attach_none": "keine Auswahl",
"support.attach_org": "Organisation {{.Org}}",
"support.close": "Ticket schließen",
"support.closed_hint": "Dieses Ticket ist geschlossen. Mit einer Antwort öffnest du es wieder.",
"support.contact": "Support kontaktieren",
"support.disabled": "Support-Tickets sind gerade abgeschaltet.",
"support.filter": "Tickets filtern",
"support.filter.all": "Alle",
"support.filter.answered": "Beantwortet",
"support.filter.closed": "Geschlossen",
"support.filter.open": "Offen",
"support.from_staff": "Support",
"support.from_you": "Du",
"support.intro": "Fragen, Probleme oder Feedback? Schreib dem Support der Plattform. Sobald er antwortet, bekommst du eine E-Mail.",
"support.message": "Nachricht",
"support.mine": "Deine Tickets",
"support.new": "Neues Ticket",
"support.no": "nein",
"support.none": "Du hast noch keine Tickets eröffnet.",
"support.none_admin": "Hier gibt es keine Tickets.",
"support.ref.alert_group": "Alertgruppe",
"support.ref.channel": "Alert-Typ (Benachrichtigungskanal)",
"support.ref.incident": "Incident",
"support.ref.monitor": "Monitor",
"support.ref.org": "Organisation",
"support.ref.status_page": "Statusseite",
"support.reopen": "Ticket wieder öffnen",
"support.reply": "Antworten",
"support.send": "Senden",
"support.settings": "Einstellungen",
"support.settings.enabled": "Konten können Support-Tickets eröffnen",
"support.settings.enabled_hint": "Abgeschaltet verschwinden die Support-Seiten für Konten; die bestehenden Tickets bleiben hier erhalten.",
"support.settings.max_open": "Offene Tickets pro Konto",
"support.settings.max_open_hint": "Offene und beantwortete Tickets zählen; 0 heißt unbegrenzt. Gesperrte Konten können ein Ticket eröffnen.",
"support.settings.off": "aus",
"support.settings.on": "an",
"support.settings.save": "Speichern",
"support.status.answered": "beantwortet",
"support.status.closed": "geschlossen",
"support.status.open": "offen",
"support.subject": "Betreff",
"support.title": "Support",
"support.yes": "ja",
"suspended.intro": "Die Administratoren der Plattform haben dein Konto gesperrt.", "suspended.intro": "Die Administratoren der Plattform haben dein Konto gesperrt.",
"suspended.options": "Du kannst deine Daten weiterhin herunterladen oder dein Konto löschen.", "suspended.options": "Du kannst deine Daten weiterhin herunterladen oder dein Konto löschen.",
"suspended.title": "Konto gesperrt", "suspended.title": "Konto gesperrt",
+152 -5
View File
@@ -1,6 +1,6 @@
{ {
"admin.check_types": "Check types", "admin.check_types": "Check types",
"admin.check_types_intro": "Switch off types this installation cannot offer, such as Docker on shared cloud checkers or ICMP without the needed privileges. They disappear for new monitors; existing monitors keep running.", "admin.check_types_intro": "Switch off types the platform's checkers cannot offer, such as Docker on shared cloud checkers or ICMP without the needed privileges. Organizations keep them for their own checkers; existing monitors keep running.",
"admin.checker_network": "Checker network", "admin.checker_network": "Checker network",
"admin.intro": "Regions, checkers and status page servers created here are shared by every organization. Organizations add their own under Regions & checkers.", "admin.intro": "Regions, checkers and status page servers created here are shared by every organization. Organizations add their own under Regions & checkers.",
"admin.platform_private": "Platform checkers may check private addresses", "admin.platform_private": "Platform checkers may check private addresses",
@@ -107,6 +107,7 @@
"audit.action.member.role_unassign": "Role removed", "audit.action.member.role_unassign": "Role removed",
"audit.action.monitor.create": "Monitor created", "audit.action.monitor.create": "Monitor created",
"audit.action.monitor.delete": "Monitor deleted", "audit.action.monitor.delete": "Monitor deleted",
"audit.action.monitor.order": "Monitors put in order",
"audit.action.monitor.update": "Monitor changed", "audit.action.monitor.update": "Monitor changed",
"audit.action.org.check_types_update": "Check types changed", "audit.action.org.check_types_update": "Check types changed",
"audit.action.org.create": "Organization created", "audit.action.org.create": "Organization created",
@@ -151,6 +152,11 @@
"audit.action.statuspage.groups_import": "Status page groups imported from monitor groups", "audit.action.statuspage.groups_import": "Status page groups imported from monitor groups",
"audit.action.statuspage.monitors_update": "Status page monitors changed", "audit.action.statuspage.monitors_update": "Status page monitors changed",
"audit.action.statuspage.update": "Status page changed", "audit.action.statuspage.update": "Status page changed",
"audit.action.support.answer": "Support ticket answered",
"audit.action.support.create": "Support ticket opened",
"audit.action.support.reply": "Support ticket replied to",
"audit.action.support.settings": "Support settings changed",
"audit.action.support.status": "Support ticket status changed",
"audit.action.token.create": "API token created", "audit.action.token.create": "API token created",
"audit.action.token.delete": "API token revoked", "audit.action.token.delete": "API token revoked",
"audit.deleted_user": "Deleted user", "audit.deleted_user": "Deleted user",
@@ -497,6 +503,7 @@
"console.nav.admin": "Admin", "console.nav.admin": "Admin",
"console.nav.logout": "Sign out", "console.nav.logout": "Sign out",
"console.nav.members": "Members", "console.nav.members": "Members",
"console.nav.menu": "Menu",
"console.nav.org": "Organization", "console.nav.org": "Organization",
"console.nav.regions": "Regions & checkers", "console.nav.regions": "Regions & checkers",
"console.nav.roles": "Roles", "console.nav.roles": "Roles",
@@ -508,10 +515,22 @@
"console.sso_required_action": "Sign in with SSO", "console.sso_required_action": "Sign in with SSO",
"console.suspended_reason": "Reason: {{.Reason}}", "console.suspended_reason": "Reason: {{.Reason}}",
"console.totp_missing_action": "Set up now", "console.totp_missing_action": "Set up now",
"email.domain_missing.body": "The status page {{.Page}} is served at {{.Domain}}, but the DNS record proving that the domain belongs to it can no longer be found.\n\nUnless it is back by {{.Date}}, the domain is switched off and the page is no longer served there. The record to restore is shown here:\n{{.Link}}",
"email.domain_missing.subject": "The DNS record of {{.Domain}} is gone",
"email.domain_off.body": "The DNS record of {{.Domain}} has been missing for a week, so the status page {{.Page}} is no longer served there.\n\nRestore the record and verify the domain again:\n{{.Link}}",
"email.domain_off.subject": "{{.Domain}} has been switched off",
"email.opened.body": "{{.Monitor}} ({{.Target}}) is down in all of its regions since {{.Since}}.\n\nLast errors:\n{{.Cause}}\n\nYou receive this because a notification channel of your organization is set up for this address.", "email.opened.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.subject": "Region {{.Region}} is checking again",
"email.region_down.body": "Region {{.Region}} has had no active checker for {{.Minutes}} minutes, since {{.Since}}.\n\nMonitors checked only from there are not being checked right now: they neither go down nor alert. Monitors with other regions as well are judged by those alone until this one reports again.\n\nStart a checker of the region or look at its logs:\n{{.Link}}",
"email.region_down.subject": "Region {{.Region}} has no active checker",
"email.resolved.body": "{{.Monitor}} ({{.Target}}) is reachable again after {{.Duration}}.", "email.resolved.body": "{{.Monitor}} ({{.Target}}) is reachable again after {{.Duration}}.",
"email.resolved.subject": "[UP] {{.Monitor}}", "email.resolved.subject": "[UP] {{.Monitor}}",
"email.support_admin.body": "Hello,\n\na support ticket waits for an answer:\n\n{{.Subject}}\n\n{{.Link}}",
"email.support_admin.subject": "Support ticket: {{.Subject}}",
"email.support_reply.body": "Hello,\n\nthe support team answered your ticket \"{{.Subject}}\":\n\n{{.Link}}\n\nReply there if you have further questions.",
"email.support_reply.subject": "Answer to your support ticket: {{.Subject}}",
"email.test.body": "This is a test. If you can read it, the channel works.", "email.test.body": "This is a test. If you can read it, the channel works.",
"email.test.subject": "Test notification from UptimeSebi", "email.test.subject": "Test notification from UptimeSebi",
"email.verify.body": "Hello,\n\nplease confirm your email address to finish signing up:\n\n{{.Link}}\n\nThe link is valid for {{.Hours}} hours. If you did not sign up, ignore this email; the account is deleted after a week.", "email.verify.body": "Hello,\n\nplease confirm your email address to finish signing up:\n\n{{.Link}}\n\nThe link is valid for {{.Hours}} hours. If you did not sign up, ignore this email; the account is deleted after a week.",
@@ -525,10 +544,12 @@
"error.channel_test_failed": "The test notification could not be delivered.", "error.channel_test_failed": "The test notification could not be delivered.",
"error.channel_type_immutable": "The type of a channel cannot be changed.", "error.channel_type_immutable": "The type of a channel cannot be changed.",
"error.check_type_disabled": "This check type is switched off for this organization or installation.", "error.check_type_disabled": "This check type is switched off for this organization or installation.",
"error.check_type_own_checkers_only": "The platform's checkers do not run this check type. Choose only your organization's own regions.",
"error.confirmation_failed": "The confirmation does not match.", "error.confirmation_failed": "The confirmation does not match.",
"error.consent_outdated": "The documents changed in the meantime. Reload the page and accept the current version.", "error.consent_outdated": "The documents changed in the meantime. Reload the page and accept the current version.",
"error.consent_required": "Please accept the privacy policy and terms first.", "error.consent_required": "Please accept the privacy policy and terms first.",
"error.domain_not_verified": "The TXT record was not found yet. DNS changes can take a while to appear.", "error.domain_changes_exceeded": "The custom domain was changed {{.Count}} times today already. Try again tomorrow.",
"error.domain_not_verified": "Neither the CNAME nor the TXT record was found yet. DNS changes can take a while to appear.",
"error.domain_taken": "This domain is already used by another status page.", "error.domain_taken": "This domain is already used by another status page.",
"error.email_not_configured": "Email is not available on this server.", "error.email_not_configured": "Email is not available on this server.",
"error.email_taken": "This email address is already registered.", "error.email_taken": "This email address is already registered.",
@@ -599,6 +620,7 @@
"error.owner_cannot_be_removed": "Owners cannot be removed. Take their ownership away first.", "error.owner_cannot_be_removed": "Owners cannot be removed. Take their ownership away first.",
"error.owner_has_all_permissions": "The owner already has every permission.", "error.owner_has_all_permissions": "The owner already has every permission.",
"error.owner_only": "Only owners can change who owns the organization.", "error.owner_only": "Only owners can change who owns the organization.",
"error.page_monitor_limit": "A status page may show at most {{.Max}} monitors.",
"error.password_too_short": "The password needs at least {{.Min}} characters.", "error.password_too_short": "The password needs at least {{.Min}} characters.",
"error.permission_escalation": "You cannot grant permissions you do not hold yourself.", "error.permission_escalation": "You cannot grant permissions you do not hold yourself.",
"error.platform_region_limit": "A monitor may be checked from at most {{.Max}} platform regions; your own checker regions do not count.", "error.platform_region_limit": "A monitor may be checked from at most {{.Max}} platform regions; your own checker regions do not count.",
@@ -632,11 +654,14 @@
"error.status_in_use": "Updates use this status; it stays so their history keeps its meaning. Rename or recolor it instead.", "error.status_in_use": "Updates use this status; it stays so their history keeps its meaning. Rename or recolor it instead.",
"error.status_name_taken": "A status with this name exists already.", "error.status_name_taken": "A status with this name exists already.",
"error.status_page_limit": "Your organization has reached its limit of {{.Max}} status pages.", "error.status_page_limit": "Your organization has reached its limit of {{.Max}} status pages.",
"error.support_disabled": "Support tickets are switched off on this platform.",
"error.suspended_ticket_limit": "While your account is suspended you can open one ticket. Reply to it instead.",
"error.target_is_admin": "Platform admins cannot be suspended or deleted here.", "error.target_is_admin": "Platform admins cannot be suspended or deleted here.",
"error.token_lifetime_exceeds_policy": { "error.token_lifetime_exceeds_policy": {
"one": "Tokens in this organization must expire within {{.Count}} day.", "one": "Tokens in this organization must expire within {{.Count}} day.",
"other": "Tokens in this organization must expire within {{.Count}} days." "other": "Tokens in this organization must expire within {{.Count}} days."
}, },
"error.too_many_tickets": "You can have {{.Count}} open tickets at the same time. Close one or reply to it instead.",
"error.totp_already_enabled": "TOTP is already active.", "error.totp_already_enabled": "TOTP is already active.",
"error.totp_required_by_org": "One of your organizations requires TOTP.", "error.totp_required_by_org": "One of your organizations requires TOTP.",
"error.totp_setup_expired": "Setup expired, please start again.", "error.totp_setup_expired": "Setup expired, please start again.",
@@ -695,6 +720,7 @@
"export.field.api_tokens": "API tokens", "export.field.api_tokens": "API tokens",
"export.field.audit_log": "Audit log", "export.field.audit_log": "Audit log",
"export.field.avg_latency_ms": "Average latency (ms)", "export.field.avg_latency_ms": "Average latency (ms)",
"export.field.body": "Text",
"export.field.cause": "Cause", "export.field.cause": "Cause",
"export.field.client_id": "Client ID", "export.field.client_id": "Client ID",
"export.field.config": "Configuration", "export.field.config": "Configuration",
@@ -711,6 +737,7 @@
"export.field.email": "Email", "export.field.email": "Email",
"export.field.enabled": "Enabled", "export.field.enabled": "Enabled",
"export.field.expires_at": "Expires", "export.field.expires_at": "Expires",
"export.field.from_staff": "From support",
"export.field.generated_at": "Generated", "export.field.generated_at": "Generated",
"export.field.group_id": "Group", "export.field.group_id": "Group",
"export.field.has_password": "Password set", "export.field.has_password": "Password set",
@@ -727,6 +754,7 @@
"export.field.member_since": "Member since", "export.field.member_since": "Member since",
"export.field.members": "Members", "export.field.members": "Members",
"export.field.message": "Message", "export.field.message": "Message",
"export.field.messages": "Messages",
"export.field.monitor": "Monitor", "export.field.monitor": "Monitor",
"export.field.monitor_groups": "Monitor groups", "export.field.monitor_groups": "Monitor groups",
"export.field.monitor_id": "Monitor ID", "export.field.monitor_id": "Monitor ID",
@@ -762,6 +790,7 @@
"export.field.status": "Status", "export.field.status": "Status",
"export.field.status_pages": "Status pages", "export.field.status_pages": "Status pages",
"export.field.subject": "Subject", "export.field.subject": "Subject",
"export.field.support_tickets": "Support tickets",
"export.field.target": "Target", "export.field.target": "Target",
"export.field.target_id": "Target", "export.field.target_id": "Target",
"export.field.time": "Time", "export.field.time": "Time",
@@ -875,6 +904,7 @@
"limits.default": "default: {{.Value}}", "limits.default": "default: {{.Value}}",
"limits.intro": "Apply to every organization and account without an override of its own, also when you change them later. 0 means unlimited. Lowering a limit keeps everything that exists; only new monitors, status pages, regions or organizations are refused.", "limits.intro": "Apply to every organization and account without an override of its own, also when you change them later. 0 means unlimited. Lowering a limit keeps everything that exists; only new monitors, status pages, regions or organizations are refused.",
"limits.monitors": "Monitors", "limits.monitors": "Monitors",
"limits.monitors_per_page": "Monitors per status page",
"limits.org_title": "Usage", "limits.org_title": "Usage",
"limits.orgs_per_account": "Organizations per account", "limits.orgs_per_account": "Organizations per account",
"limits.own_false": "do not count", "limits.own_false": "do not count",
@@ -992,6 +1022,9 @@
"monitors.alertmanager_hint": "Down while an alert matching all matchers fires. Alerts arrive through a receiver:", "monitors.alertmanager_hint": "Down while an alert matching all matchers fires. Alerts arrive through a receiver:",
"monitors.all": "All monitors", "monitors.all": "All monitors",
"monitors.all_results": "All results", "monitors.all_results": "All results",
"monitors.arrange": "Arrange monitors",
"monitors.arrange_done": "Done arranging",
"monitors.arrange_hint": "Drag the monitors, or move them with ↑ and ↓, into the order you want within each group. Every change is saved at once and is the same for everybody in the organization.",
"monitors.assertion_op": "Operator", "monitors.assertion_op": "Operator",
"monitors.assertion_path": "Path", "monitors.assertion_path": "Path",
"monitors.assertion_value": "Value", "monitors.assertion_value": "Value",
@@ -1027,6 +1060,7 @@
"monitors.db_tls_verify": "TLS with verified certificate", "monitors.db_tls_verify": "TLS with verified certificate",
"monitors.db_user": "User", "monitors.db_user": "User",
"monitors.db_user_redis": "User (ACL, optional)", "monitors.db_user_redis": "User (ACL, optional)",
"monitors.dead_region": "Region {{.Region}} has had no active checker since {{.Since}}.",
"monitors.delete": "Delete monitor", "monitors.delete": "Delete monitor",
"monitors.delete_confirm": "Delete this monitor and its history?", "monitors.delete_confirm": "Delete this monitor and its history?",
"monitors.dns_expect": "Expected answer (optional)", "monitors.dns_expect": "Expected answer (optional)",
@@ -1036,6 +1070,13 @@
"monitors.docker_host": "Docker host (unix:// socket or tcp://host:2375)", "monitors.docker_host": "Docker host (unix:// socket or tcp://host:2375)",
"monitors.edit": "Edit monitor", "monitors.edit": "Edit monitor",
"monitors.expect_status": "Expected status (e.g. 2xx, 301)", "monitors.expect_status": "Expected status (e.g. 2xx, 301)",
"monitors.filter_clear": "Show all statuses",
"monitors.filter_label": "Show monitors by status",
"monitors.filter_only": "Only",
"monitors.filter_show": {
"one": "Show only the {{.Count}} monitor that is {{.Status}}",
"other": "Show only the {{.Count}} monitors that are {{.Status}}"
},
"monitors.follow_redirects": "Follow redirects", "monitors.follow_redirects": "Follow redirects",
"monitors.game_min_free_slots": "Minimum free slots", "monitors.game_min_free_slots": "Minimum free slots",
"monitors.game_min_free_slots_hint": "0 only checks that the server answers.", "monitors.game_min_free_slots_hint": "0 only checks that the server answers.",
@@ -1062,9 +1103,13 @@
"monitors.minecraft_edition": "Edition", "monitors.minecraft_edition": "Edition",
"monitors.minecraft_hint": "Target is host:port (Java usually 25565, Bedrock 19132). Pings the server like the in-game server list.", "monitors.minecraft_hint": "Target is host:port (Java usually 25565, Bedrock 19132). Pings the server like the in-game server list.",
"monitors.minecraft_java": "Java Edition", "monitors.minecraft_java": "Java Edition",
"monitors.move_down": "Move {{.Name}} down",
"monitors.move_up": "Move {{.Name}} up",
"monitors.new": "New monitor", "monitors.new": "New monitor",
"monitors.no_data_since": "no data since {{.Time}}",
"monitors.no_match": "No monitor matches.", "monitors.no_match": "No monitor matches.",
"monitors.no_results": "No results yet.", "monitors.no_results": "No results yet.",
"monitors.no_status_match": "No monitor has this status right now.",
"monitors.op_absent": "is absent", "monitors.op_absent": "is absent",
"monitors.op_contains": "contains", "monitors.op_contains": "contains",
"monitors.op_eq": "equals", "monitors.op_eq": "equals",
@@ -1115,6 +1160,12 @@
"monitors.snmp_oid": "OID", "monitors.snmp_oid": "OID",
"monitors.snmp_value": "Value", "monitors.snmp_value": "Value",
"monitors.snmp_version": "Version", "monitors.snmp_version": "Version",
"monitors.sort": "Sort order",
"monitors.sort_custom": "own order",
"monitors.sort_latency": "latency",
"monitors.sort_name": "name",
"monitors.sort_status": "status",
"monitors.sort_uptime": "uptime",
"monitors.stale_hours": "Stale after (hours)", "monitors.stale_hours": "Stale after (hours)",
"monitors.stale_hours_hint": "A firing alert Alertmanager stops repeating counts as over after this time. Keep it above repeat_interval.", "monitors.stale_hours_hint": "A firing alert Alertmanager stops repeating counts as over after this time. Keep it above repeat_interval.",
"monitors.steam_hint": "Target is host:port of the query port (usually the game port, e.g. 27015). Asks the server for its info like the Steam server browser (A2S); works for Source and most Steam games.", "monitors.steam_hint": "Target is host:port of the query port (usually the game port, e.g. 27015). Asks the server for its info like the Steam server browser (A2S); works for Source and most Steam games.",
@@ -1138,6 +1189,7 @@
"monitors.type_mqtt": "MQTT", "monitors.type_mqtt": "MQTT",
"monitors.type_mssql": "Microsoft SQL Server", "monitors.type_mssql": "Microsoft SQL Server",
"monitors.type_mysql": "MySQL / MariaDB", "monitors.type_mysql": "MySQL / MariaDB",
"monitors.type_own_only": "own checkers only",
"monitors.type_postgres": "PostgreSQL", "monitors.type_postgres": "PostgreSQL",
"monitors.type_prometheus": "Prometheus", "monitors.type_prometheus": "Prometheus",
"monitors.type_rabbitmq": "RabbitMQ", "monitors.type_rabbitmq": "RabbitMQ",
@@ -1148,6 +1200,11 @@
"monitors.type_steam": "Steam game server", "monitors.type_steam": "Steam game server",
"monitors.type_tcp": "TCP port", "monitors.type_tcp": "TCP port",
"monitors.type_tls": "TLS certificate", "monitors.type_tls": "TLS certificate",
"monitors.unchecked": "not being checked",
"monitors.unchecked_banner": {
"one": "1 monitor is not being checked: no region has reported for it recently. It neither goes down nor alerts until a checker reports again.",
"other": "{{.Count}} monitors are not being checked: no region has reported for them recently. They neither go down nor alert until a checker reports again."
},
"monitors.ungrouped": "Without group", "monitors.ungrouped": "Without group",
"monitors.uptime_chart": "Uptime per period", "monitors.uptime_chart": "Uptime per period",
"monitors.verify_tls": "Verify TLS certificate", "monitors.verify_tls": "Verify TLS certificate",
@@ -1156,7 +1213,8 @@
"notify.title_opened": "{{.Monitor}} is down", "notify.title_opened": "{{.Monitor}} is down",
"notify.title_resolved": "{{.Monitor}} is up again", "notify.title_resolved": "{{.Monitor}} is up again",
"notify.title_test": "Test from UptimeSebi", "notify.title_test": "Test from UptimeSebi",
"org.check_types_intro": "Monitor types offered to the members of this organization, out of those this installation offers. Existing monitors of a switched-off type keep running.", "org.check_type_own_only": "own checkers only",
"org.check_types_intro": "Monitor types offered to the members of this organization. Types the platform's checkers do not run work on your own checkers only. Existing monitors of a switched-off type keep running.",
"org.policy": "Sign-in policy", "org.policy": "Sign-in policy",
"org.require_sso": "Require SSO", "org.require_sso": "Require SSO",
"org.require_sso_hint": "Members must sign in through this organization's identity provider. The owner can still use a password so a broken IdP cannot lock you out.", "org.require_sso_hint": "Members must sign in through this organization's identity provider. The owner can still use a password so a broken IdP cannot lock you out.",
@@ -1218,10 +1276,22 @@
"pages.delete_confirm": "Delete this status page?", "pages.delete_confirm": "Delete this status page?",
"pages.description": "Description", "pages.description": "Description",
"pages.domain": "Custom domain", "pages.domain": "Custom domain",
"pages.domain_cname": "Point the domain (CNAME or A record) at your status page server; it obtains a certificate automatically when TLS is enabled.", "pages.domain_alt": "Then the CNAME cannot be seen from outside. Prove the domain with this TXT record instead, and point the domain, or your proxy's origin, at {{.Target}}; for a domain without a subdomain use an ALIAS or ANAME record or CNAME flattening.",
"pages.domain_instructions": "Create this DNS record, then verify. Only verified domains are served.", "pages.domain_alt_summary": "Behind a proxy such as Cloudflare, or a domain without a subdomain?",
"pages.domain_apex": "A domain without a subdomain (example.com) cannot have a CNAME record. Use your DNS provider's ALIAS or ANAME record, or A/AAAA records, instead.",
"pages.domain_cname_step": "Create this CNAME record. It points the domain at the status page servers and proves that the domain is yours, because its target belongs to this page alone. We look for it every few minutes and verify the domain on our own; DNS changes can take a while to appear.",
"pages.domain_intro": "Serve this page under a domain of your own, e.g. status.example.com. One DNS record is usually all it takes; HTTPS follows by itself.",
"pages.domain_keep": "Keep the record in place: it is checked daily, and a domain whose record has been gone for a week is switched off, so nobody else can take it over.",
"pages.domain_missing": "The record of this domain has not been found since {{.Since}}. Unless it is back, the domain is switched off on {{.Date}}.",
"pages.domain_name": "Domain", "pages.domain_name": "Domain",
"pages.domain_step_cname_own": "Then point the domain at your organization's own status page servers: a CNAME record to their host name, or A/AAAA records to their addresses.",
"pages.domain_step_cname_unknown": "Then point the domain at the platform's status page servers with a CNAME record; the operator of this installation tells you its target.",
"pages.domain_step_tls": "HTTPS: the certificate is obtained automatically on the first visit over HTTPS, which can take up to a minute. To protect the certificate authority's limits that all organizations share, new certificates are limited per day, and the domain can be changed at most {{.Count}} times a day.",
"pages.domain_step_verified": "1. Domain verified.",
"pages.domain_step_verify": "Prove the domain is yours with this TXT record, then verify. Until then the domain is neither served nor given a certificate.",
"pages.domain_verified": "Domain verified.", "pages.domain_verified": "Domain verified.",
"pages.domain_verified_by_cname": "Domain verified by its CNAME record.",
"pages.domain_verified_by_txt": "Domain verified by its TXT record.",
"pages.draft": "draft", "pages.draft": "draft",
"pages.export": "Export as HTML", "pages.export": "Export as HTML",
"pages.group": "Group", "pages.group": "Group",
@@ -1234,8 +1304,14 @@
"pages.intro": "Public pages showing the state of selected monitors. Each page can use its own domain or be exported as a single HTML file.", "pages.intro": "Public pages showing the state of selected monitors. Each page can use its own domain or be exported as a single HTML file.",
"pages.label": "Public name", "pages.label": "Public name",
"pages.logo": "Logo URL (https)", "pages.logo": "Logo URL (https)",
"pages.monitor_limit": "This page may show at most {{.Max}} monitors.",
"pages.monitors_filter": "Filter monitors",
"pages.monitors_all": "Add all",
"pages.monitors_none": "Remove all",
"pages.no_group": "No group", "pages.no_group": "No group",
"pages.open": "Open", "pages.open": "Open",
"pages.own_servers": "Your organization's own status page servers serve its pages; the platform's do not. Open them at the address of your servers or connect a custom domain pointing at them.",
"pages.own_servers_short": "own servers",
"pages.page_title": "Title", "pages.page_title": "Title",
"pages.published": "Published", "pages.published": "Published",
"pages.section": "Section", "pages.section": "Section",
@@ -1249,6 +1325,7 @@
"pages.title": "Status pages", "pages.title": "Status pages",
"pages.value": "Value", "pages.value": "Value",
"pages.verify": "Verify", "pages.verify": "Verify",
"pages.verify_now": "Check now",
"perm.audit.read": "View the audit log", "perm.audit.read": "View the audit log",
"perm.incidents.read": "View incidents", "perm.incidents.read": "View incidents",
"perm.incidents.write": "Manage incidents", "perm.incidents.write": "Manage incidents",
@@ -1379,6 +1456,76 @@
"storage.retention": "Delete after", "storage.retention": "Delete after",
"storage.size": "Size", "storage.size": "Size",
"storage.title": "Data storage", "storage.title": "Data storage",
"support.account": "Account",
"support.account.active": "active",
"support.account.created": "Created",
"support.account.email": "Email",
"support.account.email_verified": "Email verified",
"support.account.locale": "Language",
"support.account.monitors": "Monitors",
"support.account.name": "Name",
"support.account.open_tickets": "Open tickets",
"support.account.org_suspended": "Organization suspended",
"support.account.orgs": "Organizations",
"support.account.orgs_owned": "Organizations owned",
"support.account.owner": "Owner",
"support.account.password": "Password",
"support.account.regions": "Regions per monitor",
"support.account.role": "Role",
"support.account.sign_in": "Sign-in",
"support.account.sso_only": "SSO only",
"support.account.state": "State",
"support.account.status_pages": "Status pages",
"support.account.suspended": "suspended",
"support.account.this_ticket": "named in the ticket",
"support.admin_intro": "Tickets of every account. Answering mails the account; its reply puts the ticket back among the open ones.",
"support.admin_title": "Support tickets",
"support.all": "All tickets",
"support.attach": "Attach details (optional)",
"support.attach_hint": "Point the support team at what your question is about, from the active organization.",
"support.attach_none": "none",
"support.attach_org": "Organization {{.Org}}",
"support.close": "Close ticket",
"support.closed_hint": "This ticket is closed. Replying opens it again.",
"support.contact": "Contact support",
"support.disabled": "Support tickets are switched off at the moment.",
"support.filter": "Filter tickets",
"support.filter.all": "All",
"support.filter.answered": "Answered",
"support.filter.closed": "Closed",
"support.filter.open": "Open",
"support.from_staff": "Support",
"support.from_you": "You",
"support.intro": "Questions, problems or feedback? Write to the platform's support team. You get an email as soon as they answer.",
"support.message": "Message",
"support.mine": "Your tickets",
"support.new": "New ticket",
"support.no": "no",
"support.none": "You have not opened any tickets yet.",
"support.none_admin": "No tickets here.",
"support.ref.alert_group": "Alert group",
"support.ref.channel": "Alert type (notification channel)",
"support.ref.incident": "Incident",
"support.ref.monitor": "Monitor",
"support.ref.org": "Organization",
"support.ref.status_page": "Status page",
"support.reopen": "Reopen ticket",
"support.reply": "Reply",
"support.send": "Send",
"support.settings": "Settings",
"support.settings.enabled": "Accounts can open support tickets",
"support.settings.enabled_hint": "Switched off, the support pages disappear for accounts; you keep the existing tickets here.",
"support.settings.max_open": "Open tickets per account",
"support.settings.max_open_hint": "Open and answered tickets count; 0 means unlimited. Suspended accounts can open one ticket.",
"support.settings.off": "off",
"support.settings.on": "on",
"support.settings.save": "Save",
"support.status.answered": "answered",
"support.status.closed": "closed",
"support.status.open": "open",
"support.subject": "Subject",
"support.title": "Support",
"support.yes": "yes",
"suspended.intro": "The platform's administrators have suspended your account.", "suspended.intro": "The platform's administrators have suspended your account.",
"suspended.options": "You can still download your data or delete your account.", "suspended.options": "You can still download your data or delete your account.",
"suspended.title": "Account suspended", "suspended.title": "Account suspended",
+9
View File
@@ -34,6 +34,15 @@ func TestAlertGroupsBackfill(t *testing.T) {
if _, err := tx.Exec(ctx, "SET LOCAL app.scope = 'system'"); err != nil { if _, err := tx.Exec(ctx, "SET LOCAL app.scope = 'system'"); err != nil {
t.Fatal(err) t.Fatal(err)
} }
// Support tickets point at alert groups; take them back first.
later, err := files.ReadFile("sql/00051_support_tickets.sql")
if err != nil {
t.Fatal(err)
}
_, laterDown, _ := strings.Cut(string(later), "-- +goose Down")
if _, err := tx.Exec(ctx, laterDown); err != nil {
t.Fatalf("down 00051: %v", err)
}
raw, err := files.ReadFile("sql/00039_alert_groups.sql") raw, err := files.ReadFile("sql/00039_alert_groups.sql")
if err != nil { if err != nil {
t.Fatal(err) t.Fatal(err)
@@ -0,0 +1,51 @@
-- +goose Up
-- Accounts ask the platform's admins for help. A ticket belongs to the
-- account that opened it, even a suspended one; deleting the account
-- deletes its tickets. It may point at an organization and things in it
-- the question is about; deleting those leaves the ticket.
CREATE TABLE support_tickets (
id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
user_id uuid NOT NULL REFERENCES users (id) ON DELETE CASCADE,
org_id uuid REFERENCES orgs (id) ON DELETE SET NULL,
monitor_id uuid REFERENCES monitors (id) ON DELETE SET NULL,
channel_id uuid REFERENCES notification_channels (id) ON DELETE SET NULL,
alert_group_id uuid REFERENCES alert_groups (id) ON DELETE SET NULL,
status_page_id uuid REFERENCES status_pages (id) ON DELETE SET NULL,
incident_id uuid REFERENCES incidents (id) ON DELETE SET NULL,
subject text NOT NULL CHECK (length(subject) BETWEEN 1 AND 200),
-- open waits for the admins, answered for the account.
status text NOT NULL DEFAULT 'open' CHECK (status IN ('open', 'answered', 'closed')),
created_at timestamptz NOT NULL DEFAULT now(),
updated_at timestamptz NOT NULL DEFAULT now()
);
CREATE INDEX support_tickets_user_idx ON support_tickets (user_id, updated_at DESC);
CREATE INDEX support_tickets_status_idx ON support_tickets (status, updated_at DESC);
CREATE TABLE support_messages (
id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
ticket_id uuid NOT NULL REFERENCES support_tickets (id) ON DELETE CASCADE,
-- author_id is empty once the admin who wrote it is deleted.
author_id uuid REFERENCES users (id) ON DELETE SET NULL,
from_staff boolean NOT NULL,
body text NOT NULL CHECK (length(body) BETWEEN 1 AND 10000),
created_at timestamptz NOT NULL DEFAULT now()
);
CREATE INDEX support_messages_ticket_idx ON support_messages (ticket_id, created_at);
ALTER TABLE support_tickets ENABLE ROW LEVEL SECURITY;
ALTER TABLE support_tickets FORCE ROW LEVEL SECURITY;
CREATE POLICY support_tickets_own ON support_tickets FOR ALL
USING (app_scope_system() OR user_id = app_user_id())
WITH CHECK (app_scope_system() OR user_id = app_user_id());
ALTER TABLE support_messages ENABLE ROW LEVEL SECURITY;
ALTER TABLE support_messages FORCE ROW LEVEL SECURITY;
CREATE POLICY support_messages_own ON support_messages FOR ALL
USING (app_scope_system() OR EXISTS (
SELECT 1 FROM support_tickets t WHERE t.id = ticket_id AND t.user_id = app_user_id()))
WITH CHECK (app_scope_system() OR (NOT from_staff AND EXISTS (
SELECT 1 FROM support_tickets t WHERE t.id = ticket_id AND t.user_id = app_user_id())));
-- +goose Down
DROP TABLE support_messages;
DROP TABLE support_tickets;
@@ -0,0 +1,19 @@
-- +goose Up
-- Custom domains are verified by a CNAME to a target unique to the page, or
-- by the TXT record, and checked again while they are in use: a domain that
-- no longer points at the page is switched off after a grace period, so a
-- record left behind cannot be taken over. Domains verified before this
-- have no method and are not checked again.
ALTER TABLE status_pages
ADD COLUMN domain_set_at timestamptz,
ADD COLUMN domain_checked_at timestamptz,
ADD COLUMN domain_failing_since timestamptz,
ADD COLUMN domain_verify_method text CHECK (domain_verify_method IN ('cname', 'txt'));
UPDATE status_pages SET domain_set_at = updated_at WHERE custom_domain IS NOT NULL;
-- +goose Down
ALTER TABLE status_pages
DROP COLUMN domain_verify_method,
DROP COLUMN domain_failing_since,
DROP COLUMN domain_checked_at,
DROP COLUMN domain_set_at;
@@ -0,0 +1,7 @@
-- +goose Up
-- How many monitors one status page of the organization may show; NULL
-- follows the platform default, 0 means unlimited.
ALTER TABLE orgs ADD COLUMN limit_monitors_per_page integer CHECK (limit_monitors_per_page >= 0);
-- +goose Down
ALTER TABLE orgs DROP COLUMN limit_monitors_per_page;
@@ -0,0 +1,7 @@
-- +goose Up
-- The organization's own order of its monitors on the monitor list, within
-- each group; NULL sorts after positioned monitors, by name.
ALTER TABLE monitors ADD COLUMN position integer;
-- +goose Down
ALTER TABLE monitors DROP COLUMN position;
@@ -0,0 +1,41 @@
-- +goose Up
-- The newest result per monitor and region, kept up to date as results
-- arrive. Finding it in check_results means reading a day of results of
-- every monitor, which made every console page slow for organizations
-- with many monitors.
CREATE TABLE latest_results (
monitor_id uuid NOT NULL,
region text NOT NULL,
org_id uuid NOT NULL,
time timestamptz NOT NULL,
ok boolean NOT NULL,
latency_ms integer,
status_code integer,
error text,
PRIMARY KEY (monitor_id, region),
FOREIGN KEY (monitor_id, org_id) REFERENCES monitors (id, org_id) ON DELETE CASCADE
);
CREATE INDEX latest_results_org_idx ON latest_results (org_id);
INSERT INTO latest_results (monitor_id, region, org_id, time, ok, latency_ms, status_code, error)
SELECT DISTINCT ON (r.monitor_id, r.region) r.monitor_id, r.region, r.org_id, r.time, r.ok, r.latency_ms, r.status_code, r.error
FROM check_results r
JOIN monitors m ON m.id = r.monitor_id AND m.org_id = r.org_id
WHERE r.time > now() - INTERVAL '1 day'
ORDER BY r.monitor_id, r.region, r.time DESC;
ALTER TABLE latest_results ENABLE ROW LEVEL SECURITY;
ALTER TABLE latest_results FORCE ROW LEVEL SECURITY;
CREATE POLICY latest_results_tenant ON latest_results FOR ALL
USING (app_scope_system() OR org_id = app_org_id())
WITH CHECK (app_scope_system() OR org_id = app_org_id());
-- Console queries name the organization so that these can be used; row
-- security alone does not let the planner use an index.
CREATE INDEX monitor_regions_org_idx ON monitor_regions (org_id);
CREATE INDEX incidents_open_org_idx ON incidents (org_id) WHERE resolved_at IS NULL;
-- +goose Down
DROP INDEX incidents_open_org_idx;
DROP INDEX monitor_regions_org_idx;
DROP TABLE latest_results;
+12 -2
View File
@@ -3,6 +3,7 @@ package platform
import ( import (
"context" "context"
"net/http" "net/http"
"sync"
"sync/atomic" "sync/atomic"
"time" "time"
@@ -17,15 +18,24 @@ type Probe func(context.Context) error
type Health struct { type Health struct {
probes map[string]Probe probes map[string]Probe
draining atomic.Bool draining atomic.Bool
drained chan struct{}
once sync.Once
} }
// NewHealth returns a Health that is ready while all probes pass. // NewHealth returns a Health that is ready while all probes pass.
func NewHealth(probes map[string]Probe) *Health { func NewHealth(probes map[string]Probe) *Health {
return &Health{probes: probes} return &Health{probes: probes, drained: make(chan struct{})}
} }
// Drain makes /readyz fail permanently. Call it before shutdown. // Drain makes /readyz fail permanently. Call it before shutdown.
func (h *Health) Drain() { h.draining.Store(true) } func (h *Health) Drain() {
h.draining.Store(true)
h.once.Do(func() { close(h.drained) })
}
// Draining is closed once Drain is called, so long-running requests can
// end early instead of holding up the shutdown.
func (h *Health) Draining() <-chan struct{} { return h.drained }
// Register mounts /healthz (liveness) and /readyz (readiness). // Register mounts /healthz (liveness) and /readyz (readiness).
func (h *Health) Register(r gin.IRoutes) { func (h *Health) Register(r gin.IRoutes) {
+10 -1
View File
@@ -281,7 +281,7 @@ func (s *Scheduler) Take(ctx context.Context, instance uuid.UUID, max int, wait
return nil, nil return nil, nil
} }
// BLPOP blocks server side and ignores ctx, so wait in slices. // BLPOP blocks server side and ignores ctx, so wait in slices.
first, err := s.rdb.BLPop(ctx, min(left, time.Second), q).Result() first, err := s.blpop(ctx, min(left, time.Second), q)
if errors.Is(err, redis.Nil) { if errors.Is(err, redis.Nil) {
continue continue
} }
@@ -306,6 +306,15 @@ func (s *Scheduler) Take(ctx context.Context, instance uuid.UUID, max int, wait
return out, nil return out, nil
} }
// blpop is BLPOP with a timeout below a second, which go-redis would round
// up to one (Redis takes fractions of seconds since 6.0).
func (s *Scheduler) blpop(ctx context.Context, timeout time.Duration, key string) ([]string, error) {
if timeout >= time.Second {
return s.rdb.BLPop(ctx, timeout, key).Result()
}
return s.rdb.Do(ctx, "BLPOP", key, strconv.FormatFloat(timeout.Seconds(), 'f', 3, 64)).StringSlice()
}
// Release returns instance's queued runs to its region and forgets it. // Release returns instance's queued runs to its region and forgets it.
func (s *Scheduler) Release(ctx context.Context, region string, instance uuid.UUID) error { func (s *Scheduler) Release(ctx context.Context, region string, instance uuid.UUID) error {
// Marking the instance stale lets the dispatch script do the handover, // Marking the instance stale lets the dispatch script do the handover,
+16 -1
View File
@@ -188,11 +188,26 @@ func TestTakeWaits(t *testing.T) {
if err != nil || len(got) != 0 { if err != nil || len(got) != 0 {
t.Fatalf("Take() on empty queue = %v, %v", got, err) t.Fatalf("Take() on empty queue = %v, %v", got, err)
} }
if waited := time.Since(start); waited < 250*time.Millisecond { // Not rounded up to the second that BLPOP counts in.
if waited := time.Since(start); waited < 250*time.Millisecond || waited > 800*time.Millisecond {
t.Errorf("Take() returned after %v, want it to wait about 300ms", waited) t.Errorf("Take() returned after %v, want it to wait about 300ms", waited)
} }
} }
func TestTakeGetsAJobDuringAShortWait(t *testing.T) {
s, _ := newTest(t)
ctx := context.Background()
in, monitor := uuid.New(), uuid.New()
go func() {
time.Sleep(100 * time.Millisecond)
s.rdb.RPush(ctx, jobsPrefix+in.String(), monitor.String()+"|1800000000000")
}()
got, err := s.Take(ctx, in, 10, 600*time.Millisecond)
if err != nil || len(got) != 1 || got[0].MonitorID != monitor {
t.Fatalf("Take() = %v, %v; want the job pushed while waiting", got, err)
}
}
func TestTakeReturnsWhenCancelled(t *testing.T) { func TestTakeReturnsWhenCancelled(t *testing.T) {
s, _ := newTest(t) s, _ := newTest(t)
ctx, cancel := context.WithCancel(context.Background()) ctx, cancel := context.WithCancel(context.Background())
+136 -17
View File
@@ -35,14 +35,33 @@ import (
const ( const (
// freshFor is how long a snapshot is used without asking the API. // freshFor is how long a snapshot is used without asking the API.
freshFor = 30 * time.Second freshFor = 30 * time.Second
// staleNoticeAfter is when visitors are told the state may be outdated. // refreshInterval is how often pages visited within recentFor are
staleNoticeAfter = 5 * time.Minute // refreshed.
refreshInterval = 30 * time.Second refreshInterval = 30 * time.Second
recentFor = 10 * time.Minute
// syncInterval is how often every page the API lists is fetched, so
// each one is cached before its first visit.
syncInterval = 5 * time.Minute
// staleNoticeAfter is when visitors are told the state may be outdated;
// a page nobody visited is up to syncInterval old.
staleNoticeAfter = 2 * syncInterval
// missFor is how long a host or slug without a page is answered
// without asking the API again.
missFor = time.Minute
maxMissing = 10_000
// unknownPerSecond bounds the lookups of hosts and slugs that are
// neither cached nor known to be missing, so a flood of made-up names
// is not passed on to the API. Every page the API lists is cached by
// the sync, so known pages are not affected.
unknownPerSecond = 20
) )
// Source fetches snapshots; *agentapi.Client implements it. // Source fetches snapshots; *agentapi.Client implements it.
type Source interface { type Source interface {
Page(ctx context.Context, host, slug string) (agentapi.PageSnapshot, error) // PageIfChanged answers agentapi.ErrNotModified when the page still
// has checksum.
PageIfChanged(ctx context.Context, host, slug, checksum string) (agentapi.PageSnapshot, error)
Pages(ctx context.Context) ([]agentapi.PageRef, error)
} }
// Server renders pages for one status page agent. // Server renders pages for one status page agent.
@@ -60,6 +79,14 @@ type Server struct {
mu sync.Mutex mu sync.Mutex
cache map[string]entry cache map[string]entry
refreshing map[string]bool refreshing map[string]bool
// visited holds when each cached page was last visited.
visited map[string]time.Time
// missing holds when a key was last found to have no page.
missing map[string]time.Time
// unknownSecond and unknownCount count lookups passed on to the API in
// the current second.
unknownSecond int64
unknownCount int
// background tracks refreshes started by visits. // background tracks refreshes started by visits.
background sync.WaitGroup background sync.WaitGroup
} }
@@ -71,6 +98,9 @@ type entry struct {
Slug string `json:"slug,omitempty"` Slug string `json:"slug,omitempty"`
Snap agentapi.PageSnapshot `json:"snapshot"` Snap agentapi.PageSnapshot `json:"snapshot"`
Fetched time.Time `json:"fetched"` Fetched time.Time `json:"fetched"`
// Checksum is the snapshot's, sent so the API can answer that nothing
// changed instead of sending it again.
Checksum string `json:"checksum,omitempty"`
} }
// Options configure a Server. // Options configure a Server.
@@ -88,7 +118,8 @@ type Options struct {
func New(src Source, catalog *i18n.Catalog, log *slog.Logger, o Options) (*Server, error) { func New(src Source, catalog *i18n.Catalog, log *slog.Logger, o Options) (*Server, error) {
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{}, now: time.Now, cache: map[string]entry{}, refreshing: map[string]bool{}, visited: map[string]time.Time{},
missing: map[string]time.Time{},
} }
for _, h := range o.Hosts { for _, h := range o.Hosts {
s.ownHosts[strings.ToLower(h)] = true s.ownHosts[strings.ToLower(h)] = true
@@ -152,6 +183,7 @@ func (s *Server) persist(e entry) {
func (s *Server) forget(key string) { func (s *Server) forget(key string) {
s.mu.Lock() s.mu.Lock()
delete(s.cache, key) delete(s.cache, key)
delete(s.visited, key)
s.mu.Unlock() s.mu.Unlock()
if s.dir != "" { if s.dir != "" {
_ = os.Remove(s.fileFor(key)) _ = os.Remove(s.fileFor(key))
@@ -306,8 +338,15 @@ func (s *Server) localizeRequest(c *gin.Context) {
// lookup answers from the cache whenever possible and refreshes in the // lookup answers from the cache whenever possible and refreshes in the
// background; only unknown pages wait for the API. // background; only unknown pages wait for the API.
func (s *Server) lookup(ctx context.Context, key, host, slug string) (entry, bool) { func (s *Server) lookup(ctx context.Context, key, host, slug string) (entry, bool) {
now := s.now()
s.mu.Lock() s.mu.Lock()
e, cached := s.cache[key] e, cached := s.cache[key]
if cached {
s.visited[key] = now
} else if !s.mayAsk(key, now) {
s.mu.Unlock()
return entry{}, false
}
s.mu.Unlock() s.mu.Unlock()
if cached { if cached {
if s.now().Sub(e.Fetched) >= freshFor { if s.now().Sub(e.Fetched) >= freshFor {
@@ -315,14 +354,54 @@ func (s *Server) lookup(ctx context.Context, key, host, slug string) (entry, boo
} }
return e, true return e, true
} }
return s.fetch(ctx, key, host, slug) e, ok := s.fetch(ctx, key, host, slug)
if ok {
s.mu.Lock()
s.visited[key] = now
s.mu.Unlock()
}
return e, ok
}
// mayAsk reports whether an uncached key may be looked up at the API: not
// when it was just found missing, nor beyond unknownPerSecond. s.mu is held.
func (s *Server) mayAsk(key string, now time.Time) bool {
if t, ok := s.missing[key]; ok && now.Sub(t) < missFor {
return false
}
if sec := now.Unix(); sec != s.unknownSecond {
s.unknownSecond, s.unknownCount = sec, 0
}
if s.unknownCount >= unknownPerSecond {
return false
}
s.unknownCount++
return true
} }
func (s *Server) fetch(ctx context.Context, key, host, slug string) (entry, bool) { func (s *Server) fetch(ctx context.Context, key, host, slug string) (entry, bool) {
snap, err := s.src.Page(ctx, host, slug) s.mu.Lock()
old, known := s.cache[key]
s.mu.Unlock()
snap, err := s.src.PageIfChanged(ctx, host, slug, old.Checksum)
switch { switch {
case errors.Is(err, agentapi.ErrNotModified) && known:
// Unchanged: the copy is current as of now.
old.Fetched = s.now()
old.Snap.GeneratedAt = old.Fetched
s.mu.Lock()
s.cache[key] = old
s.mu.Unlock()
s.persist(old)
return old, true
case errors.Is(err, agentapi.ErrNotFound): case errors.Is(err, agentapi.ErrNotFound):
s.forget(key) s.forget(key)
s.mu.Lock()
if len(s.missing) >= maxMissing {
clear(s.missing)
}
s.missing[key] = s.now()
s.mu.Unlock()
return entry{}, false return entry{}, false
case err != nil: case err != nil:
s.log.WarnContext(ctx, "fetching status page failed", "page", key, "error", err) s.log.WarnContext(ctx, "fetching status page failed", "page", key, "error", err)
@@ -331,9 +410,10 @@ func (s *Server) fetch(ctx context.Context, key, host, slug string) (entry, bool
s.mu.Unlock() s.mu.Unlock()
return e, ok return e, ok
} }
e := entry{Key: key, Host: host, Slug: slug, Snap: snap, Fetched: s.now()} e := entry{Key: key, Host: host, Slug: slug, Snap: snap, Fetched: s.now(), Checksum: snap.Checksum()}
s.mu.Lock() s.mu.Lock()
s.cache[key] = e s.cache[key] = e
delete(s.missing, key)
s.mu.Unlock() s.mu.Unlock()
s.persist(e) s.persist(e)
return e, true return e, true
@@ -361,25 +441,64 @@ func (s *Server) refresh(ctx context.Context, key, host, slug string) {
// Wait returns once the background refreshes started by visits are done. // Wait returns once the background refreshes started by visits are done.
func (s *Server) Wait() { s.background.Wait() } func (s *Server) Wait() { s.background.Wait() }
// Run keeps every known page fresh until ctx ends, so pages stay current // Run keeps pages fresh until ctx ends: every page the API lists every
// even without visitors and the cache is warm when the API goes away. // syncInterval, so all are cached before their first visit and survive an
// outage of the API, and recently visited ones every refreshInterval.
func (s *Server) Run(ctx context.Context) { func (s *Server) Run(ctx context.Context) {
tick := time.NewTicker(refreshInterval) refresh := time.NewTicker(refreshInterval)
defer tick.Stop() defer refresh.Stop()
listAll := time.NewTicker(syncInterval)
defer listAll.Stop()
s.Sync(ctx)
for { for {
select { select {
case <-ctx.Done(): case <-ctx.Done():
return return
case <-tick.C: case <-listAll.C:
s.Sync(ctx)
case <-refresh.C:
s.mu.Lock() s.mu.Lock()
entries := make([]entry, 0, len(s.cache)) var recent []entry
for _, e := range s.cache { for key, e := range s.cache {
entries = append(entries, e) if s.now().Sub(s.visited[key]) < recentFor {
recent = append(recent, e)
}
} }
s.mu.Unlock() s.mu.Unlock()
for _, e := range entries { for _, e := range recent {
s.refresh(ctx, e.Key, e.Host, e.Slug) s.refresh(ctx, e.Key, e.Host, e.Slug)
} }
} }
} }
} }
// Sync fetches every page the API lists and every cached one, which drops
// those the API no longer serves. While the API is unreachable the cache
// stays as it is.
func (s *Server) Sync(ctx context.Context) {
ctx, cancel := context.WithTimeout(ctx, syncInterval)
defer cancel()
refs, err := s.src.Pages(ctx)
if err != nil {
s.log.WarnContext(ctx, "listing status pages failed", "error", err)
return
}
todo := map[string]entry{}
s.mu.Lock()
for key, e := range s.cache {
todo[key] = e
}
s.mu.Unlock()
for _, r := range refs {
todo["slug:"+r.Slug] = entry{Key: "slug:" + r.Slug, Slug: r.Slug}
if r.Host != "" {
todo["host:"+r.Host] = entry{Key: "host:" + r.Host, Host: r.Host}
}
}
for _, e := range todo {
if ctx.Err() != nil {
return
}
s.refresh(ctx, e.Key, e.Host, e.Slug)
}
}
+95 -4
View File
@@ -20,12 +20,27 @@ import (
type fakeSource struct { type fakeSource struct {
mu sync.Mutex mu sync.Mutex
calls int calls int
err error // unchanged counts the answers that the page had not changed.
delay time.Duration unchanged int
pages map[string]agentapi.PageSnapshot err error
delay time.Duration
pages map[string]agentapi.PageSnapshot
} }
func (f *fakeSource) Page(ctx context.Context, host, slug string) (agentapi.PageSnapshot, error) { // PageIfChanged counts calls and answers like the API, sending pages
// only when their checksum changed.
func (f *fakeSource) PageIfChanged(ctx context.Context, host, slug, checksum string) (agentapi.PageSnapshot, error) {
p, err := f.page(ctx, host, slug)
if err == nil && checksum != "" && p.Checksum() == checksum {
f.mu.Lock()
f.unchanged++
f.mu.Unlock()
return agentapi.PageSnapshot{}, agentapi.ErrNotModified
}
return p, err
}
func (f *fakeSource) page(ctx context.Context, host, slug string) (agentapi.PageSnapshot, error) {
f.mu.Lock() f.mu.Lock()
f.calls++ f.calls++
err, delay, p, ok := f.err, f.delay, f.pages[host+"|"+slug], false err, delay, p, ok := f.err, f.delay, f.pages[host+"|"+slug], false
@@ -49,6 +64,21 @@ func (f *fakeSource) Page(ctx context.Context, host, slug string) (agentapi.Page
return p, nil return p, nil
} }
// Pages lists the fake's pages by their keys: "host|" or "|slug".
func (f *fakeSource) Pages(context.Context) ([]agentapi.PageRef, error) {
f.mu.Lock()
defer f.mu.Unlock()
if f.err != nil {
return nil, f.err
}
var out []agentapi.PageRef
for k := range f.pages {
host, slug, _ := strings.Cut(k, "|")
out = append(out, agentapi.PageRef{Host: host, Slug: slug})
}
return out, nil
}
func (f *fakeSource) set(fn func(*fakeSource)) { func (f *fakeSource) set(fn func(*fakeSource)) {
f.mu.Lock() f.mu.Lock()
defer f.mu.Unlock() defer f.mu.Unlock()
@@ -464,3 +494,64 @@ func TestNestedGroupsAndComponentDetails(t *testing.T) {
} }
}) })
} }
func TestSyncCachesPagesBeforeTheirFirstVisit(t *testing.T) {
dir := t.TempDir()
now := time.Now()
src := newSource()
h := newHarness(t, src, dir, &now)
h.srv.Sync(context.Background())
// Nobody visited them, yet both survive an outage and a restart.
now = now.Add(syncInterval)
restarted := newHarness(t, &fakeSource{err: errors.New("down")}, dir, &now)
if code, body := restarted.get("status.example.test", "/acme"); code != 200 || !strings.Contains(body, "Acme status") || strings.Contains(body, "Live-Aktualisierung") {
t.Errorf("GET of a synced page with the API down = %d, want it without stale notice", code)
}
if code, body := restarted.get("status.acme.test", "/"); code != 200 || !strings.Contains(body, "Acme on own domain") {
t.Errorf("GET of a synced custom domain with the API down = %d", code)
}
restarted.srv.Sync(context.Background())
if code, _ := restarted.get("status.example.test", "/acme"); code != 200 {
t.Errorf("a failed sync dropped the cache: %d", code)
}
// A page the API no longer lists is dropped by the next sync.
src.set(func(f *fakeSource) { delete(f.pages, "|acme") })
h.srv.Sync(context.Background())
if code, _ := h.get("status.example.test", "/acme"); code != 404 {
t.Errorf("GET after the page left the list = %d, want 404", code)
}
}
func TestRefreshSkipsUnchangedPages(t *testing.T) {
dir := t.TempDir()
now := time.Now()
src := newSource()
h := newHarness(t, src, dir, &now)
h.srv.Sync(context.Background())
now = now.Add(syncInterval)
h.srv.Sync(context.Background())
src.mu.Lock()
unchanged := src.unchanged
src.mu.Unlock()
if unchanged != 2 {
t.Errorf("unchanged answers on the second sync = %d, want 2", unchanged)
}
if _, body := h.get("status.example.test", "/acme"); !strings.Contains(body, "Acme status") || strings.Contains(body, "Live-Aktualisierung") {
t.Error("an unchanged page is not served as current")
}
// A changed page is sent again, and the checksum survives a restart.
src.set(func(f *fakeSource) {
f.pages["|acme"] = agentapi.PageSnapshot{Title: "Renamed", Status: agentapi.PageOperational}
})
restarted := newHarness(t, src, dir, &now)
restarted.srv.Sync(context.Background())
src.mu.Lock()
unchanged = src.unchanged
src.mu.Unlock()
if _, body := restarted.get("status.example.test", "/acme"); !strings.Contains(body, "Renamed") || unchanged != 3 {
t.Errorf("after a change: renamed %t, unchanged answers %d, want 3", strings.Contains(body, "Renamed"), unchanged)
}
}
+34
View File
@@ -151,6 +151,40 @@ func (s CertStorage) Unlock(ctx context.Context, name string) error {
return s.c.StorageUnlock(ctx, name) return s.c.StorageUnlock(ctx, name)
} }
// CertificateGate is asked before a new certificate is ordered;
// *agentapi.Client implements it.
type CertificateGate interface {
AllowCertificate(ctx context.Context, name string) error
}
// OnCertEvent is certmagic's event hook. Before a new certificate for a
// custom domain is ordered it asks the API, which allows verified domains
// of pages this server serves within limits shared by all servers; that
// keeps the CA's rate limits from being used up. Renewals and the default
// hosts are not asked about.
func (s *Server) OnCertEvent(ctx context.Context, event string, data map[string]any) error {
if event != "cert_obtaining" || data["renewal"] == true {
return nil
}
name, _ := data["identifier"].(string)
host := hostOnly(name)
gate, ok := s.src.(CertificateGate)
if s.ownHosts[host] || !ok {
return nil
}
switch err := gate.AllowCertificate(ctx, host); {
case err == nil:
return nil
case errors.Is(err, agentapi.ErrRateLimited):
s.log.WarnContext(ctx, "certificate order refused: limit reached", "domain", host)
return fmt.Errorf("limit on new certificates reached for %s", host)
case errors.Is(err, agentapi.ErrNotFound):
return fmt.Errorf("no status page for %s", host)
default:
return fmt.Errorf("asking whether to order a certificate for %s: %w", host, err)
}
}
// AllowCertificate decides whether to obtain a certificate for name on // AllowCertificate decides whether to obtain a certificate for name on
// demand: only for the default hosts and for verified custom domains of // demand: only for the default hosts and for verified custom domains of
// pages this server may serve. Anything else would let strangers make us // pages this server may serve. Anything else would let strangers make us
+115
View File
@@ -0,0 +1,115 @@
package statuspage
import (
"context"
"errors"
"fmt"
"net/http"
"testing"
"time"
"git.zb-server.de/ZB-Server/uptimesebi/internal/agentapi"
)
func (f *fakeSource) callCount() int {
f.mu.Lock()
defer f.mu.Unlock()
return f.calls
}
func TestUnknownNamesAreNotAskedAgainAtOnce(t *testing.T) {
now := time.Now()
src := newSource()
h := newHarness(t, src, "", &now)
for range 3 {
if code, _ := h.get("nope.example.test", "/"); code != http.StatusNotFound {
t.Fatalf("unknown host = %d, want 404", code)
}
}
if n := src.callCount(); n != 1 {
t.Errorf("the API was asked %d times about one unknown host, want 1", n)
}
now = now.Add(missFor)
h.get("nope.example.test", "/")
if n := src.callCount(); n != 2 {
t.Errorf("after %v the API was asked %d times in all, want 2", missFor, n)
}
h.srv.mu.Lock()
visited := len(h.srv.visited)
h.srv.mu.Unlock()
if visited != 0 {
t.Errorf("unknown hosts were recorded as visited pages: %d", visited)
}
}
func TestFloodOfMadeUpNamesIsThrottled(t *testing.T) {
now := time.Now()
src := newSource()
h := newHarness(t, src, "", &now)
h.srv.Sync(context.Background())
before := src.callCount()
for i := range 200 {
h.get(fmt.Sprintf("x%d.example.test", i), "/")
}
if n := src.callCount() - before; n > unknownPerSecond {
t.Errorf("a flood of made-up hosts reached the API %d times in one second, want at most %d", n, unknownPerSecond)
}
// Pages the sync cached are still served during the flood.
if code, _ := h.get("status.acme.test", "/"); code != http.StatusOK {
t.Errorf("a known page during the flood = %d, want 200", code)
}
now = now.Add(time.Second)
if err := h.srv.AllowCertificate(context.Background(), "status.acme.test"); err != nil {
t.Errorf("a known custom domain after the flood: %v", err)
}
}
type gatedSource struct {
*fakeSource
asked []string
err error
}
func (g *gatedSource) AllowCertificate(_ context.Context, name string) error {
g.asked = append(g.asked, name)
return g.err
}
func TestNewCertificatesAreOrderedOnlyWhenTheAPIAllows(t *testing.T) {
now := time.Now()
g := &gatedSource{fakeSource: newSource()}
h := newHarness(t, g.fakeSource, "", &now)
h.srv.src = g
ctx := context.Background()
obtain := func(name string, renewal bool) error {
data := map[string]any{"identifier": name}
if renewal {
data["renewal"] = true
}
return h.srv.OnCertEvent(ctx, "cert_obtaining", data)
}
if err := obtain("status.acme.test", false); err != nil {
t.Errorf("allowed order: %v", err)
}
// Renewals, the default hosts and other events are not asked about.
if err := obtain("status.acme.test", true); err != nil {
t.Errorf("renewal: %v", err)
}
if err := obtain("status.example.test", false); err != nil {
t.Errorf("default host: %v", err)
}
if err := h.srv.OnCertEvent(ctx, "cert_obtained", map[string]any{"identifier": "status.acme.test"}); err != nil {
t.Errorf("other event: %v", err)
}
if len(g.asked) != 1 || g.asked[0] != "status.acme.test" {
t.Errorf("asked about %v, want only the new order", g.asked)
}
for _, refuse := range []error{agentapi.ErrRateLimited, agentapi.ErrNotFound, errors.New("api down")} {
g.err = refuse
if err := obtain("status.acme.test", false); err == nil {
t.Errorf("order went ahead although the API answered %v", refuse)
}
}
}
+86
View File
@@ -318,6 +318,92 @@ func (q *Queries) ListVisibleRegions(ctx context.Context) ([]Region, error) {
return items, nil return items, nil
} }
const orgOwnerEmails = `-- name: OrgOwnerEmails :many
SELECT u.email FROM memberships m JOIN users u ON u.id = m.user_id
WHERE m.org_id = $1 AND m.is_owner AND u.disabled_at IS NULL
`
// System scope.
func (q *Queries) OrgOwnerEmails(ctx context.Context, orgID uuid.UUID) ([]string, error) {
rows, err := q.db.Query(ctx, orgOwnerEmails, orgID)
if err != nil {
return nil, err
}
defer rows.Close()
items := []string{}
for rows.Next() {
var email string
if err := rows.Scan(&email); err != nil {
return nil, err
}
items = append(items, email)
}
if err := rows.Err(); err != nil {
return nil, err
}
return items, nil
}
const orgServesOwnPages = `-- name: OrgServesOwnPages :one
SELECT EXISTS (
SELECT 1 FROM agents
WHERE org_id = $1 AND kind = 'statuspage' AND last_seen_at IS NOT NULL
)
`
// An organization serves its status pages itself once one of its own
// status page servers has connected.
func (q *Queries) OrgServesOwnPages(ctx context.Context, orgID *uuid.UUID) (bool, error) {
row := q.db.QueryRow(ctx, orgServesOwnPages, orgID)
var exists bool
err := row.Scan(&exists)
return exists, err
}
const regionsToWatch = `-- name: RegionsToWatch :many
SELECT r.id, r.name, r.org_id, o.name AS org_name
FROM regions r
LEFT JOIN orgs o ON o.id = r.org_id
WHERE EXISTS (SELECT 1 FROM agents a WHERE a.kind = 'checker' AND a.region_id = r.id)
AND EXISTS (SELECT 1 FROM monitor_regions mr JOIN monitors m ON m.id = mr.monitor_id
WHERE mr.region_id = r.id AND m.enabled)
ORDER BY r.name
`
type RegionsToWatchRow struct {
ID uuid.UUID
Name string
OrgID *uuid.UUID
OrgName *string
}
// System scope: regions that have checkers and enabled monitors, so a
// region without a live checker leaves monitors unchecked.
func (q *Queries) RegionsToWatch(ctx context.Context) ([]RegionsToWatchRow, error) {
rows, err := q.db.Query(ctx, regionsToWatch)
if err != nil {
return nil, err
}
defer rows.Close()
items := []RegionsToWatchRow{}
for rows.Next() {
var i RegionsToWatchRow
if err := rows.Scan(
&i.ID,
&i.Name,
&i.OrgID,
&i.OrgName,
); err != nil {
return nil, err
}
items = append(items, i)
}
if err := rows.Err(); err != nil {
return nil, err
}
return items, nil
}
const setAgentAllowPrivate = `-- name: SetAgentAllowPrivate :execrows const setAgentAllowPrivate = `-- name: SetAgentAllowPrivate :execrows
UPDATE agents SET allow_private = $1 UPDATE agents SET allow_private = $1
WHERE id = $2 AND kind = 'checker' AND org_id = $3 WHERE id = $2 AND kind = 'checker' AND org_id = $3
+74 -74
View File
@@ -124,22 +124,65 @@ 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
WHERE org_id = $1 WHERE org_id = $1 AND monitor_id = $2
GROUP BY 1, 2 GROUP BY 1, 2
` `
type FirstDataDailyParams struct {
OrgID uuid.UUID
MonitorID uuid.UUID
}
type FirstDataDailyRow struct { type FirstDataDailyRow struct {
MonitorID uuid.UUID MonitorID uuid.UUID
Region string Region string
First time.Time First time.Time
} }
// When each monitor and region first reported, to the day. // When each region of a monitor first reported, to the day.
func (q *Queries) FirstDataDaily(ctx context.Context, orgID uuid.UUID) ([]FirstDataDailyRow, error) { func (q *Queries) FirstDataDaily(ctx context.Context, arg FirstDataDailyParams) ([]FirstDataDailyRow, error) {
rows, err := q.db.Query(ctx, firstDataDaily, orgID) rows, err := q.db.Query(ctx, firstDataDaily, arg.OrgID, arg.MonitorID)
if err != nil { if err != nil {
return nil, err return nil, err
} }
@@ -161,13 +204,14 @@ func (q *Queries) FirstDataDaily(ctx context.Context, orgID uuid.UUID) ([]FirstD
const firstDataRecent = `-- name: FirstDataRecent :many const firstDataRecent = `-- name: FirstDataRecent :many
SELECT monitor_id, region, min(time)::timestamptz AS first SELECT monitor_id, region, min(time)::timestamptz AS first
FROM check_results FROM check_results
WHERE org_id = $1 AND time >= $2 WHERE org_id = $1 AND monitor_id = $2 AND time >= $3
GROUP BY 1, 2 GROUP BY 1, 2
` `
type FirstDataRecentParams struct { type FirstDataRecentParams struct {
OrgID uuid.UUID OrgID uuid.UUID
Time time.Time MonitorID uuid.UUID
Time time.Time
} }
type FirstDataRecentRow struct { type FirstDataRecentRow struct {
@@ -176,10 +220,10 @@ type FirstDataRecentRow struct {
First time.Time First time.Time
} }
// When each monitor and region first reported since $2, exactly. Used for // When each region of a monitor first reported since $3, exactly. Used for
// data younger than the daily aggregate's resolution. // data younger than the daily aggregate's resolution.
func (q *Queries) FirstDataRecent(ctx context.Context, arg FirstDataRecentParams) ([]FirstDataRecentRow, error) { func (q *Queries) FirstDataRecent(ctx context.Context, arg FirstDataRecentParams) ([]FirstDataRecentRow, error) {
rows, err := q.db.Query(ctx, firstDataRecent, arg.OrgID, arg.Time) rows, err := q.db.Query(ctx, firstDataRecent, arg.OrgID, arg.MonitorID, arg.Time)
if err != nil { if err != nil {
return nil, err return nil, err
} }
@@ -203,6 +247,7 @@ SELECT monitor_id, bucket::timestamptz AS bucket, sum(total)::bigint AS total, s
coalesce(sum(avg_latency_ms * total) / nullif(sum(total), 0), 0)::real AS avg_latency_ms coalesce(sum(avg_latency_ms * total) / nullif(sum(total), 0), 0)::real AS avg_latency_ms
FROM check_results_1h FROM check_results_1h
WHERE org_id = $1 AND bucket >= $2 WHERE org_id = $1 AND bucket >= $2
AND ($3::uuid[] IS NULL OR monitor_id = ANY ($3::uuid[]))
GROUP BY monitor_id, bucket GROUP BY monitor_id, bucket
ORDER BY monitor_id, bucket ORDER BY monitor_id, bucket
` `
@@ -210,6 +255,7 @@ ORDER BY monitor_id, bucket
type HourlyBucketsParams struct { type HourlyBucketsParams struct {
OrgID uuid.UUID OrgID uuid.UUID
Bucket interface{} Bucket interface{}
Ids []uuid.UUID
} }
type HourlyBucketsRow struct { type HourlyBucketsRow struct {
@@ -222,7 +268,7 @@ type HourlyBucketsRow struct {
// Per monitor and hour since $2, across all regions. // Per monitor and hour since $2, across all regions.
func (q *Queries) HourlyBuckets(ctx context.Context, arg HourlyBucketsParams) ([]HourlyBucketsRow, error) { func (q *Queries) HourlyBuckets(ctx context.Context, arg HourlyBucketsParams) ([]HourlyBucketsRow, error) {
rows, err := q.db.Query(ctx, hourlyBuckets, arg.OrgID, arg.Bucket) rows, err := q.db.Query(ctx, hourlyBuckets, arg.OrgID, arg.Bucket, arg.Ids)
if err != nil { if err != nil {
return nil, err return nil, err
} }
@@ -259,52 +305,6 @@ type InsertCheckResultsParams struct {
Error *string Error *string
} }
const latestResults = `-- name: LatestResults :many
SELECT DISTINCT ON (monitor_id, region) monitor_id, region, time, ok, latency_ms, status_code, error
FROM check_results
WHERE org_id = $1 AND time > now() - interval '1 day'
ORDER BY monitor_id, region, time DESC
`
type LatestResultsRow struct {
MonitorID uuid.UUID
Region string
Time time.Time
Ok bool
LatencyMs *int32
StatusCode *int32
Error *string
}
// Newest result per monitor and region in the org.
func (q *Queries) LatestResults(ctx context.Context, orgID uuid.UUID) ([]LatestResultsRow, error) {
rows, err := q.db.Query(ctx, latestResults, orgID)
if err != nil {
return nil, err
}
defer rows.Close()
items := []LatestResultsRow{}
for rows.Next() {
var i LatestResultsRow
if err := rows.Scan(
&i.MonitorID,
&i.Region,
&i.Time,
&i.Ok,
&i.LatencyMs,
&i.StatusCode,
&i.Error,
); err != nil {
return nil, err
}
items = append(items, i)
}
if err := rows.Err(); err != nil {
return nil, err
}
return items, nil
}
const latestResultsForMonitor = `-- name: LatestResultsForMonitor :many const latestResultsForMonitor = `-- name: LatestResultsForMonitor :many
SELECT DISTINCT ON (region) region, ok, error SELECT DISTINCT ON (region) region, ok, error
FROM check_results FROM check_results
@@ -425,16 +425,16 @@ SELECT monitor_id, time_bucket($2::text::interval, time)::timestamptz AS bucket,
coalesce(avg(latency_ms), 0)::real AS avg_latency_ms coalesce(avg(latency_ms), 0)::real AS avg_latency_ms
FROM check_results FROM check_results
WHERE org_id = $1 AND time >= $3 WHERE org_id = $1 AND time >= $3
AND ($4::uuid IS NULL OR monitor_id = $4) AND monitor_id = ANY ($4::uuid[])
GROUP BY 1, 2 GROUP BY 1, 2
ORDER BY 1, 2 ORDER BY 1, 2
` `
type RangeBucketsParams struct { type RangeBucketsParams struct {
OrgID uuid.UUID OrgID uuid.UUID
Width string Width string
Since time.Time Since time.Time
MonitorID *uuid.UUID Ids []uuid.UUID
} }
type RangeBucketsRow struct { type RangeBucketsRow struct {
@@ -451,7 +451,7 @@ func (q *Queries) RangeBuckets(ctx context.Context, arg RangeBucketsParams) ([]R
arg.OrgID, arg.OrgID,
arg.Width, arg.Width,
arg.Since, arg.Since,
arg.MonitorID, arg.Ids,
) )
if err != nil { if err != nil {
return nil, err return nil, err
@@ -483,16 +483,16 @@ SELECT monitor_id, time_bucket($2::text::interval, bucket)::timestamptz AS bucke
coalesce(sum(avg_latency_ms * total) / nullif(sum(total), 0), 0)::real AS avg_latency_ms coalesce(sum(avg_latency_ms * total) / nullif(sum(total), 0), 0)::real AS avg_latency_ms
FROM check_results_1d FROM check_results_1d
WHERE org_id = $1 AND bucket >= $3 WHERE org_id = $1 AND bucket >= $3
AND ($4::uuid IS NULL OR monitor_id = $4) AND monitor_id = ANY ($4::uuid[])
GROUP BY 1, 2 GROUP BY 1, 2
ORDER BY 1, 2 ORDER BY 1, 2
` `
type RangeBucketsDailyParams struct { type RangeBucketsDailyParams struct {
OrgID uuid.UUID OrgID uuid.UUID
Width string Width string
Since interface{} Since interface{}
MonitorID *uuid.UUID Ids []uuid.UUID
} }
type RangeBucketsDailyRow struct { type RangeBucketsDailyRow struct {
@@ -509,7 +509,7 @@ func (q *Queries) RangeBucketsDaily(ctx context.Context, arg RangeBucketsDailyPa
arg.OrgID, arg.OrgID,
arg.Width, arg.Width,
arg.Since, arg.Since,
arg.MonitorID, arg.Ids,
) )
if err != nil { if err != nil {
return nil, err return nil, err
@@ -541,16 +541,16 @@ SELECT monitor_id, time_bucket($2::text::interval, bucket)::timestamptz AS bucke
coalesce(sum(avg_latency_ms * total) / nullif(sum(total), 0), 0)::real AS avg_latency_ms coalesce(sum(avg_latency_ms * total) / nullif(sum(total), 0), 0)::real AS avg_latency_ms
FROM check_results_1h FROM check_results_1h
WHERE org_id = $1 AND bucket >= $3 WHERE org_id = $1 AND bucket >= $3
AND ($4::uuid IS NULL OR monitor_id = $4) AND monitor_id = ANY ($4::uuid[])
GROUP BY 1, 2 GROUP BY 1, 2
ORDER BY 1, 2 ORDER BY 1, 2
` `
type RangeBucketsHourlyParams struct { type RangeBucketsHourlyParams struct {
OrgID uuid.UUID OrgID uuid.UUID
Width string Width string
Since interface{} Since interface{}
MonitorID *uuid.UUID Ids []uuid.UUID
} }
type RangeBucketsHourlyRow struct { type RangeBucketsHourlyRow struct {
@@ -567,7 +567,7 @@ func (q *Queries) RangeBucketsHourly(ctx context.Context, arg RangeBucketsHourly
arg.OrgID, arg.OrgID,
arg.Width, arg.Width,
arg.Since, arg.Since,
arg.MonitorID, arg.Ids,
) )
if err != nil { if err != nil {
return nil, err return nil, err
+12 -7
View File
@@ -313,18 +313,23 @@ func (q *Queries) IncidentsForMonitors(ctx context.Context, arg IncidentsForMoni
const incidentsSince = `-- name: IncidentsSince :many const incidentsSince = `-- name: IncidentsSince :many
SELECT monitor_id, started_at, resolved_at FROM incidents SELECT monitor_id, started_at, resolved_at FROM incidents
WHERE resolved_at IS NULL OR resolved_at > $1 WHERE org_id = $1 AND (resolved_at IS NULL OR resolved_at > $2)
` `
type IncidentsSinceParams struct {
OrgID uuid.UUID
ResolvedAt *time.Time
}
type IncidentsSinceRow struct { type IncidentsSinceRow struct {
MonitorID uuid.UUID MonitorID uuid.UUID
StartedAt time.Time StartedAt time.Time
ResolvedAt *time.Time ResolvedAt *time.Time
} }
// Incidents overlapping the time since $1, for SLA calculation. // Incidents overlapping the time since $2, for SLA calculation.
func (q *Queries) IncidentsSince(ctx context.Context, resolvedAt *time.Time) ([]IncidentsSinceRow, error) { func (q *Queries) IncidentsSince(ctx context.Context, arg IncidentsSinceParams) ([]IncidentsSinceRow, error) {
rows, err := q.db.Query(ctx, incidentsSince, resolvedAt) rows, err := q.db.Query(ctx, incidentsSince, arg.OrgID, arg.ResolvedAt)
if err != nil { if err != nil {
return nil, err return nil, err
} }
@@ -672,11 +677,11 @@ func (q *Queries) OpenIncident(ctx context.Context, arg OpenIncidentParams) (Inc
} }
const openIncidents = `-- name: OpenIncidents :many const openIncidents = `-- name: OpenIncidents :many
SELECT id, org_id, monitor_id, started_at, resolved_at, cause, title, status, status_id FROM incidents WHERE resolved_at IS NULL SELECT id, org_id, monitor_id, started_at, resolved_at, cause, title, status, status_id FROM incidents WHERE org_id = $1 AND resolved_at IS NULL
` `
func (q *Queries) OpenIncidents(ctx context.Context) ([]Incident, error) { func (q *Queries) OpenIncidents(ctx context.Context, orgID uuid.UUID) ([]Incident, error) {
rows, err := q.db.Query(ctx, openIncidents) rows, err := q.db.Query(ctx, openIncidents, orgID)
if err != nil { if err != nil {
return nil, err return nil, err
} }
+130
View File
@@ -0,0 +1,130 @@
// Code generated by sqlc. DO NOT EDIT.
// versions:
// sqlc v1.31.1
// source: latest_results.sql
package store
import (
"context"
"time"
"github.com/google/uuid"
)
const latestResults = `-- name: LatestResults :many
SELECT monitor_id, region, time, ok, latency_ms, status_code, error
FROM latest_results
WHERE org_id = $1 AND time > now() - interval '1 day'
`
type LatestResultsRow struct {
MonitorID uuid.UUID
Region string
Time time.Time
Ok bool
LatencyMs *int32
StatusCode *int32
Error *string
}
// Newest result per monitor and region in the org, of the last day.
func (q *Queries) LatestResults(ctx context.Context, orgID uuid.UUID) ([]LatestResultsRow, error) {
rows, err := q.db.Query(ctx, latestResults, orgID)
if err != nil {
return nil, err
}
defer rows.Close()
items := []LatestResultsRow{}
for rows.Next() {
var i LatestResultsRow
if err := rows.Scan(
&i.MonitorID,
&i.Region,
&i.Time,
&i.Ok,
&i.LatencyMs,
&i.StatusCode,
&i.Error,
); err != nil {
return nil, err
}
items = append(items, i)
}
if err := rows.Err(); err != nil {
return nil, err
}
return items, nil
}
const latestResultsForMonitors = `-- name: LatestResultsForMonitors :many
SELECT monitor_id, region, time, ok, latency_ms, status_code, error
FROM latest_results
WHERE org_id = $1 AND monitor_id = ANY ($2::uuid[]) AND time > now() - interval '1 day'
`
type LatestResultsForMonitorsParams struct {
OrgID uuid.UUID
Ids []uuid.UUID
}
type LatestResultsForMonitorsRow struct {
MonitorID uuid.UUID
Region string
Time time.Time
Ok bool
LatencyMs *int32
StatusCode *int32
Error *string
}
// LatestResults limited to the monitors ids.
func (q *Queries) LatestResultsForMonitors(ctx context.Context, arg LatestResultsForMonitorsParams) ([]LatestResultsForMonitorsRow, error) {
rows, err := q.db.Query(ctx, latestResultsForMonitors, arg.OrgID, arg.Ids)
if err != nil {
return nil, err
}
defer rows.Close()
items := []LatestResultsForMonitorsRow{}
for rows.Next() {
var i LatestResultsForMonitorsRow
if err := rows.Scan(
&i.MonitorID,
&i.Region,
&i.Time,
&i.Ok,
&i.LatencyMs,
&i.StatusCode,
&i.Error,
); err != nil {
return nil, err
}
items = append(items, i)
}
if err := rows.Err(); err != nil {
return nil, err
}
return items, nil
}
const upsertLatestResults = `-- name: UpsertLatestResults :exec
INSERT INTO latest_results (monitor_id, region, org_id, time, ok, latency_ms, status_code, error)
SELECT DISTINCT ON (r.monitor_id, r.region) r.monitor_id, r.region, r.org_id, r.time, r.ok, r.latency_ms, r.status_code, r.error
FROM jsonb_to_recordset($1::jsonb)
AS r(monitor_id uuid, region text, org_id uuid, time timestamptz, ok boolean, latency_ms integer, status_code integer, error text)
ORDER BY r.monitor_id, r.region, r.time DESC
ON CONFLICT (monitor_id, region) DO UPDATE
SET org_id = excluded.org_id, time = excluded.time, ok = excluded.ok, latency_ms = excluded.latency_ms,
status_code = excluded.status_code, error = excluded.error
WHERE latest_results.time <= excluded.time
`
// latest_results holds the newest check result per monitor and region
// (see migration 00055) and has row-level security.
// Keeps the newest of rows, a JSON array of results, per monitor and
// region; results arriving late do not replace newer ones.
func (q *Queries) UpsertLatestResults(ctx context.Context, rows []byte) error {
_, err := q.db.Exec(ctx, upsertLatestResults, rows)
return err
}
+19 -2
View File
@@ -15,6 +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,
(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,
@@ -61,6 +62,7 @@ type AdminListOrgsRow struct {
LimitStatusPages *int32 LimitStatusPages *int32
LimitRegionsPerMonitor *int32 LimitRegionsPerMonitor *int32
LimitOwnRegionsCount *bool LimitOwnRegionsCount *bool
LimitMonitorsPerPage *int32
Monitors int32 Monitors int32
StatusPages int32 StatusPages int32
OwnerID uuid.UUID OwnerID uuid.UUID
@@ -102,6 +104,7 @@ func (q *Queries) AdminListOrgs(ctx context.Context, arg AdminListOrgsParams) ([
&i.LimitStatusPages, &i.LimitStatusPages,
&i.LimitRegionsPerMonitor, &i.LimitRegionsPerMonitor,
&i.LimitOwnRegionsCount, &i.LimitOwnRegionsCount,
&i.LimitMonitorsPerPage,
&i.Monitors, &i.Monitors,
&i.StatusPages, &i.StatusPages,
&i.OwnerID, &i.OwnerID,
@@ -133,6 +136,17 @@ func (q *Queries) CountMonitors(ctx context.Context, orgID uuid.UUID) (int64, er
return count, err return count, err
} }
const countStatusPageMonitors = `-- name: CountStatusPageMonitors :one
SELECT count(*) FROM status_page_monitors WHERE page_id = $1
`
func (q *Queries) CountStatusPageMonitors(ctx context.Context, pageID uuid.UUID) (int64, error) {
row := q.db.QueryRow(ctx, countStatusPageMonitors, pageID)
var count int64
err := row.Scan(&count)
return count, err
}
const countStatusPages = `-- name: CountStatusPages :one const countStatusPages = `-- name: CountStatusPages :one
SELECT count(*) FROM status_pages WHERE org_id = $1 SELECT count(*) FROM status_pages WHERE org_id = $1
` `
@@ -157,8 +171,9 @@ 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,
WHERE id = $5 limit_monitors_per_page = $5
WHERE id = $6
RETURNING id, slug RETURNING id, slug
` `
@@ -167,6 +182,7 @@ type SetOrgLimitsParams struct {
StatusPages *int32 StatusPages *int32
RegionsPerMonitor *int32 RegionsPerMonitor *int32
OwnRegionsCount *bool OwnRegionsCount *bool
MonitorsPerPage *int32
ID uuid.UUID ID uuid.UUID
} }
@@ -181,6 +197,7 @@ func (q *Queries) SetOrgLimits(ctx context.Context, arg SetOrgLimitsParams) (Set
arg.StatusPages, arg.StatusPages,
arg.RegionsPerMonitor, arg.RegionsPerMonitor,
arg.OwnRegionsCount, arg.OwnRegionsCount,
arg.MonitorsPerPage,
arg.ID, arg.ID,
) )
var i SetOrgLimitsRow var i SetOrgLimitsRow
+41
View File
@@ -197,6 +197,17 @@ type Invitation struct {
CreatedAt time.Time CreatedAt time.Time
} }
type LatestResult struct {
MonitorID uuid.UUID
Region string
OrgID uuid.UUID
Time time.Time
Ok bool
LatencyMs *int32
StatusCode *int32
Error *string
}
type LegalAcceptance struct { type LegalAcceptance struct {
UserID uuid.UUID UserID uuid.UUID
Kind string Kind string
@@ -257,6 +268,7 @@ type Monitor struct {
UpdatedAt time.Time UpdatedAt time.Time
Confirmations int32 Confirmations int32
GroupID *uuid.UUID GroupID *uuid.UUID
Position *int32
} }
type MonitorAlertGroup struct { type MonitorAlertGroup struct {
@@ -321,6 +333,7 @@ type Org struct {
LimitStatusPages *int32 LimitStatusPages *int32
LimitRegionsPerMonitor *int32 LimitRegionsPerMonitor *int32
LimitOwnRegionsCount *bool LimitOwnRegionsCount *bool
LimitMonitorsPerPage *int32
} }
type PlatformIdentity struct { type PlatformIdentity struct {
@@ -418,6 +431,10 @@ type StatusPage struct {
ShowComponentDetails bool ShowComponentDetails bool
SuspendedAt *time.Time SuspendedAt *time.Time
SuspendedReason string SuspendedReason string
DomainSetAt *time.Time
DomainCheckedAt *time.Time
DomainFailingSince *time.Time
DomainVerifyMethod *string
} }
type StatusPageGroup struct { type StatusPageGroup struct {
@@ -441,6 +458,30 @@ type StatusPageMonitor struct {
GroupID *uuid.UUID GroupID *uuid.UUID
} }
type SupportMessage struct {
ID uuid.UUID
TicketID uuid.UUID
AuthorID *uuid.UUID
FromStaff bool
Body string
CreatedAt time.Time
}
type SupportTicket struct {
ID uuid.UUID
UserID uuid.UUID
OrgID *uuid.UUID
MonitorID *uuid.UUID
ChannelID *uuid.UUID
AlertGroupID *uuid.UUID
StatusPageID *uuid.UUID
IncidentID *uuid.UUID
Subject string
Status string
CreatedAt time.Time
UpdatedAt time.Time
}
type User struct { type User struct {
ID uuid.UUID ID uuid.UUID
Email string Email string
+35 -11
View File
@@ -27,7 +27,7 @@ func (q *Queries) AddMonitorRegion(ctx context.Context, arg AddMonitorRegionPara
} }
const allMonitorRegions = `-- name: AllMonitorRegions :many const allMonitorRegions = `-- name: AllMonitorRegions :many
SELECT monitor_id, region_id FROM monitor_regions SELECT monitor_id, region_id FROM monitor_regions WHERE org_id = $1
` `
type AllMonitorRegionsRow struct { type AllMonitorRegionsRow struct {
@@ -35,8 +35,8 @@ type AllMonitorRegionsRow struct {
RegionID uuid.UUID RegionID uuid.UUID
} }
func (q *Queries) AllMonitorRegions(ctx context.Context) ([]AllMonitorRegionsRow, error) { func (q *Queries) AllMonitorRegions(ctx context.Context, orgID uuid.UUID) ([]AllMonitorRegionsRow, error) {
rows, err := q.db.Query(ctx, allMonitorRegions) rows, err := q.db.Query(ctx, allMonitorRegions, orgID)
if err != nil { if err != nil {
return nil, err return nil, err
} }
@@ -58,7 +58,7 @@ func (q *Queries) AllMonitorRegions(ctx context.Context) ([]AllMonitorRegionsRow
const createMonitor = `-- name: CreateMonitor :one const createMonitor = `-- name: CreateMonitor :one
INSERT INTO monitors (org_id, name, type, target, interval_seconds, timeout_ms, config, enabled, confirmations, group_id) INSERT INTO monitors (org_id, name, type, target, interval_seconds, timeout_ms, config, enabled, confirmations, group_id)
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10)
RETURNING id, org_id, name, type, target, interval_seconds, timeout_ms, config, enabled, created_at, updated_at, confirmations, group_id RETURNING id, org_id, name, type, target, interval_seconds, timeout_ms, config, enabled, created_at, updated_at, confirmations, group_id, position
` `
type CreateMonitorParams struct { type CreateMonitorParams struct {
@@ -102,6 +102,7 @@ func (q *Queries) CreateMonitor(ctx context.Context, arg CreateMonitorParams) (M
&i.UpdatedAt, &i.UpdatedAt,
&i.Confirmations, &i.Confirmations,
&i.GroupID, &i.GroupID,
&i.Position,
) )
return i, err return i, err
} }
@@ -128,7 +129,7 @@ func (q *Queries) DeleteMonitorRegions(ctx context.Context, monitorID uuid.UUID)
} }
const getMonitor = `-- name: GetMonitor :one const getMonitor = `-- name: GetMonitor :one
SELECT id, org_id, name, type, target, interval_seconds, timeout_ms, config, enabled, created_at, updated_at, confirmations, group_id FROM monitors WHERE id = $1 SELECT id, org_id, name, type, target, interval_seconds, timeout_ms, config, enabled, created_at, updated_at, confirmations, group_id, position FROM monitors WHERE id = $1
` `
func (q *Queries) GetMonitor(ctx context.Context, id uuid.UUID) (Monitor, error) { func (q *Queries) GetMonitor(ctx context.Context, id uuid.UUID) (Monitor, error) {
@@ -148,6 +149,7 @@ func (q *Queries) GetMonitor(ctx context.Context, id uuid.UUID) (Monitor, error)
&i.UpdatedAt, &i.UpdatedAt,
&i.Confirmations, &i.Confirmations,
&i.GroupID, &i.GroupID,
&i.Position,
) )
return i, err return i, err
} }
@@ -190,11 +192,12 @@ func (q *Queries) ListEnabledMonitorsForSchedule(ctx context.Context) ([]ListEna
} }
const listMonitors = `-- name: ListMonitors :many const listMonitors = `-- name: ListMonitors :many
SELECT id, org_id, name, type, target, interval_seconds, timeout_ms, config, enabled, created_at, updated_at, confirmations, group_id FROM monitors ORDER BY name SELECT id, org_id, name, type, target, interval_seconds, timeout_ms, config, enabled, created_at, updated_at, confirmations, group_id, position FROM monitors WHERE org_id = $1 ORDER BY name
` `
func (q *Queries) ListMonitors(ctx context.Context) ([]Monitor, error) { // The org filter, though row security implies it, lets the index be used.
rows, err := q.db.Query(ctx, listMonitors) func (q *Queries) ListMonitors(ctx context.Context, orgID uuid.UUID) ([]Monitor, error) {
rows, err := q.db.Query(ctx, listMonitors, orgID)
if err != nil { if err != nil {
return nil, err return nil, err
} }
@@ -216,6 +219,7 @@ func (q *Queries) ListMonitors(ctx context.Context) ([]Monitor, error) {
&i.UpdatedAt, &i.UpdatedAt,
&i.Confirmations, &i.Confirmations,
&i.GroupID, &i.GroupID,
&i.Position,
); err != nil { ); err != nil {
return nil, err return nil, err
} }
@@ -228,7 +232,7 @@ func (q *Queries) ListMonitors(ctx context.Context) ([]Monitor, error) {
} }
const listMonitorsPage = `-- name: ListMonitorsPage :many const listMonitorsPage = `-- name: ListMonitorsPage :many
SELECT id, org_id, name, type, target, interval_seconds, timeout_ms, config, enabled, created_at, updated_at, confirmations, group_id FROM monitors SELECT id, org_id, name, type, target, interval_seconds, timeout_ms, config, enabled, created_at, updated_at, confirmations, group_id, position FROM monitors
WHERE true WHERE true
AND ($1::text IS NULL OR (name, id) > ($1, $2::uuid)) AND ($1::text IS NULL OR (name, id) > ($1, $2::uuid))
AND ($3::text IS NULL OR (name, id) < ($3, $4::uuid)) AND ($3::text IS NULL OR (name, id) < ($3, $4::uuid))
@@ -277,6 +281,7 @@ func (q *Queries) ListMonitorsPage(ctx context.Context, arg ListMonitorsPagePara
&i.UpdatedAt, &i.UpdatedAt,
&i.Confirmations, &i.Confirmations,
&i.GroupID, &i.GroupID,
&i.Position,
); err != nil { ); err != nil {
return nil, err return nil, err
} }
@@ -313,7 +318,7 @@ func (q *Queries) MonitorRegions(ctx context.Context, monitorID uuid.UUID) ([]uu
} }
const monitorsForJobs = `-- name: MonitorsForJobs :many const monitorsForJobs = `-- name: MonitorsForJobs :many
SELECT m.id, m.org_id, m.name, m.type, m.target, m.interval_seconds, m.timeout_ms, m.config, m.enabled, m.created_at, m.updated_at, m.confirmations, m.group_id FROM monitors m SELECT m.id, m.org_id, m.name, m.type, m.target, m.interval_seconds, m.timeout_ms, m.config, m.enabled, m.created_at, m.updated_at, m.confirmations, m.group_id, m.position FROM monitors m
JOIN monitor_regions r ON r.monitor_id = m.id AND r.region_id = $1 JOIN monitor_regions r ON r.monitor_id = m.id AND r.region_id = $1
JOIN orgs o ON o.id = m.org_id AND o.suspended_at IS NULL JOIN orgs o ON o.id = m.org_id AND o.suspended_at IS NULL
WHERE m.id = ANY ($2::uuid[]) AND m.enabled WHERE m.id = ANY ($2::uuid[]) AND m.enabled
@@ -352,6 +357,7 @@ func (q *Queries) MonitorsForJobs(ctx context.Context, arg MonitorsForJobsParams
&i.UpdatedAt, &i.UpdatedAt,
&i.Confirmations, &i.Confirmations,
&i.GroupID, &i.GroupID,
&i.Position,
); err != nil { ); err != nil {
return nil, err return nil, err
} }
@@ -419,11 +425,28 @@ func (q *Queries) MonitorsForResults(ctx context.Context, arg MonitorsForResults
return items, nil return items, nil
} }
const setMonitorPosition = `-- name: SetMonitorPosition :execrows
UPDATE monitors SET position = $1 WHERE id = $2
`
type SetMonitorPositionParams struct {
Position *int32
ID uuid.UUID
}
func (q *Queries) SetMonitorPosition(ctx context.Context, arg SetMonitorPositionParams) (int64, error) {
result, err := q.db.Exec(ctx, setMonitorPosition, arg.Position, arg.ID)
if err != nil {
return 0, err
}
return result.RowsAffected(), nil
}
const updateMonitor = `-- name: UpdateMonitor :one const updateMonitor = `-- name: UpdateMonitor :one
UPDATE monitors SET name = $2, type = $3, target = $4, interval_seconds = $5, UPDATE monitors SET name = $2, type = $3, target = $4, interval_seconds = $5,
timeout_ms = $6, config = $7, enabled = $8, confirmations = $9, group_id = $10, updated_at = now() timeout_ms = $6, config = $7, enabled = $8, confirmations = $9, group_id = $10, updated_at = now()
WHERE id = $1 WHERE id = $1
RETURNING id, org_id, name, type, target, interval_seconds, timeout_ms, config, enabled, created_at, updated_at, confirmations, group_id RETURNING id, org_id, name, type, target, interval_seconds, timeout_ms, config, enabled, created_at, updated_at, confirmations, group_id, position
` `
type UpdateMonitorParams struct { type UpdateMonitorParams struct {
@@ -467,6 +490,7 @@ func (q *Queries) UpdateMonitor(ctx context.Context, arg UpdateMonitorParams) (M
&i.UpdatedAt, &i.UpdatedAt,
&i.Confirmations, &i.Confirmations,
&i.GroupID, &i.GroupID,
&i.Position,
) )
return i, err return i, err
} }
+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 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
` `
type CreateOrgParams struct { type CreateOrgParams struct {
@@ -41,6 +41,7 @@ func (q *Queries) CreateOrg(ctx context.Context, arg CreateOrgParams) (Org, erro
&i.LimitStatusPages, &i.LimitStatusPages,
&i.LimitRegionsPerMonitor, &i.LimitRegionsPerMonitor,
&i.LimitOwnRegionsCount, &i.LimitOwnRegionsCount,
&i.LimitMonitorsPerPage,
) )
return i, err return i, err
} }
@@ -58,7 +59,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 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 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) {
@@ -80,12 +81,13 @@ func (q *Queries) GetOrg(ctx context.Context, id uuid.UUID) (Org, error) {
&i.LimitStatusPages, &i.LimitStatusPages,
&i.LimitRegionsPerMonitor, &i.LimitRegionsPerMonitor,
&i.LimitOwnRegionsCount, &i.LimitOwnRegionsCount,
&i.LimitMonitorsPerPage,
) )
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 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 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) {
@@ -107,12 +109,13 @@ func (q *Queries) GetOrgBySlug(ctx context.Context, slug string) (Org, error) {
&i.LimitStatusPages, &i.LimitStatusPages,
&i.LimitRegionsPerMonitor, &i.LimitRegionsPerMonitor,
&i.LimitOwnRegionsCount, &i.LimitOwnRegionsCount,
&i.LimitMonitorsPerPage,
) )
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 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 FROM orgs ORDER BY name
` `
func (q *Queries) ListOrgs(ctx context.Context) ([]Org, error) { func (q *Queries) ListOrgs(ctx context.Context) ([]Org, error) {
@@ -140,6 +143,7 @@ func (q *Queries) ListOrgs(ctx context.Context) ([]Org, error) {
&i.LimitStatusPages, &i.LimitStatusPages,
&i.LimitRegionsPerMonitor, &i.LimitRegionsPerMonitor,
&i.LimitOwnRegionsCount, &i.LimitOwnRegionsCount,
&i.LimitMonitorsPerPage,
); err != nil { ); err != nil {
return nil, err return nil, err
} }
@@ -168,7 +172,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 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
` `
type UpdateOrgPolicyParams struct { type UpdateOrgPolicyParams struct {
@@ -202,6 +206,7 @@ func (q *Queries) UpdateOrgPolicy(ctx context.Context, arg UpdateOrgPolicyParams
&i.LimitStatusPages, &i.LimitStatusPages,
&i.LimitRegionsPerMonitor, &i.LimitRegionsPerMonitor,
&i.LimitOwnRegionsCount, &i.LimitOwnRegionsCount,
&i.LimitMonitorsPerPage,
) )
return i, err return i, err
} }
+74 -11
View File
@@ -22,6 +22,8 @@ type Querier interface {
AddMonitorAlertGroup(ctx context.Context, arg AddMonitorAlertGroupParams) (int64, error) AddMonitorAlertGroup(ctx context.Context, arg AddMonitorAlertGroupParams) (int64, error)
AddMonitorRegion(ctx context.Context, arg AddMonitorRegionParams) error AddMonitorRegion(ctx context.Context, arg AddMonitorRegionParams) error
AddStatusPageMonitor(ctx context.Context, arg AddStatusPageMonitorParams) error AddStatusPageMonitor(ctx context.Context, arg AddStatusPageMonitorParams) error
AddSupportMessage(ctx context.Context, arg AddSupportMessageParams) (SupportMessage, error)
AdminEmails(ctx context.Context) ([]string, error)
// System scope: organizations with their usage, limit overrides and owner, // System scope: organizations with their usage, limit overrides and owner,
// matching search in name, slug or owner email; newest first, a page from a // matching search in name, slug or owner email; newest first, a page from a
// keyset cursor. // keyset cursor.
@@ -37,7 +39,7 @@ type Querier interface {
// System scope: the receiver a webhook token belongs to. // System scope: the receiver a webhook token belongs to.
AlertmanagerReceiverByHash(ctx context.Context, tokenHash []byte) (AlertmanagerReceiverByHashRow, error) AlertmanagerReceiverByHash(ctx context.Context, tokenHash []byte) (AlertmanagerReceiverByHashRow, error)
AllMonitorAlertGroups(ctx context.Context) ([]MonitorAlertGroup, error) AllMonitorAlertGroups(ctx context.Context) ([]MonitorAlertGroup, error)
AllMonitorRegions(ctx context.Context) ([]AllMonitorRegionsRow, error) AllMonitorRegions(ctx context.Context, orgID uuid.UUID) ([]AllMonitorRegionsRow, error)
AnyUserExists(ctx context.Context) (bool, error) AnyUserExists(ctx context.Context) (bool, error)
// How much one instance checked for the organization in the last hour. // How much one instance checked for the organization in the last hour.
CheckerStats(ctx context.Context, arg CheckerStatsParams) (CheckerStatsRow, error) CheckerStats(ctx context.Context, arg CheckerStatsParams) (CheckerStatsRow, error)
@@ -50,10 +52,13 @@ type Querier interface {
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
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)
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)
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)
CountStatusPages(ctx context.Context, orgID uuid.UUID) (int64, error) CountStatusPages(ctx context.Context, orgID uuid.UUID) (int64, error)
CountSupportTicketsSince(ctx context.Context, arg CountSupportTicketsSinceParams) (int64, error)
CountUnusedRecoveryCodes(ctx context.Context, userID uuid.UUID) (int64, error) CountUnusedRecoveryCodes(ctx context.Context, userID uuid.UUID) (int64, error)
// Ways the account can sign in besides platform identities. // Ways the account can sign in besides platform identities.
CountUserSignIns(ctx context.Context, id uuid.UUID) (int32, error) CountUserSignIns(ctx context.Context, id uuid.UUID) (int32, error)
@@ -77,6 +82,7 @@ type Querier interface {
CreateSSOProvider(ctx context.Context, arg CreateSSOProviderParams) (SsoProvider, error) CreateSSOProvider(ctx context.Context, arg CreateSSOProviderParams) (SsoProvider, error)
CreateStatusPage(ctx context.Context, arg CreateStatusPageParams) (StatusPage, error) CreateStatusPage(ctx context.Context, arg CreateStatusPageParams) (StatusPage, error)
CreateStatusPageGroup(ctx context.Context, arg CreateStatusPageGroupParams) (StatusPageGroup, error) CreateStatusPageGroup(ctx context.Context, arg CreateStatusPageGroupParams) (StatusPageGroup, error)
CreateSupportTicket(ctx context.Context, arg CreateSupportTicketParams) (SupportTicket, error)
CreateUser(ctx context.Context, arg CreateUserParams) (User, error) CreateUser(ctx context.Context, arg CreateUserParams) (User, error)
DailyBuckets(ctx context.Context, arg DailyBucketsParams) ([]DailyBucketsRow, error) DailyBuckets(ctx context.Context, arg DailyBucketsParams) ([]DailyBucketsRow, error)
DailyBucketsForMonitors(ctx context.Context, arg DailyBucketsForMonitorsParams) ([]DailyBucketsForMonitorsRow, error) DailyBucketsForMonitors(ctx context.Context, arg DailyBucketsForMonitorsParams) ([]DailyBucketsForMonitorsRow, error)
@@ -113,6 +119,17 @@ type Querier interface {
DeleteSuccessEvidence(ctx context.Context, arg DeleteSuccessEvidenceParams) error DeleteSuccessEvidence(ctx context.Context, arg DeleteSuccessEvidenceParams) error
DeleteUser(ctx context.Context, id uuid.UUID) (int64, error) DeleteUser(ctx context.Context, id uuid.UUID) (int64, error)
DisableTOTP(ctx context.Context, id uuid.UUID) error DisableTOTP(ctx context.Context, id uuid.UUID) error
// System scope: domains due for a look at their DNS records. A new one is
// looked at every minute for a quarter of an hour, then every ten minutes
// for two days, after which only the verify button tries again. A verified
// one is checked daily, hourly once its record went missing.
DomainsToCheck(ctx context.Context, arg DomainsToCheckParams) ([]DomainsToCheckRow, error)
// The day the organization's monitors first reported, if any did.
EarliestDataDaily(ctx context.Context, orgID uuid.UUID) (time.Time, error)
// When the organization's monitors first reported since $2, exactly: the
// first result of each monitor is found through its index, so the cost
// does not grow with the days of results.
EarliestDataRecent(ctx context.Context, arg EarliestDataRecentParams) (time.Time, error)
EmailKeyTaken(ctx context.Context, emailKey *string) (bool, error) 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
@@ -128,9 +145,9 @@ type Querier interface {
// FiringAlerts newest first, a page from a keyset cursor (see paging.go) // FiringAlerts newest first, a page from a keyset cursor (see paging.go)
// whose string key is the fingerprint. // whose string key is the fingerprint.
FiringAlertsPage(ctx context.Context, arg FiringAlertsPageParams) ([]FiringAlertsPageRow, error) FiringAlertsPage(ctx context.Context, arg FiringAlertsPageParams) ([]FiringAlertsPageRow, error)
// When each monitor and region first reported, to the day. // When each region of a monitor first reported, to the day.
FirstDataDaily(ctx context.Context, orgID uuid.UUID) ([]FirstDataDailyRow, error) FirstDataDaily(ctx context.Context, arg FirstDataDailyParams) ([]FirstDataDailyRow, error)
// When each monitor and region first reported since $2, exactly. Used for // When each region of a monitor first reported since $3, exactly. Used for
// data younger than the daily aggregate's resolution. // data younger than the daily aggregate's resolution.
FirstDataRecent(ctx context.Context, arg FirstDataRecentParams) ([]FirstDataRecentRow, error) FirstDataRecent(ctx context.Context, arg FirstDataRecentParams) ([]FirstDataRecentRow, error)
// Keeps organization and platform entries readable as "deleted user" but // Keeps organization and platform entries readable as "deleted user" but
@@ -160,6 +177,7 @@ type Querier interface {
GetRole(ctx context.Context, id uuid.UUID) (Role, error) GetRole(ctx context.Context, id uuid.UUID) (Role, error)
GetSSOProvider(ctx context.Context, id uuid.UUID) (SsoProvider, error) GetSSOProvider(ctx context.Context, id uuid.UUID) (SsoProvider, error)
GetStatusPage(ctx context.Context, id uuid.UUID) (StatusPage, error) GetStatusPage(ctx context.Context, id uuid.UUID) (StatusPage, error)
GetSupportTicket(ctx context.Context, id uuid.UUID) (GetSupportTicketRow, error)
GetUser(ctx context.Context, id uuid.UUID) (User, error) GetUser(ctx context.Context, id uuid.UUID) (User, error)
GetUserByEmail(ctx context.Context, email string) (User, error) GetUserByEmail(ctx context.Context, email string) (User, error)
// System scope: the monitor a ping token belongs to. // System scope: the monitor a ping token belongs to.
@@ -172,8 +190,8 @@ type Querier interface {
// Per monitor and hour since $2, across all regions. // Per monitor and hour since $2, across all regions.
HourlyBuckets(ctx context.Context, arg HourlyBucketsParams) ([]HourlyBucketsRow, error) HourlyBuckets(ctx context.Context, arg HourlyBucketsParams) ([]HourlyBucketsRow, error)
IncidentsForMonitors(ctx context.Context, arg IncidentsForMonitorsParams) ([]Incident, error) IncidentsForMonitors(ctx context.Context, arg IncidentsForMonitorsParams) ([]Incident, error)
// Incidents overlapping the time since $1, for SLA calculation. // Incidents overlapping the time since $2, for SLA calculation.
IncidentsSince(ctx context.Context, resolvedAt *time.Time) ([]IncidentsSinceRow, error) IncidentsSince(ctx context.Context, arg IncidentsSinceParams) ([]IncidentsSinceRow, error)
InsertAuditEvent(ctx context.Context, arg InsertAuditEventParams) error InsertAuditEvent(ctx context.Context, arg InsertAuditEventParams) error
// check_results and its aggregates have no row-level security (see // check_results and its aggregates have no row-level security (see
// migration 00013). Every query here must filter by org_id. // migration 00013). Every query here must filter by org_id.
@@ -184,9 +202,11 @@ type Querier interface {
IsMember(ctx context.Context, arg IsMemberParams) (bool, error) IsMember(ctx context.Context, arg IsMemberParams) (bool, error)
LastFailureEvidence(ctx context.Context, arg LastFailureEvidenceParams) (LastFailureEvidenceRow, error) LastFailureEvidence(ctx context.Context, arg LastFailureEvidenceParams) (LastFailureEvidenceRow, error)
LatestResultForMonitor(ctx context.Context, arg LatestResultForMonitorParams) (LatestResultForMonitorRow, error) LatestResultForMonitor(ctx context.Context, arg LatestResultForMonitorParams) (LatestResultForMonitorRow, error)
// Newest result per monitor and region in the org. // Newest result per monitor and region in the org, of the last day.
LatestResults(ctx context.Context, orgID uuid.UUID) ([]LatestResultsRow, error) LatestResults(ctx context.Context, orgID uuid.UUID) ([]LatestResultsRow, error)
LatestResultsForMonitor(ctx context.Context, arg LatestResultsForMonitorParams) ([]LatestResultsForMonitorRow, error) LatestResultsForMonitor(ctx context.Context, arg LatestResultsForMonitorParams) ([]LatestResultsForMonitorRow, error)
// LatestResults limited to the monitors ids.
LatestResultsForMonitors(ctx context.Context, arg LatestResultsForMonitorsParams) ([]LatestResultsForMonitorsRow, error)
LegalAcceptances(ctx context.Context, userID uuid.UUID) ([]LegalAcceptancesRow, error) LegalAcceptances(ctx context.Context, userID uuid.UUID) ([]LegalAcceptancesRow, error)
// The organization's documents and the platform's, organization first. // The organization's documents and the platform's, organization first.
LegalDocuments(ctx context.Context, orgID *uuid.UUID) ([]LegalDocument, error) LegalDocuments(ctx context.Context, orgID *uuid.UUID) ([]LegalDocument, error)
@@ -217,7 +237,8 @@ type Querier interface {
// Latest start first, a page from a keyset cursor (see paging.go). // Latest start first, a page from a keyset cursor (see paging.go).
ListMaintenancePage(ctx context.Context, arg ListMaintenancePageParams) ([]MaintenanceWindow, error) ListMaintenancePage(ctx context.Context, arg ListMaintenancePageParams) ([]MaintenanceWindow, error)
ListMaintenanceTargets(ctx context.Context) ([]MaintenanceTarget, error) ListMaintenanceTargets(ctx context.Context) ([]MaintenanceTarget, error)
ListMonitors(ctx context.Context) ([]Monitor, error) // The org filter, though row security implies it, lets the index be used.
ListMonitors(ctx context.Context, orgID uuid.UUID) ([]Monitor, error)
// By name, a page from a keyset cursor (see paging.go). // By name, a page from a keyset cursor (see paging.go).
ListMonitorsPage(ctx context.Context, arg ListMonitorsPageParams) ([]Monitor, error) ListMonitorsPage(ctx context.Context, arg ListMonitorsPageParams) ([]Monitor, error)
ListOrgMembers(ctx context.Context, orgID uuid.UUID) ([]ListOrgMembersRow, error) ListOrgMembers(ctx context.Context, orgID uuid.UUID) ([]ListOrgMembersRow, error)
@@ -234,9 +255,14 @@ type Querier interface {
ListSSOProviders(ctx context.Context) ([]SsoProvider, error) ListSSOProviders(ctx context.Context) ([]SsoProvider, error)
ListStatusPageGroups(ctx context.Context, pageID uuid.UUID) ([]StatusPageGroup, error) ListStatusPageGroups(ctx context.Context, pageID uuid.UUID) ([]StatusPageGroup, error)
ListStatusPages(ctx context.Context) ([]StatusPage, error) ListStatusPages(ctx context.Context) ([]StatusPage, error)
// Every account's tickets for the admins, those waiting for them first.
ListSupportTickets(ctx context.Context, status *string) ([]ListSupportTicketsRow, error)
ListUserIdentitiesInOrg(ctx context.Context, userID uuid.UUID) ([]ListUserIdentitiesInOrgRow, error) ListUserIdentitiesInOrg(ctx context.Context, userID uuid.UUID) ([]ListUserIdentitiesInOrgRow, error)
ListUserOrgs(ctx context.Context, userID uuid.UUID) ([]ListUserOrgsRow, error) ListUserOrgs(ctx context.Context, userID uuid.UUID) ([]ListUserOrgsRow, error)
ListUserPlatformIdentities(ctx context.Context, userID uuid.UUID) ([]ListUserPlatformIdentitiesRow, error) ListUserPlatformIdentities(ctx context.Context, userID uuid.UUID) ([]ListUserPlatformIdentitiesRow, error)
// The tickets row-level security lets the account see, newest activity
// first.
ListUserSupportTickets(ctx context.Context, userID uuid.UUID) ([]SupportTicket, error)
// Row-level security limits this to platform regions and the scope's org; // Row-level security limits this to platform regions and the scope's org;
// the org's own regions come first. // the org's own regions come first.
ListVisibleRegions(ctx context.Context) ([]Region, error) ListVisibleRegions(ctx context.Context) ([]Region, error)
@@ -250,7 +276,11 @@ type Querier interface {
// their group or one of its ancestors. // their group or one of its ancestors.
MaintenanceForMonitors(ctx context.Context, ids []uuid.UUID) ([]MaintenanceForMonitorsRow, error) MaintenanceForMonitors(ctx context.Context, ids []uuid.UUID) ([]MaintenanceForMonitorsRow, error)
MakeAdmin(ctx context.Context, id uuid.UUID) error MakeAdmin(ctx context.Context, id uuid.UUID) error
MarkDomainVerified(ctx context.Context, id uuid.UUID) error // The record of a domain was not found. Returns since when it has not
// been, for a verified domain.
MarkDomainUnconfirmed(ctx context.Context, arg MarkDomainUnconfirmedParams) (*time.Time, error)
// The domain's record was found: verified, or still in place.
MarkDomainVerified(ctx context.Context, arg MarkDomainVerifiedParams) error
MarkEmailVerified(ctx context.Context, id uuid.UUID) (User, error) MarkEmailVerified(ctx context.Context, id uuid.UUID) (User, error)
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
@@ -270,7 +300,7 @@ type Querier interface {
// System scope. // System scope.
NotificationDetails(ctx context.Context, ids []uuid.UUID) ([]NotificationDetailsRow, error) NotificationDetails(ctx context.Context, ids []uuid.UUID) ([]NotificationDetailsRow, error)
OpenIncident(ctx context.Context, arg OpenIncidentParams) (Incident, error) OpenIncident(ctx context.Context, arg OpenIncidentParams) (Incident, error)
OpenIncidents(ctx context.Context) ([]Incident, error) OpenIncidents(ctx context.Context, orgID uuid.UUID) ([]Incident, error)
OrgAssignmentsExport(ctx context.Context, orgID uuid.UUID) ([]OrgAssignmentsExportRow, error) OrgAssignmentsExport(ctx context.Context, orgID uuid.UUID) ([]OrgAssignmentsExportRow, error)
OrgAuditExport(ctx context.Context, orgID uuid.UUID) ([]OrgAuditExportRow, error) OrgAuditExport(ctx context.Context, orgID uuid.UUID) ([]OrgAuditExportRow, error)
OrgDailyStats(ctx context.Context, orgID uuid.UUID) ([]OrgDailyStatsRow, error) OrgDailyStats(ctx context.Context, orgID uuid.UUID) ([]OrgDailyStatsRow, error)
@@ -278,6 +308,11 @@ type Querier interface {
OrgIncidentUpdatesExport(ctx context.Context, orgID uuid.UUID) ([]OrgIncidentUpdatesExportRow, error) OrgIncidentUpdatesExport(ctx context.Context, orgID uuid.UUID) ([]OrgIncidentUpdatesExportRow, error)
OrgIncidentsExport(ctx context.Context, orgID uuid.UUID) ([]OrgIncidentsExportRow, error) OrgIncidentsExport(ctx context.Context, orgID uuid.UUID) ([]OrgIncidentsExportRow, error)
OrgMembersExport(ctx context.Context, orgID uuid.UUID) ([]OrgMembersExportRow, error) OrgMembersExport(ctx context.Context, orgID uuid.UUID) ([]OrgMembersExportRow, error)
// System scope.
OrgOwnerEmails(ctx context.Context, orgID uuid.UUID) ([]string, error)
// An organization serves its status pages itself once one of its own
// status page servers has connected.
OrgServesOwnPages(ctx context.Context, orgID *uuid.UUID) (bool, error)
// Organizations user owns, with their member and owner counts. // Organizations user owns, with their member and owner counts.
OwnedOrgs(ctx context.Context, userID uuid.UUID) ([]OwnedOrgsRow, error) OwnedOrgs(ctx context.Context, userID uuid.UUID) ([]OwnedOrgsRow, error)
// The public updates of incidents shown on a status page, newest first. // The public updates of incidents shown on a status page, newest first.
@@ -307,6 +342,9 @@ type Querier interface {
RegionBuckets(ctx context.Context, arg RegionBucketsParams) ([]RegionBucketsRow, error) RegionBuckets(ctx context.Context, arg RegionBucketsParams) ([]RegionBucketsRow, error)
RegionBucketsDaily(ctx context.Context, arg RegionBucketsDailyParams) ([]RegionBucketsDailyRow, error) RegionBucketsDaily(ctx context.Context, arg RegionBucketsDailyParams) ([]RegionBucketsDailyRow, error)
RegionBucketsHourly(ctx context.Context, arg RegionBucketsHourlyParams) ([]RegionBucketsHourlyRow, error) RegionBucketsHourly(ctx context.Context, arg RegionBucketsHourlyParams) ([]RegionBucketsHourlyRow, error)
// System scope: regions that have checkers and enabled monitors, so a
// region without a live checker leaves monitors unchecked.
RegionsToWatch(ctx context.Context) ([]RegionsToWatchRow, error)
RegroupMonitors(ctx context.Context, arg RegroupMonitorsParams) error RegroupMonitors(ctx context.Context, arg RegroupMonitorsParams) error
RemoveMembership(ctx context.Context, arg RemoveMembershipParams) (int64, error) RemoveMembership(ctx context.Context, arg RemoveMembershipParams) (int64, error)
// Moves the subgroups of a group that is about to be deleted. // Moves the subgroups of a group that is about to be deleted.
@@ -323,16 +361,22 @@ type Querier interface {
// page from a keyset cursor whose string key is monitor and region. // page from a keyset cursor whose string key is monitor and region.
ResultsByChecker(ctx context.Context, arg ResultsByCheckerParams) ([]ResultsByCheckerRow, error) ResultsByChecker(ctx context.Context, arg ResultsByCheckerParams) ([]ResultsByCheckerRow, error)
ScrubAuditEmail(ctx context.Context, email string) error ScrubAuditEmail(ctx context.Context, email string) error
// System scope: the published pages a status page server serves, those
// of agent_org for an organization's server; the platform's leave the
// pages of organizations serving their own.
ServablePages(ctx context.Context, agentOrg *uuid.UUID) ([]ServablePagesRow, error)
SetAgentAllowPrivate(ctx context.Context, arg SetAgentAllowPrivateParams) (int64, error) SetAgentAllowPrivate(ctx context.Context, arg SetAgentAllowPrivateParams) (int64, error)
SetIncidentTitle(ctx context.Context, arg SetIncidentTitleParams) (int64, error) SetIncidentTitle(ctx context.Context, arg SetIncidentTitleParams) (int64, error)
SetMonitorPosition(ctx context.Context, arg SetMonitorPositionParams) (int64, error)
SetOrgDisabledCheckTypes(ctx context.Context, arg SetOrgDisabledCheckTypesParams) error SetOrgDisabledCheckTypes(ctx context.Context, arg SetOrgDisabledCheckTypesParams) error
SetOrgLimits(ctx context.Context, arg SetOrgLimitsParams) (SetOrgLimitsRow, error) SetOrgLimits(ctx context.Context, arg SetOrgLimitsParams) (SetOrgLimitsRow, error)
SetOwner(ctx context.Context, arg SetOwnerParams) (int64, error) SetOwner(ctx context.Context, arg SetOwnerParams) (int64, error)
SetPasswordHash(ctx context.Context, arg SetPasswordHashParams) error SetPasswordHash(ctx context.Context, arg SetPasswordHashParams) error
SetPlatformSetting(ctx context.Context, arg SetPlatformSettingParams) error SetPlatformSetting(ctx context.Context, arg SetPlatformSettingParams) error
// Changing the domain drops a previous verification. // Changing the domain drops a previous verification and its checks.
SetStatusPageDomain(ctx context.Context, arg SetStatusPageDomainParams) (StatusPage, error) SetStatusPageDomain(ctx context.Context, arg SetStatusPageDomainParams) (StatusPage, error)
SetStatusPageMonitorGroup(ctx context.Context, arg SetStatusPageMonitorGroupParams) error SetStatusPageMonitorGroup(ctx context.Context, arg SetStatusPageMonitorGroupParams) error
SetSupportTicketStatus(ctx context.Context, arg SetSupportTicketStatusParams) (int64, error)
SetUserAdmin(ctx context.Context, arg SetUserAdminParams) (int64, error) SetUserAdmin(ctx context.Context, arg SetUserAdminParams) (int64, error)
SetUserLocale(ctx context.Context, arg SetUserLocaleParams) error SetUserLocale(ctx context.Context, arg SetUserLocaleParams) error
SetUserOrgLimit(ctx context.Context, arg SetUserOrgLimitParams) (SetUserOrgLimitRow, error) SetUserOrgLimit(ctx context.Context, arg SetUserOrgLimitParams) (SetUserOrgLimitRow, error)
@@ -346,6 +390,18 @@ 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
SupportMessages(ctx context.Context, ticketID uuid.UUID) ([]SupportMessagesRow, error)
SupportOptionsAlertGroups(ctx context.Context, orgID uuid.UUID) ([]SupportOptionsAlertGroupsRow, error)
SupportOptionsChannels(ctx context.Context, orgID uuid.UUID) ([]SupportOptionsChannelsRow, error)
SupportOptionsIncidents(ctx context.Context, orgID uuid.UUID) ([]SupportOptionsIncidentsRow, error)
SupportOptionsMonitors(ctx context.Context, orgID uuid.UUID) ([]SupportOptionsMonitorsRow, error)
SupportOptionsStatusPages(ctx context.Context, orgID uuid.UUID) ([]SupportOptionsStatusPagesRow, error)
// Whether everything a new ticket points at belongs to org; run in the
// organization's scope so only what the account may see counts.
SupportReferencesExist(ctx context.Context, arg SupportReferencesExistParams) (*bool, error)
// The names of what a ticket points at, for showing it.
SupportTicketReferences(ctx context.Context, id uuid.UUID) (SupportTicketReferencesRow, error)
SupportTicketStatus(ctx context.Context, id uuid.UUID) (string, error)
SuspendOrg(ctx context.Context, arg SuspendOrgParams) (SuspendOrgRow, error) SuspendOrg(ctx context.Context, arg SuspendOrgParams) (SuspendOrgRow, error)
SuspendStatusPage(ctx context.Context, arg SuspendStatusPageParams) (SuspendStatusPageRow, error) SuspendStatusPage(ctx context.Context, arg SuspendStatusPageParams) (SuspendStatusPageRow, error)
SuspendUser(ctx context.Context, arg SuspendUserParams) (SuspendUserRow, error) SuspendUser(ctx context.Context, arg SuspendUserParams) (SuspendUserRow, error)
@@ -355,6 +411,8 @@ type Querier interface {
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
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.
UnverifyDomain(ctx context.Context, id uuid.UUID) error
UpdateAlertGroup(ctx context.Context, arg UpdateAlertGroupParams) (AlertGroup, error) UpdateAlertGroup(ctx context.Context, arg UpdateAlertGroupParams) (AlertGroup, error)
UpdateChannel(ctx context.Context, arg UpdateChannelParams) (NotificationChannel, error) UpdateChannel(ctx context.Context, arg UpdateChannelParams) (NotificationChannel, error)
UpdateGroup(ctx context.Context, arg UpdateGroupParams) (MonitorGroup, error) UpdateGroup(ctx context.Context, arg UpdateGroupParams) (MonitorGroup, error)
@@ -368,6 +426,11 @@ type Querier interface {
UpdateStatusPage(ctx context.Context, arg UpdateStatusPageParams) (StatusPage, error) UpdateStatusPage(ctx context.Context, arg UpdateStatusPageParams) (StatusPage, error)
UpdateStatusPageGroup(ctx context.Context, arg UpdateStatusPageGroupParams) (StatusPageGroup, error) UpdateStatusPageGroup(ctx context.Context, arg UpdateStatusPageGroupParams) (StatusPageGroup, error)
UpsertAlertmanagerAlert(ctx context.Context, arg UpsertAlertmanagerAlertParams) error UpsertAlertmanagerAlert(ctx context.Context, arg UpsertAlertmanagerAlertParams) error
// latest_results holds the newest check result per monitor and region
// (see migration 00055) and has row-level security.
// Keeps the newest of rows, a JSON array of results, per monitor and
// region; results arriving late do not replace newer ones.
UpsertLatestResults(ctx context.Context, rows []byte) error
// A new version starts when the document is created or when the edit asks // A new version starts when the document is created or when the edit asks
// everyone to accept it again. // everyone to accept it again.
UpsertLegalDocument(ctx context.Context, arg UpsertLegalDocumentParams) error UpsertLegalDocument(ctx context.Context, arg UpsertLegalDocumentParams) error
+24
View File
@@ -54,3 +54,27 @@ WHERE id = $1 AND (last_seen_at IS NULL OR last_seen_at < now() - interval '30 s
-- name: SetAgentAllowPrivate :execrows -- name: SetAgentAllowPrivate :execrows
UPDATE agents SET allow_private = sqlc.arg(allow_private) UPDATE agents SET allow_private = sqlc.arg(allow_private)
WHERE id = sqlc.arg(id) AND kind = 'checker' AND org_id = sqlc.arg(org_id); WHERE id = sqlc.arg(id) AND kind = 'checker' AND org_id = sqlc.arg(org_id);
-- name: OrgServesOwnPages :one
-- An organization serves its status pages itself once one of its own
-- status page servers has connected.
SELECT EXISTS (
SELECT 1 FROM agents
WHERE org_id = $1 AND kind = 'statuspage' AND last_seen_at IS NOT NULL
);
-- name: RegionsToWatch :many
-- System scope: regions that have checkers and enabled monitors, so a
-- region without a live checker leaves monitors unchecked.
SELECT r.id, r.name, r.org_id, o.name AS org_name
FROM regions r
LEFT JOIN orgs o ON o.id = r.org_id
WHERE EXISTS (SELECT 1 FROM agents a WHERE a.kind = 'checker' AND a.region_id = r.id)
AND EXISTS (SELECT 1 FROM monitor_regions mr JOIN monitors m ON m.id = mr.monitor_id
WHERE mr.region_id = r.id AND m.enabled)
ORDER BY r.name;
-- name: OrgOwnerEmails :many
-- System scope.
SELECT u.email FROM memberships m JOIN users u ON u.id = m.user_id
WHERE m.org_id = $1 AND m.is_owner AND u.disabled_at IS NULL;
+25 -14
View File
@@ -5,13 +5,6 @@
INSERT INTO check_results (time, org_id, monitor_id, region, checker_id, ok, latency_ms, status_code, error) INSERT INTO check_results (time, org_id, monitor_id, region, checker_id, ok, latency_ms, status_code, error)
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9); VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9);
-- name: LatestResults :many
-- Newest result per monitor and region in the org.
SELECT DISTINCT ON (monitor_id, region) monitor_id, region, time, ok, latency_ms, status_code, error
FROM check_results
WHERE org_id = $1 AND time > now() - interval '1 day'
ORDER BY monitor_id, region, time DESC;
-- name: ListResults :many -- name: ListResults :many
-- A monitor's results newest first, a page from a keyset cursor (see -- A monitor's results newest first, a page from a keyset cursor (see
-- paging.go) whose string key is region and checker. -- paging.go) whose string key is region and checker.
@@ -49,6 +42,7 @@ SELECT monitor_id, bucket::timestamptz AS bucket, sum(total)::bigint AS total, s
coalesce(sum(avg_latency_ms * total) / nullif(sum(total), 0), 0)::real AS avg_latency_ms coalesce(sum(avg_latency_ms * total) / nullif(sum(total), 0), 0)::real AS avg_latency_ms
FROM check_results_1h FROM check_results_1h
WHERE org_id = $1 AND bucket >= $2 WHERE org_id = $1 AND bucket >= $2
AND (sqlc.narg(ids)::uuid[] IS NULL OR monitor_id = ANY (sqlc.narg(ids)::uuid[]))
GROUP BY monitor_id, bucket GROUP BY monitor_id, bucket
ORDER BY monitor_id, bucket; ORDER BY monitor_id, bucket;
@@ -73,7 +67,7 @@ SELECT monitor_id, time_bucket(sqlc.arg(width)::text::interval, time)::timestamp
coalesce(avg(latency_ms), 0)::real AS avg_latency_ms coalesce(avg(latency_ms), 0)::real AS avg_latency_ms
FROM check_results FROM check_results
WHERE org_id = $1 AND time >= sqlc.arg(since) WHERE org_id = $1 AND time >= sqlc.arg(since)
AND (sqlc.narg(monitor_id)::uuid IS NULL OR monitor_id = sqlc.narg(monitor_id)) AND monitor_id = ANY (sqlc.arg(ids)::uuid[])
GROUP BY 1, 2 GROUP BY 1, 2
ORDER BY 1, 2; ORDER BY 1, 2;
@@ -84,7 +78,7 @@ SELECT monitor_id, time_bucket(sqlc.arg(width)::text::interval, bucket)::timesta
coalesce(sum(avg_latency_ms * total) / nullif(sum(total), 0), 0)::real AS avg_latency_ms coalesce(sum(avg_latency_ms * total) / nullif(sum(total), 0), 0)::real AS avg_latency_ms
FROM check_results_1h FROM check_results_1h
WHERE org_id = $1 AND bucket >= sqlc.arg(since) WHERE org_id = $1 AND bucket >= sqlc.arg(since)
AND (sqlc.narg(monitor_id)::uuid IS NULL OR monitor_id = sqlc.narg(monitor_id)) AND monitor_id = ANY (sqlc.arg(ids)::uuid[])
GROUP BY 1, 2 GROUP BY 1, 2
ORDER BY 1, 2; ORDER BY 1, 2;
@@ -95,7 +89,7 @@ SELECT monitor_id, time_bucket(sqlc.arg(width)::text::interval, bucket)::timesta
coalesce(sum(avg_latency_ms * total) / nullif(sum(total), 0), 0)::real AS avg_latency_ms coalesce(sum(avg_latency_ms * total) / nullif(sum(total), 0), 0)::real AS avg_latency_ms
FROM check_results_1d FROM check_results_1d
WHERE org_id = $1 AND bucket >= sqlc.arg(since) WHERE org_id = $1 AND bucket >= sqlc.arg(since)
AND (sqlc.narg(monitor_id)::uuid IS NULL OR monitor_id = sqlc.narg(monitor_id)) AND monitor_id = ANY (sqlc.arg(ids)::uuid[])
GROUP BY 1, 2 GROUP BY 1, 2
ORDER BY 1, 2; ORDER BY 1, 2;
@@ -125,18 +119,35 @@ GROUP BY 1, 2
ORDER BY 1, 2; ORDER BY 1, 2;
-- name: FirstDataDaily :many -- name: FirstDataDaily :many
-- When each monitor and region first reported, to the day. -- When each region of a monitor first reported, to the day.
SELECT monitor_id, region, min(bucket)::timestamptz AS first SELECT monitor_id, region, min(bucket)::timestamptz AS first
FROM check_results_1d FROM check_results_1d
WHERE org_id = $1 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 monitor and region first reported since $2, exactly. Used for -- When each region of a monitor first reported since $3, exactly. Used for
-- data younger than the daily aggregate's resolution. -- data younger than the daily aggregate's resolution.
SELECT monitor_id, region, min(time)::timestamptz AS first SELECT monitor_id, region, min(time)::timestamptz AS first
FROM check_results FROM check_results
WHERE org_id = $1 AND time >= $2 WHERE org_id = $1 AND monitor_id = $2 AND time >= $3
GROUP BY 1, 2; GROUP BY 1, 2;
-- name: ResultsByChecker :many -- name: ResultsByChecker :many
+3 -3
View File
@@ -84,7 +84,7 @@ SELECT * FROM notification_channels ORDER BY name;
DELETE FROM notification_channels WHERE id = $1; DELETE FROM notification_channels WHERE id = $1;
-- name: OpenIncidents :many -- name: OpenIncidents :many
SELECT * FROM incidents WHERE resolved_at IS NULL; SELECT * FROM incidents WHERE org_id = $1 AND resolved_at IS NULL;
-- name: IncidentsForMonitors :many -- name: IncidentsForMonitors :many
SELECT * FROM incidents SELECT * FROM incidents
@@ -93,9 +93,9 @@ ORDER BY started_at DESC
LIMIT 50; LIMIT 50;
-- name: IncidentsSince :many -- name: IncidentsSince :many
-- Incidents overlapping the time since $1, for SLA calculation. -- Incidents overlapping the time since $2, for SLA calculation.
SELECT monitor_id, started_at, resolved_at FROM incidents SELECT monitor_id, started_at, resolved_at FROM incidents
WHERE resolved_at IS NULL OR resolved_at > $1; WHERE org_id = $1 AND (resolved_at IS NULL OR resolved_at > $2);
-- name: GetIncident :one -- name: GetIncident :one
SELECT i.*, m.name AS monitor_name, m.group_id AS monitor_group_id SELECT i.*, m.name AS monitor_name, m.group_id AS monitor_group_id
+27
View File
@@ -0,0 +1,27 @@
-- latest_results holds the newest check result per monitor and region
-- (see migration 00055) and has row-level security.
-- name: UpsertLatestResults :exec
-- Keeps the newest of rows, a JSON array of results, per monitor and
-- region; results arriving late do not replace newer ones.
INSERT INTO latest_results (monitor_id, region, org_id, time, ok, latency_ms, status_code, error)
SELECT DISTINCT ON (r.monitor_id, r.region) r.monitor_id, r.region, r.org_id, r.time, r.ok, r.latency_ms, r.status_code, r.error
FROM jsonb_to_recordset(sqlc.arg(rows)::jsonb)
AS r(monitor_id uuid, region text, org_id uuid, time timestamptz, ok boolean, latency_ms integer, status_code integer, error text)
ORDER BY r.monitor_id, r.region, r.time DESC
ON CONFLICT (monitor_id, region) DO UPDATE
SET org_id = excluded.org_id, time = excluded.time, ok = excluded.ok, latency_ms = excluded.latency_ms,
status_code = excluded.status_code, error = excluded.error
WHERE latest_results.time <= excluded.time;
-- name: LatestResults :many
-- Newest result per monitor and region in the org, of the last day.
SELECT monitor_id, region, time, ok, latency_ms, status_code, error
FROM latest_results
WHERE org_id = $1 AND time > now() - interval '1 day';
-- name: LatestResultsForMonitors :many
-- LatestResults limited to the monitors ids.
SELECT monitor_id, region, time, ok, latency_ms, status_code, error
FROM latest_results
WHERE org_id = $1 AND monitor_id = ANY (sqlc.arg(ids)::uuid[]) AND time > now() - interval '1 day';
+6 -1
View File
@@ -9,9 +9,13 @@ SELECT count(*) FROM monitors WHERE org_id = $1;
-- name: CountStatusPages :one -- name: CountStatusPages :one
SELECT count(*) FROM status_pages WHERE org_id = $1; SELECT count(*) FROM status_pages WHERE org_id = $1;
-- name: CountStatusPageMonitors :one
SELECT count(*) FROM status_page_monitors WHERE page_id = $1;
-- name: SetOrgLimits :one -- 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)
WHERE id = sqlc.arg(id) WHERE id = sqlc.arg(id)
RETURNING id, slug; RETURNING id, slug;
@@ -25,6 +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,
(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,
+6 -2
View File
@@ -16,13 +16,14 @@ DELETE FROM monitors WHERE id = $1;
SELECT * FROM monitors WHERE id = $1; SELECT * FROM monitors WHERE id = $1;
-- name: ListMonitors :many -- name: ListMonitors :many
SELECT * FROM monitors ORDER BY name; -- The org filter, though row security implies it, lets the index be used.
SELECT * FROM monitors WHERE org_id = $1 ORDER BY name;
-- name: MonitorRegions :many -- name: MonitorRegions :many
SELECT region_id FROM monitor_regions WHERE monitor_id = $1 ORDER BY region_id; SELECT region_id FROM monitor_regions WHERE monitor_id = $1 ORDER BY region_id;
-- name: AllMonitorRegions :many -- name: AllMonitorRegions :many
SELECT monitor_id, region_id FROM monitor_regions; SELECT monitor_id, region_id FROM monitor_regions WHERE org_id = $1;
-- name: DeleteMonitorRegions :exec -- name: DeleteMonitorRegions :exec
DELETE FROM monitor_regions WHERE monitor_id = $1; DELETE FROM monitor_regions WHERE monitor_id = $1;
@@ -72,3 +73,6 @@ ORDER BY
CASE WHEN sqlc.narg(before_s)::text IS NULL THEN id END, CASE WHEN sqlc.narg(before_s)::text IS NULL THEN id END,
name DESC, id DESC name DESC, id DESC
LIMIT sqlc.arg(max_rows); LIMIT sqlc.arg(max_rows);
-- name: SetMonitorPosition :execrows
UPDATE monitors SET position = sqlc.arg(position) WHERE id = sqlc.arg(id);
+66 -4
View File
@@ -16,16 +16,63 @@ WHERE id = $1
RETURNING *; RETURNING *;
-- name: SetStatusPageDomain :one -- name: SetStatusPageDomain :one
-- Changing the domain drops a previous verification. -- Changing the domain drops a previous verification and its checks.
UPDATE status_pages SET UPDATE status_pages SET
custom_domain = sqlc.narg(custom_domain),
domain_verified_at = CASE WHEN custom_domain IS NOT DISTINCT FROM sqlc.narg(custom_domain) THEN domain_verified_at END, domain_verified_at = CASE WHEN custom_domain IS NOT DISTINCT FROM sqlc.narg(custom_domain) THEN domain_verified_at END,
domain_verify_method = CASE WHEN custom_domain IS NOT DISTINCT FROM sqlc.narg(custom_domain) THEN domain_verify_method END,
domain_failing_since = CASE WHEN custom_domain IS NOT DISTINCT FROM sqlc.narg(custom_domain) THEN domain_failing_since END,
domain_checked_at = CASE WHEN custom_domain IS NOT DISTINCT FROM sqlc.narg(custom_domain) THEN domain_checked_at END,
domain_set_at = CASE WHEN custom_domain IS NOT DISTINCT FROM sqlc.narg(custom_domain) THEN domain_set_at ELSE now() END,
custom_domain = sqlc.narg(custom_domain),
updated_at = now() updated_at = now()
WHERE id = sqlc.arg(id) WHERE id = sqlc.arg(id)
RETURNING *; RETURNING *;
-- name: MarkDomainVerified :exec -- name: MarkDomainVerified :exec
UPDATE status_pages SET domain_verified_at = now() WHERE id = $1; -- The domain's record was found: verified, or still in place.
UPDATE status_pages SET
domain_verified_at = coalesce(domain_verified_at, sqlc.arg(now)::timestamptz),
domain_verify_method = sqlc.arg(method)::text,
domain_checked_at = sqlc.arg(now)::timestamptz,
domain_failing_since = NULL
WHERE id = sqlc.arg(id);
-- name: MarkDomainUnconfirmed :one
-- The record of a domain was not found. Returns since when it has not
-- been, for a verified domain.
UPDATE status_pages SET
domain_checked_at = sqlc.arg(now)::timestamptz,
domain_failing_since = CASE WHEN domain_verified_at IS NULL THEN NULL
ELSE coalesce(domain_failing_since, sqlc.arg(now)::timestamptz) END
WHERE id = sqlc.arg(id)
RETURNING domain_failing_since;
-- name: UnverifyDomain :exec
-- A verified domain whose record stayed missing past the grace period.
UPDATE status_pages SET
domain_verified_at = NULL, domain_verify_method = NULL, domain_failing_since = NULL
WHERE id = $1;
-- name: DomainsToCheck :many
-- System scope: domains due for a look at their DNS records. A new one is
-- looked at every minute for a quarter of an hour, then every ten minutes
-- for two days, after which only the verify button tries again. A verified
-- one is checked daily, hourly once its record went missing.
SELECT id, org_id, title, custom_domain::text AS domain, domain_token,
domain_verified_at, domain_failing_since
FROM status_pages
WHERE custom_domain IS NOT NULL
AND (sqlc.narg(page_id)::uuid IS NULL OR id = sqlc.narg(page_id))
AND (
(domain_verified_at IS NULL AND domain_set_at > sqlc.arg(now)::timestamptz - interval '48 hours'
AND (domain_checked_at IS NULL OR domain_checked_at <= sqlc.arg(now)::timestamptz - CASE
WHEN domain_set_at > sqlc.arg(now)::timestamptz - interval '15 minutes' THEN interval '50 seconds'
ELSE interval '10 minutes' END))
OR (domain_verified_at IS NOT NULL AND domain_verify_method IS NOT NULL
AND (domain_checked_at IS NULL OR domain_checked_at <= sqlc.arg(now)::timestamptz - CASE
WHEN domain_failing_since IS NULL THEN interval '24 hours' ELSE interval '1 hour' END)))
ORDER BY domain_checked_at NULLS FIRST
LIMIT 500;
-- name: GetStatusPage :one -- name: GetStatusPage :one
SELECT * FROM status_pages WHERE id = $1; SELECT * FROM status_pages WHERE id = $1;
@@ -38,7 +85,8 @@ DELETE FROM status_pages WHERE id = $1;
-- name: StatusPageMonitors :many -- name: StatusPageMonitors :many
SELECT spm.monitor_id, spm.section, spm.group_id, spm.label, spm.position, SELECT spm.monitor_id, spm.section, spm.group_id, spm.label, spm.position,
m.name AS monitor_name, m.enabled, m.group_id AS monitor_group_id m.name AS monitor_name, m.enabled, m.group_id AS monitor_group_id,
m.type AS monitor_type, m.interval_seconds
FROM status_page_monitors spm FROM status_page_monitors spm
JOIN monitors m ON m.id = spm.monitor_id JOIN monitors m ON m.id = spm.monitor_id
WHERE spm.page_id = $1 WHERE spm.page_id = $1
@@ -93,3 +141,17 @@ WHERE published AND suspended_at IS NULL
AND NOT EXISTS (SELECT 1 FROM orgs o WHERE o.id = status_pages.org_id AND o.suspended_at IS NOT NULL) AND NOT EXISTS (SELECT 1 FROM orgs o WHERE o.id = status_pages.org_id AND o.suspended_at IS NOT NULL)
AND ((sqlc.narg(host)::citext IS NOT NULL AND custom_domain = sqlc.narg(host) AND domain_verified_at IS NOT NULL) AND ((sqlc.narg(host)::citext IS NOT NULL AND custom_domain = sqlc.narg(host) AND domain_verified_at IS NOT NULL)
OR (sqlc.narg(slug)::citext IS NOT NULL AND slug = sqlc.narg(slug))); OR (sqlc.narg(slug)::citext IS NOT NULL AND slug = sqlc.narg(slug)));
-- name: ServablePages :many
-- System scope: the published pages a status page server serves, those
-- of agent_org for an organization's server; the platform's leave the
-- pages of organizations serving their own.
SELECT p.slug, COALESCE(CASE WHEN p.domain_verified_at IS NOT NULL THEN p.custom_domain END, '')::text AS host
FROM status_pages p
JOIN orgs o ON o.id = p.org_id
WHERE p.published AND p.suspended_at IS NULL AND o.suspended_at IS NULL
AND CASE WHEN sqlc.narg(agent_org)::uuid IS NULL
THEN NOT EXISTS (SELECT 1 FROM agents a WHERE a.org_id = p.org_id AND a.kind = 'statuspage' AND a.last_seen_at IS NOT NULL)
ELSE p.org_id = sqlc.narg(agent_org)::uuid
END
ORDER BY p.slug;
+97
View File
@@ -0,0 +1,97 @@
-- name: CreateSupportTicket :one
INSERT INTO support_tickets (user_id, org_id, subject, monitor_id, channel_id, alert_group_id, status_page_id, incident_id)
VALUES ($1, $2, $3, $4, $5, $6, $7, $8)
RETURNING *;
-- name: SupportReferencesExist :one
-- Whether everything a new ticket points at belongs to org; run in the
-- organization's scope so only what the account may see counts.
SELECT (sqlc.narg(monitor_id)::uuid IS NULL OR EXISTS (SELECT 1 FROM monitors m WHERE m.id = sqlc.narg(monitor_id) AND m.org_id = sqlc.arg(org_id)::uuid))
AND (sqlc.narg(channel_id)::uuid IS NULL OR EXISTS (SELECT 1 FROM notification_channels c WHERE c.id = sqlc.narg(channel_id) AND c.org_id = sqlc.arg(org_id)::uuid))
AND (sqlc.narg(alert_group_id)::uuid IS NULL OR EXISTS (SELECT 1 FROM alert_groups g WHERE g.id = sqlc.narg(alert_group_id) AND g.org_id = sqlc.arg(org_id)::uuid))
AND (sqlc.narg(status_page_id)::uuid IS NULL OR EXISTS (SELECT 1 FROM status_pages p WHERE p.id = sqlc.narg(status_page_id) AND p.org_id = sqlc.arg(org_id)::uuid))
AND (sqlc.narg(incident_id)::uuid IS NULL OR EXISTS (SELECT 1 FROM incidents i WHERE i.id = sqlc.narg(incident_id) AND i.org_id = sqlc.arg(org_id)::uuid))
AS ok;
-- name: SupportTicketReferences :one
-- The names of what a ticket points at, for showing it.
SELECT o.name AS org_name, o.slug AS org_slug,
m.name AS monitor_name, m.type AS monitor_type,
ch.name AS channel_name, ch.type AS channel_type,
ag.name AS alert_group_name,
sp.title AS status_page_title, sp.slug AS status_page_slug,
i.title AS incident_title, i.started_at AS incident_started_at, im.name AS incident_monitor
FROM support_tickets t
LEFT JOIN orgs o ON o.id = t.org_id
LEFT JOIN monitors m ON m.id = t.monitor_id
LEFT JOIN notification_channels ch ON ch.id = t.channel_id
LEFT JOIN alert_groups ag ON ag.id = t.alert_group_id
LEFT JOIN status_pages sp ON sp.id = t.status_page_id
LEFT JOIN incidents i ON i.id = t.incident_id
LEFT JOIN monitors im ON im.id = i.monitor_id
WHERE t.id = $1;
-- name: SupportOptionsMonitors :many
SELECT id, name FROM monitors WHERE org_id = $1 ORDER BY lower(name) LIMIT 500;
-- name: SupportOptionsChannels :many
SELECT id, name, type FROM notification_channels WHERE org_id = $1 ORDER BY lower(name) LIMIT 500;
-- name: SupportOptionsAlertGroups :many
SELECT id, name FROM alert_groups WHERE org_id = $1 ORDER BY lower(name) LIMIT 500;
-- name: SupportOptionsStatusPages :many
SELECT id, title FROM status_pages WHERE org_id = $1 ORDER BY lower(title) LIMIT 500;
-- name: SupportOptionsIncidents :many
SELECT i.id, i.title, i.started_at, m.name AS monitor_name
FROM incidents i JOIN monitors m ON m.id = i.monitor_id
WHERE i.org_id = $1 ORDER BY i.started_at DESC LIMIT 50;
-- name: AddSupportMessage :one
INSERT INTO support_messages (ticket_id, author_id, from_staff, body) VALUES ($1, $2, $3, $4)
RETURNING *;
-- name: SetSupportTicketStatus :execrows
UPDATE support_tickets SET status = $2, updated_at = now() WHERE id = $1;
-- name: GetSupportTicket :one
SELECT t.*, u.email AS user_email, o.name AS org_name
FROM support_tickets t
JOIN users u ON u.id = t.user_id
LEFT JOIN orgs o ON o.id = t.org_id
WHERE t.id = $1;
-- name: ListUserSupportTickets :many
-- The tickets row-level security lets the account see, newest activity
-- first.
SELECT * FROM support_tickets WHERE user_id = $1 ORDER BY updated_at DESC LIMIT 200;
-- name: ListSupportTickets :many
-- Every account's tickets for the admins, those waiting for them first.
SELECT t.*, u.email AS user_email, o.name AS org_name
FROM support_tickets t
JOIN users u ON u.id = t.user_id
LEFT JOIN orgs o ON o.id = t.org_id
WHERE sqlc.narg(status)::text IS NULL OR t.status = sqlc.narg(status)::text
ORDER BY t.status = 'open' DESC, t.updated_at DESC
LIMIT 200;
-- name: SupportMessages :many
SELECT m.*, coalesce(u.email, '')::text AS author_email
FROM support_messages m
LEFT JOIN users u ON u.id = m.author_id
WHERE m.ticket_id = $1
ORDER BY m.created_at, m.id;
-- name: AdminEmails :many
SELECT email FROM users WHERE is_admin AND disabled_at IS NULL ORDER BY email;
-- name: CountOpenSupportTickets :one
SELECT count(*) FROM support_tickets WHERE user_id = $1 AND status <> 'closed';
-- name: CountSupportTicketsSince :one
SELECT count(*) FROM support_tickets WHERE user_id = $1 AND created_at >= $2;
-- name: SupportTicketStatus :one
SELECT status FROM support_tickets WHERE id = $1;
+207 -21
View File
@@ -7,6 +7,7 @@ package store
import ( import (
"context" "context"
"time"
"github.com/google/uuid" "github.com/google/uuid"
) )
@@ -60,7 +61,7 @@ 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)
VALUES ($1, $2, $3, $4, $5, $6, $7, $8) VALUES ($1, $2, $3, $4, $5, $6, $7, $8)
RETURNING id, org_id, slug, title, description, published, custom_domain, domain_token, domain_verified_at, theme, created_at, updated_at, show_component_details, suspended_at, suspended_reason 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
` `
type CreateStatusPageParams struct { type CreateStatusPageParams struct {
@@ -102,6 +103,10 @@ func (q *Queries) CreateStatusPage(ctx context.Context, arg CreateStatusPagePara
&i.ShowComponentDetails, &i.ShowComponentDetails,
&i.SuspendedAt, &i.SuspendedAt,
&i.SuspendedReason, &i.SuspendedReason,
&i.DomainSetAt,
&i.DomainCheckedAt,
&i.DomainFailingSince,
&i.DomainVerifyMethod,
) )
return i, err return i, err
} }
@@ -171,8 +176,73 @@ func (q *Queries) DeleteStatusPageGroup(ctx context.Context, arg DeleteStatusPag
return result.RowsAffected(), nil return result.RowsAffected(), nil
} }
const domainsToCheck = `-- name: DomainsToCheck :many
SELECT id, org_id, title, custom_domain::text AS domain, domain_token,
domain_verified_at, domain_failing_since
FROM status_pages
WHERE custom_domain IS NOT NULL
AND ($1::uuid IS NULL OR id = $1)
AND (
(domain_verified_at IS NULL AND domain_set_at > $2::timestamptz - interval '48 hours'
AND (domain_checked_at IS NULL OR domain_checked_at <= $2::timestamptz - CASE
WHEN domain_set_at > $2::timestamptz - interval '15 minutes' THEN interval '50 seconds'
ELSE interval '10 minutes' END))
OR (domain_verified_at IS NOT NULL AND domain_verify_method IS NOT NULL
AND (domain_checked_at IS NULL OR domain_checked_at <= $2::timestamptz - CASE
WHEN domain_failing_since IS NULL THEN interval '24 hours' ELSE interval '1 hour' END)))
ORDER BY domain_checked_at NULLS FIRST
LIMIT 500
`
type DomainsToCheckParams struct {
PageID *uuid.UUID
Now time.Time
}
type DomainsToCheckRow struct {
ID uuid.UUID
OrgID uuid.UUID
Title string
Domain string
DomainToken string
DomainVerifiedAt *time.Time
DomainFailingSince *time.Time
}
// System scope: domains due for a look at their DNS records. A new one is
// looked at every minute for a quarter of an hour, then every ten minutes
// for two days, after which only the verify button tries again. A verified
// one is checked daily, hourly once its record went missing.
func (q *Queries) DomainsToCheck(ctx context.Context, arg DomainsToCheckParams) ([]DomainsToCheckRow, error) {
rows, err := q.db.Query(ctx, domainsToCheck, arg.PageID, arg.Now)
if err != nil {
return nil, err
}
defer rows.Close()
items := []DomainsToCheckRow{}
for rows.Next() {
var i DomainsToCheckRow
if err := rows.Scan(
&i.ID,
&i.OrgID,
&i.Title,
&i.Domain,
&i.DomainToken,
&i.DomainVerifiedAt,
&i.DomainFailingSince,
); err != nil {
return nil, err
}
items = append(items, i)
}
if err := rows.Err(); err != nil {
return nil, err
}
return items, nil
}
const findPublishedPage = `-- name: FindPublishedPage :one const findPublishedPage = `-- name: FindPublishedPage :one
SELECT id, org_id, slug, title, description, published, custom_domain, domain_token, domain_verified_at, theme, created_at, updated_at, show_component_details, suspended_at, suspended_reason FROM status_pages SELECT id, org_id, slug, title, description, published, custom_domain, domain_token, domain_verified_at, theme, created_at, updated_at, show_component_details, suspended_at, suspended_reason, domain_set_at, domain_checked_at, domain_failing_since, domain_verify_method 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)
@@ -205,12 +275,16 @@ func (q *Queries) FindPublishedPage(ctx context.Context, arg FindPublishedPagePa
&i.ShowComponentDetails, &i.ShowComponentDetails,
&i.SuspendedAt, &i.SuspendedAt,
&i.SuspendedReason, &i.SuspendedReason,
&i.DomainSetAt,
&i.DomainCheckedAt,
&i.DomainFailingSince,
&i.DomainVerifyMethod,
) )
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 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 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) {
@@ -232,6 +306,10 @@ func (q *Queries) GetStatusPage(ctx context.Context, id uuid.UUID) (StatusPage,
&i.ShowComponentDetails, &i.ShowComponentDetails,
&i.SuspendedAt, &i.SuspendedAt,
&i.SuspendedReason, &i.SuspendedReason,
&i.DomainSetAt,
&i.DomainCheckedAt,
&i.DomainFailingSince,
&i.DomainVerifyMethod,
) )
return i, err return i, err
} }
@@ -272,7 +350,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 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 FROM status_pages ORDER BY title
` `
func (q *Queries) ListStatusPages(ctx context.Context) ([]StatusPage, error) { func (q *Queries) ListStatusPages(ctx context.Context) ([]StatusPage, error) {
@@ -300,6 +378,10 @@ func (q *Queries) ListStatusPages(ctx context.Context) ([]StatusPage, error) {
&i.ShowComponentDetails, &i.ShowComponentDetails,
&i.SuspendedAt, &i.SuspendedAt,
&i.SuspendedReason, &i.SuspendedReason,
&i.DomainSetAt,
&i.DomainCheckedAt,
&i.DomainFailingSince,
&i.DomainVerifyMethod,
); err != nil { ); err != nil {
return nil, err return nil, err
} }
@@ -311,12 +393,47 @@ func (q *Queries) ListStatusPages(ctx context.Context) ([]StatusPage, error) {
return items, nil return items, nil
} }
const markDomainVerified = `-- name: MarkDomainVerified :exec const markDomainUnconfirmed = `-- name: MarkDomainUnconfirmed :one
UPDATE status_pages SET domain_verified_at = now() WHERE id = $1 UPDATE status_pages SET
domain_checked_at = $1::timestamptz,
domain_failing_since = CASE WHEN domain_verified_at IS NULL THEN NULL
ELSE coalesce(domain_failing_since, $1::timestamptz) END
WHERE id = $2
RETURNING domain_failing_since
` `
func (q *Queries) MarkDomainVerified(ctx context.Context, id uuid.UUID) error { type MarkDomainUnconfirmedParams struct {
_, err := q.db.Exec(ctx, markDomainVerified, id) Now time.Time
ID uuid.UUID
}
// The record of a domain was not found. Returns since when it has not
// been, for a verified domain.
func (q *Queries) MarkDomainUnconfirmed(ctx context.Context, arg MarkDomainUnconfirmedParams) (*time.Time, error) {
row := q.db.QueryRow(ctx, markDomainUnconfirmed, arg.Now, arg.ID)
var domain_failing_since *time.Time
err := row.Scan(&domain_failing_since)
return domain_failing_since, err
}
const markDomainVerified = `-- name: MarkDomainVerified :exec
UPDATE status_pages SET
domain_verified_at = coalesce(domain_verified_at, $1::timestamptz),
domain_verify_method = $2::text,
domain_checked_at = $1::timestamptz,
domain_failing_since = NULL
WHERE id = $3
`
type MarkDomainVerifiedParams struct {
Now time.Time
Method string
ID uuid.UUID
}
// The domain's record was found: verified, or still in place.
func (q *Queries) MarkDomainVerified(ctx context.Context, arg MarkDomainVerifiedParams) error {
_, err := q.db.Exec(ctx, markDomainVerified, arg.Now, arg.Method, arg.ID)
return err return err
} }
@@ -352,13 +469,57 @@ func (q *Queries) ReparentStatusPageGroupMonitors(ctx context.Context, arg Repar
return err return err
} }
const servablePages = `-- name: ServablePages :many
SELECT p.slug, COALESCE(CASE WHEN p.domain_verified_at IS NOT NULL THEN p.custom_domain END, '')::text AS host
FROM status_pages p
JOIN orgs o ON o.id = p.org_id
WHERE p.published AND p.suspended_at IS NULL AND o.suspended_at IS NULL
AND CASE WHEN $1::uuid IS NULL
THEN NOT EXISTS (SELECT 1 FROM agents a WHERE a.org_id = p.org_id AND a.kind = 'statuspage' AND a.last_seen_at IS NOT NULL)
ELSE p.org_id = $1::uuid
END
ORDER BY p.slug
`
type ServablePagesRow struct {
Slug string
Host string
}
// System scope: the published pages a status page server serves, those
// of agent_org for an organization's server; the platform's leave the
// pages of organizations serving their own.
func (q *Queries) ServablePages(ctx context.Context, agentOrg *uuid.UUID) ([]ServablePagesRow, error) {
rows, err := q.db.Query(ctx, servablePages, agentOrg)
if err != nil {
return nil, err
}
defer rows.Close()
items := []ServablePagesRow{}
for rows.Next() {
var i ServablePagesRow
if err := rows.Scan(&i.Slug, &i.Host); err != nil {
return nil, err
}
items = append(items, i)
}
if err := rows.Err(); err != nil {
return nil, err
}
return items, nil
}
const setStatusPageDomain = `-- name: SetStatusPageDomain :one const setStatusPageDomain = `-- name: SetStatusPageDomain :one
UPDATE status_pages SET UPDATE status_pages SET
custom_domain = $1,
domain_verified_at = CASE WHEN custom_domain IS NOT DISTINCT FROM $1 THEN domain_verified_at END, domain_verified_at = CASE WHEN custom_domain IS NOT DISTINCT FROM $1 THEN domain_verified_at END,
domain_verify_method = CASE WHEN custom_domain IS NOT DISTINCT FROM $1 THEN domain_verify_method END,
domain_failing_since = CASE WHEN custom_domain IS NOT DISTINCT FROM $1 THEN domain_failing_since END,
domain_checked_at = CASE WHEN custom_domain IS NOT DISTINCT FROM $1 THEN domain_checked_at END,
domain_set_at = CASE WHEN custom_domain IS NOT DISTINCT FROM $1 THEN domain_set_at ELSE now() END,
custom_domain = $1,
updated_at = now() 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 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
` `
type SetStatusPageDomainParams struct { type SetStatusPageDomainParams struct {
@@ -366,7 +527,7 @@ type SetStatusPageDomainParams struct {
ID uuid.UUID ID uuid.UUID
} }
// Changing the domain drops a previous verification. // Changing the domain drops a previous verification and its checks.
func (q *Queries) SetStatusPageDomain(ctx context.Context, arg SetStatusPageDomainParams) (StatusPage, error) { func (q *Queries) SetStatusPageDomain(ctx context.Context, arg SetStatusPageDomainParams) (StatusPage, error) {
row := q.db.QueryRow(ctx, setStatusPageDomain, arg.CustomDomain, arg.ID) row := q.db.QueryRow(ctx, setStatusPageDomain, arg.CustomDomain, arg.ID)
var i StatusPage var i StatusPage
@@ -386,6 +547,10 @@ func (q *Queries) SetStatusPageDomain(ctx context.Context, arg SetStatusPageDoma
&i.ShowComponentDetails, &i.ShowComponentDetails,
&i.SuspendedAt, &i.SuspendedAt,
&i.SuspendedReason, &i.SuspendedReason,
&i.DomainSetAt,
&i.DomainCheckedAt,
&i.DomainFailingSince,
&i.DomainVerifyMethod,
) )
return i, err return i, err
} }
@@ -414,7 +579,8 @@ func (q *Queries) SetStatusPageMonitorGroup(ctx context.Context, arg SetStatusPa
const statusPageMonitors = `-- name: StatusPageMonitors :many const statusPageMonitors = `-- name: StatusPageMonitors :many
SELECT spm.monitor_id, spm.section, spm.group_id, spm.label, spm.position, SELECT spm.monitor_id, spm.section, spm.group_id, spm.label, spm.position,
m.name AS monitor_name, m.enabled, m.group_id AS monitor_group_id m.name AS monitor_name, m.enabled, m.group_id AS monitor_group_id,
m.type AS monitor_type, m.interval_seconds
FROM status_page_monitors spm FROM status_page_monitors spm
JOIN monitors m ON m.id = spm.monitor_id JOIN monitors m ON m.id = spm.monitor_id
WHERE spm.page_id = $1 WHERE spm.page_id = $1
@@ -422,14 +588,16 @@ ORDER BY spm.position, m.name
` `
type StatusPageMonitorsRow struct { type StatusPageMonitorsRow struct {
MonitorID uuid.UUID MonitorID uuid.UUID
Section string Section string
GroupID *uuid.UUID GroupID *uuid.UUID
Label string Label string
Position int32 Position int32
MonitorName string MonitorName string
Enabled bool Enabled bool
MonitorGroupID *uuid.UUID MonitorGroupID *uuid.UUID
MonitorType string
IntervalSeconds int32
} }
func (q *Queries) StatusPageMonitors(ctx context.Context, pageID uuid.UUID) ([]StatusPageMonitorsRow, error) { func (q *Queries) StatusPageMonitors(ctx context.Context, pageID uuid.UUID) ([]StatusPageMonitorsRow, error) {
@@ -450,6 +618,8 @@ func (q *Queries) StatusPageMonitors(ctx context.Context, pageID uuid.UUID) ([]S
&i.MonitorName, &i.MonitorName,
&i.Enabled, &i.Enabled,
&i.MonitorGroupID, &i.MonitorGroupID,
&i.MonitorType,
&i.IntervalSeconds,
); err != nil { ); err != nil {
return nil, err return nil, err
} }
@@ -461,6 +631,18 @@ func (q *Queries) StatusPageMonitors(ctx context.Context, pageID uuid.UUID) ([]S
return items, nil return items, nil
} }
const unverifyDomain = `-- name: UnverifyDomain :exec
UPDATE status_pages SET
domain_verified_at = NULL, domain_verify_method = NULL, domain_failing_since = NULL
WHERE id = $1
`
// A verified domain whose record stayed missing past the grace period.
func (q *Queries) UnverifyDomain(ctx context.Context, id uuid.UUID) error {
_, err := q.db.Exec(ctx, unverifyDomain, id)
return err
}
const updateStatusPage = `-- name: UpdateStatusPage :one const updateStatusPage = `-- name: UpdateStatusPage :one
UPDATE status_pages UPDATE status_pages
SET slug = $2, SET slug = $2,
@@ -471,7 +653,7 @@ SET slug = $2,
theme = $7, theme = $7,
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 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
` `
type UpdateStatusPageParams struct { type UpdateStatusPageParams struct {
@@ -511,6 +693,10 @@ func (q *Queries) UpdateStatusPage(ctx context.Context, arg UpdateStatusPagePara
&i.ShowComponentDetails, &i.ShowComponentDetails,
&i.SuspendedAt, &i.SuspendedAt,
&i.SuspendedReason, &i.SuspendedReason,
&i.DomainSetAt,
&i.DomainCheckedAt,
&i.DomainFailingSince,
&i.DomainVerifyMethod,
) )
return i, err return i, err
} }
+607
View File
@@ -0,0 +1,607 @@
// Code generated by sqlc. DO NOT EDIT.
// versions:
// sqlc v1.31.1
// source: support.sql
package store
import (
"context"
"time"
"github.com/google/uuid"
)
const addSupportMessage = `-- name: AddSupportMessage :one
INSERT INTO support_messages (ticket_id, author_id, from_staff, body) VALUES ($1, $2, $3, $4)
RETURNING id, ticket_id, author_id, from_staff, body, created_at
`
type AddSupportMessageParams struct {
TicketID uuid.UUID
AuthorID *uuid.UUID
FromStaff bool
Body string
}
func (q *Queries) AddSupportMessage(ctx context.Context, arg AddSupportMessageParams) (SupportMessage, error) {
row := q.db.QueryRow(ctx, addSupportMessage,
arg.TicketID,
arg.AuthorID,
arg.FromStaff,
arg.Body,
)
var i SupportMessage
err := row.Scan(
&i.ID,
&i.TicketID,
&i.AuthorID,
&i.FromStaff,
&i.Body,
&i.CreatedAt,
)
return i, err
}
const adminEmails = `-- name: AdminEmails :many
SELECT email FROM users WHERE is_admin AND disabled_at IS NULL ORDER BY email
`
func (q *Queries) AdminEmails(ctx context.Context) ([]string, error) {
rows, err := q.db.Query(ctx, adminEmails)
if err != nil {
return nil, err
}
defer rows.Close()
items := []string{}
for rows.Next() {
var email string
if err := rows.Scan(&email); err != nil {
return nil, err
}
items = append(items, email)
}
if err := rows.Err(); err != nil {
return nil, err
}
return items, nil
}
const countOpenSupportTickets = `-- name: CountOpenSupportTickets :one
SELECT count(*) FROM support_tickets WHERE user_id = $1 AND status <> 'closed'
`
func (q *Queries) CountOpenSupportTickets(ctx context.Context, userID uuid.UUID) (int64, error) {
row := q.db.QueryRow(ctx, countOpenSupportTickets, userID)
var count int64
err := row.Scan(&count)
return count, err
}
const countSupportTicketsSince = `-- name: CountSupportTicketsSince :one
SELECT count(*) FROM support_tickets WHERE user_id = $1 AND created_at >= $2
`
type CountSupportTicketsSinceParams struct {
UserID uuid.UUID
CreatedAt time.Time
}
func (q *Queries) CountSupportTicketsSince(ctx context.Context, arg CountSupportTicketsSinceParams) (int64, error) {
row := q.db.QueryRow(ctx, countSupportTicketsSince, arg.UserID, arg.CreatedAt)
var count int64
err := row.Scan(&count)
return count, err
}
const createSupportTicket = `-- name: CreateSupportTicket :one
INSERT INTO support_tickets (user_id, org_id, subject, monitor_id, channel_id, alert_group_id, status_page_id, incident_id)
VALUES ($1, $2, $3, $4, $5, $6, $7, $8)
RETURNING id, user_id, org_id, monitor_id, channel_id, alert_group_id, status_page_id, incident_id, subject, status, created_at, updated_at
`
type CreateSupportTicketParams struct {
UserID uuid.UUID
OrgID *uuid.UUID
Subject string
MonitorID *uuid.UUID
ChannelID *uuid.UUID
AlertGroupID *uuid.UUID
StatusPageID *uuid.UUID
IncidentID *uuid.UUID
}
func (q *Queries) CreateSupportTicket(ctx context.Context, arg CreateSupportTicketParams) (SupportTicket, error) {
row := q.db.QueryRow(ctx, createSupportTicket,
arg.UserID,
arg.OrgID,
arg.Subject,
arg.MonitorID,
arg.ChannelID,
arg.AlertGroupID,
arg.StatusPageID,
arg.IncidentID,
)
var i SupportTicket
err := row.Scan(
&i.ID,
&i.UserID,
&i.OrgID,
&i.MonitorID,
&i.ChannelID,
&i.AlertGroupID,
&i.StatusPageID,
&i.IncidentID,
&i.Subject,
&i.Status,
&i.CreatedAt,
&i.UpdatedAt,
)
return i, err
}
const getSupportTicket = `-- name: GetSupportTicket :one
SELECT t.id, t.user_id, t.org_id, t.monitor_id, t.channel_id, t.alert_group_id, t.status_page_id, t.incident_id, t.subject, t.status, t.created_at, t.updated_at, u.email AS user_email, o.name AS org_name
FROM support_tickets t
JOIN users u ON u.id = t.user_id
LEFT JOIN orgs o ON o.id = t.org_id
WHERE t.id = $1
`
type GetSupportTicketRow struct {
ID uuid.UUID
UserID uuid.UUID
OrgID *uuid.UUID
MonitorID *uuid.UUID
ChannelID *uuid.UUID
AlertGroupID *uuid.UUID
StatusPageID *uuid.UUID
IncidentID *uuid.UUID
Subject string
Status string
CreatedAt time.Time
UpdatedAt time.Time
UserEmail string
OrgName *string
}
func (q *Queries) GetSupportTicket(ctx context.Context, id uuid.UUID) (GetSupportTicketRow, error) {
row := q.db.QueryRow(ctx, getSupportTicket, id)
var i GetSupportTicketRow
err := row.Scan(
&i.ID,
&i.UserID,
&i.OrgID,
&i.MonitorID,
&i.ChannelID,
&i.AlertGroupID,
&i.StatusPageID,
&i.IncidentID,
&i.Subject,
&i.Status,
&i.CreatedAt,
&i.UpdatedAt,
&i.UserEmail,
&i.OrgName,
)
return i, err
}
const listSupportTickets = `-- name: ListSupportTickets :many
SELECT t.id, t.user_id, t.org_id, t.monitor_id, t.channel_id, t.alert_group_id, t.status_page_id, t.incident_id, t.subject, t.status, t.created_at, t.updated_at, u.email AS user_email, o.name AS org_name
FROM support_tickets t
JOIN users u ON u.id = t.user_id
LEFT JOIN orgs o ON o.id = t.org_id
WHERE $1::text IS NULL OR t.status = $1::text
ORDER BY t.status = 'open' DESC, t.updated_at DESC
LIMIT 200
`
type ListSupportTicketsRow struct {
ID uuid.UUID
UserID uuid.UUID
OrgID *uuid.UUID
MonitorID *uuid.UUID
ChannelID *uuid.UUID
AlertGroupID *uuid.UUID
StatusPageID *uuid.UUID
IncidentID *uuid.UUID
Subject string
Status string
CreatedAt time.Time
UpdatedAt time.Time
UserEmail string
OrgName *string
}
// Every account's tickets for the admins, those waiting for them first.
func (q *Queries) ListSupportTickets(ctx context.Context, status *string) ([]ListSupportTicketsRow, error) {
rows, err := q.db.Query(ctx, listSupportTickets, status)
if err != nil {
return nil, err
}
defer rows.Close()
items := []ListSupportTicketsRow{}
for rows.Next() {
var i ListSupportTicketsRow
if err := rows.Scan(
&i.ID,
&i.UserID,
&i.OrgID,
&i.MonitorID,
&i.ChannelID,
&i.AlertGroupID,
&i.StatusPageID,
&i.IncidentID,
&i.Subject,
&i.Status,
&i.CreatedAt,
&i.UpdatedAt,
&i.UserEmail,
&i.OrgName,
); err != nil {
return nil, err
}
items = append(items, i)
}
if err := rows.Err(); err != nil {
return nil, err
}
return items, nil
}
const listUserSupportTickets = `-- name: ListUserSupportTickets :many
SELECT id, user_id, org_id, monitor_id, channel_id, alert_group_id, status_page_id, incident_id, subject, status, created_at, updated_at FROM support_tickets WHERE user_id = $1 ORDER BY updated_at DESC LIMIT 200
`
// The tickets row-level security lets the account see, newest activity
// first.
func (q *Queries) ListUserSupportTickets(ctx context.Context, userID uuid.UUID) ([]SupportTicket, error) {
rows, err := q.db.Query(ctx, listUserSupportTickets, userID)
if err != nil {
return nil, err
}
defer rows.Close()
items := []SupportTicket{}
for rows.Next() {
var i SupportTicket
if err := rows.Scan(
&i.ID,
&i.UserID,
&i.OrgID,
&i.MonitorID,
&i.ChannelID,
&i.AlertGroupID,
&i.StatusPageID,
&i.IncidentID,
&i.Subject,
&i.Status,
&i.CreatedAt,
&i.UpdatedAt,
); err != nil {
return nil, err
}
items = append(items, i)
}
if err := rows.Err(); err != nil {
return nil, err
}
return items, nil
}
const setSupportTicketStatus = `-- name: SetSupportTicketStatus :execrows
UPDATE support_tickets SET status = $2, updated_at = now() WHERE id = $1
`
type SetSupportTicketStatusParams struct {
ID uuid.UUID
Status string
}
func (q *Queries) SetSupportTicketStatus(ctx context.Context, arg SetSupportTicketStatusParams) (int64, error) {
result, err := q.db.Exec(ctx, setSupportTicketStatus, arg.ID, arg.Status)
if err != nil {
return 0, err
}
return result.RowsAffected(), nil
}
const supportMessages = `-- name: SupportMessages :many
SELECT m.id, m.ticket_id, m.author_id, m.from_staff, m.body, m.created_at, coalesce(u.email, '')::text AS author_email
FROM support_messages m
LEFT JOIN users u ON u.id = m.author_id
WHERE m.ticket_id = $1
ORDER BY m.created_at, m.id
`
type SupportMessagesRow struct {
ID uuid.UUID
TicketID uuid.UUID
AuthorID *uuid.UUID
FromStaff bool
Body string
CreatedAt time.Time
AuthorEmail string
}
func (q *Queries) SupportMessages(ctx context.Context, ticketID uuid.UUID) ([]SupportMessagesRow, error) {
rows, err := q.db.Query(ctx, supportMessages, ticketID)
if err != nil {
return nil, err
}
defer rows.Close()
items := []SupportMessagesRow{}
for rows.Next() {
var i SupportMessagesRow
if err := rows.Scan(
&i.ID,
&i.TicketID,
&i.AuthorID,
&i.FromStaff,
&i.Body,
&i.CreatedAt,
&i.AuthorEmail,
); err != nil {
return nil, err
}
items = append(items, i)
}
if err := rows.Err(); err != nil {
return nil, err
}
return items, nil
}
const supportOptionsAlertGroups = `-- name: SupportOptionsAlertGroups :many
SELECT id, name FROM alert_groups WHERE org_id = $1 ORDER BY lower(name) LIMIT 500
`
type SupportOptionsAlertGroupsRow struct {
ID uuid.UUID
Name string
}
func (q *Queries) SupportOptionsAlertGroups(ctx context.Context, orgID uuid.UUID) ([]SupportOptionsAlertGroupsRow, error) {
rows, err := q.db.Query(ctx, supportOptionsAlertGroups, orgID)
if err != nil {
return nil, err
}
defer rows.Close()
items := []SupportOptionsAlertGroupsRow{}
for rows.Next() {
var i SupportOptionsAlertGroupsRow
if err := rows.Scan(&i.ID, &i.Name); err != nil {
return nil, err
}
items = append(items, i)
}
if err := rows.Err(); err != nil {
return nil, err
}
return items, nil
}
const supportOptionsChannels = `-- name: SupportOptionsChannels :many
SELECT id, name, type FROM notification_channels WHERE org_id = $1 ORDER BY lower(name) LIMIT 500
`
type SupportOptionsChannelsRow struct {
ID uuid.UUID
Name string
Type string
}
func (q *Queries) SupportOptionsChannels(ctx context.Context, orgID uuid.UUID) ([]SupportOptionsChannelsRow, error) {
rows, err := q.db.Query(ctx, supportOptionsChannels, orgID)
if err != nil {
return nil, err
}
defer rows.Close()
items := []SupportOptionsChannelsRow{}
for rows.Next() {
var i SupportOptionsChannelsRow
if err := rows.Scan(&i.ID, &i.Name, &i.Type); err != nil {
return nil, err
}
items = append(items, i)
}
if err := rows.Err(); err != nil {
return nil, err
}
return items, nil
}
const supportOptionsIncidents = `-- name: SupportOptionsIncidents :many
SELECT i.id, i.title, i.started_at, m.name AS monitor_name
FROM incidents i JOIN monitors m ON m.id = i.monitor_id
WHERE i.org_id = $1 ORDER BY i.started_at DESC LIMIT 50
`
type SupportOptionsIncidentsRow struct {
ID uuid.UUID
Title string
StartedAt time.Time
MonitorName string
}
func (q *Queries) SupportOptionsIncidents(ctx context.Context, orgID uuid.UUID) ([]SupportOptionsIncidentsRow, error) {
rows, err := q.db.Query(ctx, supportOptionsIncidents, orgID)
if err != nil {
return nil, err
}
defer rows.Close()
items := []SupportOptionsIncidentsRow{}
for rows.Next() {
var i SupportOptionsIncidentsRow
if err := rows.Scan(
&i.ID,
&i.Title,
&i.StartedAt,
&i.MonitorName,
); err != nil {
return nil, err
}
items = append(items, i)
}
if err := rows.Err(); err != nil {
return nil, err
}
return items, nil
}
const supportOptionsMonitors = `-- name: SupportOptionsMonitors :many
SELECT id, name FROM monitors WHERE org_id = $1 ORDER BY lower(name) LIMIT 500
`
type SupportOptionsMonitorsRow struct {
ID uuid.UUID
Name string
}
func (q *Queries) SupportOptionsMonitors(ctx context.Context, orgID uuid.UUID) ([]SupportOptionsMonitorsRow, error) {
rows, err := q.db.Query(ctx, supportOptionsMonitors, orgID)
if err != nil {
return nil, err
}
defer rows.Close()
items := []SupportOptionsMonitorsRow{}
for rows.Next() {
var i SupportOptionsMonitorsRow
if err := rows.Scan(&i.ID, &i.Name); err != nil {
return nil, err
}
items = append(items, i)
}
if err := rows.Err(); err != nil {
return nil, err
}
return items, nil
}
const supportOptionsStatusPages = `-- name: SupportOptionsStatusPages :many
SELECT id, title FROM status_pages WHERE org_id = $1 ORDER BY lower(title) LIMIT 500
`
type SupportOptionsStatusPagesRow struct {
ID uuid.UUID
Title string
}
func (q *Queries) SupportOptionsStatusPages(ctx context.Context, orgID uuid.UUID) ([]SupportOptionsStatusPagesRow, error) {
rows, err := q.db.Query(ctx, supportOptionsStatusPages, orgID)
if err != nil {
return nil, err
}
defer rows.Close()
items := []SupportOptionsStatusPagesRow{}
for rows.Next() {
var i SupportOptionsStatusPagesRow
if err := rows.Scan(&i.ID, &i.Title); err != nil {
return nil, err
}
items = append(items, i)
}
if err := rows.Err(); err != nil {
return nil, err
}
return items, nil
}
const supportReferencesExist = `-- name: SupportReferencesExist :one
SELECT ($1::uuid IS NULL OR EXISTS (SELECT 1 FROM monitors m WHERE m.id = $1 AND m.org_id = $2::uuid))
AND ($3::uuid IS NULL OR EXISTS (SELECT 1 FROM notification_channels c WHERE c.id = $3 AND c.org_id = $2::uuid))
AND ($4::uuid IS NULL OR EXISTS (SELECT 1 FROM alert_groups g WHERE g.id = $4 AND g.org_id = $2::uuid))
AND ($5::uuid IS NULL OR EXISTS (SELECT 1 FROM status_pages p WHERE p.id = $5 AND p.org_id = $2::uuid))
AND ($6::uuid IS NULL OR EXISTS (SELECT 1 FROM incidents i WHERE i.id = $6 AND i.org_id = $2::uuid))
AS ok
`
type SupportReferencesExistParams struct {
MonitorID *uuid.UUID
OrgID uuid.UUID
ChannelID *uuid.UUID
AlertGroupID *uuid.UUID
StatusPageID *uuid.UUID
IncidentID *uuid.UUID
}
// Whether everything a new ticket points at belongs to org; run in the
// organization's scope so only what the account may see counts.
func (q *Queries) SupportReferencesExist(ctx context.Context, arg SupportReferencesExistParams) (*bool, error) {
row := q.db.QueryRow(ctx, supportReferencesExist,
arg.MonitorID,
arg.OrgID,
arg.ChannelID,
arg.AlertGroupID,
arg.StatusPageID,
arg.IncidentID,
)
var ok *bool
err := row.Scan(&ok)
return ok, err
}
const supportTicketReferences = `-- name: SupportTicketReferences :one
SELECT o.name AS org_name, o.slug AS org_slug,
m.name AS monitor_name, m.type AS monitor_type,
ch.name AS channel_name, ch.type AS channel_type,
ag.name AS alert_group_name,
sp.title AS status_page_title, sp.slug AS status_page_slug,
i.title AS incident_title, i.started_at AS incident_started_at, im.name AS incident_monitor
FROM support_tickets t
LEFT JOIN orgs o ON o.id = t.org_id
LEFT JOIN monitors m ON m.id = t.monitor_id
LEFT JOIN notification_channels ch ON ch.id = t.channel_id
LEFT JOIN alert_groups ag ON ag.id = t.alert_group_id
LEFT JOIN status_pages sp ON sp.id = t.status_page_id
LEFT JOIN incidents i ON i.id = t.incident_id
LEFT JOIN monitors im ON im.id = i.monitor_id
WHERE t.id = $1
`
type SupportTicketReferencesRow struct {
OrgName *string
OrgSlug *string
MonitorName *string
MonitorType *string
ChannelName *string
ChannelType *string
AlertGroupName *string
StatusPageTitle *string
StatusPageSlug *string
IncidentTitle *string
IncidentStartedAt *time.Time
IncidentMonitor *string
}
// The names of what a ticket points at, for showing it.
func (q *Queries) SupportTicketReferences(ctx context.Context, id uuid.UUID) (SupportTicketReferencesRow, error) {
row := q.db.QueryRow(ctx, supportTicketReferences, id)
var i SupportTicketReferencesRow
err := row.Scan(
&i.OrgName,
&i.OrgSlug,
&i.MonitorName,
&i.MonitorType,
&i.ChannelName,
&i.ChannelType,
&i.AlertGroupName,
&i.StatusPageTitle,
&i.StatusPageSlug,
&i.IncidentTitle,
&i.IncidentStartedAt,
&i.IncidentMonitor,
)
return i, err
}
const supportTicketStatus = `-- name: SupportTicketStatus :one
SELECT status FROM support_tickets WHERE id = $1
`
func (q *Queries) SupportTicketStatus(ctx context.Context, id uuid.UUID) (string, error) {
row := q.db.QueryRow(ctx, supportTicketStatus, id)
var status string
err := row.Scan(&status)
return status, err
}
+6
View File
@@ -14,6 +14,7 @@ type LimitsView struct {
RegionsPerMonitor int RegionsPerMonitor int
OwnRegionsCount bool OwnRegionsCount bool
OrgsPerAccount int OrgsPerAccount int
MonitorsPerPage int
} }
// OrgsView lists organizations for platform admins. // OrgsView lists organizations for platform admins.
@@ -36,6 +37,7 @@ type OrgRow struct {
StatusPagesOverride string StatusPagesOverride string
RegionsOverride string RegionsOverride string
OwnRegionsOverride string OwnRegionsOverride string
PerPageOverride string
Owner *ModeratedTarget Owner *ModeratedTarget
OwnerOrgs int OwnerOrgs int
OwnerOrgLimit string OwnerOrgLimit string
@@ -62,6 +64,7 @@ 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, "")
</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>
@@ -149,6 +152,7 @@ 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)
<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">
@@ -207,6 +211,8 @@ templ usageSection(u UsageView) {
<dd class="font-mono text-xs">@usage(u.StatusPages, u.Limits.StatusPages)</dd> <dd class="font-mono text-xs">@usage(u.StatusPages, u.Limits.StatusPages)</dd>
<dt>{ i18n.T(ctx, "limits.regions_per_monitor") }</dt> <dt>{ i18n.T(ctx, "limits.regions_per_monitor") }</dt>
<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>
<dd class="font-mono text-xs">{ limitText(ctx, u.Limits.MonitorsPerPage) }</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>
+87 -51
View File
@@ -23,6 +23,7 @@ type LimitsView struct {
RegionsPerMonitor int RegionsPerMonitor int
OwnRegionsCount bool OwnRegionsCount bool
OrgsPerAccount int OrgsPerAccount int
MonitorsPerPage int
} }
// OrgsView lists organizations for platform admins. // OrgsView lists organizations for platform admins.
@@ -45,6 +46,7 @@ type OrgRow struct {
StatusPagesOverride string StatusPagesOverride string
RegionsOverride string RegionsOverride string
OwnRegionsOverride string OwnRegionsOverride string
PerPageOverride string
Owner *ModeratedTarget Owner *ModeratedTarget
OwnerOrgs int OwnerOrgs int
OwnerOrgLimit string OwnerOrgLimit string
@@ -92,7 +94,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: 57, Col: 66} return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/admin_orgs.templ`, Line: 59, 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 {
@@ -126,6 +128,10 @@ 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)
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 5, "</div>") templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 5, "</div>")
if templ_7745c5c3_Err != nil { if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err return templ_7745c5c3_Err
@@ -141,7 +147,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: 67, Col: 89} return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/admin_orgs.templ`, Line: 70, 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 {
@@ -154,7 +160,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: 68, Col: 129} return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/admin_orgs.templ`, Line: 71, 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 {
@@ -194,7 +200,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: 77, Col: 90} return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/admin_orgs.templ`, Line: 80, 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 {
@@ -207,7 +213,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: 80, Col: 14} return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/admin_orgs.templ`, Line: 83, 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 {
@@ -220,7 +226,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: 84, Col: 26} return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/admin_orgs.templ`, Line: 87, 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 {
@@ -233,7 +239,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: 85, Col: 16} return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/admin_orgs.templ`, Line: 88, 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 {
@@ -246,7 +252,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: 86, Col: 76} return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/admin_orgs.templ`, Line: 89, 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 {
@@ -292,7 +298,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: 95, Col: 74} return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/admin_orgs.templ`, Line: 98, 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 {
@@ -305,7 +311,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: 100, Col: 20} return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/admin_orgs.templ`, Line: 103, 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 {
@@ -318,7 +324,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: 101, Col: 44} return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/admin_orgs.templ`, Line: 104, 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 {
@@ -331,7 +337,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: 102, Col: 43} return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/admin_orgs.templ`, Line: 105, 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 {
@@ -344,7 +350,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: 105, Col: 142} return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/admin_orgs.templ`, Line: 108, 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 {
@@ -362,7 +368,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: 108, Col: 59} return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/admin_orgs.templ`, Line: 111, 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 {
@@ -380,7 +386,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: 114, Col: 72} return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/admin_orgs.templ`, Line: 117, 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 {
@@ -393,7 +399,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: 115, Col: 74} return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/admin_orgs.templ`, Line: 118, 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 {
@@ -406,7 +412,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: 116, Col: 73} return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/admin_orgs.templ`, Line: 119, 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 {
@@ -419,7 +425,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: 117, Col: 77} return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/admin_orgs.templ`, Line: 120, 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 {
@@ -432,7 +438,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: 118, Col: 76} return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/admin_orgs.templ`, Line: 121, 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 {
@@ -450,7 +456,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: 125, Col: 17} return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/admin_orgs.templ`, Line: 128, 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 {
@@ -463,7 +469,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: 126, Col: 66} return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/admin_orgs.templ`, Line: 129, 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 {
@@ -489,7 +495,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: 131, Col: 48} return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/admin_orgs.templ`, Line: 134, 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 {
@@ -532,7 +538,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: 139, Col: 72} return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/admin_orgs.templ`, Line: 142, 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 {
@@ -545,7 +551,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: 144, Col: 96} return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/admin_orgs.templ`, Line: 147, 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 {
@@ -558,7 +564,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: 146, Col: 61} return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/admin_orgs.templ`, Line: 149, 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 {
@@ -571,7 +577,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: 146, Col: 102} return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/admin_orgs.templ`, Line: 149, 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 {
@@ -584,7 +590,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: 147, Col: 113} return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/admin_orgs.templ`, Line: 150, 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 {
@@ -610,6 +616,10 @@ 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)
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 45, "<label class=\"mb-3 block\"><span class=\"mb-1 block text-xs font-medium uppercase tracking-wider text-muted\">") templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 45, "<label class=\"mb-3 block\"><span class=\"mb-1 block text-xs font-medium uppercase tracking-wider text-muted\">")
if templ_7745c5c3_Err != nil { if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err return templ_7745c5c3_Err
@@ -617,7 +627,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: 153, Col: 135} return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/admin_orgs.templ`, Line: 157, 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 {
@@ -640,7 +650,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: 155, Col: 187} return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/admin_orgs.templ`, Line: 159, 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 {
@@ -663,7 +673,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: 156, Col: 112} return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/admin_orgs.templ`, Line: 160, 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 {
@@ -686,7 +696,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: 157, Col: 115} return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/admin_orgs.templ`, Line: 161, 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 {
@@ -699,7 +709,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: 160, Col: 130} return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/admin_orgs.templ`, Line: 164, 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 {
@@ -721,7 +731,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: 164, Col: 84} return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/admin_orgs.templ`, Line: 168, 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 {
@@ -739,7 +749,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: 167, Col: 70} return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/admin_orgs.templ`, Line: 171, 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 {
@@ -752,7 +762,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: 167, Col: 111} return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/admin_orgs.templ`, Line: 171, 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 {
@@ -765,7 +775,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: 168, Col: 127} return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/admin_orgs.templ`, Line: 172, 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 {
@@ -790,7 +800,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: 171, Col: 132} return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/admin_orgs.templ`, Line: 175, 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 {
@@ -892,7 +902,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: 191, Col: 83} return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/admin_orgs.templ`, Line: 195, 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 {
@@ -905,7 +915,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: 191, Col: 109} return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/admin_orgs.templ`, Line: 195, 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 {
@@ -957,7 +967,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: 204, Col: 39} return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/admin_orgs.templ`, Line: 208, 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 {
@@ -978,7 +988,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: 206, Col: 43} return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/admin_orgs.templ`, Line: 210, 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 {
@@ -999,7 +1009,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: 208, Col: 50} return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/admin_orgs.templ`, Line: 212, 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 {
@@ -1012,36 +1022,62 @@ 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: 209, Col: 77} return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/admin_orgs.templ`, Line: 213, 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 {
return templ_7745c5c3_Err return templ_7745c5c3_Err
} }
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 81, "</dd></dl>") templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 81, "</dd><dt>")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
var templ_7745c5c3_Var51 string
templ_7745c5c3_Var51, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, "limits.monitors_per_page"))
if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/admin_orgs.templ`, Line: 214, Col: 48}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var51))
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 82, "</dt><dd class=\"font-mono text-xs\">")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
var templ_7745c5c3_Var52 string
templ_7745c5c3_Var52, templ_7745c5c3_Err = templ.JoinStringErrs(limitText(ctx, u.Limits.MonitorsPerPage))
if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/admin_orgs.templ`, Line: 215, Col: 75}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var52))
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 83, "</dd></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, 82, "<p class=\"mt-2 text-xs text-muted\">") templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 84, "<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_Var51 string var templ_7745c5c3_Var53 string
templ_7745c5c3_Var51, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, "limits.own_regions_free")) templ_7745c5c3_Var53, 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: 212, Col: 78} return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/admin_orgs.templ`, Line: 218, Col: 78}
} }
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var51)) _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var53))
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, "</p>") templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 85, "</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, 84, "</section>") templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 86, "</section>")
if templ_7745c5c3_Err != nil { if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err return templ_7745c5c3_Err
} }
+10
View File
@@ -108,3 +108,13 @@
filter: invert(0.92) hue-rotate(180deg); filter: invert(0.92) hue-rotate(180deg);
} }
} }
/* Outside any layer so it wins over text-sm and text-xs: iOS zooms into
form fields whose text is smaller than 16px. */
@media (pointer: coarse) {
input:not([type="checkbox"]):not([type="radio"]),
select,
textarea {
font-size: max(16px, 1em);
}
}
+91
View File
@@ -178,7 +178,75 @@
} }
}); });
// Saves the order of a list of monitors being arranged.
const saveOrder = async (list) => {
const ids = [...list.querySelectorAll(":scope > [data-sort-id]")].map((li) => li.dataset.sortId);
try {
await api.put(list.dataset.sortable, { monitor_ids: ids });
} catch (err) {
alert(message(err));
location.reload();
}
};
let dragged = null;
document.addEventListener("dragstart", (ev) => {
const item = ev.target.closest?.("[data-sortable] > [data-sort-id]");
if (!item) return;
dragged = item;
ev.dataTransfer.effectAllowed = "move";
item.style.opacity = "0.5";
});
document.addEventListener("dragover", (ev) => {
const over = ev.target.closest?.("[data-sortable] > [data-sort-id]");
if (!dragged || !over || over === dragged || over.parentElement !== dragged.parentElement) return;
ev.preventDefault();
const box = over.getBoundingClientRect();
if (ev.clientY < box.top + box.height / 2) over.before(dragged);
else over.after(dragged);
});
document.addEventListener("drop", (ev) => {
if (dragged) ev.preventDefault();
});
document.addEventListener("dragend", async () => {
if (!dragged) return;
const list = dragged.parentElement;
dragged.style.opacity = "";
dragged = null;
await saveOrder(list);
});
document.addEventListener("click", async (ev) => { document.addEventListener("click", async (ev) => {
const navToggle = ev.target.closest("[data-nav-toggle]");
if (navToggle) {
const nav = document.getElementById(navToggle.dataset.navToggle);
const open = nav?.classList.toggle("hidden") === false;
navToggle.setAttribute("aria-expanded", String(open));
return;
}
// Moves a monitor up or down while arranging the monitor list.
const move = ev.target.closest("[data-sort-move]");
if (move) {
const item = move.closest("[data-sort-id]");
const other = move.dataset.sortMove === "up" ? item.previousElementSibling : item.nextElementSibling;
if (!other) return;
if (move.dataset.sortMove === "up") other.before(item);
else other.after(item);
move.focus();
await saveOrder(item.closest("[data-sortable]"));
return;
}
// Ticks or clears every checkbox named by data-check-all in its form,
// of the rows a filter leaves visible.
const checkAll = ev.target.closest("[data-check-all]");
if (checkAll) {
const on = checkAll.dataset.checkAll === "on";
checkAll.closest("form")?.querySelectorAll(checkAll.dataset.checkTarget).forEach((box) => {
if (box.closest("[data-row]")?.hidden) return;
box.checked = on;
if (on) addRowFields(box);
});
return;
}
const locale = ev.target.closest("[data-locale]"); const locale = ev.target.closest("[data-locale]");
if (locale) { if (locale) {
await api.post("/locale", { locale: locale.dataset.locale }).catch(() => {}); await api.post("/locale", { locale: locale.dataset.locale }).catch(() => {});
@@ -261,6 +329,29 @@
} }
}); });
// A row of a long list may come without its fields until it is ticked;
// they are copied in from the form's template[data-row-fields].
function addRowFields(box) {
const row = box.closest("[data-row]");
const tpl = row?.closest("form")?.querySelector("template[data-row-fields]");
if (!tpl || row.querySelector("[data-row-extra]")) return;
row.append(tpl.content.cloneNode(true));
}
document.addEventListener("change", (ev) => {
if (ev.target.matches('[data-row] [data-field="include"]') && ev.target.checked) addRowFields(ev.target);
});
// [data-filter-rows] hides the rows of the list it names whose text does
// not contain what is typed.
document.addEventListener("input", (ev) => {
const input = ev.target.closest("[data-filter-rows]");
if (!input) return;
const needle = input.value.trim().toLowerCase();
for (const row of document.querySelectorAll(input.dataset.filterRows + " > [data-row]")) {
row.hidden = needle !== "" && !row.textContent.toLowerCase().includes(needle);
}
});
// Only the settings of the selected check type are shown and submitted. // Only the settings of the selected check type are shown and submitted.
document.addEventListener("change", (ev) => { document.addEventListener("change", (ev) => {
const sel = ev.target.closest("[data-type-select]"); const sel = ev.target.closest("[data-type-select]");
+13 -3
View File
@@ -78,7 +78,7 @@ type SignupConsent struct {
templ consentLinks(docs []LegalLink) { templ consentLinks(docs []LegalLink) {
for i, d := range docs { for i, d := range docs {
if i > 0 { if i > 0 {
{ i18n.T(ctx, "consent.and") } { " " + i18n.T(ctx, "consent.and") }
} }
<a href={ templ.SafeURL(d.Href) } target="_blank" rel="noopener" class="underline underline-offset-2">{ i18n.T(ctx, "consent.doc."+d.Kind) }</a> <a href={ templ.SafeURL(d.Href) } target="_blank" rel="noopener" class="underline underline-offset-2">{ i18n.T(ctx, "consent.doc."+d.Kind) }</a>
} }
@@ -222,7 +222,12 @@ templ ConsentPage(p Page, me Me, docs []LegalLink, versions, next string) {
</label> </label>
@submit(i18n.T(ctx, "consent.submit")) @submit(i18n.T(ctx, "consent.submit"))
</form> </form>
<p class="mt-6 text-sm"><button data-logout class="underline underline-offset-2">{ i18n.T(ctx, "console.nav.logout") }</button></p> <p class="mt-6 flex flex-wrap gap-x-4 text-sm">
if me.Support {
<a href="/support" class="underline underline-offset-2">{ i18n.T(ctx, "support.contact") }</a>
}
<button data-logout class="underline underline-offset-2">{ i18n.T(ctx, "console.nav.logout") }</button>
</p>
<div class="mt-12 border-t border-rule pt-6"> <div class="mt-12 border-t border-rule pt-6">
<p class="mb-6 text-sm text-muted">{ i18n.T(ctx, "consent.decline") }</p> <p class="mb-6 text-sm text-muted">{ i18n.T(ctx, "consent.decline") }</p>
@accountDataBody(me) @accountDataBody(me)
@@ -246,7 +251,12 @@ templ SuspendedPage(p Page, me Me, reason string) {
<p class="mb-6 border-l-2 border-down pl-3 text-sm">{ reason }</p> <p class="mb-6 border-l-2 border-down pl-3 text-sm">{ reason }</p>
} }
<p class="mb-6 text-sm text-muted">{ i18n.T(ctx, "suspended.options") }</p> <p class="mb-6 text-sm text-muted">{ i18n.T(ctx, "suspended.options") }</p>
<p class="mb-10 text-sm"><button data-logout class="underline underline-offset-2">{ i18n.T(ctx, "console.nav.logout") }</button></p> <p class="mb-10 flex flex-wrap gap-x-4 text-sm">
if me.Support {
<a href="/support" class="underline underline-offset-2">{ i18n.T(ctx, "support.contact") }</a>
}
<button data-logout class="underline underline-offset-2">{ i18n.T(ctx, "console.nav.logout") }</button>
</p>
@accountDataBody(me) @accountDataBody(me)
</main> </main>
} }
+106 -60
View File
@@ -356,9 +356,9 @@ func consentLinks(docs []LegalLink) templ.Component {
for i, d := range docs { for i, d := range docs {
if i > 0 { if i > 0 {
var templ_7745c5c3_Var17 string var templ_7745c5c3_Var17 string
templ_7745c5c3_Var17, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, "consent.and")) templ_7745c5c3_Var17, templ_7745c5c3_Err = templ.JoinStringErrs(" " + i18n.T(ctx, "consent.and"))
if templ_7745c5c3_Err != nil { if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/auth.templ`, Line: 81, Col: 31} return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/auth.templ`, Line: 81, Col: 37}
} }
_, 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 {
@@ -1292,33 +1292,56 @@ func ConsentPage(p Page, me Me, docs []LegalLink, versions, next string) templ.C
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, "</form><p class=\"mt-6 text-sm\"><button data-logout class=\"underline underline-offset-2\">") templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 85, "</form><p class=\"mt-6 flex flex-wrap gap-x-4 text-sm\">")
if templ_7745c5c3_Err != nil { if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err return templ_7745c5c3_Err
} }
var templ_7745c5c3_Var64 string if me.Support {
templ_7745c5c3_Var64, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, "console.nav.logout")) templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 86, "<a href=\"/support\" class=\"underline underline-offset-2\">")
if templ_7745c5c3_Err != nil { if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/auth.templ`, Line: 225, Col: 119} return templ_7745c5c3_Err
}
var templ_7745c5c3_Var64 string
templ_7745c5c3_Var64, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, "support.contact"))
if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/auth.templ`, Line: 227, Col: 93}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var64))
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 87, "</a> ")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
} }
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var64)) templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 88, "<button data-logout class=\"underline underline-offset-2\">")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 86, "</button></p><div class=\"mt-12 border-t border-rule pt-6\"><p class=\"mb-6 text-sm text-muted\">")
if templ_7745c5c3_Err != nil { if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err return templ_7745c5c3_Err
} }
var templ_7745c5c3_Var65 string var templ_7745c5c3_Var65 string
templ_7745c5c3_Var65, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, "consent.decline")) templ_7745c5c3_Var65, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, "console.nav.logout"))
if templ_7745c5c3_Err != nil { if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/auth.templ`, Line: 227, Col: 71} return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/auth.templ`, Line: 229, Col: 96}
} }
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var65)) _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var65))
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, 87, "</p>") templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 89, "</button></p><div class=\"mt-12 border-t border-rule pt-6\"><p class=\"mb-6 text-sm text-muted\">")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
var templ_7745c5c3_Var66 string
templ_7745c5c3_Var66, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, "consent.decline"))
if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/auth.templ`, Line: 232, Col: 71}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var66))
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 90, "</p>")
if templ_7745c5c3_Err != nil { if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err return templ_7745c5c3_Err
} }
@@ -1326,7 +1349,7 @@ func ConsentPage(p Page, me Me, docs []LegalLink, versions, next string) templ.C
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, 88, "</div></main>") templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 91, "</div></main>")
if templ_7745c5c3_Err != nil { if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err return templ_7745c5c3_Err
} }
@@ -1359,7 +1382,7 @@ func SuspendedPage(p Page, me Me, reason string) templ.Component {
} }
ctx = templ.InitializeContext(ctx) ctx = templ.InitializeContext(ctx)
ctx = templ.ClearChildren(ctx) ctx = templ.ClearChildren(ctx)
templ_7745c5c3_Var67 := templruntime.GeneratedTemplate(func(templ_7745c5c3_Input templruntime.GeneratedComponentInput) (templ_7745c5c3_Err error) { templ_7745c5c3_Var68 := templruntime.GeneratedTemplate(func(templ_7745c5c3_Input templruntime.GeneratedComponentInput) (templ_7745c5c3_Err error) {
templ_7745c5c3_W, ctx := templ_7745c5c3_Input.Writer, templ_7745c5c3_Input.Context templ_7745c5c3_W, ctx := templ_7745c5c3_Input.Writer, templ_7745c5c3_Input.Context
templ_7745c5c3_Buffer, templ_7745c5c3_IsBuffer := templruntime.GetBuffer(templ_7745c5c3_W) templ_7745c5c3_Buffer, templ_7745c5c3_IsBuffer := templruntime.GetBuffer(templ_7745c5c3_W)
if !templ_7745c5c3_IsBuffer { if !templ_7745c5c3_IsBuffer {
@@ -1371,7 +1394,7 @@ func SuspendedPage(p Page, me Me, reason string) templ.Component {
}() }()
} }
ctx = templ.InitializeContext(ctx) ctx = templ.InitializeContext(ctx)
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 89, "<main class=\"mx-auto mt-[8vh] w-full max-w-xl px-6 pb-16\"><div class=\"mb-10 flex items-center justify-between\">") templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 92, "<main class=\"mx-auto mt-[8vh] w-full max-w-xl px-6 pb-16\"><div class=\"mb-10 flex items-center justify-between\">")
if templ_7745c5c3_Err != nil { if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err return templ_7745c5c3_Err
} }
@@ -1383,82 +1406,105 @@ func SuspendedPage(p Page, me Me, reason string) templ.Component {
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, 90, "</div><h1 class=\"mb-4 text-xl font-semibold\">") templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 93, "</div><h1 class=\"mb-4 text-xl font-semibold\">")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
var templ_7745c5c3_Var68 string
templ_7745c5c3_Var68, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, p.TitleID))
if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/auth.templ`, Line: 243, Col: 66}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var68))
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 91, "</h1><p class=\"mb-2 text-sm\">")
if templ_7745c5c3_Err != nil { if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err return templ_7745c5c3_Err
} }
var templ_7745c5c3_Var69 string var templ_7745c5c3_Var69 string
templ_7745c5c3_Var69, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, "suspended.intro")) templ_7745c5c3_Var69, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, p.TitleID))
if templ_7745c5c3_Err != nil { if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/auth.templ`, Line: 244, Col: 59} return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/auth.templ`, Line: 248, Col: 66}
} }
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var69)) _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var69))
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, 92, "</p>") templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 94, "</h1><p class=\"mb-2 text-sm\">")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
var templ_7745c5c3_Var70 string
templ_7745c5c3_Var70, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, "suspended.intro"))
if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/auth.templ`, Line: 249, Col: 59}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var70))
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 95, "</p>")
if templ_7745c5c3_Err != nil { if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err return templ_7745c5c3_Err
} }
if reason != "" { if reason != "" {
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 93, "<p class=\"mb-6 border-l-2 border-down pl-3 text-sm\">") templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 96, "<p class=\"mb-6 border-l-2 border-down pl-3 text-sm\">")
if templ_7745c5c3_Err != nil { if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err return templ_7745c5c3_Err
} }
var templ_7745c5c3_Var70 string var templ_7745c5c3_Var71 string
templ_7745c5c3_Var70, templ_7745c5c3_Err = templ.JoinStringErrs(reason) templ_7745c5c3_Var71, templ_7745c5c3_Err = templ.JoinStringErrs(reason)
if templ_7745c5c3_Err != nil { if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/auth.templ`, Line: 246, Col: 64} return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/auth.templ`, Line: 251, Col: 64}
} }
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var70)) _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var71))
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, 94, "</p>") templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 97, "</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, 95, "<p class=\"mb-6 text-sm text-muted\">") templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 98, "<p class=\"mb-6 text-sm text-muted\">")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
var templ_7745c5c3_Var71 string
templ_7745c5c3_Var71, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, "suspended.options"))
if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/auth.templ`, Line: 248, Col: 72}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var71))
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 96, "</p><p class=\"mb-10 text-sm\"><button data-logout class=\"underline underline-offset-2\">")
if templ_7745c5c3_Err != nil { if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err return templ_7745c5c3_Err
} }
var templ_7745c5c3_Var72 string var templ_7745c5c3_Var72 string
templ_7745c5c3_Var72, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, "console.nav.logout")) templ_7745c5c3_Var72, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, "suspended.options"))
if templ_7745c5c3_Err != nil { if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/auth.templ`, Line: 249, Col: 120} return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/auth.templ`, Line: 253, Col: 72}
} }
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var72)) _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var72))
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, 97, "</button></p>") templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 99, "</p><p class=\"mb-10 flex flex-wrap gap-x-4 text-sm\">")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
if me.Support {
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 100, "<a href=\"/support\" class=\"underline underline-offset-2\">")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
var templ_7745c5c3_Var73 string
templ_7745c5c3_Var73, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, "support.contact"))
if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/auth.templ`, Line: 256, Col: 93}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var73))
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 101, "</a> ")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
}
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 102, "<button data-logout class=\"underline underline-offset-2\">")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
var templ_7745c5c3_Var74 string
templ_7745c5c3_Var74, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, "console.nav.logout"))
if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/auth.templ`, Line: 258, Col: 96}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var74))
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 103, "</button></p>")
if templ_7745c5c3_Err != nil { if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err return templ_7745c5c3_Err
} }
@@ -1466,13 +1512,13 @@ func SuspendedPage(p Page, me Me, reason string) templ.Component {
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, 98, "</main>") templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 104, "</main>")
if templ_7745c5c3_Err != nil { if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err return templ_7745c5c3_Err
} }
return nil return nil
}) })
templ_7745c5c3_Err = Layout(p).Render(templ.WithChildren(ctx, templ_7745c5c3_Var67), templ_7745c5c3_Buffer) templ_7745c5c3_Err = Layout(p).Render(templ.WithChildren(ctx, templ_7745c5c3_Var68), templ_7745c5c3_Buffer)
if templ_7745c5c3_Err != nil { if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err return templ_7745c5c3_Err
} }
+21 -19
View File
@@ -111,25 +111,27 @@ templ CheckerPage(p Page, me Me, v CheckerView) {
if len(v.Recent) == 0 { if len(v.Recent) == 0 {
<p class="text-sm text-muted">{ i18n.T(ctx, "checkers.no_recent") }</p> <p class="text-sm text-muted">{ i18n.T(ctx, "checkers.no_recent") }</p>
} else { } else {
<table class="w-full text-left text-sm"> <div class="overflow-x-auto">
<tbody class="divide-y divide-rule border-y border-rule"> <table class="w-full text-left text-sm">
for _, r := range v.Recent { <tbody class="divide-y divide-rule border-y border-rule">
<tr> for _, r := range v.Recent {
<td class="py-1.5 pr-4 font-mono text-xs whitespace-nowrap text-muted">{ r.Time }</td> <tr>
<td class="py-1.5 pr-4"><a href={ templ.SafeURL(r.MonitorURL) } class="hover:underline">{ r.Monitor }</a></td> <td class="py-1.5 pr-4 font-mono text-xs whitespace-nowrap text-muted">{ r.Time }</td>
<td class="py-1.5 pr-4"> <td class="py-1.5 pr-4"><a href={ templ.SafeURL(r.MonitorURL) } class="hover:underline">{ r.Monitor }</a></td>
if r.OK { <td class="py-1.5 pr-4">
<span class="text-up">●</span> if r.OK {
} else { <span class="text-up">●</span>
<span class="text-down">●</span> } else {
} <span class="text-down">●</span>
</td> }
<td class="py-1.5 pr-4 font-mono text-xs">{ r.Latency }</td> </td>
<td class="py-1.5 font-mono text-xs text-muted">{ r.Detail }</td> <td class="py-1.5 pr-4 font-mono text-xs">{ r.Latency }</td>
</tr> <td class="py-1.5 font-mono text-xs text-muted">{ r.Detail }</td>
} </tr>
</tbody> }
</table> </tbody>
</table>
</div>
} }
@pager(v.Pager, "newer", "older") @pager(v.Pager, "newer", "older")
</section> </section>
+15 -15
View File
@@ -380,7 +380,7 @@ func CheckerPage(p Page, me Me, v CheckerView) templ.Component {
return templ_7745c5c3_Err return templ_7745c5c3_Err
} }
} else { } else {
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 26, "<table class=\"w-full text-left text-sm\"><tbody class=\"divide-y divide-rule border-y border-rule\">") templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 26, "<div class=\"overflow-x-auto\"><table class=\"w-full text-left text-sm\"><tbody class=\"divide-y divide-rule border-y border-rule\">")
if templ_7745c5c3_Err != nil { if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err return templ_7745c5c3_Err
} }
@@ -392,7 +392,7 @@ func CheckerPage(p Page, me Me, v CheckerView) templ.Component {
var templ_7745c5c3_Var17 string var templ_7745c5c3_Var17 string
templ_7745c5c3_Var17, templ_7745c5c3_Err = templ.JoinStringErrs(r.Time) templ_7745c5c3_Var17, templ_7745c5c3_Err = templ.JoinStringErrs(r.Time)
if templ_7745c5c3_Err != nil { if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/checkers.templ`, Line: 118, Col: 87} return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/checkers.templ`, Line: 119, Col: 88}
} }
_, 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 {
@@ -405,7 +405,7 @@ func CheckerPage(p Page, me Me, v CheckerView) templ.Component {
var templ_7745c5c3_Var18 string var templ_7745c5c3_Var18 string
templ_7745c5c3_Var18, templ_7745c5c3_Err = templruntime.NewAttributeExpression(templ.SafeURL(r.MonitorURL)).ResolveURL(ctx) templ_7745c5c3_Var18, templ_7745c5c3_Err = templruntime.NewAttributeExpression(templ.SafeURL(r.MonitorURL)).ResolveURL(ctx)
if templ_7745c5c3_Err != nil { if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/checkers.templ`, Line: 119, Col: 69} return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/checkers.templ`, Line: 120, Col: 70}
} }
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ_7745c5c3_Var18) _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ_7745c5c3_Var18)
if templ_7745c5c3_Err != nil { if templ_7745c5c3_Err != nil {
@@ -418,7 +418,7 @@ func CheckerPage(p Page, me Me, v CheckerView) templ.Component {
var templ_7745c5c3_Var19 string var templ_7745c5c3_Var19 string
templ_7745c5c3_Var19, templ_7745c5c3_Err = templ.JoinStringErrs(r.Monitor) templ_7745c5c3_Var19, templ_7745c5c3_Err = templ.JoinStringErrs(r.Monitor)
if templ_7745c5c3_Err != nil { if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/checkers.templ`, Line: 119, Col: 107} return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/checkers.templ`, Line: 120, Col: 108}
} }
_, 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 {
@@ -446,7 +446,7 @@ func CheckerPage(p Page, me Me, v CheckerView) templ.Component {
var templ_7745c5c3_Var20 string var templ_7745c5c3_Var20 string
templ_7745c5c3_Var20, templ_7745c5c3_Err = templ.JoinStringErrs(r.Latency) templ_7745c5c3_Var20, templ_7745c5c3_Err = templ.JoinStringErrs(r.Latency)
if templ_7745c5c3_Err != nil { if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/checkers.templ`, Line: 127, Col: 61} return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/checkers.templ`, Line: 128, Col: 62}
} }
_, 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 {
@@ -459,7 +459,7 @@ func CheckerPage(p Page, me Me, v CheckerView) templ.Component {
var templ_7745c5c3_Var21 string var templ_7745c5c3_Var21 string
templ_7745c5c3_Var21, templ_7745c5c3_Err = templ.JoinStringErrs(r.Detail) templ_7745c5c3_Var21, templ_7745c5c3_Err = templ.JoinStringErrs(r.Detail)
if templ_7745c5c3_Err != nil { if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/checkers.templ`, Line: 128, Col: 66} return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/checkers.templ`, Line: 129, Col: 67}
} }
_, 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 {
@@ -470,7 +470,7 @@ func CheckerPage(p Page, me Me, v CheckerView) templ.Component {
return templ_7745c5c3_Err return templ_7745c5c3_Err
} }
} }
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 36, "</tbody></table>") templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 36, "</tbody></table></div>")
if templ_7745c5c3_Err != nil { if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err return templ_7745c5c3_Err
} }
@@ -504,7 +504,7 @@ func CheckerPage(p Page, me Me, v CheckerView) templ.Component {
var templ_7745c5c3_Var22 string var templ_7745c5c3_Var22 string
templ_7745c5c3_Var22, templ_7745c5c3_Err = templruntime.NewAttributeExpression(templ.SafeURL(sb.URL)).ResolveURL(ctx) templ_7745c5c3_Var22, templ_7745c5c3_Err = templruntime.NewAttributeExpression(templ.SafeURL(sb.URL)).ResolveURL(ctx)
if templ_7745c5c3_Err != nil { if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/checkers.templ`, Line: 141, Col: 37} return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/checkers.templ`, Line: 143, Col: 37}
} }
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ_7745c5c3_Var22) _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ_7745c5c3_Var22)
if templ_7745c5c3_Err != nil { if templ_7745c5c3_Err != nil {
@@ -517,7 +517,7 @@ func CheckerPage(p Page, me Me, v CheckerView) templ.Component {
var templ_7745c5c3_Var23 string var templ_7745c5c3_Var23 string
templ_7745c5c3_Var23, templ_7745c5c3_Err = templ.JoinStringErrs(sb.Label) templ_7745c5c3_Var23, templ_7745c5c3_Err = templ.JoinStringErrs(sb.Label)
if templ_7745c5c3_Err != nil { if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/checkers.templ`, Line: 141, Col: 87} return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/checkers.templ`, Line: 143, Col: 87}
} }
_, 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 {
@@ -567,7 +567,7 @@ func checkerFact(labelID, value string) templ.Component {
var templ_7745c5c3_Var25 string var templ_7745c5c3_Var25 string
templ_7745c5c3_Var25, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, labelID)) templ_7745c5c3_Var25, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, labelID))
if templ_7745c5c3_Err != nil { if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/checkers.templ`, Line: 151, Col: 55} return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/checkers.templ`, Line: 153, Col: 55}
} }
_, 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 {
@@ -580,7 +580,7 @@ func checkerFact(labelID, value string) templ.Component {
var templ_7745c5c3_Var26 string var templ_7745c5c3_Var26 string
templ_7745c5c3_Var26, templ_7745c5c3_Err = templruntime.NewAttributeExpression(value).Resolve(ctx) templ_7745c5c3_Var26, 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/checkers.templ`, Line: 152, Col: 54} return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/checkers.templ`, Line: 154, Col: 54}
} }
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ_7745c5c3_Var26) _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ_7745c5c3_Var26)
if templ_7745c5c3_Err != nil { if templ_7745c5c3_Err != nil {
@@ -593,7 +593,7 @@ func checkerFact(labelID, value string) templ.Component {
var templ_7745c5c3_Var27 string var templ_7745c5c3_Var27 string
templ_7745c5c3_Var27, templ_7745c5c3_Err = templ.JoinStringErrs(value) templ_7745c5c3_Var27, templ_7745c5c3_Err = templ.JoinStringErrs(value)
if templ_7745c5c3_Err != nil { if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/checkers.templ`, Line: 152, Col: 64} return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/checkers.templ`, Line: 154, Col: 64}
} }
_, 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 {
@@ -632,7 +632,7 @@ func checkerCell(l CheckerLink) templ.Component {
var templ_7745c5c3_Var29 string var templ_7745c5c3_Var29 string
templ_7745c5c3_Var29, templ_7745c5c3_Err = templruntime.NewAttributeExpression(templ.SafeURL(l.URL)).ResolveURL(ctx) templ_7745c5c3_Var29, templ_7745c5c3_Err = templruntime.NewAttributeExpression(templ.SafeURL(l.URL)).ResolveURL(ctx)
if templ_7745c5c3_Err != nil { if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/checkers.templ`, Line: 158, Col: 32} return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/checkers.templ`, Line: 160, Col: 32}
} }
_, 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 {
@@ -645,7 +645,7 @@ func checkerCell(l CheckerLink) templ.Component {
var templ_7745c5c3_Var30 string var templ_7745c5c3_Var30 string
templ_7745c5c3_Var30, templ_7745c5c3_Err = templ.JoinStringErrs(l.Label) templ_7745c5c3_Var30, templ_7745c5c3_Err = templ.JoinStringErrs(l.Label)
if templ_7745c5c3_Err != nil { if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/checkers.templ`, Line: 158, Col: 68} return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/checkers.templ`, Line: 160, Col: 68}
} }
_, 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 {
@@ -663,7 +663,7 @@ func checkerCell(l CheckerLink) templ.Component {
var templ_7745c5c3_Var31 string var templ_7745c5c3_Var31 string
templ_7745c5c3_Var31, templ_7745c5c3_Err = templ.JoinStringErrs(l.Label) templ_7745c5c3_Var31, templ_7745c5c3_Err = templ.JoinStringErrs(l.Label)
if templ_7745c5c3_Err != nil { if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/checkers.templ`, Line: 160, Col: 36} return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/checkers.templ`, Line: 162, Col: 36}
} }
_, 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 {
+50 -31
View File
@@ -30,6 +30,8 @@ type Me struct {
// DeletesOrgs names the organizations the account is the last owner // DeletesOrgs names the organizations the account is the last owner
// of; deleting it deletes them, with all their monitors. // of; deleting it deletes them, with all their monitors.
DeletesOrgs []string DeletesOrgs []string
// Support is set while accounts can open support tickets.
Support bool
} }
// Org is one entry of the organization switcher. // Org is one entry of the organization switcher.
@@ -43,41 +45,58 @@ type Org struct {
templ consoleShell(p Page, me Me) { templ consoleShell(p Page, me Me) {
@Layout(p) { @Layout(p) {
<header class="border-b border-rule"> <header class="border-b border-rule">
<div class="mx-auto flex max-w-5xl items-center gap-6 px-6 py-3 text-sm"> <div class="mx-auto flex max-w-5xl flex-wrap items-center gap-x-4 gap-y-3 px-4 py-3 text-sm sm:gap-x-6 sm:px-6">
@brandLockup("/") @brandLockup("/")
if len(me.Orgs) > 1 { <span class="flex min-w-0 items-center gap-2">
<select data-switch-org class="border border-rule bg-transparent px-1.5 py-0.5 text-sm"> if len(me.Orgs) > 1 {
for _, o := range me.Orgs { <select data-switch-org class="max-w-[10rem] min-w-0 border border-rule bg-transparent px-1.5 py-0.5 text-sm sm:max-w-none">
<option value={ o.ID } selected?={ o.ID == me.ActiveOrg }>{ o.Name }</option> for _, o := range me.Orgs {
<option value={ o.ID } selected?={ o.ID == me.ActiveOrg }>{ o.Name }</option>
}
</select>
} else if len(me.Orgs) == 1 {
<span class="truncate text-muted">{ me.Orgs[0].Name }</span>
}
<a href="/orgs/new" class="px-1 text-muted hover:text-ink" title={ i18n.T(ctx, "orgs.new_title") } aria-label={ i18n.T(ctx, "orgs.new_title") }>+</a>
</span>
<button
type="button"
data-nav-toggle="console-nav"
aria-controls="console-nav"
aria-expanded="false"
aria-label={ i18n.T(ctx, "console.nav.menu") }
class="ml-auto -my-1 border border-rule px-2.5 py-1 text-muted hover:text-ink lg:hidden"
>
<span aria-hidden="true">☰</span> <span class="hidden sm:inline">{ i18n.T(ctx, "console.nav.menu") }</span>
</button>
<div id="console-nav" class="hidden w-full flex-col gap-4 border-t border-rule pt-3 lg:flex lg:w-auto lg:flex-1 lg:flex-row lg:items-center lg:gap-5 lg:border-0 lg:pt-0">
<nav class="flex flex-col gap-3 lg:flex-row lg:items-center lg:gap-5 lg:whitespace-nowrap">
<a href="/" class="text-muted hover:text-ink">{ i18n.T(ctx, "console.monitors.title") }</a>
if me.Can["statuspages.read"] {
<a href="/statuspages" class="text-muted hover:text-ink">{ i18n.T(ctx, "pages.title") }</a>
} }
</select> if me.Can["incidents.read"] {
} else if len(me.Orgs) == 1 { <a href="/incidents" class="text-muted hover:text-ink">{ i18n.T(ctx, "incidents.title") }</a>
<span class="text-muted">{ me.Orgs[0].Name }</span> <a href="/maintenance" class="text-muted hover:text-ink">{ i18n.T(ctx, "maintenance.title") }</a>
} }
<a href="/orgs/new" class="-ml-4 text-muted hover:text-ink" title={ i18n.T(ctx, "orgs.new_title") } aria-label={ i18n.T(ctx, "orgs.new_title") }>+</a> </nav>
<nav class="flex items-center gap-5 whitespace-nowrap"> <nav class="flex flex-col gap-3 border-t border-rule pt-3 lg:ml-auto lg:flex-row lg:items-center lg:gap-5 lg:whitespace-nowrap lg:border-0 lg:pt-0">
<a href="/" class="text-muted hover:text-ink">{ i18n.T(ctx, "console.monitors.title") }</a> if me.Support {
if me.Can["statuspages.read"] { <a href="/support" class="text-muted hover:text-ink">{ i18n.T(ctx, "support.title") }</a>
<a href="/statuspages" class="text-muted hover:text-ink">{ i18n.T(ctx, "pages.title") }</a> }
} <a href="/settings" class="text-muted hover:text-ink">{ i18n.T(ctx, "console.nav.settings") }</a>
if me.Can["incidents.read"] { if me.IsAdmin {
<a href="/incidents" class="text-muted hover:text-ink">{ i18n.T(ctx, "incidents.title") }</a> <a href="/admin" class="font-medium hover:underline">{ i18n.T(ctx, "console.nav.admin") }</a>
<a href="/maintenance" class="text-muted hover:text-ink">{ i18n.T(ctx, "maintenance.title") }</a> }
} <button data-logout class="text-left text-muted hover:text-ink">{ i18n.T(ctx, "console.nav.logout") }</button>
</nav> @languageSwitch(p.Languages)
<nav class="ml-auto flex items-center gap-5 whitespace-nowrap"> </nav>
<a href="/settings" class="text-muted hover:text-ink">{ i18n.T(ctx, "console.nav.settings") }</a> </div>
if me.IsAdmin {
<a href="/admin" class="font-medium hover:underline">{ i18n.T(ctx, "console.nav.admin") }</a>
}
<button data-logout class="text-muted hover:text-ink">{ i18n.T(ctx, "console.nav.logout") }</button>
@languageSwitch(p.Languages)
</nav>
</div> </div>
</header> </header>
if me.OrgSuspended { if me.OrgSuspended {
<div class="border-b border-down bg-down/10" role="alert"> <div class="border-b border-down bg-down/10" role="alert">
<p class="mx-auto max-w-5xl px-6 py-3 text-sm"> <p class="mx-auto max-w-5xl px-4 sm:px-6 py-3 text-sm">
<strong>{ i18n.T(ctx, "console.org_suspended") }</strong> <strong>{ i18n.T(ctx, "console.org_suspended") }</strong>
if me.SuspendedReason != "" { if me.SuspendedReason != "" {
{ " " + i18n.T(ctx, "console.suspended_reason", "Reason", me.SuspendedReason) } { " " + i18n.T(ctx, "console.suspended_reason", "Reason", me.SuspendedReason) }
@@ -91,7 +110,7 @@ templ consoleShell(p Page, me Me) {
case "sso_required_by_org": case "sso_required_by_org":
@policyBanner("error.sso_required_by_org", "console.sso_required_action", "/sso/"+me.ActiveSlug) @policyBanner("error.sso_required_by_org", "console.sso_required_action", "/sso/"+me.ActiveSlug)
} }
<main class="mx-auto max-w-5xl px-6 py-10"> <main class="mx-auto max-w-5xl px-4 py-6 sm:px-6 sm:py-10">
@flash(p) @flash(p)
{ children... } { children... }
</main> </main>
@@ -226,7 +245,7 @@ templ recoveryOutput() {
templ policyBanner(msgID, actionID, href string) { templ policyBanner(msgID, actionID, href string) {
<div class="border-b border-degraded/40 bg-degraded/10"> <div class="border-b border-degraded/40 bg-degraded/10">
<p class="mx-auto max-w-5xl px-6 py-2 text-sm"> <p class="mx-auto max-w-5xl px-4 sm:px-6 py-2 text-sm">
{ i18n.T(ctx, msgID) } { i18n.T(ctx, msgID) }
<a href={ templ.SafeURL(href) } class="underline underline-offset-2">{ i18n.T(ctx, actionID) }</a> <a href={ templ.SafeURL(href) } class="underline underline-offset-2">{ i18n.T(ctx, actionID) }</a>
</p> </p>
File diff suppressed because it is too large. Load diff
+12 -10
View File
@@ -90,16 +90,18 @@ templ evidenceList(rows []EvidenceRow) {
} }
templ headerTable(rows [][2]string) { templ headerTable(rows [][2]string) {
<table class="w-full text-left font-mono text-xs"> <div class="overflow-x-auto">
<tbody> <table class="w-full text-left font-mono text-xs">
for _, h := range rows { <tbody>
<tr class="align-top"> for _, h := range rows {
<td class="w-1/3 py-0.5 pr-3 text-muted">{ h[0] }</td> <tr class="align-top">
<td class="break-all py-0.5">{ h[1] }</td> <td class="w-1/3 py-0.5 pr-3 text-muted">{ h[0] }</td>
</tr> <td class="break-all py-0.5">{ h[1] }</td>
} </tr>
</tbody> }
</table> </tbody>
</table>
</div>
} }
templ EvidencePage(p Page, me Me, v EvidenceView) { templ EvidencePage(p Page, me Me, v EvidenceView) {
+47 -47
View File
@@ -215,7 +215,7 @@ func headerTable(rows [][2]string) templ.Component {
} }
ctx = templ.InitializeContext(ctx) ctx = templ.InitializeContext(ctx)
ctx = templ.ClearChildren(ctx) ctx = templ.ClearChildren(ctx)
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 13, "<table class=\"w-full text-left font-mono text-xs\"><tbody>") templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 13, "<div class=\"overflow-x-auto\"><table class=\"w-full text-left font-mono text-xs\"><tbody>")
if templ_7745c5c3_Err != nil { if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err return templ_7745c5c3_Err
} }
@@ -227,7 +227,7 @@ func headerTable(rows [][2]string) templ.Component {
var templ_7745c5c3_Var8 string var templ_7745c5c3_Var8 string
templ_7745c5c3_Var8, templ_7745c5c3_Err = templ.JoinStringErrs(h[0]) templ_7745c5c3_Var8, templ_7745c5c3_Err = templ.JoinStringErrs(h[0])
if templ_7745c5c3_Err != nil { if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/evidence.templ`, Line: 97, Col: 52} return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/evidence.templ`, Line: 98, Col: 53}
} }
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var8)) _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var8))
if templ_7745c5c3_Err != nil { if templ_7745c5c3_Err != nil {
@@ -240,7 +240,7 @@ func headerTable(rows [][2]string) templ.Component {
var templ_7745c5c3_Var9 string var templ_7745c5c3_Var9 string
templ_7745c5c3_Var9, templ_7745c5c3_Err = templ.JoinStringErrs(h[1]) templ_7745c5c3_Var9, templ_7745c5c3_Err = templ.JoinStringErrs(h[1])
if templ_7745c5c3_Err != nil { if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/evidence.templ`, Line: 98, Col: 40} return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/evidence.templ`, Line: 99, Col: 41}
} }
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var9)) _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var9))
if templ_7745c5c3_Err != nil { if templ_7745c5c3_Err != nil {
@@ -251,7 +251,7 @@ func headerTable(rows [][2]string) templ.Component {
return templ_7745c5c3_Err return templ_7745c5c3_Err
} }
} }
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 17, "</tbody></table>") templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 17, "</tbody></table></div>")
if templ_7745c5c3_Err != nil { if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err return templ_7745c5c3_Err
} }
@@ -295,7 +295,7 @@ func EvidencePage(p Page, me Me, v EvidenceView) templ.Component {
var templ_7745c5c3_Var12 string var templ_7745c5c3_Var12 string
templ_7745c5c3_Var12, templ_7745c5c3_Err = templruntime.NewAttributeExpression(templ.SafeURL("/monitors/" + v.MonitorID)).ResolveURL(ctx) templ_7745c5c3_Var12, templ_7745c5c3_Err = templruntime.NewAttributeExpression(templ.SafeURL("/monitors/" + v.MonitorID)).ResolveURL(ctx)
if templ_7745c5c3_Err != nil { if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/evidence.templ`, Line: 108, Col: 54} return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/evidence.templ`, Line: 110, Col: 54}
} }
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ_7745c5c3_Var12) _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ_7745c5c3_Var12)
if templ_7745c5c3_Err != nil { if templ_7745c5c3_Err != nil {
@@ -308,7 +308,7 @@ func EvidencePage(p Page, me Me, v EvidenceView) templ.Component {
var templ_7745c5c3_Var13 string var templ_7745c5c3_Var13 string
templ_7745c5c3_Var13, templ_7745c5c3_Err = templ.JoinStringErrs(v.MonitorName) templ_7745c5c3_Var13, templ_7745c5c3_Err = templ.JoinStringErrs(v.MonitorName)
if templ_7745c5c3_Err != nil { if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/evidence.templ`, Line: 108, Col: 110} return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/evidence.templ`, Line: 110, Col: 110}
} }
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var13)) _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var13))
if templ_7745c5c3_Err != nil { if templ_7745c5c3_Err != nil {
@@ -340,7 +340,7 @@ func EvidencePage(p Page, me Me, v EvidenceView) templ.Component {
var templ_7745c5c3_Var14 string var templ_7745c5c3_Var14 string
templ_7745c5c3_Var14, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, "evidence.heading")) templ_7745c5c3_Var14, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, "evidence.heading"))
if templ_7745c5c3_Err != nil { if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/evidence.templ`, Line: 116, Col: 36} return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/evidence.templ`, Line: 118, Col: 36}
} }
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var14)) _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var14))
if templ_7745c5c3_Err != nil { if templ_7745c5c3_Err != nil {
@@ -353,7 +353,7 @@ func EvidencePage(p Page, me Me, v EvidenceView) templ.Component {
var templ_7745c5c3_Var15 string var templ_7745c5c3_Var15 string
templ_7745c5c3_Var15, templ_7745c5c3_Err = templ.JoinStringErrs(v.Time) templ_7745c5c3_Var15, templ_7745c5c3_Err = templ.JoinStringErrs(v.Time)
if templ_7745c5c3_Err != nil { if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/evidence.templ`, Line: 119, Col: 11} return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/evidence.templ`, Line: 121, Col: 11}
} }
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var15)) _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var15))
if templ_7745c5c3_Err != nil { if templ_7745c5c3_Err != nil {
@@ -366,7 +366,7 @@ func EvidencePage(p Page, me Me, v EvidenceView) templ.Component {
var templ_7745c5c3_Var16 string var templ_7745c5c3_Var16 string
templ_7745c5c3_Var16, templ_7745c5c3_Err = templ.JoinStringErrs(v.Region) templ_7745c5c3_Var16, templ_7745c5c3_Err = templ.JoinStringErrs(v.Region)
if templ_7745c5c3_Err != nil { if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/evidence.templ`, Line: 119, Col: 27} return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/evidence.templ`, Line: 121, Col: 27}
} }
_, 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 {
@@ -380,7 +380,7 @@ func EvidencePage(p Page, me Me, v EvidenceView) templ.Component {
var templ_7745c5c3_Var17 string var templ_7745c5c3_Var17 string
templ_7745c5c3_Var17, templ_7745c5c3_Err = templ.JoinStringErrs(" · " + v.RemoteAddr) templ_7745c5c3_Var17, templ_7745c5c3_Err = templ.JoinStringErrs(" · " + v.RemoteAddr)
if templ_7745c5c3_Err != nil { if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/evidence.templ`, Line: 121, Col: 27} return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/evidence.templ`, Line: 123, Col: 27}
} }
_, 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 {
@@ -399,7 +399,7 @@ func EvidencePage(p Page, me Me, v EvidenceView) templ.Component {
var templ_7745c5c3_Var18 string var templ_7745c5c3_Var18 string
templ_7745c5c3_Var18, templ_7745c5c3_Err = templ.JoinStringErrs(v.Error) templ_7745c5c3_Var18, templ_7745c5c3_Err = templ.JoinStringErrs(v.Error)
if templ_7745c5c3_Err != nil { if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/evidence.templ`, Line: 126, Col: 13} return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/evidence.templ`, Line: 128, Col: 13}
} }
_, 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 {
@@ -417,7 +417,7 @@ func EvidencePage(p Page, me Me, v EvidenceView) templ.Component {
var templ_7745c5c3_Var19 string var templ_7745c5c3_Var19 string
templ_7745c5c3_Var19, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, "evidence.failed_at", "Stage", i18n.T(ctx, "evidence.stage_"+v.FailedAt))) templ_7745c5c3_Var19, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, "evidence.failed_at", "Stage", i18n.T(ctx, "evidence.stage_"+v.FailedAt)))
if templ_7745c5c3_Err != nil { if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/evidence.templ`, Line: 128, Col: 131} return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/evidence.templ`, Line: 130, Col: 131}
} }
_, 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 {
@@ -448,7 +448,7 @@ func EvidencePage(p Page, me Me, v EvidenceView) templ.Component {
var templ_7745c5c3_Var20 string var templ_7745c5c3_Var20 string
templ_7745c5c3_Var20, templ_7745c5c3_Err = templruntime.NewAttributeExpression(i18n.T(ctx, "evidence.timing")).Resolve(ctx) templ_7745c5c3_Var20, templ_7745c5c3_Err = templruntime.NewAttributeExpression(i18n.T(ctx, "evidence.timing")).Resolve(ctx)
if templ_7745c5c3_Err != nil { if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/evidence.templ`, Line: 134, Col: 118} return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/evidence.templ`, Line: 136, Col: 118}
} }
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ_7745c5c3_Var20) _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ_7745c5c3_Var20)
if templ_7745c5c3_Err != nil { if templ_7745c5c3_Err != nil {
@@ -488,7 +488,7 @@ func EvidencePage(p Page, me Me, v EvidenceView) templ.Component {
var templ_7745c5c3_Var23 string var templ_7745c5c3_Var23 string
templ_7745c5c3_Var23, templ_7745c5c3_Err = templruntime.SanitizeStyleAttributeValues(widthStyle(ph.Percent)) templ_7745c5c3_Var23, templ_7745c5c3_Err = templruntime.SanitizeStyleAttributeValues(widthStyle(ph.Percent))
if templ_7745c5c3_Err != nil { if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/evidence.templ`, Line: 136, Col: 75} return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/evidence.templ`, Line: 138, Col: 75}
} }
_, 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 {
@@ -501,7 +501,7 @@ func EvidencePage(p Page, me Me, v EvidenceView) templ.Component {
var templ_7745c5c3_Var24 string var templ_7745c5c3_Var24 string
templ_7745c5c3_Var24, templ_7745c5c3_Err = templruntime.NewAttributeExpression(i18n.T(ctx, "evidence.phase_"+ph.Key) + " " + ph.Value).Resolve(ctx) templ_7745c5c3_Var24, templ_7745c5c3_Err = templruntime.NewAttributeExpression(i18n.T(ctx, "evidence.phase_"+ph.Key) + " " + ph.Value).Resolve(ctx)
if templ_7745c5c3_Err != nil { if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/evidence.templ`, Line: 136, Col: 140} return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/evidence.templ`, Line: 138, Col: 140}
} }
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ_7745c5c3_Var24) _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ_7745c5c3_Var24)
if templ_7745c5c3_Err != nil { if templ_7745c5c3_Err != nil {
@@ -578,7 +578,7 @@ func EvidencePage(p Page, me Me, v EvidenceView) templ.Component {
var templ_7745c5c3_Var27 string var templ_7745c5c3_Var27 string
templ_7745c5c3_Var27, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, "evidence.phase_"+ph.Key)) templ_7745c5c3_Var27, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, "evidence.phase_"+ph.Key))
if templ_7745c5c3_Err != nil { if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/evidence.templ`, Line: 142, Col: 156} return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/evidence.templ`, Line: 144, Col: 156}
} }
_, 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 {
@@ -591,7 +591,7 @@ func EvidencePage(p Page, me Me, v EvidenceView) templ.Component {
var templ_7745c5c3_Var28 string var templ_7745c5c3_Var28 string
templ_7745c5c3_Var28, templ_7745c5c3_Err = templ.JoinStringErrs(ph.Value) templ_7745c5c3_Var28, templ_7745c5c3_Err = templ.JoinStringErrs(ph.Value)
if templ_7745c5c3_Err != nil { if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/evidence.templ`, Line: 143, Col: 20} return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/evidence.templ`, Line: 145, Col: 20}
} }
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var28)) _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var28))
if templ_7745c5c3_Err != nil { if templ_7745c5c3_Err != nil {
@@ -609,7 +609,7 @@ func EvidencePage(p Page, me Me, v EvidenceView) templ.Component {
var templ_7745c5c3_Var29 string var templ_7745c5c3_Var29 string
templ_7745c5c3_Var29, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, "evidence.total")) templ_7745c5c3_Var29, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, "evidence.total"))
if templ_7745c5c3_Err != nil { if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/evidence.templ`, Line: 147, Col: 59} return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/evidence.templ`, Line: 149, Col: 59}
} }
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var29)) _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var29))
if templ_7745c5c3_Err != nil { if templ_7745c5c3_Err != nil {
@@ -622,7 +622,7 @@ func EvidencePage(p Page, me Me, v EvidenceView) templ.Component {
var templ_7745c5c3_Var30 string var templ_7745c5c3_Var30 string
templ_7745c5c3_Var30, templ_7745c5c3_Err = templ.JoinStringErrs(v.Total) templ_7745c5c3_Var30, templ_7745c5c3_Err = templ.JoinStringErrs(v.Total)
if templ_7745c5c3_Err != nil { if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/evidence.templ`, Line: 148, Col: 18} return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/evidence.templ`, Line: 150, Col: 18}
} }
_, 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 {
@@ -648,7 +648,7 @@ func EvidencePage(p Page, me Me, v EvidenceView) templ.Component {
var templ_7745c5c3_Var31 string var templ_7745c5c3_Var31 string
templ_7745c5c3_Var31, templ_7745c5c3_Err = templ.JoinStringErrs(strconv.Itoa(i + 1)) templ_7745c5c3_Var31, templ_7745c5c3_Err = templ.JoinStringErrs(strconv.Itoa(i + 1))
if templ_7745c5c3_Err != nil { if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/evidence.templ`, Line: 158, Col: 71} return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/evidence.templ`, Line: 160, Col: 71}
} }
_, 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 {
@@ -661,7 +661,7 @@ func EvidencePage(p Page, me Me, v EvidenceView) templ.Component {
var templ_7745c5c3_Var32 string var templ_7745c5c3_Var32 string
templ_7745c5c3_Var32, templ_7745c5c3_Err = templ.JoinStringErrs(st.Method) templ_7745c5c3_Var32, templ_7745c5c3_Err = templ.JoinStringErrs(st.Method)
if templ_7745c5c3_Err != nil { if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/evidence.templ`, Line: 159, Col: 50} return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/evidence.templ`, Line: 161, Col: 50}
} }
_, 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 {
@@ -674,7 +674,7 @@ func EvidencePage(p Page, me Me, v EvidenceView) templ.Component {
var templ_7745c5c3_Var33 string var templ_7745c5c3_Var33 string
templ_7745c5c3_Var33, templ_7745c5c3_Err = templ.JoinStringErrs(st.URL) templ_7745c5c3_Var33, templ_7745c5c3_Err = templ.JoinStringErrs(st.URL)
if templ_7745c5c3_Err != nil { if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/evidence.templ`, Line: 160, Col: 72} return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/evidence.templ`, Line: 162, Col: 72}
} }
_, 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 {
@@ -692,7 +692,7 @@ func EvidencePage(p Page, me Me, v EvidenceView) templ.Component {
var templ_7745c5c3_Var34 string var templ_7745c5c3_Var34 string
templ_7745c5c3_Var34, templ_7745c5c3_Err = templ.JoinStringErrs(st.Status) templ_7745c5c3_Var34, templ_7745c5c3_Err = templ.JoinStringErrs(st.Status)
if templ_7745c5c3_Err != nil { if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/evidence.templ`, Line: 162, Col: 51} return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/evidence.templ`, Line: 164, Col: 51}
} }
_, 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 {
@@ -705,7 +705,7 @@ func EvidencePage(p Page, me Me, v EvidenceView) templ.Component {
var templ_7745c5c3_Var35 string var templ_7745c5c3_Var35 string
templ_7745c5c3_Var35, templ_7745c5c3_Err = templ.JoinStringErrs(st.Proto) templ_7745c5c3_Var35, templ_7745c5c3_Err = templ.JoinStringErrs(st.Proto)
if templ_7745c5c3_Err != nil { if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/evidence.templ`, Line: 162, Col: 89} return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/evidence.templ`, Line: 164, Col: 89}
} }
_, 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 {
@@ -723,7 +723,7 @@ func EvidencePage(p Page, me Me, v EvidenceView) templ.Component {
var templ_7745c5c3_Var36 string var templ_7745c5c3_Var36 string
templ_7745c5c3_Var36, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, "evidence.no_response")) templ_7745c5c3_Var36, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, "evidence.no_response"))
if templ_7745c5c3_Err != nil { if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/evidence.templ`, Line: 164, Col: 87} return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/evidence.templ`, Line: 166, Col: 87}
} }
_, 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 {
@@ -741,7 +741,7 @@ func EvidencePage(p Page, me Me, v EvidenceView) templ.Component {
var templ_7745c5c3_Var37 string var templ_7745c5c3_Var37 string
templ_7745c5c3_Var37, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, "evidence.headers")) templ_7745c5c3_Var37, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, "evidence.headers"))
if templ_7745c5c3_Err != nil { if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/evidence.templ`, Line: 168, Col: 91} return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/evidence.templ`, Line: 170, Col: 91}
} }
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var37)) _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var37))
if templ_7745c5c3_Err != nil { if templ_7745c5c3_Err != nil {
@@ -754,7 +754,7 @@ func EvidencePage(p Page, me Me, v EvidenceView) templ.Component {
var templ_7745c5c3_Var38 string var templ_7745c5c3_Var38 string
templ_7745c5c3_Var38, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, "evidence.request")) templ_7745c5c3_Var38, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, "evidence.request"))
if templ_7745c5c3_Err != nil { if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/evidence.templ`, Line: 171, Col: 78} return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/evidence.templ`, Line: 173, Col: 78}
} }
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var38)) _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var38))
if templ_7745c5c3_Err != nil { if templ_7745c5c3_Err != nil {
@@ -775,7 +775,7 @@ func EvidencePage(p Page, me Me, v EvidenceView) templ.Component {
var templ_7745c5c3_Var39 string var templ_7745c5c3_Var39 string
templ_7745c5c3_Var39, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, "evidence.response")) templ_7745c5c3_Var39, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, "evidence.response"))
if templ_7745c5c3_Err != nil { if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/evidence.templ`, Line: 175, Col: 79} return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/evidence.templ`, Line: 177, Col: 79}
} }
_, 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 {
@@ -814,7 +814,7 @@ func EvidencePage(p Page, me Me, v EvidenceView) templ.Component {
var templ_7745c5c3_Var40 string var templ_7745c5c3_Var40 string
templ_7745c5c3_Var40, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, "evidence.cert_subject")) templ_7745c5c3_Var40, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, "evidence.cert_subject"))
if templ_7745c5c3_Err != nil { if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/evidence.templ`, Line: 188, Col: 66} return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/evidence.templ`, Line: 190, Col: 66}
} }
_, 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 {
@@ -827,7 +827,7 @@ func EvidencePage(p Page, me Me, v EvidenceView) templ.Component {
var templ_7745c5c3_Var41 string var templ_7745c5c3_Var41 string
templ_7745c5c3_Var41, templ_7745c5c3_Err = templ.JoinStringErrs(v.TLS.Subject) templ_7745c5c3_Var41, templ_7745c5c3_Err = templ.JoinStringErrs(v.TLS.Subject)
if templ_7745c5c3_Err != nil { if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/evidence.templ`, Line: 189, Col: 60} return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/evidence.templ`, Line: 191, Col: 60}
} }
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var41)) _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var41))
if templ_7745c5c3_Err != nil { if templ_7745c5c3_Err != nil {
@@ -840,7 +840,7 @@ func EvidencePage(p Page, me Me, v EvidenceView) templ.Component {
var templ_7745c5c3_Var42 string var templ_7745c5c3_Var42 string
templ_7745c5c3_Var42, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, "evidence.cert_names")) templ_7745c5c3_Var42, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, "evidence.cert_names"))
if templ_7745c5c3_Err != nil { if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/evidence.templ`, Line: 190, Col: 64} return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/evidence.templ`, Line: 192, Col: 64}
} }
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var42)) _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var42))
if templ_7745c5c3_Err != nil { if templ_7745c5c3_Err != nil {
@@ -853,7 +853,7 @@ func EvidencePage(p Page, me Me, v EvidenceView) templ.Component {
var templ_7745c5c3_Var43 string var templ_7745c5c3_Var43 string
templ_7745c5c3_Var43, templ_7745c5c3_Err = templ.JoinStringErrs(v.TLS.Names) templ_7745c5c3_Var43, templ_7745c5c3_Err = templ.JoinStringErrs(v.TLS.Names)
if templ_7745c5c3_Err != nil { if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/evidence.templ`, Line: 191, Col: 58} return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/evidence.templ`, Line: 193, Col: 58}
} }
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var43)) _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var43))
if templ_7745c5c3_Err != nil { if templ_7745c5c3_Err != nil {
@@ -866,7 +866,7 @@ func EvidencePage(p Page, me Me, v EvidenceView) templ.Component {
var templ_7745c5c3_Var44 string var templ_7745c5c3_Var44 string
templ_7745c5c3_Var44, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, "evidence.cert_issuer")) templ_7745c5c3_Var44, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, "evidence.cert_issuer"))
if templ_7745c5c3_Err != nil { if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/evidence.templ`, Line: 192, Col: 65} return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/evidence.templ`, Line: 194, Col: 65}
} }
_, 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 {
@@ -879,7 +879,7 @@ func EvidencePage(p Page, me Me, v EvidenceView) templ.Component {
var templ_7745c5c3_Var45 string var templ_7745c5c3_Var45 string
templ_7745c5c3_Var45, templ_7745c5c3_Err = templ.JoinStringErrs(v.TLS.Issuer) templ_7745c5c3_Var45, templ_7745c5c3_Err = templ.JoinStringErrs(v.TLS.Issuer)
if templ_7745c5c3_Err != nil { if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/evidence.templ`, Line: 193, Col: 59} return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/evidence.templ`, Line: 195, Col: 59}
} }
_, 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 {
@@ -892,7 +892,7 @@ func EvidencePage(p Page, me Me, v EvidenceView) templ.Component {
var templ_7745c5c3_Var46 string var templ_7745c5c3_Var46 string
templ_7745c5c3_Var46, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, "evidence.cert_valid")) templ_7745c5c3_Var46, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, "evidence.cert_valid"))
if templ_7745c5c3_Err != nil { if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/evidence.templ`, Line: 194, Col: 64} return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/evidence.templ`, Line: 196, Col: 64}
} }
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var46)) _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var46))
if templ_7745c5c3_Err != nil { if templ_7745c5c3_Err != nil {
@@ -905,7 +905,7 @@ func EvidencePage(p Page, me Me, v EvidenceView) templ.Component {
var templ_7745c5c3_Var47 string var templ_7745c5c3_Var47 string
templ_7745c5c3_Var47, templ_7745c5c3_Err = templ.JoinStringErrs(v.TLS.NotBefore) templ_7745c5c3_Var47, templ_7745c5c3_Err = templ.JoinStringErrs(v.TLS.NotBefore)
if templ_7745c5c3_Err != nil { if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/evidence.templ`, Line: 196, Col: 23} return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/evidence.templ`, Line: 198, Col: 23}
} }
_, 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 {
@@ -918,7 +918,7 @@ func EvidencePage(p Page, me Me, v EvidenceView) templ.Component {
var templ_7745c5c3_Var48 string var templ_7745c5c3_Var48 string
templ_7745c5c3_Var48, templ_7745c5c3_Err = templ.JoinStringErrs(v.TLS.NotAfter) templ_7745c5c3_Var48, templ_7745c5c3_Err = templ.JoinStringErrs(v.TLS.NotAfter)
if templ_7745c5c3_Err != nil { if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/evidence.templ`, Line: 196, Col: 46} return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/evidence.templ`, Line: 198, Col: 46}
} }
_, 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 {
@@ -972,7 +972,7 @@ func EvidencePage(p Page, me Me, v EvidenceView) templ.Component {
var templ_7745c5c3_Var51 string var templ_7745c5c3_Var51 string
templ_7745c5c3_Var51, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, "evidence.cert_expired")) templ_7745c5c3_Var51, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, "evidence.cert_expired"))
if templ_7745c5c3_Err != nil { if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/evidence.templ`, Line: 199, Col: 46} return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/evidence.templ`, Line: 201, Col: 46}
} }
_, 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 {
@@ -982,7 +982,7 @@ func EvidencePage(p Page, me Me, v EvidenceView) templ.Component {
var templ_7745c5c3_Var52 string var templ_7745c5c3_Var52 string
templ_7745c5c3_Var52, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, "evidence.cert_days_left", "Count", v.TLS.DaysLeft)) templ_7745c5c3_Var52, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, "evidence.cert_days_left", "Count", v.TLS.DaysLeft))
if templ_7745c5c3_Err != nil { if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/evidence.templ`, Line: 201, Col: 73} return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/evidence.templ`, Line: 203, Col: 73}
} }
_, 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 {
@@ -996,7 +996,7 @@ func EvidencePage(p Page, me Me, v EvidenceView) templ.Component {
var templ_7745c5c3_Var53 string var templ_7745c5c3_Var53 string
templ_7745c5c3_Var53, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, "evidence.tls_version")) templ_7745c5c3_Var53, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, "evidence.tls_version"))
if templ_7745c5c3_Err != nil { if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/evidence.templ`, Line: 205, Col: 65} return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/evidence.templ`, Line: 207, Col: 65}
} }
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var53)) _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var53))
if templ_7745c5c3_Err != nil { if templ_7745c5c3_Err != nil {
@@ -1009,7 +1009,7 @@ func EvidencePage(p Page, me Me, v EvidenceView) templ.Component {
var templ_7745c5c3_Var54 string var templ_7745c5c3_Var54 string
templ_7745c5c3_Var54, templ_7745c5c3_Err = templ.JoinStringErrs(v.TLS.Version) templ_7745c5c3_Var54, templ_7745c5c3_Err = templ.JoinStringErrs(v.TLS.Version)
if templ_7745c5c3_Err != nil { if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/evidence.templ`, Line: 206, Col: 50} return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/evidence.templ`, Line: 208, Col: 50}
} }
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var54)) _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var54))
if templ_7745c5c3_Err != nil { if templ_7745c5c3_Err != nil {
@@ -1022,7 +1022,7 @@ func EvidencePage(p Page, me Me, v EvidenceView) templ.Component {
var templ_7745c5c3_Var55 string var templ_7745c5c3_Var55 string
templ_7745c5c3_Var55, templ_7745c5c3_Err = templ.JoinStringErrs(v.TLS.Cipher) templ_7745c5c3_Var55, templ_7745c5c3_Err = templ.JoinStringErrs(v.TLS.Cipher)
if templ_7745c5c3_Err != nil { if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/evidence.templ`, Line: 206, Col: 70} return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/evidence.templ`, Line: 208, Col: 70}
} }
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var55)) _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var55))
if templ_7745c5c3_Err != nil { if templ_7745c5c3_Err != nil {
@@ -1049,7 +1049,7 @@ func EvidencePage(p Page, me Me, v EvidenceView) templ.Component {
var templ_7745c5c3_Var56 string var templ_7745c5c3_Var56 string
templ_7745c5c3_Var56, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, "evidence.body_binary")) templ_7745c5c3_Var56, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, "evidence.body_binary"))
if templ_7745c5c3_Err != nil { if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/evidence.templ`, Line: 213, Col: 71} return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/evidence.templ`, Line: 215, Col: 71}
} }
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var56)) _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var56))
if templ_7745c5c3_Err != nil { if templ_7745c5c3_Err != nil {
@@ -1067,7 +1067,7 @@ func EvidencePage(p Page, me Me, v EvidenceView) templ.Component {
var templ_7745c5c3_Var57 string var templ_7745c5c3_Var57 string
templ_7745c5c3_Var57, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, "evidence.body_empty")) templ_7745c5c3_Var57, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, "evidence.body_empty"))
if templ_7745c5c3_Err != nil { if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/evidence.templ`, Line: 215, Col: 70} return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/evidence.templ`, Line: 217, Col: 70}
} }
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var57)) _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var57))
if templ_7745c5c3_Err != nil { if templ_7745c5c3_Err != nil {
@@ -1085,7 +1085,7 @@ func EvidencePage(p Page, me Me, v EvidenceView) templ.Component {
var templ_7745c5c3_Var58 string var templ_7745c5c3_Var58 string
templ_7745c5c3_Var58, templ_7745c5c3_Err = templ.JoinStringErrs(v.ContentType) templ_7745c5c3_Var58, templ_7745c5c3_Err = templ.JoinStringErrs(v.ContentType)
if templ_7745c5c3_Err != nil { if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/evidence.templ`, Line: 218, Col: 20} return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/evidence.templ`, Line: 220, Col: 20}
} }
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var58)) _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var58))
if templ_7745c5c3_Err != nil { if templ_7745c5c3_Err != nil {
@@ -1099,7 +1099,7 @@ func EvidencePage(p Page, me Me, v EvidenceView) templ.Component {
var templ_7745c5c3_Var59 string var templ_7745c5c3_Var59 string
templ_7745c5c3_Var59, templ_7745c5c3_Err = templ.JoinStringErrs(" · " + i18n.T(ctx, "evidence.body_truncated")) templ_7745c5c3_Var59, templ_7745c5c3_Err = templ.JoinStringErrs(" · " + i18n.T(ctx, "evidence.body_truncated"))
if templ_7745c5c3_Err != nil { if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/evidence.templ`, Line: 220, Col: 55} return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/evidence.templ`, Line: 222, Col: 55}
} }
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var59)) _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var59))
if templ_7745c5c3_Err != nil { if templ_7745c5c3_Err != nil {
@@ -1113,7 +1113,7 @@ func EvidencePage(p Page, me Me, v EvidenceView) templ.Component {
var templ_7745c5c3_Var60 string var templ_7745c5c3_Var60 string
templ_7745c5c3_Var60, templ_7745c5c3_Err = templ.JoinStringErrs(v.Body) templ_7745c5c3_Var60, templ_7745c5c3_Err = templ.JoinStringErrs(v.Body)
if templ_7745c5c3_Err != nil { if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/evidence.templ`, Line: 223, Col: 146} return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/evidence.templ`, Line: 225, Col: 146}
} }
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var60)) _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var60))
if templ_7745c5c3_Err != nil { if templ_7745c5c3_Err != nil {
Loaded 100 of 116 files, more files were not shown because too many files have changed in this diff. Show more