API 参考#
binomic.client#
- class binomic.client.Binomic(broker_dsn: str, module_name: str, config: BinomicConfig, **broker_kwargs: Any)#
The client tying task discovery, scheduling and submission together.
Constructing one discovers the task modules of
module_nameinto a private registry.start/closemanage the broker and the scheduler; the async context manager additionally assembles theMaster, registers cron/interval tasks and tears everything down on exit.dead_lettersresolves the broker and returns a per-queue operations handle over its dead-letter surface (inspect and replay) when the broker implements the capability.- async close() None#
Stop the scheduler and close the broker; safe to call repeatedly.
- async dead_letters(queue: str) DeadLetters#
Resolve the broker and return its dead-letter operations handle.
Client-side resolution: lazily creates and starts the broker, probes the DLQ capability, then hands the narrowed broker to a
DeadLettershandle bound toqueue(inspect, replay, and on-demand pruning; the worker's retention sweep is the automatic default).
- async start() None#
Start the broker and the scheduler; safe to call repeatedly.
- async submit(message: Message) MessageEntry | None#
Submit a message for delivery according to its task's mode.
directenqueues immediately and returns the broker'sMessageEntry.Nonemeans the enqueue degraded internally (already logged). A full target queue raisesQueueCapacityError.cronandintervaltasks are periodic and rejectsubmit— they are registered when the async context starts.
- class binomic.client.BinomicConfig(queues: list[str], workers: int = 1, concurrency: int = 5, max_attempts: int = 3, task_timeout: float = 600.0, read_count: int = 10, poll_interval: float = 0.1, heartbeat_interval: float = 5.0, reclaim_interval: float = 30.0, dlq_retention: float | None = 604800.0, capacity: int | None = None, worker_init: Callable[[], None] | None = None, otel_enabled: bool = False)#
Binomic configuration.
workersis the number of worker subprocesses the master spawns andconcurrencythe number of tasks each worker executes concurrently; every stream inqueuesis consumed by all workers.max_attemptsis how many times a message may be delivered before it is moved to the DLQ.task_timeoutis a message's total delivery deadline in seconds, measured from enqueue; execution receives the part still left after the queue wait.read_countandpoll_intervalshape each worker's fetch loop;heartbeat_intervalandreclaim_intervalset the liveness beat and crash-recovery cadence.capacitycaps every queue's unacknowledged total (its stream length: messages stay in the stream from submission until ack or dead), so submissions onto a full queue are rejected immediately; unlimited by default. Retry and reclaim re-entries keep the total constant and never consume capacity.dlq_retentionis how long a record may sit in a queue's dead-letter queue before the worker's periodic sweep deletes it;Nonedisables the sweep and keeps DLQ records forever.worker_initruns once per worker subprocess before its event loop starts (the hook for installing OpenTelemetry SDK providers), andotel_enabledgates all telemetry — with the defaultFalsebinomic emits nothing and leaves message envelopes untouched. Structlog logs are not affected by the switch.
- class binomic.client.BinomicFactory(broker_dsn: str, module_name: str, config: BinomicConfig, **broker_config: Any)#
Binomic working client factory.
- class binomic.client.DeadLetters(broker: BrokerDeadLetterCapability, queue: str)#
Operations on one queue's dead letters.
Constructed by
Binomic.dead_letterswith a broker already resolved and probed for the DLQ capability; a thin, stateless facade — the queue is fixed at creation and every call delegates to the broker. Cleanup runs two ways: the worker's retention sweep (dlq_retention) is the automatic default, andpruneis the explicit on-demand trigger.- async depth() int#
Return how many dead letters the queue currently holds.
- async list(limit: int = 50, cursor: str | None = None) tuple[list[DeadLetterEntry], str | None]#
Page through the dead letters oldest-first.
- async prune(retention: float) int#
Delete dead letters older than
retentionseconds; return the count.The explicit counterpart of the worker's automatic sweep — same primitive, invoked on demand.
retentionmust be positive; deletion is irreversible, including records never replayed.
- async read(entry_id: str) DeadLetterEntry | None#
Return one full record by stream entry id, or
None.
- async replay(entry_id: str) MessageEntry | None#
Re-deliver a dead letter as a brand-new message; the record stays.
binomic.client.config#
- class binomic.client.config.BinomicConfig(queues: list[str], workers: int = 1, concurrency: int = 5, max_attempts: int = 3, task_timeout: float = 600.0, read_count: int = 10, poll_interval: float = 0.1, heartbeat_interval: float = 5.0, reclaim_interval: float = 30.0, dlq_retention: float | None = 604800.0, capacity: int | None = None, worker_init: Callable[[], None] | None = None, otel_enabled: bool = False)#
Binomic configuration.
workersis the number of worker subprocesses the master spawns andconcurrencythe number of tasks each worker executes concurrently; every stream inqueuesis consumed by all workers.max_attemptsis how many times a message may be delivered before it is moved to the DLQ.task_timeoutis a message's total delivery deadline in seconds, measured from enqueue; execution receives the part still left after the queue wait.read_countandpoll_intervalshape each worker's fetch loop;heartbeat_intervalandreclaim_intervalset the liveness beat and crash-recovery cadence.capacitycaps every queue's unacknowledged total (its stream length: messages stay in the stream from submission until ack or dead), so submissions onto a full queue are rejected immediately; unlimited by default. Retry and reclaim re-entries keep the total constant and never consume capacity.dlq_retentionis how long a record may sit in a queue's dead-letter queue before the worker's periodic sweep deletes it;Nonedisables the sweep and keeps DLQ records forever.worker_initruns once per worker subprocess before its event loop starts (the hook for installing OpenTelemetry SDK providers), andotel_enabledgates all telemetry — with the defaultFalsebinomic emits nothing and leaves message envelopes untouched. Structlog logs are not affected by the switch.
binomic.task#
- exception binomic.task.DuplicateTaskError#
Exception raised when a task with the same name already exists.
- binomic.task.OnDeadReason#
str的别名
- exception binomic.task.TaskNotFoundError#
Exception raised when a task with the given name does not exist.
- class binomic.task.TaskRegistry#
An in-process name-to-spec map.
Registries are per-owner, not global: the client and every worker handler build their own from
autodiscoverand never share one across processes.
- class binomic.task.TaskScheduler(timezone: tzinfo = datetime.timezone.utc)#
A thin APScheduler wrapper over plain callables.
It knows nothing about task specs: callers supply the callable, the trigger value and the arguments. The client owns one for cron/interval delivery; every handler owns one for retry backoff. Times default to UTC.
- property client: AsyncIOScheduler#
The underlying scheduler, created and started on first access.
- close() None#
Shut the scheduler down without waiting for running jobs.
- cron(func: Callable[[...], Any | Awaitable[Any]], *, cron: str, args: Iterable[Any] | None = None, kwargs: Mapping[str, Any] | None = None) None#
Run
funcon the crontab expressioncron.
- delay(func: Callable[[...], Any | Awaitable[Any]], *, delay: float, args: Iterable[Any] | None = None, kwargs: Mapping[str, Any] | None = None) None#
Run
funconce,delayseconds from now.Misfire grace is disabled, so a late job still runs instead of being silently dropped.
- interval(func: Callable[[...], Any | Awaitable[Any]], *, interval: float, args: Iterable[Any] | None = None, kwargs: Mapping[str, Any] | None = None) None#
Run
funceveryintervalseconds.
- property running: bool#
Whether
starthas been called andclosehas not.
- start() None#
Start the scheduler; idempotent while already running.
- class binomic.task.TaskSpec(name: str, queue: str, func: Callable[[P], T], mode: Literal['direct', 'cron', 'interval'], cron: str | None = None, interval: float | None = None, on_dead_hook: Callable[[MessageEntry, str, BaseException | None], Awaitable[None] | None] | None = None)#
A declared task: its name, queue, callable and scheduling mode.
directtasks run on submission;cronandintervaltasks run periodically and take no arguments. The queue belongs to the declaration, not to the message.
- binomic.task.autodiscover(package: str) list[TaskSpec]#
Import every
tasksmodule underpackageand collect its specs.A tasks module is a
tasks.pyortasks/__init__.pyat any depth below the package. A missing package raisesValueError; anImportErrorraised while importing a tasks module skips that module, and any other error propagates. Specs are returned, not registered.
- binomic.task.task(queue: str, *, mode: Literal['direct'] = 'direct', on_dead: Callable[[MessageEntry, str, BaseException | None], Awaitable[None] | None] | None = None) Callable[[Callable[P, T]], TaskSpec[P, T]]#
- binomic.task.task(queue: str, *, mode: Literal['cron'], cron: str, on_dead: Callable[[MessageEntry, str, BaseException | None], Awaitable[None] | None] | None = None) Callable[[Callable[P, T]], TaskSpec[P, T]]
- binomic.task.task(queue: str, *, mode: Literal['interval'], interval: float, on_dead: Callable[[MessageEntry, str, BaseException | None], Awaitable[None] | None] | None = None) Callable[[Callable[P, T]], TaskSpec[P, T]]
Declare a task in
queueand return itsTaskSpec.directtasks are submitted by name and execute as soon as a worker picks the message.cronandintervaltasks are periodic: the client registers them when its async context starts, so they take no arguments and rejectsubmit.on_deadis an optional notification hook, called once after the message enters the DLQ.
binomic.task.scheduler#
- class binomic.task.scheduler.TaskScheduler(timezone: tzinfo = datetime.timezone.utc)#
A thin APScheduler wrapper over plain callables.
It knows nothing about task specs: callers supply the callable, the trigger value and the arguments. The client owns one for cron/interval delivery; every handler owns one for retry backoff. Times default to UTC.
- property client: AsyncIOScheduler#
The underlying scheduler, created and started on first access.
- close() None#
Shut the scheduler down without waiting for running jobs.
- cron(func: Callable[[...], Any | Awaitable[Any]], *, cron: str, args: Iterable[Any] | None = None, kwargs: Mapping[str, Any] | None = None) None#
Run
funcon the crontab expressioncron.
- delay(func: Callable[[...], Any | Awaitable[Any]], *, delay: float, args: Iterable[Any] | None = None, kwargs: Mapping[str, Any] | None = None) None#
Run
funconce,delayseconds from now.Misfire grace is disabled, so a late job still runs instead of being silently dropped.
- interval(func: Callable[[...], Any | Awaitable[Any]], *, interval: float, args: Iterable[Any] | None = None, kwargs: Mapping[str, Any] | None = None) None#
Run
funceveryintervalseconds.
- property running: bool#
Whether
starthas been called andclosehas not.
- start() None#
Start the scheduler; idempotent while already running.
binomic.broker#
- class binomic.broker.Broker(*args, **kwargs)#
The delivery-path surface every broker implements.
Messages are enqueued into a queue, acquired by a named consumer, then acked, dead-lettered or requeued.
retrypreserves the originalenqueued_at;reclaimrewrites it for recovered deliveries.
- class binomic.broker.BrokerDeadLetterCapability(*args, **kwargs)#
Optional DLQ management surface a broker may implement.
Kept out of
Brokerso custom brokers stay valid without it; callers (theBinomicconvenience methods and the worker's prune sweep) probe for the capability withisinstance. Reads are plain commands whose connection errors propagate — management is an explicit operation, not a delivery-path concern — while the prune script keeps theScriptResponsedegrade contract.- async dlq_depth(queue: str) int#
Return how many records the queue's DLQ currently holds.
- async dlq_list(queue: str, limit: int = 50, cursor: str | None = None) tuple[list[DeadLetterEntry], str | None]#
Page through the DLQ oldest-first.
Returns
(records, next_cursor);next_cursorisNoneat the end of the stream, otherwise feed it back ascursor(an exclusive bound, so pages never repeat or skip). Entries whose hash record is missing are skipped, not errors.
- async dlq_prune(queue: str, retention: float) int#
Delete records that entered the DLQ more than
retentionseconds ago.The entry age comes from the DLQ stream entry id's millisecond stamp, so the payload is never decoded; at most one bounded batch is deleted per call.
retentionmust be positive. Returns the number of records deleted; script failures degrade to0.
- async dlq_read(queue: str, entry_id: str) DeadLetterEntry | None#
Return one full record by DLQ stream entry id, or
None.
- async dlq_replay(queue: str, entry_id: str) MessageEntry | None#
Re-deliver a DLQ record as a brand-new message.
The replay carries a fresh UUID and
attempt = 1(a full retry budget) and targets the record's original queue; the source record is kept. RaisesDeadLetterEntryNotFoundErrorwhen the id is unknown, andQueueCapacityErrorout ofenqueueon a full queue;Nonemeans the enqueue degraded (warning already logged).
- class binomic.broker.BrokerFactory(dsn: str, queues: list[str], namespace: str, capacity: int | None = None, **broker_config: Any)#
A factory class for creating broker instances.
- class binomic.broker.BrokerLifecycleCapability(*args, **kwargs)#
The start/stop half of the broker surface.
Clients and workers bring a broker up through this mixin, so any implementation that wires its own connections on
startfits the framework regardless of inheritance.
- class binomic.broker.BrokerTelemetryCapability(*args, **kwargs)#
Optional observability probes a broker may implement.
Kept out of
Brokerso custom brokers stay valid without them; the framework probes this capability and degrades (root spans, no queue gauges) when it is absent.- async observe(queue: str) tuple[int, float | None] | None#
Probe queue depth for observability, outside the delivery path.
Returns
(depth, oldest entry age in seconds); the age isNoneon an empty stream and the whole resultNonewhen the probe degrades, so a hiccup never reads as an empty queue.
- async trace_context(queue: str, message_id: str) dict[str, str] | None#
Read the delivery trace context stored for a message id.
Nonemeans no context was stored or the read degraded; telemetry then falls back to a root span.
- class binomic.broker.DeadLetterEntry(id: str, queue: str, message: Message, enqueued_at: float, dead_at: float)#
A DLQ record: a message entry plus when it entered the DLQ.
dead_atis derived from the DLQ stream entry id, whose prefix is the Redis server timestamp in milliseconds.- classmethod from_entry(entry: MessageEntry) Self#
Build a DLQ record from
entry, derivingdead_atfrom its id.
- exception binomic.broker.DeadLetterEntryNotFoundError(queue: str, entry_id: str)#
Exception raised when a DLQ entry id has no record to operate on.
Broker.dlq_replayraises it when the entry was never in the DLQ or has since been pruned; the DLQ keeps no tombstones, so the id is simply gone.
- class binomic.broker.Message(*, id: UUID = <factory>, task: str, attempt: int = 1, args: Iterable[Any] | None = None, kwargs: Mapping[str, ~typing.Any] | None=None)#
The payload submitted to a queue.
tasknames the registered task; the queue comes from that task's declaration, never from the message.attemptstarts at 1 and is incremented by the broker on retry and reclaim, so it survives redelivery because it is serialized with the payload.
- class binomic.broker.MessageEntry(id: str, queue: str, message: Message, enqueued_at: float)#
A message plus its delivery envelope, as stored by the broker.
idis the stream entry id,queuethe owning queue, andenqueued_atthe enqueue time in seconds. Retry keeps the original stamp (the deadline is measured from first delivery); reclaim rewrites it.
- exception binomic.broker.QueueCapacityError(current: int, capacity: int)#
Exception raised when a submission is rejected on a full queue.
Broker.enqueueraises it when the target queue's unacknowledged total has reached the effectivecapacity;currentis the depth observed at rejection andcapacitythe limit that was applied.
- class binomic.broker.RedisBroker(dsn: str, queues: Sequence[str], namespace: str, capacity: int | None = None, **config: Any)#
Redis Streams broker backed by atomic Lua scripts.
namespaceis both the key prefix ({namespace}:{queue}:stream) and the consumer group name. Payloads live in a per-queue hash while stream entries carry only the message id; dead messages land in:dlq:streamplus:dlq:hash.capacitycaps every queue's unacknowledged total (the stream length); unlimited by default. It stays an explicit constructor parameter, kept out of**config: everything there feeds the Redis connection pool, so the broker's own options do not compete for that namespace.- async dlq_depth(queue: str) int#
Return how many records the queue's DLQ currently holds.
- async dlq_list(queue: str, limit: int = 50, cursor: str | None = None) tuple[list[DeadLetterEntry], str | None]#
Page through the DLQ oldest-first.
Returns
(records, next_cursor);next_cursorisNoneat the end of the stream, otherwise feed it back ascursor(an exclusive bound, so pages never repeat or skip). Entries whose hash record is missing are skipped, not errors.
- async dlq_prune(queue: str, retention: float) int#
Delete DLQ records older than
retentionseconds; return the count.retentionmust be positive. Deletion is bounded to one batch per call and degrades to0on script failure.
- async dlq_read(queue: str, entry_id: str) DeadLetterEntry | None#
Return one full record by DLQ stream entry id, or
None.
- async dlq_replay(queue: str, entry_id: str) MessageEntry | None#
Re-deliver a DLQ record as a brand-new message.
The replay carries a fresh UUID and
attempt = 1(a full retry budget) and targets the record's original queue; the source record is kept. RaisesDeadLetterEntryNotFoundErrorwhen the id is unknown, andQueueCapacityErrorout ofenqueueon a full queue;Nonemeans the enqueue degraded (warning already logged).
- async enqueue(queue: str, message: Message, context: Mapping[str, str] | None = None) MessageEntry | None#
Enqueue a message, raising on a full queue.
Raises
QueueCapacityErrorwhen the queue's unacknowledged total has reached its effective capacity; internal script failures keep degrading toNone.
- async observe(queue: str) tuple[int, float | None] | None#
Probe queue depth for observability, outside the delivery path.
Returns
(depth, oldest entry age in seconds); the age isNoneon an empty stream and the whole resultNonewhen the probe degrades, so a hiccup never reads as an empty queue.
- async trace_context(queue: str, message_id: str) dict[str, str] | None#
Read the delivery trace context stored for a message id.
Nonemeans no context was stored or the read degraded; telemetry then falls back to a root span.
binomic.worker#
- class binomic.worker.Master(broker_dsn: str, module_name: str, policy: MasterPolicy, method: Literal['spawn'] = 'spawn', **broker_kwargs: Any)#
Supervises a fleet of worker subprocesses.
Every worker beats on a heartbeat cell the master created; the visor restarts any worker whose beat stalls or whose process dies, and hands the replacement a fresh cell.
- async close() None#
Terminate every supervised worker, escalating to kill on timeout.
- async start() None#
Spawn the configured workers and run the supervision loop.
- class binomic.worker.MasterPolicy(workers: int, worker_policy: WorkerPolicy)#
Settings for the master process.
workersis how many worker subprocesses to spawn, each configured by the sameworker_policy.
- class binomic.worker.MasterPresence#
The master's view of every worker's heartbeat cell.
Cells are shared-memory values created by the master and handed to each worker. Reads deliberately skip the cell lock: the lock exists for read-modify-write, and waiting on it would block the visor forever if a worker died while holding it.
- presence() dict[str, float]#
Return each watched worker's last beat, keyed by consumer name.
- watch(ident: str, slave: Synchronized[float]) None#
Track
slave's heartbeat cell underident.Re-watching the same ident replaces the cell, so a restarted worker starts from a fresh beat instead of inheriting its predecessor's.
- class binomic.worker.SlavePresence(heartbeat: Synchronized[float])#
The worker side: write the current time into its heartbeat cell.
- heartbeat() None#
Stamp the current wall-clock time into the shared cell.
- class binomic.worker.Worker(broker_dsn: str, module_name: str, consumer: str, policy: WorkerPolicy, presence: SlavePresence, **broker_config: Any)#
One consumer process: pull from the broker, execute, ack or requeue.
runis the subprocess entry point;arunbuilds the broker and the handler, then pumps acquired entries through an anyio memory stream to a pool of consumers until terminated. Liveness is reported by beating on the presence cell the master handed in.- async arun() None#
Run the pull/execute loop until
closesets the terminate event.
- async close() None#
Stop pulling, cancel in-flight tasks and release the broker.
- run() None#
Subprocess entry point: run the init hook, then
arun.
- async start() None#
Build the broker, handler and terminate event without consuming.
- class binomic.worker.WorkerHandler(module_name: str, consumer: str, broker: Broker, worker_policy: WorkerPolicy)#
Execute one acquired entry and own the retry/backoff decisions.
A handler autodiscovers
module_nameinto a private registry, so the task functions run from the worker's own imports.handleenforces the delivery deadline, dispatches the task, then acks, dead-letters or schedules a retry according to the outcome.- static backoff(attempt: int) float#
Return the delay before the next delivery of
attempt.The curve starts at 1.5 seconds for the second attempt and doubles up to a 30-second ceiling.
- close() None#
Stop the scheduler; pending retry jobs are dropped with it.
- async handle(entry: MessageEntry) None#
Process one entry: execute, then ack, dead-letter or retry.
Entries older than
task_timeoutgo straight to the DLQ without running. Execution gets the remaining part of that deadline; a timeout dead-letters without retrying, an unknown task is acked, and cancellation or process exit propagates without an ack so reclaim can recover the message. Other failures schedule a backoff retry, or dead-letter oncemax_attemptsis exhausted.
- async reclaim() int#
Re-deliver entries whose consumer went silent.
Entries idle past the task deadline (10-second floor) are claimed and requeued; consumer metadata is swept once it has been idle for ten reclaim intervals. Returns how many entries were reclaimed.
- start() None#
Start the handler's own scheduler, which carries retry backoff.
- class binomic.worker.WorkerPolicy(queues: list[str], concurrency: int, task_timeout: float = 600.0, max_attempts: int = 3, read_count: int = 10, poll_interval: float = 0.1, heartbeat_interval: float = 5.0, reclaim_interval: float = 30.0, dlq_retention: float | None = 604800.0, worker_init: Callable[[], None] | None = None, otel_enabled: bool = False)#
Settings for one worker subprocess.
queuesare consumed by every worker andconcurrencybounds the tasks one worker executes at once.task_timeoutis the total delivery deadline from enqueue;max_attemptsis the retry budget before the message enters the DLQ.read_countandpoll_intervalshape the fetch loop;heartbeat_intervalandreclaim_intervalset the liveness beat and crash-recovery cadence.dlq_retentionis the age after which the periodic sweep deletes DLQ records (Nonedisables it).worker_initruns once per subprocess, inWorker.runbefore the event loop starts — the hook where an embedding application installs its OpenTelemetry SDK providers.otel_enabledgates every telemetry call: with the defaultFalsebinomic emits no spans, metrics and never touches the envelope's trace fields.
binomic.otel#
- class binomic.otel.Telemetry(scope: str = 'binomic')#
Thin wrapper over the OpenTelemetry tracer and meter.
Constructing one requires
opentelemetry-api; the module-levelotelinstance isNonewhen the dependency is missing, so callers gate on it instead of catching import errors. Spans and instruments are created lazily against whatever SDK providers the embedding application installed.- static capture_context() dict[str, str]#
Serialize the current trace context into a header carrier.
- create_counter(name: str, unit: str) Counter#
Create a monotonically increasing counter instrument.
- create_histogram(name: str, unit: str) Histogram#
Create a histogram instrument for value distributions.
- create_observable_gauge(name: str, unit: str, observe: Callable[[], Iterable[tuple[float, dict[str, str]]]]) ObservableGauge#
Create a gauge whose value is read from
observeat collection.observereturns(value, attributes)pairs, so one instrument covers every queue or worker the caller tracks.
- create_up_down_counter(name: str, unit: str) UpDownCounter#
Create a counter that can increase and decrease.
- static extract_context(carrier: Mapping[str, str] | None) Any#
Rebuild a trace context from
carrier, falling back to current.
- static mark_span_error(exc: BaseException) None#
Record
excon the current span and mark it as error.
- start_process_span(task: str, carrier: Mapping[str, str] | None, attributes: dict[str, str | int]) Any#
Start the consumer span for
task, continuingcarrier.A
Noneor unreadable carrier yields a root span rather than breaking execution.
- start_producer_span(queue: str, attributes: Mapping[str, str | None]) Any#
Start the span that represents enqueueing into
queue.
binomic.base#
- class binomic.base.BaseStruct#
Base structure for data schemas.
Adds dict/JSON/TOML/YAML round trips on top of msgspec's
Struct. Encoding and decoding errors are raised by msgspec unchanged, so callers can catchTypeError,msgspec.ValidationErrorandmsgspec.DecodeErrordirectly.
- exception binomic.base.BinomicError#
Base class for binomic exceptions.
binomic.plugin.litestar#
- class binomic.plugin.litestar.BinomicPlugin(*args: Any, **kwargs: Any)#
Wire a Binomic client into a Litestar application.
app_namedoubles as the client'smodule_name, so task discovery and the Redis namespace follow it. The plugin registers aBinomicFactoryinapp.state, exposes abinomicdependency, and enters the client's async context from the application lifespan.