larastvel-core 0.2.2

Larastvel framework core - inspired by Laravel
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
use std::sync::{Arc, Mutex};

use async_trait::async_trait;

use super::{
    batches::{JobBatch, PendingBatch},
    JobBox, JobError, Queue,
};

pub type JobResolver = Arc<dyn Fn(&str, &str) -> Option<JobBox> + Send + Sync>;

type Reserved = Option<(i64, Option<String>)>;

pub struct DatabaseQueue {
    name: String,
    table_name: String,
    db: sea_orm::DatabaseConnection,
    resolver: JobResolver,
    last_reserved: Arc<Mutex<Reserved>>,
    failed_table_name: String,
    batch_table_name: String,
}

impl std::fmt::Debug for DatabaseQueue {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("DatabaseQueue")
            .field("name", &self.name)
            .field("table_name", &self.table_name)
            .field("db", &self.db)
            .field("resolver", &"<closure>")
            .finish()
    }
}

impl Clone for DatabaseQueue {
    fn clone(&self) -> Self {
        Self {
            name: self.name.clone(),
            table_name: self.table_name.clone(),
            db: self.db.clone(),
            resolver: self.resolver.clone(),
            last_reserved: self.last_reserved.clone(),
            failed_table_name: self.failed_table_name.clone(),
            batch_table_name: self.batch_table_name.clone(),
        }
    }
}

impl DatabaseQueue {
    pub fn new(name: &str, db: sea_orm::DatabaseConnection, resolver: JobResolver) -> Self {
        Self {
            name: name.to_string(),
            table_name: "jobs".to_string(),
            db,
            resolver,
            last_reserved: Arc::new(Mutex::new(None)),
            failed_table_name: "failed_jobs".to_string(),
            batch_table_name: "job_batches".to_string(),
        }
    }

    pub fn with_table(mut self, table: &str) -> Self {
        self.table_name = table.to_string();
        self
    }

    /// Set the name of the `failed_jobs` table used to record permanent
    /// failures.
    pub fn with_failed_table(mut self, table: &str) -> Self {
        self.failed_table_name = table.to_string();
        self
    }

