Invoker
Handler invocation for bus listeners: HandlerInvoker and the near-miss DropReporter protocol.
DropReporter
Bases: Protocol
Records one event that reached an app listener and didn't run its handler (a near-miss).
BusService binds one per app listener at registration. Drop sites don't call it directly: they call
Delivery.drop, which passes the delivery's event and synthetic flag.
Source code in src/hassette/bus/invoker.py
42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 | |
HandlerInvoker
dataclass
Owns handler invocation, async wrapping, parameter injection, rate limiting, and the once-guard.
Source code in src/hassette/bus/invoker.py
59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 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 | |
orig_handler: HandlerType
instance-attribute
Original handler function provided by the user.
async_handler: AsyncHandlerType
instance-attribute
Async-wrapped handler function.
injector: ParameterInjector
instance-attribute
Parameter injector for dependency injection.
kwargs: Mapping[str, Any] | None
instance-attribute
Keyword arguments to pass to the handler.
error_handler: BusErrorHandlerType | None
instance-attribute
Optional per-listener error handler.
app_error_handler_resolver: Callable[[], BusErrorHandlerType | None] | None
instance-attribute
Closure that resolves the app-level error handler at dispatch time.
rate_limiter: RateLimiter | None
instance-attribute
Rate limiter for debounce/throttle. None when no rate limiting is configured.
task_bucket: TaskBucket
instance-attribute
TaskBucket used to spawn the cancellable child handler task for non-parallel modes.
guard: ExecutionModeGuard
instance-attribute
Per-listener overlap state machine. Owns the running-task reference and live counters.
options: ListenerOptions
instance-attribute
The listener's behavioral options. Dispatch reads once, mode and the timeout fields from here.
handler_short_name: str
instance-attribute
Short handler name, captured for the stall WARNING and debug logs.
backpressure_dropped: int = 0
class-attribute
instance-attribute
Count of events dropped at the dispatch acquire gate due to DROP_NEWEST backpressure. Incremented only in BusService.dispatch — one writer, on the event loop, no await between the locked() check and the increment. Live-only; resets on restart, never persisted.
fired: bool = field(default=False, init=False)
class-attribute
instance-attribute
Guard for once=True: set before the first invocation to prevent double-fire.
report_drop: DropReporter | None = field(default=None, init=False)
class-attribute
instance-attribute
Near-miss reporter, bound by BusService at registration for app listeners, and unbound by Listener.cancel() so a removed listener records nothing more. None records nothing.
pending_done: set[asyncio.Future[None]] = field(default_factory=set, init=False)
class-attribute
instance-attribute
Unresolved per-invocation completion futures for non-parallel modes.
Each run_with_mode call (single/restart/queued) parks its outer dispatch task on a future
that resolves when the handler actually runs (or is dropped/released). A queued trigger accepted
into the deque has no live child until drain time, so its future would hang forever if the
listener is released first. release_guard resolves every remaining future here so those outer
dispatch tasks unwind and _dispatch_pending settles.
create(task_bucket: TaskBucket, handler: HandlerType, kwargs: Mapping[str, Any] | None, options: ListenerOptions, error_handler: BusErrorHandlerType | None = None, app_error_handler_resolver: Callable[[], BusErrorHandlerType | None] | None = None, clock: Callable[[], float] | None = None) -> HandlerInvoker
classmethod
Construct a HandlerInvoker from a handler and options.
Builds the async wrapper, injector, and rate limiter, and keeps a reference to options.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
task_bucket
|
TaskBucket
|
TaskBucket for async adapter and rate limiter. |
required |
handler
|
HandlerType
|
The user-supplied handler callable. |
required |
kwargs
|
Mapping[str, Any] | None
|
Optional keyword arguments to pass to the handler. |
required |
options
|
ListenerOptions
|
Behavioral options (once, debounce, throttle). |
required |
error_handler
|
BusErrorHandlerType | None
|
Optional per-listener error handler. |
None
|
app_error_handler_resolver
|
Callable[[], BusErrorHandlerType | None] | None
|
Closure for app-level error handler resolution. |
None
|
clock
|
Callable[[], float] | None
|
Zero-arg callable returning the current monotonic time, forwarded to the
RateLimiter for deterministic throttle timing in tests. Defaults to
|
None
|
Source code in src/hassette/bus/invoker.py
117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 | |
mark_fired() -> None
Mark this once-invoker as having fired. Called by dispatch() and Listener.cancel().
Source code in src/hassette/bus/invoker.py
172 173 174 | |
dispatch(delivery: Delivery, executor: CommandExecutor, config_resolver: Callable[[], float | None]) -> None
async
Run delivery through the once-guard, rate limiter, and overlap mode.
Order: once-guard → rate limiter (whether to start) → mode guard (overlap of started
invocations). The run itself is delivery.invoke(executor, config_resolver) (tracked telemetry).
delivery is for this invoker's listener.
Once-guard: if once=True and the invoker has already fired, returns immediately. Safe
without a lock — no await between check-and-set.
Mode guard: parallel runs invoke_fn as a child task in task_bucket (the owning
Bus's) and awaits it through run_parallel, so the owner's teardown cancels it; a sealed
bucket means the owner is stopping, and the invocation is skipped. For
single/restart/queued the guard receives a run-and-track callable that spawns a
fresh child task through task_bucket; this method then awaits that child so the outer
dispatch task stays pending and remains counted by _dispatch_pending. A restart
cancellation of the child surfaces as CancelledError inside the child only — it is swallowed
here so the outer dispatch task does not crash.
config_resolver returns the global handler timeout, the same one the run
enforces. BusService owns it, so a listener's stall threshold follows that timeout however the
listener was built.
Every step that drops the delivery reports it with delivery.drop.
Source code in src/hassette/bus/invoker.py
176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 | |
run_with_mode(delivery: Delivery, executor: CommandExecutor, config_resolver: Callable[[], float | None]) -> None
async
Apply the overlap mode guard to a single started invocation, reporting a busy/queue_full drop.
Source code in src/hassette/bus/invoker.py
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 | |
effective_timeout(config_resolver: Callable[[], float | None]) -> float | None
Return the timeout enforced for one invocation, or None if it has none.
The enforced timeout and the stall threshold both read this, so they can't disagree.
Source code in src/hassette/bus/invoker.py
255 256 257 258 259 260 | |
warn_stalled(threshold: float, effective_timeout: float | None) -> None
Emit the feature's stall WARNING: a non-parallel handler is still holding its guard.
Source code in src/hassette/bus/invoker.py
262 263 264 265 266 267 268 269 | |
cancel() -> None
Cancel any pending rate-limiter tasks.
Source code in src/hassette/bus/invoker.py
271 272 273 274 | |
release_guard() -> None
async
Release the execution-mode guard: cancel the in-flight task and drop queued factories.
Called when a listener is cancelled or replaced so no event/listener/app references leak.
parallel listeners hold no guard state, so this is a cheap no-op for them.
Queued triggers still parked in the guard's deque never spawn a child once released, so
their outer dispatch tasks are parked on done futures that nothing else will resolve.
release_and_drain resolves every remaining one so those tasks unwind and
_dispatch_pending settles.
Source code in src/hassette/bus/invoker.py
276 277 278 279 280 281 282 283 284 285 286 287 | |
invoke(event: AnyEvent) -> None
async
Invoke the handler with dependency injection.
Source code in src/hassette/bus/invoker.py
289 290 291 292 | |
make_async_handler(fn: HandlerType, task_bucket: TaskBucket) -> AsyncHandlerType
Wrap a function to ensure it is always called as an async handler.
If the function is already an async function, it will be called directly. If it is a regular function, it will be run in an executor to avoid blocking the event loop.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
fn
|
HandlerType
|
The function to adapt. |
required |
task_bucket
|
TaskBucket
|
TaskBucket used to create the async adapter (runs sync handlers in executor). |
required |
Returns:
| Type | Description |
|---|---|
AsyncHandlerType
|
An async handler that wraps the original function. |
Source code in src/hassette/bus/invoker.py
295 296 297 298 299 300 301 302 303 304 305 306 307 308 | |