Skip to main content

PostgresStorage

Struct PostgresStorage 

Source
pub struct PostgresStorage<Args, Codec = JsonCodec<CompactType>, Fetcher = PgFetcher<CompactType, Codec>> { /* private fields */ }
Expand description

PostgreSQL storage backend implemented with Diesel.

Implementations§

Source§

impl<Args> PostgresStorage<Args>

Source

pub fn new(pool: &PgPool) -> Self

Create storage for the queue named after Args.

Do not share pool with HTTP request handlers or other unrelated workloads. Apalis holds long-lived connections (fetcher, lifecycle keep-alive, listener) and a backend that exhausts a shared pool will stall the worker, causing heartbeat loss and orphan reenqueue cascades. See the README section “Connection pool isolation” for the recommended sizing and the Self::push_with_conn outbox API for the supported way to enqueue from a backend transaction.

Source

pub fn new_with_config(pool: &PgPool, config: &Config) -> Self

Create storage with an explicit Apalis SQL config.

Do not share pool with HTTP request handlers or other unrelated workloads — see Self::new for the rationale.

Source

pub fn new_with_notify( pool: &PgPool, config: &Config, ) -> PostgresStorage<Args, JsonCodec<CompactType>, PgNotify>

Create storage that also listens for PostgreSQL notifications.

Notify mode uses a dedicated pooled connection for LISTEN "apalis::job::insert" while the polling stream is alive. Each new_with_notify storage spawns one listener thread and pins one pool connection. If you need notify-driven dequeue across many queues, prefer crate::SharedPostgresStorage — it spawns a single listener thread shared by all queues registered with it, so the thread/connection cost stays at one regardless of queue count.

Do not share pool with HTTP request handlers or other unrelated workloads — see Self::new for the rationale.

Source

pub fn pool(&self) -> &PgPool

Return the underlying Diesel/r2d2 pool.

Source

pub fn config(&self) -> &Config

Return the queue configuration.

Source§

impl<Args, Codec, Fetcher> PostgresStorage<Args, Codec, Fetcher>

Source

pub fn with_codec<NewCodec>(self) -> PostgresStorage<Args, NewCodec, Fetcher>

Change the task codec while retaining pool, config, and fetcher.

Source§

impl<Args, EncodeCodec, Fetcher> PostgresStorage<Args, EncodeCodec, Fetcher>
where EncodeCodec: Codec<Args, Compact = CompactType>, EncodeCodec::Error: Error + Send + Sync + 'static,

Transactional enqueue on a caller-supplied connection — the outbox entry point. Use these methods when you want the task INSERT to share a transaction with your business-data writes.

Source

pub fn push_with_conn( &self, conn: &mut PgConnection, args: Args, ) -> Result<PgTaskId, Error>

Enqueue a task using a caller-supplied PgConnection.

For transactional outbox semantics, call this inside conn.transaction(|c| ...) together with your business-data writes — the INSERT into apalis.jobs is committed only if the outer transaction commits. Without an outer transaction, Diesel auto-commits the INSERT (same behaviour as the pool-based Sink<Task> path).

NOTIFY is delivered when the (outer) transaction commits, so listeners only see tasks that were actually committed. No manual pg_notify is needed.

This is the only synchronous public method in the crate. From an async context, invoke it inside tokio::task::spawn_blocking together with your business-data writes so the entire transaction lives on one blocking task.

See Self::push_task_with_conn for the full-control variant that accepts a pre-built PgTask (custom idempotency_key, priority, run_at, max_attempts, metadata, or task_id).

§Errors
Source

pub fn push_task_with_conn( &self, conn: &mut PgConnection, task: PgTask<Args>, ) -> Result<PgTaskId, Error>

Enqueue a fully-constructed PgTask<Args> using a caller-supplied connection. Use this when you need to set idempotency_key, priority, run_at, max_attempts, metadata, or a specific task_id.

Semantics are identical to Self::push_with_conn; see that method’s docs for the transaction/NOTIFY contract.

If task.parts.task_id is None, a fresh Ulid is generated and returned. If Some, that id is used as-is and echoed back.

§Errors
  • Error::Decode if the codec rejects the task’s args.
  • Error::IdempotencyConflict on idempotency_key conflict — the savepoint for this batch is rolled back (the whole batch, not just the duplicate), but your outer transaction continues; decide whether to commit or roll back based on the error.
  • Error::InvalidArgument if serialized metadata exceeds the byte cap.
  • Error::Database for SQL/driver failures.

Trait Implementations§

Source§

