Skip to main content

ClientBuilder

Struct ClientBuilder 

Source
pub struct ClientBuilder { /* private fields */ }
Expand description

Builder for the Awa worker client.

Implementations§

Source§

impl ClientBuilder

Source

pub fn new(pool: PgPool) -> Self

Source

pub fn queue(self, name: impl Into<String>, config: QueueConfig) -> Self

Add a queue with its configuration.

Source

pub fn partitioned_queue( self, partitioned_queue: &PartitionedQueue, config: QueueConfig, ) -> Self

Add every physical queue in a logical partitioned queue.

This is equivalent to calling queue once for each physical queue in the partitioned queue. Producers should route inserts through the same PartitionedQueue so workers and producers agree on the physical queue names.

The config is applied to each physical queue. In hard-reserved mode, total logical capacity is therefore roughly partitioned_queue.partitions() * config.max_workers; per-queue rate limits also apply per physical queue. Divide those knobs yourself, or use weighted mode with a global_max_workers cap, when you need a logical total.

Source

pub fn queue_descriptor( self, name: impl Into<String>, descriptor: QueueDescriptor, ) -> Self

Attach descriptive metadata (display name, description, owner, docs URL, tags, extra JSON) to a queue so it appears labelled in the admin API and UI. The queue must also be declared via queue; otherwise build fails with BuildError::QueueDescriptorWithoutQueue.

Source

pub fn job_kind_descriptor<T: JobArgs>( self, descriptor: JobKindDescriptor, ) -> Self

Attach descriptive metadata to a typed job kind. The kind string is taken from JobArgs::kind on T.

Source

pub fn job_kind_descriptor_kind( self, kind: impl Into<String>, descriptor: JobKindDescriptor, ) -> Self

Attach descriptive metadata to a job kind by string name. Useful when the kind is known dynamically (e.g. from language bridges).

Source

pub fn register<T, F, Fut>(self, handler: F) -> Self
where T: JobArgs + DeserializeOwned + Send + Sync + 'static, F: Fn(T, &JobContext) -> Fut + Send + Sync + 'static, Fut: Future<Output = Result<JobResult, JobError>> + Send + 'static,

Register a typed worker.

The worker handles jobs of type T where T: JobArgs + DeserializeOwned. The handler function receives the deserialized args and job context.

Source

pub fn on_event<T, F, Fut>(self, handler: F) -> Self
where T: JobArgs + DeserializeOwned + Send + Sync + 'static, F: Fn(JobEvent<T>) -> Fut + Send + Sync + 'static, Fut: Future<Output = ()> + Send + 'static,

Register a typed lifecycle event handler for a job kind.

Started dispatch is scheduled after the claim commits and before the worker handler is invoked. Outcome handlers run only after the corresponding DB state transition commits. Hooks are best-effort in-process notifications, not a durable workflow mechanism; because they run in detached tasks, a very short job can complete before a Started handler finishes. Capture any shared dependencies you need in the closure environment.

Source

pub fn on_event_kind<F, Fut>(self, kind: impl Into<String>, handler: F) -> Self
where F: Fn(UntypedJobEvent) -> Fut + Send + Sync + 'static, Fut: Future<Output = ()> + Send + 'static,

Register an untyped lifecycle event handler for a specific job kind.

Use this with register_worker(...) or for cross-cutting logic that doesn’t need typed args. Timing matches on_event(...).

Source

pub fn on_completed_enqueue<T, F, MakeFn>(self, make: MakeFn) -> Self
where T: JobArgs + DeserializeOwned + Send + Sync + 'static, F: JobArgs + Send + Sync + 'static, MakeFn: Fn(T, &JobRow) -> F + Send + Sync + 'static,

Register a durable follow-up Awa job to enqueue when a job of type T completes successfully.

make receives the trigger’s deserialised args plus its post-completion awa_model::JobRow and returns the follow-up’s JobArgs value. The follow-up is enqueued with default awa_model::InsertOpts — use Self::on_completed_enqueue_with to override queue, priority, or other insert options.

§Atomicity

Whether the trigger completes from the worker handler (Ok(Completed)) or via callback resolution (Client::complete_external, Client::resolve_callback with a Complete action), the follow-up INSERTs in the same database transaction as the completion’s state change. The trigger and the follow-up commit or roll back together (ADR-029, ADR-013 run-lease guard). A spec INSERT failure or a panic in this closure rolls the completion back as well, so a failed callback can be redelivered by the external sender rather than leaving the job half-applied.