    pub async fn ensure_table_exists(&self) -> Result<(), JobError> {
        let sql = format!(
            "CREATE TABLE IF NOT EXISTS {} (
                id INTEGER PRIMARY KEY AUTOINCREMENT,
                queue TEXT NOT NULL DEFAULT 'default',
                payload TEXT NOT NULL,
                class TEXT NOT NULL DEFAULT '',
                attempts INTEGER NOT NULL DEFAULT 0,
                max_attempts INTEGER NOT NULL DEFAULT 3,
                reserved_at INTEGER,
                available_at INTEGER NOT NULL,
                created_at INTEGER NOT NULL
            )",
            self.table_name
        );
        use sea_orm::ConnectionTrait;
        self.db
            .execute(sea_orm::Statement::from_string(
                sea_orm::DatabaseBackend::Sqlite,
                sql,
            ))
            .await
            .map_err(|e| JobError::Queue(format!("Failed to create jobs table: {}", e)))?;
        Ok(())
    }

    /// Ensure the `failed_jobs` table exists (used by [`Queue::fail`]).
    pub async fn ensure_failed_table_exists(&self) -> Result<(), JobError> {
        super::FailedJobStore::new(self.db.clone())
            .with_table(&self.failed_table_name)
            .ensure_table_exists()
            .await
    }

    /// Set the name of the `job_batches` table used to track batches.
    pub fn with_batches_table(mut self, table: &str) -> Self {
        self.batch_table_name = table.to_string();
        self
    }

    /// Ensure the `job_batches` table exists.
    pub async fn ensure_batches_table_exists(&self) -> Result<(), JobError> {
        super::JobBatchStore::new(self.db.clone())
            .with_table(&self.batch_table_name)
            .ensure_table_exists()
            .await
    }

    /// Dispatch a pending batch (Laravel's `Bus::batch([...])->dispatch()`).
    pub async fn dispatch_batch(&self, pending: &PendingBatch) -> Result<JobBatch, JobError> {
        self.ensure_batches_table_exists().await?;

        let now = now_unix();
        let id = uuid::Uuid::new_v4().to_string();
        let total = pending.jobs().len() as i64;
        let batch = JobBatch {
            id,
            name: pending.name_of().to_string(),
            total_jobs: total,
            pending_jobs: total,
            failed_jobs: 0,
            cancelled: false,
            created_at: now,
            finished_at: None,
            cancelled_at: None,
        };

        super::JobBatchStore::new(self.db.clone())
            .with_table(&self.batch_table_name)
            .insert(&batch)
            .await?;

        for job in pending.jobs() {
            let payload = serde_json::to_string(&serde_json::json!({
                "name": job.name(),
                "batch_id": batch.id,
            }))
            .map_err(|e| JobError::Queue(format!("Serialization error: {}", e)))?;

            let max_attempts = job.max_attempts().unwrap_or(3);
            let sql = format!(
                "INSERT INTO {} (queue, payload, class, attempts, max_attempts, available_at, created_at)
                 VALUES (?1, ?2, ?3, 0, ?4, ?5, ?5)",
                self.table_name
            );
            use sea_orm::ConnectionTrait;
            self.db
                .execute(sea_orm::Statement::from_sql_and_values(
                    sea_orm::DatabaseBackend::Sqlite,
                    &sql,
                    [
                        self.name.clone().into(),
                        payload.into(),
                        job.name().to_string().into(),
                        (max_attempts as i64).into(),
                        now.into(),
                    ],
                ))
                .await
                .map_err(|e| JobError::Queue(format!("Failed to push batch job: {}", e)))?;
        }

        Ok(batch)
    }

    /// Look up a batch by its id.
    pub async fn batch(&self, id: &str) -> Result<Option<JobBatch>, JobError> {
        super::JobBatchStore::new(self.db.clone())
            .with_table(&self.batch_table_name)
            .find(id)
            .await
    }

    /// Cancel a batch by its id. Reserved jobs finish; the rest are skipped
    /// by the worker.
    pub async fn cancel_batch(&self, id: &str) -> Result<(), JobError> {
        super::JobBatchStore::new(self.db.clone())
            .with_table(&self.batch_table_name)
            .cancel(id)
            .await
    }

    /// Record the last reserved job as failed in the `failed_jobs` table and
    /// remove it from the jobs table. If no job was reserved, falls back to
    /// exhausting its attempts.
    async fn record_failure(&self, job: JobBox, exception: String) -> Result<(), JobError> {
        let reserved = self.last_reserved.lock().unwrap().clone();
        let Some((job_id, batch_id)) = reserved else {
            return Ok(());
        };

        if let Some(batch_id) = &batch_id {
            let store =
                super::JobBatchStore::new(self.db.clone()).with_table(&self.batch_table_name);
            store.increment_failed(batch_id).await?;
            store.decrement_pending(batch_id).await?;
            store.mark_finished_if_done(batch_id).await?;
        }

        let store = super::FailedJobStore::new(self.db.clone()).with_table(&self.failed_table_name);
        store.ensure_table_exists().await?;

        let class = job.name().to_string();
        let payload = super::failed::job_payload(job.as_ref());

        store
            .log(&self.name, &self.name, &class, &payload, &exception)
            .await?;

        let sql = format!("DELETE FROM {} WHERE id = ?1", self.table_name);
        use sea_orm::ConnectionTrait;
        self.db
            .execute(sea_orm::Statement::from_sql_and_values(
                sea_orm::DatabaseBackend::Sqlite,
                &sql,
                [job_id.into()],
            ))
            .await
            .map_err(|e| JobError::Queue(format!("Failed to remove failed job row: {}", e)))?;
        Ok(())
    }
}

#[async_trait]
impl Queue for DatabaseQueue {
    async fn push(&self, job: JobBox) -> Result<(), JobError> {
        let payload = serde_json::to_string(&serde_json::json!({
            "name": job.name(),
        }))
        .map_err(|e| JobError::Queue(format!("Serialization error: {}", e)))?;

        let class = job.name().to_string();
        let max_attempts = job.max_attempts().unwrap_or(3);
        let now = std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .unwrap()
            .as_secs() as i64;

        let sql = format!(
            "INSERT INTO {} (queue, payload, class, attempts, max_attempts, available_at, created_at)
             VALUES (?1, ?2, ?3, 0, ?4, ?5, ?5)",
            self.table_name
        );
        use sea_orm::ConnectionTrait;
        self.db
            .execute(sea_orm::Statement::from_sql_and_values(
                sea_orm::DatabaseBackend::Sqlite,
                &sql,
                [
                    self.name.clone().into(),
                    payload.into(),
                    class.into(),
                    (max_attempts as i64).into(),
                    now.into(),
                ],
            ))
            .await
            .map_err(|e| JobError::Queue(format!("Failed to push job: {}", e)))?;
        Ok(())
    }

