IC Improve Code Recipes

Recipe 17.5 · Python

The Alert Manager as a Modern Worker Service

The Python listings are conversions of the book's C# code to Python 3.12. Each file's header says what it needs to run. The explanations were written for the C# version, so some names in the text refer to .NET.

Problem

CFATS Manager's alerts are the part of the product that reaches people who are not logged in. When a piece of security equipment has been out of service for more than four hours, the facility security officer gets an e-mail. After 24 hours, the corporate security officer is copied. Overdue training and missing daily reports follow similar rules. A Windows service, CFATSAlertManager, does this on a timer. It works, and it is also the code with the most latent failure modes in the product.

The way it's often written

Anti-pattern: shown so you can recognize it. Don't copy this one.

From CFATS Manager, abridged.

Four problems hide in here:

  1. Overlapping ticks. System.Timers.Timer raises Elapsed on the thread pool whether or not the last tick finished. A slow SMTP server and a 30-second interval let two passes run at once and e-mail the same people twice.
  2. Send, then record. The e-mail goes out first, and the alert level is raised afterwards. If the update fails, the next tick sends the same e-mail again, every 30 seconds, until someone notices.
  3. One failure stops everything. return false on the first failed e-mail abandons the rest of that facility's alerts, and the caller ignores the return value.
  4. Rules buried in SQL strings. The 4-hour and 24-hour thresholds live inside SQL constants (DATEADD(hh,-4,SYSDATETIME())), duplicated per range and per alert type. ClientID = 1 is hard-coded, as it is in the SQL Agent job.

OnStop was empty, and nothing in OnElapsedTime caught exceptions. System.Timers.Timer swallows exceptions thrown from its Elapsed handler, so a failure doesn't crash the service. It just disappears.

Requirements: Python 3.12+. Standard library only, nothing to install.

Python Timer-driven alert service with hard-coded client and status-flag error handling (p399_r17_5_timer_service_alert_loop_before.py)
"""Timer-driven alert service with hard-coded client and status-flag error handling

Source: ImproveCode, Chapter 17, Recipe 17.5 "The Alert Manager as a Modern Worker Service"
Section: The way it's often written
Book page: 399-400  -- original C# listing
Converted from C# to Python.
ANTI-PATTERN: kept deliberately faithful to the C# 'not to copy' example; do not use.
System.Timers.Timer becomes a re-armed threading.Timer; ConfigurationManager.RefreshSection
becomes re-reading an ini file with configparser. The per-row block is a fragment.
"""

import configparser
import threading
from typing import Any


# From CFATS Manager: CFATSAlertManager\CFATSAlertManager.cs
# lines 146-182 and 393-428 (abridged, condensed, re-wrapped)
class CFATSAlertManager:
    def __init__(self) -> None:
        self.interval = 30.0
        self.timer: threading.Timer | None = None
        self.manager: Any = None
        self.CurrentFSO: Any = None

    def on_start(self, args: list[str]) -> None:
        self._arm()

    def _arm(self) -> None:
        self.timer = threading.Timer(self.interval, self.on_elapsed_time)
        self.timer.start()

    def on_elapsed_time(self) -> None:
        config = configparser.ConfigParser()
        config.read("CFATSAlertManager.ini")  # RefreshSection("appSettings")
        # ... read TimerInterval and update self.interval ...

        # set ClientID to 1 for now since there is only one client
        ClientID = 1
        self.load_alerts(ClientID)
        self._arm()

    def load_alerts(self, client_id: int) -> None: ...

    # inside ProcessOutageRange1, for each row:
    def process_outage_row(self, R1_AlertLevel: int, R1_OutageID: int,
                           R1_Status: str, R1_AlertID: int) -> bool:
        if R1_AlertLevel == 1:
            EmailState = self.send_alert_level_one(R1_OutageID, R1_Status, self.CurrentFSO.Email)
            if EmailState.ErrorOccurred:
                self.log_message("Send Email Failed: " + EmailState.ErrorMessage)
                return False
            AlertEmailID = self.manager.InsertAlertEmail(R1_AlertID)  # ...
            if self.manager.State.ErrorOccurred:
                return False
            self.manager.UpdateAlert(R1_AlertID, R1_AlertLevel + 1)  # ...
            _ = AlertEmailID
            # ...
        return True

    def send_alert_level_one(self, outage_id: int, status: str, email: str) -> Any: ...

    def log_message(self, message: str) -> None: ...

The improved recipe

Packages: Microsoft.Extensions.Hosting and, to run as a Windows service, Microsoft.Extensions.Hosting.WindowsServices. First the rules and the contracts:

Then the worker:

Hosting it as a Windows service, as a usage snippet:

SqlAlertStore is your implementation of IAlertStore over the existing tblAlert and tblAlertEmail tables.

Requirements: Python 3.12+. Standard library only, nothing to install.

