Skip to main content

agent_client_protocol/jsonrpc/
raw_id.rs

1//! The protocol-version-neutral JSON-RPC ID used by the raw message layer.
2
3use std::fmt;
4
5use serde::{Deserialize, Serialize};
6
7use crate::v1::schema as v1;
8#[cfg(feature = "unstable_protocol_v2")]
9use crate::v2::schema as v2;
10
11/// A JSON-RPC `id` exactly as it appears on the wire: an integer, a string or
12/// `null`.
13///
14/// This is the ID of [`RawJsonRpcMessage`](crate::RawJsonRpcMessage) and its
15/// requests and responses, whichever ACP version the connection speaks. The
16/// SDK's request handles return it from `raw_id()`; their `id()` returns the
17/// request ID type of their [`Protocol`](crate::Protocol) version. It keeps the wire form: `1`
18/// and `"1"` are different IDs, and integers are kept exactly across the
19/// whole 64-bit signed range, which is the range every ACP schema version
20/// accepts. Other numbers are not valid IDs.
21///
22/// `null` is allowed because JSON-RPC allows it, and protocol v1 accepts it
23/// on requests. Protocol v2 does not; the SDK rejects a v2 request with a
24/// `null` ID before dispatch. Error responses to messages whose ID cannot be
25/// read also carry `null`.
26///
27/// It converts losslessly to and from
28/// [`v1::schema::RequestId`](crate::v1::schema::RequestId), and from
29/// `v2::schema::RequestId`. Converting to `v2::schema::RequestId` fails only
30/// for `null`:
31///
32/// ```
33/// use agent_client_protocol::{RawJsonRpcId, v1::schema};
34///
35/// let id = RawJsonRpcId::from(schema::RequestId::Number(7));
36/// assert_eq!(id, RawJsonRpcId::Number(7));
37/// assert_eq!(schema::RequestId::from(id), schema::RequestId::Number(7));
38/// assert_eq!(serde_json::to_string(&RawJsonRpcId::from("7".to_string())).unwrap(), r#""7""#);
39/// ```
40#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
41#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
42#[serde(untagged)]
43pub enum RawJsonRpcId {
44    /// The JSON-RPC `null` ID.
45    Null,
46    /// An integer ID.
47    Number(i64),
48    /// A string ID.
49    Str(String),
50}
51
52impl fmt::Display for RawJsonRpcId {
53    /// Integers and strings are written without quotes, and `null` as `null`,
54    /// as [`v1::schema::RequestId`](v1::RequestId) does. Use `serde_json` for the wire form.
55    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
56        match self {
57            Self::Null => f.write_str("null"),
58            Self::Number(id) => write!(f, "{id}"),
59            Self::Str(id) => f.write_str(id),
60        }
61    }
62}
63
64impl From<i64> for RawJsonRpcId {
65    fn from(id: i64) -> Self {
66        Self::Number(id)
67    }
68}
69
70impl From<String> for RawJsonRpcId {
71    fn from(id: String) -> Self {
72        Self::Str(id)
73    }
74}
75
76impl From<v1::RequestId> for RawJsonRpcId {
77    fn from(id: v1::RequestId) -> Self {
78        match id {
79            v1::RequestId::Null => Self::Null,
80            v1::RequestId::Number(id) => Self::Number(id),
81            v1::RequestId::Str(id) => Self::Str(id),
82        }
83    }
84}
85
86impl From<RawJsonRpcId> for v1::RequestId {
87    fn from(id: RawJsonRpcId) -> Self {
88        match id {
89            RawJsonRpcId::Null => Self::Null,
90            RawJsonRpcId::Number(id) => Self::Number(id),
91            RawJsonRpcId::Str(id) => Self::Str(id),
92        }
93    }
94}
95
96#[cfg(feature = "unstable_protocol_v2")]
97impl From<v2::RequestId> for RawJsonRpcId {
98    fn from(id: v2::RequestId) -> Self {
99        match id {
100            v2::RequestId::Number(id) => Self::Number(id),
101            v2::RequestId::Str(id) => Self::Str(id),
102        }
103    }
104}
105
106#[cfg(feature = "unstable_protocol_v2")]
107impl TryFrom<RawJsonRpcId> for v2::RequestId {
108    type Error = crate::Error;
109
110    /// Fails for `null`, which protocol v2 does not allow, with the Invalid
111    /// Request error (`-32600`) the SDK sends for a v2 request with a `null`
112    /// ID.
113    fn try_from(id: RawJsonRpcId) -> Result<Self, Self::Error> {
114        match id {
115            RawJsonRpcId::Null => Err(null_v2_request_id()),
116            RawJsonRpcId::Number(id) => Ok(Self::Number(id)),
117            RawJsonRpcId::Str(id) => Ok(Self::Str(id)),
118        }
119    }
120}
121
122/// The Invalid Request error for a protocol-v2 request whose ID is `null`.
123pub(crate) fn null_v2_request_id() -> crate::Error {
124    crate::Error::invalid_request()
125        .data("ACP protocol v2 request ids must be a string or an integer, not null")
126}
127
128#[cfg(test)]
129mod tests {
130    use serde_json::{Value, json};
131
132    use super::*;
133
134    fn wire_ids() -> Vec<Value> {
135        vec![
136            Value::Null,
137            json!(0),
138            json!(1),
139            json!(-1),
140            json!(9_007_199_254_740_993_i64),
141            json!(i64::MAX),
142            json!(i64::MIN),
143            json!("1"),
144            json!(""),
145            json!("ünïcødé \"quoted\""),
146        ]
147    }
148
149    #[test]
150    fn wire_form_round_trips_exactly() {
151        for wire in wire_ids() {
152            let text = wire.to_string();
153            let id: RawJsonRpcId = serde_json::from_str(&text).unwrap();
154            assert_eq!(serde_json::to_string(&id).unwrap(), text);
155        }
156        assert_ne!(
157            serde_json::from_str::<RawJsonRpcId>("1").unwrap(),
158            serde_json::from_str::<RawJsonRpcId>(r#""1""#).unwrap()
159        );
160    }
161
162    #[test]
163    fn non_ids_are_rejected() {
164        for text in [
165            "9223372036854775808",
166            "-9223372036854775809",
167            "1.5",
168            "1e3",
169            "true",
170            "[]",
171            "{}",
172        ] {
173            assert!(
174                serde_json::from_str::<RawJsonRpcId>(text).is_err(),
175                "{text}"
176            );
177            assert!(
178                serde_json::from_str::<v1::RequestId>(text).is_err(),
179                "{text}"
180            );
181        }
182    }
183
184    #[test]
185    fn v1_conversions_are_lossless_and_match_the_wire() {
186        for wire in wire_ids() {
187            let v1_id: v1::RequestId = serde_json::from_value(wire.clone()).unwrap();
188            let id = RawJsonRpcId::from(v1_id.clone());
189            assert_eq!(serde_json::to_value(&id).unwrap(), wire);
190            assert_eq!(id.to_string(), v1_id.to_string());
191            assert_eq!(v1::RequestId::from(id), v1_id);
192        }
193    }
194
195    #[cfg(feature = "unstable_protocol_v2")]
196    #[test]
197    fn v2_conversions_are_lossless_and_reject_null() {
198        for wire in wire_ids() {
199            let id: RawJsonRpcId = serde_json::from_value(wire.clone()).unwrap();
200            if let Ok(v2_id) = serde_json::from_value::<v2::RequestId>(wire.clone()) {
201                assert_eq!(RawJsonRpcId::from(v2_id.clone()), id);
202                assert_eq!(v2::RequestId::try_from(id).unwrap(), v2_id);
203            } else {
204                assert_eq!(id, RawJsonRpcId::Null);
205                let error = v2::RequestId::try_from(id).unwrap_err();
206                assert_eq!(error.code, crate::ErrorCode::INVALID_REQUEST);
207            }
208        }
209    }
210}