Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
9d01b62b98 | ||
|
|
4aa22327c2 | ||
|
|
965848017d | ||
|
|
b051f6c430 | ||
|
|
52d2ce25c9 | ||
|
|
383b63bc0e | ||
|
|
42d741846d | ||
|
|
4fd11cb45b | ||
|
|
ec33ef5c56 | ||
|
|
1f90fe8470 |
No files matched your search
@@ -88,6 +88,7 @@ func run(log *slog.Logger, level *slog.LevelVar) error {
|
|||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
health.Register(r)
|
health.Register(r)
|
||||||
|
r.Use(platform.Compress())
|
||||||
r.StaticFS("/static", web.Static())
|
r.StaticFS("/static", web.Static())
|
||||||
pages.Mount(r)
|
pages.Mount(r)
|
||||||
go pages.Run(ctx)
|
go pages.Run(ctx)
|
||||||
|
|||||||
@@ -362,14 +362,20 @@ type PageRef struct {
|
|||||||
Host string `json:"host,omitempty"`
|
Host string `json:"host,omitempty"`
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// PageIndex lists the pages a status page server serves.
|
||||||
|
type PageIndex struct {
|
||||||
|
Pages []PageRef `json:"pages"`
|
||||||
|
// HomeURL is the platform's home page, which the server links from
|
||||||
|
// its error page; empty for none.
|
||||||
|
HomeURL string `json:"home_url,omitempty"`
|
||||||
|
}
|
||||||
|
|
||||||
// Pages lists every page this status page server serves, so it can keep
|
// Pages lists every page this status page server serves, so it can keep
|
||||||
// them all cached before anyone visits.
|
// them all cached before anyone visits.
|
||||||
func (c *Client) Pages(ctx context.Context) ([]PageRef, error) {
|
func (c *Client) Pages(ctx context.Context) (PageIndex, error) {
|
||||||
var out struct {
|
var out PageIndex
|
||||||
Pages []PageRef `json:"pages"`
|
|
||||||
}
|
|
||||||
err := c.do(ctx, http.MethodGet, "/pages/index", nil, &out)
|
err := c.do(ctx, http.MethodGet, "/pages/index", nil, &out)
|
||||||
return out.Pages, err
|
return out, err
|
||||||
}
|
}
|
||||||
|
|
||||||
// ErrNotFound means no published page matches.
|
// ErrNotFound means no published page matches.
|
||||||
|
|||||||
@@ -318,6 +318,11 @@ var endpoints = []endpoint{
|
|||||||
{method: "PUT", path: "/api/v1/admin/checker-network", tag: "Platform", summary: "Let platform checkers check private addresses or not",
|
{method: "PUT", path: "/api/v1/admin/checker-network", tag: "Platform", summary: "Let platform checkers check private addresses or not",
|
||||||
description: "Unset, they may on self-hosted installations and may not in the cloud edition. Applies from each checker's next poll.",
|
description: "Unset, they may on self-hosted installations and may not in the cloud edition. Applies from each checker's next poll.",
|
||||||
perm: "platform admin", req: checkerNetwork{}, status: http.StatusNoContent},
|
perm: "platform admin", req: checkerNetwork{}, status: http.StatusNoContent},
|
||||||
|
{method: "GET", path: "/api/v1/admin/statuspage-home", tag: "Platform", summary: "The home page linked from the status page servers' error page", perm: "platform admin",
|
||||||
|
resp: statusPageHome{}},
|
||||||
|
{method: "PUT", path: "/api/v1/admin/statuspage-home", tag: "Platform", summary: "Set the home page linked from the status page servers' error page",
|
||||||
|
description: "Visitors of the bare status page domain and of pages that do not exist see an error page with a link to this URL. Empty links none.",
|
||||||
|
perm: "platform admin", req: statusPageHome{}, status: http.StatusNoContent},
|
||||||
{method: "GET", path: "/api/v1/admin/identity-providers", tag: "Platform", summary: "Identity providers for signing up and in",
|
{method: "GET", path: "/api/v1/admin/identity-providers", tag: "Platform", summary: "Identity providers for signing up and in",
|
||||||
description: "With the callback URL to register at each provider. Secrets are never returned.", perm: "platform admin",
|
description: "With the callback URL to register at each provider. Secrets are never returned.", perm: "platform admin",
|
||||||
resp: obj{"providers": []idpView{}, "callback_url": ""}},
|
resp: obj{"providers": []idpView{}, "callback_url": ""}},
|
||||||
|
|||||||
@@ -111,6 +111,7 @@ var auditActions = map[string]string{
|
|||||||
"PUT /api/v1/org/legal/:kind": "org.legal_update",
|
"PUT /api/v1/org/legal/:kind": "org.legal_update",
|
||||||
"PUT /api/v1/admin/check-types": "platform.check_types_update",
|
"PUT /api/v1/admin/check-types": "platform.check_types_update",
|
||||||
"PUT /api/v1/admin/checker-network": "platform.checker_network_update",
|
"PUT /api/v1/admin/checker-network": "platform.checker_network_update",
|
||||||
|
"PUT /api/v1/admin/statuspage-home": "platform.statuspage_home_update",
|
||||||
"PUT /api/v1/admin/limits": "platform.limits_update",
|
"PUT /api/v1/admin/limits": "platform.limits_update",
|
||||||
"POST /api/v1/admin/identity-providers": "platform.idp_create",
|
"POST /api/v1/admin/identity-providers": "platform.idp_create",
|
||||||
"PUT /api/v1/admin/identity-providers/:id": "platform.idp_update",
|
"PUT /api/v1/admin/identity-providers/:id": "platform.idp_update",
|
||||||
|
|||||||
+70
-55
@@ -19,6 +19,7 @@ import (
|
|||||||
"github.com/gin-gonic/gin"
|
"github.com/gin-gonic/gin"
|
||||||
"github.com/google/uuid"
|
"github.com/google/uuid"
|
||||||
"github.com/jackc/pgx/v5"
|
"github.com/jackc/pgx/v5"
|
||||||
|
"golang.org/x/sync/errgroup"
|
||||||
|
|
||||||
"git.zb-server.de/ZB-Server/uptimesebi/internal/auth"
|
"git.zb-server.de/ZB-Server/uptimesebi/internal/auth"
|
||||||
"git.zb-server.de/ZB-Server/uptimesebi/internal/authz"
|
"git.zb-server.de/ZB-Server/uptimesebi/internal/authz"
|
||||||
@@ -72,8 +73,10 @@ func (s *Server) dashboard(c *gin.Context) {
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
v := web.DashboardView{Counts: map[web.Status]int{}, Empty: true}
|
v := web.DashboardView{Counts: map[web.Status]int{}, Empty: true}
|
||||||
|
timer := newStepTimer()
|
||||||
if p != nil && me.Policy == "" {
|
if p != nil && me.Policy == "" {
|
||||||
data, err := s.loadMonitorData(c.Request.Context(), p, web.RangeByKey(c.Query("range")))
|
data, err := s.loadMonitorData(c.Request.Context(), p, web.RangeByKey(c.Query("range")))
|
||||||
|
timer.done("load")
|
||||||
if err != nil {
|
if err != nil {
|
||||||
internalError(c, err)
|
internalError(c, err)
|
||||||
return
|
return
|
||||||
@@ -84,21 +87,14 @@ func (s *Server) dashboard(c *gin.Context) {
|
|||||||
if !s.dashboardPage(c, &v, data) {
|
if !s.dashboardPage(c, &v, data) {
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
timer.done("arrange")
|
||||||
if err := s.dashboardBars(c.Request.Context(), p, &v, &data); err != nil {
|
if err := s.dashboardBars(c.Request.Context(), p, &v, &data); err != nil {
|
||||||
internalError(c, err)
|
internalError(c, err)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
timer.done("bars")
|
||||||
v.Range = data.rng.Key
|
v.Range = data.rng.Key
|
||||||
var earliest time.Time
|
v.Ranges = rangeOptions(c, data.rng, data.firstCreated, data.now)
|
||||||
if err := s.db.Tx(c.Request.Context(), p.scope(), func(q *store.Queries) error {
|
|
||||||
var err error
|
|
||||||
earliest, err = earliestData(c.Request.Context(), q, p.Org.ID, data.now)
|
|
||||||
return err
|
|
||||||
}); err != nil {
|
|
||||||
internalError(c, err)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
v.Ranges = rangeOptions(c, data.rng, earliest, data.now)
|
|
||||||
for _, m := range data.rows {
|
for _, m := range data.rows {
|
||||||
v.Counts[m.Status]++
|
v.Counts[m.Status]++
|
||||||
if m.Unchecked {
|
if m.Unchecked {
|
||||||
@@ -111,7 +107,11 @@ func (s *Server) dashboard(c *gin.Context) {
|
|||||||
}
|
}
|
||||||
slices.SortFunc(v.DeadRegions, func(a, b web.DeadRegion) int { return strings.Compare(a.Name, b.Name) })
|
slices.SortFunc(v.DeadRegions, func(a, b web.DeadRegion) int { return strings.Compare(a.Name, b.Name) })
|
||||||
}
|
}
|
||||||
|
timer.done("rest")
|
||||||
|
timer.header(c)
|
||||||
web.Render(c, http.StatusOK, web.Dashboard(s.pageFor(c, "console.monitors.title"), me, v))
|
web.Render(c, http.StatusOK, web.Dashboard(s.pageFor(c, "console.monitors.title"), me, v))
|
||||||
|
timer.done("render")
|
||||||
|
timer.logIfSlow(c, s.log)
|
||||||
}
|
}
|
||||||
|
|
||||||
// dashboardBars loads the bars of the monitors v shows, and only those.
|
// dashboardBars loads the bars of the monitors v shows, and only those.
|
||||||
@@ -218,13 +218,28 @@ func (o monitorSort) key(m web.MonitorRow) cursor {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (o monitorSort) sort(ms []web.MonitorRow) {
|
func (o monitorSort) sort(ms []web.MonitorRow) {
|
||||||
slices.SortFunc(ms, func(a, b web.MonitorRow) int {
|
// Keys are worked out once per row, not per comparison, and the rows
|
||||||
ka, kb := o.key(a), o.key(b)
|
// moved once: with thousands of monitors sorting was a good part of
|
||||||
if c := strings.Compare(ka.S, kb.S); c != 0 {
|
// the dashboard's time.
|
||||||
|
type keyed struct {
|
||||||
|
key, id string
|
||||||
|
i int
|
||||||
|
}
|
||||||
|
keys := make([]keyed, len(ms))
|
||||||
|
for i, m := range ms {
|
||||||
|
keys[i] = keyed{o.key(m).S, m.ID, i}
|
||||||
|
}
|
||||||
|
slices.SortFunc(keys, func(a, b keyed) int {
|
||||||
|
if c := strings.Compare(a.key, b.key); c != 0 {
|
||||||
return c
|
return c
|
||||||
}
|
}
|
||||||
return strings.Compare(a.ID, b.ID)
|
return strings.Compare(a.id, b.id)
|
||||||
})
|
})
|
||||||
|
sorted := make([]web.MonitorRow, len(ms))
|
||||||
|
for i, k := range keys {
|
||||||
|
sorted[i] = ms[k.i]
|
||||||
|
}
|
||||||
|
copy(ms, sorted)
|
||||||
}
|
}
|
||||||
|
|
||||||
// dashboardStatuses are the statuses the dashboard counts, in order.
|
// dashboardStatuses are the statuses the dashboard counts, in order.
|
||||||
@@ -379,6 +394,11 @@ type monitorData struct {
|
|||||||
regionOf map[uuid.UUID]store.Region
|
regionOf map[uuid.UUID]store.Region
|
||||||
rng web.TimeRange
|
rng web.TimeRange
|
||||||
now time.Time
|
now time.Time
|
||||||
|
// firstCreated is when the oldest monitor was created: the monitor
|
||||||
|
// list offers no ranges reaching far before it. (Finding the first
|
||||||
|
// result instead read results of every monitor, slow for large
|
||||||
|
// organizations.)
|
||||||
|
firstCreated time.Time
|
||||||
// first is when the monitor of a detail page first reported, from
|
// first is when the monitor of a detail page first reported, from
|
||||||
// any region; firstRegion the same per region.
|
// any region; firstRegion the same per region.
|
||||||
first time.Time
|
first time.Time
|
||||||
@@ -423,25 +443,6 @@ func loadFirstData(ctx context.Context, q *store.Queries, org, monitor uuid.UUID
|
|||||||
return first, perRegion, nil
|
return first, perRegion, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// earliestData finds when any monitor of org first reported, for the
|
|
||||||
// ranges the monitor list offers: to the day if that was over two days
|
|
||||||
// ago, otherwise exactly.
|
|
||||||
func earliestData(ctx context.Context, q *store.Queries, org uuid.UUID, now time.Time) (time.Time, error) {
|
|
||||||
none := func(t time.Time, err error) (time.Time, bool, error) {
|
|
||||||
if errors.Is(err, pgx.ErrNoRows) {
|
|
||||||
return time.Time{}, false, nil
|
|
||||||
}
|
|
||||||
return t, err == nil, err
|
|
||||||
}
|
|
||||||
recentSince := now.Add(-2 * 24 * time.Hour)
|
|
||||||
daily, ok, err := none(q.EarliestDataDaily(ctx, org))
|
|
||||||
if err != nil || (ok && daily.Before(recentSince)) {
|
|
||||||
return daily, err
|
|
||||||
}
|
|
||||||
exact, _, err := none(q.EarliestDataRecent(ctx, store.EarliestDataRecentParams{OrgID: org, Time: recentSince}))
|
|
||||||
return exact, err
|
|
||||||
}
|
|
||||||
|
|
||||||
// rangeBuckets loads the selected range for the monitors ids.
|
// rangeBuckets loads the selected range for the monitors ids.
|
||||||
func rangeBuckets(ctx context.Context, q *store.Queries, org uuid.UUID, ids []uuid.UUID, rng web.TimeRange, now time.Time) (map[uuid.UUID][]web.Bucket, error) {
|
func rangeBuckets(ctx context.Context, q *store.Queries, org uuid.UUID, ids []uuid.UUID, rng web.TimeRange, now time.Time) (map[uuid.UUID][]web.Bucket, error) {
|
||||||
out := map[uuid.UUID][]web.Bucket{}
|
out := map[uuid.UUID][]web.Bucket{}
|
||||||
@@ -498,39 +499,50 @@ func (s *Server) loadMonitorData(ctx context.Context, p *principal, rng web.Time
|
|||||||
spans []store.IncidentsSinceRow
|
spans []store.IncidentsSinceRow
|
||||||
)
|
)
|
||||||
var groups []store.MonitorGroup
|
var groups []store.MonitorGroup
|
||||||
err := s.db.Tx(ctx, p.scope(), func(q *store.Queries) error {
|
// The queries run in parallel: for large organizations each takes a
|
||||||
|
// while, mostly to move its rows.
|
||||||
|
g, gctx := errgroup.WithContext(ctx)
|
||||||
|
tx := func(f func(q *store.Queries) error) {
|
||||||
|
g.Go(func() error { return s.db.Tx(gctx, p.scope(), f) })
|
||||||
|
}
|
||||||
|
tx(func(q *store.Queries) error {
|
||||||
var err error
|
var err error
|
||||||
if groups, err = q.ListGroups(ctx); err != nil {
|
if groups, err = q.ListGroups(gctx); err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
if monitors, err = q.ListMonitors(ctx, p.Org.ID); err != nil {
|
if monitors, err = q.ListMonitors(gctx, p.Org.ID); err != nil {
|
||||||
return err
|
|
||||||
}
|
|
||||||
if assigned, err = q.AllMonitorRegions(ctx, p.Org.ID); err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
if regions, err = q.ListVisibleRegions(ctx); err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
if latest, err = q.LatestResults(ctx, p.Org.ID); err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
if open, err = q.OpenIncidents(ctx, p.Org.ID); err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
if spans, err = q.IncidentsSince(ctx, store.IncidentsSinceParams{OrgID: p.Org.ID, ResolvedAt: ptr(now.Add(-web.SLAWindows[len(web.SLAWindows)-1].Window))}); err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
if d.statuses, err = loadCustomStatuses(ctx, q); err != nil {
|
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
ids := make([]uuid.UUID, len(monitors))
|
ids := make([]uuid.UUID, len(monitors))
|
||||||
for i, m := range monitors {
|
for i, m := range monitors {
|
||||||
ids[i] = m.ID
|
ids[i] = m.ID
|
||||||
}
|
}
|
||||||
d.maint, err = maintenanceFor(ctx, q, ids)
|
d.maint, err = maintenanceFor(gctx, q, ids)
|
||||||
return err
|
return err
|
||||||
})
|
})
|
||||||
|
tx(func(q *store.Queries) (err error) {
|
||||||
|
assigned, err = q.AllMonitorRegions(gctx, p.Org.ID)
|
||||||
|
return err
|
||||||
|
})
|
||||||
|
tx(func(q *store.Queries) (err error) {
|
||||||
|
latest, err = q.LatestResults(gctx, p.Org.ID)
|
||||||
|
return err
|
||||||
|
})
|
||||||
|
tx(func(q *store.Queries) error {
|
||||||
|
var err error
|
||||||
|
if regions, err = q.ListVisibleRegions(gctx); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if open, err = q.OpenIncidents(gctx, p.Org.ID); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if spans, err = q.IncidentsSince(gctx, store.IncidentsSinceParams{OrgID: p.Org.ID, ResolvedAt: ptr(now.Add(-web.SLAWindows[len(web.SLAWindows)-1].Window))}); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
d.statuses, err = loadCustomStatuses(gctx, q)
|
||||||
|
return err
|
||||||
|
})
|
||||||
|
err := g.Wait()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return d, err
|
return d, err
|
||||||
}
|
}
|
||||||
@@ -553,6 +565,9 @@ func (s *Server) loadMonitorData(ctx context.Context, p *principal, rng web.Time
|
|||||||
if m.Enabled {
|
if m.Enabled {
|
||||||
d.usedRegions = append(d.usedRegions, regionsOf[m.ID]...)
|
d.usedRegions = append(d.usedRegions, regionsOf[m.ID]...)
|
||||||
}
|
}
|
||||||
|
if d.firstCreated.IsZero() || m.CreatedAt.Before(d.firstCreated) {
|
||||||
|
d.firstCreated = m.CreatedAt
|
||||||
|
}
|
||||||
}
|
}
|
||||||
slices.SortFunc(d.usedRegions, func(a, b uuid.UUID) int { return strings.Compare(a.String(), b.String()) })
|
slices.SortFunc(d.usedRegions, func(a, b uuid.UUID) int { return strings.Compare(a.String(), b.String()) })
|
||||||
d.usedRegions = slices.Compact(d.usedRegions)
|
d.usedRegions = slices.Compact(d.usedRegions)
|
||||||
|
|||||||
@@ -224,7 +224,11 @@ func (s *Server) listMonitors(c *gin.Context) {
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
latest, err := q.LatestResults(ctx, p.Org.ID)
|
ids := make([]uuid.UUID, len(monitors))
|
||||||
|
for i, m := range monitors {
|
||||||
|
ids[i] = m.ID
|
||||||
|
}
|
||||||
|
latest, err := q.LatestResultsForMonitors(ctx, store.LatestResultsForMonitorsParams{OrgID: p.Org.ID, Ids: ids})
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -625,7 +625,7 @@ func (s *Server) adminPage(c *gin.Context) {
|
|||||||
for _, t := range check.Types {
|
for _, t := range check.Types {
|
||||||
types = append(types, web.CheckTypeOption{Type: string(t), Enabled: !off[string(t)]})
|
types = append(types, web.CheckTypeOption{Type: string(t), Enabled: !off[string(t)]})
|
||||||
}
|
}
|
||||||
web.Render(c, http.StatusOK, web.AdminPage(s.pageFor(c, "admin.title"), me, v, storageView(c, stats), types, s.platformPrivate(ctx), webLimits(s.platformLimits(ctx)), s.idpAdminView(ctx)))
|
web.Render(c, http.StatusOK, web.AdminPage(s.pageFor(c, "admin.title"), me, v, storageView(c, stats), types, s.platformPrivate(ctx), s.statusPageHome(ctx), webLimits(s.platformLimits(ctx)), s.idpAdminView(ctx)))
|
||||||
}
|
}
|
||||||
|
|
||||||
func (s *Server) adminStatusPagesPage(c *gin.Context) {
|
func (s *Server) adminStatusPagesPage(c *gin.Context) {
|
||||||
|
|||||||
@@ -8,6 +8,7 @@ import (
|
|||||||
"time"
|
"time"
|
||||||
|
|
||||||
"github.com/google/uuid"
|
"github.com/google/uuid"
|
||||||
|
"github.com/jackc/pgx/v5"
|
||||||
)
|
)
|
||||||
|
|
||||||
func TestTimeRangesAndSLA(t *testing.T) {
|
func TestTimeRangesAndSLA(t *testing.T) {
|
||||||
@@ -53,7 +54,7 @@ func TestTimeRangesAndSLA(t *testing.T) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
bars := map[string]int{"1h": 60, "3h": 36, "12h": 48, "24h": 48, "7d": 42, "30d": 60, "90d": 45, "180d": 45, "1y": 52}
|
bars := map[string]int{"1h": 60, "3h": 36, "12h": 48, "24h": 24, "7d": 42, "30d": 60, "90d": 45, "180d": 45, "1y": 52}
|
||||||
for key, n := range bars {
|
for key, n := range bars {
|
||||||
st, _, html := owner.page("/?range=" + key)
|
st, _, html := owner.page("/?range=" + key)
|
||||||
if st != http.StatusOK {
|
if st != http.StatusOK {
|
||||||
@@ -99,9 +100,16 @@ func TestRangeAvailabilityAndRegions(t *testing.T) {
|
|||||||
id := uuid.MustParse(body["id"].(string))
|
id := uuid.MustParse(body["id"].(string))
|
||||||
org := uuid.MustParse(owner.orgID())
|
org := uuid.MustParse(owner.orgID())
|
||||||
|
|
||||||
// Two hours of results: eu always fine, us always failing.
|
// Two hours of results: eu always fine, us always failing. (The
|
||||||
|
// monitor is as old as its results.)
|
||||||
ctx := context.Background()
|
ctx := context.Background()
|
||||||
now := time.Now()
|
now := time.Now()
|
||||||
|
if err := e.asSystem(t, func(tx pgx.Tx) error {
|
||||||
|
_, err := tx.Exec(ctx, `UPDATE monitors SET created_at = $1 WHERE id = $2`, now.Add(-121*time.Minute), id)
|
||||||
|
return err
|
||||||
|
}); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
checker := uuid.New()
|
checker := uuid.New()
|
||||||
for m := 0; m <= 120; m += 5 {
|
for m := 0; m <= 120; m += 5 {
|
||||||
at := now.Add(-time.Duration(m) * time.Minute)
|
at := now.Add(-time.Duration(m) * time.Minute)
|
||||||
|
|||||||
@@ -56,6 +56,8 @@ type Server struct {
|
|||||||
limits *versioned[Limits]
|
limits *versioned[Limits]
|
||||||
// support caches how the platform runs support tickets.
|
// support caches how the platform runs support tickets.
|
||||||
support *versioned[supportSettings]
|
support *versioned[supportSettings]
|
||||||
|
// pageHome caches the home page the status page servers link.
|
||||||
|
pageHome *versioned[string]
|
||||||
// draining, once closed, ends the long polls of checkers.
|
// draining, once closed, ends the long polls of checkers.
|
||||||
draining <-chan struct{}
|
draining <-chan struct{}
|
||||||
// handler serves the requests agents send over their streams.
|
// handler serves the requests agents send over their streams.
|
||||||
@@ -99,6 +101,7 @@ func New(cfg config.API, d Deps) *Server {
|
|||||||
checkerNet: newVersioned[bool]("checker-network"),
|
checkerNet: newVersioned[bool]("checker-network"),
|
||||||
limits: newVersioned[Limits]("limits"),
|
limits: newVersioned[Limits]("limits"),
|
||||||
support: newVersioned[supportSettings]("support"),
|
support: newVersioned[supportSettings]("support"),
|
||||||
|
pageHome: newVersioned[string]("statuspage-home"),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -224,6 +227,8 @@ func (s *Server) Mount(r gin.IRouter) {
|
|||||||
admin.PUT("/users/:id/suspension", s.adminSuspendUser)
|
admin.PUT("/users/:id/suspension", s.adminSuspendUser)
|
||||||
admin.DELETE("/users/:id", s.adminDeleteUser)
|
admin.DELETE("/users/:id", s.adminDeleteUser)
|
||||||
admin.PUT("/checker-network", s.adminSetCheckerNetwork)
|
admin.PUT("/checker-network", s.adminSetCheckerNetwork)
|
||||||
|
admin.GET("/statuspage-home", s.adminGetStatusPageHome)
|
||||||
|
admin.PUT("/statuspage-home", s.adminSetStatusPageHome)
|
||||||
admin.GET("/legal", s.adminListLegal)
|
admin.GET("/legal", s.adminListLegal)
|
||||||
admin.PUT("/legal/:kind", s.adminSaveLegal)
|
admin.PUT("/legal/:kind", s.adminSaveLegal)
|
||||||
admin.GET("/regions", s.adminListRegions)
|
admin.GET("/regions", s.adminListRegions)
|
||||||
|
|||||||
@@ -256,7 +256,7 @@ func (s *Server) importStatusPageGroups(c *gin.Context) {
|
|||||||
pageID := uuid.MustParse(c.Param("id"))
|
pageID := uuid.MustParse(c.Param("id"))
|
||||||
p := current(c)
|
p := current(c)
|
||||||
ctx := c.Request.Context()
|
ctx := c.Request.Context()
|
||||||
var created []store.StatusPageGroup
|
var created []pageGroupView
|
||||||
err := s.db.Tx(ctx, p.scope(), func(q *store.Queries) error {
|
err := s.db.Tx(ctx, p.scope(), func(q *store.Queries) error {
|
||||||
if _, err := q.GetStatusPage(ctx, pageID); err != nil {
|
if _, err := q.GetStatusPage(ctx, pageID); err != nil {
|
||||||
return err
|
return err
|
||||||
@@ -290,54 +290,66 @@ func (s *Server) importStatusPageGroups(c *gin.Context) {
|
|||||||
if err := q.ClearStatusPageGroups(ctx, pageID); err != nil {
|
if err := q.ClearStatusPageGroups(ctx, pageID); err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
mapped := map[uuid.UUID]store.StatusPageGroup{}
|
// Large organizations have thousands of monitors and hundreds of
|
||||||
var createErr error
|
// 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{}
|
posByParent := map[uuid.UUID]int32{}
|
||||||
tree.walk(func(g store.MonitorGroup, _ int) {
|
tree.walk(func(g store.MonitorGroup, depth int) {
|
||||||
if createErr != nil || !needed[g.ID] {
|
if !needed[g.ID] {
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
var parentKey uuid.UUID
|
|
||||||
var parentID *uuid.UUID
|
var parentID *uuid.UUID
|
||||||
if g.ParentID != nil {
|
if g.ParentID != nil {
|
||||||
if parent, ok := mapped[*g.ParentID]; ok {
|
if parent, ok := mapped[*g.ParentID]; ok {
|
||||||
pid := parent.ID
|
pid := parent.ID
|
||||||
parentID = &pid
|
parentID = &pid
|
||||||
parentKey = pid
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
var parentKey uuid.UUID
|
||||||
|
if parentID != nil {
|
||||||
|
parentKey = *parentID
|
||||||
|
}
|
||||||
pos := posByParent[parentKey]
|
pos := posByParent[parentKey]
|
||||||
posByParent[parentKey] = pos + 1
|
posByParent[parentKey] = pos + 1
|
||||||
row, err := q.CreateStatusPageGroup(ctx, store.CreateStatusPageGroupParams{
|
row := pageGroupView{ID: uuid.New(), Name: g.Name, ParentID: parentID, Position: pos}
|
||||||
PageID: pageID,
|
|
||||||
OrgID: p.Org.ID,
|
|
||||||
ParentID: parentID,
|
|
||||||
Name: g.Name,
|
|
||||||
Position: pos,
|
|
||||||
})
|
|
||||||
if err != nil {
|
|
||||||
createErr = err
|
|
||||||
return
|
|
||||||
}
|
|
||||||
mapped[g.ID] = row
|
mapped[g.ID] = row
|
||||||
created = append(created, row)
|
created = append(created, row)
|
||||||
})
|
for len(levels) <= depth {
|
||||||
if createErr != nil {
|
levels = append(levels, store.CreateStatusPageGroupsParams{PageID: pageID, OrgID: p.Org.ID})
|
||||||
return createErr
|
|
||||||
}
|
}
|
||||||
|
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)
|
||||||
|
})
|
||||||
|
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 {
|
for _, m := range listed {
|
||||||
var gid *uuid.UUID
|
var gid uuid.UUID
|
||||||
section := ""
|
section := ""
|
||||||
if m.MonitorGroupID != nil {
|
if m.MonitorGroupID != nil {
|
||||||
if g, ok := mapped[*m.MonitorGroupID]; ok {
|
if g, ok := mapped[*m.MonitorGroupID]; ok {
|
||||||
id := g.ID
|
gid = g.ID
|
||||||
gid = &id
|
|
||||||
section = g.Name
|
section = g.Name
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if err := q.SetStatusPageMonitorGroup(ctx, store.SetStatusPageMonitorGroupParams{
|
set.MonitorIds = append(set.MonitorIds, m.MonitorID)
|
||||||
PageID: pageID, MonitorID: m.MonitorID, GroupID: gid, Section: section,
|
set.GroupIds = append(set.GroupIds, gid)
|
||||||
}); err != nil {
|
set.Sections = append(set.Sections, section)
|
||||||
|
}
|
||||||
|
if len(set.MonitorIds) > 0 {
|
||||||
|
if err := q.SetStatusPageMonitorGroups(ctx, set); err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -351,11 +363,10 @@ func (s *Server) importStatusPageGroups(c *gin.Context) {
|
|||||||
internalError(c, err)
|
internalError(c, err)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
out := make([]pageGroupView, 0, len(created))
|
if created == nil {
|
||||||
for _, g := range created {
|
created = []pageGroupView{}
|
||||||
out = append(out, pageGroupView{ID: g.ID, Name: g.Name, ParentID: g.ParentID, Position: g.Position})
|
|
||||||
}
|
}
|
||||||
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
|
// 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 {
|
for i, r := range rows {
|
||||||
out[i] = agentapi.PageRef{Slug: r.Slug, Host: r.Host}
|
out[i] = agentapi.PageRef{Slug: r.Slug, Host: r.Host}
|
||||||
}
|
}
|
||||||
c.JSON(http.StatusOK, gin.H{"pages": out})
|
c.JSON(http.StatusOK, agentapi.PageIndex{Pages: out, HomeURL: s.statusPageHome(ctx)})
|
||||||
}
|
}
|
||||||
|
|
||||||
type statusPageRequest struct {
|
type statusPageRequest struct {
|
||||||
|
|||||||
@@ -205,7 +205,8 @@ func TestStatusPages(t *testing.T) {
|
|||||||
own := e.statuspageClient(t, &org)
|
own := e.statuspageClient(t, &org)
|
||||||
lists := func(c *agentapi.Client) bool {
|
lists := func(c *agentapi.Client) bool {
|
||||||
t.Helper()
|
t.Helper()
|
||||||
refs, err := c.Pages(context.Background())
|
index, err := c.Pages(context.Background())
|
||||||
|
refs := index.Pages
|
||||||
if err != nil {
|
if err != nil {
|
||||||
t.Fatal(err)
|
t.Fatal(err)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -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...)
|
||||||
|
}
|
||||||
@@ -1261,6 +1261,11 @@
|
|||||||
"page.status.outage": "Größere Störung",
|
"page.status.outage": "Größere Störung",
|
||||||
"page.status.unknown": "Status derzeit nicht verfügbar",
|
"page.status.unknown": "Status derzeit nicht verfügbar",
|
||||||
"page.today": "Heute",
|
"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.updated": "Aktualisiert {{.Time}}",
|
"page.updated": "Aktualisiert {{.Time}}",
|
||||||
"pager.earlier": "Frühere",
|
"pager.earlier": "Frühere",
|
||||||
"pager.first": "Zum Anfang",
|
"pager.first": "Zum Anfang",
|
||||||
@@ -1310,6 +1315,7 @@
|
|||||||
"pages.monitors_filter": "Monitore filtern",
|
"pages.monitors_filter": "Monitore filtern",
|
||||||
"pages.monitors_all": "Alle hinzufügen",
|
"pages.monitors_all": "Alle hinzufügen",
|
||||||
"pages.monitors_none": "Alle entfernen",
|
"pages.monitors_none": "Alle entfernen",
|
||||||
|
"pages.monitors_range": "{from}–{to} von {total}",
|
||||||
"pages.no_group": "Ohne Gruppe",
|
"pages.no_group": "Ohne Gruppe",
|
||||||
"pages.open": "Öffnen",
|
"pages.open": "Öffnen",
|
||||||
"pages.own_servers": "Die Statusseiten dieser Organisation liefern nur ihre eigenen Statusseiten-Server aus, nicht die der Plattform. Ruf sie über die Adresse deiner Server auf oder verbinde eine eigene Domain, die auf sie zeigt.",
|
"pages.own_servers": "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.",
|
||||||
@@ -1612,5 +1618,12 @@
|
|||||||
"pages.subscribers_limit": "Neue Abos pro Woche für die Organisation: {{.Max}}",
|
"pages.subscribers_limit": "Neue Abos pro Woche für die Organisation: {{.Max}}",
|
||||||
"pages.feeds": "Feed und API",
|
"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:",
|
"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"
|
||||||
}
|
}
|
||||||
@@ -1261,6 +1261,11 @@
|
|||||||
"page.status.outage": "Major outage",
|
"page.status.outage": "Major outage",
|
||||||
"page.status.unknown": "Status currently unavailable",
|
"page.status.unknown": "Status currently unavailable",
|
||||||
"page.today": "Today",
|
"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.updated": "Updated {{.Time}}",
|
"page.updated": "Updated {{.Time}}",
|
||||||
"pager.earlier": "Earlier",
|
"pager.earlier": "Earlier",
|
||||||
"pager.first": "To the start",
|
"pager.first": "To the start",
|
||||||
@@ -1310,6 +1315,7 @@
|
|||||||
"pages.monitors_filter": "Filter monitors",
|
"pages.monitors_filter": "Filter monitors",
|
||||||
"pages.monitors_all": "Add all",
|
"pages.monitors_all": "Add all",
|
||||||
"pages.monitors_none": "Remove all",
|
"pages.monitors_none": "Remove all",
|
||||||
|
"pages.monitors_range": "{from}–{to} of {total}",
|
||||||
"pages.no_group": "No group",
|
"pages.no_group": "No group",
|
||||||
"pages.open": "Open",
|
"pages.open": "Open",
|
||||||
"pages.own_servers": "Your organization's own status page servers serve its pages; the platform's do not. Open them at the address of your servers or connect a custom domain pointing at them.",
|
"pages.own_servers": "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.",
|
||||||
@@ -1612,5 +1618,12 @@
|
|||||||
"pages.subscribers_limit": "New subscriptions per week for the organization: {{.Max}}",
|
"pages.subscribers_limit": "New subscriptions per week for the organization: {{.Max}}",
|
||||||
"pages.feeds": "Feed and API",
|
"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:",
|
"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,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")
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -21,6 +21,7 @@ import (
|
|||||||
"net/http"
|
"net/http"
|
||||||
"os"
|
"os"
|
||||||
"path/filepath"
|
"path/filepath"
|
||||||
|
"strconv"
|
||||||
"strings"
|
"strings"
|
||||||
"sync"
|
"sync"
|
||||||
"time"
|
"time"
|
||||||
@@ -63,7 +64,7 @@ type Source interface {
|
|||||||
// PageIfChanged answers agentapi.ErrNotModified when the page still
|
// PageIfChanged answers agentapi.ErrNotModified when the page still
|
||||||
// has checksum.
|
// has checksum.
|
||||||
PageIfChanged(ctx context.Context, host, slug, checksum string) (agentapi.PageSnapshot, error)
|
PageIfChanged(ctx context.Context, host, slug, checksum string) (agentapi.PageSnapshot, error)
|
||||||
Pages(ctx context.Context) ([]agentapi.PageRef, error)
|
Pages(ctx context.Context) (agentapi.PageIndex, error)
|
||||||
}
|
}
|
||||||
|
|
||||||
// Server renders pages for one status page agent.
|
// Server renders pages for one status page agent.
|
||||||
@@ -79,6 +80,8 @@ type Server struct {
|
|||||||
now func() time.Time
|
now func() time.Time
|
||||||
|
|
||||||
mu sync.Mutex
|
mu sync.Mutex
|
||||||
|
// home is the platform's home page, linked from the error page.
|
||||||
|
home string
|
||||||
cache map[string]entry
|
cache map[string]entry
|
||||||
refreshing map[string]bool
|
refreshing map[string]bool
|
||||||
// again holds pages that changed while being refreshed, which are
|
// again holds pages that changed while being refreshed, which are
|
||||||
@@ -161,9 +164,39 @@ func (s *Server) loadDisk() error {
|
|||||||
if len(s.cache) > 0 {
|
if len(s.cache) > 0 {
|
||||||
s.log.Info("loaded cached status pages", "count", len(s.cache))
|
s.log.Info("loaded cached status pages", "count", len(s.cache))
|
||||||
}
|
}
|
||||||
|
if raw, err := os.ReadFile(filepath.Join(s.dir, homeFile)); err == nil {
|
||||||
|
s.home = string(raw)
|
||||||
|
}
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// homeFile keeps the home page across restarts; not .json, which are pages.
|
||||||
|
const homeFile = "home.url"
|
||||||
|
|
||||||
|
// setHome records the home page the error page links.
|
||||||
|
func (s *Server) setHome(url string) {
|
||||||
|
s.mu.Lock()
|
||||||
|
changed := s.home != url
|
||||||
|
s.home = url
|
||||||
|
s.mu.Unlock()
|
||||||
|
if changed && s.dir != "" {
|
||||||
|
if err := os.WriteFile(filepath.Join(s.dir, homeFile), []byte(url), 0o600); err != nil {
|
||||||
|
s.log.Warn("saving the home page failed", "error", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// notFound answers visitors of a page that does not exist with a page
|
||||||
|
// leading to the platform's home page.
|
||||||
|
func (s *Server) notFound(c *gin.Context) {
|
||||||
|
s.localizeRequest(c)
|
||||||
|
s.mu.Lock()
|
||||||
|
home := s.home
|
||||||
|
s.mu.Unlock()
|
||||||
|
c.Header("Cache-Control", "no-store")
|
||||||
|
web.Render(c, http.StatusNotFound, web.PublicNotFoundPage("/static/dist/app.css", home))
|
||||||
|
}
|
||||||
|
|
||||||
func (s *Server) fileFor(key string) string {
|
func (s *Server) fileFor(key string) string {
|
||||||
sum := sha256.Sum256([]byte(key))
|
sum := sha256.Sum256([]byte(key))
|
||||||
return filepath.Join(s.dir, hex.EncodeToString(sum[:16])+".json")
|
return filepath.Join(s.dir, hex.EncodeToString(sum[:16])+".json")
|
||||||
@@ -237,7 +270,7 @@ func (s *Server) serve(c *gin.Context) {
|
|||||||
key, base = "host:"+host, "/"
|
key, base = "host:"+host, "/"
|
||||||
} else {
|
} else {
|
||||||
if len(parts) == 0 {
|
if len(parts) == 0 {
|
||||||
c.Status(http.StatusNotFound)
|
s.notFound(c)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
slug, parts = parts[0], parts[1:]
|
slug, parts = parts[0], parts[1:]
|
||||||
@@ -261,7 +294,11 @@ func (s *Server) serve(c *gin.Context) {
|
|||||||
}
|
}
|
||||||
e, ok := s.lookup(c.Request.Context(), key, host, slug)
|
e, ok := s.lookup(c.Request.Context(), key, host, slug)
|
||||||
if !ok {
|
if !ok {
|
||||||
|
if rt.kind == routeFeed || rt.kind == routeAPI {
|
||||||
c.Status(http.StatusNotFound)
|
c.Status(http.StatusNotFound)
|
||||||
|
} else {
|
||||||
|
s.notFound(c)
|
||||||
|
}
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
if rt.kind == routeLegal {
|
if rt.kind == routeLegal {
|
||||||
@@ -295,9 +332,23 @@ func (s *Server) serve(c *gin.Context) {
|
|||||||
}
|
}
|
||||||
s.localizeRequest(c)
|
s.localizeRequest(c)
|
||||||
c.Header("Cache-Control", "public, max-age=30")
|
c.Header("Cache-Control", "public, max-age=30")
|
||||||
|
assets.PageSize = componentsPerPage
|
||||||
|
if n, err := strconv.Atoi(c.Query("page")); err == nil && n > 1 {
|
||||||
|
assets.Page = n - 1
|
||||||
|
}
|
||||||
|
if q := c.Query("q"); len(q) <= maxComponentQuery {
|
||||||
|
assets.Query = q
|
||||||
|
}
|
||||||
web.Render(c, http.StatusOK, web.PublicStatusPage(e.Snap.WithMaintenance(s.now()), assets))
|
web.Render(c, http.StatusOK, web.PublicStatusPage(e.Snap.WithMaintenance(s.now()), assets))
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// componentsPerPage is how many components a status page lists at a time;
|
||||||
|
// organizations put thousands on one.
|
||||||
|
const componentsPerPage = 50
|
||||||
|
|
||||||
|
// maxComponentQuery bounds the search for components.
|
||||||
|
const maxComponentQuery = 100
|
||||||
|
|
||||||
// serveComponent renders one component's public detail page from the cached
|
// serveComponent renders one component's public detail page from the cached
|
||||||
// snapshot when the status page has enabled ShowDetails.
|
// snapshot when the status page has enabled ShowDetails.
|
||||||
func (s *Server) serveComponent(c *gin.Context, e entry, compID string, assets web.PublicAssets) {
|
func (s *Server) serveComponent(c *gin.Context, e entry, compID string, assets web.PublicAssets) {
|
||||||
@@ -523,11 +574,13 @@ func (s *Server) Run(ctx context.Context) {
|
|||||||
func (s *Server) Sync(ctx context.Context) {
|
func (s *Server) Sync(ctx context.Context) {
|
||||||
ctx, cancel := context.WithTimeout(ctx, syncInterval)
|
ctx, cancel := context.WithTimeout(ctx, syncInterval)
|
||||||
defer cancel()
|
defer cancel()
|
||||||
refs, err := s.src.Pages(ctx)
|
index, err := s.src.Pages(ctx)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
s.log.WarnContext(ctx, "listing status pages failed", "error", err)
|
s.log.WarnContext(ctx, "listing status pages failed", "error", err)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
s.setHome(index.HomeURL)
|
||||||
|
refs := index.Pages
|
||||||
todo := map[string]entry{}
|
todo := map[string]entry{}
|
||||||
s.mu.Lock()
|
s.mu.Lock()
|
||||||
for key, e := range s.cache {
|
for key, e := range s.cache {
|
||||||
|
|||||||
@@ -3,6 +3,7 @@ package statuspage
|
|||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
"errors"
|
"errors"
|
||||||
|
"fmt"
|
||||||
"log/slog"
|
"log/slog"
|
||||||
"net/http"
|
"net/http"
|
||||||
"net/http/httptest"
|
"net/http/httptest"
|
||||||
@@ -25,6 +26,7 @@ type fakeSource struct {
|
|||||||
err error
|
err error
|
||||||
delay time.Duration
|
delay time.Duration
|
||||||
pages map[string]agentapi.PageSnapshot
|
pages map[string]agentapi.PageSnapshot
|
||||||
|
home string
|
||||||
}
|
}
|
||||||
|
|
||||||
// PageIfChanged counts calls and answers like the API, sending pages
|
// PageIfChanged counts calls and answers like the API, sending pages
|
||||||
@@ -65,16 +67,16 @@ func (f *fakeSource) page(ctx context.Context, host, slug string) (agentapi.Page
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Pages lists the fake's pages by their keys: "host|" or "|slug".
|
// Pages lists the fake's pages by their keys: "host|" or "|slug".
|
||||||
func (f *fakeSource) Pages(context.Context) ([]agentapi.PageRef, error) {
|
func (f *fakeSource) Pages(context.Context) (agentapi.PageIndex, error) {
|
||||||
f.mu.Lock()
|
f.mu.Lock()
|
||||||
defer f.mu.Unlock()
|
defer f.mu.Unlock()
|
||||||
if f.err != nil {
|
if f.err != nil {
|
||||||
return nil, f.err
|
return agentapi.PageIndex{}, f.err
|
||||||
}
|
}
|
||||||
var out []agentapi.PageRef
|
out := agentapi.PageIndex{HomeURL: f.home}
|
||||||
for k := range f.pages {
|
for k := range f.pages {
|
||||||
host, slug, _ := strings.Cut(k, "|")
|
host, slug, _ := strings.Cut(k, "|")
|
||||||
out = append(out, agentapi.PageRef{Host: host, Slug: slug})
|
out.Pages = append(out.Pages, agentapi.PageRef{Host: host, Slug: slug})
|
||||||
}
|
}
|
||||||
return out, nil
|
return out, nil
|
||||||
}
|
}
|
||||||
@@ -128,6 +130,26 @@ func (h harness) get(host, path string) (int, string) {
|
|||||||
return w.Code, w.Body.String()
|
return w.Code, w.Body.String()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// The error page links the platform's home page, also after a restart
|
||||||
|
// while the API is down.
|
||||||
|
func TestNotFoundLinksHome(t *testing.T) {
|
||||||
|
dir := t.TempDir()
|
||||||
|
now := time.Now()
|
||||||
|
src := newSource()
|
||||||
|
h := newHarness(t, src, dir, &now)
|
||||||
|
if code, body := h.get("status.example.test", "/"); code != 404 || strings.Contains(body, "Zur Hauptseite") {
|
||||||
|
t.Errorf("error page without a home page = %d, links one: %t", code, strings.Contains(body, "Zur Hauptseite"))
|
||||||
|
}
|
||||||
|
src.home = "https://example.test/"
|
||||||
|
h.srv.Sync(context.Background())
|
||||||
|
restarted := newHarness(t, &fakeSource{err: errors.New("connection refused")}, dir, &now)
|
||||||
|
for _, hs := range []harness{h, restarted} {
|
||||||
|
if code, body := hs.get("status.example.test", "/gone"); code != 404 || !strings.Contains(body, `href="https://example.test/"`) {
|
||||||
|
t.Errorf("error page = %d, lacks the link to the home page", code)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
func TestRouting(t *testing.T) {
|
func TestRouting(t *testing.T) {
|
||||||
now := time.Now()
|
now := time.Now()
|
||||||
h := newHarness(t, newSource(), t.TempDir(), &now)
|
h := newHarness(t, newSource(), t.TempDir(), &now)
|
||||||
@@ -138,8 +160,8 @@ func TestRouting(t *testing.T) {
|
|||||||
}{
|
}{
|
||||||
{"status.example.test", "/acme", 200, "Acme status"},
|
{"status.example.test", "/acme", 200, "Acme status"},
|
||||||
{"status.example.test:8082", "/acme", 200, "Alle Systeme funktionieren"},
|
{"status.example.test:8082", "/acme", 200, "Alle Systeme funktionieren"},
|
||||||
{"status.example.test", "/missing", 404, ""},
|
{"status.example.test", "/missing", 404, "Seite nicht gefunden"},
|
||||||
{"status.example.test", "/", 404, ""},
|
{"status.example.test", "/", 404, "Seite nicht gefunden"},
|
||||||
{"status.acme.test", "/", 200, "Acme on own domain"},
|
{"status.acme.test", "/", 200, "Acme on own domain"},
|
||||||
{"status.acme.test", "/acme", 404, ""},
|
{"status.acme.test", "/acme", 404, ""},
|
||||||
{"other.test", "/", 404, ""},
|
{"other.test", "/", 404, ""},
|
||||||
@@ -587,3 +609,57 @@ func TestEventsRefreshPagesAtOnce(t *testing.T) {
|
|||||||
t.Errorf("fetches = %d, want 2: one for the event, one for the change during it", calls)
|
t.Errorf("fetches = %d, want 2: one for the event, one for the change during it", calls)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Pages with many components list them a page at a time and let visitors
|
||||||
|
// search them.
|
||||||
|
func TestComponentPagingAndSearch(t *testing.T) {
|
||||||
|
core := agentapi.Section{Name: "Core"}
|
||||||
|
for i := 0; i < 120; i++ {
|
||||||
|
core.Components = append(core.Components, agentapi.Component{ID: fmt.Sprintf("c%03d", i), Name: fmt.Sprintf("web-%03d", i), Status: agentapi.PageOperational, Days: []agentapi.Day{{Date: "2026-11-26", Uptime: 1}}})
|
||||||
|
}
|
||||||
|
edge := agentapi.Section{Name: "Edge"}
|
||||||
|
for i := 0; i < 10; i++ {
|
||||||
|
edge.Components = append(edge.Components, agentapi.Component{ID: fmt.Sprintf("e%d", i), Name: fmt.Sprintf("edge-%d", i), Status: agentapi.PageOperational})
|
||||||
|
}
|
||||||
|
core.Children = []agentapi.Section{edge}
|
||||||
|
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}},
|
||||||
|
}}, t.TempDir(), &now)
|
||||||
|
|
||||||
|
tests := []struct {
|
||||||
|
path string
|
||||||
|
has, hasNot []string
|
||||||
|
}{
|
||||||
|
{"/acme", []string{"web-000", "web-049", "Seite 1 von 3", `href="/acme?page=2"`, `<path d="M0 0h3v22h-3z"`}, []string{"web-050", "edge-0", `rel="prev"`, "<rect"}},
|
||||||
|
{"/acme?page=2", []string{"web-050", "web-099", "Seite 2 von 3", `href="/acme?page=3"`, `href="/acme"`}, []string{"web-049", "web-100"}},
|
||||||
|
{"/acme?page=3", []string{"web-119", "edge-9", ">Core<", ">Edge<", ">130<", "Seite 3 von 3"}, []string{"web-099", `rel="next"`}},
|
||||||
|
{"/acme?page=99", []string{"Seite 3 von 3", "edge-9"}, nil},
|
||||||
|
{"/acme?page=x", []string{"Seite 1 von 3"}, nil},
|
||||||
|
{"/acme?q=EDGE-", []string{"edge-0", "edge-9", `value="EDGE-"`, "Alle anzeigen"}, []string{"web-", "Seite 1"}},
|
||||||
|
{"/acme?q=edge", []string{"edge-0", "edge-9"}, []string{"web-"}},
|
||||||
|
{"/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")
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -124,44 +124,6 @@ func (q *Queries) DailyBucketsForMonitors(ctx context.Context, arg DailyBucketsF
|
|||||||
return items, nil
|
return items, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
const earliestDataDaily = `-- name: EarliestDataDaily :one
|
|
||||||
SELECT bucket::timestamptz AS first FROM check_results_1d WHERE org_id = $1 ORDER BY bucket LIMIT 1
|
|
||||||
`
|
|
||||||
|
|
||||||
// The day the organization's monitors first reported, if any did.
|
|
||||||
func (q *Queries) EarliestDataDaily(ctx context.Context, orgID uuid.UUID) (time.Time, error) {
|
|
||||||
row := q.db.QueryRow(ctx, earliestDataDaily, orgID)
|
|
||||||
var first time.Time
|
|
||||||
err := row.Scan(&first)
|
|
||||||
return first, err
|
|
||||||
}
|
|
||||||
|
|
||||||
const earliestDataRecent = `-- name: EarliestDataRecent :one
|
|
||||||
SELECT f.time FROM monitors m
|
|
||||||
CROSS JOIN LATERAL (
|
|
||||||
SELECT c.time FROM check_results c
|
|
||||||
WHERE c.org_id = $1 AND c.monitor_id = m.id AND c.time >= $2
|
|
||||||
ORDER BY c.time LIMIT 1
|
|
||||||
) f
|
|
||||||
WHERE m.org_id = $1
|
|
||||||
ORDER BY f.time LIMIT 1
|
|
||||||
`
|
|
||||||
|
|
||||||
type EarliestDataRecentParams struct {
|
|
||||||
OrgID uuid.UUID
|
|
||||||
Time time.Time
|
|
||||||
}
|
|
||||||
|
|
||||||
// When the organization's monitors first reported since $2, exactly: the
|
|
||||||
// first result of each monitor is found through its index, so the cost
|
|
||||||
// does not grow with the days of results.
|
|
||||||
func (q *Queries) EarliestDataRecent(ctx context.Context, arg EarliestDataRecentParams) (time.Time, error) {
|
|
||||||
row := q.db.QueryRow(ctx, earliestDataRecent, arg.OrgID, arg.Time)
|
|
||||||
var time time.Time
|
|
||||||
err := row.Scan(&time)
|
|
||||||
return time, err
|
|
||||||
}
|
|
||||||
|
|
||||||
const firstDataDaily = `-- name: FirstDataDaily :many
|
const firstDataDaily = `-- name: FirstDataDaily :many
|
||||||
SELECT monitor_id, region, min(bucket)::timestamptz AS first
|
SELECT monitor_id, region, min(bucket)::timestamptz AS first
|
||||||
FROM check_results_1d
|
FROM check_results_1d
|
||||||
|
|||||||
@@ -90,6 +90,10 @@ type Querier interface {
|
|||||||
CreateSSOProvider(ctx context.Context, arg CreateSSOProviderParams) (SsoProvider, error)
|
CreateSSOProvider(ctx context.Context, arg CreateSSOProviderParams) (SsoProvider, error)
|
||||||
CreateStatusPage(ctx context.Context, arg CreateStatusPageParams) (StatusPage, error)
|
CreateStatusPage(ctx context.Context, arg CreateStatusPageParams) (StatusPage, error)
|
||||||
CreateStatusPageGroup(ctx context.Context, arg CreateStatusPageGroupParams) (StatusPageGroup, error)
|
CreateStatusPageGroup(ctx context.Context, arg CreateStatusPageGroupParams) (StatusPageGroup, error)
|
||||||
|
// 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)
|
CreateSupportTicket(ctx context.Context, arg CreateSupportTicketParams) (SupportTicket, error)
|
||||||
CreateUser(ctx context.Context, arg CreateUserParams) (User, error)
|
CreateUser(ctx context.Context, arg CreateUserParams) (User, error)
|
||||||
DailyBuckets(ctx context.Context, arg DailyBucketsParams) ([]DailyBucketsRow, error)
|
DailyBuckets(ctx context.Context, arg DailyBucketsParams) ([]DailyBucketsRow, error)
|
||||||
@@ -133,12 +137,6 @@ type Querier interface {
|
|||||||
// for two days, after which only the verify button tries again. A verified
|
// for two days, after which only the verify button tries again. A verified
|
||||||
// one is checked daily, hourly once its record went missing.
|
// one is checked daily, hourly once its record went missing.
|
||||||
DomainsToCheck(ctx context.Context, arg DomainsToCheckParams) ([]DomainsToCheckRow, error)
|
DomainsToCheck(ctx context.Context, arg DomainsToCheckParams) ([]DomainsToCheckRow, error)
|
||||||
// The day the organization's monitors first reported, if any did.
|
|
||||||
EarliestDataDaily(ctx context.Context, orgID uuid.UUID) (time.Time, error)
|
|
||||||
// When the organization's monitors first reported since $2, exactly: the
|
|
||||||
// first result of each monitor is found through its index, so the cost
|
|
||||||
// does not grow with the days of results.
|
|
||||||
EarliestDataRecent(ctx context.Context, arg EarliestDataRecentParams) (time.Time, error)
|
|
||||||
EmailKeyTaken(ctx context.Context, emailKey *string) (bool, error)
|
EmailKeyTaken(ctx context.Context, emailKey *string) (bool, error)
|
||||||
EnableTOTP(ctx context.Context, arg EnableTOTPParams) error
|
EnableTOTP(ctx context.Context, arg EnableTOTPParams) error
|
||||||
EnqueueNotification(ctx context.Context, arg EnqueueNotificationParams) error
|
EnqueueNotification(ctx context.Context, arg EnqueueNotificationParams) error
|
||||||
@@ -401,7 +399,9 @@ type Querier interface {
|
|||||||
SetPlatformSetting(ctx context.Context, arg SetPlatformSettingParams) error
|
SetPlatformSetting(ctx context.Context, arg SetPlatformSettingParams) error
|
||||||
// Changing the domain drops a previous verification and its checks.
|
// Changing the domain drops a previous verification and its checks.
|
||||||
SetStatusPageDomain(ctx context.Context, arg SetStatusPageDomainParams) (StatusPage, error)
|
SetStatusPageDomain(ctx context.Context, arg SetStatusPageDomainParams) (StatusPage, error)
|
||||||
SetStatusPageMonitorGroup(ctx context.Context, arg SetStatusPageMonitorGroupParams) error
|
// 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)
|
SetSupportTicketStatus(ctx context.Context, arg SetSupportTicketStatusParams) (int64, error)
|
||||||
SetUserAdmin(ctx context.Context, arg SetUserAdminParams) (int64, error)
|
SetUserAdmin(ctx context.Context, arg SetUserAdminParams) (int64, error)
|
||||||
SetUserLocale(ctx context.Context, arg SetUserLocaleParams) error
|
SetUserLocale(ctx context.Context, arg SetUserLocaleParams) error
|
||||||
|
|||||||
@@ -125,23 +125,6 @@ FROM check_results_1d
|
|||||||
WHERE org_id = $1 AND monitor_id = $2
|
WHERE org_id = $1 AND monitor_id = $2
|
||||||
GROUP BY 1, 2;
|
GROUP BY 1, 2;
|
||||||
|
|
||||||
-- name: EarliestDataDaily :one
|
|
||||||
-- The day the organization's monitors first reported, if any did.
|
|
||||||
SELECT bucket::timestamptz AS first FROM check_results_1d WHERE org_id = $1 ORDER BY bucket LIMIT 1;
|
|
||||||
|
|
||||||
-- name: EarliestDataRecent :one
|
|
||||||
-- When the organization's monitors first reported since $2, exactly: the
|
|
||||||
-- first result of each monitor is found through its index, so the cost
|
|
||||||
-- does not grow with the days of results.
|
|
||||||
SELECT f.time FROM monitors m
|
|
||||||
CROSS JOIN LATERAL (
|
|
||||||
SELECT c.time FROM check_results c
|
|
||||||
WHERE c.org_id = $1 AND c.monitor_id = m.id AND c.time >= $2
|
|
||||||
ORDER BY c.time LIMIT 1
|
|
||||||
) f
|
|
||||||
WHERE m.org_id = $1
|
|
||||||
ORDER BY f.time LIMIT 1;
|
|
||||||
|
|
||||||
-- name: FirstDataRecent :many
|
-- name: FirstDataRecent :many
|
||||||
-- When each region of a monitor first reported since $3, exactly. Used for
|
-- When each region of a monitor first reported since $3, exactly. Used for
|
||||||
-- data younger than the daily aggregate's resolution.
|
-- data younger than the daily aggregate's resolution.
|
||||||
|
|||||||
@@ -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)
|
INSERT INTO status_page_monitors (page_id, monitor_id, org_id, section, group_id, label, position)
|
||||||
VALUES ($1, $2, $3, $4, $5, $6, $7);
|
VALUES ($1, $2, $3, $4, $5, $6, $7);
|
||||||
|
|
||||||
-- name: SetStatusPageMonitorGroup :exec
|
-- name: SetStatusPageMonitorGroups :exec
|
||||||
UPDATE status_page_monitors SET group_id = $3, section = $4
|
-- Files many monitors of a page at once; a nil group id (all zeros) files
|
||||||
WHERE page_id = $1 AND monitor_id = $2;
|
-- 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
|
-- name: ListStatusPageGroups :many
|
||||||
SELECT * FROM status_page_groups
|
SELECT * FROM status_page_groups
|
||||||
|
|||||||
@@ -150,6 +150,37 @@ func (q *Queries) CreateStatusPageGroup(ctx context.Context, arg CreateStatusPag
|
|||||||
return i, err
|
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
|
const deleteStatusPage = `-- name: DeleteStatusPage :execrows
|
||||||
DELETE FROM status_pages WHERE id = $1
|
DELETE FROM status_pages WHERE id = $1
|
||||||
`
|
`
|
||||||
@@ -563,24 +594,29 @@ func (q *Queries) SetStatusPageDomain(ctx context.Context, arg SetStatusPageDoma
|
|||||||
return i, err
|
return i, err
|
||||||
}
|
}
|
||||||
|
|
||||||
const setStatusPageMonitorGroup = `-- name: SetStatusPageMonitorGroup :exec
|
const setStatusPageMonitorGroups = `-- name: SetStatusPageMonitorGroups :exec
|
||||||
UPDATE status_page_monitors SET group_id = $3, section = $4
|
UPDATE status_page_monitors spm
|
||||||
WHERE page_id = $1 AND monitor_id = $2
|
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 {
|
type SetStatusPageMonitorGroupsParams struct {
|
||||||
PageID uuid.UUID
|
PageID uuid.UUID
|
||||||
MonitorID uuid.UUID
|
MonitorIds []uuid.UUID
|
||||||
GroupID *uuid.UUID
|
GroupIds []uuid.UUID
|
||||||
Section string
|
Sections []string
|
||||||
}
|
}
|
||||||
|
|
||||||
func (q *Queries) SetStatusPageMonitorGroup(ctx context.Context, arg SetStatusPageMonitorGroupParams) error {
|
// Files many monitors of a page at once; a nil group id (all zeros) files
|
||||||
_, err := q.db.Exec(ctx, setStatusPageMonitorGroup,
|
// a monitor under none.
|
||||||
|
func (q *Queries) SetStatusPageMonitorGroups(ctx context.Context, arg SetStatusPageMonitorGroupsParams) error {
|
||||||
|
_, err := q.db.Exec(ctx, setStatusPageMonitorGroups,
|
||||||
arg.PageID,
|
arg.PageID,
|
||||||
arg.MonitorID,
|
arg.MonitorIds,
|
||||||
arg.GroupID,
|
arg.GroupIds,
|
||||||
arg.Section,
|
arg.Sections,
|
||||||
)
|
)
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -241,7 +241,7 @@
|
|||||||
if (checkAll) {
|
if (checkAll) {
|
||||||
const on = checkAll.dataset.checkAll === "on";
|
const on = checkAll.dataset.checkAll === "on";
|
||||||
checkAll.closest("form")?.querySelectorAll(checkAll.dataset.checkTarget).forEach((box) => {
|
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;
|
box.checked = on;
|
||||||
if (on) addRowFields(box);
|
if (on) addRowFields(box);
|
||||||
});
|
});
|
||||||
@@ -341,15 +341,72 @@
|
|||||||
if (ev.target.matches('[data-row] [data-field="include"]') && ev.target.checked) addRowFields(ev.target);
|
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
|
// Lists with data-page-size show that many of their rows at a time, of
|
||||||
// not contain what is typed.
|
// 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) => {
|
document.addEventListener("input", (ev) => {
|
||||||
const input = ev.target.closest("[data-filter-rows]");
|
const input = ev.target.closest("[data-filter-rows]");
|
||||||
if (!input) return;
|
if (!input) return;
|
||||||
const needle = input.value.trim().toLowerCase();
|
const needle = input.value.trim().toLowerCase();
|
||||||
for (const row of document.querySelectorAll(input.dataset.filterRows + " > [data-row]")) {
|
const list = document.querySelector(input.dataset.filterRows);
|
||||||
row.hidden = needle !== "" && !row.textContent.toLowerCase().includes(needle);
|
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.
|
// Only the settings of the selected check type are shown and submitted.
|
||||||
|
|||||||
@@ -192,6 +192,28 @@ templ bars(bs []Bar, height int) {
|
|||||||
</svg>
|
</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) {
|
templ Dashboard(p Page, me Me, v DashboardView) {
|
||||||
@consoleShell(p, me) {
|
@consoleShell(p, me) {
|
||||||
<div class="mb-6 flex flex-wrap items-center justify-between gap-x-4 gap-y-3">
|
<div class="mb-6 flex flex-wrap items-center justify-between gap-x-4 gap-y-3">
|
||||||
|
|||||||
+2876
-2749
File diff suppressed because it is too large.
Load diff
@@ -3,6 +3,7 @@ package web
|
|||||||
import (
|
import (
|
||||||
"fmt"
|
"fmt"
|
||||||
"io/fs"
|
"io/fs"
|
||||||
|
"net/url"
|
||||||
"strconv"
|
"strconv"
|
||||||
"strings"
|
"strings"
|
||||||
"time"
|
"time"
|
||||||
@@ -30,6 +31,156 @@ type PublicAssets struct {
|
|||||||
Now time.Time
|
Now time.Time
|
||||||
// NoRefresh leaves out the periodic reload, on pages with a form.
|
// NoRefresh leaves out the periodic reload, on pages with a form.
|
||||||
NoRefresh bool
|
NoRefresh bool
|
||||||
|
// PageSize is how many components the page lists at a time; 0 lists
|
||||||
|
// all, as in a single-file export.
|
||||||
|
PageSize int
|
||||||
|
// Page is the zero-based page of components to show and Query what the
|
||||||
|
// visitor searched them for.
|
||||||
|
Page int
|
||||||
|
Query string
|
||||||
|
}
|
||||||
|
|
||||||
|
// ComponentPage is the part of a status page's components one page of it
|
||||||
|
// lists: the sections holding them, keeping the status and count of the
|
||||||
|
// whole section.
|
||||||
|
type ComponentPage struct {
|
||||||
|
Sections []agentapi.Section
|
||||||
|
// Page is the zero-based page shown, of Pages; Matches counts the
|
||||||
|
// components the query found, of all of them.
|
||||||
|
Page, Pages int
|
||||||
|
Matches int
|
||||||
|
Query string
|
||||||
|
}
|
||||||
|
|
||||||
|
// PageComponents picks the components of page from sections, of those whose
|
||||||
|
// name or section contains query. size 0 shows all of them.
|
||||||
|
func PageComponents(sections []agentapi.Section, page, size int, query string) ComponentPage {
|
||||||
|
query = strings.TrimSpace(query)
|
||||||
|
needle := strings.ToLower(query)
|
||||||
|
match := func(path []string, c agentapi.Component) bool {
|
||||||
|
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
|
||||||
|
}
|
||||||
|
// Components are counted in the order the page renders them: a
|
||||||
|
// section's own, then its children's. Unnamed sections are top-level
|
||||||
|
// lists without children.
|
||||||
|
var count func(sec agentapi.Section, path []string) int
|
||||||
|
count = func(sec agentapi.Section, path []string) int {
|
||||||
|
if sec.Name != "" {
|
||||||
|
path = append(path, sec.Name)
|
||||||
|
}
|
||||||
|
n := 0
|
||||||
|
for _, c := range sec.Components {
|
||||||
|
if match(path, c) {
|
||||||
|
n++
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if sec.Name != "" {
|
||||||
|
for _, child := range sec.Children {
|
||||||
|
n += count(child, path)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return n
|
||||||
|
}
|
||||||
|
total := 0
|
||||||
|
for _, sec := range sections {
|
||||||
|
total += count(sec, nil)
|
||||||
|
}
|
||||||
|
out := ComponentPage{Pages: 1, Matches: total, Query: query}
|
||||||
|
if needle == "" && (size <= 0 || total <= size) {
|
||||||
|
out.Sections = sections
|
||||||
|
return out
|
||||||
|
}
|
||||||
|
from, to := 0, total
|
||||||
|
if size > 0 && total > size {
|
||||||
|
out.Pages = (total + size - 1) / size
|
||||||
|
out.Page = min(max(page, 0), out.Pages-1)
|
||||||
|
from, to = out.Page*size, min((out.Page+1)*size, total)
|
||||||
|
}
|
||||||
|
idx := 0
|
||||||
|
var cut func(sec agentapi.Section, path []string) (agentapi.Section, bool)
|
||||||
|
cut = func(sec agentapi.Section, path []string) (agentapi.Section, bool) {
|
||||||
|
part := agentapi.Section{Name: sec.Name, Status: secStatusName(sec), Total: SectionTotal(sec)}
|
||||||
|
if sec.Name != "" {
|
||||||
|
path = append(path, sec.Name)
|
||||||
|
}
|
||||||
|
for _, c := range sec.Components {
|
||||||
|
if !match(path, c) {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if idx >= from && idx < to {
|
||||||
|
part.Components = append(part.Components, c)
|
||||||
|
}
|
||||||
|
idx++
|
||||||
|
}
|
||||||
|
if sec.Name != "" {
|
||||||
|
for _, child := range sec.Children {
|
||||||
|
if p, ok := cut(child, path); ok {
|
||||||
|
part.Children = append(part.Children, p)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return part, len(part.Components) > 0 || len(part.Children) > 0
|
||||||
|
}
|
||||||
|
for _, sec := range sections {
|
||||||
|
if p, ok := cut(sec, nil); ok {
|
||||||
|
out.Sections = append(out.Sections, p)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return out
|
||||||
|
}
|
||||||
|
|
||||||
|
// ComponentPageHref links page of the components of the status page at
|
||||||
|
// base, keeping the search for query.
|
||||||
|
func ComponentPageHref(base string, page int, query string) string {
|
||||||
|
v := url.Values{}
|
||||||
|
if page > 0 {
|
||||||
|
v.Set("page", strconv.Itoa(page+1))
|
||||||
|
}
|
||||||
|
if query != "" {
|
||||||
|
v.Set("q", query)
|
||||||
|
}
|
||||||
|
href := BackHref(base)
|
||||||
|
if len(v) > 0 {
|
||||||
|
href += "?" + v.Encode()
|
||||||
|
}
|
||||||
|
return href
|
||||||
|
}
|
||||||
|
|
||||||
|
// 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,
|
// NoticeForm is the button of a notice page that acts on a mailed link,
|
||||||
|
|||||||
@@ -94,11 +94,18 @@ templ PublicStatusPage(s agentapi.PageSnapshot, a PublicAssets) {
|
|||||||
<p class="text-lg font-medium">{ i18n.T(ctx, "page.status."+s.Status) }</p>
|
<p class="text-lg font-medium">{ i18n.T(ctx, "page.status."+s.Status) }</p>
|
||||||
</section>
|
</section>
|
||||||
@pageMaintenance(i18n.T(ctx, "page.maintenance_ongoing"), s.Ongoing(a.Now))
|
@pageMaintenance(i18n.T(ctx, "page.maintenance_ongoing"), s.Ongoing(a.Now))
|
||||||
if len(s.Sections) > 0 {
|
if cp := PageComponents(s.Sections, a.Page, a.PageSize, a.Query); len(s.Sections) > 0 {
|
||||||
|
if cp.Pages > 1 || cp.Query != "" {
|
||||||
|
@publicComponentSearch(cp, a)
|
||||||
|
}
|
||||||
<section class="mb-12 border-t border-rule">
|
<section class="mb-12 border-t border-rule">
|
||||||
for _, sec := range s.Sections {
|
for _, sec := range cp.Sections {
|
||||||
@publicSection(sec, s, a)
|
@publicSection(sec, s, a)
|
||||||
}
|
}
|
||||||
|
if cp.Matches == 0 {
|
||||||
|
<p class="py-6 text-sm text-muted">{ i18n.T(ctx, "page.search_none") }</p>
|
||||||
|
}
|
||||||
|
@publicComponentPager(cp, a)
|
||||||
</section>
|
</section>
|
||||||
}
|
}
|
||||||
@publicIncidents(s.Incidents)
|
@publicIncidents(s.Incidents)
|
||||||
@@ -158,6 +165,34 @@ templ PublicNoticePage(s agentapi.PageSnapshot, a PublicAssets, title, message s
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// publicComponentSearch finds components on pages listing too many to scan.
|
||||||
|
templ publicComponentSearch(cp ComponentPage, a PublicAssets) {
|
||||||
|
<form method="get" action={ templ.SafeURL(BackHref(a.ComponentBase)) } role="search" class="mb-4 flex flex-wrap items-center gap-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={ cp.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"/>
|
||||||
|
<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 cp.Query != "" {
|
||||||
|
<a href={ templ.SafeURL(BackHref(a.ComponentBase)) } class="text-muted hover:text-ink">{ i18n.T(ctx, "page.search_clear") }</a>
|
||||||
|
}
|
||||||
|
</form>
|
||||||
|
}
|
||||||
|
|
||||||
|
// publicComponentPager turns the pages of components.
|
||||||
|
templ publicComponentPager(cp ComponentPage, a PublicAssets) {
|
||||||
|
if cp.Pages > 1 {
|
||||||
|
<nav class="flex flex-wrap items-center gap-x-5 gap-y-2 py-4 text-sm" aria-label={ i18n.T(ctx, "pager.label") }>
|
||||||
|
if cp.Page > 0 {
|
||||||
|
<a href={ templ.SafeURL(ComponentPageHref(a.ComponentBase, 0, cp.Query)) } class="text-muted hover:text-ink">{ i18n.T(ctx, "pager.first") }</a>
|
||||||
|
<a href={ templ.SafeURL(ComponentPageHref(a.ComponentBase, cp.Page-1, cp.Query)) } 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", cp.Page+1, "Pages", cp.Pages) }</span>
|
||||||
|
if cp.Page < cp.Pages-1 {
|
||||||
|
<a href={ templ.SafeURL(ComponentPageHref(a.ComponentBase, cp.Page+1, cp.Query)) } 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
|
// publicSection renders an unnamed root component list or a collapsible nested
|
||||||
// group matching the monitor dashboard hierarchy.
|
// group matching the monitor dashboard hierarchy.
|
||||||
templ publicSection(sec agentapi.Section, s agentapi.PageSnapshot, a PublicAssets) {
|
templ publicSection(sec agentapi.Section, s agentapi.PageSnapshot, a PublicAssets) {
|
||||||
@@ -238,7 +273,12 @@ templ publicComponentBody(comp agentapi.Component, s agentapi.PageSnapshot, clic
|
|||||||
}
|
}
|
||||||
</span>
|
</span>
|
||||||
</div>
|
</div>
|
||||||
|
if clickable {
|
||||||
|
// The detail page the row links to has the tooltips.
|
||||||
|
@pathBars(DayBars(comp.Days), 22)
|
||||||
|
} else {
|
||||||
@bars(DayBars(comp.Days), 22)
|
@bars(DayBars(comp.Days), 22)
|
||||||
|
}
|
||||||
<div class="mt-1 flex justify-between font-mono text-xs text-muted">
|
<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>{ i18n.T(ctx, "page.days_ago", "Count", len(comp.Days)) }</span>
|
||||||
<span>{ UptimeText(comp.Uptime) }</span>
|
<span>{ UptimeText(comp.Uptime) }</span>
|
||||||
@@ -446,3 +486,35 @@ templ pageMaintenance(heading string, items []agentapi.PageMaintenance) {
|
|||||||
</section>
|
</section>
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// PublicNotFoundPage answers visitors of a status page that does not exist,
|
||||||
|
// and of the bare status page domain, with a link to the home page if set.
|
||||||
|
templ PublicNotFoundPage(cssHref, home string) {
|
||||||
|
<!DOCTYPE html>
|
||||||
|
<html lang={ i18n.Lang(ctx) }>
|
||||||
|
<head>
|
||||||
|
<meta charset="utf-8"/>
|
||||||
|
<meta name="viewport" content="width=device-width, initial-scale=1"/>
|
||||||
|
<meta name="robots" content="noindex"/>
|
||||||
|
<title>{ i18n.T(ctx, "page.not_found_title") }</title>
|
||||||
|
@faviconLinks()
|
||||||
|
<link rel="stylesheet" href={ cssHref }/>
|
||||||
|
</head>
|
||||||
|
<body class="min-h-screen">
|
||||||
|
<main class="mx-auto flex min-h-screen max-w-xl flex-col justify-center px-4 py-14 sm:px-6">
|
||||||
|
<p class="mb-3 font-mono text-xs text-muted">404</p>
|
||||||
|
<h1 class="mb-3 text-2xl font-semibold">{ i18n.T(ctx, "page.not_found_title") }</h1>
|
||||||
|
<p class="mb-8 text-muted">{ i18n.T(ctx, "page.not_found") }</p>
|
||||||
|
if home != "" {
|
||||||
|
<p>
|
||||||
|
<a href={ templ.SafeURL(home) } class="inline-block border border-ink px-4 py-2 text-sm hover:bg-ink hover:text-paper">{ i18n.T(ctx, "page.not_found_home") }</a>
|
||||||
|
</p>
|
||||||
|
}
|
||||||
|
<p class="mt-14 flex items-center gap-1 font-mono text-xs text-muted">
|
||||||
|
@brandMark("h-3.5 w-3.5")
|
||||||
|
UptimeSebi
|
||||||
|
</p>
|
||||||
|
</main>
|
||||||
|
</body>
|
||||||
|
</html>
|
||||||
|
}
|
||||||
+924
-461
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: "1h", Window: time.Hour, Bucket: time.Minute, Layout: "15:04"},
|
||||||
{Key: "3h", Window: 3 * time.Hour, Bucket: 5 * time.Minute, Layout: "15:04"},
|
{Key: "3h", Window: 3 * time.Hour, Bucket: 5 * time.Minute, Layout: "15:04"},
|
||||||
{Key: "12h", Window: 12 * time.Hour, Bucket: 15 * time.Minute, Layout: "15:04"},
|
{Key: "12h", Window: 12 * time.Hour, Bucket: 15 * time.Minute, Layout: "15:04"},
|
||||||
{Key: "24h", Window: day, Bucket: 30 * time.Minute, Layout: "01-02 15:04"},
|
{Key: "24h", Window: day, Bucket: time.Hour, Source: SourceHourly, Layout: "01-02 15:04"},
|
||||||
{Key: "7d", Window: 7 * day, Bucket: 4 * time.Hour, Source: SourceHourly, Layout: "01-02 15:04"},
|
{Key: "7d", Window: 7 * day, Bucket: 4 * time.Hour, Source: SourceHourly, Layout: "01-02 15:04"},
|
||||||
{Key: "30d", Window: 30 * day, Bucket: 12 * time.Hour, Source: SourceHourly, Layout: "2006-01-02 15:04"},
|
{Key: "30d", Window: 30 * day, Bucket: 12 * time.Hour, Source: SourceHourly, Layout: "2006-01-02 15:04"},
|
||||||
{Key: "90d", Window: 90 * day, Bucket: 2 * day, Source: SourceDaily, Layout: "2006-01-02"},
|
{Key: "90d", Window: 90 * day, Bucket: 2 * day, Source: SourceDaily, Layout: "2006-01-02"},
|
||||||
|
|||||||
@@ -195,7 +195,7 @@ templ RegionsPage(p Page, me Me, v RegionsView) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
templ AdminPage(p Page, me Me, v RegionsView, storage StorageView, checkTypes []CheckTypeOption, platformPrivate bool, limits LimitsView, idps IDPAdminView) {
|
templ AdminPage(p Page, me Me, v RegionsView, storage StorageView, checkTypes []CheckTypeOption, platformPrivate bool, pageHome string, limits LimitsView, idps IDPAdminView) {
|
||||||
@consoleShell(p, me) {
|
@consoleShell(p, me) {
|
||||||
@settingsHeading("admin.title", "admin.intro")
|
@settingsHeading("admin.title", "admin.intro")
|
||||||
@adminLinks()
|
@adminLinks()
|
||||||
@@ -203,6 +203,7 @@ templ AdminPage(p Page, me Me, v RegionsView, storage StorageView, checkTypes []
|
|||||||
@limitsSection(limits)
|
@limitsSection(limits)
|
||||||
@regionsBody(v)
|
@regionsBody(v)
|
||||||
@checkerNetworkSection(platformPrivate)
|
@checkerNetworkSection(platformPrivate)
|
||||||
|
@statusPageHomeSection(pageHome)
|
||||||
@checkTypesSection(checkTypes, "/admin/check-types", "/admin", "admin.check_types_intro")
|
@checkTypesSection(checkTypes, "/admin/check-types", "/admin", "admin.check_types_intro")
|
||||||
@storageSection(storage)
|
@storageSection(storage)
|
||||||
}
|
}
|
||||||
@@ -228,6 +229,23 @@ templ checkerNetworkSection(allow bool) {
|
|||||||
</section>
|
</section>
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// statusPageHomeSection sets the home page the status page servers link
|
||||||
|
// from their error page.
|
||||||
|
templ statusPageHomeSection(url string) {
|
||||||
|
<section class="mt-12 max-w-3xl">
|
||||||
|
@sectionHeading("admin.statuspage_home")
|
||||||
|
<p class="mb-4 text-sm text-muted">{ i18n.T(ctx, "admin.statuspage_home_hint") }</p>
|
||||||
|
<form data-api="/admin/statuspage-home" data-method="put" data-next="/admin">
|
||||||
|
@formError()
|
||||||
|
<label class="mb-4 block">
|
||||||
|
<span class="mb-1 block text-xs font-medium uppercase tracking-wider text-muted">{ i18n.T(ctx, "admin.statuspage_home_url") }</span>
|
||||||
|
<input class="w-full border border-rule bg-transparent px-2.5 py-1.5 outline-none focus:border-ink" type="url" name="url" value={ url } maxlength="2000" placeholder="https://example.com"/>
|
||||||
|
</label>
|
||||||
|
<button type="submit" class="border border-ink px-3 py-1.5 text-sm hover:bg-ink hover:text-paper">{ i18n.T(ctx, "common.save") }</button>
|
||||||
|
</form>
|
||||||
|
</section>
|
||||||
|
}
|
||||||
|
|
||||||
// checkTypesSection lets the platform or an organization choose the
|
// checkTypesSection lets the platform or an organization choose the
|
||||||
// check types it offers.
|
// check types it offers.
|
||||||
templ checkTypesSection(types []CheckTypeOption, api, next, introID string) {
|
templ checkTypesSection(types []CheckTypeOption, api, next, introID string) {
|
||||||
|
|||||||
+550
-451
File diff suppressed because it is too large.
Load diff
@@ -320,11 +320,11 @@ templ StatusPageEditor(p Page, me Me, e PageEditor) {
|
|||||||
<template data-row-fields>
|
<template data-row-fields>
|
||||||
@pageMonitorFields(e, PageMonitorOption{})
|
@pageMonitorFields(e, PageMonitorOption{})
|
||||||
</template>
|
</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 {
|
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">
|
<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 }/>
|
<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>
|
<span>{ m.Name }</span>
|
||||||
if m.MonitorGroupPath != "" {
|
if m.MonitorGroupPath != "" {
|
||||||
<span class="font-mono text-xs text-muted">{ m.MonitorGroupPath }</span>
|
<span class="font-mono text-xs text-muted">{ m.MonitorGroupPath }</span>
|
||||||
@@ -339,6 +339,15 @@ templ StatusPageEditor(p Page, me Me, e PageEditor) {
|
|||||||
</li>
|
</li>
|
||||||
}
|
}
|
||||||
</ul>
|
</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"))
|
@submit(i18n.T(ctx, "common.save"))
|
||||||
</form>
|
</form>
|
||||||
</section>
|
</section>
|
||||||
@@ -416,16 +425,33 @@ templ verifyButton(pageID, label string) {
|
|||||||
// offers to filter them.
|
// offers to filter them.
|
||||||
const monitorFilterFrom = 15
|
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.
|
// pageMonitorFields are the group and label of m on the page.
|
||||||
templ pageMonitorFields(e PageEditor, m PageMonitorOption) {
|
templ pageMonitorFields(e PageEditor, m PageMonitorOption) {
|
||||||
<span data-row-extra></span>
|
<span data-row-extra></span>
|
||||||
<span class="flex gap-2">
|
<span class="flex gap-2">
|
||||||
|
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">
|
<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>
|
<option value="">{ i18n.T(ctx, "pages.no_group") }</option>
|
||||||
for _, opt := range e.Groups {
|
for _, opt := range e.Groups {
|
||||||
<option value={ opt.ID } selected?={ opt.ID == m.GroupID }>{ opt.Label }</option>
|
<option value={ opt.ID }>{ opt.Label }</option>
|
||||||
}
|
}
|
||||||
</select>
|
</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"/>
|
<input data-field="label" value={ m.Label } placeholder={ i18n.T(ctx, "pages.label") } class="w-1/2 border border-rule bg-transparent px-2 py-1 text-xs outline-none focus:border-ink"/>
|
||||||
</span>
|
</span>
|
||||||
}
|
}
|
||||||
|
|||||||
+586
-443
File diff suppressed because it is too large.
Load diff
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