dfhack_remote/
channel.rs

1//! Internal module describing the exchange flow
2//!
3//! Implements the flow of sending and receiving messages.
4//! This includes the custom workflow of binding RPC methods
5//! before being able to use them.
6
7use std::collections::HashMap;
8
9use crate::{
10    message::{self, Receive, Send},
11    Error,
12};
13
14#[derive(PartialEq, Eq, Hash, Clone)]
15struct Method {
16    pub plugin: String,
17    pub name: String,
18}
19
20impl Method {
21    fn new(plugin: String, name: String) -> Self {
22        Method { plugin, name }
23    }
24}
25
26/// Communication channel with DFHack.
27///
28/// Stores the existing bindings and keep an open socket.
29pub struct Channel {
30    stream: std::net::TcpStream,
31    bindings: HashMap<Method, i16>,
32}
33
34const MAGIC_QUERY: &str = "DFHack?\n";
35const MAGIC_REPLY: &str = "DFHack!\n";
36const VERSION: i32 = 1;
37
38const BIND_METHOD_ID: i16 = 0;
39const RUN_COMMAND_ID: i16 = 1;
40
41impl dfhack_proto::Channel for Channel {
42    type TError = crate::Error;
43
44    fn request<TRequest, TReply>(
45        &mut self,
46        plugin: std::string::String,
47        name: std::string::String,
48        request: TRequest,
49    ) -> crate::Result<TReply>
50    where
51        TRequest: protobuf::MessageFull,
52        TReply: protobuf::MessageFull,
53    {
54        let method = Method::new(plugin, name);
55
56        // did not manage to use the entry api due to borrow checker
57        let maybe_id = self.bindings.get(&method);
58
59        let id = match maybe_id {
60            Some(id) => *id,
61            None => {
62                let id = self.bind_method::<TRequest, TReply>(&method)?;
63                self.bindings.insert(method, id);
64                id
65            }
66        };
67
68        self.request_raw(id, request)
69    }
70}
71
72impl Channel {
73    pub(crate) fn connect() -> crate::Result<Self> {
74        let port = match std::env::var("DFHACK_PORT") {
75            Ok(p) => p,
76            Err(_) => "5000".to_string(),
77        };
78        Self::connect_to(&format!("127.0.0.1:{}", port))
79    }
80
81    pub(crate) fn connect_to(address: &str) -> crate::Result<Channel> {
82        log::info!("Connecting to {}", address);
83        let mut client = Channel {
84            stream: std::net::TcpStream::connect(address)?,
85            bindings: HashMap::new(),
86        };
87
88        client.bindings.insert(
89            Method::new("".to_string(), "BindMethod".to_string()),
90            BIND_METHOD_ID,
91        );
92        client.bindings.insert(
93            Method::new("".to_string(), "RunCommand".to_string()),
94            RUN_COMMAND_ID,
95        );
96
97        let handshake_request = message::Handshake::new(MAGIC_QUERY.to_string(), VERSION);
98        handshake_request.send(&mut client.stream)?;
99        let handshake_reply = message::Handshake::receive(&mut client.stream)?;
100
101        if handshake_reply.magic != MAGIC_REPLY {
102            return Err(Error::ProtocolError(format!(
103                "Unexpected magic {}",
104                handshake_reply.magic
105            )));
106        }
107
108        if handshake_reply.version != VERSION {
109            return Err(Error::ProtocolError(format!(
110                "Unexpected magic version {}",
111                handshake_reply.version
112            )));
113        }
114
115        Ok(client)
116    }
117
118    fn request_raw<TIN: protobuf::MessageFull, TOUT: protobuf::MessageFull>(
119        &mut self,
120        id: i16,
121        message: TIN,
122    ) -> crate::Result<TOUT> {
123        let request = message::Request::new(id, message);
124        request.send(&mut self.stream)?;
125
126        loop {
127            let reply: message::Reply<TOUT> = message::Reply::receive(&mut self.stream)?;
128            match reply {
129                message::Reply::Text(text) => {
130                    for fragment in text.fragments {
131                        println!("{}", fragment.text());
132                    }
133                }
134                message::Reply::Result(result) => return Ok(result),
135                message::Reply::Fail(command_result) => {
136                    return Err(Error::RpcError(command_result))
137                }
138            }
139        }
140    }
141
142    fn bind_method<TIN: protobuf::MessageFull, TOUT: protobuf::MessageFull>(
143        &mut self,
144        method: &Method,
145    ) -> crate::Result<i16> {
146        let input_descriptor = TIN::descriptor();
147        let output_descriptor = TOUT::descriptor();
148        let input_msg = input_descriptor.full_name();
149        let output_msg = output_descriptor.full_name();
150        self.bind_method_by_name(&method.plugin, &method.name, input_msg, output_msg)
151    }
152
153    fn bind_method_by_name(
154        &mut self,
155        plugin: &str,
156        method: &str,
157        input_msg: &str,
158        output_msg: &str,
159    ) -> crate::Result<i16> {
160        log::debug!("Binding the method {}:{}", plugin, method);
161        let mut request = crate::CoreBindRequest::new();
162        request.set_method(method.to_owned());
163        request.set_input_msg(input_msg.to_string());
164        request.set_output_msg(output_msg.to_string());
165        request.set_plugin(plugin.to_owned());
166        let reply: crate::CoreBindReply = match self.request_raw(BIND_METHOD_ID, request) {
167            Ok(reply) => reply,
168            Err(_) => {
169                log::error!("Error attempting to bind {}", method);
170                return Err(Error::FailedToBind(format!(
171                    "{}::{} ({}->{})",
172                    plugin, method, input_msg, output_msg,
173                )));
174            }
175        };
176        let id = reply.assigned_id() as i16;
177        log::debug!("{}:{} bound to {}", plugin, method, id);
178        Ok(id)
179    }
180}
181
182impl Drop for Channel {
183    fn drop(&mut self) {
184        let quit = message::Quit::new();
185        let res = quit.send(&mut self.stream);
186        if let Err(failure) = res {
187            println!(
188                "Warning: failed to close the connection to dfhack-remote: {}",
189                failure
190            );
191        }
192    }
193}
194
195#[cfg(test)]
196mod tests {
197    #[cfg(feature = "test-with-df")]
198    mod withdf {
199        use crate::Error;
200
201        #[test]
202        fn bind() {
203            use crate::channel::Channel;
204            let mut channel = Channel::connect().unwrap();
205
206            channel
207                .bind_method_by_name(
208                    "",
209                    "GetVersion",
210                    "dfproto.EmptyMessage",
211                    "dfproto.StringMessage",
212                )
213                .unwrap();
214        }
215
216        #[test]
217        fn bad_bind() {
218            use crate::channel::Channel;
219            let mut channel = Channel::connect().unwrap();
220
221            let err = channel
222                .bind_method_by_name(
223                    "",
224                    "GetVersion",
225                    "dfproto.EmptyMessage",
226                    "dfproto.EmptyMessage",
227                )
228                .unwrap_err();
229            assert!(std::matches!(err, Error::FailedToBind(_)));
230
231            let err = channel
232                .bind_method_by_name(
233                    "dorf",
234                    "GetVersion",
235                    "dfproto.StringMessage",
236                    "dfproto.EmptyMessage",
237                )
238                .unwrap_err();
239            assert!(std::matches!(err, Error::FailedToBind(_)));
240        }
241
242        #[test]
243        #[cfg(feature = "reflection")]
244        fn bind_all() {
245            use dfhack_proto::{reflection::StubReflection, stubs::Stubs};
246
247            use crate::channel::Channel;
248            let mut channel = Channel::connect().unwrap();
249            let methods = Stubs::<Channel>::list_methods();
250
251            for method in &methods {
252                channel
253                    .bind_method_by_name(
254                        &method.plugin_name,
255                        &method.name,
256                        &method.input_type,
257                        &method.output_type,
258                    )
259                    .unwrap();
260            }
261        }
262    }
263}