1use crate::table_name;
29use ojak::queue::{Job, Queue, QueueError};
30use serde_json::Value;
31use sqlx::{PgPool, Row};
32use std::time::Duration;
33
34#[derive(Clone, Debug)]
36pub struct PostgresQueue {
37 pool: PgPool,
38 table: String,
39}
40
41impl PostgresQueue {
42 #[must_use]
44 pub fn new(pool: PgPool) -> Self {
45 Self {
46 pool,
47 table: "ojak_queue".to_owned(),
48 }
49 }
50
51 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 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 #[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 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
137const MAX_ERROR_CHARS: usize = 2000;
139
140fn 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
155const WRAPPED: &str = "ojak:json";
157
158fn 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
171fn 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 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 "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}