pgqrs 0.15.0

A high-performance PostgreSQL-backed job queue for Rust applications
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
use crate::error::Result;
use crate::store::dialect::SqlDialect;
use crate::store::turso::dialect::TursoDialect;
use crate::store::turso::{format_turso_timestamp, parse_turso_timestamp};
use crate::types::{WorkerRecord, WorkerStatus};
use async_trait::async_trait;
use chrono::Utc;
use std::str::FromStr;
use std::sync::Arc;
use turso::Database;

const INSERT_WORKER: &str = r#"
    INSERT INTO pgqrs_workers (hostname, port, queue_id, started_at, heartbeat_at, status)
    VALUES (?, ?, ?, ?, ?, ?)
    RETURNING id;
"#;

const GET_WORKER_BY_ID: &str = r#"
    SELECT id, hostname, port, queue_id, started_at, heartbeat_at, shutdown_at, status
    FROM pgqrs_workers
    WHERE id = ?;
"#;

const LIST_ALL_WORKERS: &str = r#"
    SELECT id, hostname, port, queue_id, started_at, heartbeat_at, shutdown_at, status
    FROM pgqrs_workers
    ORDER BY started_at DESC;
"#;

const LIST_WORKERS_BY_QUEUE: &str = r#"
    SELECT id, hostname, port, queue_id, started_at, heartbeat_at, shutdown_at, status
    FROM pgqrs_workers
    WHERE queue_id = ?
    ORDER BY started_at DESC;
"#;

const DELETE_WORKER_BY_ID: &str = r#"
    DELETE FROM pgqrs_workers
    WHERE id = ?;
"#;

const INSERT_EPHEMERAL_WORKER_RETURNING: &str = r#"
    INSERT INTO pgqrs_workers (hostname, port, queue_id, status, started_at, heartbeat_at)
    VALUES (?, 0, ?, 'ready', ?, ?)
    RETURNING id, hostname, port, queue_id, started_at, heartbeat_at, shutdown_at, status;
"#;

#[derive(Debug, Clone)]
pub struct TursoWorkerTable {
    db: Arc<Database>,
}

impl TursoWorkerTable {
    pub fn new(db: Arc<Database>) -> Self {
        Self { db }
    }

    fn map_row(row: &turso::Row) -> Result<WorkerRecord> {
        let id: i64 = row.get(0)?;
        let hostname: String = row.get(1)?;
        // Port might be returned as i64 in some contexts, cast if needed?
        // But row.get handles conversion often.
        // However, "port" is integer.
        let port: i32 = row.get(2)?;
        let queue_id: Option<i64> = row.get(3)?;

        let started_at_str: String = row.get(4)?;
        let started_at = parse_turso_timestamp(&started_at_str)?;

        let heartbeat_at_str: String = row.get(5)?;
        let heartbeat_at = parse_turso_timestamp(&heartbeat_at_str)?;

        let shutdown_at_str: Option<String> = row.get(6)?;
        let shutdown_at = match shutdown_at_str {
            Some(s) => Some(parse_turso_timestamp(&s)?),
            None => None,
        };

        let status_str: String = row.get(7)?;
        let status = WorkerStatus::from_str(&status_str)
            .map_err(|e| crate::error::Error::Internal { message: e })?;

        Ok(WorkerRecord {
            id,
            hostname,
            port,
            queue_id,
            started_at,
            heartbeat_at,
            shutdown_at,
            status,
        })
    }

    pub async fn get_status(&self, worker_id: i64) -> Result<WorkerStatus> {
        let status_str: String =
            crate::store::turso::query_scalar("SELECT status FROM pgqrs_workers WHERE id = ?")
                .bind(worker_id)
                .fetch_one(&self.db)
                .await?;

        WorkerStatus::from_str(&status_str)
            .map_err(|e| crate::error::Error::Internal { message: e })
    }

    pub async fn heartbeat(&self, worker_id: i64) -> Result<()> {
        let now = Utc::now();
        let now_str = format_turso_timestamp(&now);

        crate::store::turso::query("UPDATE pgqrs_workers SET heartbeat_at = ? WHERE id = ?")
            .bind(now_str)
            .bind(worker_id)
            .execute_once(&self.db)
            .await?;

        Ok(())
    }

    pub async fn is_healthy(&self, worker_id: i64, max_age: chrono::Duration) -> Result<bool> {
        let threshold = Utc::now() - max_age;
        let threshold_str = format_turso_timestamp(&threshold);

        let is_healthy: bool = crate::store::turso::query_scalar(
            "SELECT heartbeat_at > ? FROM pgqrs_workers WHERE id = ?",
        )
        .bind(threshold_str)
        .bind(worker_id)
        .fetch_one(&self.db)
        .await?;

        Ok(is_healthy)
    }

