Compare commits
No files matched your search
@@ -88,6 +88,7 @@ func run(log *slog.Logger, level *slog.LevelVar) error {
|
||||
return err
|
||||
}
|
||||
health.Register(r)
|
||||
r.Use(platform.Compress())
|
||||
r.StaticFS("/static", web.Static())
|
||||
pages.Mount(r)
|
||||
go pages.Run(ctx)
|
||||
|
||||
@@ -32,6 +32,7 @@ require (
|
||||
go.uber.org/zap v1.28.0
|
||||
golang.org/x/crypto v0.59.0
|
||||
golang.org/x/crypto/x509roots/fallback v0.0.0-20261123165210-6c21c5864259
|
||||
golang.org/x/image v0.25.0
|
||||
golang.org/x/net v0.63.0
|
||||
golang.org/x/oauth2 v0.38.0
|
||||
golang.org/x/sync v0.25.0
|
||||
|
||||
@@ -349,6 +349,8 @@ golang.org/x/crypto/x509roots/fallback v0.0.0-20261123165210-6c21c5864259 h1:wXc
|
||||
golang.org/x/crypto/x509roots/fallback v0.0.0-20261123165210-6c21c5864259/go.mod h1:HPze8vhfG6fO06AM+VSvxRm4E3+5Yk375mgrJ5M2z1E=
|
||||
golang.org/x/exp v0.0.0-20261109185158-a52e3aef5920 h1:qr+tk4P56rtbVVAJDyAr5LAOiaD/XhZCoRTr4SfLxAk=
|
||||
golang.org/x/exp v0.0.0-20261109185158-a52e3aef5920/go.mod h1:J3U+E8RzytcGvwz+uJuAP4zULJ2TkAQBnmPZMexpdXs=
|
||||
golang.org/x/image v0.25.0 h1:Y6uW6rH1y5y/LK1J8BPWZtr6yZ7hrsy6hFrXjgsc2fQ=
|
||||
golang.org/x/image v0.25.0/go.mod h1:tCAmOEGthTtkalusGp1g3xa2gke8J6c2N565dTyl9Rs=
|
||||
golang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4/go.mod h1:jJ57K6gSWd91VN4djpZkiMVwK6gcyfeH4XE8wZrZaV4=
|
||||
golang.org/x/mod v0.8.0/go.mod h1:iBbtSCu2XBx23ZKBPSOrRkjjQPZFPuis4dIYUhu/chs=
|
||||
golang.org/x/mod v0.43.0 h1:MFuq5J6s35W9D3IjkwyWc9vHh0nENOrt5K8Iof4ofmg=
|
||||
|
||||
@@ -362,14 +362,20 @@ type PageRef struct {
|
||||
Host string `json:"host,omitempty"`
|
||||
}
|
||||
|
||||
// PageIndex lists the pages a status page server serves.
|
||||
type PageIndex struct {
|
||||
Pages []PageRef `json:"pages"`
|
||||
// HomeURL is the platform's home page, which the server links from
|
||||
// its error page; empty for none.
|
||||
HomeURL string `json:"home_url,omitempty"`
|
||||
}
|
||||
|
||||
// Pages lists every page this status page server serves, so it can keep
|
||||
// them all cached before anyone visits.
|
||||
func (c *Client) Pages(ctx context.Context) ([]PageRef, error) {
|
||||
var out struct {
|
||||
Pages []PageRef `json:"pages"`
|
||||
}
|
||||
func (c *Client) Pages(ctx context.Context) (PageIndex, error) {
|
||||
var out PageIndex
|
||||
err := c.do(ctx, http.MethodGet, "/pages/index", nil, &out)
|
||||
return out.Pages, err
|
||||
return out, err
|
||||
}
|
||||
|
||||
// ErrNotFound means no published page matches.
|
||||
|
||||
@@ -22,6 +22,9 @@ func paged(o obj) obj {
|
||||
// show them.
|
||||
var endpoints = []endpoint{
|
||||
// Account
|
||||
{method: "GET", path: "/api/v1/public/regions", tag: "Public", summary: "Platform regions with their locations", public: true,
|
||||
description: "For websites showing where the platform checks from: no authentication, any origin (CORS), cached for up to a minute. Lists platform regions only; `latitude`/`longitude` are absent for regions without a location, and `online` is set while a checker of the region is connected.",
|
||||
resp: obj{"regions": []publicRegion{}}},
|
||||
{method: "POST", path: "/api/v1/auth/signup", tag: "Account", summary: "Create an account", public: true,
|
||||
description: "Depending on the installation, sign-up is open, limited to the first user, or closed. Where addresses are confirmed, answers `{\"status\": \"verification_sent\"}` and mails a link; the account signs in after confirming. Otherwise starts a session, and `org_name`/`org_slug`, if given, create a first organization. One account per mailbox (+suffixes and Gmail dots count as the same address); a client address may create only a few accounts a day (`429 signup_limit`).",
|
||||
req: signupRequest{}, resp: sessionStarted},
|
||||
@@ -268,6 +271,8 @@ var endpoints = []endpoint{
|
||||
req: regionRequest{}, status: http.StatusCreated, resp: regionView{}},
|
||||
{method: "DELETE", path: "/api/v1/org/regions/:id", tag: "Organization", summary: "Delete an own region", perm: "org.manage", sessionOnly: true,
|
||||
status: http.StatusNoContent},
|
||||
{method: "PATCH", path: "/api/v1/org/regions/:id", tag: "Organization", summary: "Set or remove the location of an own region", perm: "org.manage", sessionOnly: true,
|
||||
description: "Null for both coordinates removes the location.", req: regionLocation{}, status: http.StatusNoContent},
|
||||
{method: "GET", path: "/api/v1/org/agents", tag: "Organization", summary: "List own checkers and status page servers", perm: "org.manage",
|
||||
resp: obj{"agents": []agentView{}}},
|
||||
{method: "POST", path: "/api/v1/org/agents", tag: "Organization", summary: "Create an agent token", perm: "org.manage", sessionOnly: true,
|
||||
@@ -318,6 +323,11 @@ var endpoints = []endpoint{
|
||||
{method: "PUT", path: "/api/v1/admin/checker-network", tag: "Platform", summary: "Let platform checkers check private addresses or not",
|
||||
description: "Unset, they may on self-hosted installations and may not in the cloud edition. Applies from each checker's next poll.",
|
||||
perm: "platform admin", req: checkerNetwork{}, status: http.StatusNoContent},
|
||||
{method: "GET", path: "/api/v1/admin/statuspage-home", tag: "Platform", summary: "The home page linked from the status page servers' error page", perm: "platform admin",
|
||||
resp: statusPageHome{}},
|
||||
{method: "PUT", path: "/api/v1/admin/statuspage-home", tag: "Platform", summary: "Set the home page linked from the status page servers' error page",
|
||||
description: "Visitors of the bare status page domain and of pages that do not exist see an error page with a link to this URL. Empty links none.",
|
||||
perm: "platform admin", req: statusPageHome{}, status: http.StatusNoContent},
|
||||
{method: "GET", path: "/api/v1/admin/identity-providers", tag: "Platform", summary: "Identity providers for signing up and in",
|
||||
description: "With the callback URL to register at each provider. Secrets are never returned.", perm: "platform admin",
|
||||
resp: obj{"providers": []idpView{}, "callback_url": ""}},
|
||||
@@ -361,6 +371,8 @@ var endpoints = []endpoint{
|
||||
req: regionRequest{}, status: http.StatusCreated, resp: regionView{}},
|
||||
{method: "DELETE", path: "/api/v1/admin/regions/:id", tag: "Platform", summary: "Delete a platform region", perm: "platform admin",
|
||||
status: http.StatusNoContent},
|
||||
{method: "PATCH", path: "/api/v1/admin/regions/:id", tag: "Platform", summary: "Set or remove the location of a platform region", perm: "platform admin",
|
||||
description: "Null for both coordinates removes the location.", req: regionLocation{}, status: http.StatusNoContent},
|
||||
{method: "GET", path: "/api/v1/admin/agents", tag: "Platform", summary: "List platform agents", perm: "platform admin",
|
||||
resp: obj{"agents": []agentView{}}},
|
||||
{method: "POST", path: "/api/v1/admin/agents", tag: "Platform", summary: "Create a platform agent token", perm: "platform admin",
|
||||
|
||||
@@ -76,6 +76,7 @@ var auditActions = map[string]string{
|
||||
"DELETE /api/v1/org/groups/:id": "group.delete",
|
||||
"POST /api/v1/org/regions": "region.create",
|
||||
"DELETE /api/v1/org/regions/:id": "region.delete",
|
||||
"PATCH /api/v1/org/regions/:id": "region.update",
|
||||
"POST /api/v1/org/agents": "agent.create",
|
||||
"DELETE /api/v1/org/agents/:id": "agent.delete",
|
||||
"POST /api/v1/org/statuspages": "statuspage.create",
|
||||
@@ -111,6 +112,7 @@ var auditActions = map[string]string{
|
||||
"PUT /api/v1/org/legal/:kind": "org.legal_update",
|
||||
"PUT /api/v1/admin/check-types": "platform.check_types_update",
|
||||
"PUT /api/v1/admin/checker-network": "platform.checker_network_update",
|
||||
"PUT /api/v1/admin/statuspage-home": "platform.statuspage_home_update",
|
||||
"PUT /api/v1/admin/limits": "platform.limits_update",
|
||||
"POST /api/v1/admin/identity-providers": "platform.idp_create",
|
||||
"PUT /api/v1/admin/identity-providers/:id": "platform.idp_update",
|
||||
@@ -128,6 +130,7 @@ var auditActions = map[string]string{
|
||||
"PATCH /api/v1/org/agents/:id": "agent.update",
|
||||
"POST /api/v1/admin/regions": "platform.region_create",
|
||||
"DELETE /api/v1/admin/regions/:id": "platform.region_delete",
|
||||
"PATCH /api/v1/admin/regions/:id": "platform.region_update",
|
||||
"POST /api/v1/admin/agents": "platform.agent_create",
|
||||
"DELETE /api/v1/admin/agents/:id": "platform.agent_delete",
|
||||
}
|
||||
|
||||
+71
-56
@@ -19,6 +19,7 @@ import (
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/google/uuid"
|
||||
"github.com/jackc/pgx/v5"
|
||||
"golang.org/x/sync/errgroup"
|
||||
|
||||
"git.zb-server.de/ZB-Server/uptimesebi/internal/auth"
|
||||
"git.zb-server.de/ZB-Server/uptimesebi/internal/authz"
|
||||
@@ -72,8 +73,10 @@ func (s *Server) dashboard(c *gin.Context) {
|
||||
return
|
||||
}
|
||||
v := web.DashboardView{Counts: map[web.Status]int{}, Empty: true}
|
||||
timer := newStepTimer()
|
||||
if p != nil && me.Policy == "" {
|
||||
data, err := s.loadMonitorData(c.Request.Context(), p, web.RangeByKey(c.Query("range")))
|
||||
timer.done("load")
|
||||
if err != nil {
|
||||
internalError(c, err)
|
||||
return
|
||||
@@ -84,21 +87,14 @@ func (s *Server) dashboard(c *gin.Context) {
|
||||
if !s.dashboardPage(c, &v, data) {
|
||||
return
|
||||
}
|
||||
timer.done("arrange")
|
||||
if err := s.dashboardBars(c.Request.Context(), p, &v, &data); err != nil {
|
||||
internalError(c, err)
|
||||
return
|
||||
}
|
||||
timer.done("bars")
|
||||
v.Range = data.rng.Key
|
||||
var earliest time.Time
|
||||
if err := s.db.Tx(c.Request.Context(), p.scope(), func(q *store.Queries) error {
|
||||
var err error
|
||||
earliest, err = earliestData(c.Request.Context(), q, p.Org.ID, data.now)
|
||||
return err
|
||||
}); err != nil {
|
||||
internalError(c, err)
|
||||
return
|
||||
}
|
||||
v.Ranges = rangeOptions(c, data.rng, earliest, data.now)
|
||||
v.Ranges = rangeOptions(c, data.rng, data.firstCreated, data.now)
|
||||
for _, m := range data.rows {
|
||||
v.Counts[m.Status]++
|
||||
if m.Unchecked {
|
||||
@@ -111,7 +107,11 @@ func (s *Server) dashboard(c *gin.Context) {
|
||||
}
|
||||
slices.SortFunc(v.DeadRegions, func(a, b web.DeadRegion) int { return strings.Compare(a.Name, b.Name) })
|
||||
}
|
||||
timer.done("rest")
|
||||
timer.header(c)
|
||||
web.Render(c, http.StatusOK, web.Dashboard(s.pageFor(c, "console.monitors.title"), me, v))
|
||||
timer.done("render")
|
||||
timer.logIfSlow(c, s.log)
|
||||
}
|
||||
|
||||
// dashboardBars loads the bars of the monitors v shows, and only those.
|
||||
@@ -218,13 +218,28 @@ func (o monitorSort) key(m web.MonitorRow) cursor {
|
||||
}
|
||||
|
||||
func (o monitorSort) sort(ms []web.MonitorRow) {
|
||||
slices.SortFunc(ms, func(a, b web.MonitorRow) int {
|
||||
ka, kb := o.key(a), o.key(b)
|
||||
if c := strings.Compare(ka.S, kb.S); c != 0 {
|
||||
// Keys are worked out once per row, not per comparison, and the rows
|
||||
// moved once: with thousands of monitors sorting was a good part of
|
||||
// the dashboard's time.
|
||||
type keyed struct {
|
||||
key, id string
|
||||
i int
|
||||
}
|
||||
keys := make([]keyed, len(ms))
|
||||
for i, m := range ms {
|
||||
keys[i] = keyed{o.key(m).S, m.ID, i}
|
||||
}
|
||||
slices.SortFunc(keys, func(a, b keyed) int {
|
||||
if c := strings.Compare(a.key, b.key); c != 0 {
|
||||
return c
|
||||
}
|
||||
return strings.Compare(a.ID, b.ID)
|
||||
return strings.Compare(a.id, b.id)
|
||||
})
|
||||
sorted := make([]web.MonitorRow, len(ms))
|
||||
for i, k := range keys {
|
||||
sorted[i] = ms[k.i]
|
||||
}
|
||||
copy(ms, sorted)
|
||||
}
|
||||
|
||||
// dashboardStatuses are the statuses the dashboard counts, in order.
|
||||
@@ -379,6 +394,11 @@ type monitorData struct {
|
||||
regionOf map[uuid.UUID]store.Region
|
||||
rng web.TimeRange
|
||||
now time.Time
|
||||
// firstCreated is when the oldest monitor was created: the monitor
|
||||
// list offers no ranges reaching far before it. (Finding the first
|
||||
// result instead read results of every monitor, slow for large
|
||||
// organizations.)
|
||||
firstCreated time.Time
|
||||
// first is when the monitor of a detail page first reported, from
|
||||
// any region; firstRegion the same per region.
|
||||
first time.Time
|
||||
@@ -423,25 +443,6 @@ func loadFirstData(ctx context.Context, q *store.Queries, org, monitor uuid.UUID
|
||||
return first, perRegion, nil
|
||||
}
|
||||
|
||||
// earliestData finds when any monitor of org first reported, for the
|
||||
// ranges the monitor list offers: to the day if that was over two days
|
||||
// ago, otherwise exactly.
|
||||
func earliestData(ctx context.Context, q *store.Queries, org uuid.UUID, now time.Time) (time.Time, error) {
|
||||
none := func(t time.Time, err error) (time.Time, bool, error) {
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return time.Time{}, false, nil
|
||||
}
|
||||
return t, err == nil, err
|
||||
}
|
||||
recentSince := now.Add(-2 * 24 * time.Hour)
|
||||
daily, ok, err := none(q.EarliestDataDaily(ctx, org))
|
||||
if err != nil || (ok && daily.Before(recentSince)) {
|
||||
return daily, err
|
||||
}
|
||||
exact, _, err := none(q.EarliestDataRecent(ctx, store.EarliestDataRecentParams{OrgID: org, Time: recentSince}))
|
||||
return exact, err
|
||||
}
|
||||
|
||||
// rangeBuckets loads the selected range for the monitors ids.
|
||||
func rangeBuckets(ctx context.Context, q *store.Queries, org uuid.UUID, ids []uuid.UUID, rng web.TimeRange, now time.Time) (map[uuid.UUID][]web.Bucket, error) {
|
||||
out := map[uuid.UUID][]web.Bucket{}
|
||||
@@ -498,39 +499,50 @@ func (s *Server) loadMonitorData(ctx context.Context, p *principal, rng web.Time
|
||||
spans []store.IncidentsSinceRow
|
||||
)
|
||||
var groups []store.MonitorGroup
|
||||
err := s.db.Tx(ctx, p.scope(), func(q *store.Queries) error {
|
||||
// The queries run in parallel: for large organizations each takes a
|
||||
// while, mostly to move its rows.
|
||||
g, gctx := errgroup.WithContext(ctx)
|
||||
tx := func(f func(q *store.Queries) error) {
|
||||
g.Go(func() error { return s.db.Tx(gctx, p.scope(), f) })
|
||||
}
|
||||
tx(func(q *store.Queries) error {
|
||||
var err error
|
||||
if groups, err = q.ListGroups(ctx); err != nil {
|
||||
if groups, err = q.ListGroups(gctx); err != nil {
|
||||
return err
|
||||
}
|
||||
if monitors, err = q.ListMonitors(ctx, p.Org.ID); err != nil {
|
||||
return err
|
||||
}
|
||||
if assigned, err = q.AllMonitorRegions(ctx, p.Org.ID); err != nil {
|
||||
return err
|
||||
}
|
||||
if regions, err = q.ListVisibleRegions(ctx); err != nil {
|
||||
return err
|
||||
}
|
||||
if latest, err = q.LatestResults(ctx, p.Org.ID); err != nil {
|
||||
return err
|
||||
}
|
||||
if open, err = q.OpenIncidents(ctx, p.Org.ID); err != nil {
|
||||
return err
|
||||
}
|
||||
if spans, err = q.IncidentsSince(ctx, store.IncidentsSinceParams{OrgID: p.Org.ID, ResolvedAt: ptr(now.Add(-web.SLAWindows[len(web.SLAWindows)-1].Window))}); err != nil {
|
||||
return err
|
||||
}
|
||||
if d.statuses, err = loadCustomStatuses(ctx, q); err != nil {
|
||||
if monitors, err = q.ListMonitors(gctx, p.Org.ID); err != nil {
|
||||
return err
|
||||
}
|
||||
ids := make([]uuid.UUID, len(monitors))
|
||||
for i, m := range monitors {
|
||||
ids[i] = m.ID
|
||||
}
|
||||
d.maint, err = maintenanceFor(ctx, q, ids)
|
||||
d.maint, err = maintenanceFor(gctx, q, ids)
|
||||
return err
|
||||
})
|
||||
tx(func(q *store.Queries) (err error) {
|
||||
assigned, err = q.AllMonitorRegions(gctx, p.Org.ID)
|
||||
return err
|
||||
})
|
||||
tx(func(q *store.Queries) (err error) {
|
||||
latest, err = q.LatestResults(gctx, p.Org.ID)
|
||||
return err
|
||||
})
|
||||
tx(func(q *store.Queries) error {
|
||||
var err error
|
||||
if regions, err = q.ListVisibleRegions(gctx); err != nil {
|
||||
return err
|
||||
}
|
||||
if open, err = q.OpenIncidents(gctx, p.Org.ID); err != nil {
|
||||
return err
|
||||
}
|
||||
if spans, err = q.IncidentsSince(gctx, store.IncidentsSinceParams{OrgID: p.Org.ID, ResolvedAt: ptr(now.Add(-web.SLAWindows[len(web.SLAWindows)-1].Window))}); err != nil {
|
||||
return err
|
||||
}
|
||||
d.statuses, err = loadCustomStatuses(gctx, q)
|
||||
return err
|
||||
})
|
||||
err := g.Wait()
|
||||
if err != nil {
|
||||
return d, err
|
||||
}
|
||||
@@ -553,6 +565,9 @@ func (s *Server) loadMonitorData(ctx context.Context, p *principal, rng web.Time
|
||||
if m.Enabled {
|
||||
d.usedRegions = append(d.usedRegions, regionsOf[m.ID]...)
|
||||
}
|
||||
if d.firstCreated.IsZero() || m.CreatedAt.Before(d.firstCreated) {
|
||||
d.firstCreated = m.CreatedAt
|
||||
}
|
||||
}
|
||||
slices.SortFunc(d.usedRegions, func(a, b uuid.UUID) int { return strings.Compare(a.String(), b.String()) })
|
||||
d.usedRegions = slices.Compact(d.usedRegions)
|
||||
@@ -924,7 +939,7 @@ func (s *Server) monitorEditor(c *gin.Context, p *principal, page web.Page, me w
|
||||
return nil, err
|
||||
}
|
||||
checked := slices.Contains(assigned, r.ID) || (idParam == "" && i == 0)
|
||||
f.Regions = append(f.Regions, web.RegionOption{ID: r.ID.String(), Name: r.Name, Own: r.OrgID != nil, Checked: checked, Live: live})
|
||||
f.Regions = append(f.Regions, web.RegionOption{ID: r.ID.String(), Name: r.Name, Own: r.OrgID != nil, Checked: checked, Live: live, Lat: r.Latitude, Lon: r.Longitude})
|
||||
}
|
||||
t, err := s.loadGroupTree(ctx, p.scope())
|
||||
if err != nil {
|
||||
|
||||
+4
-13
@@ -651,19 +651,6 @@ func (s *Server) loadUser(ctx context.Context, id uuid.UUID) (store.User, error)
|
||||
return u, err
|
||||
}
|
||||
|
||||
// purgeOrg deletes an organization with everything in it, including check
|
||||
// results and status page server storage, which have no foreign key.
|
||||
func purgeOrg(ctx context.Context, q *store.Queries, org uuid.UUID) error {
|
||||
if err := q.PurgeOrgCheckData(ctx, org); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := q.DeleteOrgStorage(ctx, org); err != nil {
|
||||
return err
|
||||
}
|
||||
_, err := q.DeleteOrg(ctx, org)
|
||||
return err
|
||||
}
|
||||
|
||||
// deleteAccount erases the signed-in user (Art. 17). Organizations the
|
||||
// user is the last owner of go with the account, monitors and all, even
|
||||
// when they have other members: nobody would be left to run them. The user
|
||||
@@ -744,6 +731,9 @@ func (s *Server) eraseAccount(ctx context.Context, u store.User) (orgsDeleted in
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
if orgsDeleted > 0 {
|
||||
s.wakeOrgPurges()
|
||||
}
|
||||
if err := s.sessions.DeleteAllForUser(ctx, u.ID); err != nil {
|
||||
s.log.ErrorContext(ctx, "ending sessions of deleted account failed", "error", err)
|
||||
}
|
||||
@@ -790,6 +780,7 @@ func (s *Server) deleteOrg(c *gin.Context) {
|
||||
internalError(c, err)
|
||||
return
|
||||
}
|
||||
s.wakeOrgPurges()
|
||||
if sess := auth.Current(c); sess != nil {
|
||||
_ = s.sessions.SwitchOrg(ctx, sess, uuid.Nil)
|
||||
}
|
||||
|
||||
@@ -176,6 +176,12 @@ func TestDeleteOrganization(t *testing.T) {
|
||||
})
|
||||
keepOrg := uuid.MustParse(keep.orgID())
|
||||
e.seedResults(t, keepOrg, uuid.MustParse(km["id"].(string)))
|
||||
// Results older than a week are compressed; the purge goes through them
|
||||
// as well.
|
||||
if _, err := e.dbPool.Exec(context.Background(),
|
||||
`SELECT compress_chunk(c, if_not_compressed => true) FROM show_chunks('check_results', older_than => now() - interval '1 day') c`); err != nil {
|
||||
t.Fatalf("compressing chunks: %v", err)
|
||||
}
|
||||
|
||||
admin := e.joinVia(t, owner.invite("a@"+uniq("d")+".test", owner.roleID("admin")))
|
||||
if st, body := admin.do("POST", "/api/v1/org/delete", map[string]any{"slug": slug, "password": password}); st != http.StatusForbidden {
|
||||
@@ -191,17 +197,33 @@ func TestDeleteOrganization(t *testing.T) {
|
||||
t.Fatalf("owner deletes org = %d %v", st, body)
|
||||
}
|
||||
|
||||
// The organization is gone at once, its check data is purged in the
|
||||
// background, chunk by chunk.
|
||||
for query, want := range map[string]int{
|
||||
`SELECT count(*) FROM orgs WHERE id = $1`: 0,
|
||||
`SELECT count(*) FROM monitors WHERE org_id = $1`: 0,
|
||||
`SELECT count(*) FROM check_results WHERE org_id = $1`: 0,
|
||||
`SELECT count(*) FROM check_results_1h WHERE org_id = $1`: 0,
|
||||
`SELECT count(*) FROM audit_events WHERE org_id = $1`: 0,
|
||||
`SELECT count(*) FROM orgs WHERE id = $1`: 0,
|
||||
`SELECT count(*) FROM monitors WHERE org_id = $1`: 0,
|
||||
`SELECT count(*) FROM org_purges WHERE org_id = $1`: 1,
|
||||
} {
|
||||
if got := e.count(t, query, org); got != want {
|
||||
t.Errorf("%s = %d, want %d", query, got, want)
|
||||
}
|
||||
}
|
||||
if err := e.api.PurgeDeletedOrgs(context.Background()); err != nil {
|
||||
t.Fatalf("PurgeDeletedOrgs() = %v", err)
|
||||
}
|
||||
for query, want := range map[string]int{
|
||||
`SELECT count(*) FROM check_results WHERE org_id = $1`: 0,
|
||||
`SELECT count(*) FROM check_results_1h WHERE org_id = $1`: 0,
|
||||
`SELECT count(*) FROM audit_events WHERE org_id = $1`: 0,
|
||||
`SELECT count(*) FROM org_purges WHERE org_id = $1`: 0,
|
||||
} {
|
||||
if got := e.count(t, query, org); got != want {
|
||||
t.Errorf("%s = %d, want %d", query, got, want)
|
||||
}
|
||||
}
|
||||
if e.count(t, `SELECT count(*) FROM check_results WHERE org_id = $1`, keepOrg) != 30 {
|
||||
t.Error("another organization's results were deleted")
|
||||
}
|
||||
if e.count(t, `SELECT count(*) FROM check_results_1h WHERE org_id = $1`, keepOrg) == 0 {
|
||||
t.Error("another organization's aggregates were deleted")
|
||||
}
|
||||
|
||||
@@ -29,6 +29,7 @@ func (s *Server) RunHousekeeping(ctx context.Context) {
|
||||
// policies as owner.
|
||||
s.log.WarnContext(ctx, "applying retention policies failed", "error", err)
|
||||
}
|
||||
go s.runOrgPurges(ctx)
|
||||
tick := time.NewTicker(time.Hour)
|
||||
defer tick.Stop()
|
||||
for {
|
||||
|
||||
@@ -205,7 +205,9 @@ func (s *Server) legalPage(c *gin.Context) {
|
||||
}
|
||||
me = &m
|
||||
}
|
||||
web.Render(c, http.StatusOK, web.LegalPage(s.pageFor(c, web.LegalTitleID(kind)), me, html))
|
||||
p := s.pageFor(c, web.LegalTitleID(kind))
|
||||
p.Meta = s.publicMeta(c, "/legal/"+kind, web.LegalTitleID(kind))
|
||||
web.Render(c, http.StatusOK, web.LegalPage(p, me, html))
|
||||
return
|
||||
}
|
||||
c.Status(http.StatusNotFound)
|
||||
|
||||
@@ -205,6 +205,7 @@ func (s *Server) adminDeleteOrg(c *gin.Context) {
|
||||
return purgeOrg(ctx, q, id)
|
||||
})
|
||||
if moderated(c, err) {
|
||||
s.wakeOrgPurges()
|
||||
c.Status(http.StatusNoContent)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -224,7 +224,11 @@ func (s *Server) listMonitors(c *gin.Context) {
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
latest, err := q.LatestResults(ctx, p.Org.ID)
|
||||
ids := make([]uuid.UUID, len(monitors))
|
||||
for i, m := range monitors {
|
||||
ids[i] = m.ID
|
||||
}
|
||||
latest, err := q.LatestResultsForMonitors(ctx, store.LatestResultsForMonitorsParams{OrgID: p.Org.ID, Ids: ids})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
@@ -0,0 +1,119 @@
|
||||
package api
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"github.com/jackc/pgx/v5"
|
||||
|
||||
"git.zb-server.de/ZB-Server/uptimesebi/internal/store"
|
||||
"git.zb-server.de/ZB-Server/uptimesebi/internal/tenant"
|
||||
)
|
||||
|
||||
// orgPurgeEvery is how often an instance looks for deleted organizations
|
||||
// whose check data is left, besides right after a deletion.
|
||||
const orgPurgeEvery = time.Minute
|
||||
|
||||
// purgeOrg deletes an organization with everything in it at once, except
|
||||
// its check results and aggregates: they carry no foreign key and can run
|
||||
// to gigabytes, more than a request can delete in time, so it queues them
|
||||
// for PurgeDeletedOrgs. Nothing shows them once the organization is gone.
|
||||
func purgeOrg(ctx context.Context, q *store.Queries, org uuid.UUID) error {
|
||||
if err := q.QueueOrgPurge(ctx, org); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := q.DeleteOrgStorage(ctx, org); err != nil {
|
||||
return err
|
||||
}
|
||||
_, err := q.DeleteOrg(ctx, org)
|
||||
return err
|
||||
}
|
||||
|
||||
// wakeOrgPurges has PurgeDeletedOrgs run soon after a deletion instead of
|
||||
// at the next tick.
|
||||
func (s *Server) wakeOrgPurges() {
|
||||
select {
|
||||
case s.orgPurges <- struct{}{}:
|
||||
default:
|
||||
}
|
||||
}
|
||||
|
||||
// runOrgPurges purges the check data of deleted organizations every
|
||||
// orgPurgeEvery and when woken, until ctx ends.
|
||||
func (s *Server) runOrgPurges(ctx context.Context) {
|
||||
tick := time.NewTicker(orgPurgeEvery)
|
||||
defer tick.Stop()
|
||||
for {
|
||||
if err := s.PurgeDeletedOrgs(ctx); err != nil && ctx.Err() == nil {
|
||||
s.log.ErrorContext(ctx, "purging deleted organizations failed", "error", err)
|
||||
}
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return
|
||||
case <-tick.C:
|
||||
case <-s.orgPurges:
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// PurgeDeletedOrgs deletes the check data of deleted organizations a chunk
|
||||
// at a time, each in a transaction of its own, until none is left. An
|
||||
// instance leases an organization while it purges it; if it stops, another
|
||||
// takes over once the lease runs out and repeats the chunks, which then
|
||||
// delete nothing.
|
||||
func (s *Server) PurgeDeletedOrgs(ctx context.Context) error {
|
||||
for ctx.Err() == nil {
|
||||
var org uuid.UUID
|
||||
err := s.db.Tx(ctx, tenant.System(), func(q *store.Queries) error {
|
||||
var err error
|
||||
org, err = q.ClaimOrgPurge(ctx)
|
||||
return err
|
||||
})
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return nil
|
||||
}
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if err := s.purgeOrgCheckData(ctx, org); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return ctx.Err()
|
||||
}
|
||||
|
||||
func (s *Server) purgeOrgCheckData(ctx context.Context, org uuid.UUID) error {
|
||||
start := time.Now()
|
||||
var chunks []string
|
||||
err := s.db.Tx(ctx, tenant.System(), func(q *store.Queries) error {
|
||||
var err error
|
||||
chunks, err = q.OrgCheckDataChunks(ctx)
|
||||
return err
|
||||
})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
var rows int64
|
||||
for _, chunk := range chunks {
|
||||
err := s.db.Tx(ctx, tenant.System(), func(q *store.Queries) error {
|
||||
n, err := q.PurgeOrgCheckChunk(ctx, store.PurgeOrgCheckChunkParams{OrgID: org, Chunk: chunk})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
rows += n
|
||||
return q.ExtendOrgPurge(ctx, org)
|
||||
})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
err = s.db.Tx(ctx, tenant.System(), func(q *store.Queries) error { return q.FinishOrgPurge(ctx, org) })
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
s.log.InfoContext(ctx, "purged check data of deleted organization",
|
||||
"org", org, "rows", rows, "chunks", len(chunks), "duration", time.Since(start).Round(time.Millisecond))
|
||||
return nil
|
||||
}
|
||||
@@ -104,7 +104,9 @@ func (s *Server) loginPage(c *gin.Context) {
|
||||
}
|
||||
allowed := email || len(signupProviders) > 0
|
||||
providers := s.platformButtons(c.Request.Context(), false)
|
||||
web.Render(c, http.StatusOK, web.Login(s.pageFor(c, "auth.login.title"), allowed, next, providers, c.Query("mfa") == "1"))
|
||||
p := s.pageFor(c, "auth.login.title")
|
||||
p.Meta = s.publicMeta(c, "/login", "auth.login.title")
|
||||
web.Render(c, http.StatusOK, web.Login(p, allowed, next, providers, c.Query("mfa") == "1"))
|
||||
}
|
||||
|
||||
// signupOptions tells whether people may sign up with email, and which
|
||||
@@ -141,7 +143,9 @@ func (s *Server) signupPage(c *gin.Context) {
|
||||
internalError(c, err)
|
||||
return
|
||||
}
|
||||
web.Render(c, http.StatusOK, web.Signup(s.pageFor(c, "auth.signup.title"), providers, email, consent))
|
||||
p := s.pageFor(c, "auth.signup.title")
|
||||
p.Meta = s.publicMeta(c, "/signup", "auth.signup.title")
|
||||
web.Render(c, http.StatusOK, web.Signup(p, providers, email, consent))
|
||||
}
|
||||
|
||||
func (s *Server) signupSentPage(c *gin.Context) {
|
||||
@@ -625,7 +629,7 @@ func (s *Server) adminPage(c *gin.Context) {
|
||||
for _, t := range check.Types {
|
||||
types = append(types, web.CheckTypeOption{Type: string(t), Enabled: !off[string(t)]})
|
||||
}
|
||||
web.Render(c, http.StatusOK, web.AdminPage(s.pageFor(c, "admin.title"), me, v, storageView(c, stats), types, s.platformPrivate(ctx), webLimits(s.platformLimits(ctx)), s.idpAdminView(ctx)))
|
||||
web.Render(c, http.StatusOK, web.AdminPage(s.pageFor(c, "admin.title"), me, v, storageView(c, stats), types, s.platformPrivate(ctx), s.statusPageHome(ctx), webLimits(s.platformLimits(ctx)), s.idpAdminView(ctx)))
|
||||
}
|
||||
|
||||
func (s *Server) adminStatusPagesPage(c *gin.Context) {
|
||||
@@ -670,7 +674,7 @@ func (s *Server) buildRegionsView(ctx context.Context, regions []store.Region, a
|
||||
if err != nil {
|
||||
return v, err
|
||||
}
|
||||
wr := web.Region{ID: r.ID.String(), Key: r.Key, Name: r.Name, Platform: r.OrgID == nil, Manageable: manageable(r), Instances: n}
|
||||
wr := web.Region{ID: r.ID.String(), Key: r.Key, Name: r.Name, Platform: r.OrgID == nil, Manageable: manageable(r), Instances: n, Lat: r.Latitude, Lon: r.Longitude}
|
||||
v.Regions = append(v.Regions, wr)
|
||||
if wr.Manageable {
|
||||
v.OwnRegions = append(v.OwnRegions, wr)
|
||||
|
||||
@@ -0,0 +1,82 @@
|
||||
package api
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
|
||||
"git.zb-server.de/ZB-Server/uptimesebi/internal/store"
|
||||
"git.zb-server.de/ZB-Server/uptimesebi/internal/tenant"
|
||||
)
|
||||
|
||||
// publicRegionsTTL is how long an instance serves the platform regions
|
||||
// from memory, so the endpoint costs the database next to nothing however
|
||||
// often a front page asks.
|
||||
const publicRegionsTTL = 30 * time.Second
|
||||
|
||||
// publicRegion is a platform region as anyone may see it. Organizations'
|
||||
// own regions are never listed.
|
||||
type publicRegion struct {
|
||||
Key string `json:"key"`
|
||||
Name string `json:"name"`
|
||||
// Latitude and longitude are absent for regions without a location.
|
||||
Latitude *float64 `json:"latitude,omitempty"`
|
||||
Longitude *float64 `json:"longitude,omitempty"`
|
||||
// Online is set while at least one checker of the region is connected.
|
||||
Online bool `json:"online"`
|
||||
}
|
||||
|
||||
type publicRegionsCache struct {
|
||||
mu sync.Mutex
|
||||
body []byte
|
||||
expires time.Time
|
||||
}
|
||||
|
||||
// listPublicRegions answers without authentication and to any origin, for
|
||||
// a website showing where the platform checks from.
|
||||
func (s *Server) listPublicRegions(c *gin.Context) {
|
||||
c.Header("Access-Control-Allow-Origin", "*")
|
||||
c.Header("Cache-Control", "public, max-age=60")
|
||||
body, err := s.publicRegionsBody(c)
|
||||
if err != nil {
|
||||
internalError(c, err)
|
||||
return
|
||||
}
|
||||
c.Data(http.StatusOK, "application/json; charset=utf-8", body)
|
||||
}
|
||||
|
||||
func (s *Server) publicRegionsBody(c *gin.Context) ([]byte, error) {
|
||||
cache := &s.publicRegions
|
||||
cache.mu.Lock()
|
||||
defer cache.mu.Unlock()
|
||||
if cache.body != nil && time.Now().Before(cache.expires) {
|
||||
return cache.body, nil
|
||||
}
|
||||
ctx := c.Request.Context()
|
||||
var rows []store.Region
|
||||
err := s.db.Tx(ctx, tenant.System(), func(q *store.Queries) error {
|
||||
var err error
|
||||
rows, err = q.ListPlatformRegions(ctx)
|
||||
return err
|
||||
})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
out := make([]publicRegion, len(rows))
|
||||
for i, r := range rows {
|
||||
n, err := s.sched.Instances(ctx, r.ID.String())
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
out[i] = publicRegion{Key: r.Key, Name: r.Name, Latitude: r.Latitude, Longitude: r.Longitude, Online: n > 0}
|
||||
}
|
||||
body, err := json.Marshal(gin.H{"regions": out})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
cache.body, cache.expires = body, time.Now().Add(publicRegionsTTL)
|
||||
return body, nil
|
||||
}
|
||||
@@ -8,6 +8,7 @@ import (
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"github.com/jackc/pgx/v5"
|
||||
)
|
||||
|
||||
func TestTimeRangesAndSLA(t *testing.T) {
|
||||
@@ -53,7 +54,7 @@ func TestTimeRangesAndSLA(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
bars := map[string]int{"1h": 60, "3h": 36, "12h": 48, "24h": 48, "7d": 42, "30d": 60, "90d": 45, "180d": 45, "1y": 52}
|
||||
bars := map[string]int{"1h": 60, "3h": 36, "12h": 48, "24h": 24, "7d": 42, "30d": 60, "90d": 45, "180d": 45, "1y": 52}
|
||||
for key, n := range bars {
|
||||
st, _, html := owner.page("/?range=" + key)
|
||||
if st != http.StatusOK {
|
||||
@@ -99,9 +100,16 @@ func TestRangeAvailabilityAndRegions(t *testing.T) {
|
||||
id := uuid.MustParse(body["id"].(string))
|
||||
org := uuid.MustParse(owner.orgID())
|
||||
|
||||
// Two hours of results: eu always fine, us always failing.
|
||||
// Two hours of results: eu always fine, us always failing. (The
|
||||
// monitor is as old as its results.)
|
||||
ctx := context.Background()
|
||||
now := time.Now()
|
||||
if err := e.asSystem(t, func(tx pgx.Tx) error {
|
||||
_, err := tx.Exec(ctx, `UPDATE monitors SET created_at = $1 WHERE id = $2`, now.Add(-121*time.Minute), id)
|
||||
return err
|
||||
}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
checker := uuid.New()
|
||||
for m := 0; m <= 120; m += 5 {
|
||||
at := now.Add(-time.Duration(m) * time.Minute)
|
||||
|
||||
+86
-8
@@ -28,6 +28,14 @@ type regionView struct {
|
||||
// regions.
|
||||
Own bool `json:"own"`
|
||||
Instances int64 `json:"instances"`
|
||||
// Latitude and longitude place the region on the map; both are absent
|
||||
// for regions without a location.
|
||||
Latitude *float64 `json:"latitude,omitempty"`
|
||||
Longitude *float64 `json:"longitude,omitempty"`
|
||||
}
|
||||
|
||||
func newRegionView(r store.Region, org uuid.UUID, instances int64) regionView {
|
||||
return regionView{ID: r.ID, Key: r.Key, Name: r.Name, Own: r.OrgID != nil && *r.OrgID == org, Instances: instances, Latitude: r.Latitude, Longitude: r.Longitude}
|
||||
}
|
||||
|
||||
func (s *Server) viewRegions(ctx context.Context, rows []store.Region, org uuid.UUID) ([]regionView, error) {
|
||||
@@ -37,7 +45,7 @@ func (s *Server) viewRegions(ctx context.Context, rows []store.Region, org uuid.
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
out[i] = regionView{ID: r.ID, Key: r.Key, Name: r.Name, Own: r.OrgID != nil && *r.OrgID == org, Instances: n}
|
||||
out[i] = newRegionView(r, org, n)
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
@@ -67,6 +75,7 @@ func (s *Server) listOrgRegions(c *gin.Context) {
|
||||
type regionRequest struct {
|
||||
Key string `json:"key" binding:"required,max=40"`
|
||||
Name string `json:"name" binding:"max=100"`
|
||||
regionLocation
|
||||
}
|
||||
|
||||
func (r *regionRequest) normalize() bool {
|
||||
@@ -78,6 +87,20 @@ func (r *regionRequest) normalize() bool {
|
||||
return regionKeyRE.MatchString(r.Key)
|
||||
}
|
||||
|
||||
// regionLocation is where a region's checkers stand; null for both
|
||||
// coordinates means no location.
|
||||
type regionLocation struct {
|
||||
Latitude *float64 `json:"latitude"`
|
||||
Longitude *float64 `json:"longitude"`
|
||||
}
|
||||
|
||||
func (l regionLocation) valid() bool {
|
||||
if l.Latitude == nil || l.Longitude == nil {
|
||||
return l.Latitude == nil && l.Longitude == nil
|
||||
}
|
||||
return *l.Latitude >= -90 && *l.Latitude <= 90 && *l.Longitude >= -180 && *l.Longitude <= 180
|
||||
}
|
||||
|
||||
func (s *Server) createRegion(c *gin.Context, scope tenant.Scope, org *uuid.UUID) {
|
||||
var req regionRequest
|
||||
if !bind(c, &req) {
|
||||
@@ -87,11 +110,15 @@ func (s *Server) createRegion(c *gin.Context, scope tenant.Scope, org *uuid.UUID
|
||||
fail(c, http.StatusUnprocessableEntity, "invalid_region_key")
|
||||
return
|
||||
}
|
||||
if !req.valid() {
|
||||
fail(c, http.StatusUnprocessableEntity, "invalid_location")
|
||||
return
|
||||
}
|
||||
ctx := c.Request.Context()
|
||||
var row store.Region
|
||||
err := s.db.Tx(ctx, scope, func(q *store.Queries) error {
|
||||
var err error
|
||||
row, err = q.CreateRegion(ctx, store.CreateRegionParams{OrgID: org, Key: req.Key, Name: req.Name})
|
||||
row, err = q.CreateRegion(ctx, store.CreateRegionParams{OrgID: org, Key: req.Key, Name: req.Name, Latitude: req.Latitude, Longitude: req.Longitude})
|
||||
return err
|
||||
})
|
||||
if isUniqueViolation(err, "regions_owner_key_key") {
|
||||
@@ -102,7 +129,41 @@ func (s *Server) createRegion(c *gin.Context, scope tenant.Scope, org *uuid.UUID
|
||||
internalError(c, err)
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusCreated, regionView{ID: row.ID, Key: row.Key, Name: row.Name, Own: org != nil})
|
||||
v := newRegionView(row, uuid.Nil, 0)
|
||||
v.Own = org != nil
|
||||
c.JSON(http.StatusCreated, v)
|
||||
}
|
||||
|
||||
// updateRegion sets or removes a region's location.
|
||||
func (s *Server) updateRegion(c *gin.Context, scope tenant.Scope) {
|
||||
id, err := uuid.Parse(c.Param("id"))
|
||||
if err != nil {
|
||||
fail(c, http.StatusNotFound, "not_found")
|
||||
return
|
||||
}
|
||||
var req regionLocation
|
||||
if !bind(c, &req) {
|
||||
return
|
||||
}
|
||||
if !req.valid() {
|
||||
fail(c, http.StatusUnprocessableEntity, "invalid_location")
|
||||
return
|
||||
}
|
||||
ctx := c.Request.Context()
|
||||
var n int64
|
||||
err = s.db.Tx(ctx, scope, func(q *store.Queries) error {
|
||||
n, err = q.UpdateRegionLocation(ctx, store.UpdateRegionLocationParams{ID: id, Latitude: req.Latitude, Longitude: req.Longitude})
|
||||
return err
|
||||
})
|
||||
if err != nil {
|
||||
internalError(c, err)
|
||||
return
|
||||
}
|
||||
if n == 0 {
|
||||
fail(c, http.StatusNotFound, "not_found")
|
||||
return
|
||||
}
|
||||
c.Status(http.StatusNoContent)
|
||||
}
|
||||
|
||||
func (s *Server) deleteRegion(c *gin.Context, scope tenant.Scope) {
|
||||
@@ -141,6 +202,9 @@ func (s *Server) createOrgRegion(c *gin.Context) {
|
||||
// hides platform regions from writes in an org scope.
|
||||
func (s *Server) deleteOrgRegion(c *gin.Context) { s.deleteRegion(c, current(c).scope()) }
|
||||
|
||||
// updateOrgRegion, like deleteOrgRegion, reaches the org's own regions only.
|
||||
func (s *Server) updateOrgRegion(c *gin.Context) { s.updateRegion(c, current(c).scope()) }
|
||||
|
||||
type agentView struct {
|
||||
ID uuid.UUID `json:"id"`
|
||||
Kind string `json:"kind"`
|
||||
@@ -323,11 +387,25 @@ func (s *Server) adminListRegions(c *gin.Context) {
|
||||
func (s *Server) adminCreateRegion(c *gin.Context) { s.createRegion(c, tenant.System(), nil) }
|
||||
|
||||
func (s *Server) adminDeleteRegion(c *gin.Context) {
|
||||
// The system scope could reach org regions; only platform ones are meant.
|
||||
if s.platformRegion(c) {
|
||||
s.deleteRegion(c, tenant.System())
|
||||
}
|
||||
}
|
||||
|
||||
func (s *Server) adminUpdateRegion(c *gin.Context) {
|
||||
if s.platformRegion(c) {
|
||||
s.updateRegion(c, tenant.System())
|
||||
}
|
||||
}
|
||||
|
||||
// platformRegion reports whether the region in the path is a platform one,
|
||||
// answering the request otherwise: the system scope could reach org
|
||||
// regions, but only platform ones are meant.
|
||||
func (s *Server) platformRegion(c *gin.Context) bool {
|
||||
id, err := uuid.Parse(c.Param("id"))
|
||||
if err != nil {
|
||||
fail(c, http.StatusNotFound, "not_found")
|
||||
return
|
||||
return false
|
||||
}
|
||||
ctx := c.Request.Context()
|
||||
var r store.Region
|
||||
@@ -337,13 +415,13 @@ func (s *Server) adminDeleteRegion(c *gin.Context) {
|
||||
})
|
||||
if errors.Is(err, pgx.ErrNoRows) || (err == nil && r.OrgID != nil) {
|
||||
fail(c, http.StatusNotFound, "not_found")
|
||||
return
|
||||
return false
|
||||
}
|
||||
if err != nil {
|
||||
internalError(c, err)
|
||||
return
|
||||
return false
|
||||
}
|
||||
s.deleteRegion(c, tenant.System())
|
||||
return true
|
||||
}
|
||||
|
||||
func (s *Server) adminListAgents(c *gin.Context) { s.listAgents(c, tenant.System(), nil) }
|
||||
|
||||
@@ -2,6 +2,7 @@ package api_test
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
@@ -200,3 +201,129 @@ func TestAgentInstallConsole(t *testing.T) {
|
||||
t.Error("an agent on the platform's release is marked outdated")
|
||||
}
|
||||
}
|
||||
|
||||
func TestRegionLocations(t *testing.T) {
|
||||
e := newEnv(t)
|
||||
_, platformRegion := e.platformChecker(t, uniq("loc-"))
|
||||
|
||||
a := e.browser(t)
|
||||
a.signup("a@"+uniq("a")+".test", uniq("org-a-"))
|
||||
b := e.browser(t)
|
||||
b.signup("b@"+uniq("b")+".test", uniq("org-b-"))
|
||||
|
||||
location := func(br *browser, id string) (any, any) {
|
||||
t.Helper()
|
||||
_, body := br.do("GET", "/api/v1/org/regions", nil)
|
||||
for _, r := range body["regions"].([]any) {
|
||||
if r := r.(map[string]any); r["id"] == id {
|
||||
return r["latitude"], r["longitude"]
|
||||
}
|
||||
}
|
||||
t.Fatalf("region %s not listed", id)
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
st, body := a.do("POST", "/api/v1/org/regions", map[string]any{"key": "berlin", "latitude": 52.52, "longitude": 13.405})
|
||||
if st != http.StatusCreated || body["latitude"] != 52.52 || body["longitude"] != 13.405 {
|
||||
t.Fatalf("create region with location = %d %v", st, body)
|
||||
}
|
||||
berlin := body["id"].(string)
|
||||
plain := a.createRegion("plain")
|
||||
if lat, lon := location(a, plain); lat != nil || lon != nil {
|
||||
t.Errorf("region without location lists %v, %v", lat, lon)
|
||||
}
|
||||
|
||||
for _, tc := range []struct {
|
||||
what string
|
||||
body map[string]any
|
||||
}{
|
||||
{"latitude only", map[string]any{"latitude": 10.0}},
|
||||
{"latitude out of range", map[string]any{"latitude": 91.0, "longitude": 0.0}},
|
||||
{"longitude out of range", map[string]any{"latitude": 0.0, "longitude": -181.0}},
|
||||
} {
|
||||
st, body := a.do("PATCH", "/api/v1/org/regions/"+plain, tc.body)
|
||||
expect(t, tc.what, st, body, http.StatusUnprocessableEntity, "invalid_location")
|
||||
}
|
||||
st, body = a.do("POST", "/api/v1/org/regions", map[string]any{"key": "half", "longitude": 3.0})
|
||||
expect(t, "create with half a location", st, body, http.StatusUnprocessableEntity, "invalid_location")
|
||||
|
||||
st, body = a.do("PATCH", "/api/v1/org/regions/"+plain, map[string]any{"latitude": -33.8688, "longitude": 151.2093})
|
||||
expect(t, "set location", st, body, http.StatusNoContent, "")
|
||||
if lat, lon := location(a, plain); lat != -33.8688 || lon != 151.2093 {
|
||||
t.Errorf("location after PATCH = %v, %v", lat, lon)
|
||||
}
|
||||
st, body = a.do("PATCH", "/api/v1/org/regions/"+berlin, map[string]any{"latitude": nil, "longitude": nil})
|
||||
expect(t, "remove location", st, body, http.StatusNoContent, "")
|
||||
if lat, lon := location(a, berlin); lat != nil || lon != nil {
|
||||
t.Errorf("location after removal = %v, %v", lat, lon)
|
||||
}
|
||||
|
||||
st, body = b.do("PATCH", "/api/v1/org/regions/"+plain, map[string]any{"latitude": 1.0, "longitude": 1.0})
|
||||
expect(t, "other org sets location", st, body, http.StatusNotFound, "not_found")
|
||||
st, body = a.do("PATCH", "/api/v1/org/regions/"+platformRegion, map[string]any{"latitude": 1.0, "longitude": 1.0})
|
||||
expect(t, "org sets platform location", st, body, http.StatusNotFound, "not_found")
|
||||
st, body = a.do("PATCH", "/api/v1/admin/regions/"+platformRegion, map[string]any{"latitude": 1.0, "longitude": 1.0})
|
||||
expect(t, "non-admin sets platform location", st, body, http.StatusForbidden, "forbidden")
|
||||
|
||||
err := tenant.New(e.dbPool).Tx(context.Background(), tenant.Global(), func(q *store.Queries) error {
|
||||
return q.MakeAdmin(context.Background(), a.userIDSelf())
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
st, body = a.do("PATCH", "/api/v1/admin/regions/"+plain, map[string]any{"latitude": 1.0, "longitude": 1.0})
|
||||
expect(t, "admin sets org region location", st, body, http.StatusNotFound, "not_found")
|
||||
st, body = a.do("PATCH", "/api/v1/admin/regions/"+platformRegion, map[string]any{"latitude": 50.1109, "longitude": 8.6821})
|
||||
expect(t, "admin sets platform location", st, body, http.StatusNoContent, "")
|
||||
if lat, lon := location(b, platformRegion); lat != 50.1109 || lon != 8.6821 {
|
||||
t.Errorf("platform location seen by org B = %v, %v", lat, lon)
|
||||
}
|
||||
|
||||
t.Run("public list", func(t *testing.T) {
|
||||
req, _ := http.NewRequest(http.MethodGet, a.base+"/api/v1/public/regions", nil)
|
||||
req.Header.Set("Origin", "https://www.example.org")
|
||||
// The browser's transport trusts the test server; no cookie jar, so no session.
|
||||
resp, err := (&http.Client{Transport: a.hc.Transport}).Do(req)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer func() { _ = resp.Body.Close() }()
|
||||
var body struct {
|
||||
Regions []map[string]any `json:"regions"`
|
||||
}
|
||||
if err := json.NewDecoder(resp.Body).Decode(&body); err != nil || resp.StatusCode != http.StatusOK {
|
||||
t.Fatalf("GET public regions = %d %v", resp.StatusCode, err)
|
||||
}
|
||||
if got := resp.Header.Get("Access-Control-Allow-Origin"); got != "*" {
|
||||
t.Errorf("CORS header = %q, want *", got)
|
||||
}
|
||||
var found map[string]any
|
||||
for _, r := range body.Regions {
|
||||
if r["name"] == "Office plain" || r["key"] == "berlin" {
|
||||
t.Errorf("public list shows an org region: %v", r)
|
||||
}
|
||||
if _, leaked := r["id"]; leaked {
|
||||
t.Errorf("public list exposes region ids: %v", r)
|
||||
}
|
||||
if r["latitude"] == 50.1109 {
|
||||
found = r
|
||||
}
|
||||
}
|
||||
if _, isBool := found["online"].(bool); found == nil || found["longitude"] != 8.6821 || !isBool {
|
||||
t.Errorf("platform region in public list = %v, want its location and online state", found)
|
||||
}
|
||||
})
|
||||
|
||||
_, _, html := a.page("/monitors/new")
|
||||
if !strings.Contains(html, `data-region-map="select"`) || !strings.Contains(html, `data-lat="50.1109"`) || !strings.Contains(html, `data-lat="-33.8688"`) {
|
||||
t.Errorf("monitor form lacks the region map or markers")
|
||||
}
|
||||
_, _, html = b.page("/monitors/new")
|
||||
if !strings.Contains(html, `data-region-map="select"`) || strings.Contains(html, `data-lat="-33.8688"`) {
|
||||
t.Errorf("org B monitor form: want the platform marker only")
|
||||
}
|
||||
_, _, html = a.page("/settings/regions")
|
||||
if !strings.Contains(html, `data-region-map="edit"`) || !strings.Contains(html, `data-location-toggle="location-`+plain+`"`) {
|
||||
t.Errorf("regions page lacks the map or the location form")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,121 @@
|
||||
package api
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"net/url"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
|
||||
"git.zb-server.de/ZB-Server/uptimesebi/internal/i18n"
|
||||
"git.zb-server.de/ZB-Server/uptimesebi/internal/ogimage"
|
||||
"git.zb-server.de/ZB-Server/uptimesebi/internal/web"
|
||||
)
|
||||
|
||||
// indexable reports whether search engines may list the public pages.
|
||||
// Self-hosted installations keep their sign-in out of search results.
|
||||
func (s *Server) indexable() bool { return s.cloud() }
|
||||
|
||||
// publicMeta describes a public page at path, such as the sign-in, for
|
||||
// search engines and link previews; nil where pages are not indexed.
|
||||
func (s *Server) publicMeta(c *gin.Context, path, titleID string) *web.PageMeta {
|
||||
if !s.indexable() {
|
||||
return nil
|
||||
}
|
||||
ctx := c.Request.Context()
|
||||
lang := i18n.Lang(ctx)
|
||||
chosen := s.catalog.IsSupported(c.Query("lang"))
|
||||
title := i18n.T(ctx, titleID) + " · UptimeSebi"
|
||||
image := web.LangURL(s.cfg.PublicURL+"/og.png", lang)
|
||||
return web.NewPageMeta(title, i18n.T(ctx, "meta.app_description"), s.cfg.PublicURL+path, image, "UptimeSebi", lang, chosen, s.catalog.Supported())
|
||||
}
|
||||
|
||||
// appImages keeps the app's preview image per language.
|
||||
type appImages struct {
|
||||
mu sync.Mutex
|
||||
images map[string][]byte
|
||||
}
|
||||
|
||||
// appOGImage serves the preview image of the app's public pages.
|
||||
func (s *Server) appOGImage(c *gin.Context) {
|
||||
l := s.catalog.Match(c.Query("lang"), c.GetHeader("Accept-Language"))
|
||||
ctx := i18n.NewContext(c.Request.Context(), l)
|
||||
s.ogImages.mu.Lock()
|
||||
defer s.ogImages.mu.Unlock()
|
||||
png, ok := s.ogImages.images[l.Lang()]
|
||||
if !ok {
|
||||
host := s.cfg.PublicURL
|
||||
if u, err := url.Parse(host); err == nil {
|
||||
host = u.Host
|
||||
}
|
||||
var err error
|
||||
png, err = ogimage.Render(ogimage.Card{
|
||||
Title: i18n.T(ctx, "meta.app_card_title"),
|
||||
Subtitle: i18n.T(ctx, "meta.app_card_subtitle"),
|
||||
Footer: host,
|
||||
Accent: ogimage.Up,
|
||||
})
|
||||
if err != nil {
|
||||
internalError(c, err)
|
||||
return
|
||||
}
|
||||
if s.ogImages.images == nil {
|
||||
s.ogImages.images = map[string][]byte{}
|
||||
}
|
||||
s.ogImages.images[l.Lang()] = png
|
||||
}
|
||||
c.Header("Cache-Control", "public, max-age=86400")
|
||||
c.Data(http.StatusOK, "image/png", png)
|
||||
}
|
||||
|
||||
// robotsTxt lets crawlers read the sign-in, sign-up and legal pages and
|
||||
// nothing else; self-hosted installations turn them away entirely.
|
||||
func (s *Server) robotsTxt(c *gin.Context) {
|
||||
var b strings.Builder
|
||||
b.WriteString("User-agent: *\n")
|
||||
if s.indexable() {
|
||||
for _, p := range []string{"/login", "/signup", "/legal/", "/og.png", "/static/"} {
|
||||
b.WriteString("Allow: " + p + "\n")
|
||||
}
|
||||
}
|
||||
b.WriteString("Disallow: /\n")
|
||||
if s.indexable() {
|
||||
b.WriteString("\nSitemap: " + s.cfg.PublicURL + "/sitemap.xml\n")
|
||||
}
|
||||
c.Header("Cache-Control", "public, max-age=3600")
|
||||
c.Data(http.StatusOK, "text/plain; charset=utf-8", []byte(b.String()))
|
||||
}
|
||||
|
||||
// sitemapXML lists the public pages with their language versions.
|
||||
func (s *Server) sitemapXML(c *gin.Context) {
|
||||
if !s.indexable() {
|
||||
c.Status(http.StatusNotFound)
|
||||
return
|
||||
}
|
||||
ctx := c.Request.Context()
|
||||
paths := []string{"/login"}
|
||||
if email, providers, err := s.signupOptions(ctx); err != nil {
|
||||
internalError(c, err)
|
||||
return
|
||||
} else if email || len(providers) > 0 {
|
||||
paths = append(paths, "/signup")
|
||||
}
|
||||
for _, d := range s.platformLegalDocs(ctx) {
|
||||
if d.URL == "" {
|
||||
paths = append(paths, "/legal/"+d.Kind)
|
||||
}
|
||||
}
|
||||
var urls []string
|
||||
for _, p := range paths {
|
||||
urls = append(urls, s.cfg.PublicURL+p)
|
||||
}
|
||||
body, err := web.Sitemap(urls, s.catalog.Supported(), time.Time{})
|
||||
if err != nil {
|
||||
internalError(c, err)
|
||||
return
|
||||
}
|
||||
c.Header("Cache-Control", "public, max-age=3600")
|
||||
c.Data(http.StatusOK, "application/xml; charset=utf-8", body)
|
||||
}
|
||||
@@ -0,0 +1,81 @@
|
||||
package api_test
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"io"
|
||||
"net/http"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"git.zb-server.de/ZB-Server/uptimesebi/internal/config"
|
||||
)
|
||||
|
||||
func (b *browser) raw(path string) (int, http.Header, []byte) {
|
||||
b.t.Helper()
|
||||
resp, err := b.hc.Get(b.base + path)
|
||||
if err != nil {
|
||||
b.t.Fatalf("GET %s failed: %v", path, err)
|
||||
}
|
||||
defer func() { _ = resp.Body.Close() }()
|
||||
body, _ := io.ReadAll(resp.Body)
|
||||
return resp.StatusCode, resp.Header, body
|
||||
}
|
||||
|
||||
func TestPublicPagesForSearchEngines(t *testing.T) {
|
||||
const publicURL = "https://app.example.test"
|
||||
cloud := newEnvWith(t, func(c *config.API) {
|
||||
c.Edition, c.SignupVerify, c.PublicURL = config.EditionCloud, "off", publicURL
|
||||
})
|
||||
b := cloud.browser(t)
|
||||
|
||||
_, _, html := b.page("/login?next=/monitors&lang=de")
|
||||
for _, want := range []string{
|
||||
`<link rel="canonical" href="` + publicURL + `/login?lang=de">`,
|
||||
`<link rel="alternate" hreflang="en" href="` + publicURL + `/login?lang=en">`,
|
||||
`<link rel="alternate" hreflang="x-default" href="` + publicURL + `/login">`,
|
||||
`<meta property="og:image" content="` + publicURL + `/og.png?lang=de">`,
|
||||
`<meta name="description" content="UptimeSebi überwacht`,
|
||||
`<html lang="de">`,
|
||||
} {
|
||||
if !strings.Contains(html, want) {
|
||||
t.Errorf("login page lacks %s", want)
|
||||
}
|
||||
}
|
||||
if strings.Contains(html, "noindex") {
|
||||
t.Errorf("login page is noindex in the cloud edition")
|
||||
}
|
||||
if _, _, html := b.page("/signup"); !strings.Contains(html, `<link rel="canonical" href="`+publicURL+`/signup">`) {
|
||||
t.Errorf("signup page lacks its canonical address")
|
||||
}
|
||||
|
||||
_, _, robots := b.raw("/robots.txt")
|
||||
if !strings.Contains(string(robots), "Allow: /login\n") || !strings.Contains(string(robots), "Disallow: /\n") || !strings.Contains(string(robots), "Sitemap: "+publicURL+"/sitemap.xml") {
|
||||
t.Errorf("robots.txt = %q", robots)
|
||||
}
|
||||
code, _, sm := b.raw("/sitemap.xml")
|
||||
if code != http.StatusOK || !strings.Contains(string(sm), "<loc>"+publicURL+"/signup</loc>") || !strings.Contains(string(sm), `hreflang="de" href="`+publicURL+`/login?lang=de"`) {
|
||||
t.Errorf("sitemap = %d %s", code, sm)
|
||||
}
|
||||
code, h, png := b.raw("/og.png?lang=en")
|
||||
if code != http.StatusOK || h.Get("Content-Type") != "image/png" || !bytes.HasPrefix(png, []byte("\x89PNG")) {
|
||||
t.Errorf("preview image = %d %s", code, h.Get("Content-Type"))
|
||||
}
|
||||
|
||||
// Signed in, the console stays out of search engines.
|
||||
b.signup("seo@"+uniq("seo")+".test", uniq("seo-"))
|
||||
if _, _, html := b.page("/"); !strings.Contains(html, `<meta name="robots" content="noindex, nofollow">`) || strings.Contains(html, "og:title") {
|
||||
t.Errorf("console page is indexable")
|
||||
}
|
||||
|
||||
// Self-hosted installations keep everything out.
|
||||
self := newEnv(t).browser(t)
|
||||
if _, _, html := self.page("/login"); !strings.Contains(html, "noindex") || strings.Contains(html, "canonical") {
|
||||
t.Errorf("self-hosted login page is indexable")
|
||||
}
|
||||
if _, _, robots := self.raw("/robots.txt"); string(robots) != "User-agent: *\nDisallow: /\n" {
|
||||
t.Errorf("self-hosted robots.txt = %q", robots)
|
||||
}
|
||||
if code, _, _ := self.raw("/sitemap.xml"); code != http.StatusNotFound {
|
||||
t.Errorf("self-hosted sitemap = %d, want 404", code)
|
||||
}
|
||||
}
|
||||
+37
-15
@@ -31,20 +31,22 @@ const localeCookie = "lang"
|
||||
|
||||
// Server holds the dependencies shared by all handlers.
|
||||
type Server struct {
|
||||
cfg config.API
|
||||
log *slog.Logger
|
||||
db *tenant.DB
|
||||
rdb redis.UniversalClient
|
||||
keys *sealed.Keyring
|
||||
catalog *i18n.Catalog
|
||||
sessions *auth.Sessions
|
||||
limiter *auth.Limiter
|
||||
totp *auth.TOTPVerifier
|
||||
sso *sso.Client
|
||||
sched *schedule.Scheduler
|
||||
eval *evaluate.Evaluator
|
||||
smtp *notify.SMTP
|
||||
legal *versioned[[]agentapi.LegalDoc]
|
||||
// orgPurges wakes runOrgPurges after an organization was deleted.
|
||||
orgPurges chan struct{}
|
||||
cfg config.API
|
||||
log *slog.Logger
|
||||
db *tenant.DB
|
||||
rdb redis.UniversalClient
|
||||
keys *sealed.Keyring
|
||||
catalog *i18n.Catalog
|
||||
sessions *auth.Sessions
|
||||
limiter *auth.Limiter
|
||||
totp *auth.TOTPVerifier
|
||||
sso *sso.Client
|
||||
sched *schedule.Scheduler
|
||||
eval *evaluate.Evaluator
|
||||
smtp *notify.SMTP
|
||||
legal *versioned[[]agentapi.LegalDoc]
|
||||
// consent caches the versions of the documents accounts accept.
|
||||
consent *versioned[map[string]int64]
|
||||
// checkTypes caches the check types switched off platform-wide.
|
||||
@@ -56,6 +58,8 @@ type Server struct {
|
||||
limits *versioned[Limits]
|
||||
// support caches how the platform runs support tickets.
|
||||
support *versioned[supportSettings]
|
||||
// pageHome caches the home page the status page servers link.
|
||||
pageHome *versioned[string]
|
||||
// draining, once closed, ends the long polls of checkers.
|
||||
draining <-chan struct{}
|
||||
// handler serves the requests agents send over their streams.
|
||||
@@ -63,6 +67,11 @@ type Server struct {
|
||||
// snapshots lets status page servers asking for the same page at once
|
||||
// share one build of it.
|
||||
snapshots singleflight.Group
|
||||
|
||||
// publicRegions caches the answer of the public region list.
|
||||
publicRegions publicRegionsCache
|
||||
// ogImages keeps the preview image of the public pages.
|
||||
ogImages appImages
|
||||
}
|
||||
|
||||
// Deps are the external resources a Server needs.
|
||||
@@ -80,6 +89,7 @@ func New(cfg config.API, d Deps) *Server {
|
||||
allowPrivate := cfg.SSOAllowPrivate()
|
||||
mail, _ := notify.ParseSMTP(cfg.SMTPURL)
|
||||
return &Server{
|
||||
orgPurges: make(chan struct{}, 1),
|
||||
eval: evaluate.New(d.Redis),
|
||||
smtp: mail,
|
||||
cfg: cfg,
|
||||
@@ -99,6 +109,7 @@ func New(cfg config.API, d Deps) *Server {
|
||||
checkerNet: newVersioned[bool]("checker-network"),
|
||||
limits: newVersioned[Limits]("limits"),
|
||||
support: newVersioned[supportSettings]("support"),
|
||||
pageHome: newVersioned[string]("statuspage-home"),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -121,6 +132,11 @@ func (s *Server) Mount(r gin.IRouter) {
|
||||
g := r.Group("/", s.sessions.Load(), s.localize(), auth.CSRF(), s.audit(), s.accountGate())
|
||||
|
||||
r.GET("/api/openapi.json", s.openAPIJSON)
|
||||
// Public data for websites: no session, no CSRF.
|
||||
r.GET("/api/v1/public/regions", s.listPublicRegions)
|
||||
r.GET("/robots.txt", s.robotsTxt)
|
||||
r.GET("/sitemap.xml", s.sitemapXML)
|
||||
r.GET("/og.png", s.appOGImage)
|
||||
r.GET("/install.sh", s.installScript)
|
||||
g.GET("/api/docs", s.apiDocsPage)
|
||||
|
||||
@@ -197,6 +213,7 @@ func (s *Server) Mount(r gin.IRouter) {
|
||||
org.GET("/regions", s.listOrgRegions)
|
||||
org.POST("/regions", sessionOnly(), can(authz.OrgManage), s.createOrgRegion)
|
||||
org.DELETE("/regions/:id", sessionOnly(), can(authz.OrgManage), s.deleteOrgRegion)
|
||||
org.PATCH("/regions/:id", sessionOnly(), can(authz.OrgManage), s.updateOrgRegion)
|
||||
org.GET("/agents", can(authz.OrgManage), s.listOrgAgents)
|
||||
org.POST("/agents", sessionOnly(), can(authz.OrgManage), s.createOrgAgent)
|
||||
org.PATCH("/agents/:id", sessionOnly(), can(authz.OrgManage), s.updateOrgAgent)
|
||||
@@ -224,11 +241,14 @@ func (s *Server) Mount(r gin.IRouter) {
|
||||
admin.PUT("/users/:id/suspension", s.adminSuspendUser)
|
||||
admin.DELETE("/users/:id", s.adminDeleteUser)
|
||||
admin.PUT("/checker-network", s.adminSetCheckerNetwork)
|
||||
admin.GET("/statuspage-home", s.adminGetStatusPageHome)
|
||||
admin.PUT("/statuspage-home", s.adminSetStatusPageHome)
|
||||
admin.GET("/legal", s.adminListLegal)
|
||||
admin.PUT("/legal/:kind", s.adminSaveLegal)
|
||||
admin.GET("/regions", s.adminListRegions)
|
||||
admin.POST("/regions", s.adminCreateRegion)
|
||||
admin.DELETE("/regions/:id", s.adminDeleteRegion)
|
||||
admin.PATCH("/regions/:id", s.adminUpdateRegion)
|
||||
admin.GET("/support/settings", s.adminGetSupportSettings)
|
||||
admin.PUT("/support/settings", s.adminSetSupportSettings)
|
||||
admin.GET("/support/tickets", s.adminListTickets)
|
||||
@@ -321,7 +341,9 @@ func (s *Server) localize() gin.HandlerFunc {
|
||||
pref = sess.Locale
|
||||
}
|
||||
cookie, _ := c.Cookie(localeCookie)
|
||||
l := s.catalog.Match(pref, cookie, c.GetHeader("Accept-Language"))
|
||||
// ?lang= shows a page in that language, so each language of the
|
||||
// public pages has an address of its own.
|
||||
l := s.catalog.Match(c.Query("lang"), pref, cookie, c.GetHeader("Accept-Language"))
|
||||
c.Request = c.Request.WithContext(i18n.NewContext(c.Request.Context(), l))
|
||||
c.Header("Content-Language", l.Lang())
|
||||
c.Header("Vary", "Accept-Language, Cookie")
|
||||
|
||||
@@ -256,7 +256,7 @@ func (s *Server) importStatusPageGroups(c *gin.Context) {
|
||||
pageID := uuid.MustParse(c.Param("id"))
|
||||
p := current(c)
|
||||
ctx := c.Request.Context()
|
||||
var created []store.StatusPageGroup
|
||||
var created []pageGroupView
|
||||
err := s.db.Tx(ctx, p.scope(), func(q *store.Queries) error {
|
||||
if _, err := q.GetStatusPage(ctx, pageID); err != nil {
|
||||
return err
|
||||
@@ -290,54 +290,66 @@ func (s *Server) importStatusPageGroups(c *gin.Context) {
|
||||
if err := q.ClearStatusPageGroups(ctx, pageID); err != nil {
|
||||
return err
|
||||
}
|
||||
mapped := map[uuid.UUID]store.StatusPageGroup{}
|
||||
var createErr error
|
||||
// Large organizations have thousands of monitors and hundreds of
|
||||
// groups, so both are written in a few statements: the groups one
|
||||
// level of nesting at a time, as parents must exist before their
|
||||
// children, the monitors all at once.
|
||||
mapped := map[uuid.UUID]pageGroupView{}
|
||||
var levels []store.CreateStatusPageGroupsParams
|
||||
posByParent := map[uuid.UUID]int32{}
|
||||
tree.walk(func(g store.MonitorGroup, _ int) {
|
||||
if createErr != nil || !needed[g.ID] {
|
||||
tree.walk(func(g store.MonitorGroup, depth int) {
|
||||
if !needed[g.ID] {
|
||||
return
|
||||
}
|
||||
var parentKey uuid.UUID
|
||||
var parentID *uuid.UUID
|
||||
if g.ParentID != nil {
|
||||
if parent, ok := mapped[*g.ParentID]; ok {
|
||||
pid := parent.ID
|
||||
parentID = &pid
|
||||
parentKey = pid
|
||||
}
|
||||
}
|
||||
var parentKey uuid.UUID
|
||||
if parentID != nil {
|
||||
parentKey = *parentID
|
||||
}
|
||||
pos := posByParent[parentKey]
|
||||
posByParent[parentKey] = pos + 1
|
||||
row, err := q.CreateStatusPageGroup(ctx, store.CreateStatusPageGroupParams{
|
||||
PageID: pageID,
|
||||
OrgID: p.Org.ID,
|
||||
ParentID: parentID,
|
||||
Name: g.Name,
|
||||
Position: pos,
|
||||
})
|
||||
if err != nil {
|
||||
createErr = err
|
||||
return
|
||||
}
|
||||
row := pageGroupView{ID: uuid.New(), Name: g.Name, ParentID: parentID, Position: pos}
|
||||
mapped[g.ID] = row
|
||||
created = append(created, row)
|
||||
for len(levels) <= depth {
|
||||
levels = append(levels, store.CreateStatusPageGroupsParams{PageID: pageID, OrgID: p.Org.ID})
|
||||
}
|
||||
l := &levels[depth]
|
||||
l.Ids = append(l.Ids, row.ID)
|
||||
l.ParentIds = append(l.ParentIds, parentKey)
|
||||
l.Names = append(l.Names, row.Name)
|
||||
l.Positions = append(l.Positions, row.Position)
|
||||
})
|
||||
if createErr != nil {
|
||||
return createErr
|
||||
for _, l := range levels {
|
||||
if len(l.Ids) == 0 {
|
||||
continue
|
||||
}
|
||||
if err := q.CreateStatusPageGroups(ctx, l); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
set := store.SetStatusPageMonitorGroupsParams{PageID: pageID}
|
||||
for _, m := range listed {
|
||||
var gid *uuid.UUID
|
||||
var gid uuid.UUID
|
||||
section := ""
|
||||
if m.MonitorGroupID != nil {
|
||||
if g, ok := mapped[*m.MonitorGroupID]; ok {
|
||||
id := g.ID
|
||||
gid = &id
|
||||
gid = g.ID
|
||||
section = g.Name
|
||||
}
|
||||
}
|
||||
if err := q.SetStatusPageMonitorGroup(ctx, store.SetStatusPageMonitorGroupParams{
|
||||
PageID: pageID, MonitorID: m.MonitorID, GroupID: gid, Section: section,
|
||||
}); err != nil {
|
||||
set.MonitorIds = append(set.MonitorIds, m.MonitorID)
|
||||
set.GroupIds = append(set.GroupIds, gid)
|
||||
set.Sections = append(set.Sections, section)
|
||||
}
|
||||
if len(set.MonitorIds) > 0 {
|
||||
if err := q.SetStatusPageMonitorGroups(ctx, set); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
@@ -351,11 +363,10 @@ func (s *Server) importStatusPageGroups(c *gin.Context) {
|
||||
internalError(c, err)
|
||||
return
|
||||
}
|
||||
out := make([]pageGroupView, 0, len(created))
|
||||
for _, g := range created {
|
||||
out = append(out, pageGroupView{ID: g.ID, Name: g.Name, ParentID: g.ParentID, Position: g.Position})
|
||||
if created == nil {
|
||||
created = []pageGroupView{}
|
||||
}
|
||||
c.JSON(http.StatusOK, gin.H{"groups": out})
|
||||
c.JSON(http.StatusOK, gin.H{"groups": created})
|
||||
}
|
||||
|
||||
// resolvePageMonitorGroup returns the status page group ID and section label
|
||||
|
||||
@@ -0,0 +1,77 @@
|
||||
package api
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"net/http"
|
||||
"strings"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/jackc/pgx/v5"
|
||||
|
||||
"git.zb-server.de/ZB-Server/uptimesebi/internal/store"
|
||||
"git.zb-server.de/ZB-Server/uptimesebi/internal/tenant"
|
||||
)
|
||||
|
||||
// The status page servers answer visitors of pages that do not exist, and
|
||||
// of their bare domain, with a page linking the platform's home page.
|
||||
|
||||
const settingStatusPageHome = "statuspage_home"
|
||||
|
||||
type statusPageHome struct {
|
||||
// URL is the home page linked from the status page servers' error
|
||||
// page; empty links none.
|
||||
URL string `json:"url" binding:"max=2000"`
|
||||
}
|
||||
|
||||
func (s *Server) statusPageHome(ctx context.Context) string {
|
||||
v, err := s.pageHome.get(ctx, s.rdb, func(ctx context.Context) (string, error) {
|
||||
var v statusPageHome
|
||||
err := s.db.Tx(ctx, tenant.System(), func(q *store.Queries) error {
|
||||
raw, err := q.GetPlatformSetting(ctx, settingStatusPageHome)
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return nil
|
||||
}
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return json.Unmarshal(raw, &v)
|
||||
})
|
||||
return v.URL, err
|
||||
})
|
||||
if err != nil {
|
||||
s.log.WarnContext(ctx, "loading the status page home failed", "error", err)
|
||||
return ""
|
||||
}
|
||||
return v
|
||||
}
|
||||
|
||||
func (s *Server) adminGetStatusPageHome(c *gin.Context) {
|
||||
c.JSON(http.StatusOK, statusPageHome{URL: s.statusPageHome(c.Request.Context())})
|
||||
}
|
||||
|
||||
func (s *Server) adminSetStatusPageHome(c *gin.Context) {
|
||||
var req statusPageHome
|
||||
if !bind(c, &req) {
|
||||
return
|
||||
}
|
||||
req.URL = strings.TrimSpace(req.URL)
|
||||
if req.URL != "" && !validLegalURL(req.URL) {
|
||||
fail(c, http.StatusUnprocessableEntity, "invalid_legal_url")
|
||||
return
|
||||
}
|
||||
ctx := c.Request.Context()
|
||||
raw, _ := json.Marshal(req)
|
||||
auditDetail(c, "url", req.URL)
|
||||
if err := s.db.Tx(ctx, tenant.System(), func(q *store.Queries) error {
|
||||
return q.SetPlatformSetting(ctx, store.SetPlatformSettingParams{Key: settingStatusPageHome, Value: raw})
|
||||
}); err != nil {
|
||||
internalError(c, err)
|
||||
return
|
||||
}
|
||||
if err := s.pageHome.bump(ctx, s.rdb); err != nil {
|
||||
s.log.ErrorContext(ctx, "announcing the status page home failed", "error", err)
|
||||
}
|
||||
c.Status(http.StatusNoContent)
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
package api_test
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/http"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"git.zb-server.de/ZB-Server/uptimesebi/internal/store"
|
||||
"git.zb-server.de/ZB-Server/uptimesebi/internal/tenant"
|
||||
)
|
||||
|
||||
func TestStatusPageHome(t *testing.T) {
|
||||
e := newEnv(t)
|
||||
admin := e.browser(t)
|
||||
admin.signup("a@"+uniq("home")+".test", uniq("home-"))
|
||||
if err := tenant.New(e.dbPool).Tx(context.Background(), tenant.Global(), func(q *store.Queries) error {
|
||||
return q.MakeAdmin(context.Background(), admin.userIDSelf())
|
||||
}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() { admin.do("PUT", "/api/v1/admin/statuspage-home", map[string]any{"url": ""}) })
|
||||
pages := e.statuspageClient(t, nil)
|
||||
|
||||
st, body := admin.do("PUT", "/api/v1/admin/statuspage-home", map[string]any{"url": "javascript:alert(1)"})
|
||||
expect(t, "script link", st, body, http.StatusUnprocessableEntity, "invalid_legal_url")
|
||||
if st, body := admin.do("PUT", "/api/v1/admin/statuspage-home", map[string]any{"url": " https://example.test/ "}); st != http.StatusNoContent {
|
||||
t.Fatalf("set home = %d %v", st, body)
|
||||
}
|
||||
if _, body := admin.do("GET", "/api/v1/admin/statuspage-home", nil); body["url"] != "https://example.test/" {
|
||||
t.Errorf("home = %v", body)
|
||||
}
|
||||
index, err := pages.Pages(context.Background())
|
||||
if err != nil || index.HomeURL != "https://example.test/" {
|
||||
t.Errorf("page index home = %q %v", index.HomeURL, err)
|
||||
}
|
||||
if _, _, html := admin.page("/admin"); !strings.Contains(html, `value="https://example.test/"`) {
|
||||
t.Error("the admin page does not show the home page")
|
||||
}
|
||||
|
||||
owner := e.browser(t)
|
||||
owner.signup("o@"+uniq("home")+".test", uniq("home-"))
|
||||
if st, _ := owner.do("PUT", "/api/v1/admin/statuspage-home", map[string]any{"url": "https://evil.test/"}); st != http.StatusForbidden {
|
||||
t.Errorf("non-admin sets the home page = %d, want 403", st)
|
||||
}
|
||||
}
|
||||
@@ -461,7 +461,7 @@ func (s *Server) agentPageIndex(c *gin.Context) {
|
||||
for i, r := range rows {
|
||||
out[i] = agentapi.PageRef{Slug: r.Slug, Host: r.Host}
|
||||
}
|
||||
c.JSON(http.StatusOK, gin.H{"pages": out})
|
||||
c.JSON(http.StatusOK, agentapi.PageIndex{Pages: out, HomeURL: s.statusPageHome(ctx)})
|
||||
}
|
||||
|
||||
type statusPageRequest struct {
|
||||
|
||||
@@ -205,7 +205,8 @@ func TestStatusPages(t *testing.T) {
|
||||
own := e.statuspageClient(t, &org)
|
||||
lists := func(c *agentapi.Client) bool {
|
||||
t.Helper()
|
||||
refs, err := c.Pages(context.Background())
|
||||
index, err := c.Pages(context.Background())
|
||||
refs := index.Pages
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
@@ -0,0 +1,61 @@
|
||||
package api
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
// slowPage is when a console page logs how long its steps took.
|
||||
const slowPage = time.Second
|
||||
|
||||
// stepTimer measures the steps of a request. It reports them to the
|
||||
// browser in a Server-Timing header and, when the request was slow, in
|
||||
// the log.
|
||||
type stepTimer struct {
|
||||
start, last time.Time
|
||||
steps []step
|
||||
}
|
||||
|
||||
type step struct {
|
||||
name string
|
||||
d time.Duration
|
||||
}
|
||||
|
||||
func newStepTimer() *stepTimer {
|
||||
now := time.Now()
|
||||
return &stepTimer{start: now, last: now}
|
||||
}
|
||||
|
||||
// done ends the step name.
|
||||
func (t *stepTimer) done(name string) {
|
||||
now := time.Now()
|
||||
t.steps = append(t.steps, step{name, now.Sub(t.last)})
|
||||
t.last = now
|
||||
}
|
||||
|
||||
// header sets the Server-Timing header of the steps so far; call it
|
||||
// before the body is written.
|
||||
func (t *stepTimer) header(c *gin.Context) {
|
||||
parts := make([]string, len(t.steps))
|
||||
for i, s := range t.steps {
|
||||
parts[i] = fmt.Sprintf("%s;dur=%.1f", s.name, float64(s.d.Microseconds())/1000)
|
||||
}
|
||||
c.Header("Server-Timing", strings.Join(parts, ", "))
|
||||
}
|
||||
|
||||
// logIfSlow logs the steps when the request took slowPage or longer.
|
||||
func (t *stepTimer) logIfSlow(c *gin.Context, log *slog.Logger) {
|
||||
total := time.Since(t.start)
|
||||
if total < slowPage {
|
||||
return
|
||||
}
|
||||
attrs := []any{"path", c.Request.URL.Path, "total_ms", total.Milliseconds()}
|
||||
for _, s := range t.steps {
|
||||
attrs = append(attrs, s.name+"_ms", s.d.Milliseconds())
|
||||
}
|
||||
log.WarnContext(c.Request.Context(), "slow console page", attrs...)
|
||||
}
|
||||
@@ -129,6 +129,7 @@
|
||||
"audit.action.platform.org_suspension": "Organisation gesperrt oder entsperrt",
|
||||
"audit.action.platform.region_create": "Plattform-Region erstellt",
|
||||
"audit.action.platform.region_delete": "Plattform-Region gelöscht",
|
||||
"audit.action.platform.region_update": "Standort einer Plattform-Region geändert",
|
||||
"audit.action.platform.status_page_delete": "Statusseite durch Admin gelöscht",
|
||||
"audit.action.platform.status_page_suspension": "Statusseite gesperrt oder entsperrt",
|
||||
"audit.action.platform.user_delete": "Account durch Admin gelöscht",
|
||||
@@ -136,6 +137,7 @@
|
||||
"audit.action.platform.user_suspension": "Account gesperrt oder entsperrt",
|
||||
"audit.action.region.create": "Region erstellt",
|
||||
"audit.action.region.delete": "Region gelöscht",
|
||||
"audit.action.region.update": "Standort einer Region geändert",
|
||||
"audit.action.role.create": "Rolle erstellt",
|
||||
"audit.action.role.delete": "Rolle gelöscht",
|
||||
"audit.action.role.update": "Rolle geändert",
|
||||
@@ -587,6 +589,7 @@
|
||||
"error.invalid_maintenance_time": "Prüfe Beginn, Wochentage und letzten Tag.",
|
||||
"error.invalid_matchers": "Lege 1 bis 20 Label-Matcher mit gültigen Label-Namen und regulären Ausdrücken an.",
|
||||
"error.invalid_method": "Nur GET- und HEAD-Anfragen werden unterstützt.",
|
||||
"error.invalid_location": "Breitengrad (−90 bis 90) und Längengrad (−180 bis 180) angeben, oder keins von beiden.",
|
||||
"error.invalid_monitor": "Einer der Monitore existiert nicht oder ist doppelt aufgeführt.",
|
||||
"error.invalid_permissions": "Mindestens eine Berechtigung auswählen.",
|
||||
"error.invalid_query": "Gib eine PromQL-Abfrage mit höchstens 2000 Zeichen ein.",
|
||||
@@ -997,6 +1000,9 @@
|
||||
"members.step_down_confirm": "Als Owner zurücktreten? Ohne andere Rollen arbeitest du mit der Admin-Rolle weiter.",
|
||||
"members.title": "Mitglieder",
|
||||
"members.unassign": "Rolle entfernen",
|
||||
"meta.app_card_subtitle": "Monitore, Alarme und Statusseiten, Open Source",
|
||||
"meta.app_card_title": "Uptime-Monitoring und Statusseiten",
|
||||
"meta.app_description": "UptimeSebi überwacht Websites, Server und Dienste aus mehreren Regionen, alarmiert bei Ausfällen und betreibt öffentliche Statusseiten. Open Source.",
|
||||
"moderation.actions": "Sperren oder löschen …",
|
||||
"moderation.created": "Erstellt",
|
||||
"moderation.delete_confirm_org": "Organisation {{.Name}} mit allen Monitoren, Ergebnissen und Statusseiten endgültig löschen?",
|
||||
@@ -1253,6 +1259,7 @@
|
||||
"page.incidents": "Letzte Vorfälle",
|
||||
"page.maintenance_ongoing": "Laufende Wartung",
|
||||
"page.maintenance_upcoming": "Geplante Wartung",
|
||||
"page.meta_description": "Aktueller Status von {{.Title}}: {{.Status}}. Störungen und geplante Wartungen auf einen Blick.",
|
||||
"page.no_incidents": "Keine Vorfälle in den letzten 14 Tagen.",
|
||||
"page.stale": "Live-Aktualisierung derzeit nicht verfügbar. Diese Seite zeigt den Stand von {{.Time}}.",
|
||||
"page.status.degraded": "Einige Systeme haben Probleme",
|
||||
@@ -1261,6 +1268,13 @@
|
||||
"page.status.outage": "Größere Störung",
|
||||
"page.status.unknown": "Status derzeit nicht verfügbar",
|
||||
"page.today": "Heute",
|
||||
"page.pages": "Seite {{.Page}} von {{.Pages}}",
|
||||
"page.search": "Komponenten suchen",
|
||||
"page.search_submit": "Suchen",
|
||||
"page.search_clear": "Alle anzeigen",
|
||||
"page.search_none": "Keine Komponente passt zur Suche.",
|
||||
"page.filter_problems": "Nur Ausfälle ({{.Count}})",
|
||||
"page.filter_no_problems": "Keine Komponente hat einen Ausfall.",
|
||||
"page.updated": "Aktualisiert {{.Time}}",
|
||||
"pager.earlier": "Frühere",
|
||||
"pager.first": "Zum Anfang",
|
||||
@@ -1310,6 +1324,7 @@
|
||||
"pages.monitors_filter": "Monitore filtern",
|
||||
"pages.monitors_all": "Alle hinzufügen",
|
||||
"pages.monitors_none": "Alle entfernen",
|
||||
"pages.monitors_range": "{from}–{to} von {total}",
|
||||
"pages.no_group": "Ohne Gruppe",
|
||||
"pages.open": "Öffnen",
|
||||
"pages.own_servers": "Die Statusseiten dieser Organisation liefern nur ihre eigenen Statusseiten-Server aus, nicht die der Plattform. Ruf sie über die Adresse deiner Server auf oder verbinde eine eigene Domain, die auf sie zeigt.",
|
||||
@@ -1353,6 +1368,16 @@
|
||||
"one": "{{.Count}} aktiv",
|
||||
"other": "{{.Count}} aktiv"
|
||||
},
|
||||
"regions.latitude": "Breitengrad",
|
||||
"regions.location": "Standort",
|
||||
"regions.location_clear": "Standort entfernen",
|
||||
"regions.location_for": "Standort von {{.Name}}: auf die Karte klicken oder die Koordinaten eingeben.",
|
||||
"regions.location_pick_hint": "Ein Klick auf die Karte setzt die Koordinaten einer neuen Region oder der Region, deren Standort du gerade setzt.",
|
||||
"regions.location_set": "Setzen",
|
||||
"regions.longitude": "Längengrad",
|
||||
"regions.map_ctrl_key": "Strg",
|
||||
"regions.map_scroll_hint": "{{.Key}} + Scrollen zoomt die Karte.",
|
||||
"regions.map_touch_hint": "Mit zwei Fingern verschiebst du die Karte.",
|
||||
"regions.own": "diese Organisation",
|
||||
"regions.owner": "Besitzer",
|
||||
"regions.platform": "Plattform",
|
||||
@@ -1612,5 +1637,12 @@
|
||||
"pages.subscribers_limit": "Neue Abos pro Woche für die Organisation: {{.Max}}",
|
||||
"pages.feeds": "Feed und API",
|
||||
"pages.feeds_hint": "Jede veröffentlichte Seite hat einen RSS-Feed und eine JSON-API zum Lesen, pro Besucher begrenzt:",
|
||||
"audit.action.statuspage.subscriber_delete": "Abonnent einer Statusseite entfernt"
|
||||
"audit.action.statuspage.subscriber_delete": "Abonnent einer Statusseite entfernt",
|
||||
"page.not_found_title": "Seite nicht gefunden",
|
||||
"page.not_found": "Unter dieser Adresse gibt es keine Statusseite, oder sie ist nicht veröffentlicht.",
|
||||
"page.not_found_home": "Zur Hauptseite",
|
||||
"admin.statuspage_home": "Hauptseite der Statusseiten",
|
||||
"admin.statuspage_home_hint": "Wer die Statusseiten-Domain ohne Pfad oder eine Seite aufruft, die es nicht gibt, sieht eine Fehlerseite. Sie verlinkt diese Adresse, z. B. eure Website. Leer: kein Link.",
|
||||
"admin.statuspage_home_url": "Adresse der Hauptseite",
|
||||
"audit.action.platform.statuspage_home_update": "Hauptseite der Statusseiten geändert"
|
||||
}
|
||||
@@ -129,6 +129,7 @@
|
||||
"audit.action.platform.org_suspension": "Organization suspended or reinstated",
|
||||
"audit.action.platform.region_create": "Platform region created",
|
||||
"audit.action.platform.region_delete": "Platform region deleted",
|
||||
"audit.action.platform.region_update": "Platform region location changed",
|
||||
"audit.action.platform.status_page_delete": "Status page deleted by admin",
|
||||
"audit.action.platform.status_page_suspension": "Status page suspended or reinstated",
|
||||
"audit.action.platform.user_delete": "Account deleted by admin",
|
||||
@@ -136,6 +137,7 @@
|
||||
"audit.action.platform.user_suspension": "Account suspended or reinstated",
|
||||
"audit.action.region.create": "Region created",
|
||||
"audit.action.region.delete": "Region deleted",
|
||||
"audit.action.region.update": "Region location changed",
|
||||
"audit.action.role.create": "Role created",
|
||||
"audit.action.role.delete": "Role deleted",
|
||||
"audit.action.role.update": "Role changed",
|
||||
@@ -587,6 +589,7 @@
|
||||
"error.invalid_maintenance_time": "Check start, weekdays and last day.",
|
||||
"error.invalid_matchers": "Add 1 to 20 label matchers with valid label names and regular expressions.",
|
||||
"error.invalid_method": "Only GET and HEAD requests are supported.",
|
||||
"error.invalid_location": "Give latitude (−90 to 90) and longitude (−180 to 180), or neither.",
|
||||
"error.invalid_monitor": "One of the monitors does not exist or is listed twice.",
|
||||
"error.invalid_permissions": "Choose at least one permission.",
|
||||
"error.invalid_query": "Enter a PromQL query of at most 2000 characters.",
|
||||
@@ -997,6 +1000,9 @@
|
||||
"members.step_down_confirm": "Step down as owner? You keep working with the Admin role unless you have other roles.",
|
||||
"members.title": "Members",
|
||||
"members.unassign": "Remove role",
|
||||
"meta.app_card_subtitle": "Monitors, alerts and status pages, open source",
|
||||
"meta.app_card_title": "Uptime monitoring and status pages",
|
||||
"meta.app_description": "UptimeSebi watches websites, servers and services from several regions, alerts you on outages and runs public status pages. Open source.",
|
||||
"moderation.actions": "Suspend or delete …",
|
||||
"moderation.created": "Created",
|
||||
"moderation.delete_confirm_org": "Delete the organization {{.Name}} with all its monitors, results and status pages for good?",
|
||||
@@ -1253,6 +1259,7 @@
|
||||
"page.incidents": "Recent incidents",
|
||||
"page.maintenance_ongoing": "Maintenance in progress",
|
||||
"page.maintenance_upcoming": "Planned maintenance",
|
||||
"page.meta_description": "Current status of {{.Title}}: {{.Status}}. Incidents and planned maintenance at a glance.",
|
||||
"page.no_incidents": "No incidents in the last 14 days.",
|
||||
"page.stale": "Live updates are currently unavailable. This page shows the status as of {{.Time}}.",
|
||||
"page.status.degraded": "Some systems are experiencing problems",
|
||||
@@ -1261,6 +1268,13 @@
|
||||
"page.status.outage": "Major outage",
|
||||
"page.status.unknown": "Status currently unavailable",
|
||||
"page.today": "Today",
|
||||
"page.pages": "Page {{.Page}} of {{.Pages}}",
|
||||
"page.search": "Search components",
|
||||
"page.search_submit": "Search",
|
||||
"page.search_clear": "Show all",
|
||||
"page.search_none": "No component matches the search.",
|
||||
"page.filter_problems": "Outages only ({{.Count}})",
|
||||
"page.filter_no_problems": "No component has an outage.",
|
||||
"page.updated": "Updated {{.Time}}",
|
||||
"pager.earlier": "Earlier",
|
||||
"pager.first": "To the start",
|
||||
@@ -1310,6 +1324,7 @@
|
||||
"pages.monitors_filter": "Filter monitors",
|
||||
"pages.monitors_all": "Add all",
|
||||
"pages.monitors_none": "Remove all",
|
||||
"pages.monitors_range": "{from}–{to} of {total}",
|
||||
"pages.no_group": "No group",
|
||||
"pages.open": "Open",
|
||||
"pages.own_servers": "Your organization's own status page servers serve its pages; the platform's do not. Open them at the address of your servers or connect a custom domain pointing at them.",
|
||||
@@ -1353,6 +1368,16 @@
|
||||
"one": "{{.Count}} live",
|
||||
"other": "{{.Count}} live"
|
||||
},
|
||||
"regions.latitude": "Latitude",
|
||||
"regions.location": "Location",
|
||||
"regions.location_clear": "Remove location",
|
||||
"regions.location_for": "Location of {{.Name}}: click the map or enter the coordinates.",
|
||||
"regions.location_pick_hint": "Click the map to fill in the coordinates of a new region, or of the region whose location you are setting.",
|
||||
"regions.location_set": "Set",
|
||||
"regions.longitude": "Longitude",
|
||||
"regions.map_ctrl_key": "Ctrl",
|
||||
"regions.map_scroll_hint": "Use {{.Key}} + scroll to zoom the map.",
|
||||
"regions.map_touch_hint": "Use two fingers to move the map.",
|
||||
"regions.own": "this organization",
|
||||
"regions.owner": "Owner",
|
||||
"regions.platform": "platform",
|
||||
@@ -1612,5 +1637,12 @@
|
||||
"pages.subscribers_limit": "New subscriptions per week for the organization: {{.Max}}",
|
||||
"pages.feeds": "Feed and API",
|
||||
"pages.feeds_hint": "Every published page has an RSS feed and a read-only JSON API, rate limited per visitor:",
|
||||
"audit.action.statuspage.subscriber_delete": "Status page subscriber removed"
|
||||
"audit.action.statuspage.subscriber_delete": "Status page subscriber removed",
|
||||
"page.not_found_title": "Page not found",
|
||||
"page.not_found": "There is no status page at this address, or it is not published.",
|
||||
"page.not_found_home": "Go to the home page",
|
||||
"admin.statuspage_home": "Status page home",
|
||||
"admin.statuspage_home_hint": "Visitors of the bare status page domain and of pages that do not exist see an error page. It links this address, e.g. your website. Empty: no link.",
|
||||
"admin.statuspage_home_url": "Home page URL",
|
||||
"audit.action.platform.statuspage_home_update": "Status page home changed"
|
||||
}
|
||||
@@ -0,0 +1,72 @@
|
||||
-- +goose Up
|
||||
-- Deleting an organization removes it at once but leaves its check results
|
||||
-- and aggregates, which carry no foreign key, to the background: years of
|
||||
-- results take far longer to delete than a request may last. The purge
|
||||
-- goes a chunk at a time, each in a transaction of its own, so it never
|
||||
-- holds locks for long and resumes where it stopped.
|
||||
CREATE TABLE org_purges (
|
||||
org_id uuid PRIMARY KEY,
|
||||
requested_at timestamptz NOT NULL DEFAULT now(),
|
||||
-- An API instance purging the organization holds it until then.
|
||||
leased_until timestamptz NOT NULL DEFAULT '-infinity'
|
||||
);
|
||||
|
||||
ALTER TABLE org_purges ENABLE ROW LEVEL SECURITY;
|
||||
ALTER TABLE org_purges FORCE ROW LEVEL SECURITY;
|
||||
CREATE POLICY org_purges_system ON org_purges FOR ALL
|
||||
USING (app_scope_system()) WITH CHECK (app_scope_system());
|
||||
|
||||
-- +goose StatementBegin
|
||||
-- The chunks holding check data: those of the raw results first, so the
|
||||
-- aggregates' refresh does not materialize again what was purged from them,
|
||||
-- then those of both aggregates, oldest first. Runs with the owner's rights because the application role
|
||||
-- may not reach TimescaleDB's internal schema.
|
||||
CREATE FUNCTION org_check_data_chunks() RETURNS SETOF text
|
||||
LANGUAGE sql STABLE SECURITY DEFINER SET search_path = public, pg_temp AS $$
|
||||
SELECT format('%I.%I', c.chunk_schema, c.chunk_name)
|
||||
FROM timescaledb_information.chunks c
|
||||
WHERE (c.hypertable_schema, c.hypertable_name) IN (
|
||||
SELECT 'public'::name, 'check_results'::name
|
||||
UNION ALL
|
||||
SELECT materialization_hypertable_schema, materialization_hypertable_name
|
||||
FROM timescaledb_information.continuous_aggregates
|
||||
WHERE view_name IN ('check_results_1h', 'check_results_1d'))
|
||||
ORDER BY c.hypertable_name <> 'check_results', c.range_start, 1
|
||||
$$;
|
||||
-- +goose StatementEnd
|
||||
|
||||
-- +goose StatementBegin
|
||||
-- Deletes an organization's rows in one chunk of org_check_data_chunks,
|
||||
-- through its hypertable and limited to the chunk's time range, so that
|
||||
-- TimescaleDB handles compressed chunks. Chunks dropped meanwhile, and
|
||||
-- names of anything else, delete nothing.
|
||||
CREATE FUNCTION purge_org_check_chunk(org uuid, chunk text) RETURNS bigint
|
||||
LANGUAGE plpgsql SECURITY DEFINER SET search_path = public, pg_temp AS $$
|
||||
DECLARE
|
||||
r record;
|
||||
n bigint;
|
||||
BEGIN
|
||||
SELECT c.hypertable_schema AS hs, c.hypertable_name AS hn, d.column_name AS col,
|
||||
c.range_start AS lo, c.range_end AS hi
|
||||
INTO r
|
||||
FROM timescaledb_information.chunks c
|
||||
JOIN timescaledb_information.dimensions d
|
||||
ON d.hypertable_schema = c.hypertable_schema AND d.hypertable_name = c.hypertable_name
|
||||
AND d.dimension_number = 1
|
||||
WHERE format('%I.%I', c.chunk_schema, c.chunk_name) = chunk
|
||||
AND chunk IN (SELECT org_check_data_chunks());
|
||||
IF NOT FOUND THEN
|
||||
RETURN 0;
|
||||
END IF;
|
||||
EXECUTE format('DELETE FROM %I.%I WHERE org_id = $1 AND %I >= $2 AND %I < $3', r.hs, r.hn, r.col, r.col)
|
||||
USING org, r.lo, r.hi;
|
||||
GET DIAGNOSTICS n = ROW_COUNT;
|
||||
RETURN n;
|
||||
END
|
||||
$$;
|
||||
-- +goose StatementEnd
|
||||
|
||||
-- +goose Down
|
||||
DROP FUNCTION purge_org_check_chunk(uuid, text);
|
||||
DROP FUNCTION org_check_data_chunks();
|
||||
DROP TABLE org_purges;
|
||||
@@ -0,0 +1,16 @@
|
||||
-- +goose Up
|
||||
-- Where a region's checkers stand, so the monitor form can show them on a
|
||||
-- map. Both coordinates are set or neither is.
|
||||
ALTER TABLE regions
|
||||
ADD COLUMN latitude double precision,
|
||||
ADD COLUMN longitude double precision,
|
||||
ADD CONSTRAINT regions_location_check CHECK (
|
||||
(latitude IS NULL AND longitude IS NULL)
|
||||
OR (latitude BETWEEN -90 AND 90 AND longitude BETWEEN -180 AND 180)
|
||||
);
|
||||
|
||||
-- +goose Down
|
||||
ALTER TABLE regions
|
||||
DROP CONSTRAINT regions_location_check,
|
||||
DROP COLUMN latitude,
|
||||
DROP COLUMN longitude;
|
||||
@@ -0,0 +1,209 @@
|
||||
// Package ogimage draws the preview images link previews show for status
|
||||
// pages and the app (Open Graph and Twitter cards): 1200×630 PNGs in the
|
||||
// style of the console.
|
||||
package ogimage
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"image"
|
||||
"image/color"
|
||||
"image/draw"
|
||||
"image/png"
|
||||
"math"
|
||||
"strings"
|
||||
"sync"
|
||||
|
||||
"golang.org/x/image/font"
|
||||
"golang.org/x/image/font/gofont/gobold"
|
||||
"golang.org/x/image/font/gofont/goregular"
|
||||
"golang.org/x/image/font/opentype"
|
||||
"golang.org/x/image/math/fixed"
|
||||
)
|
||||
|
||||
// Width and Height are the size link previews expect.
|
||||
const (
|
||||
Width = 1200
|
||||
Height = 630
|
||||
)
|
||||
|
||||
// Colors of the console's palette.
|
||||
var (
|
||||
Paper = color.RGBA{0xf4, 0xf2, 0xee, 0xff}
|
||||
Ink = color.RGBA{0x1c, 0x1d, 0x1f, 0xff}
|
||||
Muted = color.RGBA{0x6b, 0x67, 0x5f, 0xff}
|
||||
Rule = color.RGBA{0xd9, 0xd5, 0xcc, 0xff}
|
||||
Up = color.RGBA{0x2f, 0x7d, 0x4f, 0xff}
|
||||
Down = color.RGBA{0xb3, 0x36, 0x1f, 0xff}
|
||||
Degraded = color.RGBA{0xb5, 0x7b, 0x14, 0xff}
|
||||
Unknown = color.RGBA{0x8a, 0x8a, 0x86, 0xff}
|
||||
Maintenance = color.RGBA{0x3d, 0x6f, 0xa6, 0xff}
|
||||
)
|
||||
|
||||
// Card is what an image shows: a title, a line below it marked with a dot
|
||||
// in Accent, and a footer such as the page's address.
|
||||
type Card struct {
|
||||
Title string
|
||||
Subtitle string
|
||||
Footer string
|
||||
Accent color.Color
|
||||
}
|
||||
|
||||
var (
|
||||
fontsOnce sync.Once
|
||||
regular *opentype.Font
|
||||
bold *opentype.Font
|
||||
fontsErr error
|
||||
)
|
||||
|
||||
func loadFonts() error {
|
||||
fontsOnce.Do(func() {
|
||||
if regular, fontsErr = opentype.Parse(goregular.TTF); fontsErr != nil {
|
||||
return
|
||||
}
|
||||
bold, fontsErr = opentype.Parse(gobold.TTF)
|
||||
})
|
||||
return fontsErr
|
||||
}
|
||||
|
||||
func face(f *opentype.Font, size float64) (font.Face, error) {
|
||||
return opentype.NewFace(f, &opentype.FaceOptions{Size: size, DPI: 72, Hinting: font.HintingFull})
|
||||
}
|
||||
|
||||
const margin = 80
|
||||
|
||||
// Render draws c as a PNG.
|
||||
func Render(c Card) ([]byte, error) {
|
||||
if err := loadFonts(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
accent := c.Accent
|
||||
if accent == nil {
|
||||
accent = Ink
|
||||
}
|
||||
img := image.NewRGBA(image.Rect(0, 0, Width, Height))
|
||||
draw.Draw(img, img.Bounds(), image.NewUniform(Paper), image.Point{}, draw.Src)
|
||||
// A band in the accent colour along the top, and a rule above the footer.
|
||||
fill(img, image.Rect(0, 0, Width, 14), accent)
|
||||
fill(img, image.Rect(margin, Height-130, Width-margin, Height-128), Rule)
|
||||
|
||||
brand, err := face(bold, 30)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
drawText(img, brand, Ink, margin, 104, "UptimeSebi")
|
||||
|
||||
// The title shrinks for long names and wraps onto at most two lines.
|
||||
y := 230
|
||||
for _, size := range []float64{76, 64, 54} {
|
||||
title, err := face(bold, size)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
lines := wrap(title, c.Title, Width-2*margin, 2)
|
||||
if len(lines) == 1 || size == 54 {
|
||||
lh := int(size * 1.15)
|
||||
for _, l := range lines {
|
||||
drawText(img, title, Ink, margin, y, l)
|
||||
y += lh
|
||||
}
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
if c.Subtitle != "" {
|
||||
sub, err := face(regular, 38)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
y += 30
|
||||
dot(img, margin+14, y-13, 14, accent)
|
||||
lines := wrap(sub, c.Subtitle, Width-2*margin-48, 1)
|
||||
drawText(img, sub, Ink, margin+48, y, lines[0])
|
||||
}
|
||||
|
||||
if c.Footer != "" {
|
||||
foot, err := face(regular, 28)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
drawText(img, foot, Muted, margin, Height-72, wrap(foot, c.Footer, Width-2*margin, 1)[0])
|
||||
}
|
||||
|
||||
var buf bytes.Buffer
|
||||
if err := png.Encode(&buf, img); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return buf.Bytes(), nil
|
||||
}
|
||||
|
||||
func fill(img *image.RGBA, r image.Rectangle, c color.Color) {
|
||||
draw.Draw(img, r, image.NewUniform(c), image.Point{}, draw.Src)
|
||||
}
|
||||
|
||||
// dot draws a filled circle of radius r around (cx, cy), smoothing its edge.
|
||||
func dot(img *image.RGBA, cx, cy, r int, c color.Color) {
|
||||
cr, cg, cb, _ := c.RGBA()
|
||||
for y := cy - r - 1; y <= cy+r+1; y++ {
|
||||
for x := cx - r - 1; x <= cx+r+1; x++ {
|
||||
// Coverage from the distance of the pixel centre to the edge.
|
||||
dx, dy := float64(x-cx)+0.5, float64(y-cy)+0.5
|
||||
d := float64(r) - math.Sqrt(dx*dx+dy*dy) + 0.5
|
||||
if d <= 0 {
|
||||
continue
|
||||
}
|
||||
if d > 1 {
|
||||
d = 1
|
||||
}
|
||||
bg := img.RGBAAt(x, y)
|
||||
mix := func(fg uint32, b uint8) uint8 { return uint8(float64(fg>>8)*d + float64(b)*(1-d)) }
|
||||
img.SetRGBA(x, y, color.RGBA{mix(cr, bg.R), mix(cg, bg.G), mix(cb, bg.B), 0xff})
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func drawText(img *image.RGBA, f font.Face, c color.Color, x, y int, s string) {
|
||||
d := font.Drawer{Dst: img, Src: image.NewUniform(c), Face: f, Dot: fixed.P(x, y)}
|
||||
d.DrawString(s)
|
||||
}
|
||||
|
||||
// wrap breaks s into lines no wider than width, at most max of them; the
|
||||
// last one ends in an ellipsis when s does not fit.
|
||||
func wrap(f font.Face, s string, width, max int) []string {
|
||||
words := strings.Fields(s)
|
||||
if len(words) == 0 {
|
||||
return []string{""}
|
||||
}
|
||||
limit := fixed.I(width)
|
||||
var lines []string
|
||||
line := ""
|
||||
for i, w := range words {
|
||||
next := strings.TrimSpace(line + " " + w)
|
||||
if font.MeasureString(f, next) <= limit {
|
||||
line = next
|
||||
continue
|
||||
}
|
||||
if line != "" {
|
||||
lines = append(lines, line)
|
||||
}
|
||||
line = w
|
||||
if len(lines) == max {
|
||||
// Out of lines: finish the last one with what is left.
|
||||
rest := strings.Join(words[i:], " ")
|
||||
lines[max-1] = ellipsize(f, lines[max-1]+" "+rest, limit)
|
||||
return lines
|
||||
}
|
||||
}
|
||||
return append(lines, ellipsize(f, line, limit))
|
||||
}
|
||||
|
||||
// ellipsize shortens s until it fits limit, marking the cut with "…".
|
||||
func ellipsize(f font.Face, s string, limit fixed.Int26_6) string {
|
||||
if font.MeasureString(f, s) <= limit {
|
||||
return s
|
||||
}
|
||||
r := []rune(s)
|
||||
for len(r) > 0 && font.MeasureString(f, string(r)+"…") > limit {
|
||||
r = r[:len(r)-1]
|
||||
}
|
||||
return strings.TrimSpace(string(r)) + "…"
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
package ogimage
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"image/png"
|
||||
"os"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestRender(t *testing.T) {
|
||||
for _, c := range []Card{
|
||||
{Title: "Hetzner Cloud", Subtitle: "All systems operational", Footer: "uptimesebi-status.net/hetzner", Accent: Up},
|
||||
{Title: strings.Repeat("A very long status page name ", 6), Subtitle: strings.Repeat("problems ", 20), Footer: "x", Accent: Down},
|
||||
{Title: ""},
|
||||
} {
|
||||
b, err := Render(c)
|
||||
if err != nil {
|
||||
t.Fatalf("Render(%q) error = %v", c.Title, err)
|
||||
}
|
||||
img, err := png.Decode(bytes.NewReader(b))
|
||||
if err != nil {
|
||||
t.Fatalf("Render(%q) is no PNG: %v", c.Title, err)
|
||||
}
|
||||
if r := img.Bounds(); r.Dx() != Width || r.Dy() != Height {
|
||||
t.Errorf("Render(%q) size = %v, want %dx%d", c.Title, r, Width, Height)
|
||||
}
|
||||
if dir := os.Getenv("OGIMAGE_OUT"); dir != "" {
|
||||
_ = os.WriteFile(dir+"/"+string(rune('a'+len(c.Title)%26))+".png", b, 0o600)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestWrap(t *testing.T) {
|
||||
if err := loadFonts(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
f, err := face(bold, 76)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
lines := wrap(f, strings.Repeat("word ", 100), 1040, 2)
|
||||
if len(lines) != 2 || !strings.HasSuffix(lines[1], "…") {
|
||||
t.Errorf("wrap() = %q, want two lines ending in an ellipsis", lines)
|
||||
}
|
||||
if got := wrap(f, "Short", 1040, 2); len(got) != 1 || got[0] != "Short" {
|
||||
t.Errorf("wrap(Short) = %q", got)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,142 @@
|
||||
package platform
|
||||
|
||||
import (
|
||||
"compress/gzip"
|
||||
"io"
|
||||
"mime"
|
||||
"net/http"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
// compressMin is the smallest body worth compressing, for responses that
|
||||
// state their length.
|
||||
const compressMin = 1024
|
||||
|
||||
var gzipWriters = sync.Pool{New: func() any {
|
||||
w, _ := gzip.NewWriterLevel(io.Discard, gzip.DefaultCompression)
|
||||
return w
|
||||
}}
|
||||
|
||||
// Compress gzips text responses (HTML, CSS, JavaScript, JSON, XML, SVG) for
|
||||
// clients that accept it. Status pages list thousands of components in
|
||||
// markup that repeats itself, so this shrinks them many times over.
|
||||
func Compress() gin.HandlerFunc {
|
||||
return func(c *gin.Context) {
|
||||
c.Writer.Header().Add("Vary", "Accept-Encoding")
|
||||
if c.Request.Method == http.MethodHead || !acceptsGzip(c.Request.Header.Get("Accept-Encoding")) {
|
||||
c.Next()
|
||||
return
|
||||
}
|
||||
w := &gzipWriter{ResponseWriter: c.Writer}
|
||||
c.Writer = w
|
||||
defer w.finish()
|
||||
c.Next()
|
||||
}
|
||||
}
|
||||
|
||||
// acceptsGzip reports whether an Accept-Encoding header allows gzip.
|
||||
func acceptsGzip(header string) bool {
|
||||
for _, part := range strings.Split(header, ",") {
|
||||
name, params, _ := strings.Cut(part, ";")
|
||||
name = strings.ToLower(strings.TrimSpace(name))
|
||||
if name != "gzip" && name != "*" {
|
||||
continue
|
||||
}
|
||||
for _, p := range strings.Split(params, ";") {
|
||||
k, v, _ := strings.Cut(strings.TrimSpace(p), "=")
|
||||
if strings.EqualFold(k, "q") {
|
||||
if q, err := strconv.ParseFloat(strings.TrimSpace(v), 64); err == nil && q == 0 {
|
||||
return false
|
||||
}
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func compressible(contentType string) bool {
|
||||
mt, _, err := mime.ParseMediaType(contentType)
|
||||
if err != nil {
|
||||
return false
|
||||
}
|
||||
switch {
|
||||
case strings.HasPrefix(mt, "text/"):
|
||||
return true
|
||||
case mt == "application/json", mt == "application/javascript", mt == "image/svg+xml",
|
||||
mt == "application/xml", mt == "application/rss+xml", mt == "application/atom+xml":
|
||||
return true
|
||||
}
|
||||
return strings.HasSuffix(mt, "+json") || strings.HasSuffix(mt, "+xml")
|
||||
}
|
||||
|
||||
// gzipWriter decides at the first write whether to compress, when the
|
||||
// handler has set the status and headers.
|
||||
type gzipWriter struct {
|
||||
gin.ResponseWriter
|
||||
decided bool
|
||||
gz *gzip.Writer
|
||||
}
|
||||
|
||||
func (w *gzipWriter) decide() {
|
||||
w.decided = true
|
||||
h := w.Header()
|
||||
switch status := w.Status(); {
|
||||
case status < 200, status == http.StatusNoContent, status == http.StatusNotModified, status == http.StatusPartialContent:
|
||||
return
|
||||
}
|
||||
if h.Get("Content-Encoding") != "" || !compressible(h.Get("Content-Type")) {
|
||||
return
|
||||
}
|
||||
if n, err := strconv.Atoi(h.Get("Content-Length")); err == nil && n < compressMin {
|
||||
return
|
||||
}
|
||||
h.Set("Content-Encoding", "gzip")
|
||||
h.Del("Content-Length")
|
||||
if etag := h.Get("ETag"); etag != "" && !strings.HasPrefix(etag, "W/") {
|
||||
h.Set("ETag", "W/"+etag)
|
||||
}
|
||||
w.gz = gzipWriters.Get().(*gzip.Writer)
|
||||
w.gz.Reset(w.ResponseWriter)
|
||||
}
|
||||
|
||||
// Write compresses b if decide chose to, which it does at the first write.
|
||||
func (w *gzipWriter) Write(b []byte) (int, error) {
|
||||
if !w.decided {
|
||||
if w.Header().Get("Content-Type") == "" {
|
||||
w.Header().Set("Content-Type", http.DetectContentType(b))
|
||||
}
|
||||
w.decide()
|
||||
}
|
||||
if w.gz == nil {
|
||||
return w.ResponseWriter.Write(b)
|
||||
}
|
||||
return w.gz.Write(b)
|
||||
}
|
||||
|
||||
// WriteString writes s like Write, so strings are compressed as well.
|
||||
func (w *gzipWriter) WriteString(s string) (int, error) {
|
||||
return w.Write([]byte(s))
|
||||
}
|
||||
|
||||
// Flush sends what is compressed so far, for responses that stream.
|
||||
func (w *gzipWriter) Flush() {
|
||||
if w.gz != nil {
|
||||
_ = w.gz.Flush()
|
||||
}
|
||||
w.ResponseWriter.Flush()
|
||||
}
|
||||
|
||||
func (w *gzipWriter) finish() {
|
||||
if w.gz == nil {
|
||||
return
|
||||
}
|
||||
_ = w.gz.Close()
|
||||
w.gz.Reset(io.Discard)
|
||||
gzipWriters.Put(w.gz)
|
||||
w.gz = nil
|
||||
}
|
||||
@@ -0,0 +1,86 @@
|
||||
package platform
|
||||
|
||||
import (
|
||||
"compress/gzip"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strconv"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
func TestCompress(t *testing.T) {
|
||||
gin.SetMode(gin.TestMode)
|
||||
page := strings.Repeat("<li>component</li>", 2000)
|
||||
r := gin.New()
|
||||
r.Use(Compress())
|
||||
r.GET("/page", func(c *gin.Context) {
|
||||
c.Header("Content-Type", "text/html; charset=utf-8")
|
||||
c.Status(http.StatusOK)
|
||||
for i := 0; i < 2000; i++ {
|
||||
_, _ = c.Writer.WriteString("<li>component</li>")
|
||||
}
|
||||
})
|
||||
r.GET("/small", func(c *gin.Context) { c.String(http.StatusOK, "ok") })
|
||||
r.GET("/sized", func(c *gin.Context) {
|
||||
c.Header("Content-Length", strconv.Itoa(len("tiny")))
|
||||
c.Data(http.StatusOK, "text/plain", []byte("tiny"))
|
||||
})
|
||||
r.GET("/png", func(c *gin.Context) { c.Data(http.StatusOK, "image/png", []byte(page)) })
|
||||
r.GET("/json", func(c *gin.Context) { c.JSON(http.StatusOK, gin.H{"page": page}) })
|
||||
r.GET("/notmodified", func(c *gin.Context) { c.Status(http.StatusNotModified) })
|
||||
|
||||
get := func(path, accept string) *httptest.ResponseRecorder {
|
||||
req := httptest.NewRequest(http.MethodGet, path, nil)
|
||||
if accept != "" {
|
||||
req.Header.Set("Accept-Encoding", accept)
|
||||
}
|
||||
rec := httptest.NewRecorder()
|
||||
r.ServeHTTP(rec, req)
|
||||
return rec
|
||||
}
|
||||
gunzip := func(t *testing.T, rec *httptest.ResponseRecorder) string {
|
||||
t.Helper()
|
||||
zr, err := gzip.NewReader(rec.Body)
|
||||
if err != nil {
|
||||
t.Fatalf("gzip.NewReader() error = %v", err)
|
||||
}
|
||||
b, err := io.ReadAll(zr)
|
||||
if err != nil {
|
||||
t.Fatalf("reading gzip body error = %v", err)
|
||||
}
|
||||
return string(b)
|
||||
}
|
||||
|
||||
rec := get("/page", "br, gzip;q=0.8")
|
||||
if rec.Header().Get("Content-Encoding") != "gzip" || rec.Header().Get("Vary") != "Accept-Encoding" {
|
||||
t.Fatalf("headers = %v, want gzip with Vary", rec.Header())
|
||||
}
|
||||
if rec.Body.Len() >= len(page)/10 {
|
||||
t.Errorf("compressed size = %d, want far below %d", rec.Body.Len(), len(page))
|
||||
}
|
||||
if got := gunzip(t, rec); got != page {
|
||||
t.Errorf("decompressed body differs: %d bytes, want %d", len(got), len(page))
|
||||
}
|
||||
if rec := get("/json", "gzip"); rec.Header().Get("Content-Encoding") != "gzip" || !strings.Contains(gunzip(t, rec), "component") {
|
||||
t.Errorf("JSON not compressed: %v", rec.Header())
|
||||
}
|
||||
for _, tc := range []struct{ path, accept string }{
|
||||
{"/page", ""},
|
||||
{"/page", "gzip;q=0, deflate"},
|
||||
{"/page", "identity"},
|
||||
{"/sized", "gzip"},
|
||||
{"/png", "gzip"},
|
||||
{"/notmodified", "gzip"},
|
||||
} {
|
||||
if rec := get(tc.path, tc.accept); rec.Header().Get("Content-Encoding") != "" {
|
||||
t.Errorf("GET %s with %q compressed, want plain", tc.path, tc.accept)
|
||||
}
|
||||
}
|
||||
if rec := get("/page", "*"); rec.Header().Get("Content-Encoding") != "gzip" {
|
||||
t.Errorf("Accept-Encoding * not compressed")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,143 @@
|
||||
package statuspage
|
||||
|
||||
import (
|
||||
"image/color"
|
||||
"net/http"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
|
||||
"git.zb-server.de/ZB-Server/uptimesebi/internal/agentapi"
|
||||
"git.zb-server.de/ZB-Server/uptimesebi/internal/i18n"
|
||||
"git.zb-server.de/ZB-Server/uptimesebi/internal/ogimage"
|
||||
"git.zb-server.de/ZB-Server/uptimesebi/internal/web"
|
||||
)
|
||||
|
||||
// maxDescription bounds a page's description, about what search results
|
||||
// show.
|
||||
const maxDescription = 160
|
||||
|
||||
// origin is the scheme and host the visitor reached the server at.
|
||||
func origin(c *gin.Context) string {
|
||||
scheme := "http"
|
||||
if c.Request.TLS != nil || strings.EqualFold(c.GetHeader("X-Forwarded-Proto"), "https") {
|
||||
scheme = "https"
|
||||
}
|
||||
return scheme + "://" + c.Request.Host
|
||||
}
|
||||
|
||||
var statusAccent = map[string]color.Color{
|
||||
agentapi.PageOperational: ogimage.Up,
|
||||
agentapi.PageDegraded: ogimage.Degraded,
|
||||
agentapi.PageOutage: ogimage.Down,
|
||||
agentapi.PageUnderMaintenance: ogimage.Maintenance,
|
||||
agentapi.PageUnknown: ogimage.Unknown,
|
||||
}
|
||||
|
||||
// pageMeta describes the status page at base for search engines and link
|
||||
// previews, in the language the request was localized to.
|
||||
func (s *Server) pageMeta(c *gin.Context, snap agentapi.PageSnapshot, base string) *web.PageMeta {
|
||||
ctx := c.Request.Context()
|
||||
lang := i18n.Lang(ctx)
|
||||
desc := web.PlainText(snap.Description, maxDescription)
|
||||
if desc == "" {
|
||||
desc = i18n.T(ctx, "page.meta_description", "Title", snap.Title, "Status", i18n.T(ctx, "page.status."+snap.Status))
|
||||
}
|
||||
abs := origin(c) + base
|
||||
image := web.LangURL(abs+"og.png", lang)
|
||||
_, chosen := c.GetQuery("lang")
|
||||
return web.NewPageMeta(snap.Title, desc, abs, image, snap.Title, lang, chosen && s.catalog.IsSupported(c.Query("lang")), s.catalog.Supported())
|
||||
}
|
||||
|
||||
// ogCache keeps each page's preview image until its title, status or
|
||||
// language changes.
|
||||
type ogCache struct {
|
||||
mu sync.Mutex
|
||||
images map[string]ogEntry
|
||||
}
|
||||
|
||||
type ogEntry struct {
|
||||
sig string
|
||||
png []byte
|
||||
}
|
||||
|
||||
// serveOG draws the page's preview image: its name and current status.
|
||||
func (s *Server) serveOG(c *gin.Context, e entry, base string) {
|
||||
s.localizeRequest(c)
|
||||
ctx := c.Request.Context()
|
||||
snap := e.Snap.WithMaintenance(s.now())
|
||||
card := ogimage.Card{
|
||||
Title: snap.Title,
|
||||
Subtitle: i18n.T(ctx, "page.status."+snap.Status),
|
||||
Footer: strings.TrimSuffix(c.Request.Host+base, "/"),
|
||||
Accent: statusAccent[snap.Status],
|
||||
}
|
||||
sig := strings.Join([]string{card.Title, card.Subtitle, card.Footer, snap.Status}, "\x00")
|
||||
key := e.Key + "\x00" + i18n.Lang(ctx)
|
||||
s.og.mu.Lock()
|
||||
cached, ok := s.og.images[key]
|
||||
s.og.mu.Unlock()
|
||||
if !ok || cached.sig != sig {
|
||||
png, err := ogimage.Render(card)
|
||||
if err != nil {
|
||||
s.log.Warn("drawing preview image failed", "page", e.Key, "error", err)
|
||||
c.Status(http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
cached = ogEntry{sig: sig, png: png}
|
||||
s.og.mu.Lock()
|
||||
if s.og.images == nil {
|
||||
s.og.images = map[string]ogEntry{}
|
||||
}
|
||||
s.og.images[key] = cached
|
||||
s.og.mu.Unlock()
|
||||
}
|
||||
c.Header("Cache-Control", "public, max-age=300")
|
||||
c.Data(http.StatusOK, "image/png", cached.png)
|
||||
}
|
||||
|
||||
func (s *Server) forgetOG(key string) {
|
||||
s.og.mu.Lock()
|
||||
defer s.og.mu.Unlock()
|
||||
for k := range s.og.images {
|
||||
if strings.HasPrefix(k, key+"\x00") {
|
||||
delete(s.og.images, k)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (s *Server) serveSitemap(c *gin.Context, base string) {
|
||||
// No lastmod: a snapshot is regenerated every minute, which says
|
||||
// nothing about whether the page changed.
|
||||
body, err := web.Sitemap([]string{origin(c) + base}, s.catalog.Supported(), time.Time{})
|
||||
if err != nil {
|
||||
c.Status(http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
c.Header("Cache-Control", "public, max-age=3600")
|
||||
c.Data(http.StatusOK, "application/xml; charset=utf-8", body)
|
||||
}
|
||||
|
||||
// serveRobots lets crawlers read the pages but not the feeds, the API or
|
||||
// the subscription forms. A custom domain serves one page, so its sitemap
|
||||
// can be named; the shared hosts serve many under their slugs.
|
||||
func (s *Server) serveRobots(c *gin.Context) {
|
||||
var b strings.Builder
|
||||
b.WriteString("User-agent: *\n")
|
||||
prefix := "/*"
|
||||
custom := s.IsCustomDomain(hostOnly(c.Request.Host))
|
||||
if custom {
|
||||
prefix = ""
|
||||
}
|
||||
for _, p := range []string{"/api/", "/subscribe", "/unsubscribe", "/feed.rss"} {
|
||||
b.WriteString("Disallow: " + prefix + p + "\n")
|
||||
}
|
||||
b.WriteString("Allow: /\n")
|
||||
if custom {
|
||||
b.WriteString("\nSitemap: " + origin(c) + "/sitemap.xml\n")
|
||||
}
|
||||
c.Header("Cache-Control", "public, max-age=3600")
|
||||
c.Data(http.StatusOK, "text/plain; charset=utf-8", []byte(b.String()))
|
||||
}
|
||||
@@ -34,6 +34,8 @@ const (
|
||||
routeSubscribe
|
||||
routeConfirm
|
||||
routeUnsubscribe
|
||||
routeOG
|
||||
routeSitemap
|
||||
)
|
||||
|
||||
// posts reports whether the route takes form posts.
|
||||
@@ -63,6 +65,10 @@ func routeOf(parts []string) (route, bool) {
|
||||
return route{kind: routeConfirm}, true
|
||||
case len(parts) == 1 && parts[0] == "unsubscribe":
|
||||
return route{kind: routeUnsubscribe}, true
|
||||
case len(parts) == 1 && parts[0] == "og.png":
|
||||
return route{kind: routeOG}, true
|
||||
case len(parts) == 1 && parts[0] == "sitemap.xml":
|
||||
return route{kind: routeSitemap}, true
|
||||
case len(parts) == 3 && parts[0] == "api" && parts[1] == "v1" && apiResources[parts[2]]:
|
||||
return route{kind: routeAPI, arg: parts[2]}, true
|
||||
case len(parts) == 1 && parts[0] != "" && parts[0] != "api":
|
||||
|
||||
@@ -19,8 +19,10 @@ import (
|
||||
"log/slog"
|
||||
"net"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
@@ -63,7 +65,7 @@ type Source interface {
|
||||
// PageIfChanged answers agentapi.ErrNotModified when the page still
|
||||
// has checksum.
|
||||
PageIfChanged(ctx context.Context, host, slug, checksum string) (agentapi.PageSnapshot, error)
|
||||
Pages(ctx context.Context) ([]agentapi.PageRef, error)
|
||||
Pages(ctx context.Context) (agentapi.PageIndex, error)
|
||||
}
|
||||
|
||||
// Server renders pages for one status page agent.
|
||||
@@ -71,6 +73,8 @@ type Server struct {
|
||||
src Source
|
||||
catalog *i18n.Catalog
|
||||
log *slog.Logger
|
||||
// og keeps the pages' preview images.
|
||||
og ogCache
|
||||
// ownHosts are the hosts that serve pages by slug; any other host is
|
||||
// looked up as a custom domain.
|
||||
ownHosts map[string]bool
|
||||
@@ -78,7 +82,9 @@ type Server struct {
|
||||
dir string
|
||||
now func() time.Time
|
||||
|
||||
mu sync.Mutex
|
||||
mu sync.Mutex
|
||||
// home is the platform's home page, linked from the error page.
|
||||
home string
|
||||
cache map[string]entry
|
||||
refreshing map[string]bool
|
||||
// again holds pages that changed while being refreshed, which are
|
||||
@@ -161,9 +167,39 @@ func (s *Server) loadDisk() error {
|
||||
if len(s.cache) > 0 {
|
||||
s.log.Info("loaded cached status pages", "count", len(s.cache))
|
||||
}
|
||||
if raw, err := os.ReadFile(filepath.Join(s.dir, homeFile)); err == nil {
|
||||
s.home = string(raw)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// homeFile keeps the home page across restarts; not .json, which are pages.
|
||||
const homeFile = "home.url"
|
||||
|
||||
// setHome records the home page the error page links.
|
||||
func (s *Server) setHome(url string) {
|
||||
s.mu.Lock()
|
||||
changed := s.home != url
|
||||
s.home = url
|
||||
s.mu.Unlock()
|
||||
if changed && s.dir != "" {
|
||||
if err := os.WriteFile(filepath.Join(s.dir, homeFile), []byte(url), 0o600); err != nil {
|
||||
s.log.Warn("saving the home page failed", "error", err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// notFound answers visitors of a page that does not exist with a page
|
||||
// leading to the platform's home page.
|
||||
func (s *Server) notFound(c *gin.Context) {
|
||||
s.localizeRequest(c)
|
||||
s.mu.Lock()
|
||||
home := s.home
|
||||
s.mu.Unlock()
|
||||
c.Header("Cache-Control", "no-store")
|
||||
web.Render(c, http.StatusNotFound, web.PublicNotFoundPage("/static/dist/app.css", home))
|
||||
}
|
||||
|
||||
func (s *Server) fileFor(key string) string {
|
||||
sum := sha256.Sum256([]byte(key))
|
||||
return filepath.Join(s.dir, hex.EncodeToString(sum[:16])+".json")
|
||||
@@ -187,6 +223,7 @@ func (s *Server) persist(e entry) {
|
||||
}
|
||||
|
||||
func (s *Server) forget(key string) {
|
||||
s.forgetOG(key)
|
||||
s.mu.Lock()
|
||||
delete(s.cache, key)
|
||||
delete(s.visited, key)
|
||||
@@ -227,6 +264,10 @@ func hostOnly(h string) string {
|
||||
}
|
||||
|
||||
func (s *Server) serve(c *gin.Context) {
|
||||
if c.Request.URL.Path == "/robots.txt" && (c.Request.Method == http.MethodGet || c.Request.Method == http.MethodHead) {
|
||||
s.serveRobots(c)
|
||||
return
|
||||
}
|
||||
host := hostOnly(c.Request.Host)
|
||||
var parts []string
|
||||
if trimmed := strings.Trim(c.Request.URL.Path, "/"); trimmed != "" {
|
||||
@@ -237,7 +278,7 @@ func (s *Server) serve(c *gin.Context) {
|
||||
key, base = "host:"+host, "/"
|
||||
} else {
|
||||
if len(parts) == 0 {
|
||||
c.Status(http.StatusNotFound)
|
||||
s.notFound(c)
|
||||
return
|
||||
}
|
||||
slug, parts = parts[0], parts[1:]
|
||||
@@ -261,12 +302,23 @@ func (s *Server) serve(c *gin.Context) {
|
||||
}
|
||||
e, ok := s.lookup(c.Request.Context(), key, host, slug)
|
||||
if !ok {
|
||||
c.Status(http.StatusNotFound)
|
||||
if rt.kind == routeFeed || rt.kind == routeAPI || rt.kind == routeOG || rt.kind == routeSitemap {
|
||||
c.Status(http.StatusNotFound)
|
||||
} else {
|
||||
s.notFound(c)
|
||||
}
|
||||
return
|
||||
}
|
||||
if rt.kind == routeLegal {
|
||||
switch rt.kind {
|
||||
case routeLegal:
|
||||
s.serveLegal(c, e, rt.arg, base)
|
||||
return
|
||||
case routeOG:
|
||||
s.serveOG(c, e, base)
|
||||
return
|
||||
case routeSitemap:
|
||||
s.serveSitemap(c, base)
|
||||
return
|
||||
}
|
||||
var staleSince time.Time
|
||||
if s.now().Sub(e.Fetched) > staleNoticeAfter {
|
||||
@@ -281,6 +333,7 @@ func (s *Server) serve(c *gin.Context) {
|
||||
}
|
||||
switch rt.kind {
|
||||
case routeComponent:
|
||||
assets.NoIndex = true
|
||||
s.serveComponent(c, e, rt.arg, assets)
|
||||
return
|
||||
case routeFeed:
|
||||
@@ -290,12 +343,47 @@ func (s *Server) serve(c *gin.Context) {
|
||||
s.serveAPI(c, e, rt.arg, base)
|
||||
return
|
||||
case routeSubscribe, routeConfirm, routeUnsubscribe:
|
||||
assets.NoIndex = true
|
||||
s.serveSubscription(c, e, rt.kind, host, slug, base, assets)
|
||||
return
|
||||
}
|
||||
s.localizeRequest(c)
|
||||
c.Header("Cache-Control", "public, max-age=30")
|
||||
web.Render(c, http.StatusOK, web.PublicStatusPage(e.Snap.WithMaintenance(s.now()), assets))
|
||||
assets.PageSize = componentsPerPage
|
||||
assets.Pages = sectionPages(c.Request.URL.Query())
|
||||
if q := c.Query("q"); len(q) <= maxComponentQuery {
|
||||
assets.Query = q
|
||||
}
|
||||
assets.OnlyProblems = c.Query("problems") == "1"
|
||||
snap := e.Snap.WithMaintenance(s.now())
|
||||
assets.Meta = s.pageMeta(c, snap, base)
|
||||
web.Render(c, http.StatusOK, web.PublicStatusPage(snap, assets))
|
||||
}
|
||||
|
||||
// componentsPerPage is how many of its own components a section of a
|
||||
// status page lists at a time; organizations put thousands on one.
|
||||
const componentsPerPage = 25
|
||||
|
||||
// maxComponentQuery bounds the search for components.
|
||||
const maxComponentQuery = 100
|
||||
|
||||
// maxPagedSections bounds the sections a request pages.
|
||||
const maxPagedSections = 100
|
||||
|
||||
// sectionPages reads the pages of sections a request asks for, as
|
||||
// "p.<key>=<page from 1>".
|
||||
func sectionPages(q url.Values) map[string]int {
|
||||
pages := map[string]int{}
|
||||
for k, vs := range q {
|
||||
key, ok := strings.CutPrefix(k, "p.")
|
||||
if !ok || key == "" || len(vs) == 0 || len(pages) >= maxPagedSections {
|
||||
continue
|
||||
}
|
||||
if n, err := strconv.Atoi(vs[0]); err == nil && n > 1 {
|
||||
pages[key] = n - 1
|
||||
}
|
||||
}
|
||||
return pages
|
||||
}
|
||||
|
||||
// serveComponent renders one component's public detail page from the cached
|
||||
@@ -333,14 +421,17 @@ func (s *Server) serveLegal(c *gin.Context, e entry, kind, base string) {
|
||||
}
|
||||
s.localizeRequest(c)
|
||||
c.Header("Cache-Control", "public, max-age=300")
|
||||
web.Render(c, http.StatusOK, web.PublicLegalPage(e.Snap, web.PublicAssets{CSSHref: "/static/dist/app.css"}, kind, html, base))
|
||||
web.Render(c, http.StatusOK, web.PublicLegalPage(e.Snap, web.PublicAssets{CSSHref: "/static/dist/app.css", NoIndex: true}, kind, html, base))
|
||||
}
|
||||
}
|
||||
|
||||
// localizeRequest shows the language ?lang= names, else the visitor's
|
||||
// preferred one; each language has its own address for search engines.
|
||||
func (s *Server) localizeRequest(c *gin.Context) {
|
||||
l := s.catalog.Match(c.GetHeader("Accept-Language"))
|
||||
l := s.catalog.Match(c.Query("lang"), c.GetHeader("Accept-Language"))
|
||||
c.Request = c.Request.WithContext(i18n.NewContext(c.Request.Context(), l))
|
||||
c.Header("Content-Language", l.Lang())
|
||||
c.Writer.Header().Add("Vary", "Accept-Language")
|
||||
}
|
||||
|
||||
// lookup answers from the cache whenever possible and refreshes in the
|
||||
@@ -523,11 +614,13 @@ func (s *Server) Run(ctx context.Context) {
|
||||
func (s *Server) Sync(ctx context.Context) {
|
||||
ctx, cancel := context.WithTimeout(ctx, syncInterval)
|
||||
defer cancel()
|
||||
refs, err := s.src.Pages(ctx)
|
||||
index, err := s.src.Pages(ctx)
|
||||
if err != nil {
|
||||
s.log.WarnContext(ctx, "listing status pages failed", "error", err)
|
||||
return
|
||||
}
|
||||
s.setHome(index.HomeURL)
|
||||
refs := index.Pages
|
||||
todo := map[string]entry{}
|
||||
s.mu.Lock()
|
||||
for key, e := range s.cache {
|
||||
|
||||
@@ -1,8 +1,10 @@
|
||||
package statuspage
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
@@ -25,6 +27,7 @@ type fakeSource struct {
|
||||
err error
|
||||
delay time.Duration
|
||||
pages map[string]agentapi.PageSnapshot
|
||||
home string
|
||||
}
|
||||
|
||||
// PageIfChanged counts calls and answers like the API, sending pages
|
||||
@@ -65,16 +68,16 @@ func (f *fakeSource) page(ctx context.Context, host, slug string) (agentapi.Page
|
||||
}
|
||||
|
||||
// Pages lists the fake's pages by their keys: "host|" or "|slug".
|
||||
func (f *fakeSource) Pages(context.Context) ([]agentapi.PageRef, error) {
|
||||
func (f *fakeSource) Pages(context.Context) (agentapi.PageIndex, error) {
|
||||
f.mu.Lock()
|
||||
defer f.mu.Unlock()
|
||||
if f.err != nil {
|
||||
return nil, f.err
|
||||
return agentapi.PageIndex{}, f.err
|
||||
}
|
||||
var out []agentapi.PageRef
|
||||
out := agentapi.PageIndex{HomeURL: f.home}
|
||||
for k := range f.pages {
|
||||
host, slug, _ := strings.Cut(k, "|")
|
||||
out = append(out, agentapi.PageRef{Host: host, Slug: slug})
|
||||
out.Pages = append(out.Pages, agentapi.PageRef{Host: host, Slug: slug})
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
@@ -128,6 +131,26 @@ func (h harness) get(host, path string) (int, string) {
|
||||
return w.Code, w.Body.String()
|
||||
}
|
||||
|
||||
// The error page links the platform's home page, also after a restart
|
||||
// while the API is down.
|
||||
func TestNotFoundLinksHome(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
now := time.Now()
|
||||
src := newSource()
|
||||
h := newHarness(t, src, dir, &now)
|
||||
if code, body := h.get("status.example.test", "/"); code != 404 || strings.Contains(body, "Zur Hauptseite") {
|
||||
t.Errorf("error page without a home page = %d, links one: %t", code, strings.Contains(body, "Zur Hauptseite"))
|
||||
}
|
||||
src.home = "https://example.test/"
|
||||
h.srv.Sync(context.Background())
|
||||
restarted := newHarness(t, &fakeSource{err: errors.New("connection refused")}, dir, &now)
|
||||
for _, hs := range []harness{h, restarted} {
|
||||
if code, body := hs.get("status.example.test", "/gone"); code != 404 || !strings.Contains(body, `href="https://example.test/"`) {
|
||||
t.Errorf("error page = %d, lacks the link to the home page", code)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestRouting(t *testing.T) {
|
||||
now := time.Now()
|
||||
h := newHarness(t, newSource(), t.TempDir(), &now)
|
||||
@@ -138,8 +161,8 @@ func TestRouting(t *testing.T) {
|
||||
}{
|
||||
{"status.example.test", "/acme", 200, "Acme status"},
|
||||
{"status.example.test:8082", "/acme", 200, "Alle Systeme funktionieren"},
|
||||
{"status.example.test", "/missing", 404, ""},
|
||||
{"status.example.test", "/", 404, ""},
|
||||
{"status.example.test", "/missing", 404, "Seite nicht gefunden"},
|
||||
{"status.example.test", "/", 404, "Seite nicht gefunden"},
|
||||
{"status.acme.test", "/", 200, "Acme on own domain"},
|
||||
{"status.acme.test", "/acme", 404, ""},
|
||||
{"other.test", "/", 404, ""},
|
||||
@@ -587,3 +610,169 @@ func TestEventsRefreshPagesAtOnce(t *testing.T) {
|
||||
t.Errorf("fetches = %d, want 2: one for the event, one for the change during it", calls)
|
||||
}
|
||||
}
|
||||
|
||||
// Every group of a page with many components lists them a page at a time,
|
||||
// and visitors can search them or show those with an outage only.
|
||||
func TestComponentPagingAndSearch(t *testing.T) {
|
||||
comp := func(id, name, status string) agentapi.Component {
|
||||
return agentapi.Component{ID: id, Name: name, Status: status, Days: []agentapi.Day{{Date: "2026-11-26", Uptime: 1}}}
|
||||
}
|
||||
core := agentapi.Section{Name: "Core"}
|
||||
for i := 0; i < 120; i++ {
|
||||
st := agentapi.PageOperational
|
||||
if i == 7 {
|
||||
st = agentapi.PageDegraded
|
||||
}
|
||||
core.Components = append(core.Components, comp(fmt.Sprintf("c%03d", i), fmt.Sprintf("web-%03d", i), st))
|
||||
}
|
||||
edge := agentapi.Section{Name: "Edge"}
|
||||
for i := 0; i < 10; i++ {
|
||||
st := agentapi.PageOperational
|
||||
if i == 3 {
|
||||
st = agentapi.PageOutage
|
||||
}
|
||||
edge.Components = append(edge.Components, comp(fmt.Sprintf("e%d", i), fmt.Sprintf("edge-%d", i), st))
|
||||
}
|
||||
core.Children = []agentapi.Section{edge}
|
||||
other := agentapi.Section{Name: "Other"}
|
||||
for i := 0; i < 30; i++ {
|
||||
other.Components = append(other.Components, comp(fmt.Sprintf("o%02d", i), fmt.Sprintf("other-%02d", i), agentapi.PageOperational))
|
||||
}
|
||||
now := time.Now()
|
||||
h := newHarness(t, &fakeSource{pages: map[string]agentapi.PageSnapshot{
|
||||
"|acme": {Title: "Acme status", Status: agentapi.PageOperational, ShowDetails: true, Sections: []agentapi.Section{core, other}},
|
||||
"|calm": {Title: "Calm", Status: agentapi.PageOperational, Sections: []agentapi.Section{other}},
|
||||
}}, t.TempDir(), &now)
|
||||
if _, body := h.get("status.example.test", "/calm?problems=1"); !strings.Contains(body, "Keine Komponente hat einen Ausfall.") || strings.Contains(body, "other-00") {
|
||||
t.Errorf("outages only without any lacks the notice")
|
||||
}
|
||||
|
||||
tests := []struct {
|
||||
path string
|
||||
has, hasNot []string
|
||||
}{
|
||||
// Every group shows its first page.
|
||||
{"/acme", []string{"web-000", "web-024", "Seite 1 von 5", "edge-0", "edge-9", "other-00", "other-24", "Seite 1 von 2",
|
||||
`id="g-0"`, `id="g-0.0"`, `id="g-1"`, `href="/acme?p.0=2#g-0"`, `href="/acme?p.1=2#g-1"`, `<path d="M0 0h3v22h-3z"`, "Nur Ausfälle (2)"},
|
||||
[]string{"web-025", "other-25", `rel="prev"`, "<rect", "Alle anzeigen"}},
|
||||
// Groups page on their own and keep the others' pages.
|
||||
{"/acme?p.0=2", []string{"web-025", "web-049", "Seite 2 von 5", `href="/acme#g-0"`, "edge-0", "other-00"}, []string{"web-024", "web-050"}},
|
||||
{"/acme?p.0=2&p.1=2", []string{"web-025", "other-29", `href="/acme?p.0=3&p.1=2#g-0"`, `href="/acme?p.0=2#g-1"`}, []string{"other-00"}},
|
||||
{"/acme?p.0=99", []string{"Seite 5 von 5", "web-119", "edge-9"}, nil},
|
||||
{"/acme?p.0=x", []string{"Seite 1 von 5"}, nil},
|
||||
// Outages only: degraded and down components, groups without any left out.
|
||||
{"/acme?problems=1", []string{"web-007", "edge-3", ">Core<", ">Edge<", ">130<", "checked", "Alle anzeigen"},
|
||||
[]string{"web-000", "edge-0", ">Other<", "Seite 1 von"}},
|
||||
{"/acme?problems=1&q=edge", []string{"edge-3"}, []string{"web-007", "edge-0"}},
|
||||
{"/acme?q=EDGE-", []string{"edge-0", "edge-9", `value="EDGE-"`, "Alle anzeigen"}, []string{"web-", "other-"}},
|
||||
{"/acme?q=edge", []string{"edge-0", "edge-9", ">Core<"}, []string{"web-", ">Other<"}},
|
||||
{"/acme?q=web-11", []string{"web-110", "web-119"}, []string{"web-109", "edge-"}},
|
||||
{"/acme?q=nothing", []string{"Keine Komponente passt zur Suche."}, []string{"web-", "edge-"}},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
code, body := h.get("status.example.test", tt.path)
|
||||
if code != http.StatusOK {
|
||||
t.Errorf("GET %s = %d", tt.path, code)
|
||||
continue
|
||||
}
|
||||
for _, s := range tt.has {
|
||||
if !strings.Contains(body, s) {
|
||||
t.Errorf("GET %s lacks %q", tt.path, s)
|
||||
}
|
||||
}
|
||||
for _, s := range tt.hasNot {
|
||||
if strings.Contains(body, s) {
|
||||
t.Errorf("GET %s has %q", tt.path, s)
|
||||
}
|
||||
}
|
||||
}
|
||||
// The detail page keeps the tooltips of the bars.
|
||||
if _, body := h.get("status.example.test", "/acme/components/c000"); !strings.Contains(body, "<title>2026-11-26") {
|
||||
t.Errorf("component page lacks the bar tooltips")
|
||||
}
|
||||
}
|
||||
|
||||
func (h harness) getFull(host, path string) *httptest.ResponseRecorder {
|
||||
req := httptest.NewRequest(http.MethodGet, path, nil)
|
||||
req.Host = host
|
||||
req.Header.Set("Accept-Language", "de")
|
||||
w := httptest.NewRecorder()
|
||||
h.r.ServeHTTP(w, req)
|
||||
return w
|
||||
}
|
||||
|
||||
func TestSearchAndPreviewMetadata(t *testing.T) {
|
||||
now := time.Now()
|
||||
src := newSource()
|
||||
src.set(func(f *fakeSource) {
|
||||
p := f.pages["|acme"]
|
||||
p.Description = "Status of **Acme** services.\n\nSecond paragraph."
|
||||
p.ShowDetails = true
|
||||
p.Sections = []agentapi.Section{{Components: []agentapi.Component{{ID: "c1", Name: "API", Status: agentapi.PageOperational}}}}
|
||||
f.pages["|acme"] = p
|
||||
})
|
||||
h := newHarness(t, src, t.TempDir(), &now)
|
||||
|
||||
_, body := h.get("status.example.test", "/acme")
|
||||
for _, want := range []string{
|
||||
`<meta name="description" content="Status of Acme services. Second paragraph.">`,
|
||||
`<link rel="canonical" href="http://status.example.test/acme/">`,
|
||||
`<link rel="alternate" hreflang="en" href="http://status.example.test/acme/?lang=en">`,
|
||||
`<link rel="alternate" hreflang="x-default" href="http://status.example.test/acme/">`,
|
||||
`<meta property="og:title" content="Acme status">`,
|
||||
`<meta property="og:image" content="http://status.example.test/acme/og.png?lang=de">`,
|
||||
`<meta property="og:locale" content="de_DE">`,
|
||||
`<meta name="twitter:card" content="summary_large_image">`,
|
||||
} {
|
||||
if !strings.Contains(body, want) {
|
||||
t.Errorf("status page lacks %s", want)
|
||||
}
|
||||
}
|
||||
if strings.Contains(body, "noindex") {
|
||||
t.Errorf("status page is noindex")
|
||||
}
|
||||
|
||||
// ?lang= picks the language and becomes the canonical address.
|
||||
_, body = h.get("status.example.test", "/acme?lang=en&q=api")
|
||||
if !strings.Contains(body, "All systems operational") || !strings.Contains(body, `<link rel="canonical" href="http://status.example.test/acme/?lang=en">`) {
|
||||
t.Errorf("?lang=en does not show English with its own canonical address")
|
||||
}
|
||||
|
||||
// A page without a description describes itself by its status.
|
||||
_, body = h.get("status.acme.test", "/")
|
||||
if !strings.Contains(body, `<meta name="description" content="Aktueller Status von Acme on own domain: Größere Störung. Störungen`) {
|
||||
t.Errorf("custom domain page lacks the generated description")
|
||||
}
|
||||
if !strings.Contains(body, `<link rel="canonical" href="http://status.acme.test/">`) {
|
||||
t.Errorf("custom domain canonical address missing")
|
||||
}
|
||||
|
||||
for _, path := range []string{"/acme/components/c1", "/acme/subscribe"} {
|
||||
if code, body := h.get("status.example.test", path); code == 200 && !strings.Contains(body, `<meta name="robots" content="noindex, nofollow">`) {
|
||||
t.Errorf("GET %s is indexable", path)
|
||||
}
|
||||
}
|
||||
|
||||
w := h.getFull("status.example.test", "/acme/og.png")
|
||||
if w.Code != 200 || w.Header().Get("Content-Type") != "image/png" || !bytes.HasPrefix(w.Body.Bytes(), []byte("\x89PNG")) {
|
||||
t.Errorf("preview image = %d %s", w.Code, w.Header().Get("Content-Type"))
|
||||
}
|
||||
if code, _ := h.get("status.example.test", "/missing/og.png"); code != 404 {
|
||||
t.Errorf("preview image of a missing page = %d, want 404", code)
|
||||
}
|
||||
|
||||
w = h.getFull("status.acme.test", "/sitemap.xml")
|
||||
sm := w.Body.String()
|
||||
if w.Code != 200 || !strings.Contains(sm, "<loc>http://status.acme.test/</loc>") || !strings.Contains(sm, `hreflang="de" href="http://status.acme.test/?lang=de"`) {
|
||||
t.Errorf("sitemap = %d %s", w.Code, sm)
|
||||
}
|
||||
|
||||
_, robots := h.get("status.acme.test", "/robots.txt")
|
||||
if !strings.Contains(robots, "Disallow: /api/") || !strings.Contains(robots, "Sitemap: http://status.acme.test/sitemap.xml") {
|
||||
t.Errorf("custom domain robots.txt = %q", robots)
|
||||
}
|
||||
_, robots = h.get("status.example.test", "/robots.txt")
|
||||
if !strings.Contains(robots, "Disallow: /*/api/") || strings.Contains(robots, "Sitemap:") {
|
||||
t.Errorf("shared host robots.txt = %q", robots)
|
||||
}
|
||||
}
|
||||
@@ -56,18 +56,26 @@ func (q *Queries) CreateAgent(ctx context.Context, arg CreateAgentParams) (Agent
|
||||
}
|
||||
|
||||
const createRegion = `-- name: CreateRegion :one
|
||||
INSERT INTO regions (org_id, key, name) VALUES ($1, $2, $3)
|
||||
RETURNING key, name, created_at, id, org_id
|
||||
INSERT INTO regions (org_id, key, name, latitude, longitude) VALUES ($1, $2, $3, $4, $5)
|
||||
RETURNING key, name, created_at, id, org_id, latitude, longitude
|
||||
`
|
||||
|
||||
type CreateRegionParams struct {
|
||||
OrgID *uuid.UUID
|
||||
Key string
|
||||
Name string
|
||||
OrgID *uuid.UUID
|
||||
Key string
|
||||
Name string
|
||||
Latitude *float64
|
||||
Longitude *float64
|
||||
}
|
||||
|
||||
func (q *Queries) CreateRegion(ctx context.Context, arg CreateRegionParams) (Region, error) {
|
||||
row := q.db.QueryRow(ctx, createRegion, arg.OrgID, arg.Key, arg.Name)
|
||||
row := q.db.QueryRow(ctx, createRegion,
|
||||
arg.OrgID,
|
||||
arg.Key,
|
||||
arg.Name,
|
||||
arg.Latitude,
|
||||
arg.Longitude,
|
||||
)
|
||||
var i Region
|
||||
err := row.Scan(
|
||||
&i.Key,
|
||||
@@ -75,6 +83,8 @@ func (q *Queries) CreateRegion(ctx context.Context, arg CreateRegionParams) (Reg
|
||||
&i.CreatedAt,
|
||||
&i.ID,
|
||||
&i.OrgID,
|
||||
&i.Latitude,
|
||||
&i.Longitude,
|
||||
)
|
||||
return i, err
|
||||
}
|
||||
@@ -113,7 +123,7 @@ INSERT INTO regions (org_id, key, name)
|
||||
VALUES (NULL, $1, coalesce(nullif($2::text, ''), $1))
|
||||
ON CONFLICT ON CONSTRAINT regions_owner_key_key
|
||||
DO UPDATE SET name = CASE WHEN $2::text = '' THEN regions.name ELSE EXCLUDED.name END
|
||||
RETURNING key, name, created_at, id, org_id
|
||||
RETURNING key, name, created_at, id, org_id, latitude, longitude
|
||||
`
|
||||
|
||||
type EnsurePlatformRegionParams struct {
|
||||
@@ -131,6 +141,8 @@ func (q *Queries) EnsurePlatformRegion(ctx context.Context, arg EnsurePlatformRe
|
||||
&i.CreatedAt,
|
||||
&i.ID,
|
||||
&i.OrgID,
|
||||
&i.Latitude,
|
||||
&i.Longitude,
|
||||
)
|
||||
return i, err
|
||||
}
|
||||
@@ -181,7 +193,7 @@ func (q *Queries) GetAgentByHash(ctx context.Context, tokenHash []byte) (GetAgen
|
||||
}
|
||||
|
||||
const getRegion = `-- name: GetRegion :one
|
||||
SELECT key, name, created_at, id, org_id FROM regions WHERE id = $1
|
||||
SELECT key, name, created_at, id, org_id, latitude, longitude FROM regions WHERE id = $1
|
||||
`
|
||||
|
||||
func (q *Queries) GetRegion(ctx context.Context, id uuid.UUID) (Region, error) {
|
||||
@@ -193,6 +205,8 @@ func (q *Queries) GetRegion(ctx context.Context, id uuid.UUID) (Region, error) {
|
||||
&i.CreatedAt,
|
||||
&i.ID,
|
||||
&i.OrgID,
|
||||
&i.Latitude,
|
||||
&i.Longitude,
|
||||
)
|
||||
return i, err
|
||||
}
|
||||
@@ -257,7 +271,7 @@ func (q *Queries) ListAgents(ctx context.Context, orgID *uuid.UUID) ([]ListAgent
|
||||
}
|
||||
|
||||
const listPlatformRegions = `-- name: ListPlatformRegions :many
|
||||
SELECT key, name, created_at, id, org_id FROM regions WHERE org_id IS NULL ORDER BY name, key
|
||||
SELECT key, name, created_at, id, org_id, latitude, longitude FROM regions WHERE org_id IS NULL ORDER BY name, key
|
||||
`
|
||||
|
||||
func (q *Queries) ListPlatformRegions(ctx context.Context) ([]Region, error) {
|
||||
@@ -275,6 +289,8 @@ func (q *Queries) ListPlatformRegions(ctx context.Context) ([]Region, error) {
|
||||
&i.CreatedAt,
|
||||
&i.ID,
|
||||
&i.OrgID,
|
||||
&i.Latitude,
|
||||
&i.Longitude,
|
||||
); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -287,7 +303,7 @@ func (q *Queries) ListPlatformRegions(ctx context.Context) ([]Region, error) {
|
||||
}
|
||||
|
||||
const listVisibleRegions = `-- name: ListVisibleRegions :many
|
||||
SELECT key, name, created_at, id, org_id FROM regions ORDER BY org_id IS NULL, name, key
|
||||
SELECT key, name, created_at, id, org_id, latitude, longitude FROM regions ORDER BY org_id IS NULL, name, key
|
||||
`
|
||||
|
||||
// Row-level security limits this to platform regions and the scope's org;
|
||||
@@ -307,6 +323,8 @@ func (q *Queries) ListVisibleRegions(ctx context.Context) ([]Region, error) {
|
||||
&i.CreatedAt,
|
||||
&i.ID,
|
||||
&i.OrgID,
|
||||
&i.Latitude,
|
||||
&i.Longitude,
|
||||
); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -437,3 +455,23 @@ func (q *Queries) TouchAgent(ctx context.Context, arg TouchAgentParams) error {
|
||||
_, err := q.db.Exec(ctx, touchAgent, arg.ID, arg.Release)
|
||||
return err
|
||||
}
|
||||
|
||||
const updateRegionLocation = `-- name: UpdateRegionLocation :execrows
|
||||
UPDATE regions SET latitude = $1, longitude = $2
|
||||
WHERE id = $3
|
||||
`
|
||||
|
||||
type UpdateRegionLocationParams struct {
|
||||
Latitude *float64
|
||||
Longitude *float64
|
||||
ID uuid.UUID
|
||||
}
|
||||
|
||||
// Null coordinates remove the location.
|
||||
func (q *Queries) UpdateRegionLocation(ctx context.Context, arg UpdateRegionLocationParams) (int64, error) {
|
||||
result, err := q.db.Exec(ctx, updateRegionLocation, arg.Latitude, arg.Longitude, arg.ID)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
return result.RowsAffected(), nil
|
||||
}
|
||||
@@ -124,44 +124,6 @@ func (q *Queries) DailyBucketsForMonitors(ctx context.Context, arg DailyBucketsF
|
||||
return items, nil
|
||||
}
|
||||
|
||||
const earliestDataDaily = `-- name: EarliestDataDaily :one
|
||||
SELECT bucket::timestamptz AS first FROM check_results_1d WHERE org_id = $1 ORDER BY bucket LIMIT 1
|
||||
`
|
||||
|
||||
// The day the organization's monitors first reported, if any did.
|
||||
func (q *Queries) EarliestDataDaily(ctx context.Context, orgID uuid.UUID) (time.Time, error) {
|
||||
row := q.db.QueryRow(ctx, earliestDataDaily, orgID)
|
||||
var first time.Time
|
||||
err := row.Scan(&first)
|
||||
return first, err
|
||||
}
|
||||
|
||||
const earliestDataRecent = `-- name: EarliestDataRecent :one
|
||||
SELECT f.time FROM monitors m
|
||||
CROSS JOIN LATERAL (
|
||||
SELECT c.time FROM check_results c
|
||||
WHERE c.org_id = $1 AND c.monitor_id = m.id AND c.time >= $2
|
||||
ORDER BY c.time LIMIT 1
|
||||
) f
|
||||
WHERE m.org_id = $1
|
||||
ORDER BY f.time LIMIT 1
|
||||
`
|
||||
|
||||
type EarliestDataRecentParams struct {
|
||||
OrgID uuid.UUID
|
||||
Time time.Time
|
||||
}
|
||||
|
||||
// When the organization's monitors first reported since $2, exactly: the
|
||||
// first result of each monitor is found through its index, so the cost
|
||||
// does not grow with the days of results.
|
||||
func (q *Queries) EarliestDataRecent(ctx context.Context, arg EarliestDataRecentParams) (time.Time, error) {
|
||||
row := q.db.QueryRow(ctx, earliestDataRecent, arg.OrgID, arg.Time)
|
||||
var time time.Time
|
||||
err := row.Scan(&time)
|
||||
return time, err
|
||||
}
|
||||
|
||||
const firstDataDaily = `-- name: FirstDataDaily :many
|
||||
SELECT monitor_id, region, min(bucket)::timestamptz AS first
|
||||
FROM check_results_1d
|
||||
|
||||
@@ -345,15 +345,6 @@ func (q *Queries) OwnedOrgs(ctx context.Context, userID uuid.UUID) ([]OwnedOrgsR
|
||||
return items, nil
|
||||
}
|
||||
|
||||
const purgeOrgCheckData = `-- name: PurgeOrgCheckData :exec
|
||||
SELECT purge_org_check_data($1)
|
||||
`
|
||||
|
||||
func (q *Queries) PurgeOrgCheckData(ctx context.Context, org uuid.UUID) error {
|
||||
_, err := q.db.Exec(ctx, purgeOrgCheckData, org)
|
||||
return err
|
||||
}
|
||||
|
||||
const scrubAuditEmail = `-- name: ScrubAuditEmail :exec
|
||||
UPDATE audit_events SET details = details - 'email' WHERE lower(details->>'email') = lower($1::text)
|
||||
`
|
||||
|
||||
@@ -337,6 +337,12 @@ type Org struct {
|
||||
LimitSubscribersPerWeek *int32
|
||||
}
|
||||
|
||||
type OrgPurge struct {
|
||||
OrgID uuid.UUID
|
||||
RequestedAt time.Time
|
||||
LeasedUntil time.Time
|
||||
}
|
||||
|
||||
type PlatformIdentity struct {
|
||||
ProviderID uuid.UUID
|
||||
Subject string
|
||||
@@ -378,6 +384,8 @@ type Region struct {
|
||||
CreatedAt time.Time
|
||||
ID uuid.UUID
|
||||
OrgID *uuid.UUID
|
||||
Latitude *float64
|
||||
Longitude *float64
|
||||
}
|
||||
|
||||
type Role struct {
|
||||
|
||||
@@ -0,0 +1,109 @@
|
||||
// Code generated by sqlc. DO NOT EDIT.
|
||||
// versions:
|
||||
// sqlc v1.31.1
|
||||
// source: org_purges.sql
|
||||
|
||||
package store
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
const claimOrgPurge = `-- name: ClaimOrgPurge :one
|
||||
UPDATE org_purges SET leased_until = now() + interval '15 minutes'
|
||||
WHERE org_id = (
|
||||
SELECT org_id FROM org_purges WHERE leased_until < now()
|
||||
ORDER BY requested_at LIMIT 1
|
||||
FOR UPDATE SKIP LOCKED
|
||||
)
|
||||
RETURNING org_id
|
||||
`
|
||||
|
||||
// System scope: leases the longest waiting purge no other instance holds.
|
||||
func (q *Queries) ClaimOrgPurge(ctx context.Context) (uuid.UUID, error) {
|
||||
row := q.db.QueryRow(ctx, claimOrgPurge)
|
||||
var org_id uuid.UUID
|
||||
err := row.Scan(&org_id)
|
||||
return org_id, err
|
||||
}
|
||||
|
||||
const countOrgPurges = `-- name: CountOrgPurges :one
|
||||
SELECT count(*) FROM org_purges
|
||||
`
|
||||
|
||||
func (q *Queries) CountOrgPurges(ctx context.Context) (int64, error) {
|
||||
row := q.db.QueryRow(ctx, countOrgPurges)
|
||||
var count int64
|
||||
err := row.Scan(&count)
|
||||
return count, err
|
||||
}
|
||||
|
||||
const extendOrgPurge = `-- name: ExtendOrgPurge :exec
|
||||
UPDATE org_purges SET leased_until = now() + interval '15 minutes' WHERE org_id = $1
|
||||
`
|
||||
|
||||
func (q *Queries) ExtendOrgPurge(ctx context.Context, orgID uuid.UUID) error {
|
||||
_, err := q.db.Exec(ctx, extendOrgPurge, orgID)
|
||||
return err
|
||||
}
|
||||
|
||||
const finishOrgPurge = `-- name: FinishOrgPurge :exec
|
||||
DELETE FROM org_purges WHERE org_id = $1
|
||||
`
|
||||
|
||||
func (q *Queries) FinishOrgPurge(ctx context.Context, orgID uuid.UUID) error {
|
||||
_, err := q.db.Exec(ctx, finishOrgPurge, orgID)
|
||||
return err
|
||||
}
|
||||
|
||||
const orgCheckDataChunks = `-- name: OrgCheckDataChunks :many
|
||||
SELECT chunk::text FROM org_check_data_chunks() AS chunk
|
||||
`
|
||||
|
||||
func (q *Queries) OrgCheckDataChunks(ctx context.Context) ([]string, error) {
|
||||
rows, err := q.db.Query(ctx, orgCheckDataChunks)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
items := []string{}
|
||||
for rows.Next() {
|
||||
var chunk string
|
||||
if err := rows.Scan(&chunk); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
items = append(items, chunk)
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return items, nil
|
||||
}
|
||||
|
||||
const purgeOrgCheckChunk = `-- name: PurgeOrgCheckChunk :one
|
||||
SELECT purge_org_check_chunk($1::uuid, $2::text)::bigint AS rows
|
||||
`
|
||||
|
||||
type PurgeOrgCheckChunkParams struct {
|
||||
OrgID uuid.UUID
|
||||
Chunk string
|
||||
}
|
||||
|
||||
func (q *Queries) PurgeOrgCheckChunk(ctx context.Context, arg PurgeOrgCheckChunkParams) (int64, error) {
|
||||
row := q.db.QueryRow(ctx, purgeOrgCheckChunk, arg.OrgID, arg.Chunk)
|
||||
var rows int64
|
||||
err := row.Scan(&rows)
|
||||
return rows, err
|
||||
}
|
||||
|
||||
const queueOrgPurge = `-- name: QueueOrgPurge :exec
|
||||
INSERT INTO org_purges (org_id) VALUES ($1) ON CONFLICT DO NOTHING
|
||||
`
|
||||
|
||||
// System scope: has the check data of a deleted organization purged.
|
||||
func (q *Queries) QueueOrgPurge(ctx context.Context, orgID uuid.UUID) error {
|
||||
_, err := q.db.Exec(ctx, queueOrgPurge, orgID)
|
||||
return err
|
||||
}
|
||||
@@ -46,6 +46,8 @@ type Querier interface {
|
||||
// System scope. Leases due rows for five minutes so a crashed sender's rows
|
||||
// come back; SKIP LOCKED lets every API replica work the outbox.
|
||||
ClaimNotifications(ctx context.Context, max int32) ([]uuid.UUID, error)
|
||||
// System scope: leases the longest waiting purge no other instance holds.
|
||||
ClaimOrgPurge(ctx context.Context) (uuid.UUID, error)
|
||||
// System scope; leased like ClaimNotifications.
|
||||
ClaimSubscriberNotifications(ctx context.Context, max int32) ([]uuid.UUID, error)
|
||||
// Shortens tokens that would outlive a newly set maximum lifetime.
|
||||
@@ -56,6 +58,7 @@ type Querier interface {
|
||||
ConfirmPageSubscriber(ctx context.Context, id uuid.UUID) error
|
||||
CountMonitors(ctx context.Context, orgID uuid.UUID) (int64, error)
|
||||
CountOpenSupportTickets(ctx context.Context, userID uuid.UUID) (int64, error)
|
||||
CountOrgPurges(ctx context.Context) (int64, error)
|
||||
CountOwnedOrgs(ctx context.Context, userID uuid.UUID) (int64, error)
|
||||
CountOwners(ctx context.Context, orgID uuid.UUID) (int64, error)
|
||||
CountPageSubscribers(ctx context.Context, pageID uuid.UUID) (CountPageSubscribersRow, error)
|
||||
@@ -90,6 +93,10 @@ type Querier interface {
|
||||
CreateSSOProvider(ctx context.Context, arg CreateSSOProviderParams) (SsoProvider, error)
|
||||
CreateStatusPage(ctx context.Context, arg CreateStatusPageParams) (StatusPage, error)
|
||||
CreateStatusPageGroup(ctx context.Context, arg CreateStatusPageGroupParams) (StatusPageGroup, error)
|
||||
// Creates many groups of a page at once, with ids the caller chose. Parents
|
||||
// must exist before their children are created; a nil parent id (all
|
||||
// zeros) means none.
|
||||
CreateStatusPageGroups(ctx context.Context, arg CreateStatusPageGroupsParams) error
|
||||
CreateSupportTicket(ctx context.Context, arg CreateSupportTicketParams) (SupportTicket, error)
|
||||
CreateUser(ctx context.Context, arg CreateUserParams) (User, error)
|
||||
DailyBuckets(ctx context.Context, arg DailyBucketsParams) ([]DailyBucketsRow, error)
|
||||
@@ -133,12 +140,6 @@ type Querier interface {
|
||||
// for two days, after which only the verify button tries again. A verified
|
||||
// one is checked daily, hourly once its record went missing.
|
||||
DomainsToCheck(ctx context.Context, arg DomainsToCheckParams) ([]DomainsToCheckRow, error)
|
||||
// The day the organization's monitors first reported, if any did.
|
||||
EarliestDataDaily(ctx context.Context, orgID uuid.UUID) (time.Time, error)
|
||||
// When the organization's monitors first reported since $2, exactly: the
|
||||
// first result of each monitor is found through its index, so the cost
|
||||
// does not grow with the days of results.
|
||||
EarliestDataRecent(ctx context.Context, arg EarliestDataRecentParams) (time.Time, error)
|
||||
EmailKeyTaken(ctx context.Context, emailKey *string) (bool, error)
|
||||
EnableTOTP(ctx context.Context, arg EnableTOTPParams) error
|
||||
EnqueueNotification(ctx context.Context, arg EnqueueNotificationParams) error
|
||||
@@ -149,9 +150,11 @@ type Querier interface {
|
||||
EnsurePlatformRegion(ctx context.Context, arg EnsurePlatformRegionParams) (Region, error)
|
||||
// Evidence of a monitor in a time span, to link results to it.
|
||||
EvidenceBetween(ctx context.Context, arg EvidenceBetweenParams) ([]EvidenceBetweenRow, error)
|
||||
ExtendOrgPurge(ctx context.Context, orgID uuid.UUID) error
|
||||
// System scope: resolves a request to a page by verified custom domain or
|
||||
// by slug.
|
||||
FindPublishedPage(ctx context.Context, arg FindPublishedPageParams) (StatusPage, error)
|
||||
FinishOrgPurge(ctx context.Context, orgID uuid.UUID) error
|
||||
// Alerts of org that fire and were repeated within the stale period.
|
||||
FiringAlerts(ctx context.Context, arg FiringAlertsParams) ([]FiringAlertsRow, error)
|
||||
// FiringAlerts newest first, a page from a keyset cursor (see paging.go)
|
||||
@@ -325,6 +328,7 @@ type Querier interface {
|
||||
OpenIncidents(ctx context.Context, orgID uuid.UUID) ([]Incident, error)
|
||||
OrgAssignmentsExport(ctx context.Context, orgID uuid.UUID) ([]OrgAssignmentsExportRow, error)
|
||||
OrgAuditExport(ctx context.Context, orgID uuid.UUID) ([]OrgAuditExportRow, error)
|
||||
OrgCheckDataChunks(ctx context.Context) ([]string, error)
|
||||
OrgDailyStats(ctx context.Context, orgID uuid.UUID) ([]OrgDailyStatsRow, error)
|
||||
OrgIDBySlug(ctx context.Context, slug string) (uuid.UUID, error)
|
||||
OrgIncidentUpdatesExport(ctx context.Context, orgID uuid.UUID) ([]OrgIncidentUpdatesExportRow, error)
|
||||
@@ -349,13 +353,15 @@ type Querier interface {
|
||||
PurgeInvitations(ctx context.Context, expiresAt time.Time) (int64, error)
|
||||
// Delivered and given-up notifications; pending ones are still being worked.
|
||||
PurgeNotifications(ctx context.Context, createdAt time.Time) (int64, error)
|
||||
PurgeOrgCheckData(ctx context.Context, org uuid.UUID) error
|
||||
PurgeOrgCheckChunk(ctx context.Context, arg PurgeOrgCheckChunkParams) (int64, error)
|
||||
PurgeSubscriberNotifications(ctx context.Context, createdAt time.Time) (int64, error)
|
||||
// Unconfirmed subscriptions are kept for as long as they count towards the
|
||||
// weekly limit, so letting them lapse frees no room for more.
|
||||
PurgeUnconfirmedSubscribers(ctx context.Context, createdAt time.Time) (int64, error)
|
||||
// Accounts never confirmed; they belong to no organization.
|
||||
PurgeUnverifiedUsers(ctx context.Context, createdAt time.Time) (int64, error)
|
||||
// System scope: has the check data of a deleted organization purged.
|
||||
QueueOrgPurge(ctx context.Context, orgID uuid.UUID) error
|
||||
// Raw results bucketed by width since a point in time, for short ranges.
|
||||
RangeBuckets(ctx context.Context, arg RangeBucketsParams) ([]RangeBucketsRow, error)
|
||||
// The daily aggregate rebucketed by width, for ranges of months.
|
||||
@@ -401,7 +407,9 @@ type Querier interface {
|
||||
SetPlatformSetting(ctx context.Context, arg SetPlatformSettingParams) error
|
||||
// Changing the domain drops a previous verification and its checks.
|
||||
SetStatusPageDomain(ctx context.Context, arg SetStatusPageDomainParams) (StatusPage, error)
|
||||
SetStatusPageMonitorGroup(ctx context.Context, arg SetStatusPageMonitorGroupParams) error
|
||||
// Files many monitors of a page at once; a nil group id (all zeros) files
|
||||
// a monitor under none.
|
||||
SetStatusPageMonitorGroups(ctx context.Context, arg SetStatusPageMonitorGroupsParams) error
|
||||
SetSupportTicketStatus(ctx context.Context, arg SetSupportTicketStatusParams) (int64, error)
|
||||
SetUserAdmin(ctx context.Context, arg SetUserAdminParams) (int64, error)
|
||||
SetUserLocale(ctx context.Context, arg SetUserLocaleParams) error
|
||||
@@ -452,6 +460,8 @@ type Querier interface {
|
||||
UpdateMonitor(ctx context.Context, arg UpdateMonitorParams) (Monitor, error)
|
||||
UpdateOrgPolicy(ctx context.Context, arg UpdateOrgPolicyParams) (Org, error)
|
||||
UpdatePlatformIDP(ctx context.Context, arg UpdatePlatformIDPParams) (PlatformIdentityProvider, error)
|
||||
// Null coordinates remove the location.
|
||||
UpdateRegionLocation(ctx context.Context, arg UpdateRegionLocationParams) (int64, error)
|
||||
UpdateRole(ctx context.Context, arg UpdateRoleParams) (Role, error)
|
||||
UpdateSSOProvider(ctx context.Context, arg UpdateSSOProviderParams) (SsoProvider, error)
|
||||
UpdateStatusPage(ctx context.Context, arg UpdateStatusPageParams) (StatusPage, error)
|
||||
|
||||
@@ -1,7 +1,12 @@
|
||||
-- name: CreateRegion :one
|
||||
INSERT INTO regions (org_id, key, name) VALUES ($1, $2, $3)
|
||||
INSERT INTO regions (org_id, key, name, latitude, longitude) VALUES ($1, $2, $3, $4, $5)
|
||||
RETURNING *;
|
||||
|
||||
-- name: UpdateRegionLocation :execrows
|
||||
-- Null coordinates remove the location.
|
||||
UPDATE regions SET latitude = sqlc.narg(latitude), longitude = sqlc.narg(longitude)
|
||||
WHERE id = sqlc.arg(id);
|
||||
|
||||
-- name: EnsurePlatformRegion :one
|
||||
-- An empty name names a new region after its key and keeps an existing name.
|
||||
INSERT INTO regions (org_id, key, name)
|
||||
|
||||
@@ -125,23 +125,6 @@ FROM check_results_1d
|
||||
WHERE org_id = $1 AND monitor_id = $2
|
||||
GROUP BY 1, 2;
|
||||
|
||||
-- name: EarliestDataDaily :one
|
||||
-- The day the organization's monitors first reported, if any did.
|
||||
SELECT bucket::timestamptz AS first FROM check_results_1d WHERE org_id = $1 ORDER BY bucket LIMIT 1;
|
||||
|
||||
-- name: EarliestDataRecent :one
|
||||
-- When the organization's monitors first reported since $2, exactly: the
|
||||
-- first result of each monitor is found through its index, so the cost
|
||||
-- does not grow with the days of results.
|
||||
SELECT f.time FROM monitors m
|
||||
CROSS JOIN LATERAL (
|
||||
SELECT c.time FROM check_results c
|
||||
WHERE c.org_id = $1 AND c.monitor_id = m.id AND c.time >= $2
|
||||
ORDER BY c.time LIMIT 1
|
||||
) f
|
||||
WHERE m.org_id = $1
|
||||
ORDER BY f.time LIMIT 1;
|
||||
|
||||
-- name: FirstDataRecent :many
|
||||
-- When each region of a monitor first reported since $3, exactly. Used for
|
||||
-- data younger than the daily aggregate's resolution.
|
||||
|
||||
@@ -49,9 +49,6 @@ UPDATE audit_events SET details = details - 'email' WHERE lower(details->>'email
|
||||
-- name: DeleteInvitationsForEmail :exec
|
||||
DELETE FROM invitations WHERE email = $1;
|
||||
|
||||
-- name: PurgeOrgCheckData :exec
|
||||
SELECT purge_org_check_data($1);
|
||||
|
||||
-- name: DeleteOrgStorage :exec
|
||||
DELETE FROM agent_storage WHERE owner = 'org:' || sqlc.arg(org_id)::uuid::text;
|
||||
|
||||
|
||||
@@ -0,0 +1,28 @@
|
||||
-- name: QueueOrgPurge :exec
|
||||
-- System scope: has the check data of a deleted organization purged.
|
||||
INSERT INTO org_purges (org_id) VALUES ($1) ON CONFLICT DO NOTHING;
|
||||
|
||||
-- name: ClaimOrgPurge :one
|
||||
-- System scope: leases the longest waiting purge no other instance holds.
|
||||
UPDATE org_purges SET leased_until = now() + interval '15 minutes'
|
||||
WHERE org_id = (
|
||||
SELECT org_id FROM org_purges WHERE leased_until < now()
|
||||
ORDER BY requested_at LIMIT 1
|
||||
FOR UPDATE SKIP LOCKED
|
||||
)
|
||||
RETURNING org_id;
|
||||
|
||||
-- name: ExtendOrgPurge :exec
|
||||
UPDATE org_purges SET leased_until = now() + interval '15 minutes' WHERE org_id = $1;
|
||||
|
||||
-- name: FinishOrgPurge :exec
|
||||
DELETE FROM org_purges WHERE org_id = $1;
|
||||
|
||||
-- name: CountOrgPurges :one
|
||||
SELECT count(*) FROM org_purges;
|
||||
|
||||
-- name: OrgCheckDataChunks :many
|
||||
SELECT chunk::text FROM org_check_data_chunks() AS chunk;
|
||||
|
||||
-- name: PurgeOrgCheckChunk :one
|
||||
SELECT purge_org_check_chunk(sqlc.arg(org_id)::uuid, sqlc.arg(chunk)::text)::bigint AS rows;
|
||||
@@ -100,9 +100,23 @@ DELETE FROM status_page_monitors WHERE page_id = $1;
|
||||
INSERT INTO status_page_monitors (page_id, monitor_id, org_id, section, group_id, label, position)
|
||||
VALUES ($1, $2, $3, $4, $5, $6, $7);
|
||||
|
||||
-- name: SetStatusPageMonitorGroup :exec
|
||||
UPDATE status_page_monitors SET group_id = $3, section = $4
|
||||
WHERE page_id = $1 AND monitor_id = $2;
|
||||
-- name: SetStatusPageMonitorGroups :exec
|
||||
-- Files many monitors of a page at once; a nil group id (all zeros) files
|
||||
-- a monitor under none.
|
||||
UPDATE status_page_monitors spm
|
||||
SET group_id = nullif(v.group_id, '00000000-0000-0000-0000-000000000000'::uuid), section = v.section
|
||||
FROM (SELECT unnest(sqlc.arg(monitor_ids)::uuid[]) AS monitor_id, unnest(sqlc.arg(group_ids)::uuid[]) AS group_id,
|
||||
unnest(sqlc.arg(sections)::text[]) AS section) AS v
|
||||
WHERE spm.page_id = sqlc.arg(page_id) AND spm.monitor_id = v.monitor_id;
|
||||
|
||||
-- name: CreateStatusPageGroups :exec
|
||||
-- Creates many groups of a page at once, with ids the caller chose. Parents
|
||||
-- must exist before their children are created; a nil parent id (all
|
||||
-- zeros) means none.
|
||||
INSERT INTO status_page_groups (id, page_id, org_id, parent_id, name, position)
|
||||
SELECT v.id, sqlc.arg(page_id), sqlc.arg(org_id), nullif(v.parent_id, '00000000-0000-0000-0000-000000000000'::uuid), v.name, v.position
|
||||
FROM (SELECT unnest(sqlc.arg(ids)::uuid[]) AS id, unnest(sqlc.arg(parent_ids)::uuid[]) AS parent_id,
|
||||
unnest(sqlc.arg(names)::text[]) AS name, unnest(sqlc.arg(positions)::int[]) AS position) AS v;
|
||||
|
||||
-- name: ListStatusPageGroups :many
|
||||
SELECT * FROM status_page_groups
|
||||
|
||||
@@ -150,6 +150,37 @@ func (q *Queries) CreateStatusPageGroup(ctx context.Context, arg CreateStatusPag
|
||||
return i, err
|
||||
}
|
||||
|
||||
const createStatusPageGroups = `-- name: CreateStatusPageGroups :exec
|
||||
INSERT INTO status_page_groups (id, page_id, org_id, parent_id, name, position)
|
||||
SELECT v.id, $1, $2, nullif(v.parent_id, '00000000-0000-0000-0000-000000000000'::uuid), v.name, v.position
|
||||
FROM (SELECT unnest($3::uuid[]) AS id, unnest($4::uuid[]) AS parent_id,
|
||||
unnest($5::text[]) AS name, unnest($6::int[]) AS position) AS v
|
||||
`
|
||||
|
||||
type CreateStatusPageGroupsParams struct {
|
||||
PageID uuid.UUID
|
||||
OrgID uuid.UUID
|
||||
Ids []uuid.UUID
|
||||
ParentIds []uuid.UUID
|
||||
Names []string
|
||||
Positions []int32
|
||||
}
|
||||
|
||||
// Creates many groups of a page at once, with ids the caller chose. Parents
|
||||
// must exist before their children are created; a nil parent id (all
|
||||
// zeros) means none.
|
||||
func (q *Queries) CreateStatusPageGroups(ctx context.Context, arg CreateStatusPageGroupsParams) error {
|
||||
_, err := q.db.Exec(ctx, createStatusPageGroups,
|
||||
arg.PageID,
|
||||
arg.OrgID,
|
||||
arg.Ids,
|
||||
arg.ParentIds,
|
||||
arg.Names,
|
||||
arg.Positions,
|
||||
)
|
||||
return err
|
||||
}
|
||||
|
||||
const deleteStatusPage = `-- name: DeleteStatusPage :execrows
|
||||
DELETE FROM status_pages WHERE id = $1
|
||||
`
|
||||
@@ -563,24 +594,29 @@ func (q *Queries) SetStatusPageDomain(ctx context.Context, arg SetStatusPageDoma
|
||||
return i, err
|
||||
}
|
||||
|
||||
const setStatusPageMonitorGroup = `-- name: SetStatusPageMonitorGroup :exec
|
||||
UPDATE status_page_monitors SET group_id = $3, section = $4
|
||||
WHERE page_id = $1 AND monitor_id = $2
|
||||
const setStatusPageMonitorGroups = `-- name: SetStatusPageMonitorGroups :exec
|
||||
UPDATE status_page_monitors spm
|
||||
SET group_id = nullif(v.group_id, '00000000-0000-0000-0000-000000000000'::uuid), section = v.section
|
||||
FROM (SELECT unnest($2::uuid[]) AS monitor_id, unnest($3::uuid[]) AS group_id,
|
||||
unnest($4::text[]) AS section) AS v
|
||||
WHERE spm.page_id = $1 AND spm.monitor_id = v.monitor_id
|
||||
`
|
||||
|
||||
type SetStatusPageMonitorGroupParams struct {
|
||||
PageID uuid.UUID
|
||||
MonitorID uuid.UUID
|
||||
GroupID *uuid.UUID
|
||||
Section string
|
||||
type SetStatusPageMonitorGroupsParams struct {
|
||||
PageID uuid.UUID
|
||||
MonitorIds []uuid.UUID
|
||||
GroupIds []uuid.UUID
|
||||
Sections []string
|
||||
}
|
||||
|
||||
func (q *Queries) SetStatusPageMonitorGroup(ctx context.Context, arg SetStatusPageMonitorGroupParams) error {
|
||||
_, err := q.db.Exec(ctx, setStatusPageMonitorGroup,
|
||||
// Files many monitors of a page at once; a nil group id (all zeros) files
|
||||
// a monitor under none.
|
||||
func (q *Queries) SetStatusPageMonitorGroups(ctx context.Context, arg SetStatusPageMonitorGroupsParams) error {
|
||||
_, err := q.db.Exec(ctx, setStatusPageMonitorGroups,
|
||||
arg.PageID,
|
||||
arg.MonitorID,
|
||||
arg.GroupID,
|
||||
arg.Section,
|
||||
arg.MonitorIds,
|
||||
arg.GroupIds,
|
||||
arg.Sections,
|
||||
)
|
||||
return err
|
||||
}
|
||||
|
||||
@@ -118,3 +118,61 @@
|
||||
font-size: max(16px, 1em);
|
||||
}
|
||||
}
|
||||
|
||||
/* Region maps: a labelled pin per region, filled when it is selected;
|
||||
its dot is green while a checker of the region is live. */
|
||||
.region-pin {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
padding: 3px 9px 3px 5px;
|
||||
border: 1px solid var(--color-rule);
|
||||
border-radius: 9999px;
|
||||
background: var(--color-paper);
|
||||
color: var(--color-ink);
|
||||
font: 500 11px/1.3 var(--font-sans);
|
||||
white-space: nowrap;
|
||||
cursor: pointer;
|
||||
box-shadow: 0 1px 4px rgb(0 0 0 / 0.25);
|
||||
transition: background-color 0.15s, color 0.15s, transform 0.15s, box-shadow 0.15s;
|
||||
}
|
||||
.region-pin-dot {
|
||||
flex: none;
|
||||
width: 8px;
|
||||
height: 8px;
|
||||
border-radius: 9999px;
|
||||
background: var(--color-unknown);
|
||||
box-shadow: 0 0 0 2px var(--color-paper);
|
||||
}
|
||||
.region-pin:not([data-live="0"]) .region-pin-dot { background: var(--color-up); }
|
||||
.region-pin.is-checked {
|
||||
border-color: var(--color-ink);
|
||||
background: var(--color-ink);
|
||||
color: var(--color-paper);
|
||||
}
|
||||
.region-pin.is-checked .region-pin-dot { box-shadow: 0 0 0 2px var(--color-ink); }
|
||||
.maplibregl-marker.is-hover,
|
||||
.maplibregl-marker:hover { z-index: 3; }
|
||||
.is-hover > .region-pin,
|
||||
.region-pin:hover {
|
||||
transform: scale(1.1);
|
||||
box-shadow: 0 2px 8px rgb(0 0 0 / 0.35);
|
||||
}
|
||||
@media (pointer: coarse) {
|
||||
.region-pin {
|
||||
padding: 6px 11px 6px 8px;
|
||||
font-size: 12px;
|
||||
}
|
||||
}
|
||||
.region-pin:focus-visible { outline: 2px solid var(--color-maintenance); outline-offset: 2px; }
|
||||
.region-pick {
|
||||
width: 14px;
|
||||
height: 14px;
|
||||
border: 2px solid var(--color-paper);
|
||||
border-radius: 9999px;
|
||||
background: var(--color-down);
|
||||
box-shadow: 0 1px 4px rgb(0 0 0 / 0.4);
|
||||
}
|
||||
.region-row { transition: background-color 0.15s; }
|
||||
.region-row.is-hover { background: color-mix(in srgb, var(--color-ink) 7%, transparent); }
|
||||
.region-map .maplibregl-ctrl-attrib { font-size: 10px; }
|
||||
+233
-5
@@ -241,7 +241,7 @@
|
||||
if (checkAll) {
|
||||
const on = checkAll.dataset.checkAll === "on";
|
||||
checkAll.closest("form")?.querySelectorAll(checkAll.dataset.checkTarget).forEach((box) => {
|
||||
if (box.closest("[data-row]")?.hidden) return;
|
||||
if (box.closest("[data-row]")?.hasAttribute("data-filtered-out")) return;
|
||||
box.checked = on;
|
||||
if (on) addRowFields(box);
|
||||
});
|
||||
@@ -341,15 +341,72 @@
|
||||
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.
|
||||
// Lists with data-page-size show that many of their rows at a time, of
|
||||
// those a filter leaves; the [data-row-pager] naming the list turns the
|
||||
// pages. The other rows stay in the DOM, so forms still send them.
|
||||
// Selects with data-lazy-options hold their chosen option only; the full
|
||||
// list comes from the form's row template once the row is shown or used.
|
||||
const fillOptions = (sel) => {
|
||||
const tpl = sel.closest("form")?.querySelector("template[data-row-fields]");
|
||||
const full = tpl?.content.querySelector(`select[data-field="${sel.dataset.field}"]`);
|
||||
if (!full) return;
|
||||
const value = sel.value;
|
||||
sel.replaceChildren(...[...full.options].map((o) => o.cloneNode(true)));
|
||||
sel.value = value;
|
||||
sel.removeAttribute("data-lazy-options");
|
||||
};
|
||||
document.addEventListener("focusin", (ev) => {
|
||||
if (ev.target.matches?.("select[data-lazy-options]")) fillOptions(ev.target);
|
||||
});
|
||||
const showRowPage = (list, page) => {
|
||||
const rows = [...list.querySelectorAll(":scope > [data-row]")];
|
||||
const size = Number(list.dataset.pageSize) || rows.length || 1;
|
||||
const shown = rows.filter((row) => !row.hasAttribute("data-filtered-out"));
|
||||
const pages = Math.max(1, Math.ceil(shown.length / size));
|
||||
page = Math.min(Math.max(0, page), pages - 1);
|
||||
list.dataset.page = String(page);
|
||||
for (const row of rows) row.hidden = true;
|
||||
for (const row of shown.slice(page * size, (page + 1) * size)) {
|
||||
row.hidden = false;
|
||||
row.querySelectorAll("select[data-lazy-options]").forEach(fillOptions);
|
||||
}
|
||||
for (const nav of document.querySelectorAll(`[data-row-pager="#${list.id}"]`)) {
|
||||
nav.hidden = pages < 2;
|
||||
nav.querySelector('[data-row-page="prev"]').disabled = page === 0;
|
||||
nav.querySelector('[data-row-page="next"]').disabled = page >= pages - 1;
|
||||
const status = nav.querySelector("[data-row-page-status]");
|
||||
if (status) {
|
||||
const values = {
|
||||
from: shown.length ? page * size + 1 : 0,
|
||||
to: Math.min((page + 1) * size, shown.length),
|
||||
total: shown.length,
|
||||
};
|
||||
status.textContent = status.dataset.template.replace(/\{(\w+)\}/g, (m, k) => values[k] ?? m);
|
||||
}
|
||||
}
|
||||
};
|
||||
for (const list of document.querySelectorAll("[data-page-size][id]")) showRowPage(list, 0);
|
||||
document.addEventListener("click", (ev) => {
|
||||
const btn = ev.target.closest("[data-row-page]");
|
||||
if (!btn) return;
|
||||
const list = document.querySelector(btn.closest("[data-row-pager]").dataset.rowPager);
|
||||
showRowPage(list, Number(list.dataset.page || 0) + (btn.dataset.rowPage === "next" ? 1 : -1));
|
||||
});
|
||||
|
||||
// [data-filter-rows] hides the rows of the list it names whose text, or
|
||||
// that of their [data-filter-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);
|
||||
const list = document.querySelector(input.dataset.filterRows);
|
||||
for (const row of list.querySelectorAll(":scope > [data-row]")) {
|
||||
const text = (row.querySelector("[data-filter-text]") ?? row).textContent;
|
||||
const out = needle !== "" && !text.toLowerCase().includes(needle);
|
||||
row.toggleAttribute("data-filtered-out", out);
|
||||
row.hidden = out;
|
||||
}
|
||||
if (list.dataset.pageSize) showRowPage(list, 0);
|
||||
});
|
||||
|
||||
// Only the settings of the selected check type are shown and submitted.
|
||||
@@ -531,4 +588,175 @@ for (const el of document.querySelectorAll("input[data-tz-default]")) {
|
||||
};
|
||||
for (const t of ed.querySelectorAll("[data-md-tab]")) t.addEventListener("click", () => show(t.dataset.mdTab));
|
||||
}
|
||||
|
||||
// Region maps show the [data-lat][data-lon] elements inside the element
|
||||
// [data-region-items] selects, on the map server's tiles. MapLibre loads
|
||||
// only on pages with a map, and the map stays hidden when it cannot.
|
||||
let maplibre;
|
||||
const loadMaplibre = (server) =>
|
||||
(maplibre ??= window.maplibregl
|
||||
? Promise.resolve(window.maplibregl)
|
||||
: new Promise((resolve, reject) => {
|
||||
const css = Object.assign(document.createElement("link"), { rel: "stylesheet", href: `${server}/vendor/maplibre-gl.css` });
|
||||
const js = Object.assign(document.createElement("script"), { src: `${server}/vendor/maplibre-gl.js` });
|
||||
js.onload = () => (window.maplibregl ? resolve(window.maplibregl) : reject(new Error("no MapLibre")));
|
||||
js.onerror = reject;
|
||||
document.head.append(css, js);
|
||||
}));
|
||||
const darkScheme = window.matchMedia?.("(prefers-color-scheme: dark)");
|
||||
const mapStyle = (server) => `${server}/style-${darkScheme?.matches ? "dark" : "light"}.json`;
|
||||
|
||||
// A click on the map fills the coordinates of the location form last
|
||||
// opened or focused, else the one marked [data-location-default].
|
||||
let locationTarget = document.querySelector("[data-location-default]");
|
||||
document.addEventListener("focusin", (ev) => {
|
||||
const form = ev.target.closest?.("[data-location-form]");
|
||||
if (form) locationTarget = form;
|
||||
});
|
||||
document.addEventListener("click", (ev) => {
|
||||
const toggle = ev.target.closest("[data-location-toggle]");
|
||||
if (toggle) {
|
||||
const row = document.getElementById(toggle.dataset.locationToggle);
|
||||
row.hidden = !row.hidden;
|
||||
const form = row.querySelector("[data-location-form]");
|
||||
if (!row.hidden) {
|
||||
locationTarget = form;
|
||||
row.querySelector("[data-location-field]")?.focus();
|
||||
} else if (locationTarget === form) {
|
||||
locationTarget = document.querySelector("[data-location-default]");
|
||||
}
|
||||
}
|
||||
const clear = ev.target.closest("[data-location-clear]");
|
||||
if (clear) {
|
||||
const form = clear.closest("form");
|
||||
for (const f of form.querySelectorAll("[data-location-field]")) f.value = "";
|
||||
form.requestSubmit();
|
||||
}
|
||||
});
|
||||
|
||||
const initRegionMap = async (box) => {
|
||||
const server = box.dataset.mapServer;
|
||||
let gl;
|
||||
try {
|
||||
gl = await loadMaplibre(server);
|
||||
} catch {
|
||||
return;
|
||||
}
|
||||
const items = [...document.querySelectorAll(`${box.dataset.regionItems} [data-lat][data-lon]`)];
|
||||
const lngLat = (item) => [Number(item.dataset.lon), Number(item.dataset.lat)];
|
||||
box.hidden = false;
|
||||
let map;
|
||||
try {
|
||||
// Scrolling the page must not zoom the map; the buttons, a double
|
||||
// click and pinching do. On touch screens one finger scrolls the page
|
||||
// and two move the map.
|
||||
const touch = window.matchMedia?.("(pointer: coarse)").matches ?? false;
|
||||
map = new gl.Map({
|
||||
container: box,
|
||||
style: mapStyle(server),
|
||||
center: [10.45, 51.17],
|
||||
zoom: 3,
|
||||
// With cooperative gestures, scrolling zooms only with Ctrl or ⌘.
|
||||
scrollZoom: touch,
|
||||
cooperativeGestures: touch,
|
||||
locale: {
|
||||
"CooperativeGesturesHandler.MobileHelpText": box.dataset.touchHint,
|
||||
"CooperativeGesturesHandler.WindowsHelpText": box.dataset.scrollHint.replace("{key}", box.dataset.ctrlKey),
|
||||
"CooperativeGesturesHandler.MacHelpText": box.dataset.scrollHint.replace("{key}", "⌘"),
|
||||
},
|
||||
attributionControl: { compact: true },
|
||||
});
|
||||
} catch {
|
||||
box.hidden = true;
|
||||
return;
|
||||
}
|
||||
let styled = false;
|
||||
map.on("styledata", () => (styled = true));
|
||||
map.on("error", () => {
|
||||
if (!styled) box.hidden = true;
|
||||
});
|
||||
map.addControl(new gl.NavigationControl({ showCompass: false }), "top-right");
|
||||
darkScheme?.addEventListener("change", () => map.setStyle(mapStyle(server)));
|
||||
|
||||
// The map may start hidden, as with the regions of passive monitor
|
||||
// types, so it fits the markers once it has a size.
|
||||
let fitted = false;
|
||||
const fit = () => {
|
||||
map.resize();
|
||||
if (fitted || !box.clientWidth) return;
|
||||
fitted = true;
|
||||
const points = items.map(lngLat);
|
||||
if (points.length > 1) {
|
||||
const bounds = points.slice(1).reduce((b, p) => b.extend(p), new gl.LngLatBounds(points[0], points[0]));
|
||||
// Labels run to the right of their point.
|
||||
map.fitBounds(bounds, { padding: { top: 40, bottom: 40, left: 40, right: 130 }, maxZoom: 6, duration: 0 });
|
||||
} else if (points.length === 1) {
|
||||
map.jumpTo({ center: points[0], zoom: 5 });
|
||||
}
|
||||
};
|
||||
new ResizeObserver(fit).observe(box);
|
||||
fit();
|
||||
|
||||
const selecting = box.dataset.regionMap === "select";
|
||||
for (const item of items) {
|
||||
// The list row (a label or table row) and the marker light up together.
|
||||
const row = item.closest("label, tr") ?? item;
|
||||
row.classList.add("region-row");
|
||||
const pin = Object.assign(document.createElement("button"), { type: "button", className: "region-pin", title: item.dataset.name });
|
||||
pin.dataset.live = item.dataset.live;
|
||||
pin.append(Object.assign(document.createElement("span"), { className: "region-pin-dot" }), Object.assign(document.createElement("span"), { textContent: item.dataset.name }));
|
||||
const holder = document.createElement("div");
|
||||
holder.append(pin);
|
||||
const marker = new gl.Marker({ element: holder, anchor: "left", offset: [-8, 0] }).setLngLat(lngLat(item)).addTo(map);
|
||||
const hover = (on) => {
|
||||
holder.classList.toggle("is-hover", on);
|
||||
row.classList.toggle("is-hover", on);
|
||||
};
|
||||
// Mouse only: a tap would leave the highlight behind.
|
||||
for (const el of [pin, row]) {
|
||||
el.addEventListener("pointerenter", (ev) => ev.pointerType === "mouse" && hover(true));
|
||||
el.addEventListener("pointerleave", () => hover(false));
|
||||
}
|
||||
if (selecting) {
|
||||
// The checkbox stays the source of truth; its change event keeps
|
||||
// the form's own behaviour.
|
||||
const paint = () => {
|
||||
pin.classList.toggle("is-checked", item.checked);
|
||||
row.classList.toggle("is-checked", item.checked);
|
||||
pin.setAttribute("aria-pressed", String(item.checked));
|
||||
};
|
||||
paint();
|
||||
item.addEventListener("change", () => {
|
||||
paint();
|
||||
// A region ticked in the list comes into view on the map.
|
||||
const bounds = map.getBounds?.();
|
||||
if (item.checked && bounds && !bounds.contains(marker.getLngLat())) map.easeTo({ center: marker.getLngLat() });
|
||||
});
|
||||
pin.addEventListener("click", (ev) => {
|
||||
ev.stopPropagation();
|
||||
if (!item.matches(":disabled")) item.click();
|
||||
});
|
||||
} else {
|
||||
pin.addEventListener("click", (ev) => {
|
||||
ev.stopPropagation();
|
||||
item.querySelector("[data-location-toggle]")?.click();
|
||||
});
|
||||
}
|
||||
}
|
||||
if (selecting) return;
|
||||
let pick;
|
||||
map.on("click", (ev) => {
|
||||
if (!locationTarget) return;
|
||||
const at = ev.lngLat.wrap ? ev.lngLat.wrap() : ev.lngLat;
|
||||
const round = (v) => String(Math.round(v * 10000) / 10000);
|
||||
locationTarget.querySelector('[data-location-field="latitude"]').value = round(at.lat);
|
||||
locationTarget.querySelector('[data-location-field="longitude"]').value = round(at.lng);
|
||||
const point = [at.lng, at.lat];
|
||||
pick ??= new gl.Marker({ element: Object.assign(document.createElement("div"), { className: "region-pick" }) })
|
||||
.setLngLat(point)
|
||||
.addTo(map);
|
||||
pick.setLngLat(point);
|
||||
});
|
||||
};
|
||||
for (const box of document.querySelectorAll("[data-region-map]")) initRegionMap(box);
|
||||
})();
|
||||
@@ -19,6 +19,9 @@ type Page struct {
|
||||
Legal []LegalLink
|
||||
// RefreshSeconds reloads pages that show live state.
|
||||
RefreshSeconds int
|
||||
// Meta describes public pages for search engines and link previews;
|
||||
// pages without it are kept out of search engines.
|
||||
Meta *PageMeta
|
||||
}
|
||||
|
||||
templ Layout(p Page) {
|
||||
@@ -34,6 +37,11 @@ templ Layout(p Page) {
|
||||
<meta http-equiv="refresh" content={ strconv.Itoa(p.RefreshSeconds) }/>
|
||||
}
|
||||
<title>{ i18n.T(ctx, p.TitleID) } · UptimeSebi</title>
|
||||
if p.Meta != nil {
|
||||
@metaTags(p.Meta)
|
||||
} else {
|
||||
@noIndex()
|
||||
}
|
||||
@faviconLinks()
|
||||
<link rel="stylesheet" href="/static/dist/app.css"/>
|
||||
<script src="/static/dist/axios.min.js" defer></script>
|
||||
|
||||
@@ -28,6 +28,9 @@ type Page struct {
|
||||
Legal []LegalLink
|
||||
// RefreshSeconds reloads pages that show live state.
|
||||
RefreshSeconds int
|
||||
// Meta describes public pages for search engines and link previews;
|
||||
// pages without it are kept out of search engines.
|
||||
Meta *PageMeta
|
||||
}
|
||||
|
||||
func Layout(p Page) templ.Component {
|
||||
@@ -55,7 +58,7 @@ func Layout(p Page) templ.Component {
|
||||
var templ_7745c5c3_Var2 string
|
||||
templ_7745c5c3_Var2, templ_7745c5c3_Err = templruntime.NewAttributeExpression(i18n.Lang(ctx)).Resolve(ctx)
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/layout.templ`, Line: 26, Col: 28}
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/layout.templ`, Line: 29, Col: 28}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ_7745c5c3_Var2)
|
||||
if templ_7745c5c3_Err != nil {
|
||||
@@ -73,7 +76,7 @@ func Layout(p Page) templ.Component {
|
||||
var templ_7745c5c3_Var3 string
|
||||
templ_7745c5c3_Var3, templ_7745c5c3_Err = templruntime.NewAttributeExpression(p.CSRF).Resolve(ctx)
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/layout.templ`, Line: 31, Col: 44}
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/layout.templ`, Line: 34, Col: 44}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ_7745c5c3_Var3)
|
||||
if templ_7745c5c3_Err != nil {
|
||||
@@ -92,7 +95,7 @@ func Layout(p Page) templ.Component {
|
||||
var templ_7745c5c3_Var4 string
|
||||
templ_7745c5c3_Var4, templ_7745c5c3_Err = templruntime.NewAttributeExpression(strconv.Itoa(p.RefreshSeconds)).Resolve(ctx)
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/layout.templ`, Line: 34, Col: 71}
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/layout.templ`, Line: 37, Col: 71}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ_7745c5c3_Var4)
|
||||
if templ_7745c5c3_Err != nil {
|
||||
@@ -110,7 +113,7 @@ func Layout(p Page) templ.Component {
|
||||
var templ_7745c5c3_Var5 string
|
||||
templ_7745c5c3_Var5, 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/layout.templ`, Line: 36, Col: 34}
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/layout.templ`, Line: 39, Col: 34}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var5))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
@@ -120,6 +123,17 @@ func Layout(p Page) templ.Component {
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
if p.Meta != nil {
|
||||
templ_7745c5c3_Err = metaTags(p.Meta).Render(ctx, templ_7745c5c3_Buffer)
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
} else {
|
||||
templ_7745c5c3_Err = noIndex().Render(ctx, templ_7745c5c3_Buffer)
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
}
|
||||
templ_7745c5c3_Err = faviconLinks().Render(ctx, templ_7745c5c3_Buffer)
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
@@ -131,7 +145,7 @@ func Layout(p Page) templ.Component {
|
||||
var templ_7745c5c3_Var6 string
|
||||
templ_7745c5c3_Var6, templ_7745c5c3_Err = templruntime.NewAttributeExpression(i18n.T(ctx, "app.network_error")).Resolve(ctx)
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/layout.templ`, Line: 42, Col: 94}
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/layout.templ`, Line: 50, Col: 94}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ_7745c5c3_Var6)
|
||||
if templ_7745c5c3_Err != nil {
|
||||
@@ -191,7 +205,7 @@ func languageSwitch(langs []string) templ.Component {
|
||||
var templ_7745c5c3_Var8 string
|
||||
templ_7745c5c3_Var8, templ_7745c5c3_Err = templ.JoinStringErrs(l)
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/layout.templ`, Line: 55, Col: 50}
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/layout.templ`, Line: 63, Col: 50}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var8))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
@@ -209,7 +223,7 @@ func languageSwitch(langs []string) templ.Component {
|
||||
var templ_7745c5c3_Var9 string
|
||||
templ_7745c5c3_Var9, templ_7745c5c3_Err = templruntime.NewAttributeExpression(l).Resolve(ctx)
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/layout.templ`, Line: 57, Col: 41}
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/layout.templ`, Line: 65, Col: 41}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ_7745c5c3_Var9)
|
||||
if templ_7745c5c3_Err != nil {
|
||||
@@ -222,7 +236,7 @@ func languageSwitch(langs []string) templ.Component {
|
||||
var templ_7745c5c3_Var10 string
|
||||
templ_7745c5c3_Var10, templ_7745c5c3_Err = templruntime.NewAttributeExpression(i18n.T(ctx, "lang."+l)).Resolve(ctx)
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/layout.templ`, Line: 57, Col: 108}
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/layout.templ`, Line: 65, Col: 108}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ_7745c5c3_Var10)
|
||||
if templ_7745c5c3_Err != nil {
|
||||
@@ -235,7 +249,7 @@ func languageSwitch(langs []string) templ.Component {
|
||||
var templ_7745c5c3_Var11 string
|
||||
templ_7745c5c3_Var11, templ_7745c5c3_Err = templ.JoinStringErrs(l)
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/layout.templ`, Line: 57, Col: 114}
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/layout.templ`, Line: 65, Col: 114}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var11))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
@@ -304,7 +318,7 @@ func authShell(p Page) templ.Component {
|
||||
var templ_7745c5c3_Var14 string
|
||||
templ_7745c5c3_Var14, 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/layout.templ`, Line: 70, Col: 66}
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/layout.templ`, Line: 78, Col: 66}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var14))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
@@ -360,7 +374,7 @@ func field(label, name, typ, autocomplete string, required bool) templ.Component
|
||||
var templ_7745c5c3_Var16 string
|
||||
templ_7745c5c3_Var16, templ_7745c5c3_Err = templ.JoinStringErrs(label)
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/layout.templ`, Line: 79, Col: 90}
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/layout.templ`, Line: 87, Col: 90}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var16))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
@@ -373,7 +387,7 @@ func field(label, name, typ, autocomplete string, required bool) templ.Component
|
||||
var templ_7745c5c3_Var17 string
|
||||
templ_7745c5c3_Var17, templ_7745c5c3_Err = templruntime.NewAttributeExpression(typ).Resolve(ctx)
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/layout.templ`, Line: 82, Col: 13}
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/layout.templ`, Line: 90, Col: 13}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ_7745c5c3_Var17)
|
||||
if templ_7745c5c3_Err != nil {
|
||||
@@ -386,7 +400,7 @@ func field(label, name, typ, autocomplete string, required bool) templ.Component
|
||||
var templ_7745c5c3_Var18 string
|
||||
templ_7745c5c3_Var18, templ_7745c5c3_Err = templruntime.NewAttributeExpression(name).Resolve(ctx)
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/layout.templ`, Line: 83, Col: 14}
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/layout.templ`, Line: 91, Col: 14}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ_7745c5c3_Var18)
|
||||
if templ_7745c5c3_Err != nil {
|
||||
@@ -399,7 +413,7 @@ func field(label, name, typ, autocomplete string, required bool) templ.Component
|
||||
var templ_7745c5c3_Var19 string
|
||||
templ_7745c5c3_Var19, templ_7745c5c3_Err = templruntime.NewAttributeExpression(autocomplete).Resolve(ctx)
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/layout.templ`, Line: 84, Col: 30}
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/layout.templ`, Line: 92, Col: 30}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ_7745c5c3_Var19)
|
||||
if templ_7745c5c3_Err != nil {
|
||||
@@ -447,7 +461,7 @@ func submit(label string) templ.Component {
|
||||
var templ_7745c5c3_Var21 string
|
||||
templ_7745c5c3_Var21, templ_7745c5c3_Err = templ.JoinStringErrs(label)
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/layout.templ`, Line: 92, Col: 9}
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/layout.templ`, Line: 100, Col: 9}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var21))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
@@ -486,7 +500,7 @@ func flash(p Page) templ.Component {
|
||||
var templ_7745c5c3_Var23 string
|
||||
templ_7745c5c3_Var23, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, p.ErrorID))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/layout.templ`, Line: 98, Col: 88}
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/layout.templ`, Line: 106, Col: 88}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var23))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
@@ -505,7 +519,7 @@ func flash(p Page) templ.Component {
|
||||
var templ_7745c5c3_Var24 string
|
||||
templ_7745c5c3_Var24, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, p.NoticeID))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/layout.templ`, Line: 101, Col: 77}
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/layout.templ`, Line: 109, Col: 77}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var24))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
|
||||
@@ -0,0 +1,138 @@
|
||||
package web
|
||||
|
||||
import (
|
||||
"html"
|
||||
"net/url"
|
||||
"regexp"
|
||||
"strconv"
|
||||
"strings"
|
||||
"unicode/utf8"
|
||||
|
||||
"git.zb-server.de/ZB-Server/uptimesebi/internal/ogimage"
|
||||
)
|
||||
|
||||
// PageMeta describes a page for search engines and link previews. Pages
|
||||
// without one are private and carry noindex.
|
||||
type PageMeta struct {
|
||||
// Title is the shared title, without the site suffix of <title>.
|
||||
Title string
|
||||
Description string
|
||||
// URL is the canonical address of the page.
|
||||
URL string
|
||||
Image string
|
||||
SiteName string
|
||||
// Lang is the language the page is shown in.
|
||||
Lang string
|
||||
// Alternates are the page in each language, plus x-default.
|
||||
Alternates []MetaAlternate
|
||||
}
|
||||
|
||||
// MetaAlternate is a language version of a page; Lang "x-default" marks
|
||||
// the one that picks the language itself.
|
||||
type MetaAlternate struct {
|
||||
Lang string
|
||||
URL string
|
||||
}
|
||||
|
||||
// LangURL adds ?lang= to a page's address.
|
||||
func LangURL(base, lang string) string {
|
||||
u, err := url.Parse(base)
|
||||
if err != nil {
|
||||
return base
|
||||
}
|
||||
q := u.Query()
|
||||
q.Set("lang", lang)
|
||||
u.RawQuery = q.Encode()
|
||||
return u.String()
|
||||
}
|
||||
|
||||
// NewPageMeta fills the language versions and the canonical address of a
|
||||
// page at base: the address of its language when the visitor chose one
|
||||
// with ?lang=, else base, which picks the language itself.
|
||||
func NewPageMeta(title, description, base, image, siteName, lang string, chosen bool, langs []string) *PageMeta {
|
||||
m := &PageMeta{Title: title, Description: description, URL: base, Image: image, SiteName: siteName, Lang: lang}
|
||||
if chosen {
|
||||
m.URL = LangURL(base, lang)
|
||||
}
|
||||
for _, l := range langs {
|
||||
m.Alternates = append(m.Alternates, MetaAlternate{Lang: l, URL: LangURL(base, l)})
|
||||
}
|
||||
m.Alternates = append(m.Alternates, MetaAlternate{Lang: "x-default", URL: base})
|
||||
return m
|
||||
}
|
||||
|
||||
var tagRE = regexp.MustCompile(`<[^>]*>`)
|
||||
|
||||
// PlainText turns Markdown into a single line of text of at most max
|
||||
// characters, for descriptions.
|
||||
func PlainText(markdown string, max int) string {
|
||||
s := html.UnescapeString(tagRE.ReplaceAllString(Markdown(markdown), " "))
|
||||
s = strings.Join(strings.Fields(s), " ")
|
||||
if utf8.RuneCountInString(s) <= max {
|
||||
return s
|
||||
}
|
||||
r := []rune(s)[:max-1]
|
||||
if i := strings.LastIndex(string(r), " "); i > max/2 {
|
||||
return string(r)[:i] + "…"
|
||||
}
|
||||
return string(r) + "…"
|
||||
}
|
||||
|
||||
// ogLocale maps a language to the locale Open Graph expects.
|
||||
func ogLocale(lang string) string {
|
||||
switch lang {
|
||||
case "de":
|
||||
return "de_DE"
|
||||
case "en":
|
||||
return "en_US"
|
||||
}
|
||||
return strings.ReplaceAll(lang, "-", "_")
|
||||
}
|
||||
|
||||
// metaTags are the description, canonical address, language versions and
|
||||
// Open Graph and Twitter tags of m.
|
||||
templ metaTags(m *PageMeta) {
|
||||
if m.Description != "" {
|
||||
<meta name="description" content={ m.Description }/>
|
||||
}
|
||||
<link rel="canonical" href={ m.URL }/>
|
||||
for _, a := range m.Alternates {
|
||||
<link rel="alternate" hreflang={ a.Lang } href={ a.URL }/>
|
||||
}
|
||||
<meta property="og:type" content="website"/>
|
||||
if m.SiteName != "" {
|
||||
<meta property="og:site_name" content={ m.SiteName }/>
|
||||
}
|
||||
<meta property="og:title" content={ m.Title }/>
|
||||
if m.Description != "" {
|
||||
<meta property="og:description" content={ m.Description }/>
|
||||
}
|
||||
<meta property="og:url" content={ m.URL }/>
|
||||
<meta property="og:locale" content={ ogLocale(m.Lang) }/>
|
||||
if m.Image != "" {
|
||||
<meta property="og:image" content={ m.Image }/>
|
||||
<meta property="og:image:type" content="image/png"/>
|
||||
<meta property="og:image:width" content={ strconv.Itoa(ogimage.Width) }/>
|
||||
<meta property="og:image:height" content={ strconv.Itoa(ogimage.Height) }/>
|
||||
<meta property="og:image:alt" content={ m.Title }/>
|
||||
}
|
||||
<meta name="twitter:card" content={ twitterCard(m) }/>
|
||||
<meta name="twitter:title" content={ m.Title }/>
|
||||
if m.Description != "" {
|
||||
<meta name="twitter:description" content={ m.Description }/>
|
||||
}
|
||||
if m.Image != "" {
|
||||
<meta name="twitter:image" content={ m.Image }/>
|
||||
}
|
||||
}
|
||||
|
||||
func twitterCard(m *PageMeta) string {
|
||||
if m.Image != "" {
|
||||
return "summary_large_image"
|
||||
}
|
||||
return "summary"
|
||||
}
|
||||
|
||||
templ noIndex() {
|
||||
<meta name="robots" content="noindex, nofollow"/>
|
||||
}
|
||||
@@ -0,0 +1,439 @@
|
||||
// Code generated by templ - DO NOT EDIT.
|
||||
|
||||
// templ: version: v0.3.1118
|
||||
|
||||
package web
|
||||
|
||||
//lint:file-ignore SA4006 This context is only used if a nested component is present.
|
||||
|
||||
import "github.com/a-h/templ"
|
||||
import templruntime "github.com/a-h/templ/runtime"
|
||||
|
||||
import (
|
||||
"html"
|
||||
"net/url"
|
||||
"regexp"
|
||||
"strconv"
|
||||
"strings"
|
||||
"unicode/utf8"
|
||||
|
||||
"git.zb-server.de/ZB-Server/uptimesebi/internal/ogimage"
|
||||
)
|
||||
|
||||
// PageMeta describes a page for search engines and link previews. Pages
|
||||
// without one are private and carry noindex.
|
||||
type PageMeta struct {
|
||||
// Title is the shared title, without the site suffix of <title>.
|
||||
Title string
|
||||
Description string
|
||||
// URL is the canonical address of the page.
|
||||
URL string
|
||||
Image string
|
||||
SiteName string
|
||||
// Lang is the language the page is shown in.
|
||||
Lang string
|
||||
// Alternates are the page in each language, plus x-default.
|
||||
Alternates []MetaAlternate
|
||||
}
|
||||
|
||||
// MetaAlternate is a language version of a page; Lang "x-default" marks
|
||||
// the one that picks the language itself.
|
||||
type MetaAlternate struct {
|
||||
Lang string
|
||||
URL string
|
||||
}
|
||||
|
||||
// LangURL adds ?lang= to a page's address.
|
||||
func LangURL(base, lang string) string {
|
||||
u, err := url.Parse(base)
|
||||
if err != nil {
|
||||
return base
|
||||
}
|
||||
q := u.Query()
|
||||
q.Set("lang", lang)
|
||||
u.RawQuery = q.Encode()
|
||||
return u.String()
|
||||
}
|
||||
|
||||
// NewPageMeta fills the language versions and the canonical address of a
|
||||
// page at base: the address of its language when the visitor chose one
|
||||
// with ?lang=, else base, which picks the language itself.
|
||||
func NewPageMeta(title, description, base, image, siteName, lang string, chosen bool, langs []string) *PageMeta {
|
||||
m := &PageMeta{Title: title, Description: description, URL: base, Image: image, SiteName: siteName, Lang: lang}
|
||||
if chosen {
|
||||
m.URL = LangURL(base, lang)
|
||||
}
|
||||
for _, l := range langs {
|
||||
m.Alternates = append(m.Alternates, MetaAlternate{Lang: l, URL: LangURL(base, l)})
|
||||
}
|
||||
m.Alternates = append(m.Alternates, MetaAlternate{Lang: "x-default", URL: base})
|
||||
return m
|
||||
}
|
||||
|
||||
var tagRE = regexp.MustCompile(`<[^>]*>`)
|
||||
|
||||
// PlainText turns Markdown into a single line of text of at most max
|
||||
// characters, for descriptions.
|
||||
func PlainText(markdown string, max int) string {
|
||||
s := html.UnescapeString(tagRE.ReplaceAllString(Markdown(markdown), " "))
|
||||
s = strings.Join(strings.Fields(s), " ")
|
||||
if utf8.RuneCountInString(s) <= max {
|
||||
return s
|
||||
}
|
||||
r := []rune(s)[:max-1]
|
||||
if i := strings.LastIndex(string(r), " "); i > max/2 {
|
||||
return string(r)[:i] + "…"
|
||||
}
|
||||
return string(r) + "…"
|
||||
}
|
||||
|
||||
// ogLocale maps a language to the locale Open Graph expects.
|
||||
func ogLocale(lang string) string {
|
||||
switch lang {
|
||||
case "de":
|
||||
return "de_DE"
|
||||
case "en":
|
||||
return "en_US"
|
||||
}
|
||||
return strings.ReplaceAll(lang, "-", "_")
|
||||
}
|
||||
|
||||
// metaTags are the description, canonical address, language versions and
|
||||
// Open Graph and Twitter tags of m.
|
||||
func metaTags(m *PageMeta) templ.Component {
|
||||
return templruntime.GeneratedTemplate(func(templ_7745c5c3_Input templruntime.GeneratedComponentInput) (templ_7745c5c3_Err error) {
|
||||
templ_7745c5c3_W, ctx := templ_7745c5c3_Input.Writer, templ_7745c5c3_Input.Context
|
||||
if templ_7745c5c3_CtxErr := ctx.Err(); templ_7745c5c3_CtxErr != nil {
|
||||
return templ_7745c5c3_CtxErr
|
||||
}
|
||||
templ_7745c5c3_Buffer, templ_7745c5c3_IsBuffer := templruntime.GetBuffer(templ_7745c5c3_W)
|
||||
if !templ_7745c5c3_IsBuffer {
|
||||
defer func() {
|
||||
templ_7745c5c3_BufErr := templruntime.ReleaseBuffer(templ_7745c5c3_Buffer)
|
||||
if templ_7745c5c3_Err == nil {
|
||||
templ_7745c5c3_Err = templ_7745c5c3_BufErr
|
||||
}
|
||||
}()
|
||||
}
|
||||
ctx = templ.InitializeContext(ctx)
|
||||
ctx = templ.ClearChildren(ctx)
|
||||
if m.Description != "" {
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 1, "<meta name=\"description\" content=\"")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
var templ_7745c5c3_Var2 string
|
||||
templ_7745c5c3_Var2, templ_7745c5c3_Err = templruntime.NewAttributeExpression(m.Description).Resolve(ctx)
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/meta.templ`, Line: 96, Col: 50}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ_7745c5c3_Var2)
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 2, "\">")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
}
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 3, "<link rel=\"canonical\" href=\"")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
var templ_7745c5c3_Var3 string
|
||||
templ_7745c5c3_Var3, templ_7745c5c3_Err = templruntime.NewAttributeExpression(m.URL).ResolveURL(ctx)
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/meta.templ`, Line: 98, Col: 35}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ_7745c5c3_Var3)
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 4, "\">")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
for _, a := range m.Alternates {
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 5, "<link rel=\"alternate\" hreflang=\"")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
var templ_7745c5c3_Var4 string
|
||||
templ_7745c5c3_Var4, templ_7745c5c3_Err = templruntime.NewAttributeExpression(a.Lang).Resolve(ctx)
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/meta.templ`, Line: 100, Col: 41}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ_7745c5c3_Var4)
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 6, "\" href=\"")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
var templ_7745c5c3_Var5 string
|
||||
templ_7745c5c3_Var5, templ_7745c5c3_Err = templruntime.NewAttributeExpression(a.URL).ResolveURL(ctx)
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/meta.templ`, Line: 100, Col: 56}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ_7745c5c3_Var5)
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 7, "\">")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
}
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 8, "<meta property=\"og:type\" content=\"website\">")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
if m.SiteName != "" {
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 9, "<meta property=\"og:site_name\" content=\"")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
var templ_7745c5c3_Var6 string
|
||||
templ_7745c5c3_Var6, templ_7745c5c3_Err = templruntime.NewAttributeExpression(m.SiteName).Resolve(ctx)
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/meta.templ`, Line: 104, Col: 52}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ_7745c5c3_Var6)
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 10, "\">")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
}
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 11, "<meta property=\"og:title\" content=\"")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
var templ_7745c5c3_Var7 string
|
||||
templ_7745c5c3_Var7, templ_7745c5c3_Err = templruntime.NewAttributeExpression(m.Title).Resolve(ctx)
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/meta.templ`, Line: 106, Col: 44}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ_7745c5c3_Var7)
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 12, "\">")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
if m.Description != "" {
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 13, "<meta property=\"og:description\" content=\"")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
var templ_7745c5c3_Var8 string
|
||||
templ_7745c5c3_Var8, templ_7745c5c3_Err = templruntime.NewAttributeExpression(m.Description).Resolve(ctx)
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/meta.templ`, Line: 108, Col: 57}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ_7745c5c3_Var8)
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 14, "\">")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
}
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 15, "<meta property=\"og:url\" content=\"")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
var templ_7745c5c3_Var9 string
|
||||
templ_7745c5c3_Var9, templ_7745c5c3_Err = templruntime.NewAttributeExpression(m.URL).Resolve(ctx)
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/meta.templ`, Line: 110, Col: 40}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ_7745c5c3_Var9)
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 16, "\"><meta property=\"og:locale\" content=\"")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
var templ_7745c5c3_Var10 string
|
||||
templ_7745c5c3_Var10, templ_7745c5c3_Err = templruntime.NewAttributeExpression(ogLocale(m.Lang)).Resolve(ctx)
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/meta.templ`, Line: 111, Col: 54}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ_7745c5c3_Var10)
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 17, "\">")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
if m.Image != "" {
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 18, "<meta property=\"og:image\" content=\"")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
var templ_7745c5c3_Var11 string
|
||||
templ_7745c5c3_Var11, templ_7745c5c3_Err = templruntime.NewAttributeExpression(m.Image).Resolve(ctx)
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/meta.templ`, Line: 113, Col: 45}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ_7745c5c3_Var11)
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 19, "\"><meta property=\"og:image:type\" content=\"image/png\"><meta property=\"og:image:width\" content=\"")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
var templ_7745c5c3_Var12 string
|
||||
templ_7745c5c3_Var12, templ_7745c5c3_Err = templruntime.NewAttributeExpression(strconv.Itoa(ogimage.Width)).Resolve(ctx)
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/meta.templ`, Line: 115, Col: 71}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ_7745c5c3_Var12)
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 20, "\"><meta property=\"og:image:height\" content=\"")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
var templ_7745c5c3_Var13 string
|
||||
templ_7745c5c3_Var13, templ_7745c5c3_Err = templruntime.NewAttributeExpression(strconv.Itoa(ogimage.Height)).Resolve(ctx)
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/meta.templ`, Line: 116, Col: 73}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ_7745c5c3_Var13)
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 21, "\"><meta property=\"og:image:alt\" content=\"")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
var templ_7745c5c3_Var14 string
|
||||
templ_7745c5c3_Var14, templ_7745c5c3_Err = templruntime.NewAttributeExpression(m.Title).Resolve(ctx)
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/meta.templ`, Line: 117, Col: 49}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ_7745c5c3_Var14)
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 22, "\">")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
}
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 23, "<meta name=\"twitter:card\" content=\"")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
var templ_7745c5c3_Var15 string
|
||||
templ_7745c5c3_Var15, templ_7745c5c3_Err = templruntime.NewAttributeExpression(twitterCard(m)).Resolve(ctx)
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/meta.templ`, Line: 119, Col: 51}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ_7745c5c3_Var15)
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 24, "\"><meta name=\"twitter:title\" content=\"")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
var templ_7745c5c3_Var16 string
|
||||
templ_7745c5c3_Var16, templ_7745c5c3_Err = templruntime.NewAttributeExpression(m.Title).Resolve(ctx)
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/meta.templ`, Line: 120, Col: 45}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ_7745c5c3_Var16)
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 25, "\">")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
if m.Description != "" {
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 26, "<meta name=\"twitter:description\" content=\"")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
var templ_7745c5c3_Var17 string
|
||||
templ_7745c5c3_Var17, templ_7745c5c3_Err = templruntime.NewAttributeExpression(m.Description).Resolve(ctx)
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/meta.templ`, Line: 122, Col: 58}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ_7745c5c3_Var17)
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 27, "\">")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
}
|
||||
if m.Image != "" {
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 28, "<meta name=\"twitter:image\" content=\"")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
var templ_7745c5c3_Var18 string
|
||||
templ_7745c5c3_Var18, templ_7745c5c3_Err = templruntime.NewAttributeExpression(m.Image).Resolve(ctx)
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/meta.templ`, Line: 125, Col: 46}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ_7745c5c3_Var18)
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 29, "\">")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
})
|
||||
}
|
||||
|
||||
func twitterCard(m *PageMeta) string {
|
||||
if m.Image != "" {
|
||||
return "summary_large_image"
|
||||
}
|
||||
return "summary"
|
||||
}
|
||||
|
||||
func noIndex() templ.Component {
|
||||
return templruntime.GeneratedTemplate(func(templ_7745c5c3_Input templruntime.GeneratedComponentInput) (templ_7745c5c3_Err error) {
|
||||
templ_7745c5c3_W, ctx := templ_7745c5c3_Input.Writer, templ_7745c5c3_Input.Context
|
||||
if templ_7745c5c3_CtxErr := ctx.Err(); templ_7745c5c3_CtxErr != nil {
|
||||
return templ_7745c5c3_CtxErr
|
||||
}
|
||||
templ_7745c5c3_Buffer, templ_7745c5c3_IsBuffer := templruntime.GetBuffer(templ_7745c5c3_W)
|
||||
if !templ_7745c5c3_IsBuffer {
|
||||
defer func() {
|
||||
templ_7745c5c3_BufErr := templruntime.ReleaseBuffer(templ_7745c5c3_Buffer)
|
||||
if templ_7745c5c3_Err == nil {
|
||||
templ_7745c5c3_Err = templ_7745c5c3_BufErr
|
||||
}
|
||||
}()
|
||||
}
|
||||
ctx = templ.InitializeContext(ctx)
|
||||
ctx = templ.ClearChildren(ctx)
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 30, "<meta name=\"robots\" content=\"noindex, nofollow\">")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
return nil
|
||||
})
|
||||
}
|
||||
|
||||
var _ = templruntime.GeneratedTemplate
|
||||
+68
-15
@@ -84,8 +84,8 @@ type DashboardView struct {
|
||||
// ArrangeURL turns it on or off, empty when not offered.
|
||||
Arrange bool
|
||||
ArrangeURL string
|
||||
Range string
|
||||
Ranges []RangeOption
|
||||
Range string
|
||||
Ranges []RangeOption
|
||||
// Unchecked counts the monitors no region has reported for recently.
|
||||
Unchecked int
|
||||
// DeadRegions are regions of the monitors without a live checker.
|
||||
@@ -192,6 +192,28 @@ templ bars(bs []Bar, height int) {
|
||||
</svg>
|
||||
}
|
||||
|
||||
// pathBars draws bars like bars, in a few paths and without tooltips.
|
||||
templ pathBars(bs []Bar, height int) {
|
||||
<svg
|
||||
viewBox={ "0 0 " + strconv.Itoa(len(bs)*4) + " " + strconv.Itoa(height) }
|
||||
preserveAspectRatio="none"
|
||||
class="block w-full"
|
||||
style={ "height:" + strconv.Itoa(height) + "px" }
|
||||
role="img"
|
||||
aria-label={ i18n.T(ctx, "monitors.uptime_chart") }
|
||||
>
|
||||
for _, p := range BarPaths(bs, height) {
|
||||
<path
|
||||
d={ p.D }
|
||||
class={ templ.KV("fill-up", p.Status == StatusUp),
|
||||
templ.KV("fill-degraded", p.Status == StatusDegraded),
|
||||
templ.KV("fill-down", p.Status == StatusDown),
|
||||
templ.KV("fill-rule", p.Status == StatusUnknown) }
|
||||
></path>
|
||||
}
|
||||
</svg>
|
||||
}
|
||||
|
||||
templ Dashboard(p Page, me Me, v DashboardView) {
|
||||
@consoleShell(p, me) {
|
||||
<div class="mb-6 flex flex-wrap items-center justify-between gap-x-4 gap-y-3">
|
||||
@@ -699,6 +721,19 @@ type RegionOption struct {
|
||||
Own bool
|
||||
Checked bool
|
||||
Live int64
|
||||
// Lat and Lon place the region on the map; both are nil without a
|
||||
// location.
|
||||
Lat, Lon *float64
|
||||
}
|
||||
|
||||
// RegionsMapped reports whether any region of the form has a location.
|
||||
func (f MonitorForm) RegionsMapped() bool {
|
||||
for _, r := range f.Regions {
|
||||
if r.HasLocation() {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// MonitorForm is the data of the monitor editor; ID is empty for new ones.
|
||||
@@ -1097,20 +1132,38 @@ templ MonitorEditor(p Page, me Me, f MonitorForm) {
|
||||
<fieldset class="mb-4" data-hide-for="heartbeat alertmanager" hidden?={ passiveType(f.Type) } disabled?={ f.Type == "heartbeat" }>
|
||||
<legend class="mb-1 block text-xs font-medium uppercase tracking-wider text-muted">{ i18n.T(ctx, "monitors.regions") }</legend>
|
||||
<p class="mb-2 text-xs text-muted">{ i18n.T(ctx, "monitors.regions_hint") }</p>
|
||||
for _, r := range f.Regions {
|
||||
<label class="mb-1.5 flex items-center gap-2 text-sm">
|
||||
<input type="checkbox" name="regions" value={ r.ID } data-multi checked?={ r.Checked } class="accent-ink"/>
|
||||
{ r.Name }
|
||||
<span class="font-mono text-xs text-muted">
|
||||
if r.Own {
|
||||
{ i18n.T(ctx, "regions.own") }
|
||||
} else {
|
||||
{ i18n.T(ctx, "regions.platform") }
|
||||
}
|
||||
· { i18n.T(ctx, "regions.live", "Count", int(r.Live)) }
|
||||
</span>
|
||||
</label>
|
||||
if f.RegionsMapped() {
|
||||
@regionMap("select", "#monitor-regions")
|
||||
}
|
||||
<div id="monitor-regions">
|
||||
for _, r := range f.Regions {
|
||||
<label class="-mx-2 mb-0.5 flex items-center gap-2 px-2 py-1 text-sm">
|
||||
<input
|
||||
type="checkbox"
|
||||
name="regions"
|
||||
value={ r.ID }
|
||||
data-multi
|
||||
checked?={ r.Checked }
|
||||
class="accent-ink"
|
||||
if r.HasLocation() {
|
||||
data-lat={ coord(r.Lat) }
|
||||
data-lon={ coord(r.Lon) }
|
||||
}
|
||||
data-name={ r.Name }
|
||||
data-live={ strconv.FormatInt(r.Live, 10) }
|
||||
/>
|
||||
{ r.Name }
|
||||
<span class="font-mono text-xs text-muted">
|
||||
if r.Own {
|
||||
{ i18n.T(ctx, "regions.own") }
|
||||
} else {
|
||||
{ i18n.T(ctx, "regions.platform") }
|
||||
}
|
||||
· { i18n.T(ctx, "regions.live", "Count", int(r.Live)) }
|
||||
</span>
|
||||
</label>
|
||||
}
|
||||
</div>
|
||||
</fieldset>
|
||||
@checkbox(i18n.T(ctx, "sso.field.enabled"), "enabled", f.Enabled)
|
||||
@submit(i18n.T(ctx, "common.save"))
|
||||
|
||||
+2641
-2429
File diff suppressed because it is too large.
Load diff
@@ -3,6 +3,7 @@ package web
|
||||
import (
|
||||
"fmt"
|
||||
"io/fs"
|
||||
"net/url"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
@@ -15,6 +16,11 @@ import (
|
||||
type PublicAssets struct {
|
||||
CSSHref string
|
||||
InlineCSS string
|
||||
// Meta describes the page for search engines and link previews.
|
||||
Meta *PageMeta
|
||||
// NoIndex keeps the page out of search engines, as with legal and
|
||||
// subscription pages, which only repeat or serve the status page.
|
||||
NoIndex bool
|
||||
// StaleSince, if set, tells visitors that live updates are unavailable
|
||||
// and the page shows the state of that moment.
|
||||
StaleSince time.Time
|
||||
@@ -30,6 +36,183 @@ type PublicAssets struct {
|
||||
Now time.Time
|
||||
// NoRefresh leaves out the periodic reload, on pages with a form.
|
||||
NoRefresh bool
|
||||
// PageSize is how many of a section's own components the page lists
|
||||
// at a time; 0 lists all, as in a single-file export.
|
||||
PageSize int
|
||||
// Pages holds the zero-based page shown of the sections paged, by
|
||||
// their PublicSection.Key.
|
||||
Pages map[string]int
|
||||
// Query is what the visitor searched the components for; OnlyProblems
|
||||
// keeps those with an outage or degraded.
|
||||
Query string
|
||||
OnlyProblems bool
|
||||
}
|
||||
|
||||
// PublicSection is a section of a status page as a request for it shows
|
||||
// it: the components of one page of the section's own, its status and
|
||||
// count those of the whole section.
|
||||
type PublicSection struct {
|
||||
Name string
|
||||
Status string
|
||||
Total int
|
||||
// Key identifies the section in the URLs paging it, e.g. "0.2".
|
||||
Key string
|
||||
Components []agentapi.Component
|
||||
Children []PublicSection
|
||||
// Page is the zero-based page of the section's own components shown,
|
||||
// of Pages.
|
||||
Page, Pages int
|
||||
}
|
||||
|
||||
// ComponentView is what a request for a status page shows of its
|
||||
// components: every section paged on its own, filtered by a search and to
|
||||
// those with problems if the visitor asked.
|
||||
type ComponentView struct {
|
||||
Sections []PublicSection
|
||||
// Total counts all components, Matches those the filters leave and
|
||||
// Problems those with an outage or degraded.
|
||||
Total, Matches, Problems int
|
||||
Query string
|
||||
OnlyProblems bool
|
||||
|
||||
base string
|
||||
size int
|
||||
pages map[string]int
|
||||
}
|
||||
|
||||
// Filterable reports whether the page lists enough components to offer the
|
||||
// search and filter, or uses them.
|
||||
func (v ComponentView) Filterable() bool {
|
||||
return v.size > 0 && v.Total > v.size || v.Query != "" || v.OnlyProblems
|
||||
}
|
||||
|
||||
// Filtered reports whether a search or filter is in use.
|
||||
func (v ComponentView) Filtered() bool { return v.Query != "" || v.OnlyProblems }
|
||||
|
||||
// PageHref links page of the section key, keeping the other sections' pages
|
||||
// and the filters.
|
||||
func (v ComponentView) PageHref(key string, page int) string {
|
||||
q := url.Values{}
|
||||
if v.Query != "" {
|
||||
q.Set("q", v.Query)
|
||||
}
|
||||
if v.OnlyProblems {
|
||||
q.Set("problems", "1")
|
||||
}
|
||||
for k, p := range v.pages {
|
||||
if k != key && p > 0 {
|
||||
q.Set("p."+k, strconv.Itoa(p+1))
|
||||
}
|
||||
}
|
||||
if page > 0 {
|
||||
q.Set("p."+key, strconv.Itoa(page+1))
|
||||
}
|
||||
href := BackHref(v.base)
|
||||
if len(q) > 0 {
|
||||
href += "?" + q.Encode()
|
||||
}
|
||||
return href + "#g-" + key
|
||||
}
|
||||
|
||||
// ResetHref links the page without search, filter and paging.
|
||||
func (v ComponentView) ResetHref() string { return BackHref(v.base) }
|
||||
|
||||
// Problem reports whether a component counts as an outage for the filter.
|
||||
func Problem(c agentapi.Component) bool {
|
||||
return c.Status == agentapi.PageOutage || c.Status == agentapi.PageDegraded
|
||||
}
|
||||
|
||||
// PublicComponents decides which components of sections a request for the
|
||||
// page shows, as a.Query, a.OnlyProblems and a.Pages ask.
|
||||
func PublicComponents(sections []agentapi.Section, a PublicAssets) ComponentView {
|
||||
v := ComponentView{
|
||||
Query: strings.TrimSpace(a.Query), OnlyProblems: a.OnlyProblems,
|
||||
base: a.ComponentBase, size: a.PageSize, pages: a.Pages,
|
||||
}
|
||||
needle := strings.ToLower(v.Query)
|
||||
match := func(path []string, c agentapi.Component) bool {
|
||||
if v.OnlyProblems && !Problem(c) {
|
||||
return false
|
||||
}
|
||||
if needle == "" || strings.Contains(strings.ToLower(c.Name), needle) {
|
||||
return true
|
||||
}
|
||||
for _, p := range path {
|
||||
if strings.Contains(strings.ToLower(p), needle) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
filtered := v.Filtered()
|
||||
var walk func(sec agentapi.Section, key string, path []string) (PublicSection, bool)
|
||||
walk = func(sec agentapi.Section, key string, path []string) (PublicSection, bool) {
|
||||
ps := PublicSection{Name: sec.Name, Status: secStatusName(sec), Total: SectionTotal(sec), Key: key, Pages: 1}
|
||||
if sec.Name != "" {
|
||||
path = append(path, sec.Name)
|
||||
}
|
||||
var own []agentapi.Component
|
||||
for _, c := range sec.Components {
|
||||
v.Total++
|
||||
if Problem(c) {
|
||||
v.Problems++
|
||||
}
|
||||
if match(path, c) {
|
||||
own = append(own, c)
|
||||
}
|
||||
}
|
||||
v.Matches += len(own)
|
||||
if v.size > 0 && len(own) > v.size {
|
||||
ps.Pages = (len(own) + v.size - 1) / v.size
|
||||
ps.Page = min(max(v.pages[key], 0), ps.Pages-1)
|
||||
own = own[ps.Page*v.size : min((ps.Page+1)*v.size, len(own))]
|
||||
}
|
||||
ps.Components = own
|
||||
// Unnamed sections are top-level lists without children.
|
||||
if sec.Name != "" {
|
||||
for i, child := range sec.Children {
|
||||
if c, ok := walk(child, key+"."+strconv.Itoa(i), path); ok {
|
||||
ps.Children = append(ps.Children, c)
|
||||
}
|
||||
}
|
||||
}
|
||||
return ps, !filtered || len(ps.Components) > 0 || len(ps.Children) > 0
|
||||
}
|
||||
for i, sec := range sections {
|
||||
if ps, ok := walk(sec, strconv.Itoa(i), nil); ok {
|
||||
v.Sections = append(v.Sections, ps)
|
||||
}
|
||||
}
|
||||
return v
|
||||
}
|
||||
|
||||
// BarPath draws the bars of one status of a chart.
|
||||
type BarPath struct {
|
||||
Status Status
|
||||
D string
|
||||
}
|
||||
|
||||
// BarPaths draws bars as one path per status instead of an element with a
|
||||
// tooltip each: status pages list thousands of components with 90 bars
|
||||
// each, and their detail pages have the tooltips.
|
||||
func BarPaths(bs []Bar, height int) []BarPath {
|
||||
var order []Status
|
||||
ds := map[Status]*strings.Builder{}
|
||||
h := strconv.Itoa(height)
|
||||
for i, b := range bs {
|
||||
d, ok := ds[b.Status]
|
||||
if !ok {
|
||||
d = &strings.Builder{}
|
||||
ds[b.Status] = d
|
||||
order = append(order, b.Status)
|
||||
}
|
||||
d.WriteString("M" + strconv.Itoa(i*4) + " 0h3v" + h + "h-3z")
|
||||
}
|
||||
out := make([]BarPath, 0, len(order))
|
||||
for _, st := range order {
|
||||
out = append(out, BarPath{Status: st, D: ds[st].String()})
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// NoticeForm is the button of a notice page that acts on a mailed link,
|
||||
|
||||
+100
-11
@@ -22,6 +22,12 @@ templ publicShell(s agentapi.PageSnapshot, a PublicAssets, docTitle string) {
|
||||
<link rel="alternate" type="application/rss+xml" title={ s.Title } href={ a.ComponentBase + "feed.rss" }/>
|
||||
}
|
||||
<title>{ docTitle }</title>
|
||||
if a.Meta != nil {
|
||||
@metaTags(a.Meta)
|
||||
}
|
||||
if a.NoIndex {
|
||||
@noIndex()
|
||||
}
|
||||
if a.InlineCSS == "" {
|
||||
@faviconLinks()
|
||||
}
|
||||
@@ -94,10 +100,20 @@ templ PublicStatusPage(s agentapi.PageSnapshot, a PublicAssets) {
|
||||
<p class="text-lg font-medium">{ i18n.T(ctx, "page.status."+s.Status) }</p>
|
||||
</section>
|
||||
@pageMaintenance(i18n.T(ctx, "page.maintenance_ongoing"), s.Ongoing(a.Now))
|
||||
if len(s.Sections) > 0 {
|
||||
if v := PublicComponents(s.Sections, a); len(s.Sections) > 0 {
|
||||
if v.Filterable() {
|
||||
@publicComponentFilter(v, a)
|
||||
}
|
||||
<section class="mb-12 border-t border-rule">
|
||||
for _, sec := range s.Sections {
|
||||
@publicSection(sec, s, a)
|
||||
for _, sec := range v.Sections {
|
||||
@publicSection(sec, v, s, a)
|
||||
}
|
||||
if v.Filtered() && v.Matches == 0 {
|
||||
if v.OnlyProblems && v.Query == "" {
|
||||
<p class="py-6 text-sm text-muted">{ i18n.T(ctx, "page.filter_no_problems") }</p>
|
||||
} else {
|
||||
<p class="py-6 text-sm text-muted">{ i18n.T(ctx, "page.search_none") }</p>
|
||||
}
|
||||
}
|
||||
</section>
|
||||
}
|
||||
@@ -158,23 +174,59 @@ templ PublicNoticePage(s agentapi.PageSnapshot, a PublicAssets, title, message s
|
||||
}
|
||||
}
|
||||
|
||||
// publicComponentFilter searches the components of pages listing too many
|
||||
// to scan, or narrows them to those with an outage.
|
||||
templ publicComponentFilter(v ComponentView, a PublicAssets) {
|
||||
<form method="get" action={ templ.SafeURL(BackHref(a.ComponentBase)) } role="search" class="mb-4 flex flex-wrap items-center gap-x-4 gap-y-2 text-sm">
|
||||
<label class="sr-only" for="component-search">{ i18n.T(ctx, "page.search") }</label>
|
||||
<input id="component-search" type="search" name="q" value={ v.Query } maxlength="100" placeholder={ i18n.T(ctx, "page.search") } class="min-w-0 flex-1 border border-rule bg-transparent px-2 py-1.5"/>
|
||||
<label class="flex items-center gap-2">
|
||||
<input type="checkbox" name="problems" value="1" checked?={ v.OnlyProblems }/>
|
||||
<span>{ i18n.T(ctx, "page.filter_problems", "Count", v.Problems) }</span>
|
||||
</label>
|
||||
<button type="submit" class="border border-ink px-3 py-1.5 hover:bg-ink hover:text-paper">{ i18n.T(ctx, "page.search_submit") }</button>
|
||||
if v.Filtered() {
|
||||
<a href={ templ.SafeURL(v.ResetHref()) } class="text-muted hover:text-ink">{ i18n.T(ctx, "page.search_clear") }</a>
|
||||
}
|
||||
</form>
|
||||
}
|
||||
|
||||
// publicSectionPager turns the pages of a section's own components.
|
||||
templ publicSectionPager(sec PublicSection, v ComponentView) {
|
||||
if sec.Pages > 1 {
|
||||
<nav class="flex flex-wrap items-center gap-x-5 gap-y-2 border-b border-rule py-2 text-sm" aria-label={ i18n.T(ctx, "pager.label") }>
|
||||
if sec.Page > 0 {
|
||||
<a href={ templ.SafeURL(v.PageHref(sec.Key, sec.Page-1)) } rel="prev" class="text-muted hover:text-ink">← { i18n.T(ctx, "pager.previous") }</a>
|
||||
}
|
||||
<span class="font-mono text-xs text-muted">{ i18n.T(ctx, "page.pages", "Page", sec.Page+1, "Pages", sec.Pages) }</span>
|
||||
if sec.Page < sec.Pages-1 {
|
||||
<a href={ templ.SafeURL(v.PageHref(sec.Key, sec.Page+1)) } rel="next" class="ml-auto text-muted hover:text-ink">{ i18n.T(ctx, "pager.next") } →</a>
|
||||
}
|
||||
</nav>
|
||||
}
|
||||
}
|
||||
|
||||
// publicSection renders an unnamed root component list or a collapsible nested
|
||||
// group matching the monitor dashboard hierarchy.
|
||||
templ publicSection(sec agentapi.Section, s agentapi.PageSnapshot, a PublicAssets) {
|
||||
templ publicSection(sec PublicSection, v ComponentView, s agentapi.PageSnapshot, a PublicAssets) {
|
||||
if sec.Name == "" {
|
||||
@publicComponentList(sec.Components, s, a)
|
||||
<div id={ "g-" + sec.Key }>
|
||||
@publicComponentList(sec.Components, s, a)
|
||||
@publicSectionPager(sec, v)
|
||||
</div>
|
||||
} else {
|
||||
<details open class="border-b border-rule">
|
||||
<details open id={ "g-" + sec.Key } class="border-b border-rule">
|
||||
<summary class="flex cursor-pointer items-center gap-2.5 py-3 text-sm font-medium select-none hover:bg-rule/30">
|
||||
@statusDot(SectionStatus(sec))
|
||||
@statusDot(PageStatus(sec.Status))
|
||||
<span>{ sec.Name }</span>
|
||||
<span class="font-mono text-xs font-normal text-muted">{ strconv.Itoa(SectionTotal(sec)) }</span>
|
||||
<span class="ml-auto text-xs font-normal text-muted">{ i18n.T(ctx, "page.component."+string(secStatusName(sec))) }</span>
|
||||
<span class="font-mono text-xs font-normal text-muted">{ strconv.Itoa(sec.Total) }</span>
|
||||
<span class="ml-auto text-xs font-normal text-muted">{ i18n.T(ctx, "page.component."+sec.Status) }</span>
|
||||
</summary>
|
||||
<div class="ml-4 border-l border-rule pl-4">
|
||||
@publicComponentList(sec.Components, s, a)
|
||||
@publicSectionPager(sec, v)
|
||||
for _, child := range sec.Children {
|
||||
@publicSection(child, s, a)
|
||||
@publicSection(child, v, s, a)
|
||||
}
|
||||
</div>
|
||||
</details>
|
||||
@@ -238,7 +290,12 @@ templ publicComponentBody(comp agentapi.Component, s agentapi.PageSnapshot, clic
|
||||
}
|
||||
</span>
|
||||
</div>
|
||||
@bars(DayBars(comp.Days), 22)
|
||||
if clickable {
|
||||
// The detail page the row links to has the tooltips.
|
||||
@pathBars(DayBars(comp.Days), 22)
|
||||
} else {
|
||||
@bars(DayBars(comp.Days), 22)
|
||||
}
|
||||
<div class="mt-1 flex justify-between font-mono text-xs text-muted">
|
||||
<span>{ i18n.T(ctx, "page.days_ago", "Count", len(comp.Days)) }</span>
|
||||
<span>{ UptimeText(comp.Uptime) }</span>
|
||||
@@ -446,3 +503,35 @@ templ pageMaintenance(heading string, items []agentapi.PageMaintenance) {
|
||||
</section>
|
||||
}
|
||||
}
|
||||
|
||||
// PublicNotFoundPage answers visitors of a status page that does not exist,
|
||||
// and of the bare status page domain, with a link to the home page if set.
|
||||
templ PublicNotFoundPage(cssHref, home string) {
|
||||
<!DOCTYPE html>
|
||||
<html lang={ i18n.Lang(ctx) }>
|
||||
<head>
|
||||
<meta charset="utf-8"/>
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1"/>
|
||||
<meta name="robots" content="noindex"/>
|
||||
<title>{ i18n.T(ctx, "page.not_found_title") }</title>
|
||||
@faviconLinks()
|
||||
<link rel="stylesheet" href={ cssHref }/>
|
||||
</head>
|
||||
<body class="min-h-screen">
|
||||
<main class="mx-auto flex min-h-screen max-w-xl flex-col justify-center px-4 py-14 sm:px-6">
|
||||
<p class="mb-3 font-mono text-xs text-muted">404</p>
|
||||
<h1 class="mb-3 text-2xl font-semibold">{ i18n.T(ctx, "page.not_found_title") }</h1>
|
||||
<p class="mb-8 text-muted">{ i18n.T(ctx, "page.not_found") }</p>
|
||||
if home != "" {
|
||||
<p>
|
||||
<a href={ templ.SafeURL(home) } class="inline-block border border-ink px-4 py-2 text-sm hover:bg-ink hover:text-paper">{ i18n.T(ctx, "page.not_found_home") }</a>
|
||||
</p>
|
||||
}
|
||||
<p class="mt-14 flex items-center gap-1 font-mono text-xs text-muted">
|
||||
@brandMark("h-3.5 w-3.5")
|
||||
UptimeSebi
|
||||
</p>
|
||||
</main>
|
||||
</body>
|
||||
</html>
|
||||
}
|
||||
+1038
-507
File diff suppressed because it is too large.
Load diff
@@ -33,7 +33,7 @@ var Ranges = []TimeRange{
|
||||
{Key: "1h", Window: time.Hour, Bucket: time.Minute, Layout: "15:04"},
|
||||
{Key: "3h", Window: 3 * time.Hour, Bucket: 5 * time.Minute, Layout: "15:04"},
|
||||
{Key: "12h", Window: 12 * time.Hour, Bucket: 15 * time.Minute, Layout: "15:04"},
|
||||
{Key: "24h", Window: day, Bucket: 30 * time.Minute, Layout: "01-02 15:04"},
|
||||
{Key: "24h", Window: day, Bucket: time.Hour, Source: SourceHourly, Layout: "01-02 15:04"},
|
||||
{Key: "7d", Window: 7 * day, Bucket: 4 * time.Hour, Source: SourceHourly, Layout: "01-02 15:04"},
|
||||
{Key: "30d", Window: 30 * day, Bucket: 12 * time.Hour, Source: SourceHourly, Layout: "2006-01-02 15:04"},
|
||||
{Key: "90d", Window: 90 * day, Bucket: 2 * day, Source: SourceDaily, Layout: "2006-01-02"},
|
||||
|
||||
@@ -0,0 +1,71 @@
|
||||
package web
|
||||
|
||||
import (
|
||||
"strconv"
|
||||
|
||||
"git.zb-server.de/ZB-Server/uptimesebi/internal/i18n"
|
||||
)
|
||||
|
||||
// MapServer serves the map tiles, styles and the MapLibre library the
|
||||
// region maps load.
|
||||
const MapServer = "https://maps.zb-server.de"
|
||||
|
||||
// coord formats a coordinate for an attribute or input, empty for none.
|
||||
func coord(f *float64) string {
|
||||
if f == nil {
|
||||
return ""
|
||||
}
|
||||
return strconv.FormatFloat(*f, 'f', -1, 64)
|
||||
}
|
||||
|
||||
// HasLocation reports whether r has a place on the map.
|
||||
func (r RegionOption) HasLocation() bool { return r.Lat != nil && r.Lon != nil }
|
||||
|
||||
// HasLocation reports whether r has a place on the map.
|
||||
func (r Region) HasLocation() bool { return r.Lat != nil && r.Lon != nil }
|
||||
|
||||
// regionMap is a map of the regions marked with data-lat and data-lon
|
||||
// inside the element items selects. In "select" mode a click on a marker
|
||||
// toggles the region's checkbox; in "edit" mode a click on the map fills
|
||||
// the active [data-location-form]. The script shows it once the map loads.
|
||||
templ regionMap(mode, items string) {
|
||||
<div
|
||||
data-region-map={ mode }
|
||||
data-region-items={ items }
|
||||
data-map-server={ MapServer }
|
||||
data-touch-hint={ i18n.T(ctx, "regions.map_touch_hint") }
|
||||
data-scroll-hint={ i18n.T(ctx, "regions.map_scroll_hint", "Key", "{key}") }
|
||||
data-ctrl-key={ i18n.T(ctx, "regions.map_ctrl_key") }
|
||||
hidden
|
||||
class="region-map mb-3 h-60 w-full overflow-hidden border border-rule sm:h-72"
|
||||
></div>
|
||||
}
|
||||
|
||||
// locationFields are the coordinate inputs of a region; empty ones remove
|
||||
// the location.
|
||||
templ locationFields(lat, lon *float64) {
|
||||
<div class="flex flex-wrap gap-3">
|
||||
for _, f := range []struct {
|
||||
label, name, value, min, max string
|
||||
}{
|
||||
{i18n.T(ctx, "regions.latitude"), "latitude", coord(lat), "-90", "90"},
|
||||
{i18n.T(ctx, "regions.longitude"), "longitude", coord(lon), "-180", "180"},
|
||||
} {
|
||||
<label class="mb-4 block">
|
||||
<span class="mb-1 block text-xs font-medium uppercase tracking-wider text-muted">{ f.label }</span>
|
||||
<input
|
||||
type="number"
|
||||
step="any"
|
||||
name={ f.name }
|
||||
data-number
|
||||
data-nullable
|
||||
data-location-field={ f.name }
|
||||
value={ f.value }
|
||||
min={ f.min }
|
||||
max={ f.max }
|
||||
class="w-36 border border-rule bg-transparent px-2.5 py-1.5 font-mono text-sm outline-none focus:border-ink"
|
||||
/>
|
||||
</label>
|
||||
}
|
||||
</div>
|
||||
}
|
||||
@@ -0,0 +1,263 @@
|
||||
// Code generated by templ - DO NOT EDIT.
|
||||
|
||||
// templ: version: v0.3.1118
|
||||
|
||||
package web
|
||||
|
||||
//lint:file-ignore SA4006 This context is only used if a nested component is present.
|
||||
|
||||
import "github.com/a-h/templ"
|
||||
import templruntime "github.com/a-h/templ/runtime"
|
||||
|
||||
import (
|
||||
"strconv"
|
||||
|
||||
"git.zb-server.de/ZB-Server/uptimesebi/internal/i18n"
|
||||
)
|
||||
|
||||
// MapServer serves the map tiles, styles and the MapLibre library the
|
||||
// region maps load.
|
||||
const MapServer = "https://maps.zb-server.de"
|
||||
|
||||
// coord formats a coordinate for an attribute or input, empty for none.
|
||||
func coord(f *float64) string {
|
||||
if f == nil {
|
||||
return ""
|
||||
}
|
||||
return strconv.FormatFloat(*f, 'f', -1, 64)
|
||||
}
|
||||
|
||||
// HasLocation reports whether r has a place on the map.
|
||||
func (r RegionOption) HasLocation() bool { return r.Lat != nil && r.Lon != nil }
|
||||
|
||||
// HasLocation reports whether r has a place on the map.
|
||||
func (r Region) HasLocation() bool { return r.Lat != nil && r.Lon != nil }
|
||||
|
||||
// regionMap is a map of the regions marked with data-lat and data-lon
|
||||
// inside the element items selects. In "select" mode a click on a marker
|
||||
// toggles the region's checkbox; in "edit" mode a click on the map fills
|
||||
// the active [data-location-form]. The script shows it once the map loads.
|
||||
func regionMap(mode, items string) templ.Component {
|
||||
return templruntime.GeneratedTemplate(func(templ_7745c5c3_Input templruntime.GeneratedComponentInput) (templ_7745c5c3_Err error) {
|
||||
templ_7745c5c3_W, ctx := templ_7745c5c3_Input.Writer, templ_7745c5c3_Input.Context
|
||||
if templ_7745c5c3_CtxErr := ctx.Err(); templ_7745c5c3_CtxErr != nil {
|
||||
return templ_7745c5c3_CtxErr
|
||||
}
|
||||
templ_7745c5c3_Buffer, templ_7745c5c3_IsBuffer := templruntime.GetBuffer(templ_7745c5c3_W)
|
||||
if !templ_7745c5c3_IsBuffer {
|
||||
defer func() {
|
||||
templ_7745c5c3_BufErr := templruntime.ReleaseBuffer(templ_7745c5c3_Buffer)
|
||||
if templ_7745c5c3_Err == nil {
|
||||
templ_7745c5c3_Err = templ_7745c5c3_BufErr
|
||||
}
|
||||
}()
|
||||
}
|
||||
ctx = templ.InitializeContext(ctx)
|
||||
ctx = templ.ClearChildren(ctx)
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 1, "<div data-region-map=\"")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
var templ_7745c5c3_Var2 string
|
||||
templ_7745c5c3_Var2, templ_7745c5c3_Err = templruntime.NewAttributeExpression(mode).Resolve(ctx)
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/regionmap.templ`, Line: 33, Col: 24}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ_7745c5c3_Var2)
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 2, "\" data-region-items=\"")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
var templ_7745c5c3_Var3 string
|
||||
templ_7745c5c3_Var3, templ_7745c5c3_Err = templruntime.NewAttributeExpression(items).Resolve(ctx)
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/regionmap.templ`, Line: 34, Col: 27}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ_7745c5c3_Var3)
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 3, "\" data-map-server=\"")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
var templ_7745c5c3_Var4 string
|
||||
templ_7745c5c3_Var4, templ_7745c5c3_Err = templruntime.NewAttributeExpression(MapServer).Resolve(ctx)
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/regionmap.templ`, Line: 35, Col: 29}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ_7745c5c3_Var4)
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 4, "\" data-touch-hint=\"")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
var templ_7745c5c3_Var5 string
|
||||
templ_7745c5c3_Var5, templ_7745c5c3_Err = templruntime.NewAttributeExpression(i18n.T(ctx, "regions.map_touch_hint")).Resolve(ctx)
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/regionmap.templ`, Line: 36, Col: 57}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ_7745c5c3_Var5)
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 5, "\" data-scroll-hint=\"")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
var templ_7745c5c3_Var6 string
|
||||
templ_7745c5c3_Var6, templ_7745c5c3_Err = templruntime.NewAttributeExpression(i18n.T(ctx, "regions.map_scroll_hint", "Key", "{key}")).Resolve(ctx)
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/regionmap.templ`, Line: 37, Col: 75}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ_7745c5c3_Var6)
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 6, "\" data-ctrl-key=\"")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
var templ_7745c5c3_Var7 string
|
||||
templ_7745c5c3_Var7, templ_7745c5c3_Err = templruntime.NewAttributeExpression(i18n.T(ctx, "regions.map_ctrl_key")).Resolve(ctx)
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/regionmap.templ`, Line: 38, Col: 53}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ_7745c5c3_Var7)
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 7, "\" hidden class=\"region-map mb-3 h-60 w-full overflow-hidden border border-rule sm:h-72\"></div>")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
return nil
|
||||
})
|
||||
}
|
||||
|
||||
// locationFields are the coordinate inputs of a region; empty ones remove
|
||||
// the location.
|
||||
func locationFields(lat, lon *float64) templ.Component {
|
||||
return templruntime.GeneratedTemplate(func(templ_7745c5c3_Input templruntime.GeneratedComponentInput) (templ_7745c5c3_Err error) {
|
||||
templ_7745c5c3_W, ctx := templ_7745c5c3_Input.Writer, templ_7745c5c3_Input.Context
|
||||
if templ_7745c5c3_CtxErr := ctx.Err(); templ_7745c5c3_CtxErr != nil {
|
||||
return templ_7745c5c3_CtxErr
|
||||
}
|
||||
templ_7745c5c3_Buffer, templ_7745c5c3_IsBuffer := templruntime.GetBuffer(templ_7745c5c3_W)
|
||||
if !templ_7745c5c3_IsBuffer {
|
||||
defer func() {
|
||||
templ_7745c5c3_BufErr := templruntime.ReleaseBuffer(templ_7745c5c3_Buffer)
|
||||
if templ_7745c5c3_Err == nil {
|
||||
templ_7745c5c3_Err = templ_7745c5c3_BufErr
|
||||
}
|
||||
}()
|
||||
}
|
||||
ctx = templ.InitializeContext(ctx)
|
||||
ctx = templ.ClearChildren(ctx)
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 8, "<div class=\"flex flex-wrap gap-3\">")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
for _, f := range []struct {
|
||||
label, name, value, min, max string
|
||||
}{
|
||||
{i18n.T(ctx, "regions.latitude"), "latitude", coord(lat), "-90", "90"},
|
||||
{i18n.T(ctx, "regions.longitude"), "longitude", coord(lon), "-180", "180"},
|
||||
} {
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 9, "<label class=\"mb-4 block\"><span class=\"mb-1 block text-xs font-medium uppercase tracking-wider text-muted\">")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
var templ_7745c5c3_Var9 string
|
||||
templ_7745c5c3_Var9, templ_7745c5c3_Err = templ.JoinStringErrs(f.label)
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/regionmap.templ`, Line: 55, Col: 94}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var9))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 10, "</span> <input type=\"number\" step=\"any\" name=\"")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
var templ_7745c5c3_Var10 string
|
||||
templ_7745c5c3_Var10, templ_7745c5c3_Err = templruntime.NewAttributeExpression(f.name).Resolve(ctx)
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/regionmap.templ`, Line: 59, Col: 18}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ_7745c5c3_Var10)
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 11, "\" data-number data-nullable data-location-field=\"")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
var templ_7745c5c3_Var11 string
|
||||
templ_7745c5c3_Var11, templ_7745c5c3_Err = templruntime.NewAttributeExpression(f.name).Resolve(ctx)
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/regionmap.templ`, Line: 62, Col: 33}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ_7745c5c3_Var11)
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 12, "\" value=\"")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
var templ_7745c5c3_Var12 string
|
||||
templ_7745c5c3_Var12, templ_7745c5c3_Err = templruntime.NewAttributeExpression(f.value).Resolve(ctx)
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/regionmap.templ`, Line: 63, Col: 20}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ_7745c5c3_Var12)
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 13, "\" min=\"")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
var templ_7745c5c3_Var13 string
|
||||
templ_7745c5c3_Var13, templ_7745c5c3_Err = templruntime.NewAttributeExpression(f.min).Resolve(ctx)
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/regionmap.templ`, Line: 64, Col: 16}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ_7745c5c3_Var13)
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 14, "\" max=\"")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
var templ_7745c5c3_Var14 string
|
||||
templ_7745c5c3_Var14, templ_7745c5c3_Err = templruntime.NewAttributeExpression(f.max).Resolve(ctx)
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/regionmap.templ`, Line: 65, Col: 16}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ_7745c5c3_Var14)
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 15, "\" class=\"w-36 border border-rule bg-transparent px-2.5 py-1.5 font-mono text-sm outline-none focus:border-ink\"></label>")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
}
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 16, "</div>")
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
return nil
|
||||
})
|
||||
}
|
||||
|
||||
var _ = templruntime.GeneratedTemplate
|
||||
@@ -1,6 +1,10 @@
|
||||
package web
|
||||
|
||||
import "git.zb-server.de/ZB-Server/uptimesebi/internal/i18n"
|
||||
import (
|
||||
"strconv"
|
||||
|
||||
"git.zb-server.de/ZB-Server/uptimesebi/internal/i18n"
|
||||
)
|
||||
|
||||
// Region is a row in a region list.
|
||||
type Region struct {
|
||||
@@ -12,6 +16,9 @@ type Region struct {
|
||||
// Manageable regions can be deleted on the current page.
|
||||
Manageable bool
|
||||
Instances int64
|
||||
// Lat and Lon place the region on the map; both are nil without a
|
||||
// location.
|
||||
Lat, Lon *float64
|
||||
}
|
||||
|
||||
// Agent is a checker or status page server.
|
||||
@@ -65,23 +72,33 @@ type RegionsView struct {
|
||||
templ regionsBody(v RegionsView) {
|
||||
<section class="mb-12">
|
||||
@sectionHeading("regions.list")
|
||||
<p class="mb-2 text-xs text-muted">{ i18n.T(ctx, "regions.location_pick_hint") }</p>
|
||||
@regionMap("edit", "#region-list")
|
||||
<div class="overflow-x-auto">
|
||||
<table class="w-full text-left text-sm">
|
||||
<thead class="border-b border-rule text-xs uppercase tracking-wider text-muted">
|
||||
<tr>
|
||||
<th class="py-2 pr-4 font-medium">{ i18n.T(ctx, "sso.field.name") }</th>
|
||||
<th class="py-2 pr-4 font-medium">{ i18n.T(ctx, "regions.key") }</th>
|
||||
<th class="py-2 pr-4 font-medium">{ i18n.T(ctx, "regions.owner") }</th>
|
||||
<th class="hidden py-2 pr-4 font-medium sm:table-cell">{ i18n.T(ctx, "regions.key") }</th>
|
||||
<th class="hidden py-2 pr-4 font-medium sm:table-cell">{ i18n.T(ctx, "regions.owner") }</th>
|
||||
<th class="py-2 pr-4 font-medium">{ i18n.T(ctx, "regions.instances") }</th>
|
||||
<th class="py-2 pr-4 font-medium">{ i18n.T(ctx, "regions.location") }</th>
|
||||
<th class="py-2"></th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody class="divide-y divide-rule">
|
||||
<tbody id="region-list" class="divide-y divide-rule">
|
||||
for _, r := range v.Regions {
|
||||
<tr>
|
||||
<tr
|
||||
if r.HasLocation() {
|
||||
data-lat={ coord(r.Lat) }
|
||||
data-lon={ coord(r.Lon) }
|
||||
}
|
||||
data-name={ r.Name }
|
||||
data-live={ strconv.FormatInt(r.Instances, 10) }
|
||||
>
|
||||
<td class="py-2.5 pr-4">{ r.Name }</td>
|
||||
<td class="py-2.5 pr-4 font-mono text-xs">{ r.Key }</td>
|
||||
<td class="py-2.5 pr-4">
|
||||
<td class="hidden py-2.5 pr-4 font-mono text-xs sm:table-cell">{ r.Key }</td>
|
||||
<td class="hidden py-2.5 pr-4 sm:table-cell">
|
||||
if r.Platform {
|
||||
<span class="text-muted">{ i18n.T(ctx, "regions.platform") }</span>
|
||||
} else {
|
||||
@@ -91,12 +108,41 @@ templ regionsBody(v RegionsView) {
|
||||
<td class="py-2.5 pr-4 font-mono text-xs">
|
||||
<span class={ templ.KV("text-up", r.Instances > 0), templ.KV("text-unknown", r.Instances == 0) }>●</span> { i18n.T(ctx, "regions.live", "Count", int(r.Instances)) }
|
||||
</td>
|
||||
<td class="py-2.5 pr-4 font-mono text-xs">
|
||||
if r.HasLocation() {
|
||||
{ coord(r.Lat) }, { coord(r.Lon) }
|
||||
} else {
|
||||
<span class="text-muted">–</span>
|
||||
}
|
||||
if r.Manageable {
|
||||
<button type="button" data-location-toggle={ "location-" + r.ID } class="ml-2 font-sans text-muted hover:text-ink">{ i18n.T(ctx, "regions.location_set") }</button>
|
||||
}
|
||||
</td>
|
||||
<td class="py-2.5 text-right">
|
||||
if r.Manageable {
|
||||
<button type="button" data-delete={ v.APIBase + "/regions/" + r.ID } data-confirm={ i18n.T(ctx, "regions.delete_confirm") } class="text-muted hover:text-down">{ i18n.T(ctx, "regions.delete") }</button>
|
||||
}
|
||||
</td>
|
||||
</tr>
|
||||
if r.Manageable {
|
||||
<tr id={ "location-" + r.ID } hidden>
|
||||
<td colspan="6" class="py-3">
|
||||
<form data-api={ v.APIBase + "/regions/" + r.ID } data-method="patch" data-next={ v.Next } data-location-form>
|
||||
@formError()
|
||||
<p class="mb-2 text-xs text-muted">{ i18n.T(ctx, "regions.location_for", "Name", r.Name) }</p>
|
||||
<div class="flex flex-wrap items-end gap-4">
|
||||
@locationFields(r.Lat, r.Lon)
|
||||
<div class="mb-4 flex gap-3">
|
||||
<button type="submit" class="bg-ink px-3 py-1.5 text-sm font-medium text-paper hover:opacity-90 disabled:opacity-50">{ i18n.T(ctx, "common.save") }</button>
|
||||
if r.HasLocation() {
|
||||
<button type="button" data-location-clear class="text-sm text-muted hover:text-down">{ i18n.T(ctx, "regions.location_clear") }</button>
|
||||
}
|
||||
</div>
|
||||
</div>
|
||||
</form>
|
||||
</td>
|
||||
</tr>
|
||||
}
|
||||
}
|
||||
</tbody>
|
||||
</table>
|
||||
@@ -109,6 +155,9 @@ templ regionsBody(v RegionsView) {
|
||||
@formError()
|
||||
@valueField(i18n.T(ctx, "regions.key"), "key", "", "office-berlin", true)
|
||||
@valueField(i18n.T(ctx, "sso.field.name"), "name", "", "Office Berlin", false)
|
||||
<div data-location-form data-location-default>
|
||||
@locationFields(nil, nil)
|
||||
</div>
|
||||
@submit(i18n.T(ctx, "regions.create"))
|
||||
</form>
|
||||
</section>
|
||||
@@ -195,7 +244,7 @@ templ RegionsPage(p Page, me Me, v RegionsView) {
|
||||
}
|
||||
}
|
||||
|
||||
templ AdminPage(p Page, me Me, v RegionsView, storage StorageView, checkTypes []CheckTypeOption, platformPrivate bool, limits LimitsView, idps IDPAdminView) {
|
||||
templ AdminPage(p Page, me Me, v RegionsView, storage StorageView, checkTypes []CheckTypeOption, platformPrivate bool, pageHome string, limits LimitsView, idps IDPAdminView) {
|
||||
@consoleShell(p, me) {
|
||||
@settingsHeading("admin.title", "admin.intro")
|
||||
@adminLinks()
|
||||
@@ -203,6 +252,7 @@ templ AdminPage(p Page, me Me, v RegionsView, storage StorageView, checkTypes []
|
||||
@limitsSection(limits)
|
||||
@regionsBody(v)
|
||||
@checkerNetworkSection(platformPrivate)
|
||||
@statusPageHomeSection(pageHome)
|
||||
@checkTypesSection(checkTypes, "/admin/check-types", "/admin", "admin.check_types_intro")
|
||||
@storageSection(storage)
|
||||
}
|
||||
@@ -228,6 +278,23 @@ templ checkerNetworkSection(allow bool) {
|
||||
</section>
|
||||
}
|
||||
|
||||
// statusPageHomeSection sets the home page the status page servers link
|
||||
// from their error page.
|
||||
templ statusPageHomeSection(url string) {
|
||||
<section class="mt-12 max-w-3xl">
|
||||
@sectionHeading("admin.statuspage_home")
|
||||
<p class="mb-4 text-sm text-muted">{ i18n.T(ctx, "admin.statuspage_home_hint") }</p>
|
||||
<form data-api="/admin/statuspage-home" data-method="put" data-next="/admin">
|
||||
@formError()
|
||||
<label class="mb-4 block">
|
||||
<span class="mb-1 block text-xs font-medium uppercase tracking-wider text-muted">{ i18n.T(ctx, "admin.statuspage_home_url") }</span>
|
||||
<input class="w-full border border-rule bg-transparent px-2.5 py-1.5 outline-none focus:border-ink" type="url" name="url" value={ url } maxlength="2000" placeholder="https://example.com"/>
|
||||
</label>
|
||||
<button type="submit" class="border border-ink px-3 py-1.5 text-sm hover:bg-ink hover:text-paper">{ i18n.T(ctx, "common.save") }</button>
|
||||
</form>
|
||||
</section>
|
||||
}
|
||||
|
||||
// checkTypesSection lets the platform or an organization choose the
|
||||
// check types it offers.
|
||||
templ checkTypesSection(types []CheckTypeOption, api, next, introID string) {
|
||||
|
||||
+983
-590
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,55 @@
|
||||
package web
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/xml"
|
||||
"time"
|
||||
)
|
||||
|
||||
type sitemapLink struct {
|
||||
Rel string `xml:"rel,attr"`
|
||||
Hreflang string `xml:"hreflang,attr"`
|
||||
Href string `xml:"href,attr"`
|
||||
}
|
||||
|
||||
type sitemapURL struct {
|
||||
Loc string `xml:"loc"`
|
||||
LastMod string `xml:"lastmod,omitempty"`
|
||||
Links []sitemapLink `xml:"xhtml:link"`
|
||||
}
|
||||
|
||||
type sitemap struct {
|
||||
XMLName xml.Name `xml:"urlset"`
|
||||
NS string `xml:"xmlns,attr"`
|
||||
XHTML string `xml:"xmlns:xhtml,attr"`
|
||||
URLs []sitemapURL `xml:"url"`
|
||||
}
|
||||
|
||||
// Sitemap lists pages with each of their language versions, as NewPageMeta
|
||||
// names them; lastMod may be zero.
|
||||
func Sitemap(pages, langs []string, lastMod time.Time) ([]byte, error) {
|
||||
sm := sitemap{NS: "http://www.sitemaps.org/schemas/sitemap/0.9", XHTML: "http://www.w3.org/1999/xhtml"}
|
||||
mod := ""
|
||||
if !lastMod.IsZero() {
|
||||
mod = lastMod.UTC().Format(time.RFC3339)
|
||||
}
|
||||
for _, page := range pages {
|
||||
m := NewPageMeta("", "", page, "", "", "", false, langs)
|
||||
links := make([]sitemapLink, len(m.Alternates))
|
||||
for i, a := range m.Alternates {
|
||||
links[i] = sitemapLink{Rel: "alternate", Hreflang: a.Lang, Href: a.URL}
|
||||
}
|
||||
for _, a := range m.Alternates {
|
||||
sm.URLs = append(sm.URLs, sitemapURL{Loc: a.URL, LastMod: mod, Links: links})
|
||||
}
|
||||
}
|
||||
var buf bytes.Buffer
|
||||
buf.WriteString(xml.Header)
|
||||
enc := xml.NewEncoder(&buf)
|
||||
enc.Indent("", " ")
|
||||
if err := enc.Encode(sm); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
buf.WriteString("\n")
|
||||
return buf.Bytes(), nil
|
||||
}
|
||||
@@ -320,11 +320,11 @@ templ StatusPageEditor(p Page, me Me, e PageEditor) {
|
||||
<template data-row-fields>
|
||||
@pageMonitorFields(e, PageMonitorOption{})
|
||||
</template>
|
||||
<ul id="page-monitors" class="mb-4 divide-y divide-rule border-y border-rule text-sm">
|
||||
<ul id="page-monitors" class="mb-4 divide-y divide-rule border-y border-rule text-sm" data-page-size={ strconv.Itoa(monitorPageSize) }>
|
||||
for _, m := range e.Monitors {
|
||||
<li data-row class="grid grid-cols-[auto_1fr] items-center gap-x-3 gap-y-1.5 py-2">
|
||||
<input type="checkbox" data-field="include" checked?={ m.Included } class="accent-ink" aria-label={ m.Name }/>
|
||||
<span class="flex flex-wrap items-baseline gap-x-2">
|
||||
<span data-filter-text class="flex flex-wrap items-baseline gap-x-2">
|
||||
<span>{ m.Name }</span>
|
||||
if m.MonitorGroupPath != "" {
|
||||
<span class="font-mono text-xs text-muted">{ m.MonitorGroupPath }</span>
|
||||
@@ -339,6 +339,15 @@ templ StatusPageEditor(p Page, me Me, e PageEditor) {
|
||||
</li>
|
||||
}
|
||||
</ul>
|
||||
if len(e.Monitors) > monitorPageSize {
|
||||
// All rows stay in the form, as saving replaces the page's
|
||||
// monitors; the pager only shows them a page at a time.
|
||||
<nav data-row-pager="#page-monitors" class="-mt-2 mb-4 flex flex-wrap items-center gap-x-5 gap-y-2 text-sm" aria-label={ i18n.T(ctx, "pager.label") }>
|
||||
<button type="button" data-row-page="prev" class="text-muted hover:text-ink disabled:opacity-40">← { i18n.T(ctx, "pager.previous") }</button>
|
||||
<span data-row-page-status data-template={ i18n.T(ctx, "pages.monitors_range") } class="text-xs text-muted"></span>
|
||||
<button type="button" data-row-page="next" class="text-muted hover:text-ink disabled:opacity-40">{ i18n.T(ctx, "pager.next") } →</button>
|
||||
</nav>
|
||||
}
|
||||
@submit(i18n.T(ctx, "common.save"))
|
||||
</form>
|
||||
</section>
|
||||
@@ -416,16 +425,33 @@ templ verifyButton(pageID, label string) {
|
||||
// offers to filter them.
|
||||
const monitorFilterFrom = 15
|
||||
|
||||
// monitorPageSize is how many monitors the page editor shows at a time.
|
||||
const monitorPageSize = 50
|
||||
|
||||
// pageMonitorFields are the group and label of m on the page.
|
||||
templ pageMonitorFields(e PageEditor, m PageMonitorOption) {
|
||||
<span data-row-extra></span>
|
||||
<span class="flex gap-2">
|
||||
<select data-field="group_id" data-nullable aria-label={ i18n.T(ctx, "pages.group") } class="w-1/2 border border-rule bg-transparent px-2 py-1 text-xs outline-none focus:border-ink">
|
||||
<option value="">{ i18n.T(ctx, "pages.no_group") }</option>
|
||||
for _, opt := range e.Groups {
|
||||
<option value={ opt.ID } selected?={ opt.ID == m.GroupID }>{ opt.Label }</option>
|
||||
}
|
||||
</select>
|
||||
if m.ID == "" {
|
||||
<select data-field="group_id" data-nullable aria-label={ i18n.T(ctx, "pages.group") } class="w-1/2 border border-rule bg-transparent px-2 py-1 text-xs outline-none focus:border-ink">
|
||||
<option value="">{ i18n.T(ctx, "pages.no_group") }</option>
|
||||
for _, opt := range e.Groups {
|
||||
<option value={ opt.ID }>{ opt.Label }</option>
|
||||
}
|
||||
</select>
|
||||
} else {
|
||||
// With thousands of monitors and hundreds of groups the options of
|
||||
// every row would make the page tens of megabytes: rows carry their
|
||||
// group only and get the others from the template when shown.
|
||||
<select data-field="group_id" data-nullable data-lazy-options aria-label={ i18n.T(ctx, "pages.group") } class="w-1/2 border border-rule bg-transparent px-2 py-1 text-xs outline-none focus:border-ink">
|
||||
<option value="">{ i18n.T(ctx, "pages.no_group") }</option>
|
||||
for _, opt := range e.Groups {
|
||||
if opt.ID == m.GroupID {
|
||||
<option value={ opt.ID } selected>{ opt.Label }</option>
|
||||
}
|
||||
}
|
||||
</select>
|
||||
}
|
||||
<input data-field="label" value={ m.Label } placeholder={ i18n.T(ctx, "pages.label") } class="w-1/2 border border-rule bg-transparent px-2 py-1 text-xs outline-none focus:border-ink"/>
|
||||
</span>
|
||||
}
|
||||
|
||||
+423
-280
File diff suppressed because it is too large.
Load diff
Vendored
+106
@@ -0,0 +1,106 @@
|
||||
<!doctype html><html><body data-msg-network="net">
|
||||
<form id="monitor">
|
||||
<div id="select-map" data-region-map="select" data-region-items="#monitor-regions" data-map-server="stub" data-touch-hint="t" data-scroll-hint="{key} s" data-ctrl-key="Ctrl" hidden style="width:300px;height:200px"></div>
|
||||
<div id="monitor-regions">
|
||||
<label><input type="checkbox" name="regions" value="r1" data-multi checked data-lat="50.11" data-lon="8.68" data-name="Frankfurt" data-live="2"></label>
|
||||
<label><input type="checkbox" name="regions" value="r2" data-multi data-lat="40.71" data-lon="-74.0" data-name="New York" data-live="0"></label>
|
||||
<label><input type="checkbox" name="regions" value="r3" data-multi data-name="Office" data-live="1"></label>
|
||||
</div>
|
||||
</form>
|
||||
<div id="edit-map" data-region-map="edit" data-region-items="#region-list" data-map-server="stub" data-touch-hint="t" data-scroll-hint="{key} s" data-ctrl-key="Ctrl" hidden style="width:300px;height:200px"></div>
|
||||
<table><tbody id="region-list">
|
||||
<tr data-lat="50.11" data-lon="8.68" data-name="Frankfurt" data-live="2"><td><button type="button" id="toggle" data-location-toggle="location-r1">set</button></td></tr>
|
||||
<tr id="location-r1" hidden><td><form data-api="/org/regions/r1" data-method="patch" data-next="#saved" data-location-form id="row-form">
|
||||
<input name="latitude" data-number data-nullable data-location-field="latitude" value="50.11">
|
||||
<input name="longitude" data-number data-nullable data-location-field="longitude" value="8.68">
|
||||
<button type="submit">save</button><button type="button" id="clear" data-location-clear>clear</button>
|
||||
</form></td></tr>
|
||||
</tbody></table>
|
||||
<form data-api="/org/regions" id="create"><div data-location-form data-location-default>
|
||||
<input name="latitude" data-number data-nullable data-location-field="latitude">
|
||||
<input name="longitude" data-number data-nullable data-location-field="longitude">
|
||||
</div></form>
|
||||
<pre id="out"></pre>
|
||||
<script>
|
||||
const sent = [];
|
||||
window.axios = { create: () => ({ interceptors: { request: { use() {} } }, request: async (cfg) => { sent.push(cfg); return { data: {} }; } }) };
|
||||
const maps = [];
|
||||
window.maplibregl = {
|
||||
Map: class {
|
||||
constructor(opts) { this.container = opts.container; this.handlers = {}; this.style = opts.style; maps.push(this); }
|
||||
on(ev, fn) { (this.handlers[ev] ??= []).push(fn); }
|
||||
fire(ev, arg) { for (const fn of this.handlers[ev] ?? []) fn(arg); }
|
||||
addControl() {}
|
||||
resize() {}
|
||||
fitBounds(b) { this.bounds = b.points; }
|
||||
jumpTo(o) { this.center = o.center; }
|
||||
setStyle(s) { this.style = s; }
|
||||
},
|
||||
Marker: class {
|
||||
constructor(o) { this.el = o.element; }
|
||||
setLngLat(p) { this.at = p; this.el.dataset.at = p.join(","); return this; }
|
||||
getLngLat() { return this.at; }
|
||||
addTo(map) { map.container.append(this.el); return this; }
|
||||
},
|
||||
NavigationControl: class {},
|
||||
LngLatBounds: class {
|
||||
constructor(a) { this.points = [a]; }
|
||||
extend(p) { this.points.push(p); return this; }
|
||||
},
|
||||
};
|
||||
</script>
|
||||
<script src="../assets/app.js"></script>
|
||||
<script>
|
||||
(async () => {
|
||||
const out = [];
|
||||
const check = (name, got, want) => {
|
||||
const g = JSON.stringify(got), w = JSON.stringify(want);
|
||||
out.push((g === w ? "PASS " : "FAIL ") + name + (g === w ? "" : " got=" + g + " want=" + w));
|
||||
};
|
||||
await new Promise((r) => setTimeout(r, 50));
|
||||
const sel = document.getElementById("select-map");
|
||||
const markers = () => [...sel.querySelectorAll(".region-pin")];
|
||||
const box = (v) => document.querySelector(`[value="${v}"]`);
|
||||
check("select map shown", sel.hidden, false);
|
||||
check("light style", maps[0].style, "stub/style-light.json");
|
||||
check("markers for located regions", markers().map((m) => m.title), ["Frankfurt", "New York"]);
|
||||
check("fits all markers", maps[0].bounds, [[8.68, 50.11], [-74, 40.71]]);
|
||||
check("checked marker filled", markers().map((m) => m.classList.contains("is-checked")), [true, false]);
|
||||
check("idle region marked", markers()[1].dataset.live, "0");
|
||||
markers()[1].click();
|
||||
check("marker click ticks checkbox", box("r2").checked, true);
|
||||
check("marker follows", markers()[1].classList.contains("is-checked"), true);
|
||||
check("row follows", box("r2").closest("label").classList.contains("is-checked"), true);
|
||||
markers()[0].dispatchEvent(new PointerEvent("pointerenter", { pointerType: "touch" }));
|
||||
check("a tap leaves no highlight", box("r1").closest("label").classList.contains("is-hover"), false);
|
||||
markers()[0].dispatchEvent(new PointerEvent("pointerenter", { pointerType: "mouse" }));
|
||||
check("hovering a marker lights its row", box("r1").closest("label").classList.contains("is-hover"), true);
|
||||
box("r2").closest("label").dispatchEvent(new PointerEvent("pointerenter", { pointerType: "mouse" }));
|
||||
check("hovering a row lights its marker", markers()[1].parentElement.classList.contains("is-hover"), true);
|
||||
box("r1").click();
|
||||
check("checkbox untick clears marker", markers()[0].classList.contains("is-checked"), false);
|
||||
|
||||
const edit = maps[1];
|
||||
const click = (lat, lng) => edit.fire("click", { lngLat: { lat, lng, wrap() { return { lat, lng: lng > 180 ? lng - 360 : lng }; } } });
|
||||
click(48.137154, 11.576124);
|
||||
const create = document.getElementById("create");
|
||||
check("map click fills create form", [create.elements.latitude.value, create.elements.longitude.value], ["48.1372", "11.5761"]);
|
||||
check("pick marker shown", document.querySelector("#edit-map .region-pick")?.dataset.at, "11.576124,48.137154");
|
||||
document.querySelector("#edit-map .region-pin").click();
|
||||
check("marker click opens its row", document.getElementById("location-r1").hidden, false);
|
||||
click(52.52, 373.4);
|
||||
const row = document.getElementById("row-form");
|
||||
check("map click fills open row", [row.elements.latitude.value, row.elements.longitude.value], ["52.52", "13.4"]);
|
||||
check("create form untouched", create.elements.latitude.value, "48.1372");
|
||||
document.getElementById("clear").click();
|
||||
await new Promise((r) => setTimeout(r, 50));
|
||||
check("clear sends nulls", sent.at(-1) && [sent.at(-1).method, sent.at(-1).url, sent.at(-1).data], ["patch", "/org/regions/r1", { latitude: null, longitude: null }]);
|
||||
document.getElementById("toggle").click();
|
||||
check("toggle closes row", document.getElementById("location-r1").hidden, true);
|
||||
click(1, 2);
|
||||
check("closed row falls back to create form", create.elements.latitude.value, "1");
|
||||
|
||||
document.getElementById("out").textContent = out.join("\n");
|
||||
})();
|
||||
</script>
|
||||
</body></html>
|
||||
+15
@@ -0,0 +1,15 @@
|
||||
<!doctype html><html><body data-msg-network="net">
|
||||
<div id="map" data-region-map="select" data-region-items="#items" data-map-server="./missing" data-touch-hint="t" data-scroll-hint="{key} s" data-ctrl-key="Ctrl" hidden></div>
|
||||
<div id="items"><input type="checkbox" data-lat="1" data-lon="2" data-name="x" data-live="1"></div>
|
||||
<pre id="out"></pre>
|
||||
<script>
|
||||
window.axios = { create: () => ({ interceptors: { request: { use() {} } } }) };
|
||||
</script>
|
||||
<script src="../assets/app.js"></script>
|
||||
<script>
|
||||
setTimeout(() => {
|
||||
const ok = document.getElementById("map").hidden && !document.querySelector(".region-pin");
|
||||
document.getElementById("out").textContent = (ok ? "PASS" : "FAIL") + " map stays hidden when MapLibre cannot load";
|
||||
}, 500);
|
||||
</script>
|
||||
</body></html>
|
||||
Vendored
+72
@@ -0,0 +1,72 @@
|
||||
<!doctype html><html><body data-msg-network="net">
|
||||
<form data-api="/org/statuspages/p1/monitors" data-method="put" data-rows="monitors" data-next="#saved" id="sp">
|
||||
<p><button type="button" id="all" data-check-all="on" data-check-target="[data-field=include]">all</button></p>
|
||||
<input type="search" id="filter" data-filter-rows="#rows">
|
||||
<template data-row-fields><span data-row-extra></span><select data-field="group_id" data-nullable><option value="">none</option><option value="g1">G1</option><option value="g2">G2</option></select></template>
|
||||
<ul id="rows" data-page-size="2"></ul>
|
||||
<nav data-row-pager="#rows">
|
||||
<button type="button" id="prev" data-row-page="prev">prev</button>
|
||||
<span id="status" data-row-page-status data-template="{from}-{to}/{total}"></span>
|
||||
<button type="button" id="next" data-row-page="next">next</button>
|
||||
</nav>
|
||||
<button type="submit">save</button>
|
||||
</form>
|
||||
<pre id="out"></pre>
|
||||
<script>
|
||||
const sent = [];
|
||||
window.axios = { create: () => ({ interceptors: { request: { use() {} } }, request: async (cfg) => { sent.push(cfg.data); return { data: {} }; }, post: async () => ({ data: {} }) }) };
|
||||
const list = document.getElementById("rows");
|
||||
for (const [id, name, on] of [["m1", "alpha", true], ["m2", "beta", false], ["m3", "gamma", false], ["m4", "alpine", false], ["m5", "delta", true]]) {
|
||||
list.insertAdjacentHTML("beforeend", `<li data-row><input type="checkbox" data-field="include"${on ? " checked" : ""}><span data-filter-text>${name}</span><input type="hidden" data-field="monitor_id" value="${id}">${on ? '<span data-row-extra></span><select data-field="group_id" data-nullable data-lazy-options><option value="">none</option><option value="g2" selected>G2</option></select>' : ""}</li>`);
|
||||
}
|
||||
</script>
|
||||
<script src="../assets/app.js"></script>
|
||||
<script>
|
||||
(async () => {
|
||||
const out = [];
|
||||
const check = (name, got, want) => {
|
||||
const g = JSON.stringify(got), w = JSON.stringify(want);
|
||||
out.push((g === w ? "PASS " : "FAIL ") + name + (g === w ? "" : " got=" + g + " want=" + w));
|
||||
};
|
||||
const visible = () => [...list.children].filter((r) => !r.hidden).map((r) => r.querySelector("[data-filter-text]").textContent);
|
||||
const status = () => document.getElementById("status").textContent;
|
||||
const submit = async () => {
|
||||
sent.length = 0;
|
||||
document.getElementById("sp").dispatchEvent(new Event("submit", { bubbles: true, cancelable: true }));
|
||||
await new Promise((r) => setTimeout(r, 50));
|
||||
return sent[0] ? (typeof sent[0] === "string" ? JSON.parse(sent[0]) : sent[0]).monitors.map((m) => m.monitor_id) : null;
|
||||
};
|
||||
const sel = (id) => document.querySelector(`[value="${id}"]`).closest("[data-row]").querySelector("select");
|
||||
check("shown row gets all options", [...sel("m1").options].map((o) => o.value), ["", "g1", "g2"]);
|
||||
check("shown row keeps its group", sel("m1").value, "g2");
|
||||
check("hidden row stays lean", sel("m5").options.length, 2);
|
||||
check("first page", visible(), ["alpha", "beta"]);
|
||||
check("first status", status(), "1-2/5");
|
||||
check("prev disabled", document.getElementById("prev").disabled, true);
|
||||
document.getElementById("next").click();
|
||||
document.getElementById("next").click();
|
||||
check("last page", visible(), ["delta"]);
|
||||
check("last status", status(), "5-5/5");
|
||||
check("next disabled", document.getElementById("next").disabled, true);
|
||||
check("row shown later gets all options", sel("m5").options.length, 3);
|
||||
check("rows of all pages sent", await submit(), ["m1", "m5"]);
|
||||
const filter = document.getElementById("filter");
|
||||
filter.value = "g1";
|
||||
filter.dispatchEvent(new Event("input", { bubbles: true }));
|
||||
check("group options are not searched", visible(), []);
|
||||
filter.value = "alp";
|
||||
filter.dispatchEvent(new Event("input", { bubbles: true }));
|
||||
check("filtered", visible(), ["alpha", "alpine"]);
|
||||
check("filtered status", status(), "1-2/2");
|
||||
check("pager hidden for one page", document.querySelector("[data-row-pager]").hidden, true);
|
||||
filter.value = "a";
|
||||
filter.dispatchEvent(new Event("input", { bubbles: true }));
|
||||
check("filter restarts at first page", visible(), ["alpha", "beta"]);
|
||||
filter.value = "alp";
|
||||
filter.dispatchEvent(new Event("input", { bubbles: true }));
|
||||
document.getElementById("all").click();
|
||||
check("check all ticks filtered rows only", await submit(), ["m1", "m4", "m5"]);
|
||||
document.getElementById("out").textContent = out.join("\n");
|
||||
})();
|
||||
</script>
|
||||
</body></html>
|
||||
Reference in new issue
Block a user