channel_plugin 0.2.0

The fastest, most secure and extendable digital workforce platform
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
//! Async runtime that wires **stdin / stdout** JSON‑RPC traffic to a user‑supplied
//! `PluginHandler` implementation.
//!
//! ### Key design goals
//! * **Zero dependencies** beyond `tokio`, `serde_json`, `async‑trait`
//! * Works with the existing `jsonrpc` and `message` modules we defined earlier
//! * Handles:
//!   * Requests → method dispatch → JSON‑RPC response
//!   * Notifications (no `id`) → fire‑and‑forget
//!   * Basic error handling (invalid JSON‑RPC, unknown method, panics)
//!
//! Usage:
//! ```ignore
//! use channel_plugin::PluginRuntime;
//! #[tokio::main]
//! async fn main() -> anyhow::Result<()> {
//!     let my_plugin = MyPlugin::default();
//!     let mut runtime = PluginRuntime::new(my_plugin);
//!     runtime.run().await;
//! }
//! ```

use std::{panic, time::{Instant}};

use async_trait::async_trait;
use anyhow::Result;
use dashmap::DashMap;
use tracing::{dispatcher, error, level_filters::LevelFilter, Dispatch};
use tracing_appender::rolling::daily;
use tracing_subscriber::{fmt, Registry};
use crate::{jsonrpc::{Id, Message, Request, Response}, plugin_actor::Method};
use tracing_subscriber::prelude::__tracing_subscriber_SubscriberExt;
use tracing_subscriber::Layer;
use serde_json::{json, Value};
use tokio::{io::{self, AsyncBufReadExt, AsyncWriteExt, BufReader, BufWriter}, sync::{mpsc::{self, UnboundedSender}}, time::sleep};
use crate::message::*;


// -----------------------------------------------------------------------------
// PluginHandler trait – implement this in your plugin code
// -----------------------------------------------------------------------------

///  A tiny trait that just gives access to the store.
///
///  Every plugin struct that wants to use the default `set_config` /
///  `set_secrets` impls only has to return a reference to its map.
pub trait HasStore {
    fn config_store(&self) -> &DashMap<String, String>;
    fn secret_store(&self) -> &DashMap<String, String>;
}

pub const VERSION: &str = "0.1.0";

