Skip to main content

alloy_json_rpc/
packet.rs

1use crate::{ErrorPayload, Id, Response, ResponsePayload, SerializedRequest};
2use alloy_primitives::map::HashSet;
3use http::HeaderMap;
4use serde::{
5    de::{self, Deserializer, MapAccess, SeqAccess, Visitor},
6    Deserialize, Serialize,
7};
8use serde_json::value::RawValue;
9use std::{borrow::Borrow, fmt, hash::Hash, marker::PhantomData};
10
11/// A [`RequestPacket`] is a [`SerializedRequest`] or a batch of serialized
12/// request.
13#[derive(Clone, Debug)]
14pub enum RequestPacket {
15    /// A single request.
16    Single(SerializedRequest),
17    /// A batch of requests.
18    Batch(Vec<SerializedRequest>),
19}
20
21impl FromIterator<SerializedRequest> for RequestPacket {
22    fn from_iter<T: IntoIterator<Item = SerializedRequest>>(iter: T) -> Self {
23        Self::Batch(iter.into_iter().collect())
24    }
25}
26
27impl From<SerializedRequest> for RequestPacket {
28    fn from(req: SerializedRequest) -> Self {
29        Self::Single(req)
30    }
31}
32
33impl Serialize for RequestPacket {
34    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
35    where
36        S: serde::Serializer,
37    {
38        match self {
39            Self::Single(single) => single.serialize(serializer),
40            Self::Batch(batch) => batch.serialize(serializer),
41        }
42    }
43}
44
45impl RequestPacket {
46    /// Create a new empty packet with the given capacity.
47    pub fn with_capacity(capacity: usize) -> Self {
48        Self::Batch(Vec::with_capacity(capacity))
49    }
50
51    /// Returns the [`SerializedRequest`] if this packet is [`RequestPacket::Single`]
52    pub const fn as_single(&self) -> Option<&SerializedRequest> {
53        match self {
54            Self::Single(req) => Some(req),
55            Self::Batch(_) => None,
56        }
57    }
58
59    /// Returns the batch of [`SerializedRequest`] if this packet is [`RequestPacket::Batch`]
60    pub const fn as_batch(&self) -> Option<&[SerializedRequest]> {
61        match self {
62            Self::Batch(req) => Some(req.as_slice()),
63            Self::Single(_) => None,
64        }
65    }
66
67    /// Serialize the packet as a boxed [`RawValue`].
68    pub fn serialize(self) -> serde_json::Result<Box<RawValue>> {
69        match self {
70            Self::Single(single) => Ok(single.take_request()),
71            Self::Batch(batch) => serde_json::value::to_raw_value(&batch),
72        }
73    }
74
75    /// Get the request IDs of all subscription requests in the packet.
76    pub fn subscription_request_ids(&self) -> HashSet<&Id> {
77        match self {
78            Self::Single(single) => {
79                let id = single.is_subscription().then(|| single.id());
80                HashSet::from_iter(id)
81            }
82            Self::Batch(batch) => {
83                batch.iter().filter(|req| req.is_subscription()).map(|req| req.id()).collect()
84            }
85        }
86    }
87
88    /// Get the number of requests in the packet.
89    pub const fn len(&self) -> usize {
90        match self {
91            Self::Single(_) => 1,
92            Self::Batch(batch) => batch.len(),
93        }
94    }
95
96    /// Check if the packet is empty.
97    pub const fn is_empty(&self) -> bool {
98        self.len() == 0
99    }
100
101    /// Push a request into the packet.
102    pub fn push(&mut self, req: SerializedRequest) {
103        match self {
104            Self::Batch(batch) => batch.push(req),
105            Self::Single(_) => {
106                let old = std::mem::replace(self, Self::Batch(Vec::with_capacity(10)));
107                if let Self::Single(single) = old {
108                    self.push(single);
109                }
110                self.push(req);
111            }
112        }
113    }
114
115    /// Returns all [`SerializedRequest`].
116    pub const fn requests(&self) -> &[SerializedRequest] {
117        match self {
118            Self::Single(req) => std::slice::from_ref(req),
119            Self::Batch(req) => req.as_slice(),
120        }
121    }
122
123    /// Returns a mutable reference to all [`SerializedRequest`].
124    pub const fn requests_mut(&mut self) -> &mut [SerializedRequest] {
125        match self {
126            Self::Single(req) => std::slice::from_mut(req),
127            Self::Batch(req) => req.as_mut_slice(),
128        }
129    }
130
131    /// Returns an iterator over the requests' method names
132    pub fn method_names(&self) -> impl Iterator<Item = &str> + '_ {
133        self.requests().iter().map(|req| req.method())
134    }
135
136    /// Retrieves the combined HTTP headers from all requests in the packet.
137    ///
138    /// Headers are appended in request order, retaining every value for a repeated name. An HTTP
139    /// batch is sent as one request, so these headers apply to the whole packet rather than to
140    /// individual JSON-RPC calls.
141    pub fn headers(&self) -> HeaderMap {
142        self.requests().iter().fold(HeaderMap::new(), |mut acc, req| {
143            if let Some(http_header_extension) = req.meta().extensions().get::<HeaderMap>() {
144                acc.extend(http_header_extension.iter().map(|(k, v)| (k.clone(), v.clone())));
145            };
146            acc
147        })
148    }
149}
150
151/// A [`ResponsePacket`] is a [`Response`] or a batch of responses.
152#[derive(Clone, Debug)]
153pub enum ResponsePacket<Payload = Box<RawValue>, ErrData = Box<RawValue>> {
154    /// A single response.
155    Single(Response<Payload, ErrData>),
156    /// A batch of responses.
157    Batch(Vec<Response<Payload, ErrData>>),
158}
159
160impl<Payload, ErrData> FromIterator<Response<Payload, ErrData>>
161    for ResponsePacket<Payload, ErrData>
162{
163    fn from_iter<T: IntoIterator<Item = Response<Payload, ErrData>>>(iter: T) -> Self {
164        let mut iter = iter.into_iter().peekable();
165        // return single if iter has exactly one element, else make a batch
166        if let Some(first) = iter.next() {
167            return if iter.peek().is_none() {
168                Self::Single(first)
169            } else {
170                let mut batch = Vec::new();
171                batch.push(first);
172                batch.extend(iter);
173                Self::Batch(batch)
174            };
175        }
176        Self::Batch(vec![])
177    }
178}
179
180impl<Payload, ErrData> From<Vec<Response<Payload, ErrData>>> for ResponsePacket<Payload, ErrData> {
181    fn from(value: Vec<Response<Payload, ErrData>>) -> Self {
182        if value.len() == 1 {
183            Self::Single(value.into_iter().next().unwrap())
184        } else {
185            Self::Batch(value)
186        }
187    }
188}
189
190impl<'de, Payload, ErrData> Deserialize<'de> for ResponsePacket<Payload, ErrData>
191where
192    Payload: Deserialize<'de>,
193    ErrData: Deserialize<'de>,
194{
195    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
196    where
197        D: Deserializer<'de>,
198    {
199        struct ResponsePacketVisitor<Payload, ErrData> {
200            marker: PhantomData<fn() -> ResponsePacket<Payload, ErrData>>,
201        }
202
203        impl<'de, Payload, ErrData> Visitor<'de> for ResponsePacketVisitor<Payload, ErrData>
204        where
205            Payload: Deserialize<'de>,
206            ErrData: Deserialize<'de>,
207        {
208            type Value = ResponsePacket<Payload, ErrData>;
209
210            fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
211                formatter.write_str("a single response or a batch of responses")
212            }
213
214            fn visit_seq<A>(self, mut seq: A) -> Result<Self::Value, A::Error>
215            where
216                A: SeqAccess<'de>,
217            {
218                let mut responses = Vec::new();
219
220                while let Some(response) = seq.next_element()? {
221                    responses.push(response);
222                }
223
224                Ok(ResponsePacket::Batch(responses))
225            }
226
227            fn visit_map<M>(self, map: M) -> Result<Self::Value, M::Error>
228            where
229                M: MapAccess<'de>,
230            {
231                let response =
232                    Deserialize::deserialize(de::value::MapAccessDeserializer::new(map))?;
233                Ok(ResponsePacket::Single(response))
234            }
235        }
236
237        deserializer.deserialize_any(ResponsePacketVisitor { marker: PhantomData })
238    }
239}
240
241/// A [`BorrowedResponsePacket`] is a [`ResponsePacket`] that has been partially deserialized,
242/// borrowing its contents from the deserializer.
243///
244/// This is used primarily for intermediate deserialization. Most users will not require it.
245///
246/// See the [top-level docs] for more info.
247///
248/// [top-level docs]: crate
249pub type BorrowedResponsePacket<'a> = ResponsePacket<&'a RawValue, &'a RawValue>;
250
251impl BorrowedResponsePacket<'_> {
252    /// Convert this borrowed response packet into an owned packet by copying
253    /// the data from the deserializer (if necessary).
254    pub fn into_owned(self) -> ResponsePacket {
255        match self {
256            Self::Single(single) => ResponsePacket::Single(single.into_owned()),
257            Self::Batch(batch) => {
258                ResponsePacket::Batch(batch.into_iter().map(Response::into_owned).collect())
259            }
260        }
261    }
262}
263
264impl<Payload, ErrData> ResponsePacket<Payload, ErrData> {
265    /// Returns the [`Response`] if this packet is [`ResponsePacket::Single`].
266    pub const fn as_single(&self) -> Option<&Response<Payload, ErrData>> {
267        match self {
268            Self::Single(resp) => Some(resp),
269            Self::Batch(_) => None,
270        }
271    }
272
273    /// Returns the batch of [`Response`] if this packet is [`ResponsePacket::Batch`].
274    pub const fn as_batch(&self) -> Option<&[Response<Payload, ErrData>]> {
275        match self {
276            Self::Batch(resp) => Some(resp.as_slice()),
277            Self::Single(_) => None,
278        }
279    }
280
281    /// Returns the [`ResponsePayload`] if this packet is [`ResponsePacket::Single`].
282    pub fn single_payload(&self) -> Option<&ResponsePayload<Payload, ErrData>> {
283        self.as_single().map(|resp| &resp.payload)
284    }
285
286    /// Returns `true` if the response payload is a success.
287    ///
288    /// For batch responses, this returns `true` if __all__ responses are successful.
289    pub fn is_success(&self) -> bool {
290        match self {
291            Self::Single(single) => single.is_success(),
292            Self::Batch(batch) => batch.iter().all(|res| res.is_success()),
293        }
294    }
295
296    /// Returns `true` if the response payload is an error.
297    ///
298    /// For batch responses, this returns `true` there's at least one error response.
299    pub fn is_error(&self) -> bool {
300        match self {
301            Self::Single(single) => single.is_error(),
302            Self::Batch(batch) => batch.iter().any(|res| res.is_error()),
303        }
304    }
305
306    /// Returns the [ErrorPayload] if the response is an error.
307    ///
308    /// For batch responses, this returns the first error response.
309    pub fn as_error(&self) -> Option<&ErrorPayload<ErrData>> {
310        self.iter_errors().next()
311    }
312
313    /// Returns an iterator over the [ErrorPayload]s in the response.
314    pub fn iter_errors(&self) -> impl Iterator<Item = &ErrorPayload<ErrData>> + '_ {
315        match self {
316            Self::Single(single) => ResponsePacketErrorsIter::Single(Some(single)),
317            Self::Batch(batch) => ResponsePacketErrorsIter::Batch(batch.iter()),
318        }
319    }
320
321    /// Returns the first error code in this packet if it contains any error responses.
322    pub fn first_error_code(&self) -> Option<i64> {
323        self.as_error().map(|error| error.code)
324    }
325
326    /// Returns the first error message in this packet if it contains any error responses.
327    pub fn first_error_message(&self) -> Option<&str> {
328        self.as_error().map(|error| error.message.as_ref())
329    }
330
331    /// Returns the first error data in this packet if it contains any error responses.
332    pub fn first_error_data(&self) -> Option<&ErrData> {
333        self.as_error().and_then(|error| error.data.as_ref())
334    }
335
336    /// Returns a all [`Response`].
337    pub const fn responses(&self) -> &[Response<Payload, ErrData>] {
338        match self {
339            Self::Single(req) => std::slice::from_ref(req),
340            Self::Batch(req) => req.as_slice(),
341        }
342    }
343
344    /// Returns an iterator over the responses' payloads.
345    pub fn payloads(&self) -> impl Iterator<Item = &ResponsePayload<Payload, ErrData>> + '_ {
346        self.responses().iter().map(|resp| &resp.payload)
347    }
348
349    /// Returns the first [`ResponsePayload`] in this packet.
350    pub fn first_payload(&self) -> Option<&ResponsePayload<Payload, ErrData>> {
351        self.payloads().next()
352    }
353
354    /// Returns an iterator over the responses' identifiers.
355    pub fn response_ids(&self) -> impl Iterator<Item = &Id> + '_ {
356        self.responses().iter().map(|resp| &resp.id)
357    }
358
359    /// Find responses by a list of IDs.
360    ///
361    /// This is intended to be used in conjunction with
362    /// [`RequestPacket::subscription_request_ids`] to identify subscription
363    /// responses.
364    ///
365    /// # Note
366    ///
367    /// - Responses are not guaranteed to be in the same order.
368    /// - Responses are not guaranteed to be in the set.
369    /// - If the packet contains duplicate IDs, both will be found.
370    pub fn responses_by_ids<K>(&self, ids: &HashSet<K>) -> Vec<&Response<Payload, ErrData>>
371    where
372        K: Borrow<Id> + Eq + Hash,
373    {
374        match self {
375            Self::Single(single) if ids.contains(&single.id) => vec![single],
376            Self::Batch(batch) => batch.iter().filter(|res| ids.contains(&res.id)).collect(),
377            _ => Vec::new(),
378        }
379    }
380}
381
382/// An Iterator over the [ErrorPayload]s in a [ResponsePacket].
383#[derive(Clone, Debug)]
384enum ResponsePacketErrorsIter<'a, Payload, ErrData> {
385    Single(Option<&'a Response<Payload, ErrData>>),
386    Batch(std::slice::Iter<'a, Response<Payload, ErrData>>),
387}
388
389impl<'a, Payload, ErrData> Iterator for ResponsePacketErrorsIter<'a, Payload, ErrData> {
390    type Item = &'a ErrorPayload<ErrData>;
391
392    fn next(&mut self) -> Option<Self::Item> {
393        match self {
394            ResponsePacketErrorsIter::Single(single) => single.take()?.payload.as_error(),
395            ResponsePacketErrorsIter::Batch(batch) => loop {
396                let res = batch.next()?;
397                if let Some(err) = res.payload.as_error() {
398                    return Some(err);
399                }
400            },
401        }
402    }
403}