This is the durable counterpart to Self::on_event: hooks are best-effort, in-process; this enqueue is at-least-once and rides Awa’s existing retry/DLQ machinery.

Multiple registrations for the same kind stack and all run in the same dispatch.

Source

pub fn on_completed_enqueue_with<T, F, MakeFn>(self, make: MakeFn) -> Self
where T: JobArgs + DeserializeOwned + Send + Sync + 'static, F: JobArgs + Send + Sync + 'static, MakeFn: Fn(T, &JobRow) -> EnqueueRequest<F> + Send + Sync + 'static,

Like Self::on_completed_enqueue but lets the closure return an EnqueueRequest with explicit queue, priority, or other awa_model::InsertOpts overrides.

Source

pub fn on_retried_enqueue<T, F, MakeFn>(self, make: MakeFn) -> Self
where T: JobArgs + DeserializeOwned + Send + Sync + 'static, F: JobArgs + Send + Sync + 'static, MakeFn: Fn(T, &JobRow, &str, i16, DateTime<Utc>) -> F + Send + Sync + 'static,

Register a durable follow-up Awa job to enqueue when a job of type T is retried (whether via Ok(RetryAfter) or a retryable Err). make receives the trigger’s args, its post-retry JobRow, the error string, the previous attempt number, and the next-run-at timestamp.

Atomicity matches Self::on_completed_enqueue: worker-driven retries dispatch in the transition’s transaction, and a retry driven by Client::retry_external dispatches in the same transaction as the resolution. A spec failure rolls the retry transition back so the external sender can redeliver.

Source

pub fn on_retried_enqueue_with<T, F, MakeFn>(self, make: MakeFn) -> Self
where T: JobArgs + DeserializeOwned + Send + Sync + 'static, F: JobArgs + Send + Sync + 'static, MakeFn: Fn(T, &JobRow, &str, i16, DateTime<Utc>) -> EnqueueRequest<F> + Send + Sync + 'static,

Like Self::on_retried_enqueue but the closure returns an EnqueueRequest with InsertOpts overrides.

Source

pub fn on_exhausted_enqueue<T, F, MakeFn>(self, make: MakeFn) -> Self
where T: JobArgs + DeserializeOwned + Send + Sync + 'static, F: JobArgs + Send + Sync + 'static, MakeFn: Fn(T, &JobRow, &str, i16) -> F + Send + Sync + 'static,

Register a durable follow-up Awa job to enqueue when a job of type T is exhausted (retries used up or Err(JobError::Terminal)). make receives the trigger’s args, its post-failure JobRow, the error string, and the attempt number.

Atomicity matches Self::on_completed_enqueue: worker-driven exhaustion dispatches in the transition’s transaction, and an exhaustion driven by Client::fail_external or Client::resolve_callback with a Fail action dispatches in the same transaction as the resolution. A spec failure rolls the failure transition back so the external sender can redeliver.

Source

pub fn on_exhausted_enqueue_with<T, F, MakeFn>(self, make: MakeFn) -> Self
where T: JobArgs + DeserializeOwned + Send + Sync + 'static, F: JobArgs + Send + Sync + 'static, MakeFn: Fn(T, &JobRow, &str, i16) -> EnqueueRequest<F> + Send + Sync + 'static,

Like Self::on_exhausted_enqueue but the closure returns an EnqueueRequest with InsertOpts overrides.

Source

pub fn on_cancelled_enqueue<T, F, MakeFn>(self, make: MakeFn) -> Self
where T: JobArgs + DeserializeOwned + Send + Sync + 'static, F: JobArgs + Send + Sync + 'static, MakeFn: Fn(T, &JobRow, &str) -> F + Send + Sync + 'static,

Register a durable follow-up Awa job to enqueue when a job of type T is cancelled via Ok(JobResult::Cancel(reason)). make receives the trigger’s args, its post-cancellation JobRow, and the reason string.

See Self::on_completed_enqueue for the same-transaction semantics.

Source

pub fn on_cancelled_enqueue_with<T, F, MakeFn>(self, make: MakeFn) -> Self
where T: JobArgs + DeserializeOwned + Send + Sync + 'static, F: JobArgs + Send + Sync + 'static, MakeFn: Fn(T, &JobRow, &str) -> EnqueueRequest<F> + Send + Sync + 'static,