#[async_trait]
pub trait PluginHandler: HasStore + Send + Sync + Clone + 'static {
    /// Initialise the plugin and start any underlying services
    async fn init(&mut self, params: InitParams) -> InitResult;
    async fn start(&mut self, params: InitParams) -> InitResult {
        let res = self.init_from_params(&params).await;
        if !res.success {
            return res;
        }
        let result = self.init(params).await;
        result
    }
    /// Drain the plugin
    async fn drain(&mut self) -> DrainResult;
    async fn wait_until_drained(&self, params: WaitUntilDrainedParams) -> WaitUntilDrainedResult {
        let deadline = Instant::now() + std::time::Duration::from_millis(params.timeout_ms);

        loop {
            let state = self.state().await.state;

            if state == ChannelState::STOPPED {
                return WaitUntilDrainedResult{stopped: true, error: false};
            }

            if Instant::now() >= deadline {
                return WaitUntilDrainedResult{stopped: false, error: true};
            }

            sleep(std::time::Duration::from_millis(100)).await;
        }
    }
    /// Stop the plugin
    async fn stop(&mut self) -> StopResult;
    /// When a message needs to be send
    async fn send_message(&mut self, params: MessageOutParams) -> MessageOutResult;
    /// When a message comes in
    async fn receive_message(&mut self) -> MessageInResult;
    /// Check the health of the plugin
    async fn health(&self) -> HealthResult {
        HealthResult { healthy: true, reason: None }
    }
    async fn version(&self) -> VersionResult{
        VersionResult{version: VERSION.to_string()}
    }
    /// Request the current status
    async fn state(&self) -> StateResult;
    /// Set the configuration
    async fn set_config(&mut self, p: SetConfigParams) -> SetConfigResult {
        // 1. persist the keys we just received
        for (k, v) in p.config {
            self.config_store().insert(k, v);
        }
        // 2. gather the list of required keys
        let required: std::collections::HashSet<_> =
            self.list_config_keys().required_keys.into_iter().map(|(k, _)| k).collect();

         // 3. check which of them are still missing
        let missing: Vec<_> = required
            .into_iter()
            .filter(|k| !self.config_store().contains_key(k))
            .collect();

        if missing.is_empty() {
            SetConfigResult { success: true, error: None }
        } else {
            let msg = format!("missing required config keys: {}", missing.join(", "));
            SetConfigResult { success: false, error: Some(msg) }
        }
    }
    /// Set the secrets
    async fn set_secrets(&mut self, p: SetSecretsParams) -> SetSecretsResult {
        for (k, v) in p.secrets {
            self.secret_store().insert(k, v);
        }
        let required: std::collections::HashSet<_> =
        self.list_secret_keys().required_keys.into_iter().map(|(k, _)| k).collect();

        let missing: Vec<_> = required
            .into_iter()
            .filter(|k| !self.secret_store().contains_key(k))
            .collect();

        if missing.is_empty() {
            SetSecretsResult { success: true, error: None }
        } else {
            let msg = format!("missing required secret keys: {}", missing.join(", "));
            SetSecretsResult { success: false, error: Some(msg) }
        }
    }

    /// Gets a config value from the config store
    fn get_config(&self, key: &str) -> Option<String> {
        self.config_store()            // &DashMap<String, String>
        .get(key)                  // Option< Ref<'_, String, String> >
        .map(|guard| guard.value().clone())
    }
    /// Gets a secret from the secret store
    fn get_secret(&self, key: &str) -> Option<String> {
        self.secret_store()            // &DashMap<String, String>
        .get(key)                  // Option< Ref<'_, String, String> >
        .map(|guard| guard.value().clone())
    }
    /// Returns the plugin name, e.g., "telegram", "ws", etc.
    fn name(&self) -> NameResult;
    /// List of expected config keys (like `API_KEY`, `WS_PORT`, etc.)
    fn list_config_keys(&self) -> ListKeysResult;
    /// List of expected secret keys
    fn list_secret_keys(&self) -> ListKeysResult;
    /// Declares plugin capabilities (sending, receiving, text, etc.)
    fn capabilities(&self) -> CapabilitiesResult;

    /// initialise logging, config and secrets so plugins don't have to
    async fn init_from_params(&mut self, params: &InitParams) -> InitResult{
        static LOG_INIT: std::sync::Once = std::sync::Once::new();
        LOG_INIT.call_once(|| {
            let result = panic::catch_unwind(|| {
                // ── level ───────────────────────────────────────────────
                let level = match params.log_level {
                    LogLevel::Trace    => LevelFilter::TRACE,
                    LogLevel::Debug    => LevelFilter::DEBUG,
                    LogLevel::Info     => LevelFilter::INFO,
                    LogLevel::Warn     => LevelFilter::WARN,
                    LogLevel::Error    => LevelFilter::ERROR,
                    LogLevel::Critical => LevelFilter::ERROR,
                };

                // ── optional file layer  ────────────────────────────────
                let subscriber_dispatch: Dispatch = if let Some(dir) = &params.log_dir {
                    std::fs::create_dir_all(dir).ok();               // ignore error, best-effort
                    let file_app = daily(dir, "plugin.log");

                    Dispatch::new(
                        Registry::default()
                            .with(
                                fmt::layer()
                                    .with_ansi(false)
                                    .with_target(false)
                                    .with_writer(file_app)
                                    .with_filter(level),
                            ),
                    )
                } else {
                    panic!("❌ Logging requires a `log_dir`. None was provided.");
                };

                // ── install ─────────────────────────────────────────────
                dispatcher::set_global_default(subscriber_dispatch)
                    .expect("failed to install tracing subscriber");

                if cfg!(debug_assertions) && std::io::IsTerminal::is_terminal(&std::io::stdout()) {
                    tracing::warn!(
                        "‼️  A tracing layer is writing to STDOUT – \
                        this WILL break the JSON-RPC protocol."
                    );
                }
            });
            if result.is_err() {
                eprintln!("❌ Logging setup failed");
            }
        });

        let res = self
            .set_config(SetConfigParams { config: params.config.clone() })
            .await;
        if !res.success {
            return InitResult{ success: false, error: res.error }
        }

        let res = self.set_secrets(SetSecretsParams{secrets:params.secrets.clone()}).await;
        if !res.success {
            return InitResult{ success: false, error: res.error }
        }

        InitResult{ success: true, error: None }
    }
}