Python Alert escalation rules as data, plus store and notifier interfaces (p401_r17_5_alert_escalation_policy_model.py)
"""Alert escalation rules as data, plus store and notifier interfaces

Source: ImproveCode, Chapter 17, Recipe 17.5 "The Alert Manager as a Modern Worker Service"
Section: The improved recipe
Book page: 401-402  -- original C# listing
Converted from C# to Python.
Enums become Enum/Flag, records frozen dataclasses (TimeSpan -> timedelta), and the
store/notifier interfaces async Protocols; CancellationToken is left to asyncio.
"""

from __future__ import annotations

from collections.abc import Iterable, Sequence
from dataclasses import dataclass
from datetime import datetime, timedelta
from enum import Enum, Flag, auto
from typing import ClassVar, Protocol


class AlertKind(Enum):
    OUTAGE = auto()
    TRAINING = auto()
    DAILY_REPORT = auto()


class Recipients(Flag):
    NONE = 0
    FSO = 1
    CSO = 2
    OTHERS = 4


@dataclass(frozen=True)
class OpenAlert:
    alert_id: int
    facility_id: int
    kind: AlertKind
    object_id: int
    level: int
    opened_at: datetime


@dataclass(frozen=True)
class EscalationStep:
    kind: AlertKind
    from_level: int
    after: timedelta
    to: Recipients


class EscalationPolicy:
    DEFAULT: ClassVar[EscalationPolicy]

    def __init__(self, steps: Iterable[EscalationStep]) -> None:
        self._steps = tuple(steps)

    def next_step(self, a: OpenAlert, now: datetime) -> EscalationStep | None:
        return next(
            (
                s
                for s in self._steps
                if s.kind == a.kind and s.from_level == a.level and now - a.opened_at >= s.after
            ),
            None,
        )


# The CFATS Manager outage rules, expressed as data.
EscalationPolicy.DEFAULT = EscalationPolicy(
    [
        EscalationStep(AlertKind.OUTAGE, 1, timedelta(hours=4), Recipients.FSO),
        EscalationStep(AlertKind.OUTAGE, 2, timedelta(hours=24), Recipients.FSO | Recipients.CSO),
    ]
)


class AlertStore(Protocol):
    async def get_open_alerts(self) -> Sequence[OpenAlert]: ...

    # UPDATE ... SET AlertLevel = ? WHERE AlertID = ?
    #   AND AlertLevel = ?; returns False if someone else won.
    async def try_advance(self, alert_id: int, from_level: int, to_level: int) -> bool: ...

    async def get_addresses(self, facility_id: int, to: Recipients) -> Sequence[str]: ...

    async def record_email(self, alert_id: int, level: int, to: Sequence[str], sent: bool) -> None: ...


class AlertNotifier(Protocol):
    async def send(self, alert: OpenAlert, new_level: int, to: Sequence[str]) -> None: ...

Requirements: Python 3.12+. Standard library only, nothing to install.

Python Background worker that escalates open alerts on a fixed interval (p402_r17_5_alert_escalation_worker.py)
"""Background worker that escalates open alerts on a fixed interval

Source: ImproveCode, Chapter 17, Recipe 17.5 "The Alert Manager as a Modern Worker Service"
Section: The improved recipe
Book page: 402-403  -- original C# listing
Converted from C# to Python.
BackgroundService + PeriodicTimer become an asyncio loop with asyncio.sleep; ILogger
becomes logging. asyncio.CancelledError is a BaseException, so "except Exception"
already excludes cancellation like the C# "when (ex is not OperationCanceledException)".
"""

import asyncio
import logging
from dataclasses import dataclass
from datetime import datetime, timedelta
from typing import Protocol

from p401_r17_5_alert_escalation_policy_model import AlertNotifier, AlertStore, EscalationPolicy


class Clock(Protocol):
    def get_utc_now(self) -> datetime: ...


@dataclass
class AlertWorkerOptions:
    interval: timedelta = timedelta(minutes=1)


class AlertEscalationWorker:
    def __init__(
        self,
        store: AlertStore,
        notifier: AlertNotifier,
        policy: EscalationPolicy,
        clock: Clock,
        options: AlertWorkerOptions,
        log: logging.Logger | None = None,
    ) -> None:
        self._store = store
        self._notifier = notifier
        self._policy = policy
        self._clock = clock
        self._options = options
        self._log = log or logging.getLogger(__name__)

    async def execute(self) -> None:
        """Run until the task is cancelled (the host's stop signal)."""
        while True:
            try:
                await self.run_once()
            except Exception:
                self._log.exception("Alert pass failed; retrying next tick")
            await asyncio.sleep(self._options.interval.total_seconds())

    async def run_once(self) -> None:
        now = self._clock.get_utc_now()
        alerts = await self._store.get_open_alerts()

        for alert in alerts:
            step = self._policy.next_step(alert, now)
            if step is None:
                continue

            next_level = alert.level + 1
            if not await self._store.try_advance(alert.alert_id, alert.level, next_level):
                continue  # another instance already handled it

            to = await self._store.get_addresses(alert.facility_id, step.to)

            sent = False
            try:
                await self._notifier.send(alert, next_level, to)
                sent = True
            except Exception:
                self._log.warning(
                    "Alert %s level %s e-mail failed", alert.alert_id, next_level, exc_info=True
                )

            await self._store.record_email(alert.alert_id, next_level, to, sent)

