use std::collections::HashMap;
use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::{Arc, Mutex};
use std::time::{SystemTime, UNIX_EPOCH};
use ek_core::context::PluginContext;
use ek_core::plugin::Plugin;
use ek_event::{Event, EventEngine};
use crate::audit::AuditLog;
use crate::hub::{self, Hub};
pub struct ApiPlugin {
ctx: Mutex<Option<PluginContext>>,
store: ek_cfg::Store,
profile: String,
log_path: Mutex<PathBuf>,
audit: AuditLog,
hub: Arc<Hub>,
dropped: Arc<AtomicU64>,
orders: Mutex<HashMap<String, serde_json::Value>>,
conns: AtomicU64,
started_ms: u64,
}
impl ApiPlugin {
#[must_use]
pub fn new(
store: ek_cfg::Store,
profile: String,
log_path: PathBuf,
event: &Arc<EventEngine>,
) -> Self {
let audit_dir = log_path
.parent()
.map_or_else(|| PathBuf::from("."), Path::to_path_buf);
let hub = Arc::new(Hub::new());
let dropped = Arc::new(AtomicU64::new(0));
let h = Arc::clone(&hub);
event.register_general(Arc::new(move |e: &Event| {
if let Some(frame) = crate::event_json::event_frame(e) {
h.publish(e.event_type.as_str(), frame);
}
}));
Self {
ctx: Mutex::new(None),
store,
profile,
log_path: Mutex::new(log_path),
audit: AuditLog::new(&audit_dir),
hub,
dropped,
orders: Mutex::new(HashMap::new()),
conns: AtomicU64::new(0),
started_ms: now_ms(),
}
}
#[must_use]
pub fn order_result(&self, client_id: &str) -> Option<serde_json::Value> {
self.orders
.lock()
.unwrap_or_else(|p| p.into_inner())
.get(client_id)
.cloned()
}
pub fn store_order_result(&self, client_id: String, result: serde_json::Value) {
let mut g = self.orders.lock().unwrap_or_else(|p| p.into_inner());
if g.len() >= 4096 {
g.clear();
}
g.insert(client_id, result);
}
#[must_use]
pub fn audit(&self) -> &AuditLog {
&self.audit
}
#[must_use]
pub fn hub(&self) -> &Arc<Hub> {
&self.hub
}
#[must_use]
pub fn dropped(&self) -> Arc<AtomicU64> {
Arc::clone(&self.dropped)
}
#[must_use]
pub fn ctx(&self) -> Option<PluginContext> {
self.ctx.lock().unwrap_or_else(|p| p.into_inner()).clone()
}
#[must_use]
pub fn store(&self) -> &ek_cfg::Store {
&self.store
}
#[must_use]
pub fn profile(&self) -> &str {
&self.profile
}
#[must_use]
pub fn log_path(&self) -> PathBuf {
self.log_path
.lock()
.unwrap_or_else(|p| p.into_inner())
.clone()
}
#[must_use]
pub fn conns(&self) -> u64 {
self.conns.load(Ordering::Relaxed)
}
pub fn conn_open(&self) {
self.conns.fetch_add(1, Ordering::Relaxed);
}
pub fn conn_close(&self) {
self.conns.fetch_sub(1, Ordering::Relaxed);
}
#[must_use]
pub fn started_ms(&self) -> u64 {
self.started_ms
}
#[must_use]
pub fn uptime_ms(&self) -> u64 {
now_ms().saturating_sub(self.started_ms)
}
}
impl Plugin for ApiPlugin {
fn name(&self) -> &str {
"api"
}
fn version(&self) -> std::borrow::Cow<'static, str> {
std::borrow::Cow::Borrowed(env!("CARGO_PKG_VERSION"))
}
fn routes(&self) -> Vec<std::borrow::Cow<'static, str>> {
hub::EV_TOPICS
.iter()
.map(|t| std::borrow::Cow::Borrowed(*t))
.collect()
}
fn on_init(&self, ctx: &PluginContext) {
*self.ctx.lock().unwrap_or_else(|p| p.into_inner()) = Some(ctx.clone());
}
fn on_mail(&self, _event: &Event) {
}
}
fn now_ms() -> u64 {
SystemTime::now()
.duration_since(UNIX_EPOCH)
.map(|d| d.as_millis() as u64)
.unwrap_or(0)
}
pub type SharedApi = Arc<ApiPlugin>;