diff --git a/docs/events.md b/docs/events.md index eed39b2..d2d76eb 100644 --- a/docs/events.md +++ b/docs/events.md @@ -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 diff --git a/internal/api/routes.go b/internal/api/routes.go index b9479e8..1a456b4 100644 --- a/internal/api/routes.go +++ b/internal/api/routes.go @@ -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", diff --git a/internal/api/v2/availability_summary.go b/internal/api/v2/availability_summary.go new file mode 100644 index 0000000..9331b79 --- /dev/null +++ b/internal/api/v2/availability_summary.go @@ -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, + } +} diff --git a/internal/api/v2/availability_summary_test.go b/internal/api/v2/availability_summary_test.go new file mode 100644 index 0000000..d9210e4 --- /dev/null +++ b/internal/api/v2/availability_summary_test.go @@ -0,0 +1,328 @@ +package v2 + +import ( + "testing" + "time" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/stackmon/otc-status-dashboard/internal/db" +) + +func summaryTestComponent(id uint, createdAt, deletedAt *time.Time) db.Component { + return db.Component{ + ID: id, + Name: "component", + CreatedAt: createdAt, + DeletedAt: deletedAt, + } +} + +func timePointer(value time.Time) *time.Time { + return &value +} + +func assertMonthsNewestFirst(t *testing.T, months []MonthlyAvailability) { + t.Helper() + + for i := 1; i < len(months); i++ { + newer, older := months[i-1], months[i] + assert.True(t, + newer.Year > older.Year || (newer.Year == older.Year && newer.Month > older.Month), + "month %d-%02d must come after %d-%02d", + newer.Year, newer.Month, older.Year, older.Month, + ) + } +} + +func TestAvailabilitySummaryWindow(t *testing.T) { + t.Run("trailing six months ending with the current one", func(t *testing.T) { + now := time.Date(2026, time.November, 12, 15, 30, 45, 123456789, time.UTC) + + start, end := availabilitySummaryWindow(now) + + assert.Equal(t, time.Date(2026, time.June, 1, 0, 0, 0, 0, time.UTC), start) + assert.Equal(t, now.Truncate(time.Second), end) + assert.Zero(t, end.Nanosecond(), "window end is truncated to seconds") + + months := summaryMonths(end) + require.Len(t, months, availabilitySummaryWindowMonths) + assert.Equal(t, time.Date(2026, time.November, 1, 0, 0, 0, 0, time.UTC), months[0]) + assert.Equal(t, time.Date(2026, time.June, 1, 0, 0, 0, 0, time.UTC), months[5]) + assertMonthsNewestFirst(t, monthlyAvailabilityFromMonths(months)) + }) + + t.Run("window crosses the year boundary", func(t *testing.T) { + now := time.Date(2026, time.January, 15, 0, 0, 0, 0, time.UTC) + + start, end := availabilitySummaryWindow(now) + + assert.Equal(t, time.Date(2025, time.August, 1, 0, 0, 0, 0, time.UTC), start) + assert.Equal(t, now, end) + + months := summaryMonths(end) + require.Len(t, months, 6) + assert.Equal(t, time.Date(2026, time.January, 1, 0, 0, 0, 0, time.UTC), months[0]) + assert.Equal(t, time.Date(2025, time.August, 1, 0, 0, 0, 0, time.UTC), months[5]) + }) + + t.Run("exactly the first instant of a month still has six labels", func(t *testing.T) { + now := time.Date(2026, time.December, 1, 0, 0, 0, 0, time.UTC) + start, end := availabilitySummaryWindow(now) + + summary := buildAvailabilitySummary( + []db.Component{summaryTestComponent(1, nil, nil)}, nil, start, end, + ) + + require.Len(t, summary.Monthly, 6, "the summary always reports six months") + assert.Equal(t, 2026, summary.Monthly[0].Year) + assert.Equal(t, int(time.December), summary.Monthly[0].Month) + assert.InDelta(t, 100.0, summary.Monthly[0].Percentage, 0.000001, + "the current month has a zero denominator at its first instant") + assert.InDelta(t, 100.0, summary.Percentage, 0.000001) + assert.Equal(t, 6, summary.Window.Months) + }) +} + +// monthlyAvailabilityFromMonths keeps the ordering assertions readable while +// reusing the month label shape of the response. +func monthlyAvailabilityFromMonths(months []time.Time) []MonthlyAvailability { + monthly := make([]MonthlyAvailability, len(months)) + for i, month := range months { + monthly[i] = MonthlyAvailability{Year: month.Year(), Month: int(month.Month())} + } + return monthly +} + +func TestComponentActiveInMonth(t *testing.T) { + monthEnd := time.Date(2026, time.December, 1, 0, 0, 0, 0, time.UTC) + duringMonth := time.Date(2026, time.November, 10, 9, 0, 0, 0, time.UTC) + beforeMonth := time.Date(2026, time.October, 31, 9, 0, 0, 0, time.UTC) + afterMonthEnd := monthEnd.Add(time.Hour) + + tests := []struct { + name string + createdAt *time.Time + deletedAt *time.Time + want bool + }{ + { + name: "legacy component without lifecycle timestamps stays active", + want: true, + }, + { + name: "created before the month is active", + createdAt: timePointer(beforeMonth), + want: true, + }, + { + name: "created during the month counts for the whole month", + createdAt: timePointer(duringMonth), + want: true, + }, + { + name: "created exactly at month end is not active yet", + createdAt: timePointer(monthEnd), + want: false, + }, + { + name: "created after month end is not active", + createdAt: timePointer(afterMonthEnd), + want: false, + }, + { + name: "deleted during the month is excluded from the whole month", + deletedAt: timePointer(duringMonth), + want: false, + }, + { + name: "deleted at month end survived the whole month", + deletedAt: timePointer(monthEnd), + want: true, + }, + { + name: "deleted before the month is not active", + deletedAt: timePointer(beforeMonth), + want: false, + }, + } + + for _, tc := range tests { + t.Run(tc.name, func(t *testing.T) { + comp := summaryTestComponent(1, tc.createdAt, tc.deletedAt) + assert.Equal(t, tc.want, componentActiveInMonth(comp, monthEnd)) + }) + } +} + +func TestBuildAvailabilitySummaryEmpty(t *testing.T) { + end := time.Date(2026, time.June, 15, 12, 0, 0, 0, time.UTC) + start := time.Date(2026, time.January, 1, 0, 0, 0, 0, time.UTC) + + summary := buildAvailabilitySummary(nil, nil, start, end) + + assert.Equal(t, AvailabilityWindow{Start: start, End: end, Months: 6}, summary.Window) + assert.InDelta(t, 100.0, summary.Percentage, 0.000001) + assert.Zero(t, summary.ComponentsTotal) + assert.Zero(t, summary.ComponentsAffected) + require.Len(t, summary.Monthly, 6) + assertMonthsNewestFirst(t, summary.Monthly) + + for _, month := range summary.Monthly { + assert.InDelta(t, 100.0, month.Percentage, 0.000001) + } +} + +func TestBuildAvailabilitySummaryLifecycle(t *testing.T) { + end := time.Date(2026, time.June, 15, 12, 0, 0, 0, time.UTC) + start := time.Date(2026, time.January, 1, 0, 0, 0, 0, time.UTC) + + created := time.Date(2026, time.April, 10, 9, 0, 0, 0, time.UTC) + deleted := time.Date(2026, time.May, 10, 9, 0, 0, 0, time.UTC) + + components := []db.Component{ + summaryTestComponent(1, &created, nil), + summaryTestComponent(2, nil, &deleted), + } + outages := []db.ComponentOutage{{ + ComponentID: 1, + Start: time.Date(2026, time.April, 1, 0, 0, 0, 0, time.UTC), + End: time.Date(2026, time.April, 16, 0, 0, 0, 0, time.UTC), + }} + + summary := buildAvailabilitySummary(components, outages, start, end) + + require.Len(t, summary.Monthly, 6) + assertMonthsNewestFirst(t, summary.Monthly) + + percentages := map[string]float64{} + for _, month := range summary.Monthly { + percentages[time.Month(month.Month).String()] = month.Percentage + } + + // June: only component 1 is active; half a month of window, no outage. + assert.InDelta(t, 100.0, percentages["June"], 0.000001) + // May: component 2 was deleted during May, so it contributes to no part of + // that month; only component 1 remains. + assert.InDelta(t, 100.0, percentages["May"], 0.000001) + // April: both components count for the whole month, although component 1 + // was created mid-month. 15 days of downtime over 2 * 30 days. + assert.InDelta(t, 75.0, percentages["April"], 0.000001) + assert.InDelta(t, 100.0, percentages["March"], 0.000001) + assert.InDelta(t, 100.0, percentages["February"], 0.000001) + assert.InDelta(t, 100.0, percentages["January"], 0.000001) + + assert.Equal(t, 2, summary.ComponentsTotal) + assert.Equal(t, 1, summary.ComponentsAffected) + + // Overall availability is weighted by component-time, not by averaging the + // monthly percentages: 15 days of downtime over 195.5 component-days. + assert.InEpsilon(t, 92.32737, summary.Percentage, 0.00001) +} + +func TestBuildAvailabilitySummaryDeletionDropsMonthDowntime(t *testing.T) { + end := time.Date(2026, time.June, 15, 0, 0, 0, 0, time.UTC) + start := time.Date(2026, time.January, 1, 0, 0, 0, 0, time.UTC) + + created := time.Date(2026, time.January, 1, 0, 0, 0, 0, time.UTC) + deleted := time.Date(2026, time.May, 10, 9, 0, 0, 0, time.UTC) + + components := []db.Component{ + // Deleted mid-May: excluded from all of May, including its outage. + summaryTestComponent(1, &created, &deleted), + summaryTestComponent(2, nil, nil), + } + outages := []db.ComponentOutage{{ + ComponentID: 1, + Start: time.Date(2026, time.May, 1, 0, 0, 0, 0, time.UTC), + End: time.Date(2026, time.May, 20, 0, 0, 0, 0, time.UTC), + }} + + summary := buildAvailabilitySummary(components, outages, start, end) + + for _, month := range summary.Monthly { + assert.InDelta(t, 100.0, month.Percentage, 0.000001, + "month %d-%02d must stay at 100", month.Year, month.Month) + } + assert.Equal(t, 2, summary.ComponentsTotal, "component 1 is still active in earlier months") + assert.Zero(t, summary.ComponentsAffected) +} + +func TestBuildAvailabilitySummaryMergesOverlappingOutages(t *testing.T) { + end := time.Date(2026, time.July, 1, 0, 0, 0, 0, time.UTC) + start := time.Date(2026, time.February, 1, 0, 0, 0, 0, time.UTC) + + components := []db.Component{summaryTestComponent(1, nil, nil)} + outages := []db.ComponentOutage{ + { + ComponentID: 1, + Start: time.Date(2026, time.June, 1, 0, 0, 0, 0, time.UTC), + End: time.Date(2026, time.June, 10, 0, 0, 0, 0, time.UTC), + }, + { + ComponentID: 1, + Start: time.Date(2026, time.June, 5, 0, 0, 0, 0, time.UTC), + End: time.Date(2026, time.June, 20, 0, 0, 0, 0, time.UTC), + }, + } + + summary := buildAvailabilitySummary(components, outages, start, end) + + require.Len(t, summary.Monthly, 6) + assert.Equal(t, int(time.July), summary.Monthly[0].Month) + assert.InDelta(t, 100.0, summary.Monthly[0].Percentage, 0.000001, + "the zero-length current month keeps 100") + + june := summary.Monthly[1] + require.Equal(t, int(time.June), june.Month) + // The union is 19 days, not the 24 days obtained by summing the rows. + assert.InEpsilon(t, 36.66667, june.Percentage, 0.00001) + + for _, month := range summary.Monthly[2:] { + assert.InDelta(t, 100.0, month.Percentage, 0.000001) + } + + assert.Equal(t, 1, summary.ComponentsTotal) + assert.Equal(t, 1, summary.ComponentsAffected) +} + +func TestBuildAvailabilitySummaryOverallUsesRawDurations(t *testing.T) { + end := time.Date(2026, time.June, 16, 0, 0, 0, 0, time.UTC) + start := time.Date(2026, time.January, 1, 0, 0, 0, 0, time.UTC) + + components := []db.Component{summaryTestComponent(1, nil, nil)} + outages := []db.ComponentOutage{{ + ComponentID: 1, + Start: time.Date(2026, time.May, 1, 0, 0, 0, 0, time.UTC), + End: time.Date(2026, time.May, 16, 12, 0, 0, 0, time.UTC), + }} + + summary := buildAvailabilitySummary(components, outages, start, end) + + require.Len(t, summary.Monthly, 6) + assert.InDelta(t, 100.0, summary.Monthly[0].Percentage, 0.000001, "June is unaffected") + assert.InDelta(t, 50.0, summary.Monthly[1].Percentage, 0.000001, + "May has 15.5 days of downtime over a 31-day month") + + // 15.5 days over 166 component-days. Averaging the monthly percentages + // would produce 75, which the weighted calculation must not do. + assert.InEpsilon(t, 90.66265, summary.Percentage, 0.00001) + assert.NotEqual(t, 75.0, summary.Percentage) +} + +func TestBuildAvailabilitySummaryComponentWithoutIncidents(t *testing.T) { + end := time.Date(2026, time.June, 15, 0, 0, 0, 0, time.UTC) + start := time.Date(2026, time.January, 1, 0, 0, 0, 0, time.UTC) + + summary := buildAvailabilitySummary( + []db.Component{summaryTestComponent(1, nil, nil)}, nil, start, end, + ) + + for _, month := range summary.Monthly { + assert.InDelta(t, 100.0, month.Percentage, 0.000001) + } + assert.Equal(t, 1, summary.ComponentsTotal) + assert.Zero(t, summary.ComponentsAffected) + assert.InDelta(t, 100.0, summary.Percentage, 0.000001) +} diff --git a/openapi.yaml b/openapi.yaml index 287a705..d1ff5ae 100644 --- a/openapi.yaml +++ b/openapi.yaml @@ -151,6 +151,36 @@ paths: application/json: schema: $ref: "#/components/schemas/BadRequestGeneralError" + /v2/availability/summary: + get: + summary: Get platform availability summary. + description: | + Platform-level availability over the trailing six calendar months, including the + current partial month. The public endpoint has no query parameters and never changes + the per-component `GET /v2/availability` response. + + Only incidents with an impact of exactly `3` (outage) contribute. 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 first, and an incident linked to + several components counts for each of them. + + A component that exists during a month contributes to that whole month, even when it + was created during that month. A component deleted during a month is excluded from + that month entirely. The denominator of a month is the number of active components + multiplied by the overlap of the month with the window; the current month is partial. + + The overall `percentage` is computed from the raw duration sums, not by averaging the + rounded monthly percentages, and is rounded to five decimals. With no components both + counters are zero and every percentage is `100`. + tags: + - availability + responses: + "200": + description: Successful operation. + content: + application/json: + schema: + $ref: "#/components/schemas/AvailabilitySummary" /v2/incidents: get: deprecated: true @@ -569,6 +599,56 @@ components: months: type: integer example: 12 + AvailabilitySummary: + type: object + required: + - window + - percentage + - components_total + - components_affected + - monthly + properties: + window: + description: Effective window; `months` is always 6 for this endpoint. + $ref: "#/components/schemas/AvailabilityWindow" + percentage: + type: number + format: double + description: Overall availability from the raw duration sums, rounded to five decimals. + example: 99.12345 + components_total: + type: integer + description: Distinct components active in at least one reported month. + example: 3 + components_affected: + type: integer + description: Distinct active components with any downtime in a month where they are active. + example: 1 + monthly: + type: array + description: Exactly six calendar months, newest first. + items: + $ref: "#/components/schemas/AvailabilitySummaryMonth" + AvailabilitySummaryMonth: + type: object + required: + - year + - month + - percentage + properties: + year: + type: integer + example: 2026 + month: + type: integer + minimum: 1 + maximum: 12 + example: 11 + percentage: + type: number + format: double + description: Availability for the month; 100 when the month has a zero denominator. + example: 99.5 ComponentAvailability: type: object required: diff --git a/tests/availability_summary_test.go b/tests/availability_summary_test.go new file mode 100644 index 0000000..da5a0c0 --- /dev/null +++ b/tests/availability_summary_test.go @@ -0,0 +1,65 @@ +package tests + +import ( + "encoding/json" + "fmt" + "net/http" + "net/http/httptest" + "testing" + "time" + + "github.com/gin-gonic/gin" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + v2 "github.com/stackmon/otc-status-dashboard/internal/api/v2" +) + +func getAvailabilitySummary(t *testing.T, r *gin.Engine) v2.AvailabilitySummary { + t.Helper() + + w := httptest.NewRecorder() + req, _ := http.NewRequest(http.MethodGet, v2AvailabilitySummaryEndpoint, nil) + r.ServeHTTP(w, req) + require.Equal(t, http.StatusOK, w.Code, w.Body.String()) + + var summary v2.AvailabilitySummary + require.NoError(t, json.Unmarshal(w.Body.Bytes(), &summary)) + + return summary +} + +// TestV2AvailabilitySummaryIncludesSoftDeletedComponents pins the lifecycle +// contract to the database boundary: GetComponentsWithValues must return +// soft-deleted components. A component deleted during the current month is +// inactive only for the current month; the earlier months of the six-month +// window must still count it. If the query starts filtering deleted_at, the +// component disappears entirely and the count no longer grows. +func TestV2AvailabilitySummaryIncludesSoftDeletedComponents(t *testing.T) { + truncateIncidents(t) + r := initTests(t) + + before := getAvailabilitySummary(t, r) + + sqlDB := openRawDB(t) + + now := time.Now().UTC() + createdAt := now.AddDate(0, -3, 0) + name := fmt.Sprintf("summary-soft-deleted-%d", now.UnixNano()) + + var id int + require.NoError(t, sqlDB.QueryRow( + `INSERT INTO component (name, created_at, modified_at, deleted_at) + VALUES ($1, $2, $3, $4) RETURNING id`, + name, createdAt, now, now, + ).Scan(&id)) + t.Cleanup(func() { + _, err := sqlDB.Exec(`DELETE FROM component WHERE id = $1`, id) + require.NoError(t, err) + }) + + after := getAvailabilitySummary(t, r) + + assert.Equal(t, before.ComponentsTotal+1, after.ComponentsTotal, + "a component soft-deleted during the current month must still count for earlier months") +} diff --git a/tests/main_test.go b/tests/main_test.go index 2fb0bfd..134db1c 100644 --- a/tests/main_test.go +++ b/tests/main_test.go @@ -235,6 +235,7 @@ func initRoutesV2(t *testing.T, c *gin.Engine, dbInst *db.DB, authn *auth.Provid v2.PatchEventUpdateTextHandler(dbInst, logger)) v2Api.GET("availability", v2.GetComponentsAvailabilityHandler(dbInst, logger)) + v2Api.GET("availability/summary", v2.GetAvailabilitySummaryHandler(dbInst, logger)) } func truncateIncidents(t *testing.T) { diff --git a/tests/v2_test.go b/tests/v2_test.go index 7398a35..e365590 100644 --- a/tests/v2_test.go +++ b/tests/v2_test.go @@ -20,9 +20,10 @@ import ( ) const ( - v2IncidentsEndpoint = "/v2/incidents" - v2AvailabilityEndpoint = "/v2/availability" - v2EventsEndpoint = "/v2/events" + v2IncidentsEndpoint = "/v2/incidents" + v2AvailabilityEndpoint = "/v2/availability" + v2AvailabilitySummaryEndpoint = "/v2/availability/summary" + v2EventsEndpoint = "/v2/events" ) // V2IncidentsListResponse defines the expected structure for the GET /v2/incidents endpoint. @@ -1820,6 +1821,71 @@ func getAvailabilityComponent(t *testing.T, r *gin.Engine, componentID int, quer return v2.ComponentAvailability{} } +func TestV2GetAvailabilitySummary(t *testing.T) { + truncateIncidents(t) + t.Logf("start to test GET %s", v2AvailabilitySummaryEndpoint) + r := initTests(t) + + impact := 3 + system := false + now := time.Now().UTC() + + // The previous calendar month is inside the six-month window and is + // reported as a complete month. + affectedMonth := time.Date(now.Year(), now.Month(), 1, 0, 0, 0, 0, time.UTC).AddDate(0, -1, 0) + incidentEnd := affectedMonth.Add(48 * time.Hour) + + incData := v2.IncidentData{ + Title: "Availability summary outage on two components", + Impact: &impact, + Components: []int{1, 3}, + StartDate: affectedMonth, + System: &system, + Type: event.TypeIncident, + } + + created := v2CreateIncident(t, r, &incData) + require.NotNil(t, created) + require.Len(t, created.Result, 2) + + incident := v2GetIncident(t, r, created.Result[0].IncidentID) + incident.EndDate = &incidentEnd + v2PatchIncident(t, r, incident) + + w := httptest.NewRecorder() + req, _ := http.NewRequest(http.MethodGet, v2AvailabilitySummaryEndpoint, nil) + r.ServeHTTP(w, req) + require.Equal(t, http.StatusOK, w.Code, w.Body.String()) + + var summary v2.AvailabilitySummary + require.NoError(t, json.Unmarshal(w.Body.Bytes(), &summary)) + + require.Len(t, summary.Monthly, 6, "the summary always reports six months") + assert.Equal(t, 6, summary.Window.Months) + assert.False(t, summary.Window.End.After(time.Now().UTC()), "window end must not be in the future") + assert.GreaterOrEqual(t, summary.ComponentsAffected, 2) + assert.GreaterOrEqual(t, summary.ComponentsTotal, summary.ComponentsAffected) + assert.Less(t, summary.Percentage, 100.0) + + for i := 1; i < len(summary.Monthly); i++ { + newer, older := summary.Monthly[i-1], summary.Monthly[i] + assert.True(t, + newer.Year > older.Year || (newer.Year == older.Year && newer.Month > older.Month), + "monthly entries must be newest first", + ) + } + + foundAffectedMonth := false + for _, month := range summary.Monthly { + if month.Year == affectedMonth.Year() && month.Month == int(affectedMonth.Month()) { + foundAffectedMonth = true + assert.Less(t, month.Percentage, 100.0, + "a month with an impact-3 incident on two components must be below 100%%") + } + } + assert.True(t, foundAffectedMonth, "the affected month must be present") +} + func TestV2PatchIncidentUpdateHandler(t *testing.T) { t.Log("start to test PATCH /v2/incidents/:incidentID/updates/:updateID") r := initTests(t)