|
| 1 | +use crate::schema::cloudfront_invalidation_queue; |
| 2 | +use diesel::prelude::*; |
| 3 | +use diesel_async::{AsyncPgConnection, RunQueryDsl}; |
| 4 | + |
| 5 | +#[derive(Debug, Identifiable, Queryable, QueryableByName, Selectable)] |
| 6 | +#[diesel(table_name = cloudfront_invalidation_queue, check_for_backend(diesel::pg::Pg))] |
| 7 | +pub struct CloudFrontInvalidationQueueItem { |
| 8 | + pub id: i64, |
| 9 | + pub path: String, |
| 10 | + pub created_at: chrono::DateTime<chrono::Utc>, |
| 11 | +} |
| 12 | + |
| 13 | +#[derive(Debug, Insertable)] |
| 14 | +#[diesel(table_name = cloudfront_invalidation_queue, check_for_backend(diesel::pg::Pg))] |
| 15 | +pub struct NewCloudFrontInvalidationQueueItem<'a> { |
| 16 | + pub path: &'a str, |
| 17 | +} |
| 18 | + |
| 19 | +impl CloudFrontInvalidationQueueItem { |
| 20 | + /// Queue multiple invalidation paths for later processing |
| 21 | + pub async fn queue_paths(conn: &mut AsyncPgConnection, paths: &[String]) -> QueryResult<usize> { |
| 22 | + let new_items: Vec<_> = paths |
| 23 | + .iter() |
| 24 | + .map(|path| NewCloudFrontInvalidationQueueItem { path }) |
| 25 | + .collect(); |
| 26 | + |
| 27 | + diesel::insert_into(cloudfront_invalidation_queue::table) |
| 28 | + .values(&new_items) |
| 29 | + .execute(conn) |
| 30 | + .await |
| 31 | + } |
| 32 | + |
| 33 | + /// Fetch the oldest paths from the queue |
| 34 | + pub async fn fetch_batch( |
| 35 | + conn: &mut AsyncPgConnection, |
| 36 | + limit: i64, |
| 37 | + ) -> QueryResult<Vec<CloudFrontInvalidationQueueItem>> { |
| 38 | + // Fetch the oldest entries up to the limit |
| 39 | + cloudfront_invalidation_queue::table |
| 40 | + .order(cloudfront_invalidation_queue::created_at.asc()) |
| 41 | + .limit(limit) |
| 42 | + .load(conn) |
| 43 | + .await |
| 44 | + } |
| 45 | + |
| 46 | + /// Remove queue items by their IDs |
| 47 | + pub async fn remove_items( |
| 48 | + conn: &mut AsyncPgConnection, |
| 49 | + item_ids: &[i64], |
| 50 | + ) -> QueryResult<usize> { |
| 51 | + diesel::delete(cloudfront_invalidation_queue::table) |
| 52 | + .filter(cloudfront_invalidation_queue::id.eq_any(item_ids)) |
| 53 | + .execute(conn) |
| 54 | + .await |
| 55 | + } |
| 56 | +} |
0 commit comments