impl<Args, Decode, Fetcher> Backend for PostgresStorage<Args, Decode, Fetcher>
where Args: Send + 'static + Unpin, Decode: Codec<Args, Compact = CompactType> + Send + 'static, Decode::Error: Error + Send + Sync + 'static, Fetcher: PgFetcherSource,

Single generic Backend impl covering every Fetcher: PgFetcherSource. Heartbeat/middleware are identical for all three modes; the per-mode pipeline is delegated through PgFetcherSource::into_compact_stream.

Source§

type Args = Args

The type of arguments the backend handles.
Source§

type IdType = Ulid

The type used to uniquely identify tasks.
Source§

type Context = SqlContext<Pool<ConnectionManager<PgConnection>>>

Context associated with each task.
Source§

type Error = Error

The error type returned by backend operations
Source§

type Stream = Pin<Box<dyn Stream<Item = Result<Option<Task<Args, SqlContext<Pool<ConnectionManager<PgConnection>>>, Ulid>>, Error>> + Send>>

A stream of tasks provided by the backend.
Source§

type Beat = Pin<Box<dyn Stream<Item = Result<(), Error>> + Send>>

A stream representing heartbeat signals.
Source§

type Layer = PgMiddleware

The type representing backend middleware layer.
Source§

fn heartbeat(&self, worker: &WorkerContext) -> Self::Beat

Returns a heartbeat stream for the given worker.
Source§

fn middleware(&self) -> Self::Layer

Returns the backend’s middleware layer.
Source§

fn poll(self, worker: &WorkerContext) -> Self::Stream

Polls the backend for tasks for the given worker.
Source§

impl<Args, Decode, Fetcher> BackendExt for PostgresStorage<Args, Decode, Fetcher>
where Args: Send + 'static + Unpin, Decode: Codec<Args, Compact = CompactType> + Send + 'static, Decode::Error: Error + Send + Sync + 'static, Fetcher: PgFetcherSource,

Source§

type Compact = Vec<u8>

The compact representation of task arguments.
Source§

type Codec = Decode

The codec used for serialization/deserialization of tasks.
Source§

type CompactStream = Pin<Box<dyn Stream<Item = Result<Option<Task<Vec<u8>, SqlContext<Pool<ConnectionManager<PgConnection>>>, Ulid>>, <PostgresStorage<Args, Decode, Fetcher> as Backend>::Error>> + Send>>

A stream of encoded tasks provided by the backend.
Source§

fn get_queue(&self) -> Queue

Returns the queue associated with the backend.
Source§

fn poll_compact(self, worker: &WorkerContext) -> Self::CompactStream

Polls the backend for encoded tasks for the given worker.
Source§

impl<Args, Codec, Fetcher: Clone> Clone for PostgresStorage<Args, Codec, Fetcher>

Source§

fn clone(&self) -> Self

Returns a duplicate of the value. Read more
1.0.0 (const: unstable) · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl<Args, Codec, Fetcher: Debug> Debug for PostgresStorage<Args, Codec, Fetcher>

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl<Args, D, F> FetchById<Args> for PostgresStorage<Args, D, F>
where PostgresStorage<Args, D, F>: BackendExt<Context = PgContext, Compact = CompactType, IdType = Ulid, Error = Error>, D: Codec<Args, Compact = CompactType>, D::Error: Error + Send + Sync + 'static, Args: 'static,

Source§

fn fetch_by_id( &mut self, task_id: &PgTaskId, ) -> impl Future<Output = Result<Option<PgTask<Args>>, Self::Error>> + Send

Fetch a task by its unique identifier
Source§

impl<Args, D, F> ListAllTasks for PostgresStorage<Args, D, F>
where PostgresStorage<Args, D, F>: BackendExt<Context = PgContext, Compact = CompactType, IdType = Ulid, Error = Error>,

Source§

fn list_all_tasks( &self, filter: &Filter, ) -> impl Future<Output = Result<Vec<Task<Self::Compact, Self::Context, Self::IdType>>, Self::Error>> + Send

List tasks matching the given filter in all queues
Source§

impl<Args, D, F> ListQueues for PostgresStorage<Args, D, F>
where PostgresStorage<Args, D, F>: BackendExt<Context = PgContext, Compact = CompactType, IdType = Ulid, Error = Error>,

Source§

fn list_queues( &self, ) -> impl Future<Output = Result<Vec<QueueInfo>, Self::Error>> + Send

List all available queues in the backend
Source§

impl<Args, D, F> ListTasks<Args> for PostgresStorage<Args, D, F>
where PostgresStorage<Args, D, F>: BackendExt<Context = PgContext, Compact = CompactType, IdType = Ulid, Error = Error>, D: Codec<Args, Compact = CompactType>, D::Error: Error + Send + Sync + 'static, Args: 'static,

