@oneuptime/common 11.6.2 → 11.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (37) hide show
  1. package/Models/AnalyticsModels/SloHistory.ts +6 -3
  2. package/Models/DatabaseModels/ServiceLevelObjective.ts +9 -0
  3. package/Server/Infrastructure/Postgres/SchemaMigrations/1785066759532-MigrationName.ts +30 -0
  4. package/Server/Infrastructure/Postgres/SchemaMigrations/Index.ts +2 -0
  5. package/Server/Services/ServiceLevelObjectiveService.ts +12 -4
  6. package/Tests/Server/Services/ServiceLevelObjectiveService.test.ts +2 -2
  7. package/Tests/Types/Monitor/MonitorCriteria.test.ts +155 -0
  8. package/Tests/Types/Monitor/MonitorCriteriaInstance.test.ts +465 -0
  9. package/Tests/Types/Monitor/MonitorStep.test.ts +183 -0
  10. package/Tests/Types/Monitor/MonitorSteps.test.ts +183 -0
  11. package/Tests/Utils/Memory.test.ts +44 -0
  12. package/Tests/Utils/Slo/SloBurnRateRuleState.test.ts +124 -0
  13. package/Tests/Utils/Slo/SloDuration.test.ts +148 -0
  14. package/Tests/Utils/Slo/SloHealth.test.ts +334 -0
  15. package/Utils/Slo/SloBurnRateRuleState.ts +91 -0
  16. package/Utils/Slo/SloDuration.ts +165 -0
  17. package/Utils/Slo/SloEvaluation.ts +22 -0
  18. package/Utils/Slo/SloHealth.ts +302 -0
  19. package/build/dist/Models/AnalyticsModels/SloHistory.js +6 -3
  20. package/build/dist/Models/AnalyticsModels/SloHistory.js.map +1 -1
  21. package/build/dist/Models/DatabaseModels/ServiceLevelObjective.js +11 -1
  22. package/build/dist/Models/DatabaseModels/ServiceLevelObjective.js.map +1 -1
  23. package/build/dist/Server/Infrastructure/Postgres/SchemaMigrations/1785066759532-MigrationName.js +21 -0
  24. package/build/dist/Server/Infrastructure/Postgres/SchemaMigrations/1785066759532-MigrationName.js.map +1 -0
  25. package/build/dist/Server/Infrastructure/Postgres/SchemaMigrations/Index.js +2 -0
  26. package/build/dist/Server/Infrastructure/Postgres/SchemaMigrations/Index.js.map +1 -1
  27. package/build/dist/Server/Services/ServiceLevelObjectiveService.js +10 -4
  28. package/build/dist/Server/Services/ServiceLevelObjectiveService.js.map +1 -1
  29. package/build/dist/Utils/Slo/SloBurnRateRuleState.js +35 -0
  30. package/build/dist/Utils/Slo/SloBurnRateRuleState.js.map +1 -0
  31. package/build/dist/Utils/Slo/SloDuration.js +87 -0
  32. package/build/dist/Utils/Slo/SloDuration.js.map +1 -0
  33. package/build/dist/Utils/Slo/SloEvaluation.js +21 -0
  34. package/build/dist/Utils/Slo/SloEvaluation.js.map +1 -0
  35. package/build/dist/Utils/Slo/SloHealth.js +179 -0
  36. package/build/dist/Utils/Slo/SloHealth.js.map +1 -0
  37. package/package.json +1 -1
