actrpc_core/interception/
phase.rs1use crate::{
2 error::ProtocolError,
3 json_rpc::{JsonRpcMessage, JsonRpcSingleMessage},
4};
5use serde::{Deserialize, Serialize};
6use std::hash::Hash;
7use strum::Display;
8
9#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize, Display)]
10#[serde(rename_all = "lowercase")]
11pub enum InterceptionPhase {
12 Outbound,
13 Inbound,
14}
15
16impl InterceptionPhase {
17 pub fn is_outbound(self) -> bool {
18 matches!(self, Self::Outbound)
19 }
20
21 pub fn is_inbound(self) -> bool {
22 matches!(self, Self::Inbound)
23 }
24}
25
26impl JsonRpcMessage {
27 pub fn phase(&self) -> Result<InterceptionPhase, ProtocolError> {
28 match self {
29 JsonRpcMessage::Single(JsonRpcSingleMessage::Response(_)) => {
30 Ok(InterceptionPhase::Inbound)
31 }
32
33 JsonRpcMessage::Single(
34 JsonRpcSingleMessage::Request(_) | JsonRpcSingleMessage::Notification(_),
35 ) => Ok(InterceptionPhase::Outbound),
36
37 JsonRpcMessage::Batch(batch) => {
38 let all_inbound = batch
39 .0
40 .iter()
41 .all(|msg| matches!(msg, JsonRpcSingleMessage::Response(_)));
42
43 let all_outbound = batch.0.iter().all(|msg| {
44 matches!(
45 msg,
46 JsonRpcSingleMessage::Request(_) | JsonRpcSingleMessage::Notification(_)
47 )
48 });
49
50 match (all_inbound, all_outbound) {
51 (true, false) => Ok(InterceptionPhase::Inbound),
52 (false, true) => Ok(InterceptionPhase::Outbound),
53 _ => Err(ProtocolError::MixedBatch),
54 }
55 }
56 }
57 }
58}