Skip to main content

ojak_postgres/
queue.rs

1//! The queue, in a table of its own.
2//!
3//! Jobs live in one table, `ojak_queue` unless named otherwise, created by
4//! [`PostgresQueue::initialize`] if it is not there. Every queue — deliveries,
5//! and whatever else an application runs through Ojak — shares the table,
6//! each claimed separately.
7//!
8//! A claim is an `UPDATE … FOR UPDATE SKIP LOCKED` that pushes `run_at` out by
9//! the lease, so any number of workers in any number of processes can claim
10//! from one table without two of them taking the same job, and a job whose
11//! worker stopped comes back when its lease lapses. A job that is done is
12//! deleted; one given up on keeps its row, with `failed_at` and the last
13//! error, until [`PostgresQueue::prune_failed`] removes it.
14//!
15//! A job queued with an ordering key keeps it in `ordering_key`, and a claim
16//! passes over a job while a row with the same key and a smaller `id` is
17//! still there and not failed: the jobs before it are waiting, claimed or to
18//! be retried, and it goes once they are done.
19//!
20//! A payload is `jsonb`, which refuses a string with NUL in it, and a payload
21//! is often a document a peer sent: one Note with `\u0000` in its content
22//! would fail the enqueue, and the activity would be lost. A payload that
23//! holds NUL anywhere is stored as its JSON text instead, in which NUL is
24//! only ever the escape `\u0000`, wrapped as `{"ojak:json": text}`, and
25//! unwrapped when it is claimed. Nothing else changes, so the table needs no
26//! migration.
27
28use crate::table_name;
29use ojak::queue::{Job, Queue, QueueError};
30use serde_json::Value;
31use sqlx::{PgPool, Row};
32use std::time::Duration;
33
34/// A [`Queue`] in a PostgreSQL table.
35#[derive(Clone, Debug)]
36pub struct PostgresQueue {
37    pool: PgPool,
38    table: String,
39}
40
41impl PostgresQueue {
42    /// A queue in the table `ojak_queue`.
43    #[must_use]
44    pub fn new(pool: PgPool) -> Self {
45        Self {
46            pool,
47            table: "ojak_queue".to_owned(),
48        }
49    }
50
51    /// A queue in the table `table`.
52    ///
53    /// # Errors
54    ///
55    /// When `table` is not a plain SQL identifier: ASCII letters, digits and
56    /// underscores, not starting with a digit, optionally prefixed by a schema
57    /// of the same shape and a dot.
58    pub fn with_table(pool: PgPool, table: &str) -> Result<Self, QueueError> {
59        Ok(Self {
60            pool,
61            table: table_name(table).map_err(QueueError)?,
62        })
63    }
64
65    /// Create the table and its index if they do not exist.
66    ///
67    /// Safe to run from every process at start-up, including both colours of
68    /// a blue/green deploy at once. An application that changes its schema
69    /// only through its own migrations creates the table there instead, from
70    /// [`PostgresQueue::schema`].
71    ///
72    /// # Errors
73    ///
74    /// When the database refuses.
75    pub async fn initialize(&self) -> Result<(), QueueError> {
76        for statement in Self::schema(&self.table) {
77            sqlx::query(crate::sql(statement))
78                .execute(&self.pool)
79                .await
80                .map_err(error)?;
81        }
82        Ok(())
83    }
84
85    /// The statements that create a queue table named `table` and its
86    /// indexes, each safe to run again, and bring one made before ordering
87    /// keys up to date. What [`PostgresQueue::initialize`] runs, for an
88    /// application to put in a migration of its own.
89    #[must_use]
90    pub fn schema(table: &str) -> Vec<String> {
91        let index = format!("{}_due", table.replace('.', "_"));
92        let ordering = format!("{}_ordering", table.replace('.', "_"));
93        vec![
94            format!(
95                "CREATE TABLE IF NOT EXISTS {table} (
96                    id BIGSERIAL PRIMARY KEY,
97                    queue TEXT NOT NULL,
98                    payload JSONB NOT NULL,
99                    attempts INTEGER NOT NULL DEFAULT 0,
100                    run_at TIMESTAMPTZ NOT NULL DEFAULT now(),
101                    last_error TEXT,
102                    failed_at TIMESTAMPTZ,
103                    created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
104                    ordering_key TEXT
105                )"
106            ),
107            format!(
108                "CREATE INDEX IF NOT EXISTS {index} ON {table} (queue, run_at) \
109                 WHERE failed_at IS NULL"
110            ),
111            format!("ALTER TABLE {table} ADD COLUMN IF NOT EXISTS ordering_key TEXT"),
112            format!(
113                "CREATE INDEX IF NOT EXISTS {ordering} ON {table} (ordering_key, id) \
114                 WHERE ordering_key IS NOT NULL AND failed_at IS NULL"
115            ),
116        ]
117    }
118
119    /// Delete jobs given up on more than `age` ago.
120    ///
121    /// # Errors
122    ///
123    /// When the database refuses.
124    pub async fn prune_failed(&self, age: Duration) -> Result<u64, QueueError> {
125        let result = sqlx::query(crate::sql(format!(
126            "DELETE FROM {} WHERE failed_at < now() - make_interval(secs => $1)",
127            self.table
128        )))
129        .bind(age.as_secs_f64())
130        .execute(&self.pool)
131        .await
132        .map_err(error)?;
133        Ok(result.rows_affected())
134    }
135}
136
137/// How much of a job's last error is kept.
138const MAX_ERROR_CHARS: usize = 2000;
139
140/// An error message made safe to store: without NUL, which PostgreSQL `text`
141/// refuses, and bounded.
142///
143/// A delivery's error can carry part of a peer's response. If recording it
144/// failed, the job would keep its lease, be handed out again when the lease
145/// lapsed, and never reach its last attempt: a job that cannot be failed is
146/// retried forever.
147fn storable(error: &str) -> String {
148    let cleaned = error.replace('\0', "");
149    match cleaned.char_indices().nth(MAX_ERROR_CHARS) {
150        Some((end, _)) => format!("{}…", &cleaned[..end]),
151        None => cleaned,
152    }
153}
154
155/// The key a payload stored as its JSON text is wrapped under.
156const WRAPPED: &str = "ojak:json";
157
158/// `payload` as `jsonb` can hold it: itself, or, when it holds NUL or could
159/// be mistaken for a wrapped payload, its JSON text wrapped.
160fn wrap(payload: &Value) -> Value {
161    let ambiguous = payload
162        .as_object()
163        .is_some_and(|object| object.len() == 1 && object.contains_key(WRAPPED));
164    if ambiguous || holds_nul(payload) {
165        serde_json::json!({ WRAPPED: payload.to_string() })
166    } else {
167        payload.clone()
168    }
169}
170
171/// A payload as it was enqueued.
172fn unwrap(stored: Value) -> Value {
173    if let Some(object) = stored.as_object()
174        && object.len() == 1
175        && let Some(Value::String(text)) = object.get(WRAPPED)
176        && let Ok(payload) = serde_json::from_str(text)
177    {
178        return payload;
179    }
180    stored
181}
182
183fn holds_nul(value: &Value) -> bool {
184    match value {
185        Value::String(text) => text.contains('\0'),
186        Value::Array(items) => items.iter().any(holds_nul),
187        Value::Object(object) => object
188            .iter()
189            .any(|(key, value)| key.contains('\0') || holds_nul(value)),
190        _ => false,
191    }
192}
193
194fn error(error: sqlx::Error) -> QueueError {
195    QueueError(error.to_string())
196}
197
198fn id(id: &str) -> Result<i64, QueueError> {
199    id.parse()
200        .map_err(|_| QueueError(format!("not a job id: {id}")))
201}
202
203impl Queue for PostgresQueue {
204    async fn enqueue(&self, queue: &str, payloads: Vec<Value>) -> Result<(), QueueError> {
205        if payloads.is_empty() {
206            return Ok(());
207        }
208        sqlx::query(crate::sql(format!(
209            "INSERT INTO {} (queue, payload) SELECT $1, unnest($2::jsonb[])",
210            self.table
211        )))
212        .bind(queue)
213        .bind(payloads.iter().map(wrap).collect::<Vec<_>>())
214        .execute(&self.pool)
215        .await
216        .map_err(error)?;
217        Ok(())
218    }
219
220    async fn enqueue_ordered(
221        &self,
222        queue: &str,
223        jobs: Vec<(String, Value)>,
224    ) -> Result<(), QueueError> {
225        if jobs.is_empty() {
226            return Ok(());
227        }
228        let (keys, payloads): (Vec<String>, Vec<Value>) = jobs
229            .into_iter()
230            .map(|(key, payload)| (storable(&key), wrap(&payload)))
231            .unzip();
232        // `WITH ORDINALITY` keeps the ids in the order the jobs were given,
233        // which is the order they are claimed in.
234        sqlx::query(crate::sql(format!(
235            "INSERT INTO {} (queue, ordering_key, payload)
236             SELECT $1, job.key, job.payload
237             FROM unnest($2::text[], $3::jsonb[]) WITH ORDINALITY AS job(key, payload, n)
238             ORDER BY job.n",
239            self.table
240        )))
241        .bind(queue)
242        .bind(keys)
243        .bind(payloads)
244        .execute(&self.pool)
245        .await
246        .map_err(error)?;
247        Ok(())
248    }
249
250    async fn claim(
251        &self,
252        queue: &str,
253        limit: usize,
254        lease: Duration,
255    ) -> Result<Vec<Job>, QueueError> {
256        let table = &self.table;
257        let rows = sqlx::query(crate::sql(format!(
258            // `UPDATE ... RETURNING` hands rows back in no particular order,
259            // so the picked order is carried through and reapplied.
260            "WITH picked AS (
261                 SELECT id, run_at FROM {table} AS job
262                 WHERE queue = $1 AND failed_at IS NULL AND run_at <= now()
263                   AND (ordering_key IS NULL OR NOT EXISTS (
264                       SELECT 1 FROM {table} AS ahead
265                       WHERE ahead.ordering_key = job.ordering_key
266                         AND ahead.id < job.id AND ahead.failed_at IS NULL
267                   ))
268                 ORDER BY run_at, id
269                 LIMIT $2
270                 FOR UPDATE SKIP LOCKED
271             ), claimed AS (
272                 UPDATE {table} AS job SET run_at = now() + make_interval(secs => $3)
273                 FROM picked WHERE job.id = picked.id
274                 RETURNING job.id, job.queue, job.payload, job.attempts, picked.run_at AS picked_at
275             )
276             SELECT id, queue, payload, attempts FROM claimed ORDER BY picked_at, id"
277        )))
278        .bind(queue)
279        .bind(i64::try_from(limit).unwrap_or(i64::MAX))
280        .bind(lease.as_secs_f64())
281        .fetch_all(&self.pool)
282        .await
283        .map_err(error)?;
284        rows.into_iter()
285            .map(|row| {
286                Ok(Job {
287                    id: row.try_get::<i64, _>("id").map_err(error)?.to_string(),
288                    queue: row.try_get("queue").map_err(error)?,
289                    payload: unwrap(row.try_get("payload").map_err(error)?),
290                    attempts: u32::try_from(row.try_get::<i32, _>("attempts").map_err(error)?)
291                        .unwrap_or(0),
292                })
293            })
294            .collect()
295    }
296
297    async fn complete(&self, job: &str) -> Result<(), QueueError> {
298        sqlx::query(crate::sql(format!(
299            "DELETE FROM {} WHERE id = $1",
300            self.table
301        )))
302        .bind(id(job)?)
303        .execute(&self.pool)
304        .await
305        .map_err(error)?;
306        Ok(())
307    }
308
309    async fn retry(&self, job: &str, delay: Duration, message: &str) -> Result<(), QueueError> {
310        sqlx::query(crate::sql(format!(
311            "UPDATE {} SET attempts = attempts + 1,
312                 run_at = now() + make_interval(secs => $2),
313                 last_error = $3
314             WHERE id = $1",
315            self.table
316        )))
317        .bind(id(job)?)
318        .bind(delay.as_secs_f64())
319        .bind(storable(message))
320        .execute(&self.pool)
321        .await
322        .map_err(error)?;
323        Ok(())
324    }
325
326    async fn fail(&self, job: &str, message: &str) -> Result<(), QueueError> {
327        sqlx::query(crate::sql(format!(
328            "UPDATE {} SET attempts = attempts + 1, failed_at = now(), last_error = $2
329             WHERE id = $1",
330            self.table
331        )))
332        .bind(id(job)?)
333        .bind(storable(message))
334        .execute(&self.pool)
335        .await
336        .map_err(error)?;
337        Ok(())
338    }
339
340    async fn next_due(&self, queue: &str) -> Result<Option<Duration>, QueueError> {
341        let seconds: Option<f64> = sqlx::query_scalar(crate::sql(format!(
342            "SELECT EXTRACT(EPOCH FROM (min(run_at) - now()))::float8
343             FROM {} WHERE queue = $1 AND failed_at IS NULL",
344            self.table
345        )))
346        .bind(queue)
347        .fetch_one(&self.pool)
348        .await
349        .map_err(error)?;
350        Ok(seconds.map(|seconds| Duration::from_secs_f64(seconds.max(0.0))))
351    }
352}
353
354#[cfg(test)]
355mod tests {
356    use super::*;
357    use serde_json::json;
358
359    #[test]
360    fn what_jsonb_refuses_is_wrapped_and_comes_back() {
361        for payload in [
362            json!({"activity": {"content": "a\u{0}b"}}),
363            json!({"a\u{0}": 1}),
364            json!(["x", ["\u{0}"]]),
365            json!({WRAPPED: "not wrapped by us"}),
366        ] {
367            let stored = wrap(&payload);
368            assert!(!stored.to_string().contains('\0'));
369            assert_ne!(stored, payload);
370            assert_eq!(unwrap(stored), payload);
371        }
372        let plain = json!({"activity": {"content": "hello"}});
373        assert_eq!(wrap(&plain), plain);
374        assert_eq!(unwrap(plain.clone()), plain);
375    }
376}