use std::collections::{HashMap, HashSet};
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::Arc;
use serde::de::DeserializeOwned;
use serde::Serialize;
use serde_json::{json, Value};
use tokio::sync::mpsc::UnboundedSender;
use crate::events::WireEvent;
use crate::{Error, Result};
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum AlertLevel {
Info,
Success,
Warn,
Error,
}
impl AlertLevel {
pub fn as_str(&self) -> &'static str {
match self {
AlertLevel::Info => "info",
AlertLevel::Success => "success",
AlertLevel::Warn => "warn",
AlertLevel::Error => "error",
}
}
}
pub struct Context {
inputs: Arc<HashMap<String, Value>>,
push: Option<UnboundedSender<Value>>,
cancel: Arc<AtomicBool>,
event: Option<WireEvent>,
flow_in: Option<HashSet<String>>,
flow_out: Option<HashSet<String>>,
skipped: HashSet<String>,
all: Vec<(String, Value)>,
emitted: Vec<(String, Value)>,
wasm: Arc<crate::wasm::WasmRegistry>,
user: Option<crate::auth::UserProfile>,
}
impl Context {
pub(crate) fn new(
inputs: Arc<HashMap<String, Value>>,
push: Option<UnboundedSender<Value>>,
cancel: Arc<AtomicBool>,
event: Option<WireEvent>,
) -> Self {
Self {
inputs,
push,
cancel,
event,
flow_in: None,
flow_out: None,
skipped: HashSet::new(),
all: Vec::new(),
emitted: Vec::new(),
wasm: Arc::new(crate::wasm::WasmRegistry::new()),
user: None,
}
}
pub(crate) fn with_wasm(mut self, wasm: Arc<crate::wasm::WasmRegistry>) -> Self {
self.wasm = wasm;
self
}
pub(crate) fn with_user(mut self, user: Option<crate::auth::UserProfile>) -> Self {
self.user = user;
self
}
pub fn event(&self) -> Option<&WireEvent> {
self.event.as_ref()
}
pub(crate) fn set_flow(&mut self, inputs: Option<&[String]>, outputs: Option<&[String]>) {
self.flow_in = inputs.map(|l| l.iter().cloned().collect());
self.flow_out = outputs.map(|l| l.iter().cloned().collect());
}
pub fn skip(&mut self, id: impl Into<String>) {
self.skipped.insert(id.into());
}
pub fn skipped(&self, id: &str) -> bool {
self.skipped.contains(id)
}
pub fn unskip(&mut self, id: impl Into<String>) {
self.skipped.remove(&id.into());
}
pub fn get<T: DeserializeOwned>(&self, id: &str) -> Result<T> {
if self.flow_in.as_ref().is_some_and(|s| !s.contains(id)) {
return Err(Error::from(format!("input `{id}` hors du flux déclaré")));
}
let v = self
.inputs
.get(id)
.ok_or_else(|| Error::from(format!("unknown input `{id}`")))?;
Ok(serde_json::from_value(v.clone())?)
}
pub fn get_f64(&self, id: &str) -> Result<f64> {
self.get(id)
}
pub fn get_str(&self, id: &str) -> Option<&str> {
if self.flow_in.as_ref().is_some_and(|s| !s.contains(id)) {
return None;
}
self.inputs.get(id).and_then(|v| v.as_str())
}
pub fn has(&self, id: &str) -> bool {
if self.flow_in.as_ref().is_some_and(|s| !s.contains(id)) {
return false;
}
self.inputs.contains_key(id)
}
pub fn set<T: Serialize>(&mut self, id: impl Into<String>, v: T) {
let id = id.into();
if self.blocked_writes(&id) {
return;
}
let patch = json!({ "value": serde_json::to_value(v).unwrap_or(Value::Null) });
self.push_update(id, patch);
}
pub fn set_prop<T: Serialize>(&mut self, id: impl Into<String>, prop: &str, v: T) {
let id = id.into();
if self.blocked_writes(&id) {
return;
}
let patch = json!({ prop: serde_json::to_value(v).unwrap_or(Value::Null) });
self.push_update(id, patch);
}
pub fn set_visible(&mut self, id: impl Into<String>, visible: bool) {
self.set_prop(id, "visible", visible);
}
pub fn append_component(
&mut self,
container_id: impl Into<String>,
c: impl crate::components::Component + 'static,
) {
let container_id = container_id.into();
let html = crate::server::render_fragment(&c);
self.send(json!({
"t": "slot",
"container": container_id,
"mode": "append",
"html": html,
}));
}
pub fn replace_children(
&mut self,
container_id: impl Into<String>,
items: Vec<Box<dyn crate::components::Component>>,
) {
let container_id = container_id.into();
let mut html = String::new();
for it in items {
html.push_str(&crate::server::render_fragment(it.as_ref()));
}
self.send(json!({
"t": "slot",
"container": container_id,
"mode": "replace",
"html": html,
}));
}
pub fn clear_container(&mut self, container_id: impl Into<String>) {
let container_id = container_id.into();
self.send(json!({
"t": "slot",
"container": container_id,
"mode": "clear",
"html": "",
}));
}
pub fn append_rows(&mut self, id: impl Into<String>, rows: Vec<Vec<serde_json::Value>>) {
let id = id.into();
self.send(json!({
"t": "patch",
"c": id,
"append_rows": rows,
}));
}
pub fn append_binary(&mut self, id: impl Into<String>, data: &[u8]) {
let id = id.into();
let b64 = crate::media::encode(data);
self.send(json!({
"t": "bin",
"c": id,
"b64": b64,
}));
}
pub fn append_f32_points(&mut self, id: impl Into<String>, points: &[f32]) {
let bytes: &[u8] = unsafe {
std::slice::from_raw_parts(
points.as_ptr() as *const u8,
std::mem::size_of_val(points),
)
};
self.append_binary(id, bytes);
}
pub fn append_series_points(
&mut self,
id: impl Into<String>,
series_index: u32,
points: &[f32],
) {
let id = id.into();
let bytes: &[u8] = unsafe {
std::slice::from_raw_parts(
points.as_ptr() as *const u8,
std::mem::size_of_val(points),
)
};
let b64 = crate::media::encode(bytes);
self.send(json!({
"t": "bin_series",
"c": id,
"s": series_index,
"b64": b64,
}));
}
pub fn append<T: Serialize>(&mut self, id: impl Into<String>, fragment: T) {
let id = id.into();
if self.blocked_writes(&id) {
return;
}
let patch = json!({ "append": serde_json::to_value(fragment).unwrap_or(Value::Null) });
self.send(json!({ "t": "update", "u": [json!({ "id": id, "p": patch })] }));
}
pub fn progress<T: Serialize>(&mut self, id: impl Into<String>, f: f64, label: T) {
let id = id.into();
if self.blocked_writes(&id) {
return;
}
let patch = json!({ "value": json!({ "progress": f, "label": label }) });
self.send(json!({ "t": "update", "u": [json!({ "id": id, "p": patch })] }));
}
pub fn alert<T: Serialize>(&mut self, level: impl Into<AlertLevel>, msg: T) {
let level = level.into();
self.send(json!({ "t": "alert", "level": level.as_str(), "m": msg }));
}
pub fn set_theme(&mut self, theme: crate::app::Theme) {
let mode_str = match theme.mode {
crate::app::ThemeMode::Dark => "dark",
crate::app::ThemeMode::Light => "light",
crate::app::ThemeMode::System => "system",
};
self.send(json!({
"t": "theme",
"mode": mode_str,
"primary": theme.primary,
"radius": theme.radius,
"font": theme.font,
}));
}
pub fn push_audio_stream(&mut self, id: impl Into<String>, chunk: &crate::media::AudioChunk) {
let id = id.into();
let b64_data = crate::media::encode(&chunk.data);
self.send(json!({
"t": "audio_stream",
"id": id,
"format": chunk.format,
"sample_rate": chunk.sample_rate,
"channels": chunk.channels,
"data": b64_data,
}));
}
pub fn set_overlays<T: Serialize>(&mut self, id: impl Into<String>, overlays: &T) {
let id = id.into();
if let Ok(v) = serde_json::to_value(overlays) {
self.send(json!({
"t": "set_overlays",
"id": id,
"overlays": v,
}));
}
}
pub fn call_wasm(&self, plugin_id: &str, method: &str, input: &Value) -> Result<Value> {
let plugin = self.wasm.get(plugin_id).ok_or_else(|| {
Error::from(format!("plugin WebAssembly `{plugin_id}` introuvable dans le registre"))
})?;
plugin.call(method, input)
}
pub fn call_wasm_bytes(&self, plugin_id: &str, method: &str, input: &[u8]) -> Result<Vec<u8>> {
let plugin = self.wasm.get(plugin_id).ok_or_else(|| {
Error::from(format!("plugin WebAssembly `{plugin_id}` introuvable dans le registre"))
})?;
plugin.invoke_bytes(method, input)
}
pub fn user(&self) -> Option<&crate::auth::UserProfile> {
self.user.as_ref()
}
pub fn user_id(&self) -> Option<&str> {
self.user.as_ref().map(|u| u.id.as_str())
}
pub fn has_role(&self, role: &str) -> bool {
match &self.user {
Some(u) => u.has_role(role),
None => true, }
}
pub fn cancelled(&self) -> bool {
self.cancel.load(Ordering::SeqCst)
}
pub fn emit<T: Serialize>(&mut self, name: impl Into<String>, data: T) {
self.emitted.push((
name.into(),
serde_json::to_value(data).unwrap_or(Value::Null),
));
}
fn push_update(&mut self, id: String, patch: Value) {
self.all.push((id.clone(), patch.clone()));
self.send(json!({ "t": "update", "u": [json!({ "id": id, "p": patch })] }));
}
fn blocked_writes(&self, id: &str) -> bool {
self.skipped.contains(id) || self.flow_out.as_ref().is_some_and(|s| !s.contains(id))
}
fn send(&self, msg: Value) {
if let Some(tx) = &self.push {
let _ = tx.send(msg);
}
}
pub(crate) fn take_all(&mut self) -> Vec<(String, Value)> {
std::mem::take(&mut self.all)
}
pub(crate) fn take_emitted(&mut self) -> Vec<(String, Value)> {
std::mem::take(&mut self.emitted)
}
}