// -----------------------------------------------------------------------------
// Runtime function – spawn read / write loops
// -----------------------------------------------------------------------------

/// Runs the JSON‑RPC stdin/stdout loop until EOF or fatal error.
pub async fn run<P: PluginHandler>(mut plugin: P) -> Result<()> {
    let (tx, mut rx) = mpsc::unbounded_channel::<String>();
    tokio::spawn(async move {
        let mut w = BufWriter::new(io::stdout());
        while let Some(line) = rx.recv().await {
            if let Err(e) = w.write_all(line.as_bytes()).await {
                error!("stdout write error: {e}");
                break;              // abort writer task → plugin will exit
            }
            // avoid tight loop when channel is empty
            if w.flush().await.is_err() {
                error!("stdout flush error");
                break;
            }
        }
    });

    // ── 2. spawn poller that turns `receive_message()` into `messageIn` notif
    let mut plugin_clone = plugin.clone();

    tokio::spawn(async move {
        loop {
            //if plugin_clone.state().await.state == ChannelState::RUNNING {
                let result = plugin_clone.receive_message().await;
                match serde_json::to_value(&result) {
                    Ok(v) => {
                        let notif = Request::notification("messageIn", Some(v));
                        let mut w = BufWriter::new(io::stdout());
                        let msg = format!("{}\n", serde_json::to_string(&notif).unwrap());
                        if let Err(e) = w.write_all(msg.as_bytes()).await {
                            error!("stdout write error: {e}");
                        }
                        if w.flush().await.is_err() {
                            error!("stdout flush error");
                        }
                    }
                    Err(e) => {
                        error!("serde_json error serialising MessageInResult: {e}");
                        break;
                    }
                }
           // } else {
           //     tokio::time::sleep(Duration::from_millis(1000)).await;
           // }
        }
    });
    // ── 3. read stdin, dispatch requests, send responses via the same tx ─────
    let mut reader = BufReader::new(io::stdin());
    let mut line   = String::new();

    while reader.read_line(&mut line).await? != 0 {
        trim_newlines(&mut line);
        if line.is_empty() { continue; }

        match serde_json::from_str::<Message>(&line) {
            Ok(Message::Request(req)) => {
                handle_request(&mut plugin, req, &tx.clone()).await
            }
            Ok(_) => { /* ignore stray Response/Notif from stdin */ }
            Err(e) => {
                let err = Response::fail(Id::Null, -32700, "Parse error", Some(json!(e.to_string())));
                let _  = tx.send(format!("{}\n", serde_json::to_string(&err).unwrap()));
            }
        }
        line.clear();
    }

    Ok(())
}

fn trim_newlines(s: &mut String) {
    while matches!(s.chars().last(), Some('\n' | '\r')) { s.pop(); }
}