Source§

fn list_tasks( &self, filter: &Filter, ) -> impl Future<Output = Result<Vec<PgTask<Args>>, Self::Error>> + Send

List tasks matching the given filter in the current queue
Source§

impl<Args, D, F> ListWorkers for PostgresStorage<Args, D, F>
where Args: Sync, PostgresStorage<Args, D, F>: BackendExt<Context = PgContext, Compact = CompactType, IdType = Ulid, Error = Error>,

Source§

fn list_workers( &self, ) -> impl Future<Output = Result<Vec<RunningWorker>, Self::Error>> + Send

List all registered workers in the current queue
Source§

fn list_all_workers( &self, ) -> impl Future<Output = Result<Vec<RunningWorker>, Self::Error>> + Send

List all registered workers in all queues
Source§

impl<Args, D, F> Metrics for PostgresStorage<Args, D, F>
where PostgresStorage<Args, D, F>: BackendExt<Context = PgContext, Compact = CompactType, IdType = Ulid, Error = Error>,

Source§

fn global( &self, ) -> impl Future<Output = Result<Vec<Statistic>, Self::Error>> + Send

Scans apalis.jobs to compute global statistics. Each call evaluates 20+ FILTER aggregates over every row; cost grows linearly with the table size. Treat as a slow admin call.

Source§

fn fetch_by_queue( &self, ) -> impl Future<Output = Result<Vec<Statistic>, Self::Error>> + Send

Same shape as Self::global, scoped to the configured queue. Cost still depends on the number of jobs in that job_type.

Source§

impl<Args, D, F> RegisterWorker for PostgresStorage<Args, D, F>
where PostgresStorage<Args, D, F>: BackendExt<Context = PgContext, Compact = CompactType, IdType = Ulid, Error = Error>,

Source§

fn register_worker( &mut self, worker_id: String, ) -> impl Future<Output = Result<(), Self::Error>> + Send

Registers a worker
Source§

impl<Args, Encode, Fetcher> Sink<Task<Vec<u8>, SqlContext<Pool<ConnectionManager<PgConnection>>>, Ulid>> for PostgresStorage<Args, Encode, Fetcher>
where Args: Send + Sync + 'static, Fetcher: Unpin,

Source§

type Error = Error

The type of value produced by the sink when an error occurs.
Source§

