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
31 changes: 20 additions & 11 deletions docs/events.md
Original file line number Diff line number Diff line change
Expand Up @@ -209,17 +209,26 @@ whose status is not a terminal one (`resolved`, `completed`, `cancelled`, `pendi

## Availability — `GET /v2/availability`

Availability is `100 - downtime / totalHours * 100`, rounded to five decimals, and only counts
incidents with an impact of exactly `3` (outage) that have an `end_date`. The window is 12 months
ending with the current one, i.e. it starts on the first day of the month 11 months back; downtime is
clipped to that window. The optional `start_date` and `end_date` query parameters (RFC3339) narrow or
shift the window; it may cover at most 12 calendar months. Downtime is aggregated in the database
over the requested window.

Every component of `GET /v2/components` is reported as
`{id, name, region, availability: [{year, month, percentage}]}`, with all 12 months listed
(100 % for months without an outage) and the months ordered newest first. Only a component that has
no recorded incident at all comes back with an empty `availability` array.
Availability is `100 - downtime / totalHours * 100`, clamped to `[0, 100]` and rounded to five
decimals. Only incidents with an impact of exactly `3` (outage) contribute; an incident that is
still open counts 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
window length. An incident linked to several components counts for each of them.

The window is 12 months ending with the current one, i.e. it starts on the first day of the month 11
months back. The optional `start_date` and `end_date` query parameters (RFC3339) narrow or shift the
window; a window may span at most 12 months of duration, and `end_date` is capped at the current
time. The denominator of a month is the part of that month inside the window: the current month and
custom boundaries are partial, while complete months use the full month.

The response is `{window: {start, end, months}, data: [...]}`. `window` is the effective reporting
window (`start` and `end` are RFC3339, `months` is the number of reported months). Because the limit
is measured by duration, a window that starts and ends on the same day of different months can
include 13 calendar month labels. Every component
of `GET /v2/components` appears in `data` as
`{id, name, region, availability: [{year, month, percentage}]}`. Every component lists every month
of the window, with 100 % for months that have no outage, ordered newest first. Components are
ordered by `id`.

## RSS — `GET /rss/`

Expand Down
169 changes: 130 additions & 39 deletions internal/api/v2/v2.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import (
"context"
"errors"
"fmt"
"math"
"net/http"
"sort"
"time"
Expand Down Expand Up @@ -1532,6 +1533,14 @@ type ComponentAvailability struct {
Region string `json:"region"`
}

// AvailabilityWindow describes the effective reporting window of a
// GET /v2/availability response.
type AvailabilityWindow struct {
Start time.Time `json:"start"`
End time.Time `json:"end"`
Months int `json:"months"`
}

type ComponentID struct {
ID int `json:"id" uri:"id" binding:"required,gte=0,lte=2147483647"`
}
Expand Down Expand Up @@ -1732,18 +1741,18 @@ func GetComponentsAvailabilityHandler(dbInst *db.DB, logger *zap.Logger) gin.Han
return
}

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

months := availabilityMonths(start, end)
downtimeByComponent := groupComponentDowntime(downtime)
outagesByComponent := mergeComponentOutages(outages)

availability := make([]*ComponentAvailability, len(components))
for index, comp := range components {
monthly := buildMonthlyAvailability(months, downtimeByComponent[comp.ID])
monthly := buildMonthlyAvailability(months, start, end, outagesByComponent[comp.ID])
sortComponentAvailability(monthly)

availability[index] = &ComponentAvailability{
Expand All @@ -1754,7 +1763,14 @@ func GetComponentsAvailabilityHandler(dbInst *db.DB, logger *zap.Logger) gin.Han
}
}

c.JSON(http.StatusOK, gin.H{"data": availability})
c.JSON(http.StatusOK, gin.H{
"data": availability,
"window": AvailabilityWindow{
Start: start,
End: end,
Months: len(months),
},
})
}
}

Expand All @@ -1767,20 +1783,45 @@ func componentRegion(comp db.Component) string {
return ""
}

type availabilityMonth int

func monthKey(month time.Time) availabilityMonth {
return availabilityMonth(month.Year()*12 + int(month.Month()) - 1)
type availabilityInterval struct {
start time.Time
end time.Time
}

func groupComponentDowntime(rows []db.ComponentDowntime) map[uint]map[availabilityMonth]float64 {
grouped := make(map[uint]map[availabilityMonth]float64, len(rows))
for _, row := range rows {
if grouped[row.ComponentID] == nil {
grouped[row.ComponentID] = make(map[availabilityMonth]float64)
// mergeComponentOutages groups outage rows by component and merges overlapping
// or touching intervals. An incident linked to several components stays in
// each component's group; only same-component overlaps are deduplicated.
func mergeComponentOutages(outages []db.ComponentOutage) map[uint][]availabilityInterval {
grouped := make(map[uint][]availabilityInterval, len(outages))
for _, outage := range outages {
grouped[outage.ComponentID] = append(grouped[outage.ComponentID], availabilityInterval{
start: outage.Start,
end: outage.End,
})
}

for componentID, intervals := range grouped {
sort.Slice(intervals, func(i, j int) bool {
if intervals[i].start.Equal(intervals[j].start) {
return intervals[i].end.Before(intervals[j].end)
}
return intervals[i].start.Before(intervals[j].start)
})

merged := make([]availabilityInterval, 0, len(intervals))
for _, interval := range intervals {
last := len(merged) - 1
if last < 0 || interval.start.After(merged[last].end) {
merged = append(merged, interval)
continue
}
if interval.end.After(merged[last].end) {
merged[last].end = interval.end
}
}
grouped[row.ComponentID][monthKey(row.Month)] += row.Hours
grouped[componentID] = merged
}

return grouped
}

Expand All @@ -1789,11 +1830,17 @@ func groupComponentDowntime(rows []db.ComponentDowntime) map[uint]map[availabili
const availabilityWindowMonths = 12

// availabilityWindow resolves the reporting window. Without parameters it is
// the trailing 12 months ending with the current month.
// the trailing 12 months ending with the current month. now is truncated to
// seconds, and a requested end in the future is capped at now.
func availabilityWindow(queryStart, queryEnd *time.Time, now time.Time) (time.Time, time.Time, error) {
now = now.UTC().Truncate(time.Second)

end := now
if queryEnd != nil {
end = queryEnd.UTC()
if end.After(now) {
end = now
}
}

start := time.Date(end.Year(), end.Month(), 1, 0, 0, 0, 0, time.UTC).
Expand All @@ -1802,52 +1849,103 @@ func availabilityWindow(queryStart, queryEnd *time.Time, now time.Time) (time.Ti
start = queryStart.UTC()
}

if !start.Before(end) || availabilityMonthCount(start, end) > availabilityWindowMonths {
if !start.Before(end) || end.After(start.AddDate(0, availabilityWindowMonths, 0)) {
return time.Time{}, time.Time{}, apiErrors.ErrAvailabilityQueryInvalidFormat
}

return start, end, nil
}

func availabilityMonthCount(start, end time.Time) int {
return (end.Year()-start.Year())*12 + int(end.Month()-start.Month()) + 1
}

// availabilityMonths lists the calendar months that intersect [start, end]. A
// month that only touches the end boundary (end is exactly its first instant)
// has no overlap and is not listed.
func availabilityMonths(start, end time.Time) []time.Time {
first := time.Date(start.Year(), start.Month(), 1, 0, 0, 0, 0, time.UTC)
last := time.Date(end.Year(), end.Month(), 1, 0, 0, 0, 0, time.UTC)
if end.Equal(last) {
last = last.AddDate(0, -1, 0)
}

months := make([]time.Time, 0, availabilityMonthCount(start, end))
months := make([]time.Time, 0, availabilityWindowMonths+1)
for month := first; !month.After(last); month = month.AddDate(0, 1, 0) {
months = append(months, month)
}

return months
}

func buildMonthlyAvailability(months []time.Time, downtime map[availabilityMonth]float64) []MonthlyAvailability {
const (
precisionFactor = 100000
fullPercentage = 100
roundFactor = 0.5
)

func buildMonthlyAvailability(
months []time.Time, start, end time.Time, intervals []availabilityInterval,
) []MonthlyAvailability {
monthlyAvailability := make([]MonthlyAvailability, 0, len(months))
for _, month := range months {
totalHours := hoursInMonth(month.Year(), int(month.Month()))
percentage := fullPercentage - (downtime[monthKey(month)] / totalHours * fullPercentage)
percentage = float64(int(percentage*precisionFactor+roundFactor)) / precisionFactor
monthStart := month
monthEnd := month.AddDate(0, 1, 0)
windowStart := laterTime(monthStart, start)
windowEnd := earlierTime(monthEnd, end)

downtime := downtimeOverlap(intervals, windowStart, windowEnd)
total := overlapDuration(monthStart, monthEnd, start, end)

monthlyAvailability = append(monthlyAvailability, MonthlyAvailability{
Year: month.Year(),
Month: int(month.Month()),
Percentage: percentage,
Percentage: availabilityPercentage(downtime, total),
})
}

return monthlyAvailability
}

// availabilityPercentage converts merged downtime inside a month into the
// reported availability. A month with no requested time at all keeps 100.
func availabilityPercentage(downtime, total time.Duration) float64 {
const (
precisionFactor = 100000
fullPercentage = 100.0
)

if total <= 0 {
return fullPercentage
}

percentage := fullPercentage * (1 - downtime.Seconds()/total.Seconds())
percentage = math.Min(fullPercentage, math.Max(0, percentage))

return math.Round(percentage*precisionFactor) / precisionFactor
}

func downtimeOverlap(intervals []availabilityInterval, start, end time.Time) time.Duration {
var total time.Duration
for _, interval := range intervals {
total += overlapDuration(interval.start, interval.end, start, end)
}
return total
}

func overlapDuration(start, end, otherStart, otherEnd time.Time) time.Duration {
overlapStart := laterTime(start, otherStart)
overlapEnd := earlierTime(end, otherEnd)
if !overlapEnd.After(overlapStart) {
return 0
}
return overlapEnd.Sub(overlapStart)
}

func laterTime(a, b time.Time) time.Time {
if a.After(b) {
return a
}
return b
}

func earlierTime(a, b time.Time) time.Time {
if a.Before(b) {
return a
}
return b
}

func sortComponentAvailability(availabilities []MonthlyAvailability) {
sort.Slice(availabilities, func(i, j int) bool {
if availabilities[i].Year == availabilities[j].Year {
Expand All @@ -1857,13 +1955,6 @@ func sortComponentAvailability(availabilities []MonthlyAvailability) {
})
}

func hoursInMonth(year int, month int) float64 {
firstDay := time.Date(year, time.Month(month), 1, 0, 0, 0, 0, time.UTC)
nextMonth := firstDay.AddDate(0, 1, 0)

return float64(nextMonth.Sub(firstDay).Hours())
}

type EventUpdateData struct {
ID int `json:"id"`
Status event.Status `json:"status"`
Expand Down
Loading