    pub async fn suspend(&self, worker_id: i64) -> Result<()> {
        let count = crate::store::turso::query(
            "UPDATE pgqrs_workers SET status = 'suspended' WHERE id = ? AND status IN ('ready', 'polling', 'interrupted')", 
        )
        .bind(worker_id)
        .execute_once(&self.db)
        .await?;

        if count == 0 {
            let current_status = self.get_status(worker_id).await?;
            return Err(crate::error::Error::InvalidStateTransition {
                from: current_status.to_string(),
                to: "suspended".to_string(),
                reason: "Worker must be Ready, Polling, or Interrupted to suspend".to_string(),
            });
        }
        Ok(())
    }

    pub async fn resume(&self, worker_id: i64) -> Result<()> {
        let count = crate::store::turso::query(
            "UPDATE pgqrs_workers SET status = 'ready' WHERE id = ? AND status = 'suspended'",
        )
        .bind(worker_id)
        .execute_once(&self.db)
        .await?;

        if count == 0 {
            let current_status = self.get_status(worker_id).await?;
            return Err(crate::error::Error::InvalidStateTransition {
                from: current_status.to_string(),
                to: "ready".to_string(),
                reason: "Worker must be in Suspended state to resume".to_string(),
            });
        }
        Ok(())
    }

    pub async fn poll(&self, worker_id: i64) -> Result<()> {
        let count = crate::store::turso::query(
            "UPDATE pgqrs_workers SET status = 'polling' WHERE id = ? AND status IN ('ready', 'polling')",
        )
        .bind(worker_id)
        .execute_once(&self.db)
        .await?;

        if count == 0 {
            let current_status = self.get_status(worker_id).await?;
            return Err(crate::error::Error::InvalidStateTransition {
                from: current_status.to_string(),
                to: "polling".to_string(),
                reason: "Worker must be Ready to start polling".to_string(),
            });
        }
        Ok(())
    }

    pub async fn interrupt(&self, worker_id: i64) -> Result<()> {
        let count = crate::store::turso::query(
            "UPDATE pgqrs_workers SET status = 'interrupted' WHERE id = ? AND status = 'polling'",
        )
        .bind(worker_id)
        .execute_once(&self.db)
        .await?;

        if count == 0 {
            let current_status = self.get_status(worker_id).await?;
            return Err(crate::error::Error::InvalidStateTransition {
                from: current_status.to_string(),
                to: "interrupted".to_string(),
                reason: "Worker must be in Polling state to be interrupted".to_string(),
            });
        }
        Ok(())
    }

    pub async fn shutdown(&self, worker_id: i64) -> Result<()> {
        let held_count: i64 = crate::store::turso::query_scalar(
            "SELECT COUNT(*) FROM pgqrs_messages WHERE consumer_worker_id = ? AND archived_at IS NULL",
        )
        .bind(worker_id)
        .fetch_one(&self.db)
        .await?;

        if held_count > 0 {
            return Err(crate::error::Error::WorkerHasPendingMessages {
                reason: format!("Worker has {} pending messages", held_count),
                count: held_count as u64,
            });
        }

        let now = Utc::now();
        let now_str = format_turso_timestamp(&now);

        let count = crate::store::turso::query("UPDATE pgqrs_workers SET status = 'stopped', shutdown_at = ? WHERE id = ? AND status = 'suspended'")
            .bind(now_str)
            .bind(worker_id)
            .execute_once(&self.db)
            .await?;

        if count == 0 {
            let current_status = self.get_status(worker_id).await?;
            return Err(crate::error::Error::InvalidStateTransition {
                from: current_status.to_string(),
                to: "stopped".to_string(),
                reason: "Worker must be in Suspended state to shutdown".to_string(),
            });
        }
        Ok(())
    }
}

#[async_trait]
impl crate::store::WorkerTable for TursoWorkerTable {
    async fn insert(&self, data: crate::types::NewWorkerRecord) -> Result<WorkerRecord> {
        let now = Utc::now();
        let now_str = format_turso_timestamp(&now);
        let status_str = WorkerStatus::Ready.to_string();

        let id: i64 = crate::store::turso::query_scalar(INSERT_WORKER)
            .bind(data.hostname.as_str())
            .bind(data.port as i64)
            .bind(match data.queue_id {
                Some(id) => turso::Value::Integer(id),
                None => turso::Value::Null,
            })
            .bind(now_str.as_str())
            .bind(now_str.as_str())
            .bind(status_str.as_str())
            .fetch_one_once(&self.db)
            .await?;

        Ok(WorkerRecord {
            id,
            hostname: data.hostname,
            port: data.port,
            queue_id: data.queue_id,
            started_at: now,
            heartbeat_at: now,
            shutdown_at: None,
            status: WorkerStatus::Ready,
        })
    }

