Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
38 changes: 38 additions & 0 deletions docs/events.md
Original file line number Diff line number Diff line change
Expand Up @@ -230,6 +230,44 @@ of `GET /v2/components` appears in `data` as
of the window, with 100 % for months that have no outage, ordered newest first. Components are
ordered by `id`.

## Availability summary — `GET /v2/availability/summary`

The summary is the platform-level counterpart of `GET /v2/availability`. It is public, takes no
query parameters and does not change the per-component report.

The window is always the six calendar months ending with the current one: it starts on the
first day of the month five months back and ends at the request time, so the current month is
partial. Exactly six month labels are always returned, newest first. When the request arrives
at the first instant of a month, that month has no time inside the window and is reported as
`100` because its denominator is zero, but it is still present as the sixth label.

Only incidents with an impact of exactly `3` (outage) contribute; maintenance, info and impacts
`0`-`2` are excluded. An incident that is still open runs up to the end of the window, and
soft-deleted incidents are ignored. Overlapping outages on the same component are merged before
downtime is summed, so downtime never exceeds the denominator. An incident linked to several
components counts once for each affected component.

Component lifecycles follow the calendar month, not the day: a component that exists during a
month contributes to that whole month, even if it was created mid-month; a component deleted
during a month is excluded from that entire month. Rows without `created_at` or `deleted_at`
are treated as legacy and stay active. A deletion exactly at the start of the next month means
the component survived the whole month and is still active for it.

For each month the denominator is `active component count * overlap of the month with the
window`, and the downtime is the sum, over the active components, of their merged outage
overlap with the window inside that month. The monthly `percentage` is
`100 - downtime / denominator * 100`, clamped to `[0, 100]`. The overall `percentage` uses the
raw duration sums over all six months, so it is not an average of the rounded monthly values.
Both are rounded to five decimals, and a zero denominator reports `100`.

The response is `{window, percentage, components_total, components_affected, monthly}` with no
`data` wrapper. `window` is `{start, end, months}` (`start` and `end` are RFC3339, `months` is
always `6`). `components_total` counts distinct components active in at least one month;
`components_affected` counts distinct active components with any downtime in a month where they
are active. `monthly` holds exactly six `{year, month, percentage}` entries, newest first. With
no components the response is `percentage: 100`, both counters `0`, and six monthly entries at
`100`.

## RSS — `GET /rss/`

