Skip to main content

crabtalk_core/protocol/message/
convert.rs

1//! Conversions between protocol message types.
2
3use crate::protocol::proto::{
4    AgentEventMsg, ClientMessage, ReplyToAsk, SendMsg, SendResponse, ServerMessage, StreamEvent,
5    StreamMsg, client_message, server_message, stream_event,
6};
7
8// ── ClientMessage constructors ───────────────────────────────────
9
10impl From<SendMsg> for ClientMessage {
11    fn from(msg: SendMsg) -> Self {
12        Self {
13            msg: Some(client_message::Msg::Send(msg)),
14        }
15    }
16}
17
18impl From<StreamMsg> for ClientMessage {
19    fn from(msg: StreamMsg) -> Self {
20        Self {
21            msg: Some(client_message::Msg::Stream(msg)),
22        }
23    }
24}
25
26impl From<ReplyToAsk> for ClientMessage {
27    fn from(msg: ReplyToAsk) -> Self {
28        Self {
29            msg: Some(client_message::Msg::ReplyToAsk(msg)),
30        }
31    }
32}
33
34// ── ServerMessage constructors ───────────────────────────────────
35
36impl From<SendResponse> for ServerMessage {
37    fn from(r: SendResponse) -> Self {
38        Self {
39            msg: Some(server_message::Msg::Response(r)),
40        }
41    }
42}
43
44impl From<StreamEvent> for ServerMessage {
45    fn from(e: StreamEvent) -> Self {
46        Self {
47            msg: Some(server_message::Msg::Stream(e)),
48        }
49    }
50}
51
52impl From<AgentEventMsg> for ServerMessage {
53    fn from(e: AgentEventMsg) -> Self {
54        Self {
55            msg: Some(server_message::Msg::AgentEvent(e)),
56        }
57    }
58}
59
60// ── TryFrom<ServerMessage> ───────────────────────────────────────
61
62fn error_or_unexpected(msg: ServerMessage) -> anyhow::Error {
63    match msg.msg {
64        Some(server_message::Msg::Error(e)) => {
65            anyhow::anyhow!("server error ({}): {}", e.code, e.message)
66        }
67        other => anyhow::anyhow!("unexpected response: {other:?}"),
68    }
69}
70
71impl TryFrom<ServerMessage> for SendResponse {
72    type Error = anyhow::Error;
73    fn try_from(msg: ServerMessage) -> anyhow::Result<Self> {
74        match msg.msg {
75            Some(server_message::Msg::Response(r)) => Ok(r),
76            _ => Err(error_or_unexpected(msg)),
77        }
78    }
79}
80
81impl TryFrom<ServerMessage> for stream_event::Event {
82    type Error = anyhow::Error;
83    fn try_from(msg: ServerMessage) -> anyhow::Result<Self> {
84        match msg.msg {
85            Some(server_message::Msg::Stream(e)) => {
86                e.event.ok_or_else(|| anyhow::anyhow!("empty stream event"))
87            }
88            _ => Err(error_or_unexpected(msg)),
89        }
90    }
91}