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
use crate::{
  key::Key,
  task::{CompletionReceipt, PendingAssignment, Task, TaskAssignment, TaskHandler},
};
use diesel_connection::{get_connection, PooledConnection};
use std::collections::HashMap;
use tokio::task::spawn_blocking;

use super::error::{DieselError, SimpleDieselError};

/// a [`diesel`] specific loader interface designed with that optimizes batching around connection acquisition using [`diesel_connection::get_connection`].
pub trait DieselLoader: Send + Sync {
  type Key: Key;
  type Value: Send + Clone + 'static;
  const MAX_BATCH_SIZE: i32 = 100;
  fn load(
    conn: PooledConnection,
    keys: Vec<Self::Key>,
  ) -> Result<HashMap<Self::Key, Self::Value>, DieselError>;
}

#[async_trait::async_trait]
impl<T> TaskHandler for T
where
  T: Default + DieselLoader + 'static,
{
  type Key = T::Key;
  type Value = T::Value;
  type Error = SimpleDieselError;
  const MAX_BATCH_SIZE: i32 = T::MAX_BATCH_SIZE;

  async fn handle_task(task: Task<PendingAssignment<Self>>) -> Task<CompletionReceipt<Self>> {
    spawn_blocking(move || {
      let conn = get_connection();

      match task.get_assignment() {
        TaskAssignment::LoadBatch(task) => match conn {
          Ok(conn) => {
            let keys = task.keys();
            let result = T::load(conn, keys).map_err(|err| err.into());
            task.resolve(result)
          }
          Err(err) => task.resolve(Err(err.into())),
        },
        TaskAssignment::NoAssignment(receipt) => receipt,
      }
    })
    .await
    .unwrap()
  }
}