Options are `mt` (region: `EU-DE`, `EU-NL`, `EU-CH2`, `Global`) and `srv` (component name, requires
Expand Down
1 change: 1 addition & 0 deletions internal/api/routes.go
Original file line number Diff line number Diff line change
Expand Up @@ -112,6 +112,7 @@ func (a *API) initV2Routes() {
v2.PatchEventUpdateTextHandler(a.db, a.log))
// Availability section.
v2API.GET("availability", v2.GetComponentsAvailabilityHandler(a.db, a.log))
v2API.GET("availability/summary", v2.GetAvailabilitySummaryHandler(a.db, a.log))

// Notifications operations (admin only): queue stats, failed rows, re-drive.
v2API.GET("notifications/stats",
Expand Down
167 changes: 167 additions & 0 deletions internal/api/v2/availability_summary.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,167 @@
package v2

import (
"net/http"
"time"

"github.com/gin-gonic/gin"
"go.uber.org/zap"

apiErrors "github.com/stackmon/otc-status-dashboard/internal/api/errors"
"github.com/stackmon/otc-status-dashboard/internal/db"
)

// availabilitySummaryWindowMonths is the fixed number of calendar months in a
// GET /v2/availability/summary response: the current month plus the five
// previous ones.
const availabilitySummaryWindowMonths = 6

// AvailabilitySummary is the platform-level availability report returned by
// GET /v2/availability/summary.
type AvailabilitySummary struct {
Window AvailabilityWindow `json:"window"`
Percentage float64 `json:"percentage"`
ComponentsTotal int `json:"components_total"`
ComponentsAffected int `json:"components_affected"`
Monthly []MonthlyAvailability `json:"monthly"`
}

// GetAvailabilitySummaryHandler reports platform availability for the trailing
// six calendar months, ending at the request time. Public, no parameters.
func GetAvailabilitySummaryHandler(dbInst *db.DB, logger *zap.Logger) gin.HandlerFunc {
return func(c *gin.Context) {
logger.Debug("retrieve platform availability summary")

start, end := availabilitySummaryWindow(time.Now().UTC())

ctx := c.Request.Context()

// The lifecycle rule below needs soft-deleted rows too, so this query
// must not filter on deleted_at.
components, err := dbInst.GetComponentsWithValues(ctx)
if err != nil {
apiErrors.RaiseInternalErr(c, err)
return
}

outages, err := dbInst.GetComponentOutages(ctx, start, end)
if err != nil {
apiErrors.RaiseInternalErr(c, err)
return
}

c.JSON(http.StatusOK, buildAvailabilitySummary(components, outages, start, end))
}
}

// availabilitySummaryWindow resolves the summary window: the six calendar
// months ending with the month of now. now is truncated to seconds; the
// current month is partial because the window ends at the request time.
func availabilitySummaryWindow(now time.Time) (time.Time, time.Time) {
now = now.UTC().Truncate(time.Second)

currentMonth := time.Date(now.Year(), now.Month(), 1, 0, 0, 0, 0, time.UTC)

return currentMonth.AddDate(0, -(availabilitySummaryWindowMonths - 1), 0), now
}

// summaryMonths lists the summary month labels, newest first. The current month
// is always the first label, even when the window has no overlap with it.
func summaryMonths(end time.Time) []time.Time {
currentMonth := time.Date(end.Year(), end.Month(), 1, 0, 0, 0, 0, time.UTC)

months := make([]time.Time, 0, availabilitySummaryWindowMonths)
for i := range availabilitySummaryWindowMonths {
months = append(months, currentMonth.AddDate(0, -i, 0))
}

return months
}

// componentActiveInMonth reports whether comp contributes to the whole month
// ending at monthEnd. A component created during a month counts for that
// entire month; a component deleted during a month does not. A deletion
// exactly at monthEnd means the component survived the month. Nil timestamps
// are legacy rows and stay active so they are never silently dropped.
func componentActiveInMonth(comp db.Component, monthEnd time.Time) bool {
if comp.CreatedAt != nil && !comp.CreatedAt.Before(monthEnd) {
return false
}

if comp.DeletedAt != nil && comp.DeletedAt.Before(monthEnd) {
return false
}

return true
}

// buildAvailabilitySummary aggregates component outages into a platform-level
// report. Each month's denominator is the number of active components times the
// part of the month inside the window. An incident shared by several components
// counts once per affected component. Overall availability is derived from the
// raw duration sums, so it is not an average of the rounded monthly values.
func buildAvailabilitySummary(
components []db.Component,
outages []db.ComponentOutage,
start, end time.Time,
) AvailabilitySummary {
months := summaryMonths(end)
outagesByComponent := mergeComponentOutages(outages)

activeComponents := make(map[uint]struct{}, len(components))
affectedComponents := make(map[uint]struct{}, len(components))

monthly := make([]MonthlyAvailability, 0, len(months))

var totalDowntime, totalDuration time.Duration

for _, month := range months {
monthStart := month
monthEnd := month.AddDate(0, 1, 0)
windowStart := laterTime(monthStart, start)
windowEnd := earlierTime(monthEnd, end)
overlap := overlapDuration(monthStart, monthEnd, start, end)

var (
monthDowntime time.Duration
componentCount int
)

for _, comp := range components {
if !componentActiveInMonth(comp, monthEnd) {
continue
}

componentCount++
activeComponents[comp.ID] = struct{}{}

downtime := downtimeOverlap(outagesByComponent[comp.ID], windowStart, windowEnd)
if downtime > 0 {
affectedComponents[comp.ID] = struct{}{}
monthDowntime += downtime
}
}

monthDuration := time.Duration(componentCount) * overlap
totalDowntime += monthDowntime
totalDuration += monthDuration

monthly = append(monthly, MonthlyAvailability{
Year: month.Year(),
Month: int(month.Month()),
Percentage: availabilityPercentage(monthDowntime, monthDuration),
})
}

return AvailabilitySummary{
Window: AvailabilityWindow{
Start: start,
End: end,
Months: len(months),
},
Percentage: availabilityPercentage(totalDowntime, totalDuration),
ComponentsTotal: len(activeComponents),
ComponentsAffected: len(affectedComponents),
Monthly: monthly,
}
}
Loading