    async fn get(&self, id: i64) -> Result<WorkerRecord> {
        let row = crate::store::turso::query(GET_WORKER_BY_ID)
            .bind(id)
            .fetch_one(&self.db)
            .await?;

        Self::map_row(&row)
    }

    async fn list(&self) -> Result<Vec<WorkerRecord>> {
        let rows = crate::store::turso::query(LIST_ALL_WORKERS)
            .fetch_all(&self.db)
            .await?;

        let mut workers = Vec::with_capacity(rows.len());
        for row in rows {
            workers.push(Self::map_row(&row)?);
        }
        Ok(workers)
    }

    async fn count(&self) -> Result<i64> {
        let count: i64 = crate::store::turso::query_scalar("SELECT COUNT(*) FROM pgqrs_workers")
            .fetch_one(&self.db)
            .await?;
        Ok(count)
    }

    async fn delete(&self, id: i64) -> Result<u64> {
        let count = crate::store::turso::query(DELETE_WORKER_BY_ID)
            .bind(id)
            .execute_once(&self.db)
            .await?;
        Ok(count)
    }

    async fn filter_by_fk(&self, queue_id: i64) -> Result<Vec<WorkerRecord>> {
        let rows = crate::store::turso::query(LIST_WORKERS_BY_QUEUE)
            .bind(queue_id)
            .fetch_all(&self.db)
            .await?;

        let mut workers = Vec::with_capacity(rows.len());
        for row in rows {
            workers.push(Self::map_row(&row)?);
        }
        Ok(workers)
    }

    async fn count_by_fk(&self, queue_id: i64) -> Result<i64> {
        let count: i64 = crate::store::turso::query_scalar(
            "SELECT COUNT(*) FROM pgqrs_workers WHERE queue_id = ?",
        )
        .bind(queue_id)
        .fetch_one(&self.db)
        .await?;
        Ok(count)
    }

    async fn mark_stopped(&self, id: i64) -> Result<()> {
        crate::store::turso::query(TursoDialect::WORKER.mark_stopped)
            .bind(id)
            .execute_once(&self.db)
            .await?;
        Ok(())
    }

    async fn count_for_queue(
        &self,
        queue_id: i64,
        state: crate::types::WorkerStatus,
    ) -> Result<i64> {
        let state_str = state.to_string();
        let count: i64 = crate::store::turso::query_scalar(
            "SELECT COUNT(*) FROM pgqrs_workers WHERE queue_id = ? AND status = ?",
        )
        .bind(queue_id)
        .bind(turso::Value::Text(state_str))
        .fetch_one(&self.db)
        .await?;
        Ok(count)
    }

    async fn count_zombies_for_queue(
        &self,
        queue_id: i64,
        older_than: chrono::Duration,
    ) -> Result<i64> {
        let threshold = Utc::now() - older_than;
        let threshold_str = format_turso_timestamp(&threshold);

        let count: i64 = crate::store::turso::query_scalar("SELECT COUNT(*) FROM pgqrs_workers WHERE queue_id = ? AND status IN ('ready', 'polling', 'suspended', 'interrupted') AND heartbeat_at < ?")
            .bind(queue_id)
            .bind(threshold_str)
            .fetch_one(&self.db)
            .await?;
        Ok(count)
    }

    async fn list_for_queue(
        &self,
        queue_id: i64,
        state: crate::types::WorkerStatus,
    ) -> Result<Vec<WorkerRecord>> {
        let state_str = state.to_string();
        let rows = crate::store::turso::query("SELECT id, hostname, port, queue_id, started_at, heartbeat_at, shutdown_at, status FROM pgqrs_workers WHERE queue_id = ? AND status = ? ORDER BY started_at DESC")
            .bind(queue_id)
            .bind(state_str)
            .fetch_all(&self.db)
            .await?;

        let mut workers = Vec::with_capacity(rows.len());
        for row in rows {
            workers.push(Self::map_row(&row)?);
        }
        Ok(workers)
    }

