base_service
base_service
¶
Abstract base class for long-running BigBrotr services.
BaseService[ConfigT] provides the standard lifecycle for all services:
structured logging via Logger, graceful
shutdown via asyncio.Event, configurable interval-based cycling with
run_forever(),
consecutive failure limits, and automatic Prometheus metrics tracking via
MetricsServer.
Services persist operational state through Brotr.upsert_service_state() and Brotr.get_service_state() rather than in-memory storage.
See Also
Brotr: Database interface injected into every service. Pool: Connection pool managed by Brotr. BaseServiceConfig: Base configuration model for all services.
Classes¶
BaseServiceConfig
¶
Bases: BaseModel
Base configuration shared by all services that run in a loop.
Subclass this to add service-specific fields. The fields defined here control the run_forever() cycle interval, failure tolerance, and Prometheus metrics exposition.
See Also
BaseService: The abstract service class that consumes this configuration. MetricsConfig: Embedded configuration for the Prometheus metrics endpoint.
BaseService
¶
BaseService(brotr: Brotr, config: ConfigT | None = None)
Bases: ABC, Generic[ConfigT]
Abstract base class for all BigBrotr services.
Subclasses must set SERVICE_NAME to a unique string identifier,
set CONFIG_CLASS to their Pydantic config model, and implement
run() with the main
service logic.
Attributes:
-
SERVICE_NAME(ServiceName) –Unique service identifier used in logging and metrics.
-
CONFIG_CLASS(type[BaseModel]) –Pydantic model class used by factory methods to parse configuration from YAML/dict sources.
-
_brotr–Brotr database interface for all database operations.
-
_config(ConfigT) –Typed service configuration (defaults from
CONFIG_CLASS). -
_logger–Logger named after the service.
-
_shutdown_event–asyncio.Eventcontrolling the run loop. Clear means the service is running; set means shutdown was requested.
Note
The lifecycle pattern is: async with brotr: then
async with service: then
run_forever()
(or a single
run() call with
--once). The async context manager clears/sets the shutdown
event on entry/exit, while
run_forever()
handles the cycle loop, metrics, and failure tracking.
See Also
Brotr: Database interface injected via the constructor. BaseServiceConfig: Base configuration model with interval, failure limits, and metrics settings. Logger: Structured logging used internally. MetricsServer: Prometheus endpoint started alongside the service.
Source code in src/bigbrotr/core/base_service.py
Attributes¶
is_running
property
¶
Whether the service is still active (shutdown not yet requested).
Functions¶
run
abstractmethod
async
¶
Execute one cycle of the service's main logic.
Called repeatedly by run_forever(). Implementations should perform a bounded unit of work and return. Long-running work should periodically check is_running for early exit.
See Also
run_forever(): The loop that calls this method repeatedly.
Source code in src/bigbrotr/core/base_service.py
request_shutdown
¶
Request a graceful shutdown of the service.
Safe to call from signal handlers or other threads because
setting an asyncio.Event is atomic. The next
wait() call in
run_forever()
will detect the signal and break the loop.
See Also
is_running: Property that reflects whether shutdown has been requested.
Source code in src/bigbrotr/core/base_service.py
wait
async
¶
Wait for either a shutdown signal or a timeout to elapse.
Returns True if shutdown was requested during the wait, or
False if the timeout expired normally. Use this instead of
asyncio.sleep() to enable interruptible waits.
Note
This method is used internally by run_forever() for the inter-cycle sleep. Subclasses can also use it for long-running operations that should be interruptible by a request_shutdown() call.
Source code in src/bigbrotr/core/base_service.py
run_forever
async
¶
Run the service in an infinite loop with interval-based cycling.
Repeatedly calls
run(), sleeping for
config.interval seconds between cycles. Exits when shutdown
is requested via
request_shutdown()
or when the consecutive failure limit
(config.max_consecutive_failures) is reached. A value of 0
disables the failure limit.
Prometheus metrics are tracked automatically:
cycles_success, cycles_failed,
errors_{ExceptionType} (via
SERVICE_COUNTER),
consecutive_failures, last_cycle_timestamp (via
SERVICE_GAUGE), and
cycle_duration_seconds (via
CYCLE_DURATION_SECONDS).
The consecutive failure counter resets after each successful cycle.
CancelledError, KeyboardInterrupt, and SystemExit always
propagate immediately without being counted as failures.
Note
The inter-cycle sleep uses
wait() rather
than asyncio.sleep() so that a shutdown signal can interrupt
the wait immediately instead of blocking until the next cycle.
See Also
run(): The abstract method called each cycle. request_shutdown(): Trigger graceful exit from this loop.
Source code in src/bigbrotr/core/base_service.py
198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 | |
from_yaml
classmethod
¶
from_yaml(
config_path: str, brotr: Brotr, **kwargs: Any
) -> Self
Create a service instance from a YAML configuration file.
Delegates to load_yaml() for safe YAML parsing, then to from_dict() for construction.
Parameters:
-
config_path(str) –Path to the YAML file.
-
brotr(Brotr) –Brotr database interface for the service.
-
**kwargs(Any, default:{}) –Additional keyword arguments passed to the constructor.
See Also
from_dict(): Construct from a pre-parsed dictionary.
Source code in src/bigbrotr/core/base_service.py
from_dict
classmethod
¶
from_dict(
data: dict[str, Any], brotr: Brotr, **kwargs: Any
) -> Self
Create a service instance from a configuration dictionary.
Parses data into the service's CONFIG_CLASS Pydantic model.
Parameters:
-
data(dict[str, Any]) –Configuration dictionary parsed into
CONFIG_CLASS. -
brotr(Brotr) –Brotr database interface for the service.
-
**kwargs(Any, default:{}) –Additional keyword arguments passed to the constructor.
Source code in src/bigbrotr/core/base_service.py
set_gauge
¶
Set a named gauge metric for this service.
Records a point-in-time value via the shared
SERVICE_GAUGE Prometheus
metric with service and name labels. No-op if metrics
are disabled in
MetricsConfig.
Parameters:
-
name(str) –Metric name (e.g.
"pending","queue_size"). -
value(float) –Current numeric value.
See Also
inc_counter(): Increment a cumulative counter metric.
Source code in src/bigbrotr/core/base_service.py
inc_counter
¶
Increment a named counter metric for this service.
Records a monotonically increasing total via the shared
SERVICE_COUNTER Prometheus
metric. Counters persist across cycles, making them suitable for
cumulative totals. No-op if metrics are disabled in
MetricsConfig.
Parameters:
-
name(str) –Metric name (e.g.
"total_processed","total_promoted"). -
value(float, default:1) –Amount to increment (default: 1).
See Also
set_gauge(): Set a point-in-time gauge metric.