From 31036e4fe9a236cb03fa2ced0655f908bcdfda1f Mon Sep 17 00:00:00 2001 From: Aloento <11802769+Aloento@users.noreply.github.com> Date: Tue, 1 Dec 2026 12:43:27 +0100 Subject: [PATCH 1/3] [Fix] Bound availability windows and merge overlapping outages --- docs/events.md | 29 ++-- internal/api/v2/v2.go | 169 +++++++++++++++++------ internal/api/v2/v2_test.go | 259 +++++++++++++++++++++++++++++++----- internal/db/availability.go | 75 ++++------- internal/db/db.go | 1 + openapi.yaml | 26 +++- tests/v2_test.go | 233 ++++++++++++++++++++++++++++++++ 7 files changed, 656 insertions(+), 136 deletions(-) diff --git a/docs/events.md b/docs/events.md index 0e57b4f..b85b2b3 100644 --- a/docs/events.md +++ b/docs/events.md @@ -209,17 +209,24 @@ 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). 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/` diff --git a/internal/api/v2/v2.go b/internal/api/v2/v2.go index 5b4a4a5..d321fdb 100644 --- a/internal/api/v2/v2.go +++ b/internal/api/v2/v2.go @@ -4,6 +4,7 @@ import ( "context" "errors" "fmt" + "math" "net/http" "sort" "time" @@ -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"` } @@ -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{ @@ -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), + }, + }) } } @@ -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 } @@ -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). @@ -1802,22 +1849,24 @@ 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) } @@ -1825,29 +1874,78 @@ func availabilityMonths(start, end time.Time) []time.Time { 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 { @@ -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"` diff --git a/internal/api/v2/v2_test.go b/internal/api/v2/v2_test.go index 4d4805c..d8399ae 100644 --- a/internal/api/v2/v2_test.go +++ b/internal/api/v2/v2_test.go @@ -2,6 +2,7 @@ package v2 import ( "fmt" + "math" "net/http" "net/http/httptest" "strings" @@ -31,10 +32,15 @@ func TestReturn404Handler(t *testing.T) { } func TestAvailabilityWindow(t *testing.T) { - now := time.Date(2026, time.November, 12, 15, 30, 0, 0, time.UTC) + now := time.Date(2026, time.November, 12, 15, 30, 45, 123456789, time.UTC) + truncatedNow := now.Truncate(time.Second) defaultStart := time.Date(2025, time.December, 1, 0, 0, 0, 0, time.UTC) - withinWindow := now.AddDate(0, -3, 0) - tooEarly := now.AddDate(0, -13, 0) + withinWindow := truncatedNow.AddDate(0, -3, 0) + tooEarly := truncatedNow.AddDate(0, -13, 0) + futureEnd := truncatedNow.AddDate(0, 6, 0) + yearStart := time.Date(2024, time.November, 15, 0, 0, 0, 0, time.UTC) + yearEnd := time.Date(2025, time.November, 15, 0, 0, 0, 0, time.UTC) + oneDayOver := yearEnd.AddDate(0, 0, 1) tests := []struct { name string @@ -47,18 +53,18 @@ func TestAvailabilityWindow(t *testing.T) { { name: "default window", wantStart: defaultStart, - wantEnd: now, + wantEnd: truncatedNow, }, { name: "custom window inside the default range", start: &withinWindow, - end: &now, + end: &truncatedNow, wantStart: withinWindow, - wantEnd: now, + wantEnd: truncatedNow, }, { name: "start after end", - start: &now, + start: &truncatedNow, end: &withinWindow, wantErr: errors.ErrAvailabilityQueryInvalidFormat, }, @@ -67,6 +73,32 @@ func TestAvailabilityWindow(t *testing.T) { start: &tooEarly, wantErr: errors.ErrAvailabilityQueryInvalidFormat, }, + { + name: "future end is capped at now", + end: &futureEnd, + wantStart: defaultStart, + wantEnd: truncatedNow, + }, + { + name: "future end keeps an explicit start", + start: &withinWindow, + end: &futureEnd, + wantStart: withinWindow, + wantEnd: truncatedNow, + }, + { + name: "twelve months from the fifteenth", + start: &yearStart, + end: &yearEnd, + wantStart: yearStart, + wantEnd: yearEnd, + }, + { + name: "one day over twelve months", + start: &yearStart, + end: &oneDayOver, + wantErr: errors.ErrAvailabilityQueryInvalidFormat, + }, } for _, tc := range tests { @@ -84,24 +116,144 @@ func TestAvailabilityWindow(t *testing.T) { } func TestAvailabilityMonths(t *testing.T) { - start := time.Date(2026, time.March, 15, 10, 0, 0, 0, time.UTC) - end := time.Date(2026, time.May, 2, 0, 0, 0, 0, time.UTC) + tests := []struct { + name string + start time.Time + end time.Time + want []time.Time + }{ + { + name: "months intersected by the window", + start: time.Date(2026, time.March, 15, 10, 0, 0, 0, time.UTC), + end: time.Date(2026, time.May, 2, 0, 0, 0, 0, time.UTC), + want: []time.Time{ + time.Date(2026, time.March, 1, 0, 0, 0, 0, time.UTC), + time.Date(2026, time.April, 1, 0, 0, 0, 0, time.UTC), + time.Date(2026, time.May, 1, 0, 0, 0, 0, time.UTC), + }, + }, + { + name: "month starting at the window end is not listed", + start: time.Date(2026, time.March, 15, 10, 0, 0, 0, time.UTC), + end: time.Date(2026, time.May, 1, 0, 0, 0, 0, time.UTC), + want: []time.Time{ + time.Date(2026, time.March, 1, 0, 0, 0, 0, time.UTC), + time.Date(2026, time.April, 1, 0, 0, 0, 0, time.UTC), + }, + }, + { + name: "window inside a single month", + start: time.Date(2026, time.March, 15, 10, 0, 0, 0, time.UTC), + end: time.Date(2026, time.March, 20, 10, 0, 0, 0, time.UTC), + want: []time.Time{ + time.Date(2026, time.March, 1, 0, 0, 0, 0, time.UTC), + }, + }, + } - months := availabilityMonths(start, end) + for _, tc := range tests { + t.Run(tc.name, func(t *testing.T) { + assert.Equal(t, tc.want, availabilityMonths(tc.start, tc.end)) + }) + } +} - require.Len(t, months, 3) - assert.Equal(t, time.Date(2026, time.March, 1, 0, 0, 0, 0, time.UTC), months[0]) - assert.Equal(t, time.Date(2026, time.April, 1, 0, 0, 0, 0, time.UTC), months[1]) - assert.Equal(t, time.Date(2026, time.May, 1, 0, 0, 0, 0, time.UTC), months[2]) +func TestMergeComponentOutages(t *testing.T) { + at := func(day, hour int) time.Time { + return time.Date(2026, time.January, day, hour, 0, 0, 0, time.UTC) + } + + tests := []struct { + name string + outages []db.ComponentOutage + want map[uint][]availabilityInterval + }{ + { + name: "overlapping intervals are merged", + outages: []db.ComponentOutage{ + {ComponentID: 1, Start: at(1, 0), End: at(10, 0)}, + {ComponentID: 1, Start: at(5, 0), End: at(15, 0)}, + }, + want: map[uint][]availabilityInterval{ + 1: {{start: at(1, 0), end: at(15, 0)}}, + }, + }, + { + name: "contained interval does not extend the outage", + outages: []db.ComponentOutage{ + {ComponentID: 1, Start: at(1, 0), End: at(20, 0)}, + {ComponentID: 1, Start: at(5, 0), End: at(10, 0)}, + }, + want: map[uint][]availabilityInterval{ + 1: {{start: at(1, 0), end: at(20, 0)}}, + }, + }, + { + name: "touching intervals are merged", + outages: []db.ComponentOutage{ + {ComponentID: 1, Start: at(1, 0), End: at(10, 0)}, + {ComponentID: 1, Start: at(10, 0), End: at(15, 0)}, + }, + want: map[uint][]availabilityInterval{ + 1: {{start: at(1, 0), end: at(15, 0)}}, + }, + }, + { + name: "disjoint intervals stay separate", + outages: []db.ComponentOutage{ + {ComponentID: 1, Start: at(10, 0), End: at(15, 0)}, + {ComponentID: 1, Start: at(1, 0), End: at(5, 0)}, + }, + want: map[uint][]availabilityInterval{ + 1: { + {start: at(1, 0), end: at(5, 0)}, + {start: at(10, 0), end: at(15, 0)}, + }, + }, + }, + { + name: "multi-component incident stays on each component", + outages: []db.ComponentOutage{ + {ComponentID: 1, Start: at(1, 0), End: at(5, 0)}, + {ComponentID: 2, Start: at(1, 0), End: at(5, 0)}, + {ComponentID: 1, Start: at(4, 0), End: at(8, 0)}, + }, + want: map[uint][]availabilityInterval{ + 1: {{start: at(1, 0), end: at(8, 0)}}, + 2: {{start: at(1, 0), end: at(5, 0)}}, + }, + }, + } + + for _, tc := range tests { + t.Run(tc.name, func(t *testing.T) { + assert.Equal(t, tc.want, mergeComponentOutages(tc.outages)) + }) + } } -func TestBuildMonthlyAvailability(t *testing.T) { - const ( - precisionFactor = 100000.0 - fullPercentage = 100.0 - roundFactor = 0.5 - ) +func TestAvailabilityPercentage(t *testing.T) { + tests := []struct { + name string + downtime time.Duration + total time.Duration + want float64 + }{ + {name: "no downtime", total: 24 * time.Hour, want: 100}, + {name: "full downtime", downtime: 24 * time.Hour, total: 24 * time.Hour, want: 0}, + {name: "downtime beyond the window is clamped", downtime: 30 * time.Hour, total: 24 * time.Hour, want: 0}, + {name: "zero total keeps 100", downtime: time.Hour, want: 100}, + {name: "rounds to five decimals", downtime: time.Second, total: 3 * time.Second, want: 66.66667}, + } + for _, tc := range tests { + t.Run(tc.name, func(t *testing.T) { + assert.Equal(t, tc.want, availabilityPercentage(tc.downtime, tc.total)) + }) + } +} + +func TestBuildMonthlyAvailability(t *testing.T) { now := time.Date(2026, time.November, 12, 15, 30, 0, 0, time.UTC) start := time.Date(now.Year(), now.Month(), 1, 0, 0, 0, 0, time.UTC).AddDate(0, -11, 0) months := availabilityMonths(start, now) @@ -109,31 +261,32 @@ func TestBuildMonthlyAvailability(t *testing.T) { stDate := time.Date(start.Year(), start.Month(), 21, 0, 0, 0, 0, time.UTC) endDate := time.Date(start.Year(), start.Month()+1, 2, 20, 0, 0, 0, time.UTC) - firstMonthDowntime := time.Date(stDate.Year(), stDate.Month()+1, 1, 0, 0, 0, 0, time.UTC).Sub(stDate).Hours() - secondMonthDowntime := endDate.Sub(time.Date(endDate.Year(), endDate.Month(), 1, 0, 0, 0, 0, time.UTC)).Hours() - downtime := map[availabilityMonth]float64{ - monthKey(stDate): firstMonthDowntime, - monthKey(endDate): secondMonthDowntime, - } + firstMonthDowntime := time.Date(stDate.Year(), stDate.Month()+1, 1, 0, 0, 0, 0, time.UTC).Sub(stDate) + secondMonthDowntime := endDate.Sub(time.Date(endDate.Year(), endDate.Month(), 1, 0, 0, 0, 0, time.UTC)) + intervals := []availabilityInterval{{start: stDate, end: endDate}} - calculateExpectedAvailability := func(downtimeHours, totalHours float64) float64 { - availability := fullPercentage - (downtimeHours / totalHours * fullPercentage) - return float64(int(availability*precisionFactor+roundFactor)) / precisionFactor + monthDuration := func(year int, month time.Month) time.Duration { + return time.Date(year, month+1, 1, 0, 0, 0, 0, time.UTC). + Sub(time.Date(year, month, 1, 0, 0, 0, 0, time.UTC)) + } + calculateExpectedAvailability := func(downtime, total time.Duration) float64 { + availability := 100 * (1 - downtime.Seconds()/total.Seconds()) + return math.Round(availability*100000) / 100000 } firstMonthAvailability := calculateExpectedAvailability( firstMonthDowntime, - hoursInMonth(stDate.Year(), int(stDate.Month())), + monthDuration(stDate.Year(), stDate.Month()), ) secondMonthAvailability := calculateExpectedAvailability( secondMonthDowntime, - hoursInMonth(endDate.Year(), int(endDate.Month())), + monthDuration(endDate.Year(), endDate.Month()), ) - result := buildMonthlyAvailability(months, downtime) + result := buildMonthlyAvailability(months, start, now, intervals) require.Len(t, result, 12) for _, item := range result { - want := fullPercentage + want := 100.0 switch { case item.Year == stDate.Year() && item.Month == int(stDate.Month()): want = firstMonthAvailability @@ -143,11 +296,45 @@ func TestBuildMonthlyAvailability(t *testing.T) { assert.InEpsilon(t, want, item.Percentage, 0.0001) } + t.Run("ongoing incident is clipped at the window end", func(t *testing.T) { + windowStart := time.Date(2026, time.January, 1, 0, 0, 0, 0, time.UTC) + windowEnd := windowStart.Add(15*24*time.Hour + 12*time.Hour) + incidentStart := windowStart.Add(9 * 24 * time.Hour) + ongoing := []availabilityInterval{{start: incidentStart, end: windowEnd}} + + result := buildMonthlyAvailability([]time.Time{windowStart}, windowStart, windowEnd, ongoing) + require.Len(t, result, 1) + want := calculateExpectedAvailability(windowEnd.Sub(incidentStart), windowEnd.Sub(windowStart)) + assert.InEpsilon(t, want, result[0].Percentage, 0.0001) + assert.Less(t, result[0].Percentage, 100.0) + }) + + t.Run("full window outage reports zero", func(t *testing.T) { + windowStart := time.Date(2026, time.January, 1, 12, 0, 0, 0, time.UTC) + windowEnd := windowStart.Add(24 * time.Hour) + full := []availabilityInterval{{start: windowStart, end: windowEnd}} + + result := buildMonthlyAvailability([]time.Time{windowStart}, windowStart, windowEnd, full) + require.Len(t, result, 1) + assert.Equal(t, 0.0, result[0].Percentage) + }) + + t.Run("zero-length month keeps 100", func(t *testing.T) { + month := time.Date(2026, time.May, 1, 0, 0, 0, 0, time.UTC) + + result := buildMonthlyAvailability([]time.Time{month}, month, month, nil) + require.Len(t, result, 1) + assert.Equal(t, 100.0, result[0].Percentage) + }) + t.Run("ignores downtime outside the window", func(t *testing.T) { - outside := map[availabilityMonth]float64{monthKey(start.AddDate(0, -1, 0)): 1000} + outside := []availabilityInterval{{ + start: start.AddDate(0, -1, 0), + end: start.AddDate(0, -1, 0).Add(time.Hour), + }} - for _, item := range buildMonthlyAvailability(months, outside) { - assert.InEpsilon(t, fullPercentage, item.Percentage, 0.0001) + for _, item := range buildMonthlyAvailability(months, start, now, outside) { + assert.InEpsilon(t, 100.0, item.Percentage, 0.0001) } }) } diff --git a/internal/db/availability.go b/internal/db/availability.go index 6672fa9..6313bac 100644 --- a/internal/db/availability.go +++ b/internal/db/availability.go @@ -5,77 +5,58 @@ import ( "time" ) -// componentDowntimeQuery aggregates impact-3 downtime per component and -// calendar month inside [start, end]. The month series is clipped to the window -// so an incident that crosses a boundary only contributes its in-window part. -const componentDowntimeQuery = ` -WITH months AS ( - SELECT generate_series( - date_trunc('month', $1::timestamp), - date_trunc('month', $2::timestamp), - interval '1 month' - ) AS month_start -) +// componentOutagesQuery returns impact-3 incident intervals clipped to the +// requested window. Overlaps are resolved in the API layer, so the query only +// clips boundaries and never aggregates. +const componentOutagesQuery = ` SELECT icr.component_id, - TO_CHAR(m.month_start, 'YYYY-MM') AS month_key, - SUM( - EXTRACT(EPOCH FROM ( - LEAST(i.end_date, m.month_start + interval '1 month', $2::timestamp) - - GREATEST(i.start_date, m.month_start, $1::timestamp) - )) / 3600.0 - )::double precision AS hours + GREATEST(i.start_date, $1::timestamp) AS outage_start, + LEAST(COALESCE(i.end_date, $2::timestamp), $2::timestamp) AS outage_end FROM incident i JOIN incident_component_relation icr ON icr.incident_id = i.id -CROSS JOIN months m WHERE i.impact = 3 - AND i.end_date IS NOT NULL + AND i.deleted_at IS NULL AND i.start_date < $2::timestamp - AND i.end_date > $1::timestamp - AND i.start_date < m.month_start + interval '1 month' - AND i.end_date > m.month_start -GROUP BY icr.component_id, m.month_start -ORDER BY icr.component_id, m.month_start` + AND COALESCE(i.end_date, $2::timestamp) > $1::timestamp + AND COALESCE(i.end_date, $2::timestamp) > i.start_date +ORDER BY icr.component_id, outage_start, outage_end` -// ComponentDowntime is the outage downtime one component accumulated in a -// calendar month of the requested availability window. -type ComponentDowntime struct { +// ComponentOutage is one impact-3 outage interval of a component, clipped to +// the requested availability window. End is the window end for ongoing +// incidents. +type ComponentOutage struct { ComponentID uint - Month time.Time - Hours float64 + Start time.Time + End time.Time } -// GetComponentDowntime aggregates outage downtime by component and month -// without loading the incident rows into the application. -func (db *DB) GetComponentDowntime( +// GetComponentOutages loads the outage intervals that intersect [start, end]. +func (db *DB) GetComponentOutages( ctx context.Context, start, end time.Time, -) ([]ComponentDowntime, error) { - rows, err := db.sql.QueryContext(ctx, componentDowntimeQuery, start, end) +) ([]ComponentOutage, error) { + rows, err := db.sql.QueryContext(ctx, componentOutagesQuery, start, end) if err != nil { return nil, err } defer rows.Close() - downtime := make([]ComponentDowntime, 0) + outages := make([]ComponentOutage, 0) for rows.Next() { var ( componentID int - monthKey string - hours float64 + startDate time.Time + endDate time.Time ) - if err = rows.Scan(&componentID, &monthKey, &hours); err != nil { + if err = rows.Scan(&componentID, &startDate, &endDate); err != nil { return nil, err } - month, parseErr := time.Parse("2006-01", monthKey) - if parseErr != nil { - return nil, parseErr - } - downtime = append(downtime, ComponentDowntime{ + outages = append(outages, ComponentOutage{ ComponentID: uint(componentID), - Month: month, - Hours: hours, + Start: startDate, + End: endDate, }) } - return downtime, rows.Err() + return outages, rows.Err() } diff --git a/internal/db/db.go b/internal/db/db.go index fb8262b..ae66af3 100644 --- a/internal/db/db.go +++ b/internal/db/db.go @@ -751,6 +751,7 @@ func (db *DB) GetComponentsAsMap(ctx context.Context) (map[int]*Component, error func (db *DB) GetComponentsWithValues(ctx context.Context) ([]Component, error) { rows, err := db.e.Component.Query(). WithAttributes(). + Order(component.ByID(entsql.OrderAsc())). All(ctx) if err != nil { return nil, err diff --git a/openapi.yaml b/openapi.yaml index a397d0a..cc79007 100644 --- a/openapi.yaml +++ b/openapi.yaml @@ -143,6 +143,8 @@ paths: type: array items: $ref: "#/components/schemas/ComponentAvailability" + window: + $ref: "#/components/schemas/AvailabilityWindow" "400": description: Invalid availability window. content: @@ -549,6 +551,24 @@ components: errMsg: type: string example: internal server error + AvailabilityWindow: + type: object + required: + - start + - end + - months + properties: + start: + type: string + format: date-time + example: "2025-12-01T00:00:00Z" + end: + type: string + format: date-time + example: "2026-11-12T15:30:45Z" + months: + type: integer + example: 12 ComponentAvailability: type: object required: @@ -585,7 +605,7 @@ components: percentage: type: number format: float - example: 99.999666 + example: 99.99967 Incidents: type: object properties: @@ -948,7 +968,7 @@ components: AvailabilityStartDate: name: start_date in: query - description: Start of the availability window (RFC3339 format). Defaults to the first day of the month 11 months before the end date. + description: Start of the availability window (RFC3339 format). Defaults to the first day of the month 11 months before the end date. The window may span at most 12 months of duration. required: false schema: type: string @@ -957,7 +977,7 @@ components: AvailabilityEndDate: name: end_date in: query - description: End of the availability window (RFC3339 format). Defaults to now. The window is capped at 12 months. + description: End of the availability window (RFC3339 format). Defaults to now and is capped at now. The window may span at most 12 months of duration. required: false schema: type: string diff --git a/tests/v2_test.go b/tests/v2_test.go index 699f621..7398a35 100644 --- a/tests/v2_test.go +++ b/tests/v2_test.go @@ -1563,6 +1563,239 @@ func TestV2GetComponentsAvailabilityWindow(t *testing.T) { }) } +func TestV2GetComponentsAvailabilityOngoingIncident(t *testing.T) { + truncateIncidents(t) + r := initTests(t) + + impact := 3 + system := false + now := time.Now().UTC() + start := now.Add(-48 * time.Hour) + + incData := v2.IncidentData{ + Title: "Ongoing outage", + Impact: &impact, + Components: []int{1}, + StartDate: start, + System: &system, + Type: event.TypeIncident, + } + + created := v2CreateIncident(t, r, &incData) + require.NotNil(t, created) + require.Len(t, created.Result, 1) + + stored := v2GetIncident(t, r, created.Result[0].IncidentID) + assert.Nil(t, stored.EndDate, "the incident must stay open") + + component := getAvailabilityComponent(t, r, 1, "") + require.NotEmpty(t, component.Availability) + + currentMonthFound := false + for _, month := range component.Availability { + if month.Year == now.Year() && month.Month == int(now.Month()) { + currentMonthFound = true + assert.Less(t, month.Percentage, 100.0, + "an ongoing outage must reduce the current month") + } + } + + // A request made exactly at a month boundary has no overlap with the new + // month; the month that contains the incident must still count it. + if !currentMonthFound { + assert.Less(t, percentageForMonth(t, component, start), 100.0) + } +} + +func TestV2GetComponentsAvailabilityIgnoresSoftDeletedIncident(t *testing.T) { + truncateIncidents(t) + r := initTests(t) + + impact := 3 + system := false + now := time.Now().UTC() + start := time.Date(now.Year(), now.Month(), 1, 0, 0, 0, 0, time.UTC).AddDate(0, -1, 0) + end := start.Add(48 * time.Hour) + + incData := v2.IncidentData{ + Title: "Soft-deleted outage", + Impact: &impact, + Components: []int{1}, + StartDate: start, + System: &system, + Type: event.TypeIncident, + } + + created := v2CreateIncident(t, r, &incData) + require.NotNil(t, created) + require.Len(t, created.Result, 1) + + incident := v2GetIncident(t, r, created.Result[0].IncidentID) + incident.EndDate = &end + v2PatchIncident(t, r, incident) + + before := getAvailabilityComponent(t, r, 1, "") + assert.Less(t, percentageForMonth(t, before, start), 100.0) + + sqlDB := openRawDB(t) + _, err := sqlDB.Exec("UPDATE incident SET deleted_at = now() WHERE id = $1", incident.ID) + require.NoError(t, err) + + after := getAvailabilityComponent(t, r, 1, "") + assert.InEpsilon(t, 100.0, percentageForMonth(t, after, start), 0.0001, + "a soft-deleted incident must not reduce availability") +} + +func TestV2GetComponentsAvailabilityMultiComponentIncident(t *testing.T) { + truncateIncidents(t) + r := initTests(t) + + impact := 3 + system := false + now := time.Now().UTC() + start := time.Date(now.Year(), now.Month(), 1, 0, 0, 0, 0, time.UTC).AddDate(0, -1, 0) + end := start.Add(48 * time.Hour) + + incData := v2.IncidentData{ + Title: "Outage on two components", + Impact: &impact, + Components: []int{1, 3}, + StartDate: start, + System: &system, + Type: event.TypeIncident, + } + + created := v2CreateIncident(t, r, &incData) + require.NotNil(t, created) + require.Len(t, created.Result, 2) + assert.Equal(t, created.Result[0].IncidentID, created.Result[1].IncidentID, + "both components belong to the same incident") + + incident := v2GetIncident(t, r, created.Result[0].IncidentID) + incident.EndDate = &end + v2PatchIncident(t, r, incident) + + for _, componentID := range []int{1, 3} { + component := getAvailabilityComponent(t, r, componentID, "") + assert.Less(t, percentageForMonth(t, component, start), 100.0, + "component %d must count the shared incident", componentID) + } + + unaffected := getAvailabilityComponent(t, r, 2, "") + assert.InEpsilon(t, 100.0, percentageForMonth(t, unaffected, start), 0.0001, + "an unaffected component must stay at 100%%") +} + +func TestV2GetComponentsAvailabilityWindowResponse(t *testing.T) { + truncateIncidents(t) + r := initTests(t) + + type availabilityResponse struct { + Data []v2.ComponentAvailability `json:"data"` + Window v2.AvailabilityWindow `json:"window"` + } + + get := func(t *testing.T, query string) availabilityResponse { + t.Helper() + + w := httptest.NewRecorder() + req, _ := http.NewRequest(http.MethodGet, v2AvailabilityEndpoint+query, nil) + r.ServeHTTP(w, req) + require.Equal(t, http.StatusOK, w.Code, w.Body.String()) + + var response availabilityResponse + require.NoError(t, json.Unmarshal(w.Body.Bytes(), &response)) + require.NotEmpty(t, response.Data) + + return response + } + + t.Run("default window is exposed", func(t *testing.T) { + before := time.Now().UTC() + response := get(t, "") + + assert.True(t, response.Window.Start.Before(response.Window.End)) + assert.False(t, response.Window.End.After(time.Now().UTC()), "window end must not be in the future") + assert.Zero(t, response.Window.End.Nanosecond(), "window end is truncated to seconds") + assert.Equal(t, len(response.Data[0].Availability), response.Window.Months) + + wantStart := time.Date(response.Window.End.Year(), response.Window.End.Month(), 1, + 0, 0, 0, 0, time.UTC).AddDate(0, -11, 0) + assert.True(t, wantStart.Equal(response.Window.Start), + "unexpected default start: %v", response.Window.Start) + assert.False(t, response.Window.Start.After(before)) + }) + + t.Run("future end is capped", func(t *testing.T) { + future := time.Now().UTC().AddDate(0, 2, 0) + response := get(t, "?end_date="+future.Format(time.RFC3339)) + + assert.False(t, response.Window.End.After(time.Now().UTC())) + assert.True(t, response.Window.End.Before(future)) + }) + + t.Run("twelve months of duration are accepted", func(t *testing.T) { + now := time.Now().UTC() + end := time.Date(now.Year(), now.Month(), 1, 12, 0, 0, 0, time.UTC).AddDate(0, -1, 0) + start := end.AddDate(-1, 0, 0) + query := fmt.Sprintf("?start_date=%s&end_date=%s", + start.Format(time.RFC3339), end.Format(time.RFC3339)) + + response := get(t, query) + assert.True(t, start.Equal(response.Window.Start)) + assert.True(t, end.Equal(response.Window.End)) + assert.Equal(t, 13, response.Window.Months, + "a year-long window touches 13 calendar labels") + }) + + t.Run("one day over twelve months is rejected", func(t *testing.T) { + now := time.Now().UTC() + end := time.Date(now.Year(), now.Month(), 1, 12, 0, 0, 0, time.UTC).AddDate(0, -1, 0) + start := end.AddDate(-1, 0, -1) + query := fmt.Sprintf("?start_date=%s&end_date=%s", + start.Format(time.RFC3339), end.Format(time.RFC3339)) + + w := httptest.NewRecorder() + req, _ := http.NewRequest(http.MethodGet, v2AvailabilityEndpoint+query, nil) + r.ServeHTTP(w, req) + assert.Equal(t, http.StatusBadRequest, w.Code) + }) +} + +func TestV2GetComponentsAvailabilityOrder(t *testing.T) { + truncateIncidents(t) + r := initTests(t) + + w := httptest.NewRecorder() + req, _ := http.NewRequest(http.MethodGet, v2AvailabilityEndpoint, nil) + r.ServeHTTP(w, req) + require.Equal(t, http.StatusOK, w.Code) + + var response struct { + Data []v2.ComponentAvailability `json:"data"` + } + require.NoError(t, json.Unmarshal(w.Body.Bytes(), &response)) + require.NotEmpty(t, response.Data) + + for i := 1; i < len(response.Data); i++ { + assert.Less(t, response.Data[i-1].ID, response.Data[i].ID, + "components must be ordered by id") + } +} + +func percentageForMonth(t *testing.T, compAvail v2.ComponentAvailability, month time.Time) float64 { + t.Helper() + + for _, item := range compAvail.Availability { + if item.Year == month.Year() && item.Month == int(month.Month()) { + return item.Percentage + } + } + + t.Fatalf("month %d-%02d is missing from component %d", month.Year(), month.Month(), compAvail.ID) + return 0 +} + func getAvailabilityComponent(t *testing.T, r *gin.Engine, componentID int, query string) v2.ComponentAvailability { t.Helper() From 9b05a345aea3f4dd40194be4e973b5c527dff5b1 Mon Sep 17 00:00:00 2001 From: Aloento <11802769+Aloento@users.noreply.github.com> Date: Tue, 1 Dec 2026 12:46:36 +0100 Subject: [PATCH 2/3] [Fix] Resolve availability test lint findings --- internal/api/v2/v2_test.go | 22 +++++++++++----------- 1 file changed, 11 insertions(+), 11 deletions(-) diff --git a/internal/api/v2/v2_test.go b/internal/api/v2/v2_test.go index d8399ae..89c9d25 100644 --- a/internal/api/v2/v2_test.go +++ b/internal/api/v2/v2_test.go @@ -248,7 +248,7 @@ func TestAvailabilityPercentage(t *testing.T) { for _, tc := range tests { t.Run(tc.name, func(t *testing.T) { - assert.Equal(t, tc.want, availabilityPercentage(tc.downtime, tc.total)) + assert.InDelta(t, tc.want, availabilityPercentage(tc.downtime, tc.total), 0.000001) }) } } @@ -302,11 +302,11 @@ func TestBuildMonthlyAvailability(t *testing.T) { incidentStart := windowStart.Add(9 * 24 * time.Hour) ongoing := []availabilityInterval{{start: incidentStart, end: windowEnd}} - result := buildMonthlyAvailability([]time.Time{windowStart}, windowStart, windowEnd, ongoing) - require.Len(t, result, 1) + monthly := buildMonthlyAvailability([]time.Time{windowStart}, windowStart, windowEnd, ongoing) + require.Len(t, monthly, 1) want := calculateExpectedAvailability(windowEnd.Sub(incidentStart), windowEnd.Sub(windowStart)) - assert.InEpsilon(t, want, result[0].Percentage, 0.0001) - assert.Less(t, result[0].Percentage, 100.0) + assert.InEpsilon(t, want, monthly[0].Percentage, 0.0001) + assert.Less(t, monthly[0].Percentage, 100.0) }) t.Run("full window outage reports zero", func(t *testing.T) { @@ -314,17 +314,17 @@ func TestBuildMonthlyAvailability(t *testing.T) { windowEnd := windowStart.Add(24 * time.Hour) full := []availabilityInterval{{start: windowStart, end: windowEnd}} - result := buildMonthlyAvailability([]time.Time{windowStart}, windowStart, windowEnd, full) - require.Len(t, result, 1) - assert.Equal(t, 0.0, result[0].Percentage) + monthly := buildMonthlyAvailability([]time.Time{windowStart}, windowStart, windowEnd, full) + require.Len(t, monthly, 1) + assert.InDelta(t, 0.0, monthly[0].Percentage, 0.000001) }) t.Run("zero-length month keeps 100", func(t *testing.T) { month := time.Date(2026, time.May, 1, 0, 0, 0, 0, time.UTC) - result := buildMonthlyAvailability([]time.Time{month}, month, month, nil) - require.Len(t, result, 1) - assert.Equal(t, 100.0, result[0].Percentage) + monthly := buildMonthlyAvailability([]time.Time{month}, month, month, nil) + require.Len(t, monthly, 1) + assert.InDelta(t, 100.0, monthly[0].Percentage, 0.000001) }) t.Run("ignores downtime outside the window", func(t *testing.T) { From 35e4dfde40863fb86981bdf3ce4a246ddd52699e Mon Sep 17 00:00:00 2001 From: Aloento <11802769+Aloento@users.noreply.github.com> Date: Tue, 1 Dec 2026 12:49:41 +0100 Subject: [PATCH 3/3] [Docs] Clarify availability month-label boundary --- docs/events.md | 4 +++- openapi.yaml | 4 ++-- 2 files changed, 5 insertions(+), 3 deletions(-) diff --git a/docs/events.md b/docs/events.md index b85b2b3..eed39b2 100644 --- a/docs/events.md +++ b/docs/events.md @@ -222,7 +222,9 @@ time. The denominator of a month is the part of that month inside the window: th 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). Every component +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 diff --git a/openapi.yaml b/openapi.yaml index cc79007..287a705 100644 --- a/openapi.yaml +++ b/openapi.yaml @@ -968,7 +968,7 @@ components: AvailabilityStartDate: name: start_date in: query - description: Start of the availability window (RFC3339 format). Defaults to the first day of the month 11 months before the end date. The window may span at most 12 months of duration. + description: Start of the availability window (RFC3339 format). Defaults to the first day of the month 11 months before the end date. The window may span at most 12 months of duration, so up to 13 calendar month labels. required: false schema: type: string @@ -977,7 +977,7 @@ components: AvailabilityEndDate: name: end_date in: query - description: End of the availability window (RFC3339 format). Defaults to now and is capped at now. The window may span at most 12 months of duration. + description: End of the availability window (RFC3339 format). Defaults to now and is capped at now. The window may span at most 12 months of duration, so up to 13 calendar month labels. required: false schema: type: string