    async fn list_zombies_for_queue(
        &self,
        queue_id: i64,
        older_than: chrono::Duration,
    ) -> Result<Vec<WorkerRecord>> {
        let threshold = Utc::now() - older_than;
        let threshold_str = format_turso_timestamp(&threshold);

        let rows = crate::store::turso::query("SELECT id, hostname, port, queue_id, started_at, heartbeat_at, shutdown_at, status FROM pgqrs_workers WHERE queue_id = ? AND status IN ('ready', 'polling', 'suspended', 'interrupted') AND heartbeat_at < ? ORDER BY heartbeat_at ASC")
            .bind(queue_id)
            .bind(threshold_str)
            .fetch_all(&self.db)
            .await?;

        let mut workers = Vec::with_capacity(rows.len());
        for row in rows {
            workers.push(Self::map_row(&row)?);
        }
        Ok(workers)
    }

    async fn register(
        &self,
        queue_id: Option<i64>,
        hostname: &str,
        port: i32,
    ) -> Result<WorkerRecord> {
        let existing = crate::store::turso::query("SELECT id, hostname, port, queue_id, started_at, heartbeat_at, shutdown_at, status FROM pgqrs_workers WHERE hostname = ? AND port = ?")
            .bind(hostname)
            .bind(port)
            .fetch_optional(&self.db)
            .await?;

        if let Some(row) = existing {
            let worker = Self::map_row(&row)?;
            match worker.status {
                WorkerStatus::Stopped => {
                    // Reset
                    let now = Utc::now();
                    let now_str = format_turso_timestamp(&now);
                    let row = crate::store::turso::query("UPDATE pgqrs_workers SET status = 'ready', queue_id = ?, started_at = ?, heartbeat_at = ?, shutdown_at = NULL WHERE id = ? RETURNING id, hostname, port, queue_id, started_at, heartbeat_at, shutdown_at, status")
                        .bind(match queue_id {
                            Some(id) => turso::Value::Integer(id),
                            None => turso::Value::Null,
                        })
                        .bind(now_str.clone())
                        .bind(now_str)
                        .bind(worker.id)
                        .fetch_one_once(&self.db)
                        .await?;

                    Self::map_row(&row)
                }
                WorkerStatus::Ready => Err(crate::error::Error::ValidationFailed {
                    reason: format!(
                        "Worker {}:{} is already active. Cannot register duplicate.",
                        hostname, port
                    ),
                }),
                WorkerStatus::Suspended => Err(crate::error::Error::ValidationFailed {
                    reason: format!(
                        "Worker {}:{} is suspended. Use resume() to reactivate.",
                        hostname, port
                    ),
                }),
                WorkerStatus::Polling | WorkerStatus::Interrupted => {
                    Err(crate::error::Error::ValidationFailed {
                        reason: format!(
                            "Worker {}:{} is already active. Cannot register duplicate.",
                            hostname, port
                        ),
                    })
                }
            }
        } else {
            // Create new
            self.insert(crate::types::NewWorkerRecord {
                hostname: hostname.to_string(),
                port,
                queue_id,
            })
            .await
        }
    }

    async fn register_ephemeral(&self, queue_id: Option<i64>) -> Result<WorkerRecord> {
        let hostname = format!("__ephemeral__{}", uuid::Uuid::new_v4());
        let now = Utc::now();
        let now_str = format_turso_timestamp(&now);

        let row = crate::store::turso::query(INSERT_EPHEMERAL_WORKER_RETURNING)
            .bind(hostname.as_str())
            .bind(match queue_id {
                Some(id) => turso::Value::Integer(id),
                None => turso::Value::Null,
            })
            .bind(now_str.clone())
            .bind(now_str.clone())
            .fetch_one_once(&self.db)
            .await?;

        Self::map_row(&row)
    }

    async fn get_status(&self, id: i64) -> Result<WorkerStatus> {
        self.get_status(id).await
    }

    async fn suspend(&self, id: i64) -> Result<()> {
        self.suspend(id).await
    }

    async fn resume(&self, id: i64) -> Result<()> {
        self.resume(id).await
    }

    async fn shutdown(&self, id: i64) -> Result<()> {
        self.shutdown(id).await
    }

    async fn poll(&self, id: i64) -> Result<()> {
        self.poll(id).await
    }

    async fn interrupt(&self, id: i64) -> Result<()> {
        self.interrupt(id).await
    }

    async fn heartbeat(&self, id: i64) -> Result<()> {
        self.heartbeat(id).await
    }

    async fn is_healthy(&self, id: i64, max_age: chrono::Duration) -> Result<bool> {
        self.is_healthy(id, max_age).await
    }
}