@@ -0,0 +1,334 @@
1
+ import SliType from "../../../Types/ServiceLevelObjective/SliType";
2
+ import SloMultiMonitorMode from "../../../Types/ServiceLevelObjective/SloMultiMonitorMode";
3
+ import SloStatus from "../../../Types/ServiceLevelObjective/SloStatus";
4
+ import SloWindowType from "../../../Types/ServiceLevelObjective/SloWindowType";
5
+ import {
6
+ DEFAULT_AT_RISK_THRESHOLD_PERCENTAGE,
7
+ getSloBudgetTier,
8
+ getSloNotice,
9
+ isRollingWindowNotYetFull,
10
+ SloBudgetTier,
11
+ SloNotice,
12
+ SloNoticeType,
13
+ } from "../../../Utils/Slo/SloHealth";
14
+
15
+ const SECONDS_PER_DAY: number = 24 * 60 * 60;
16
+
17
+ /** The full 30-day error budget of a 99.9% SLO: 43m 12s. */
18
+ const THIRTY_DAY_999_BUDGET_SECONDS: number = 0.001 * 30 * SECONDS_PER_DAY;
19
+
20
+ describe("SloHealth", () => {
21
+ describe("getSloBudgetTier", () => {
22
+ it("returns Unknown when the SLO has not been evaluated", () => {
23
+ expect(getSloBudgetTier({ errorBudgetRemainingPercentage: null })).toBe(
24
+ SloBudgetTier.Unknown,
25
+ );
26
+ expect(
27
+ getSloBudgetTier({ errorBudgetRemainingPercentage: undefined }),
28
+ ).toBe(SloBudgetTier.Unknown);
29
+ });
30
+
31
+ it("returns Unknown for non-finite values", () => {
32
+ expect(
33
+ getSloBudgetTier({ errorBudgetRemainingPercentage: Number.NaN }),
34
+ ).toBe(SloBudgetTier.Unknown);
35
+ });
36
+
37
+ it("returns Healthy well above the threshold", () => {
38
+ expect(getSloBudgetTier({ errorBudgetRemainingPercentage: 68 })).toBe(
39
+ SloBudgetTier.Healthy,
40
+ );
41
+ });
42
+
43
+ it("returns Exhausted at exactly zero", () => {
44
+ expect(getSloBudgetTier({ errorBudgetRemainingPercentage: 0 })).toBe(
45
+ SloBudgetTier.Exhausted,
46
+ );
47
+ });
48
+
49
+ it("returns Exhausted when overspent", () => {
50
+ expect(getSloBudgetTier({ errorBudgetRemainingPercentage: -37 })).toBe(
51
+ SloBudgetTier.Exhausted,
52
+ );
53
+ });
54
+
55
+ it("returns AtRisk at exactly the threshold", () => {
56
+ expect(
57
+ getSloBudgetTier({
58
+ errorBudgetRemainingPercentage: DEFAULT_AT_RISK_THRESHOLD_PERCENTAGE,
59
+ }),
60
+ ).toBe(SloBudgetTier.AtRisk);
61
+ });
62
+
63
+ it("falls back to the 20% default when no threshold is given", () => {
64
+ expect(getSloBudgetTier({ errorBudgetRemainingPercentage: 19.9 })).toBe(
65
+ SloBudgetTier.AtRisk,
66
+ );
67
+ expect(getSloBudgetTier({ errorBudgetRemainingPercentage: 20.1 })).toBe(
68
+ SloBudgetTier.Healthy,
69
+ );
70
+ });
71
+
72
+ it("honours a custom at-risk threshold instead of the hardcoded 20", () => {
73
+ /*
74
+ * The regression this function exists for: at a 50% threshold the
75
+ * old `remaining <= 20` check rendered 35% green while the worker
76
+ * had already moved the SLO to At Risk.
77
+ */
78
+ expect(
79
+ getSloBudgetTier({
80
+ errorBudgetRemainingPercentage: 35,
81
+ atRiskThresholdPercentage: 50,
82
+ }),
83
+ ).toBe(SloBudgetTier.AtRisk);
84
+
85
+ expect(
86
+ getSloBudgetTier({
87
+ errorBudgetRemainingPercentage: 15,
88
+ atRiskThresholdPercentage: 5,
89
+ }),
90
+ ).toBe(SloBudgetTier.Healthy);
91
+ });
92
+
93
+ it("treats a zero threshold as 'at risk only once exhausted'", () => {
94
+ expect(
95
+ getSloBudgetTier({
96
+ errorBudgetRemainingPercentage: 0.5,
97
+ atRiskThresholdPercentage: 0,
98
+ }),
99
+ ).toBe(SloBudgetTier.Healthy);
100
+ });
101
+ });
102
+
103
+ describe("getSloNotice", () => {
104
+ it("returns null for a normally measuring SLO", () => {
105
+ expect(
106
+ getSloNotice({
107
+ isEnabled: true,
108
+ sloStatus: SloStatus.Healthy,
109
+ sliType: SliType.MonitorUptime,
110
+ monitorCount: 2,
111
+ targetPercentage: 99.9,
112
+ lastEvaluatedAt: new Date(),
113
+ }),
114
+ ).toBeNull();
115
+ });
116
+
117
+ it("reports a disabled SLO ahead of any other reason", () => {
118
+ /*
119
+ * A disabled SLO is never evaluated, so its stale Misconfigured
120
+ * status must not send the user off to attach monitors.
121
+ */
122
+ const notice: SloNotice | null = getSloNotice({
123
+ isEnabled: false,
124
+ sloStatus: SloStatus.Misconfigured,
125
+ monitorCount: 0,
126
+ });
127
+
128
+ expect(notice?.type).toBe(SloNoticeType.Info);
129
+ expect(notice?.title).toBe("This SLO is disabled");
130
+ });
131
+
132
+ it("names 'no monitors' as the reason for Misconfigured", () => {
133
+ const notice: SloNotice | null = getSloNotice({
134
+ isEnabled: true,
135
+ sloStatus: SloStatus.Misconfigured,
136
+ sliType: SliType.MonitorUptime,
137
+ monitorCount: 0,
138
+ targetPercentage: 99.9,
139
+ lastEvaluatedAt: new Date(),
140
+ });
141
+
142
+ expect(notice?.type).toBe(SloNoticeType.Warning);
143
+ expect(notice?.title).toBe("No monitors attached");
144
+ });
145
+
146
+ it("names an out-of-range target as the reason for Misconfigured", () => {
147
+ const notice: SloNotice | null = getSloNotice({
148
+ isEnabled: true,
149
+ sloStatus: SloStatus.Misconfigured,
150
+ sliType: SliType.MonitorUptime,
151
+ monitorCount: 1,
152
+ targetPercentage: 100,
153
+ lastEvaluatedAt: new Date(),
154
+ });
155
+
156
+ expect(notice?.title).toBe("The target is out of range");
157
+ });
158
+
159
+ it("names an unsupported SLI type ahead of the monitor count", () => {
160
+ const notice: SloNotice | null = getSloNotice({
161
+ isEnabled: true,
162
+ sloStatus: SloStatus.Misconfigured,
163
+ sliType: SliType.Metric,
164
+ monitorCount: 0,
165
+ targetPercentage: 99.9,
166
+ lastEvaluatedAt: new Date(),
167
+ });
168
+
169
+ expect(notice?.body).toContain(SliType.MonitorUptime);
170
+ });
171
+
172
+ it("falls back to a generic reason for Misconfigured", () => {
173
+ const notice: SloNotice | null = getSloNotice({
174
+ isEnabled: true,
175
+ sloStatus: SloStatus.Misconfigured,
176
+ sliType: SliType.MonitorUptime,
177
+ monitorCount: 1,
178
+ targetPercentage: 99.9,
179
+ lastEvaluatedAt: new Date(),
180
+ });
181
+
182
+ expect(notice?.title).toBe("This SLO cannot be evaluated");
183
+ });
184
+
185
+ it("explains Paused", () => {
186
+ const notice: SloNotice | null = getSloNotice({
187
+ isEnabled: true,
188
+ sloStatus: SloStatus.Paused,
189
+ sliType: SliType.MonitorUptime,
190
+ monitorCount: 2,
191
+ targetPercentage: 99.9,
192
+ lastEvaluatedAt: new Date(),
193
+ });
194
+
195
+ expect(notice?.type).toBe(SloNoticeType.Info);
196
+ expect(notice?.title).toBe("Measurement is paused");
197
+ });
198
+
199
+ it("explains a never-evaluated SLO", () => {
200
+ const notice: SloNotice | null = getSloNotice({
201
+ isEnabled: true,
202
+ sloStatus: SloStatus.Healthy,
203
+ sliType: SliType.MonitorUptime,
204
+ monitorCount: 1,
205
+ targetPercentage: 99.9,
206
+ lastEvaluatedAt: null,
207
+ });
208
+
209
+ expect(notice?.title).toBe("Not evaluated yet");
210
+ });
211
+
212
+ it("says nothing about a healthy SLO whose isEnabled was not selected", () => {
213
+ // `undefined` means "not loaded", which is not the same as `false`.
214
+ expect(
215
+ getSloNotice({
216
+ sloStatus: SloStatus.Healthy,
217
+ sliType: SliType.MonitorUptime,
218
+ monitorCount: 1,
219
+ targetPercentage: 99.9,
220
+ lastEvaluatedAt: new Date(),
221
+ }),
222
+ ).toBeNull();
223
+ });
224
+ });
225
+
226
+ describe("isRollingWindowNotYetFull", () => {
227
+ it("is false for a mature rolling window", () => {
228
+ expect(
229
+ isRollingWindowNotYetFull({
230
+ windowType: SloWindowType.Rolling,
231
+ windowDays: 30,
232
+ targetPercentage: 99.9,
233
+ errorBudgetTotalSeconds: THIRTY_DAY_999_BUDGET_SECONDS,
234
+ }),
235
+ ).toBe(false);
236
+ });
237
+
238
+ it("is true for a 30-day SLO carrying only a week of data", () => {
239
+ expect(
240
+ isRollingWindowNotYetFull({
241
+ windowType: SloWindowType.Rolling,
242
+ windowDays: 30,
243
+ targetPercentage: 99.9,
244
+ errorBudgetTotalSeconds: 0.001 * 7 * SECONDS_PER_DAY,
245
+ }),
246
+ ).toBe(true);
247
+ });
248
+
249
+ it("stays silent for Monitor Seconds Average — its budget scales with the monitor count", () => {
250
+ /*
251
+ * A five-monitor SLO with a week of data carries 35 monitor-days of
252
+ * budget, which would read as mature against a 30-day yardstick. The
253
+ * helper declines to guess rather than answer wrongly in either
254
+ * direction.
255
+ */
256
+ expect(
257
+ isRollingWindowNotYetFull({
258
+ windowType: SloWindowType.Rolling,
259
+ windowDays: 30,
260
+ targetPercentage: 99.9,
261
+ errorBudgetTotalSeconds: 0.001 * 7 * SECONDS_PER_DAY,
262
+ multiMonitorMode: SloMultiMonitorMode.MonitorSecondsAverage,
263
+ }),
264
+ ).toBe(false);
265
+ });
266
+
267
+ it("still answers for the default Any Monitor Down mode", () => {
268
+ expect(
269
+ isRollingWindowNotYetFull({
270
+ windowType: SloWindowType.Rolling,
271
+ windowDays: 30,
272
+ targetPercentage: 99.9,
273
+ errorBudgetTotalSeconds: 0.001 * 7 * SECONDS_PER_DAY,
274
+ multiMonitorMode: SloMultiMonitorMode.AnyDown,
275
+ }),
276
+ ).toBe(true);
277
+ });
278
+
279
+ it("tolerates the small shortfall between now and the last evaluation", () => {
280
+ // 0.5% short — a mature SLO must not flicker the banner.
281
+ expect(
282
+ isRollingWindowNotYetFull({
283
+ windowType: SloWindowType.Rolling,
284
+ windowDays: 30,
285
+ targetPercentage: 99.9,
286
+ errorBudgetTotalSeconds: THIRTY_DAY_999_BUDGET_SECONDS * 0.995,
287
+ }),
288
+ ).toBe(false);
289
+ });
290
+
291
+ it("is false for calendar-month windows — their budget is never prorated", () => {
292
+ expect(
293
+ isRollingWindowNotYetFull({
294
+ windowType: SloWindowType.CalendarMonth,
295
+ windowDays: 30,
296
+ targetPercentage: 99.9,
297
+ errorBudgetTotalSeconds: 1,
298
+ }),
299
+ ).toBe(false);
300
+ });
301
+
302
+ it("is false when the SLO has not been evaluated", () => {
303
+ expect(
304
+ isRollingWindowNotYetFull({
305
+ windowType: SloWindowType.Rolling,
306
+ windowDays: 30,
307
+ targetPercentage: 99.9,
308
+ errorBudgetTotalSeconds: null,
309
+ }),
310
+ ).toBe(false);
311
+ });
312
+
313
+ it("is false when the target would make the full-window budget meaningless", () => {
314
+ expect(
315
+ isRollingWindowNotYetFull({
316
+ windowType: SloWindowType.Rolling,
317
+ windowDays: 30,
318
+ targetPercentage: 100,
319
+ errorBudgetTotalSeconds: 60,
320
+ }),
321
+ ).toBe(false);
322
+ });
323
+
324
+ it("defaults windowDays to 30 when it is not set", () => {
325
+ expect(
326
+ isRollingWindowNotYetFull({
327
+ windowType: SloWindowType.Rolling,
328
+ targetPercentage: 99.9,
329
+ errorBudgetTotalSeconds: 0.001 * 7 * SECONDS_PER_DAY,
330
+ }),
331
+ ).toBe(true);
332
+ });
333
+ });
334
+ });
@@ -0,0 +1,91 @@
1
+ /**
2
+ * Whether a burn rate rule currently has an alert open.
3
+ *
4
+ * `lastAlertCreatedAt` / `lastAlertResolvedAt` are stamped by the
5
+ * evaluation worker every time it fires or resolves a rule's alert, and
6
+ * together they are the only record of the rule's lifecycle — but nothing
7
+ * read them outside the worker, so the Burn Rate Rules table could not
8
+ * tell the user whether a rule was paging someone right now, had ever
9
+ * fired, or had never once triggered.
10
+ *
11
+ * The predicate is the worker's own (EvaluateSlos.evaluateBurnRateRule's
12
+ * `hasUnresolvedFiringState`), lifted here so the table and the worker can
13
+ * never disagree about what "firing" means.
14
+ *
15
+ * Kept free of React and of the database model so both can import it and
16
+ * so the ordering edges are unit-testable without a DOM.
17
+ */
18
+
19
+ import SloStatus from "../../Types/ServiceLevelObjective/SloStatus";
20
+
21
+ export interface SloBurnRateRuleAlertState {
22
+ lastAlertCreatedAt?: Date | undefined | null;
23
+ lastAlertResolvedAt?: Date | undefined | null;
24
+ }
25
+
26
+ /**
27
+ * True when the rule has fired and that alert has not been resolved
28
+ * since.
29
+ *
30
+ * A resolve stamped at exactly the same instant as the fire counts as
31
+ * resolved: the worker writes the resolve strictly after the fire, so an
32
+ * equal pair can only be the same lifecycle, and treating it as firing
33
+ * would leave a red "Firing" pill on a rule with nothing open.
34
+ */
35
+ export type IsBurnRateRuleFiringFunction = (
36
+ rule: SloBurnRateRuleAlertState,
37
+ ) => boolean;
38
+
39
+ export const isBurnRateRuleFiring: IsBurnRateRuleFiringFunction = (
40
+ rule: SloBurnRateRuleAlertState,
41
+ ): boolean => {
42
+ if (!rule.lastAlertCreatedAt) {
43
+ return false;
44
+ }
45
+
46
+ if (!rule.lastAlertResolvedAt) {
47
+ return true;
48
+ }
49
+
50
+ return rule.lastAlertResolvedAt.getTime() < rule.lastAlertCreatedAt.getTime();
51
+ };
52
+
53
+ /**
54
+ * Whether the OWNING SLO is in a state where a burn rate rule could be
55
+ * firing at all.
56
+ *
57
+ * `isBurnRateRuleFiring` alone is not enough to render a live "Firing"
58
+ * badge. When an SLO is disabled, or the worker's guards move it to
59
+ * Misconfigured or Paused, the SLO-level resolve paths
60
+ * (ServiceLevelObjectiveService.resolveOpenBurnRateAlertsForSlo and the
61
+ * worker's setGuardStatusAndResolveOpenAlerts) close every open alert but
62
+ * deliberately do NOT stamp `lastAlertResolvedAt` — that column drives a
63
+ * live rule's re-fire suppression, and this is a state change of the SLO
64
+ * rather than a burn rate that recovered. The rule's own columns are
65
+ * therefore left mid-lifecycle, and a UI reading them alone would show a
66
+ * red "Firing" pill on a rule with nothing open, forever.
67
+ *
68
+ * Pairing the two predicates keeps the badge honest without touching the
69
+ * suppression semantics the worker depends on.
70
+ */
71
+ export interface SloBurnRateFiringContext {
72
+ isEnabled?: boolean | undefined | null;
73
+ sloStatus?: SloStatus | undefined | null;
74
+ }
75
+
76
+ export type CanSloFireBurnRateAlertsFunction = (
77
+ slo: SloBurnRateFiringContext,
78
+ ) => boolean;
79
+
80
+ export const canSloFireBurnRateAlerts: CanSloFireBurnRateAlertsFunction = (
81
+ slo: SloBurnRateFiringContext,
82
+ ): boolean => {
83
+ if (slo.isEnabled === false) {
84
+ return false;
85
+ }
86
+
87
+ return (
88
+ slo.sloStatus !== SloStatus.Misconfigured &&
89
+ slo.sloStatus !== SloStatus.Paused
90
+ );
91
+ };
@@ -0,0 +1,165 @@
1
+ /**
2
+ * Compact duration rendering for error budgets.
3
+ *
4
+ * Error budgets span four orders of magnitude — a 99.99% / 7-day SLO gets
5
+ * 60 seconds, a 99% / 90-day SLO gets 21.6 hours — so the "minutes only"
6
+ * rendering the SLO pages started with reads badly at both ends: a
7
+ * one-minute budget shows as "1 min", and a 90-day budget shows as
8
+ * "1296 min of 1296 min". The docs quote budgets the way an SRE says them
9
+ * out loud ("43m 12s", "2h 9m"), and this is the helper that produces
10
+ * exactly that.
11
+ *
12
+ * Kept free of React (and of the database models) so the SLO pages, the
13
+ * dashboard SLO widget and any future status-page surface can all share
14
+ * one rendering, and so every rounding edge is unit-testable without a
15
+ * DOM.
16
+ */
17
+
18
+ /** U+2212 MINUS SIGN — reads as a minus rather than a hyphen at tile sizes. */
19
+ const MINUS_SIGN: string = "−";
20
+
21
+ /**
22
+ * Seconds per unit, largest first. Only the two most significant non-zero
23
+ * units are rendered: "2d 5h" is what an on-call engineer needs, "2d 5h
24
+ * 13m 7s" is noise, and truncating rather than rounding up keeps the
25
+ * remaining budget from ever reading larger than it is.
26
+ */
27
+ const UNITS: Array<{ suffix: string; seconds: number }> = [
28
+ { suffix: "d", seconds: 86400 },
29
+ { suffix: "h", seconds: 3600 },
30
+ { suffix: "m", seconds: 60 },
31
+ { suffix: "s", seconds: 1 },
32
+ ];
33
+
34
+ const MAX_UNITS_SHOWN: number = 2;
35
+
36
+ /**
37
+ * `null` for anything that is not a real, finite number. The
38
+ * worker-owned budget columns are NULL until the SLO is first evaluated,
39
+ * and a Postgres decimal can arrive as a string over JSON, so the guard
40
+ * has to reject non-numbers rather than coerce them.
41
+ */
42
+ type ToFiniteNumberFunction = (
43
+ value: number | undefined | null,
44
+ ) => number | null;
45
+
46
+ const toFiniteNumber: ToFiniteNumberFunction = (
47
+ value: number | undefined | null,
48
+ ): number | null => {
49
+ if (typeof value !== "number" || !isFinite(value)) {
50
+ return null;
51
+ }
52
+
53
+ return value;
54
+ };
55
+
56
+ /**
57
+ * An unsigned duration as "2d 5h" / "43m 12s" / "45s". Fractional seconds
58
+ * are floored, so a 59.9-second budget renders "59s" rather than rounding
59
+ * up to a minute the SLO does not actually have.
60
+ *
61
+ * A duration that floors to zero renders "0s" — a real, sayable state —
62
+ * instead of an empty string.
63
+ */
64
+ export type FormatDurationCompactFunction = (seconds: number) => string;
65
+
66
+ export const formatDurationCompact: FormatDurationCompactFunction = (
67
+ seconds: number,
68
+ ): string => {
69
+ let remainingSeconds: number = Math.floor(Math.abs(seconds));
70
+
71
+ const parts: Array<string> = [];
72
+
73
+ for (const unit of UNITS) {
74
+ if (parts.length >= MAX_UNITS_SHOWN) {
75
+ break;
76
+ }
77
+
78
+ const count: number = Math.floor(remainingSeconds / unit.seconds);
79
+
80
+ /*
81
+ * Skip leading zero units ("0d 5h"), but once a larger unit has been
82
+ * emitted a zero is still skipped rather than padded — "2d" is
83
+ * correct for exactly 48 hours, "2d 0h" is not how anyone says it.
84
+ */
85
+ if (count <= 0) {
86
+ continue;
87
+ }
88
+
89
+ parts.push(`${count}${unit.suffix}`);
90
+ remainingSeconds -= count * unit.seconds;
91
+ }
92
+
93
+ if (parts.length === 0) {
94
+ return "0s";
95
+ }
96
+
97
+ return parts.join(" ");
98
+ };
99
+
100
+ /**
101
+ * `errorBudgetRemainingSeconds` is SIGNED: negative means the budget is
102
+ * overspent, and that overage is the single most useful number during a
103
+ * bad month. Render it plainly rather than clamping to zero, which would
104
+ * hide a breach.
105
+ *
106
+ * Returns `null` (not a placeholder string) when the SLO has not been
107
+ * evaluated, so callers decide how to phrase "no data yet" in their own
108
+ * context.
109
+ */
110
+ export type FormatErrorBudgetRemainingFunction = (
111
+ seconds: number | undefined | null,
112
+ ) => string | null;
113
+
114
+ export const formatErrorBudgetRemaining: FormatErrorBudgetRemainingFunction = (
115
+ seconds: number | undefined | null,
116
+ ): string | null => {
117
+ const numericSeconds: number | null = toFiniteNumber(seconds);
118
+
119
+ if (numericSeconds === null) {
120
+ return null;
121
+ }
122
+
123
+ if (numericSeconds < 0) {
124
+ return `${MINUS_SIGN}${formatDurationCompact(numericSeconds)} over budget`;
125
+ }
126
+
127
+ return `${formatDurationCompact(numericSeconds)} left`;
128
+ };
129
+
130
+ /**
131
+ * "12m 30s left of 43m 12s" — the phrasing the error-budget docs use.
132
+ * Falls back to the bare remaining string when the total is not known
133
+ * (the two columns are written together by the worker, but a partially
134
+ * evaluated row must not render "of null").
135
+ */
136
+ export type FormatErrorBudgetRemainingOfTotalFunction = (data: {
137
+ remainingSeconds: number | undefined | null;
138
+ totalSeconds: number | undefined | null;
139
+ }) => string | null;
140
+
141
+ export const formatErrorBudgetRemainingOfTotal: FormatErrorBudgetRemainingOfTotalFunction =
142
+ (data: {
143
+ remainingSeconds: number | undefined | null;
144
+ totalSeconds: number | undefined | null;
145
+ }): string | null => {
146
+ const remainingText: string | null = formatErrorBudgetRemaining(
147
+ data.remainingSeconds,
148
+ );
149
+
150
+ if (remainingText === null) {
151
+ return null;
152
+ }
153
+
154
+ const totalSeconds: number | null = toFiniteNumber(data.totalSeconds);
155
+
156
+ /*
157
+ * A zero total is a real state for a brand-new SLO (no elapsed window
158
+ * yet). "of 0s" adds nothing, so drop the suffix rather than print it.
159
+ */
160
+ if (totalSeconds === null || totalSeconds <= 0) {
161
+ return remainingText;
162
+ }
163
+
164
+ return `${remainingText} of ${formatDurationCompact(totalSeconds)}`;
165
+ };
@@ -0,0 +1,22 @@
1
+ /**
2
+ * Cadence constants shared by the SLO evaluation worker and every UI
3
+ * surface that describes what the worker produced.
4
+ *
5
+ * These numbers were previously duplicated as prose: the worker owned
6
+ * them, and the dashboard said "evaluated every few minutes" and "1×
7
+ * spends the budget exactly over the window" without ever naming the
8
+ * lookback the headline burn rate is actually measured over. A reader who
9
+ * compared the tile against a burn rate rule had no way to know they were
10
+ * measuring different spans. Naming them once here keeps the copy and the
11
+ * computation from drifting.
12
+ */
13
+
14
+ /** How often a due SLO is re-evaluated, and how far ahead the worker schedules the next run. */
15
+ export const SLO_EVALUATION_CADENCE_MINUTES: number = 5;
16
+
17
+ /**
18
+ * Lookback for the "current burn rate" column shown on the SLO overview
19
+ * and the dashboard SLO widget. Deliberately equal to the default
20
+ * fast-burn rule's long window, so the tile and that rule move together.
21
+ */
22
+ export const SLO_CURRENT_BURN_RATE_WINDOW_MINUTES: number = 60;