async fn handle_request<P>(
    plugin: &mut P,
    req: Request,
    tx: &UnboundedSender<String>,
) 
where
    P: PluginHandler,
{
    /// Helper that serialises a `Response` and sends it to the writer queue.
    fn enqueue(tx: &UnboundedSender<String>, resp: Response) {
        let _ = tx.send(format!("{}\n", serde_json::to_string(&resp).unwrap()));
    }


    match req.method.parse::<Method>() {
        Ok(Method::Init) => {
            if let Some(v) = req.params {
                if let Ok(p) = serde_json::from_value::<InitParams>(v) { 
                    if let Some(id) = req.id {
                        enqueue(tx, Response::success(id, json!(plugin.init(p).await)));
                    }
                }
            }
        }
        Ok(Method::Start) => {
            if let Some(v) = req.params {
                if let Ok(p) = serde_json::from_value::<InitParams>(v) { 
                    if let Some(id) = req.id {
                        enqueue(tx, Response::success(id, json!(plugin.start(p).await)));
                    }
                }
            }
        }
        Ok(Method::Drain) => {
            if let Some(id) = req.id { 
                 enqueue(tx, Response::success(id, json!(plugin.drain().await)));
            }
        }
        Ok(Method::Stop) => {
            if let Some(id) = req.id { 
                 enqueue(tx, Response::success(id, json!(plugin.stop().await)));
            }
        }
        Ok(Method::MessageOut) => {
            match serde_json::from_value::<MessageOutParams>(req.params.unwrap_or(Value::Null)) {
                Ok(p) => {
                    let result = plugin.send_message(p).await;
                    if let Some(id) = req.id {
                        enqueue(tx, Response::success(id, json!(result)));
                    }
                }
                Err(e) => {
                    if let Some(id) = req.id {
                        enqueue(tx,
                            Response::fail(id, -32602, "Invalid params", Some(json!(e.to_string())))
                        );
                    }
                }
            }
        }
        Ok(Method::Name) => {
            if let Some(id) = req.id {
               enqueue(tx, Response::success(id, json!(plugin.name())));
            }
        }
        Ok(Method::Health) => {
            if let Some(id) = req.id {
               enqueue(tx, Response::success(id, json!(plugin.health().await)));
            }
        }
        Ok(Method::State) => {
            if let Some(id) = req.id {
                enqueue(tx, Response::success(id, json!(plugin.state().await)));
            }
        }
        Ok(Method::Capabilities) => {
            if let Some(id) = req.id {
                enqueue(tx, Response::success(id, json!(plugin.capabilities())));
            }
        }
        Ok(Method::ListConfigKeys) => {
            if let Some(id) = req.id {
                enqueue(tx, Response::success(id, json!(plugin.list_config_keys())));
            }
        }
        Ok(Method::ListSecretKeys) => {
            if let Some(id) = req.id {
                enqueue(tx, Response::success(id, json!(plugin.list_secret_keys())));
            }
        }
        Ok(Method::WaitUntilDrained) => {
            if let Some(v) = req.params {
                if let Some(id) = req.id {
                    if let Ok(p) = serde_json::from_value::<WaitUntilDrainedParams>(v) {
                        enqueue(tx, Response::success(id, json!(plugin.wait_until_drained(p).await))); 
                    }
                }
            }
        }
        Ok(Method::SetConfig) => {
            if let Some(v) = req.params {
                if let Ok(p) = serde_json::from_value::<SetConfigParams>(v) { 
                    if let Some(id) = req.id {
                        enqueue(tx, Response::success(id, json!(plugin.set_config(p).await)));
                    }
                }
            }
        }
        Ok(Method::SetSecrets) => {
            if let Some(v) = req.params {
                if let Ok(p) = serde_json::from_value::<SetSecretsParams>(v) { 
                    if let Some(id) = req.id {
                        enqueue(tx, Response::success(id, json!(plugin.set_secrets(p).await)));
                    }
                }
            }
        }
        method => {
            error!("Failed to implement method {:?} in handle_request",method);
            if let Some(id) = req.id {
               enqueue(tx, Response::fail(id, -32601, "Method not found", None));
            }
        }
    }
}