use std::path::PathBuf;
use std::sync::Arc;
use serde_json::Value;
use crate::daemon::{CoreConfig, Daemon, InProcess, Serving};
use crate::operation::DaemonOperation;
pub struct CoreHandle {
daemon: Arc<Daemon>,
runtime: tokio::runtime::Handle,
maintenance: Option<tokio::task::JoinHandle<()>>,
_serving: Serving,
}
impl CoreHandle {
pub async fn open(config: CoreConfig) -> Result<Self, String> {
let daemon = Daemon::open(&config)?;
daemon.recover_owned_state().await?;
let daemon = Arc::new(daemon);
let serving = daemon.serve_in_process();
let maintenance = Daemon::spawn_maintenance(&daemon);
Ok(Self {
daemon,
runtime: tokio::runtime::Handle::current(),
maintenance: Some(maintenance),
_serving: serving,
})
}
pub async fn call(&self, method: &str, params: Value) -> Result<Value, String> {
let controller = crate::process::controller(false);
InProcess::call(
Arc::clone(&self.daemon),
self.runtime.clone(),
method.to_string(),
params,
controller,
)
.await
}
pub async fn execute<O: DaemonOperation>(&self, operation: O) -> Result<O::Response, String> {
let params = serde_json::to_value(operation).map_err(|error| error.to_string())?;
let value = self.call(O::METHOD, params).await?;
serde_json::from_value(value).map_err(|error| error.to_string())
}
pub async fn shutdown(mut self) {
self.daemon.stop();
if let Some(maintenance) = self.maintenance.take() {
let _ = maintenance.await;
}
}
}
impl Drop for CoreHandle {
fn drop(&mut self) {
self.daemon.stop();
if let Some(maintenance) = self.maintenance.take() {
maintenance.abort();
}
}
}
pub struct Apoc {
core: Option<CoreHandle>,
runtime: tokio::runtime::Runtime,
}
impl Apoc {
pub fn open(state_dir: impl Into<PathBuf>) -> Result<Self, String> {
Self::open_with(CoreConfig::new(state_dir))
}
pub fn open_with(config: CoreConfig) -> Result<Self, String> {
refuse_inside_async("Apoc::open")?;
let runtime = tokio::runtime::Builder::new_multi_thread()
.thread_name("apoc-core")
.enable_all()
.build()
.map_err(|error| error.to_string())?;
let core = runtime.block_on(CoreHandle::open(config))?;
Ok(Self {
core: Some(core),
runtime,
})
}
pub fn call(&self, method: &str, params: Value) -> Result<Value, String> {
refuse_inside_async("Apoc::call")?;
let core = self.core.as_ref().expect("an open core");
self.runtime.block_on(core.call(method, params))
}
pub fn execute<O: DaemonOperation>(&self, operation: O) -> Result<O::Response, String> {
refuse_inside_async("Apoc::execute")?;
let core = self.core.as_ref().expect("an open core");
self.runtime.block_on(core.execute(operation))
}
}
impl Drop for Apoc {
fn drop(&mut self) {
if let Some(core) = self.core.take() {
if tokio::runtime::Handle::try_current().is_err() {
self.runtime.block_on(core.shutdown());
}
}
}
}
fn refuse_inside_async(call: &str) -> Result<(), String> {
if tokio::runtime::Handle::try_current().is_ok() {
return Err(format!(
"BLOCKING_FROM_ASYNC: {call} blocks its thread and was called inside an async \
runtime; use CoreHandle from async code"
));
}
Ok(())
}