Skip to main content

cozo/runtime/db/
running.rs

1/*
2 * Copyright 2022, The Cozo Project Authors.
3 *
4 * This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0.
5 * If a copy of the MPL was not distributed with this file,
6 * You can obtain one at https://mozilla.org/MPL/2.0/.
7 */
8
9use std::collections::BTreeMap;
10use std::sync::atomic::{AtomicBool, Ordering};
11use std::sync::{Arc, Mutex};
12#[allow(unused_imports)]
13use std::thread;
14#[allow(unused_imports)]
15use std::time::{Duration, SystemTime, UNIX_EPOCH};
16
17#[allow(unused_imports)]
18use miette::{bail, Diagnostic, IntoDiagnostic, Result};
19use thiserror::Error;
20
21pub(crate) struct RunningQueryHandle {
22    pub(crate) started_at: f64,
23    pub(crate) poison: Poison,
24}
25
26pub(crate) struct RunningQueryCleanup {
27    pub(crate) id: u64,
28    pub(crate) running_queries: Arc<Mutex<BTreeMap<u64, RunningQueryHandle>>>,
29}
30
31impl Drop for RunningQueryCleanup {
32    fn drop(&mut self) {
33        let mut map = self.running_queries.lock().unwrap();
34        if let Some(handle) = map.remove(&self.id) {
35            handle.poison.0.store(true, Ordering::Relaxed);
36        }
37    }
38}
39
40/// Used for user-initiated termination of running queries
41#[derive(Clone, Default)]
42pub struct Poison(pub(crate) Arc<AtomicBool>);
43
44impl Poison {
45    /// Will return `Err` if user has initiated termination.
46    #[inline(always)]
47    pub fn check(&self) -> Result<()> {
48        #[derive(Debug, Error, Diagnostic)]
49        #[error("Running query is killed before completion")]
50        #[diagnostic(code(eval::killed))]
51        #[diagnostic(help("A query may be killed by timeout, or explicit command"))]
52        struct ProcessKilled;
53
54        if self.0.load(Ordering::Relaxed) {
55            bail!(ProcessKilled)
56        }
57        Ok(())
58    }
59    #[cfg(target_arch = "wasm32")]
60    pub(crate) fn set_timeout(&self, _secs: f64) -> Result<()> {
61        bail!("Cannot set timeout when threading is disallowed");
62    }
63    #[cfg(not(target_arch = "wasm32"))]
64    pub(crate) fn set_timeout(&self, secs: f64) -> Result<()> {
65        let pill = self.clone();
66        thread::spawn(move || {
67            thread::sleep(Duration::from_micros((secs * 1000000.) as u64));
68            pill.0.store(true, Ordering::Relaxed);
69        });
70        Ok(())
71    }
72}
73
74pub(crate) fn seconds_since_the_epoch() -> Result<f64> {
75    #[cfg(not(target_arch = "wasm32"))]
76    let now = SystemTime::now();
77    #[cfg(not(target_arch = "wasm32"))]
78    return Ok(now
79        .duration_since(UNIX_EPOCH)
80        .into_diagnostic()?
81        .as_secs_f64());
82
83    #[cfg(target_arch = "wasm32")]
84    Ok(js_sys::Date::now())
85}