fn poll_ready( self: Pin<&mut Self>, cx: &mut Context<'_>, ) -> Poll<Result<(), Self::Error>>

Attempts to prepare the Sink to receive a value. Read more
Source§

fn start_send( self: Pin<&mut Self>, item: PgTask<CompactType>, ) -> Result<(), Self::Error>

Begin the process of sending a value to the sink. Each call to this function must be preceded by a successful call to poll_ready which returned Poll::Ready(Ok(())). Read more
Source§

fn poll_flush( self: Pin<&mut Self>, cx: &mut Context<'_>, ) -> Poll<Result<(), Self::Error>>

Flush any remaining output from this sink. Read more
Source§

fn poll_close( self: Pin<&mut Self>, cx: &mut Context<'_>, ) -> Poll<Result<(), Self::Error>>

Flush any remaining output and close this sink, if necessary. Read more
Source§

impl<O, Args, F, Decode> WaitForCompletion<O> for PostgresStorage<Args, Decode, F>
where O: 'static + Send, PostgresStorage<Args, Decode, F>: BackendExt<Context = PgContext, Compact = CompactType, IdType = Ulid, Error = Error>, Result<O, String>: DeserializeOwned,

Source§

fn wait_for( &self, task_ids: impl IntoIterator<Item = TaskId<Self::IdType>>, ) -> Self::ResultStream

Wait for the given tasks to complete, yielding each result as it lands.

§Error handling

A transient database error during polling does not abandon the batch: the poll is retried with backoff. The stream yields an Err and ends only once the failures persist across several consecutive polls. Because completed results are durable in apalis.jobs, a surfaced error is always safe to recover from by calling wait_for again with the ids that have not yet yielded a result.

Source§

type ResultStream = Pin<Box<dyn Stream<Item = Result<TaskResult<O, Ulid>, Error>> + Send>>

The result stream type yielding task results
Source§

fn check_status( &self, task_ids: impl IntoIterator<Item = TaskId<Self::IdType>> + Send, ) -> impl Future<Output = Result<Vec<TaskResult<O, Ulid>>, Self::Error>> + Send

Check current status of tasks without waiting
Source§

fn wait_for_single(&self, task_id: TaskId<Self::IdType>) -> Self::ResultStream

Wait for a single task to complete, yielding its result
Source§

impl<Args, Codec, Fetcher: Unpin> Unpin for PostgresStorage<Args, Codec, Fetcher>

Auto Trait Implementations§

§

impl<Args, Codec = JsonCodec<Vec<u8>>, Fetcher = PgFetcher<Vec<u8>, Codec>> !Freeze for PostgresStorage<Args, Codec, Fetcher>

§

impl<Args, Codec = JsonCodec<Vec<u8>>, Fetcher = PgFetcher<Vec<u8>, Codec>> !RefUnwindSafe for PostgresStorage<Args, Codec, Fetcher>

§

impl<Args, Codec, Fetcher> Send for PostgresStorage<Args, Codec, Fetcher>
where Fetcher: Send, Args: Send, Codec: Send,

§

impl<Args, Codec, Fetcher> Sync for PostgresStorage<Args, Codec, Fetcher>
where Fetcher: Sync, Args: Sync, Codec: Sync,

§

impl<Args, Codec, Fetcher> UnsafeUnpin for PostgresStorage<Args, Codec, Fetcher>
where Fetcher: UnsafeUnpin,

§

impl<Args, Codec = JsonCodec<Vec<u8>>, Fetcher = PgFetcher<Vec<u8>, Codec>> !UnwindSafe for PostgresStorage<Args, Codec, Fetcher>

Blanket Implementations§

Source§

impl<T> AggregateExpressionMethods for T

Source§

fn aggregate_distinct(self) -> Self::Output
where Self: DistinctDsl,

DISTINCT modifier for aggregate functions Read more
Source§

fn aggregate_all(self) -> Self::Output
where Self: AllDsl,

ALL modifier for aggregate functions Read more
Source§

fn aggregate_filter<P>(self, f: P) -> Self::Output
where P: AsExpression<Bool>, Self: FilterDsl<<P as AsExpression<Bool>>::Expression>,

Add an aggregate function filter Read more
Source§

fn aggregate_order<O>(self, o: O) -> Self::Output
where Self: OrderAggregateDsl<O>,

Add an aggregate function order Read more
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> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> Downcast for T
where T: Any,

Source§

fn into_any(self: Box<T>) -> Box<dyn Any>

Converts Box<dyn Trait> (where Trait: Downcast) to Box<dyn Any>, which can then be downcast into Box<dyn ConcreteType> where ConcreteType implements Trait.
Source§

fn into_any_rc(self: Rc<T>) -> Rc<dyn Any>

Converts Rc<Trait> (where Trait: Downcast) to Rc<Any>, which can then be further downcast into Rc<ConcreteType> where ConcreteType implements Trait.
Source§

fn as_any(&self) -> &(dyn Any + 'static)

Converts &Trait (where Trait: Downcast) to &Any. This is needed since Rust cannot generate &Any’s vtable from &Trait’s.
Source§

fn as_any_mut(&mut self) -> &mut (dyn Any + 'static)

Converts &mut Trait (where Trait: Downcast) to &Any. This is needed since Rust cannot generate &mut Any’s vtable from &mut Trait’s.
Source§

impl<T> DowncastSend for T
where T: Any + Send,

Source§

fn into_any_send(self: Box<T>) -> Box<dyn Any + Send>

Converts Box<Trait> (where Trait: DowncastSend) to Box<dyn Any + Send>, which can then be downcast into Box<ConcreteType> where ConcreteType implements Trait.
Source§

impl<T> DowncastSync for T
where T: Any + Send + Sync,

Source§

fn into_any_sync(self: Box<T>) -> Box<dyn Any + Send + Sync>

Converts Box<Trait> (where Trait: DowncastSync) to Box<dyn Any + Send + Sync>, which can then be downcast into Box<ConcreteType> where ConcreteType implements Trait.
Source§

fn into_any_arc(self: Arc<T>) -> Arc<dyn Any + Send + Sync>

Converts Arc<Trait> (where Trait: DowncastSync) to Arc<Any>, which can then be downcast into Arc<ConcreteType> where ConcreteType implements Trait.
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

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> IntoSql for T

Source§

fn into_sql<T>(self) -> Self::Expression

Convert self to an expression for Diesel’s query builder. Read more
Source§

fn as_sql<'a, T>(&'a self) -> <&'a Self as AsExpression<T>>::Expression
where &'a Self: AsExpression<T>, T: SqlType + TypedExpressionType,

Convert &self to an expression for Diesel’s query builder. Read more
Source§

impl<T, Item> SinkExt<Item> for T
where T: Sink<Item> + ?Sized,

Source§

fn with<U, Fut, F, E>(self, f: F) -> With<Self, Item, U, Fut, F>
where F: FnMut(U) -> Fut, Fut: Future<Output = Result<Item, E>>, E: From<Self::Error>, Self: Sized,

Composes a function in front of the sink. Read more
Source§

fn with_flat_map<U, St, F>(self, f: F) -> WithFlatMap<Self, Item, U, St, F>
where F: FnMut(U) -> St, St: Stream<Item = Result<Item, Self::Error>>, Self: Sized,

Composes a function in front of the sink. Read more
Source§

fn sink_map_err<E, F>(self, f: F) -> SinkMapErr<Self, F>
where F: FnOnce(Self::Error) -> E, Self: Sized,

Transforms the error returned by the sink.
Source§

fn sink_err_into<E>(self) -> SinkErrInto<Self, Item, E>
where Self: Sized, Self::Error: Into<E>,

Map this sink’s error to a different error type using the Into trait. Read more
Source§

fn buffer(self, capacity: usize) -> Buffer<Self, Item>
where Self: Sized,

Adds a fixed-size buffer to the current sink. Read more
Source§

fn close(&mut self) -> Close<'_, Self, Item>
where Self: Unpin,

Close the sink.
Source§

fn fanout<Si>(self, other: Si) -> Fanout<Self, Si>
where Self: Sized, Item: Clone, Si: Sink<Item, Error = Self::Error>,

Fanout items to multiple sinks. Read more
Source§

fn flush(&mut self) -> Flush<'_, Self, Item>
where Self: Unpin,

Flush the sink, processing all pending items. Read more
Source§

fn send(&mut self, item: Item) -> Send<'_, Self, Item>
where Self: Unpin,

A future that completes after the given item has been fully processed into the sink, including flushing. Read more
Source§

fn feed(&mut self, item: Item) -> Feed<'_, Self, Item>
where Self: Unpin,

A future that completes after the given item has been received by the sink. Read more
Source§

fn send_all<'a, St>(&'a mut self, stream: &'a mut St) -> SendAll<'a, Self, St>
where St: TryStream<Ok = Item, Error = Self::Error> + Stream + Unpin + ?Sized, Self: Unpin,

A future that completes after the given stream has been fully processed into the sink, including flushing. Read more
Source§

fn left_sink<Si2>(self) -> Either<Self, Si2>
where Si2: Sink<Item, Error = Self::Error>, Self: Sized,

Wrap this sink in an Either sink, making it the left-hand variant of that Either. Read more
Source§

fn right_sink<Si1>(self) -> Either<Si1, Self>
where Si1: Sink<Item, Error = Self::Error>, Self: Sized,

Wrap this stream in an Either stream, making it the right-hand variant of that Either. Read more
Source§

fn poll_ready_unpin( &mut self, cx: &mut Context<'_>, ) -> Poll<Result<(), Self::Error>>
where Self: Unpin,

A convenience method for calling Sink::poll_ready on Unpin sink types.
Source§

fn start_send_unpin(&mut self, item: Item) -> Result<(), Self::Error>
where Self: Unpin,

A convenience method for calling Sink::start_send on Unpin sink types.
Source§

fn poll_flush_unpin( &mut self, cx: &mut Context<'_>, ) -> Poll<Result<(), Self::Error>>
where Self: Unpin,

A convenience method for calling Sink::poll_flush on Unpin sink types.
Source§

fn poll_close_unpin( &mut self, cx: &mut Context<'_>, ) -> Poll<Result<(), Self::Error>>
where Self: Unpin,

A convenience method for calling Sink::poll_close on Unpin sink types.
Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
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> WindowExpressionMethods for T

Source§

fn over(self) -> Self::Output
where Self: OverDsl,

Turn a function call into a window function call Read more
Source§

fn window_filter<P>(self, f: P) -> Self::Output
where P: AsExpression<Bool>, Self: FilterDsl<<P as AsExpression<Bool>>::Expression>,

Add a filter to the current window function Read more
Source§

fn partition_by<E>(self, expr: E) -> Self::Output
where Self: PartitionByDsl<E>,

Add a partition clause to the current window function Read more
Source§

fn window_order<E>(self, expr: E) -> Self::Output
where Self: OrderWindowDsl<E>,

Add a order clause to the current window function Read more
Source§

fn frame_by<E>(self, expr: E) -> Self::Output
where Self: FrameDsl<E>,

Add a frame clause to the current window function Read more
Source§

impl<B, Args> Expose<Args> for B
where B: Backend<Args = Args> + Metrics + ListWorkers + ListQueues + ListAllTasks + ListTasks<Args> + TaskSink<Args>,