Like Self::on_cancelled_enqueue but the closure returns an EnqueueRequest with InsertOpts overrides.

Source

pub fn on_waiting_for_callback_enqueue<T, F, MakeFn>(self, make: MakeFn) -> Self
where T: JobArgs + DeserializeOwned + Send + Sync + 'static, F: JobArgs + Send + Sync + 'static, MakeFn: Fn(T, &JobRow) -> F + Send + Sync + 'static,

Register a durable follow-up Awa job to enqueue when a job of type T parks on an external callback (Ok(JobResult::WaitForCallback)). make receives the trigger’s args plus the parked JobRow (job.callback_id and job.callback_timeout_at identify the pending callback).

See Self::on_completed_enqueue for the same-transaction semantics.

Source

pub fn on_waiting_for_callback_enqueue_with<T, F, MakeFn>( self, make: MakeFn, ) -> Self
where T: JobArgs + DeserializeOwned + Send + Sync + 'static, F: JobArgs + Send + Sync + 'static, MakeFn: Fn(T, &JobRow) -> EnqueueRequest<F> + Send + Sync + 'static,

Like Self::on_waiting_for_callback_enqueue but the closure returns an EnqueueRequest with InsertOpts overrides.

Source

pub fn on_rescued_enqueue<T, F, MakeFn>(self, make: MakeFn) -> Self
where T: JobArgs + DeserializeOwned + Send + Sync + 'static, F: JobArgs + Send + Sync + 'static, MakeFn: Fn(T, &JobRow, RescueReason) -> F + Send + Sync + 'static,

Register a durable follow-up Awa job to enqueue when a job of type T is rescued by maintenance (expired callback, stale heartbeat, or deadline exceeded). make receives the trigger’s args, its post-rescue JobRow, and the RescueReason.

Atomicity: best-effort, separate transaction. Maintenance rescues commit the rescue UPDATE before this dispatcher runs; the follow-up dispatch opens its own transaction afterwards. If the spec INSERT fails the rescue stands and the failure is logged. Don’t predicate a workflow on a rescue-driven follow-up landing — for compensation after a stuck attempt, build the follow-up handler to be safely re-runnable. The atomic variant is tracked as an open extension in ADR-029.

Source

pub fn on_rescued_enqueue_with<T, F, MakeFn>(self, make: MakeFn) -> Self
where T: JobArgs + DeserializeOwned + Send + Sync + 'static, F: JobArgs + Send + Sync + 'static, MakeFn: Fn(T, &JobRow, RescueReason) -> EnqueueRequest<F> + Send + Sync + 'static,

Like Self::on_rescued_enqueue but the closure returns an EnqueueRequest with InsertOpts overrides.

Source

