graphrt_plugin/
transport.rs1use 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
14pub const INITIALIZE_TIMEOUT: Duration = Duration::from_secs(15);
16
17pub trait Transport: Send + Sync + fmt::Debug {
19 fn next_id(&self) -> String;
21
22 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 fn initialize<'a>(&'a self, clock: &'a Arc<dyn Clock>) -> BoxFuture<'a, Result<serde_json::Value, CallError>>;
37
38 fn note_timeout(&self) {}
41
42 fn note_answer(&self) {}
44}
45
46pub(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
56pub(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
67pub(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#[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 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}