Requirements: Python 3.12+. Standard library only, nothing to install.

Python Compose and run the alert worker as a long-running service process (p403_r17_5_alert_worker_host_setup.py)
"""Compose and run the alert worker as a long-running service process

Source: ImproveCode, Chapter 17, Recipe 17.5 "The Alert Manager as a Modern Worker Service"
Section: The improved recipe
Book page: 403  -- original C# listing
Converted from C# to Python.
The generic host + DI container becomes hand wiring in an asyncio main; configuration
sections come from appsettings.json. AddWindowsService has no stdlib equivalent: run the
script under a service wrapper (NSSM, pywin32 or systemd). SqlAlertStore is not shown.
"""

import asyncio
import json
import logging
import signal
from datetime import UTC, datetime, timedelta
from pathlib import Path

from p401_r17_5_alert_escalation_policy_model import EscalationPolicy
from p402_r17_5_alert_escalation_worker import AlertEscalationWorker, AlertWorkerOptions
from p406_r17_6_smtp_email_sender import SmtpEmailSender, SmtpOptions
from p407_r17_6_alert_email_notifier import AlertEmailNotifier

SERVICE_NAME = "CFATS Alert Manager"


class SystemClock:
    def get_utc_now(self) -> datetime:
        return datetime.now(UTC)


async def main() -> None:
    logging.basicConfig(level=logging.INFO)
    config = json.loads(Path("appsettings.json").read_text(encoding="utf-8"))

    alerts_cfg = config.get("Alerts", {})
    options = AlertWorkerOptions(
        interval=timedelta(seconds=alerts_cfg.get("IntervalSeconds", 60))
    )
    smtp = SmtpOptions(**config.get("Smtp", {}))

    from cfats_alerts_sql import SqlAlertStore  # data access, not shown in the book

    store = SqlAlertStore(config["ConnectionStrings"]["Cfats"])
    sender = SmtpEmailSender(smtp)
    notifier = AlertEmailNotifier(sender)
    worker = AlertEscalationWorker(
        store, notifier, EscalationPolicy.DEFAULT, SystemClock(), options,
        logging.getLogger(SERVICE_NAME),
    )

    task = asyncio.create_task(worker.execute())
    loop = asyncio.get_running_loop()
    for sig in (signal.SIGINT, signal.SIGTERM):
        try:
            loop.add_signal_handler(sig, task.cancel)
        except NotImplementedError:  # Windows: Ctrl+C raises KeyboardInterrupt instead
            pass
    try:
        await task
    except asyncio.CancelledError:
        pass


if __name__ == "__main__":
    asyncio.run(main())

How it works

PeriodicTimer cannot overlap. WaitForNextTickAsync returns only after the previous pass has finished, so a slow pass delays the next one instead of running beside it. The stop token is the host's shutdown signal: stopping the service cancels the wait and lets the current pass end cleanly. That is what the empty OnStop never did. IOptions replaces re-reading appSettings on every tick.

The order of operations is reversed. The worker first claims the escalation with a conditional update (WHERE AlertLevel = @from). Only the caller that changed the row gets true, so two service instances, or two overlapping passes, can't both send. Then it sends. Then it records the attempt, sent or not, in the alert e-mail table. If SMTP is down, the level has still advanced and the failure is logged and recorded. The user sees one missed e-mail instead of an e-mail every 30 seconds. That is a deliberate choice of at-most-once delivery. For alerts that must arrive, add a retry job that re-sends rows recorded with sent = false.

One failed e-mail no longer stops the loop. The catch logs the failure and moves on to the next alert. The outer catch in ExecuteAsync keeps a database outage from killing the service. It logs and tries again on the next tick.

The thresholds are data. EscalationPolicy.Default holds the product's two outage rules. Training and daily-report rules are more rows, not more SQL constants, and a per-facility policy can be loaded from the existing alert-setting tables. Because the worker takes a TimeProvider, a test can open an alert, advance a fake clock by 4 hours, call RunOnceAsync, and assert who was e-mailed. I ran exactly that check with in-memory fakes while writing this chapter. Nobody could test the original without waiting four real hours.

Variations and pitfalls

  • Let SQL find the candidates. GetOpenAlertsAsync should still filter in SQL (open alerts with level below the maximum). The policy decides only which step, not which of a million rows to load.
  • Store times in UTC. The original compared datetime columns written with DateTime.Now against SYSDATETIME(). That is fine on one server in one time zone and wrong twice a year at the daylight-saving change. Use datetime2 with SYSUTCDATETIME(), or datetimeoffset.
  • Remove ClientID = 1. Loop over clients, or make the client part of OpenAlert. A hard-coded tenant is the easiest assumption to forget when a second customer signs.
  • Log somewhere a person reads. The original appended to logfile.txt beside the executable, without a lock and without rotation. Use ILogger with the Windows Event Log or Serilog (Chapter 4).
  • Hangfire or Quartz.NET make sense when you need many schedules or a dashboard. One fixed-interval loop doesn't need them (Chapter 14).