headless_lms_server/programs/
regrader.rs

1use std::{env, sync::Arc, time::Duration};
2
3use crate::domain::models_requests::{self, JwtKey};
4use headless_lms_models as models;
5use models::library::regrading;
6use sqlx::{Connection, PgConnection};
7
8/**
9Starts a thread that will periodically send regrading submissions to the corresponding exercise services for regrading.
10*/
11pub async fn main() -> anyhow::Result<()> {
12    // TODO: Audit that the environment access only happens in single-threaded code.
13    unsafe { env::set_var("RUST_LOG", "info,actix_web=info,sqlx=warn") };
14    dotenv::dotenv().ok();
15    crate::setup_tracing()?;
16    let db_url = env::var("DATABASE_URL")
17        .unwrap_or_else(|_| "postgres://localhost/headless_lms_dev".to_string());
18    let jwt_key = Arc::new(JwtKey::try_from_env().expect("Could not initialise JwtKey"));
19
20    let mut interval = tokio::time::interval(Duration::from_secs(10));
21    let mut ticks = 60;
22    // Since this is repeating every 10 seconds we can keep the connection open.
23    let mut conn = PgConnection::connect(&db_url).await?;
24    loop {
25        interval.tick().await;
26
27        ticks += 1;
28        // 60 10 second intervals = 10 minutes
29        if ticks > 60 {
30            // occasionally prints a reminder that the service is still running
31            ticks = 0;
32            tracing::info!("running the regrader");
33        }
34
35        let exercise_services_by_type =
36            models::exercise_service_info::get_all_exercise_services_by_type(
37                &mut conn,
38                models_requests::fetch_service_info,
39            )
40            .await?;
41        // do not stop the thread on error, report it and try again next tick
42        if let Err(err) = regrading::regrade(
43            &mut conn,
44            &exercise_services_by_type,
45            models_requests::make_grading_request_sender(Arc::clone(&jwt_key)),
46        )
47        .await
48        {
49            tracing::error!("Error in regrader: {}", err);
50        }
51    }
52}