Skip to main content

graphrt_plugin/
transport.rs

1//! Transports carrying the plugin protocol.
2
3use std::fmt;
4use std::sync::Arc;
5use std::time::Duration;
6
7use futures::future::BoxFuture;
8use graphrt_core::node::Clock;
9
10use crate::conn::{Connection, NotifySink};
11use crate::error::CallError;
12use crate::manifest::PROTOCOL_VERSION;
13
14/// How long the `initialize` handshake may take.
15pub const INITIALIZE_TIMEOUT: Duration = Duration::from_secs(15);
16
17/// A channel to one plugin.
18pub trait Transport: Send + Sync + fmt::Debug {
19    /// A fresh request id.
20    fn next_id(&self) -> String;
21
22    /// Send request `id` and wait for the response. Notifications carrying
23    /// `request_id == id` are passed to `sink`. Dropping the future abandons the
24    /// request (and cancels it when `cancel_on_drop` is set).
25    fn call<'a>(
26        &'a self,
27        id: String,
28        method: &'a str,
29        params: serde_json::Value,
30        sink: Option<NotifySink>,
31        cancel_on_drop: bool,
32        clock: &'a Arc<dyn Clock>,
33    ) -> BoxFuture<'a, Result<serde_json::Value, CallError>>;
34
35    /// Run the `initialize` handshake (starting the plugin if needed) and return its result.
36    fn initialize<'a>(&'a self, clock: &'a Arc<dyn Clock>) -> BoxFuture<'a, Result<serde_json::Value, CallError>>;
37
38    /// A request was abandoned after its timeout. Transports supervising a process
39    /// use this to restart a plugin that stopped answering. Default: no-op.
40    fn note_timeout(&self) {}
41
42    /// A request completed (successfully or with a plugin error). Default: no-op.
43    fn note_answer(&self) {}
44}
45
46/// Parameters of `initialize`. `max_message_bytes` tells the plugin how large a
47/// line the host may send, so SDKs size their read buffers to match.
48pub(crate) fn initialize_params(max_message_bytes: usize) -> serde_json::Value {
49    serde_json::json!({
50        "protocol_version": PROTOCOL_VERSION,
51        "host": {"name": "graphrt", "version": env!("CARGO_PKG_VERSION")},
52        "max_message_bytes": max_message_bytes,
53    })
54}
55
56/// Validate an `initialize` result.
57pub(crate) fn check_initialize(result: &serde_json::Value) -> Result<(), CallError> {
58    match result.get("protocol_version").and_then(serde_json::Value::as_u64) {
59        None => Ok(()),
60        Some(v) if v == u64::from(PROTOCOL_VERSION) => Ok(()),
61        Some(v) => {
62            Err(CallError::Protocol(format!("plugin speaks protocol version {v}, this host speaks {PROTOCOL_VERSION}")))
63        }
64    }
65}
66
67/// Race `fut` against `timeout` on `clock` (no timeout when the clock has no timers).
68pub(crate) async fn with_timeout<T>(
69    clock: &Arc<dyn Clock>,
70    timeout: Duration,
71    fut: impl std::future::Future<Output = Result<T, CallError>>,
72) -> Result<T, CallError> {
73    if !clock.supports_timers() {
74        return fut.await;
75    }
76    let sleep = clock.sleep(timeout);
77    futures::pin_mut!(fut);
78    match futures::future::select(fut, sleep).await {
79        futures::future::Either::Left((result, _)) => result,
80        futures::future::Either::Right(((), _)) => {
81            Err(CallError::Timeout(u64::try_from(timeout.as_millis()).unwrap_or(u64::MAX)))
82        }
83    }
84}
85
86/// A transport over an already-connected byte stream, e.g. an in-process
87/// plugin or a socket. The connection is initialized on first use.
88#[derive(Debug)]
89pub struct IoTransport {
90    conn: Connection,
91    max_message_bytes: usize,
92    initialized: tokio::sync::OnceCell<serde_json::Value>,
93}
94
95impl IoTransport {
96    /// Wrap a reader/writer pair. Must be called inside a tokio runtime.
97    pub fn new<R, W>(reader: R, writer: W, max_message_bytes: usize) -> Self
98    where
99        R: tokio::io::AsyncRead + Send + Unpin + 'static,
100        W: tokio::io::AsyncWrite + Send + Unpin + 'static,
101    {
102        Self {
103            conn: Connection::new(reader, writer, max_message_bytes),
104            max_message_bytes,
105            initialized: tokio::sync::OnceCell::new(),
106        }
107    }
108
109    async fn ensure_initialized(&self, clock: &Arc<dyn Clock>) -> Result<serde_json::Value, CallError> {
110        let result = self
111            .initialized
112            .get_or_try_init(|| async {
113                let id = self.conn.next_id();
114                let fut = self.conn.call(id, "initialize", initialize_params(self.max_message_bytes), None, false);
115                let result = with_timeout(clock, INITIALIZE_TIMEOUT, fut).await?;
116                check_initialize(&result)?;
117                Ok::<_, CallError>(result)
118            })
119            .await?;
120        Ok(result.clone())
121    }
122}
123
124impl Transport for IoTransport {
125    fn next_id(&self) -> String {
126        self.conn.next_id()
127    }
128
129    fn call<'a>(
130        &'a self,
131        id: String,
132        method: &'a str,
133        params: serde_json::Value,
134        sink: Option<NotifySink>,
135        cancel_on_drop: bool,
136        clock: &'a Arc<dyn Clock>,
137    ) -> BoxFuture<'a, Result<serde_json::Value, CallError>> {
138        Box::pin(async move {
139            self.ensure_initialized(clock).await?;
140            self.conn.call(id, method, params, sink, cancel_on_drop).await
141        })
142    }
143
144    fn initialize<'a>(&'a self, clock: &'a Arc<dyn Clock>) -> BoxFuture<'a, Result<serde_json::Value, CallError>> {
145        Box::pin(self.ensure_initialized(clock))
146    }
147}