//! 独立队列参考：官方 SQLite 事务、deadpool 阻塞交接及 Tokio 信号，不链接 Dever。
mod queue;
use deadpool_sqlite::{Object, Runtime, rusqlite::Connection};
use queue::*;
use std::time::Duration;

async fn call<T: Send + 'static>(
    object: &Object,
    action: impl FnOnce(&mut Connection) -> Result<T> + Send + 'static,
) -> Result<T> {
    // 每次阻塞操作都等待真实结束，终止信号不丢弃正在提交或回滚的任务。
    object
        .interact(action)
        .await
        .map_err(|error| error.to_string())?
}

async fn run() -> Result<()> {
    let args: Vec<String> = std::env::args().collect();
    let pool = deadpool_sqlite::Config::new(&args[1])
        .builder(Runtime::Tokio1)?
        .max_size(2)
        .build()?;
    let object = pool.get().await?;
    call(&object, |connection| {
        connection.execute_batch(
            "PRAGMA journal_mode=WAL;PRAGMA synchronous=NORMAL;PRAGMA foreign_keys=ON;",
        )?;
        connection.busy_timeout(Duration::from_secs(30))?;
        Ok(())
    })
    .await?;
    if args[2] == "worker" {
        let mut stop = tokio::signal::unix::signal(tokio::signal::unix::SignalKind::terminate())?;
        loop {
            // 仅在领取间隙停止；已经领取的工作在上方期限内完成事务收尾。
            let stopping = tokio::select! { biased;
                _ = stop.recv() => true,
                _ = std::future::ready(()) => false,
            };
            if stopping {
                break;
            }
            match call(&object, claim).await? {
                Some(value) => call(&object, move |connection| apply(connection, value)).await?,
                None => tokio::select! {
                    _ = stop.recv() => break,
                    _ = tokio::time::sleep(Duration::from_millis(1)) => {},
                },
            }
        }
    } else {
        let inputs = match args[2].as_str() {
            "submitAll" => serde_json::from_str::<Batch>(&args[3])?
                .inputs
                .into_iter()
                .map(|input| Submit {
                    key: input.name.clone(),
                    input,
                })
                .collect(),
            "submit" => vec![serde_json::from_str::<Submit>(&args[3])?],
            _ => return Err("unknown command".into()),
        };
        let ids = call(&object, move |connection| submit(connection, inputs)).await?;
        let out = if args[2] == "submit" {
            serde_json::to_value(&ids[0])?
        } else {
            serde_json::to_value(ids)?
        };
        println!("{out}");
    }
    drop(object);
    pool.close();
    Ok(())
}

fn main() {
    let runtime = tokio::runtime::Builder::new_current_thread()
        .enable_all()
        .build()
        .unwrap();
    if let Err(error) = runtime.block_on(run()) {
        eprintln!("{error}");
        std::process::exit(1);
    }
}