    async fn pop(&self) -> Option<(JobBox, u64)> {
        let now = now_unix();
        let store = super::JobBatchStore::new(self.db.clone()).with_table(&self.batch_table_name);

        loop {
            let sql = format!(
                "SELECT id, payload, class, attempts FROM {}
                 WHERE queue = ?1 AND (reserved_at IS NULL OR reserved_at < ?2)
                 AND attempts < max_attempts
                 AND available_at <= ?2
                 ORDER BY id ASC LIMIT 1",
                self.table_name
            );
            use sea_orm::{ConnectionTrait, QueryResult};
            let result: Vec<QueryResult> = self
                .db
                .query_all(sea_orm::Statement::from_sql_and_values(
                    sea_orm::DatabaseBackend::Sqlite,
                    &sql,
                    [self.name.clone().into(), now.into(), now.into()],
                ))
                .await
                .ok()?;

            let row = result.into_iter().next()?;

            let class: String = row.try_get_by_index::<String>(2).ok()?;
            let payload: String = row.try_get_by_index::<String>(1).ok()?;
            let id: Option<i64> = row.try_get_by_index::<i64>(0).ok();
            let batch_id: Option<String> =
                serde_json::from_str(&payload)
                    .ok()
                    .and_then(|v: serde_json::Value| {
                        v.get("batch_id").and_then(|b| b.as_str()).map(String::from)
                    });

            if let Some(batch_id) = &batch_id {
                if store.is_cancelled(batch_id).await.unwrap_or(false) {
                    if let Some(job_id) = id {
                        let delete_sql = format!("DELETE FROM {} WHERE id = ?1", self.table_name);
                        let _ = self
                            .db
                            .execute(sea_orm::Statement::from_sql_and_values(
                                sea_orm::DatabaseBackend::Sqlite,
                                &delete_sql,
                                [job_id.into()],
                            ))
                            .await;
                    }
                    continue;
                }
            }

            let resolver = self.resolver.clone();
            let job = resolver(&class, &payload)?;

            let attempts: i64 = row.try_get_by_index::<i64>(3).unwrap_or(0);
            if let Some(job_id) = id {
                let update_sql = format!(
                    "UPDATE {} SET reserved_at = ?1, attempts = attempts + 1 WHERE id = ?2",
                    self.table_name
                );
                let _ = self
                    .db
                    .execute(sea_orm::Statement::from_sql_and_values(
                        sea_orm::DatabaseBackend::Sqlite,
                        &update_sql,
                        [now.into(), job_id.into()],
                    ))
                    .await;

                let mut last = self.last_reserved.lock().unwrap();
                *last = Some((job_id, batch_id));
            }

            return Some((job, (attempts + 1) as u64));
        }
    }

    /// Release the last reserved row back to the queue with a delay, keeping
    /// its attempt count. Assumes a single worker per queue instance.
    async fn release(
        &self,
        job: JobBox,
        attempts: u64,
        delay_seconds: u64,
    ) -> Result<(), JobError> {
        let _ = (job, attempts);
        let id = {
            let last = self.last_reserved.lock().unwrap();
            last.as_ref().map(|(job_id, _)| *job_id)
        };
        let Some(job_id) = id else {
            return Ok(());
        };
        let now = std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .unwrap()
            .as_secs() as i64;

        let sql = format!(
            "UPDATE {} SET reserved_at = NULL, available_at = ?1 WHERE id = ?2",
            self.table_name
        );
        use sea_orm::ConnectionTrait;
        self.db
            .execute(sea_orm::Statement::from_sql_and_values(
                sea_orm::DatabaseBackend::Sqlite,
                &sql,
                [(now + delay_seconds as i64).into(), job_id.into()],
            ))
            .await
            .map_err(|e| JobError::Queue(format!("Failed to release job: {}", e)))?;
        Ok(())
    }

    /// Permanently fail the last reserved row by recording it in the
    /// `failed_jobs` table and removing it from the jobs table.
    async fn fail(&self, job: JobBox, exception: String) -> Result<(), JobError> {
        self.record_failure(job, exception).await
    }

    /// Called by the worker after a job finishes successfully: decrements the
    /// pending count of the job's batch (if any) and marks it finished.
    async fn job_succeeded(&self, job: JobBox) -> Result<(), JobError> {
        let reserved = self.last_reserved.lock().unwrap().clone();
        let _ = job;

        let Some((_, Some(batch_id))) = reserved else {
            return Ok(());
        };

        let store = super::JobBatchStore::new(self.db.clone()).with_table(&self.batch_table_name);
        store.decrement_pending(&batch_id).await?;
        store.mark_finished_if_done(&batch_id).await?;
        Ok(())
    }

    async fn count(&self) -> usize {
        let sql = format!(
            "SELECT COUNT(*) as cnt FROM {} WHERE queue = ?1 AND attempts < max_attempts",
            self.table_name
        );
        use sea_orm::ConnectionTrait;
        let result = self
            .db
            .query_one(sea_orm::Statement::from_sql_and_values(
                sea_orm::DatabaseBackend::Sqlite,
                &sql,
                [self.name.clone().into()],
            ))
            .await;

        match result {
            Ok(Some(row)) => {
                let cnt: Option<i64> = row.try_get_by_index(0).ok();
                cnt.unwrap_or(0) as usize
            }
            _ => 0,
        }
    }

    fn name(&self) -> &str {
        &self.name
    }
}

fn now_unix() -> i64 {
    std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .unwrap()
        .as_secs() as i64
}