streamcast-watch 0.33.0__py3-none-any.whl

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.
@@ -0,0 +1,114 @@
1
+ """Alert on rules over streamcast streams, from a bounded cache in memory.
2
+
3
+ A real-time subscriber: each `Follower` replays a bounded window of a stream
4
+ and follows it live into a `Window`, which keeps each rule's own reduction of
5
+ the rows it matches (`Newest`, `Buckets`) and what delivery covers
6
+ (`Coverage`). The `Alerter` evaluates every `Rule` against those windows —
7
+ BREACH, OK or UNKNOWN — and sends one notice per state change through a
8
+ `Notifier`, recording what it delivered on the stream (`StreamAnnouncer`).
9
+ The stream is the only store; nothing here is written to disk.
10
+
11
+ The `WorkloadPublisher` is the other process: it reads the Kubernetes API
12
+ (`KubeApi`, GET only) for each target in a `TargetsFile` and publishes OTel
13
+ metric rows through a `Sink`. The AWS notifier and liveness are
14
+ `streamcast_watch.aws`, behind the `aws` extra, and are not imported here.
15
+ """
16
+
17
+ from importlib.metadata import PackageNotFoundError, version
18
+
19
+ from streamcast_watch.alerter import Alerter
20
+ from streamcast_watch.announce import Announced, Announcements, StreamAnnouncer
21
+ from streamcast_watch.config import (
22
+ RulesError,
23
+ RulesFile,
24
+ Settings,
25
+ build_rules,
26
+ build_windows,
27
+ metric_names,
28
+ )
29
+ from streamcast_watch.follow import Follower
30
+ from streamcast_watch.kube import KubeApi, KubeError
31
+ from streamcast_watch.liveness import Liveness, NoLiveness
32
+ from streamcast_watch.notify import LogNotifier, Notice, Notifier, NotifyFailed
33
+ from streamcast_watch.otel import METRICS_SCHEMA
34
+ from streamcast_watch.publisher import (
35
+ PublisherSettings,
36
+ Target,
37
+ TargetsError,
38
+ TargetsFile,
39
+ WorkloadPublisher,
40
+ )
41
+ from streamcast_watch.rules import (
42
+ KINDS,
43
+ Finding,
44
+ Match,
45
+ Rule,
46
+ Stale,
47
+ Threshold,
48
+ Verdict,
49
+ register,
50
+ )
51
+ from streamcast_watch.sink import SendFailed, Sink, StreamSink
52
+ from streamcast_watch.window import (
53
+ Buckets,
54
+ Coverage,
55
+ Evidence,
56
+ Newest,
57
+ Point,
58
+ Series,
59
+ Watched,
60
+ Window,
61
+ )
62
+
63
+ try:
64
+ __version__ = version("streamcast-watch")
65
+ except PackageNotFoundError: # a source tree that was never installed
66
+ __version__ = "0.0.0"
67
+
68
+ __all__ = [
69
+ "Alerter",
70
+ "Announced",
71
+ "Announcements",
72
+ "Buckets",
73
+ "Coverage",
74
+ "Evidence",
75
+ "Finding",
76
+ "Follower",
77
+ "KINDS",
78
+ "KubeApi",
79
+ "KubeError",
80
+ "Liveness",
81
+ "LogNotifier",
82
+ "METRICS_SCHEMA",
83
+ "Match",
84
+ "Newest",
85
+ "NoLiveness",
86
+ "Notice",
87
+ "Notifier",
88
+ "NotifyFailed",
89
+ "Point",
90
+ "PublisherSettings",
91
+ "Rule",
92
+ "RulesError",
93
+ "RulesFile",
94
+ "SendFailed",
95
+ "Series",
96
+ "Settings",
97
+ "Sink",
98
+ "Stale",
99
+ "StreamAnnouncer",
100
+ "StreamSink",
101
+ "Target",
102
+ "TargetsError",
103
+ "TargetsFile",
104
+ "Threshold",
105
+ "Verdict",
106
+ "Watched",
107
+ "Window",
108
+ "WorkloadPublisher",
109
+ "build_rules",
110
+ "build_windows",
111
+ "metric_names",
112
+ "register",
113
+ "__version__",
114
+ ]
@@ -0,0 +1,420 @@
1
+ """`Alerter`: every rule evaluated on a clock, one notice per state change.
2
+
3
+ **One loop, so evaluations never overlap.** Every `evaluate_every` (15 s) it
4
+ evaluates each rule against its stream's window, in memory, then delivers
5
+ what is pending, then beats. A slow notifier delays the next evaluation and
6
+ starts no second one.
7
+
8
+ **Two states per rule, three verdicts, and one notice per change.** A rule
9
+ is OK or FIRING; each evaluation's verdict is BREACH, OK or UNKNOWN
10
+ (`rules.Verdict`):
11
+
12
+ * BREACH: OK to FIRING sends one ALARM, and the clear timer stops.
13
+ * OK starts the clear timer, or lets it run. FIRING clears, with one OK,
14
+ only once the verdict has been OK for the rule's `keep_firing_for` (5
15
+ minutes by default) without a break. An OK that rests on nothing seen
16
+ since this process started (`Finding.clears` false: a `Stale` rule before
17
+ its first row and before its `after`) restarts the timer instead, so a
18
+ rule restored FIRING stays firing through an outage that has not changed.
19
+ * UNKNOWN sends nothing and restarts the clear timer: a rule that cannot be
20
+ evaluated is never taken to have cleared, so a FIRING rule stays firing.
21
+
22
+ `keep_firing_for` is also what turns a pod that is Ready for seconds between
23
+ five-minute back-offs into one ALARM, rather than an ALARM and an OK every
24
+ five minutes. Nothing is sent again while the state holds.
25
+
26
+ **Sustained UNKNOWN is said, once.** After `unknown_after` (20) UNKNOWN
27
+ evaluations in a row, one `[UNKNOWN] <rule>` notice names the causes; the
28
+ next definite verdict, BREACH or OK, sends one `[EVALUABLE] <rule>`. These
29
+ are a second pair beside ALARM and OK, through the same notifier, and say
30
+ only the rule's name, the causes, the counts and identifying attributes
31
+ (`Series.label`), and the alerter's own view of the stream.
32
+
33
+ **A notice is never dropped.** One that fails (`NotifyFailed`) stays pending,
34
+ in order, and is tried again at later evaluations with a delay doubling up to
35
+ `retry_max`. A rule that changes state twice while its notices wait collapses
36
+ rather than queueing, each pair on its own: an ALARM, OK, ALARM sequence is
37
+ one ALARM, which is the state a person must act on, and UNKNOWN, EVALUABLE,
38
+ UNKNOWN is one UNKNOWN, so the queue holds at most four notices per rule.
39
+ While one waits longer than `overdue`, the liveness beat stops, so the
40
+ outside alarm says the alerter cannot deliver.
41
+
42
+ **At start every rule is OK**, unless the stream says otherwise. Without
43
+ `announcements`, nothing has been announced, and a rule that holds sends its
44
+ ALARM even if an earlier process sent the same one before it restarted. With
45
+ them (`announce.StreamAnnouncer`), a stream is **restored** once its
46
+ follower's replay has ended (`Window.replayed`): everything an earlier
47
+ process announced has then arrived. Its rules are evaluated from then, or
48
+ from `restore_within` (60 s) after the window started if the replay has not
49
+ ended by then: a **fallback** that lets a broker that cannot be reached be
50
+ alerted on, and is not a restoration. In fallback the announcements are not
51
+ this process's to publish, so nothing it writes can cover what an earlier
52
+ process announced and this one has not read; what it delivers is held until
53
+ the replay ends.
54
+
55
+ **At the restore, the replayed state is reconciled**, however late it
56
+ comes. Each rule an earlier process last announced FIRING, and for which
57
+ this process has delivered no ALARM or OK of its own:
58
+
59
+ * with no ALARM or OK of its own pending, starts or becomes FIRING, so it
60
+ sends no second ALARM while it holds and sends its OK once it has read OK
61
+ for `keep_firing_for`;
62
+ * with its own ALARM pending, undelivered, has that ALARM withdrawn: the
63
+ person already has one. An OK queued behind it stays, and clears the
64
+ earlier process's ALARM.
65
+
66
+ An ALARM this process delivered in fallback, before the replay ended, may
67
+ repeat the earlier process's: that is the at-least-once case, and nothing
68
+ more is sent for it. Each delivered ALARM and OK is handed to the
69
+ announcements after it is delivered, never before: notify, then record. If
70
+ nothing can be replayed, a rule that holds sends its ALARM again: delivery
71
+ is at least once. All of this assumes one alerter per stream at a time
72
+ (one replica, replaced with `Recreate`): two would each restore the other's
73
+ silence and both notify.
74
+
75
+ **The liveness beat says every rule was evaluated and notices are delivered.**
76
+ It follows an evaluate-and-deliver pass, while no notice has waited longer
77
+ than `overdue`. It reads no verdict or broker state: a rule's inability to
78
+ decide is reported by its own [UNKNOWN] notice. If that notice cannot be
79
+ delivered, the pending-notice bound stops the beat too.
80
+ """
81
+
82
+ from __future__ import annotations
83
+
84
+ import asyncio
85
+ import logging
86
+ import time
87
+ from dataclasses import dataclass
88
+ from typing import TYPE_CHECKING, Protocol
89
+
90
+ from streamcast_watch.liveness import due
91
+ from streamcast_watch.notify import Notice, NotifyFailed, State
92
+ from streamcast_watch.rules import Finding, Verdict, stamp
93
+
94
+ if TYPE_CHECKING:
95
+ from collections.abc import Awaitable, Callable, Mapping, Sequence
96
+
97
+ from streamcast_watch.announce import Announcements
98
+ from streamcast_watch.config import Settings
99
+ from streamcast_watch.liveness import Liveness
100
+ from streamcast_watch.notify import Notifier
101
+ from streamcast_watch.rules import Rule
102
+ from streamcast_watch.window import Window
103
+
104
+ log = logging.getLogger(__name__)
105
+
106
+
107
+ class View(Protocol):
108
+ """What a notice says of the stream's follower (`Follower.describe`)."""
109
+
110
+ def describe(self, now: float) -> str: ...
111
+
112
+
113
+ @dataclass(slots=True)
114
+ class _Status:
115
+ firing: bool = False
116
+ ok_since: float | None = None
117
+ """When the current unbroken run of OK verdicts began: the clear timer."""
118
+
119
+ unknown_run: int = 0
120
+ """UNKNOWN verdicts in a row."""
121
+
122
+ unknown_said: bool = False
123
+ """Whether an [UNKNOWN] went out for the current run."""
124
+
125
+
126
+ _PAIRS: dict[State, frozenset[State]] = {
127
+ "ALARM": frozenset({"ALARM", "OK"}),
128
+ "OK": frozenset({"ALARM", "OK"}),
129
+ "UNKNOWN": frozenset({"UNKNOWN", "EVALUABLE"}),
130
+ "EVALUABLE": frozenset({"UNKNOWN", "EVALUABLE"}),
131
+ }
132
+
133
+
134
+ @dataclass(slots=True)
135
+ class _Pending:
136
+ notice: Notice
137
+ since: float
138
+ next_try: float
139
+ delay: float
140
+
141
+
142
+ class Alerter:
143
+ def __init__(
144
+ self,
145
+ rules: Sequence[Rule],
146
+ windows: Mapping[str, Window],
147
+ views: Mapping[str, View],
148
+ notifier: Notifier,
149
+ liveness: Liveness,
150
+ settings: Settings,
151
+ *,
152
+ clock: Callable[[], float] = time.time,
153
+ sleep: Callable[[float], Awaitable[None]] = asyncio.sleep,
154
+ announcements: Announcements | None = None,
155
+ ) -> None:
156
+ missing = {rule.stream for rule in rules} - set(windows)
157
+ if missing:
158
+ msg = f"no window for stream(s) {sorted(missing)}"
159
+ raise ValueError(msg)
160
+
161
+ self.rules = list(rules)
162
+ self._windows = windows
163
+ self._views = views
164
+ self._notifier = notifier
165
+ self._liveness = liveness
166
+ self._settings = settings
167
+ self._clock = clock
168
+ self._sleep = sleep
169
+ self._status = {rule.name: _Status() for rule in self.rules}
170
+ self._stream = {rule.name: rule.stream for rule in self.rules}
171
+ self._announcements = announcements
172
+ self._restored: set[str] = set()
173
+ self._fallback: set[str] = set()
174
+ """Streams evaluated since `restore_within` passed, not yet restored."""
175
+ self._pending: list[_Pending] = []
176
+ self.last_tick: float | None = None
177
+ self._last_beat: float | None = None
178
+
179
+ @property
180
+ def pending(self) -> list[Notice]:
181
+ return [entry.notice for entry in self._pending]
182
+
183
+ def firing(self, rule: str) -> bool:
184
+ return self._status[rule].firing
185
+
186
+ async def run(self) -> None:
187
+ """Evaluate, deliver and beat every `evaluate_every`, until cancelled."""
188
+ while True:
189
+ await self.tick(self._clock())
190
+ await self._sleep(self._settings.evaluate_every)
191
+
192
+ def restored(self, stream: str) -> bool:
193
+ """Whether `stream`'s announced state is restored (see the module):
194
+ never by `restore_within` alone."""
195
+ return self._announcements is None or stream in self._restored
196
+
197
+ async def tick(self, now: float) -> None:
198
+ for window in self._windows.values():
199
+ window.trim(now)
200
+
201
+ evaluated = True
202
+ for rule in self.rules:
203
+ if not self._restore(rule.stream, now):
204
+ evaluated = False
205
+ continue
206
+
207
+ self._evaluate(rule, rule.holds(self._windows[rule.stream], now), now)
208
+
209
+ await self._deliver(now)
210
+ self.last_tick = now
211
+ if due(
212
+ now,
213
+ evaluated=evaluated,
214
+ oldest_pending=min((entry.since for entry in self._pending), default=None),
215
+ last_beat=self._last_beat,
216
+ beat_every=self._settings.beat_every,
217
+ overdue=self._settings.overdue,
218
+ ):
219
+ await self._beat(now)
220
+
221
+ def _restore(self, stream: str, now: float) -> bool:
222
+ """Whether `stream`'s rules may be evaluated: restoring their
223
+ announced state once the replay has ended, and evaluating them in
224
+ fallback once `restore_within` has passed without that."""
225
+ if self.restored(stream):
226
+ return True
227
+
228
+ assert self._announcements is not None
229
+ window = self._windows[stream]
230
+ if window.replayed:
231
+ self._reconcile(stream, self._announcements.restore(stream))
232
+ self._restored.add(stream)
233
+ self._fallback.discard(stream)
234
+ return True
235
+
236
+ if stream in self._fallback:
237
+ return True
238
+
239
+ if now - window.started < self._settings.restore_within:
240
+ return False
241
+
242
+ self._fallback.add(stream)
243
+ log.warning(
244
+ "%s: no replay within restore_within (%gs); evaluating its rules "
245
+ "without what was announced before, and publishing nothing until "
246
+ "the replay ends",
247
+ stream,
248
+ self._settings.restore_within,
249
+ )
250
+ return True
251
+
252
+ def _reconcile(self, stream: str, firing: frozenset[str]) -> None:
253
+ """The replay has ended: take each rule an earlier process announced
254
+ FIRING, and this one has not announced since, as FIRING (see the
255
+ module)."""
256
+ withdrawn = 0
257
+ for rule in self.rules:
258
+ if rule.stream != stream or rule.name not in firing:
259
+ continue
260
+
261
+ mine = next(
262
+ (
263
+ entry
264
+ for entry in self._pending
265
+ if entry.notice.rule == rule.name
266
+ and entry.notice.state in _PAIRS["ALARM"]
267
+ ),
268
+ None,
269
+ )
270
+ if mine is None:
271
+ self._status[rule.name].firing = True
272
+ elif mine.notice.state == "ALARM":
273
+ # Undelivered, and the earlier process's ALARM is already
274
+ # with the person: this one would be its duplicate.
275
+ self._pending.remove(mine)
276
+ withdrawn += 1
277
+
278
+ log.info(
279
+ "%s: replay over; %d rule(s) restored as FIRING, %d queued ALARM(s) "
280
+ "withdrawn as already announced",
281
+ stream,
282
+ len(firing),
283
+ withdrawn,
284
+ )
285
+
286
+ # -- state ---------------------------------------------------------------------
287
+
288
+ def _evaluate(self, rule: Rule, finding: Finding, now: float) -> None:
289
+ status = self._status[rule.name]
290
+ if finding.verdict is Verdict.UNKNOWN:
291
+ status.ok_since = None
292
+ status.unknown_run += 1
293
+ if (
294
+ status.unknown_run >= self._settings.unknown_after
295
+ and not status.unknown_said
296
+ ):
297
+ status.unknown_said = True
298
+ self._queue(rule, "UNKNOWN", finding, now)
299
+
300
+ return
301
+
302
+ status.unknown_run = 0
303
+ if status.unknown_said:
304
+ status.unknown_said = False
305
+ self._queue(rule, "EVALUABLE", finding, now)
306
+
307
+ if finding.verdict is Verdict.BREACH:
308
+ status.ok_since = None
309
+ if not status.firing:
310
+ status.firing = True
311
+ self._queue(rule, "ALARM", finding, now)
312
+
313
+ return
314
+
315
+ if not status.firing:
316
+ return
317
+
318
+ if not finding.clears:
319
+ status.ok_since = None
320
+ return
321
+
322
+ if status.ok_since is None:
323
+ status.ok_since = now
324
+
325
+ if now - status.ok_since >= rule.keep_firing_for:
326
+ status.firing = False
327
+ status.ok_since = None
328
+ self._queue(rule, "OK", finding, now)
329
+
330
+ def _queue(self, rule: Rule, state: State, finding: Finding, now: float) -> None:
331
+ notice = Notice(
332
+ rule=rule.name,
333
+ state=state,
334
+ at=now,
335
+ body=self._body(rule, state, finding, now),
336
+ )
337
+ log.warning("%s at %s", notice.subject, stamp(now))
338
+ mine = [
339
+ entry
340
+ for entry in self._pending
341
+ if entry.notice.rule == rule.name and entry.notice.state in _PAIRS[state]
342
+ ]
343
+ if len(mine) >= 2 and mine[-2].notice.state == state:
344
+ # [X, Y] then X again: Y is superseded before anyone read it,
345
+ # and X is already waiting to say what holds now.
346
+ self._pending.remove(mine[-1])
347
+ return
348
+
349
+ self._pending.append(
350
+ _Pending(
351
+ notice, since=now, next_try=now, delay=self._settings.evaluate_every
352
+ )
353
+ )
354
+
355
+ def _body(self, rule: Rule, state: State, finding: Finding, now: float) -> str:
356
+ if state == "UNKNOWN":
357
+ lines = [
358
+ f"{rule.name} could not be evaluated for "
359
+ f"{self._settings.unknown_after} evaluations in a row, as of "
360
+ f"{stamp(now)}. It sends no ALARM or OK until it can; a FIRING "
361
+ f"rule stays firing.",
362
+ *(f"Because of {reason}." for reason in finding.reasons),
363
+ ]
364
+ elif state == "EVALUABLE":
365
+ lines = [f"{rule.name} can be evaluated again as of {stamp(now)}."]
366
+ else:
367
+ lines = [rule.says.strip()] if rule.says.strip() else []
368
+
369
+ if state == "OK":
370
+ lines.append(
371
+ f"{rule.name} has read OK for {int(rule.keep_firing_for)}s; "
372
+ f"it is clear as of {stamp(now)}."
373
+ )
374
+
375
+ lines.extend(finding.detail)
376
+ view = self._views.get(rule.stream)
377
+ lines.append(
378
+ f"The alerter at {stamp(now)}: "
379
+ + (
380
+ view.describe(now)
381
+ if view is not None
382
+ else f"{rule.stream}: no follower"
383
+ )
384
+ )
385
+ return "\n\n".join(lines)
386
+
387
+ # -- delivery ------------------------------------------------------------------
388
+
389
+ async def _deliver(self, now: float) -> None:
390
+ """In order: a failed notice holds the ones behind it, so a person
391
+ never reads an OK before the ALARM it clears."""
392
+ while self._pending and self._pending[0].next_try <= now:
393
+ entry = self._pending[0]
394
+ try:
395
+ await self._notifier.send(entry.notice)
396
+ except NotifyFailed as exc:
397
+ log.warning(
398
+ "%s not delivered (%s); trying again in %gs",
399
+ entry.notice.subject,
400
+ exc,
401
+ entry.delay,
402
+ )
403
+ entry.next_try = now + entry.delay
404
+ entry.delay = min(entry.delay * 2, self._settings.retry_max)
405
+ return
406
+
407
+ self._pending.pop(0)
408
+ if self._announcements is not None and entry.notice.state in (
409
+ "ALARM",
410
+ "OK",
411
+ ):
412
+ self._announcements.delivered(
413
+ self._stream[entry.notice.rule],
414
+ entry.notice.rule,
415
+ firing=entry.notice.state == "ALARM",
416
+ )
417
+
418
+ async def _beat(self, now: float) -> None:
419
+ await self._liveness.beat(now)
420
+ self._last_beat = now