pub fn register_worker(self, worker: impl Worker + 'static) -> Self

Register a raw worker implementation.

Source

pub fn state<T: Any + Send + Sync + Clone>(self, value: T) -> Self

Add shared state accessible via ctx.extract::<T>().

Source

pub fn heartbeat_interval(self, interval: Duration) -> Self

Set the heartbeat interval (default: 30s).

Source

pub fn promote_interval(self, interval: Duration) -> Self

Set the scheduled/retryable promotion interval (default: 250ms).

Source

pub fn heartbeat_rescue_interval(self, interval: Duration) -> Self

Set the stale-heartbeat rescue interval (default: 30s).

Source

pub fn heartbeat_staleness(self, staleness: Duration) -> Self

Set how long a heartbeat must be stale before the job is rescued (default: 90s).

Should be at least 3× the heartbeat interval to avoid false rescues.

Source

pub fn deadline_rescue_interval(self, interval: Duration) -> Self

Set the deadline rescue interval (default: 30s).

Source

pub fn callback_rescue_interval(self, interval: Duration) -> Self

Set the callback-timeout rescue interval (default: 30s).

Source

pub fn leader_election_interval(self, interval: Duration) -> Self

Set the leader election retry interval (default: 10s).

Controls how often a non-leader instance retries acquiring the maintenance advisory lock. Lower values are useful in tests.

Source

pub fn leader_check_interval(self, interval: Duration) -> Self

Set the leader connection health-check interval (default: 30s).

Source

pub fn global_max_workers(self, max: u32) -> Self

Set a global maximum worker count across all queues (enables weighted mode).

When set, each queue gets min_workers guaranteed permits plus a share of the remaining overflow capacity based on weight.

Source

pub fn completed_retention(self, retention: Duration) -> Self

Set retention for completed jobs (default: 24h).

Source

pub fn failed_retention(self, retention: Duration) -> Self

Set retention for failed/cancelled jobs (default: 72h).

Source

pub fn descriptor_retention(self, retention: Duration) -> Self

How long a descriptor catalog row can go un-refreshed before the maintenance leader deletes it (default: 30 days). Pass Duration::ZERO to disable — the catalog will then accumulate rows indefinitely. See MaintenanceService::descriptor_retention.

Source

pub fn cleanup_batch_size(self, batch_size: i64) -> Self

Set the maximum number of jobs to delete per cleanup pass (default: 1000).

Source

pub fn cleanup_interval(self, interval: Duration) -> Self

Set the cleanup interval (default: 60s).

Source

pub fn queue_retention( self, queue: impl Into<String>, policy: RetentionPolicy, ) -> Self

Set a per-queue retention override.

Source

pub fn runtime_snapshot_interval(self, interval: Duration) -> Self

Set how often runtime observability snapshots are published (default: 10s).

Source

pub fn priority_aging_interval(self, interval: Duration) -> Self

Set the maintenance priority aging interval.

This controls how often waiting available jobs are promoted toward higher priority to prevent starvation. It is a global maintenance setting for this worker runtime.

Source

pub fn terminal_count_rollup_interval(self, interval: Duration) -> Self

Set how often queue-storage terminal-count deltas are rolled into folded live counters (default: 30s).

Exact queue-depth reads include both folded counters and pending deltas, so increasing this interval trades a larger append-only delta ledger for fewer maintenance writes to the mutable counter table.

Source

pub fn queue_stats_interval(self, interval: Duration) -> Self

Set how often queue depth/lag metrics are published (default: 30s).

Source

pub fn dlq_enabled_by_default(self, enabled: bool) -> Self

Enable or disable DLQ routing by default.

Source

pub fn queue_dlq_enabled(self, queue: impl Into<String>, enabled: bool) -> Self

Override DLQ routing for a single queue.

Source

pub fn dlq_retention(self, retention: Duration) -> Self

Set retention for DLQ rows.

Source

pub fn dlq_cleanup_batch_size(self, batch_size: i64) -> Self

Set the maximum number of DLQ rows deleted per cleanup pass.

Source

pub fn queue_storage( self, config: QueueStorageConfig, queue_rotate_interval: Duration, lease_rotate_interval: Duration, ) -> Self

Override the segmented queue storage configuration for this runtime.

Queue storage is the default worker engine. Canonical tables remain migration compatibility, not a second supported worker runtime. Use this to change the schema name or rotation sizing/timing.

Source

pub fn claim_rotate_interval(self, claim_rotate_interval: Duration) -> Self

Override the ADR-023 claim-ring rotation cadence.

Defaults to queue_rotate_interval so claim partitions age out in step with the ready / done partitions they reference. Only takes effect when queue storage is active; no-op on the canonical engine.

Source

pub fn canonical_storage(self) -> Self

Force the worker runtime onto canonical storage.

This is primarily useful for migration/testing and benchmark comparisons against the pre-0.6 engine. Production 0.6 runtimes should normally use queue storage.

Source

pub fn transition_role(self, role: TransitionWorkerRole) -> Self

Choose how this runtime participates in a storage transition.

Source

pub fn periodic(self, job: PeriodicJob) -> Self

Register a periodic (cron) job schedule.

The schedule is synced to the database by the leader and evaluated every second. When a fire is due, a job is atomically enqueued.

Source

pub fn build(self) -> Result<Client, BuildError>

Build the client.

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T> FutureExt for T

Source§

fn with_context(self, otel_cx: Context) -> WithContext<Self>

Attaches the provided Context to this type, returning a WithContext wrapper. Read more
Source§

fn with_current_context(self) -> WithContext<Self>

Attaches the current Context to this type, returning a WithContext wrapper. Read more
Source§

impl<T> Instrument for T

Source§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Source§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> IntoEither for T

Source§

fn into_either(self, into_left: bool) -> Either<Self, Self>

Converts self into a Left variant of Either<Self, Self> if into_left is true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
where F: FnOnce(&Self) -> bool,

Converts self into a Left variant of Either<Self, Self> if into_left(&self) returns true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<V, T> VZip<V> for T
where V: MultiLane<T>,

Source§

fn vzip(self) -> V

Source§

impl<T> WithSubscriber for T

Source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more