pub mod artifacts;
pub mod canon;
pub mod catalogue;
pub mod code;
pub mod commands;
pub use crate::declarations;
pub mod diag;
pub mod event_journal;
pub mod event_archive;
pub mod webhooks;
pub mod journal;
pub(crate) mod inputs;
pub mod keys;
pub mod ops;
pub mod output_schema;
pub mod surface;
pub mod tools;
pub mod wire;
use std::sync::Arc;
mod files;
pub struct CadService {
pub files: files::Files,
pub event_archive: std::sync::OnceLock<event_archive::Archive>,
pub webhooks: webhooks::Webhooks,
pub ops: ops::Operations,
pub artifacts: artifacts::Artifacts,
pub code: code::Executions,
pub catalogue: catalogue::Catalogue,
pub services: Vec<crate::script_sdk::ServiceEntry>,
pub server: std::sync::OnceLock<std::sync::Weak<crate::server::ServerState>>,
pub retry_keys: std::sync::Mutex<std::collections::HashMap<String, String>>,
}
pub use crate::script_sdk::{script_callable, ScriptTool};
impl CadService {
pub fn new(slot: crate::tools::app::SessionSlot) -> Arc<Self> {
let catalogue = catalogue::Catalogue::new();
Arc::new_cyclic(|weak| CadService {
files: files::Files::new(),
event_archive: Default::default(),
webhooks: Default::default(),
ops: ops::Operations::new(slot, weak.clone()),
artifacts: artifacts::Artifacts::new(),
code: code::Executions::new(weak.clone()),
services: surface::service_entries(&catalogue),
catalogue,
server: std::sync::OnceLock::new(),
retry_keys: Default::default(),
})
}
pub fn event(&self, kind: &'static str, id: Option<&str>, state: Option<&str>, code: Option<&str>, sequence: Option<u64>) {
let value = diag::event(kind, id, state, code, sequence);
self.webhooks.publish(&value);
if let Some(archive) = self.event_archive.get() { archive.publish(value); }
}
pub fn archive_resource(&self, uri: &str) -> Result<serde_json::Value, String> {
match self.event_archive.get() {
Some(archive) => archive.resource(uri),
None if uri == "brep://events/archive" => Ok(serde_json::json!({"enabled":false,"records":[],"persistence":{"status":"disabled"}})),
None => Err("diagnostic archive is disabled".into()),
}
}
pub(crate) fn server_state(&self) -> Option<Arc<crate::server::ServerState>> {
self.server.get().and_then(std::sync::Weak::upgrade)
}
pub fn script_tools(&self) -> Vec<ScriptTool> {
let Some(state) = self.server_state() else { return vec![] };
let set = state.tools.blocking_read();
crate::script_sdk::script_tools(&set.specs)
}
pub async fn script_tool(&self, name: &str) -> Option<crate::tools::ToolSpec> {
let state = self.server_state()?;
let set = state.tools.read().await;
set.specs.iter().find(|t| t.name == name && script_callable(t.group, &t.name)).cloned()
}
pub async fn describe(&self, paths: &[String]) -> Result<serde_json::Value, wire::ApiError> {
use serde_json::json;
if paths.is_empty() || paths.len() > 8 { return Err(wire::ApiError::new("invalid_arguments", "validation", "describe takes 1..8 paths")); }
let state = self.server_state();
let empty = crate::tools::ToolSet::default();
let guard = match &state { Some(state) => Some(state.tools.read().await), None => None };
let surface = self.surface(guard.as_deref().unwrap_or(&empty), None);
let mut methods = Vec::new();
for path in paths {
let registry = |old: &str| {
let (group, tool) = old.split_once('.')?;
surface.entries.iter().find(|e| matches!(e.target, crate::script_sdk::Target::Tool(t) if crate::script_sdk::ident(t.group) == group && (t.name == tool || t.name == format!("files_{tool}"))))
};
let entry = surface.get(path).or_else(|| path.strip_prefix("brep.").and_then(registry))
.ok_or_else(|| wire::ApiError::new("method_unknown", "lookup", surface.unknown(path)))?;
methods.push(entry.to_json());
}
let result = json!({"manifest":self.catalogue.identity(),"version":surface.version(),"methods":methods});
if result.to_string().len() > 64 << 10 { return Err(wire::ApiError::new("resource_limit", "validation", "describe fewer paths")); }
Ok(result)
}
pub fn run_local(&self, source: &str) -> Result<String, String> {
let caller = tools::caller_of_transport();
let (key, _) = keys::issue(&caller.scope, keys::Purpose::Execution);
let req = serde_json::json!({
"manifest": self.catalogue.identity(),
"source": source,
"initialDocuments": [],
"requestedCapabilities": [],
"idempotencyKey": key,
});
let status = self.code.submit_as(&caller, &req, true).map_err(|e| e.message)?;
Ok(status["executionId"].as_str().unwrap_or_default().to_string())
}
pub fn result_local(&self, id: &str) -> Result<Option<serde_json::Value>, String> {
let caller = tools::caller_of_transport();
match self.code.result(&caller, &serde_json::json!({ "executionId": id })) {
Ok(mut result) => {
let log = result["logArtifact"]["artifactId"].as_str().map(str::to_string);
if let Some(log) = log {
if let Ok((bytes, _)) = self.artifacts.lease(&caller.owner(), &log) {
self.artifacts.release(&log);
result["logText"] = String::from_utf8_lossy(&bytes).into_owned().into();
}
}
Ok(Some(result))
}
Err(e) if e.code == "not_ready" => Ok(None),
Err(e) => Err(e.message),
}
}
pub fn halt_local(&self, id: &str) -> Result<(), String> {
let caller = tools::caller_of_transport();
self.code.cancel(&caller, &serde_json::json!({ "executionId": id })).map(|_| ()).map_err(|e| e.message)
}
}
#[derive(Clone)]
pub struct LocalScripts {
cad: std::sync::Weak<CadService>,
runtime: tokio::runtime::Handle,
}
impl std::fmt::Debug for LocalScripts {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str("LocalScripts")
}
}
impl LocalScripts {
pub fn new(cad: &Arc<CadService>, runtime: tokio::runtime::Handle) -> Self {
LocalScripts { cad: Arc::downgrade(cad), runtime }
}
fn cad(&self) -> Result<Arc<CadService>, String> {
self.cad.upgrade().ok_or_else(|| "the script runner has stopped".to_string())
}
pub fn ready(&self) -> Result<bool, String> {
let state = self.cad()?.server_state().ok_or("the server is stopping")?;
Ok(state.tools.try_read().is_ok_and(|set| set.specs.iter().any(|t| t.name == "docs_list")))
}
pub fn run(&self, source: &str) -> Result<String, String> {
let _enter = self.runtime.enter();
self.cad()?.run_local(source)
}
pub fn result(&self, id: &str) -> Result<Option<serde_json::Value>, String> {
self.cad()?.result_local(id)
}
pub fn halt(&self, id: &str) -> Result<(), String> {
let _enter = self.runtime.enter();
self.cad()?.halt_local(id)
}
}