Skip to main content

jsonrpsee_core/server/
method_response.rs

1// Copyright 2019-2021 Parity Technologies (UK) Ltd.
2//
3// Permission is hereby granted, free of charge, to any
4// person obtaining a copy of this software and associated
5// documentation files (the "Software"), to deal in the
6// Software without restriction, including without
7// limitation the rights to use, copy, modify, merge,
8// publish, distribute, sublicense, and/or sell copies of
9// the Software, and to permit persons to whom the Software
10// is furnished to do so, subject to the following
11// conditions:
12//
13// The above copyright notice and this permission notice
14// shall be included in all copies or substantial portions
15// of the Software.
16//
17// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF
18// ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
19// TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
20// PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
21// SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
22// CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
23// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR
24// IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
25// DEALINGS IN THE SOFTWARE.
26
27//! Represent a method response.
28
29const LOG_TARGET: &str = "jsonrpsee-core";
30
31use std::{
32    future::Future,
33    io::{self, Write},
34    panic::AssertUnwindSafe,
35    pin::Pin,
36    sync::{
37        atomic::{AtomicUsize, Ordering},
38        Arc,
39    },
40    task::{ready, Context, Poll},
41};
42
43use bytes::Bytes;
44use futures_util::{future::BoxFuture, FutureExt, Stream, StreamExt};
45use jsonrpsee_types::{
46    error::{reject_too_big_batch_response, reject_too_big_response, ErrorCode, ErrorObject},
47    ErrorObjectOwned, Id, Response,
48};
49use serde::Serialize;
50use tokio::sync::mpsc;
51
52pub use jsonrpsee_types::ResponsePayload;
53
54#[derive(Debug)]
55enum ResponseKind {
56    MethodCall,
57    /// A method call whose result is still being produced, see [`ResponseStream`]. Boxed, so it
58    /// doesn't grow every other response.
59    Stream(Box<StreamedJson>),
60    Subscription,
61    Batch,
62    Notification,
63}
64
65/// Represents a response to a method call.
66///
67/// NOTE: A subscription is also a method call but it's
68/// possible determine whether a method response
69/// is "subscription" or "ordinary method call"
70/// by calling [`MethodResponse::is_subscription`]
71#[derive(Debug)]
72pub struct MethodResponse {
73    /// Serialized JSON-RPC response.
74    json: String,
75    /// Indicates whether the call was successful or not.
76    success_or_error: MethodResponseResult,
77    /// Indicates whether the call was a subscription response.
78    kind: ResponseKind,
79}
80
81impl AsRef<str> for MethodResponse {
82    fn as_ref(&self) -> &str {
83        &self.json
84    }
85}
86
87impl std::fmt::Display for MethodResponse {
88    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
89        write!(f, "{}", self.json)
90    }
91}
92
93impl MethodResponse {
94    /// Returns whether the call was successful.
95    pub fn is_success(&self) -> bool {
96        self.success_or_error.is_success()
97    }
98
99    /// Returns whether the call failed.
100    pub fn is_error(&self) -> bool {
101        self.success_or_error.is_error()
102    }
103
104    /// Returns whether the response is a subscription response.
105    pub fn is_subscription(&self) -> bool {
106        matches!(self.kind, ResponseKind::Subscription)
107    }
108
109    /// Returns whether the response is a method response, streamed or not.
110    pub fn is_method_call(&self) -> bool {
111        matches!(self.kind, ResponseKind::MethodCall | ResponseKind::Stream(_))
112    }
113
114    /// Returns whether the response is a batch response.
115    pub fn is_batch(&self) -> bool {
116        matches!(self.kind, ResponseKind::Batch)
117    }
118
119    /// Consume the method response and extract the serialized JSON response.
120    ///
121    /// # Panics
122    ///
123    /// If the response is a stream, which must be [buffered](MethodResponse::buffer) first.
124    pub fn into_json(self) -> String {
125        assert!(
126            !matches!(self.kind, ResponseKind::Stream(_)),
127            "a streamed response must be buffered first"
128        );
129        self.json
130    }
131
132    /// Consume the method response and return its body, whole or as a stream of parts.
133    pub fn into_body(self) -> ResponseBody {
134        match self.kind {
135            ResponseKind::Stream(stream) => ResponseBody::Stream(*stream),
136            _ => ResponseBody::Json(self.json),
137        }
138    }
139
140    /// Waits for the rest of a streamed response and returns it as a whole. Other responses are
141    /// returned unchanged.
142    ///
143    /// If the result fails or exceeds the response size limit after it started, the response is
144    /// replaced with that error, because none of it was sent yet.
145    pub async fn buffer(self) -> Self {
146        let ResponseKind::Stream(mut stream) = self.kind else { return self };
147        let mut json = Vec::with_capacity(stream.head.iter().map(Bytes::len).sum());
148        while let Some(part) = stream.next().await {
149            match part {
150                Ok(part) => json.extend_from_slice(&part),
151                Err(err) => return Self::bounded_error(stream.id, err, stream.max_response_size),
152            }
153        }
154        Self::from_parts(stream.id, json)
155    }
156
157    /// Get the serialized JSON response.
158    pub fn to_json(&self) -> String {
159        self.json.clone()
160    }
161
162    /// Get the error code
163    ///
164    /// Returns `Some(error code)` if the call failed.
165    pub fn as_error_code(&self) -> Option<i32> {
166        self.success_or_error.as_error_code()
167    }
168
169    /// This is similar to [`MethodResponse::response`] but sets a flag to indicate
170    /// that response is a subscription.
171    pub fn subscription_response<T>(
172        id: Id,
173        result: ResponsePayload<T>,
174        max_response_size: usize,
175    ) -> Self
176    where
177        T: Serialize + Clone,
178    {
179        let mut rp = Self::response(id, result, max_response_size);
180        rp.kind = ResponseKind::Subscription;
181        rp
182    }
183
184    /// Create a new method response.
185    ///
186    /// If the serialization of `result` exceeds `max_response_size` then
187    /// the response is changed to an JSON-RPC error object.
188    pub fn response<T>(id: Id, rp: ResponsePayload<T>, max_response_size: usize) -> Self
189    where
190        T: Serialize + Clone,
191    {
192        Self::response_with_capacity(id, rp, max_response_size, 128)
193    }
194
195    /// Same as [`MethodResponse::response`], but sizes the serialization buffer from the method's
196    /// previous responses and records the size of this one if it is a success.
197    pub(crate) fn sized_response<T>(
198        id: Id,
199        rp: ResponsePayload<T>,
200        max_response_size: usize,
201        size_hint: &ResponseSizeHint,
202    ) -> Self
203    where
204        T: Serialize + Clone,
205    {
206        // An error's size says nothing about the method's results, so it neither uses nor updates
207        // the hint.
208        if matches!(rp, ResponsePayload::Error(_)) {
209            return Self::response(id, rp, max_response_size)
210        }
211        let mut rp = Self::response_with_capacity(id, rp, max_response_size, size_hint.capacity());
212        // A response much smaller than the hint would otherwise keep the unused capacity until it
213        // is sent.
214        let unused = rp.json.capacity() - rp.json.len();
215        if unused > rp.json.len() && unused > RESPONSE_SHRINK_THRESHOLD {
216            rp.json.shrink_to_fit();
217        }
218        // A success that exceeded the limit was replaced with an error, which isn't recorded.
219        if rp.is_success() {
220            size_hint.record(rp.json.len());
221        }
222        rp
223    }
224
225    fn response_with_capacity<T>(
226        id: Id,
227        rp: ResponsePayload<T>,
228        max_response_size: usize,
229        capacity: usize,
230    ) -> Self
231    where
232        T: Serialize + Clone,
233    {
234        let mut writer = BoundedWriter::new(max_response_size, capacity);
235
236        let success_or_error = if let ResponsePayload::Error(e) = &rp {
237            MethodResponseResult::Failed(e.code())
238        } else {
239            MethodResponseResult::Success
240        };
241
242        let kind = ResponseKind::MethodCall;
243
244        match serde_json::to_writer(&mut writer, &Response::new(rp, id.clone())) {
245            Ok(_) => {
246                // SAFETY: serde_json does not emit invalid UTF-8.
247                let json = unsafe { String::from_utf8_unchecked(writer.into_bytes()) };
248
249                Self { json, success_or_error, kind }
250            }
251            Err(err) => {
252                tracing::error!(target: LOG_TARGET, "Error serializing response: {:?}", err);
253
254                if err.is_io() {
255                    Self::error(id, reject_too_big_response(max_response_size))
256                } else {
257                    let err = ErrorCode::InternalError;
258                    let payload = ResponsePayload::<()>::error(err);
259                    let json = serde_json::to_string(&Response::new(payload, id))
260                        .expect("JSON serialization infallible; qed");
261                    Self { json, success_or_error: MethodResponseResult::Failed(err.code()), kind }
262                }
263            }
264        }
265    }
266
267    /// This is similar to [`MethodResponse::error`] but sets a flag to indicate
268    /// that error is a subscription.
269    pub fn subscription_error<'a>(id: Id, err: impl Into<ErrorObject<'a>>) -> Self {
270        let mut rp = Self::error(id, err);
271        rp.kind = ResponseKind::Subscription;
272        rp
273    }
274
275    /// Create a [`MethodResponse`] from a JSON-RPC error.
276    pub fn error<'a>(id: Id, err: impl Into<ErrorObject<'a>>) -> Self {
277        let err: ErrorObject = err.into();
278        let err_code = err.code();
279        let err = ResponsePayload::<()>::error_borrowed(err);
280        let json = serde_json::to_string(&Response::new(err, id))
281            .expect("JSON serialization infallible; qed");
282        Self {
283            json,
284            success_or_error: MethodResponseResult::Failed(err_code),
285            kind: ResponseKind::MethodCall,
286        }
287    }
288
289    /// Same as [`MethodResponse::error`], but if the serialization of `err` exceeds
290    /// `max_response_size`, the response is changed to the oversized response error.
291    pub(crate) fn bounded_error(id: Id, err: ErrorObjectOwned, max_response_size: usize) -> Self {
292        Self::response(id, ResponsePayload::<()>::error(err), max_response_size)
293    }
294
295    /// Create notification response which is a response that doesn't expect a reply.
296    pub fn notification() -> Self {
297        Self {
298            json: String::from("null"),
299            success_or_error: MethodResponseResult::Success,
300            kind: ResponseKind::Notification,
301        }
302    }
303
304    /// Create a response whose result is produced in parts by `stream`.
305    ///
306    /// Buffers the parts until they reach [`STREAM_THRESHOLD`] bytes, so a result that finishes or
307    /// fails before that is answered as a whole response or a regular JSON-RPC error. Only a larger
308    /// result is streamed.
309    pub(crate) async fn stream(
310        id: Id<'static>,
311        stream: ResponseStream,
312        max_response_size: usize,
313    ) -> Self {
314        let mut json = String::from(r#"{"jsonrpc":"2.0","id":"#);
315        // SAFETY: serde_json does not emit invalid UTF-8.
316        serde_json::to_writer(unsafe { json.as_mut_vec() }, &id)
317            .expect("JSON serialization infallible; qed");
318        json.push_str(r#","result":"#);
319
320        // The closing brace needs one byte, so a response that fits leaves `remaining` above zero.
321        let Some(left) = max_response_size.checked_sub(json.len()).filter(|&left| left > 0) else {
322            return Self::error(id, reject_too_big_response(max_response_size))
323        };
324        let (tx, parts) = mpsc::unbounded_channel();
325        let remaining = Arc::new(AtomicUsize::new(left));
326        let producer = (stream.producer)(ResponseSink { parts: tx, remaining: remaining.clone() });
327        let mut stream = StreamedJson {
328            id,
329            head: Default::default(),
330            parts,
331            producer: Some(producer),
332            outcome: Ok(()),
333            remaining,
334            max_response_size,
335            done: false,
336        };
337        let mut head = json.clone().into_bytes();
338        while let Some(part) = stream.next().await {
339            match part {
340                // A producer that finished without a part yields only the closing brace, but a
341                // result needs at least one part to be a JSON value.
342                Ok(_) if stream.done && head.len() == json.len() => {
343                    return Self::error(stream.id, ErrorCode::InternalError)
344                }
345                // The part that reaches the threshold can be most of the result, so it is kept as
346                // it is instead of being copied. Only result bytes count, so a large id can't skip
347                // the first part.
348                Ok(part)
349                    if !stream.done && head.len() - json.len() + part.len() >= STREAM_THRESHOLD =>
350                {
351                    stream.head = [head.into(), part];
352                    return Self {
353                        json,
354                        success_or_error: MethodResponseResult::Success,
355                        kind: ResponseKind::Stream(Box::new(stream)),
356                    }
357                }
358                Ok(part) => head.extend_from_slice(&part),
359                Err(err) => return Self::bounded_error(stream.id, err, max_response_size),
360            }
361        }
362        // The result ended below the threshold, so the buffered parts are the whole response.
363        Self::from_parts(stream.id, head)
364    }
365
366    /// Creates the response of a streamed method call from its parts, joined into `json`.
367    fn from_parts(id: Id, json: Vec<u8>) -> Self {
368        let Ok(json) = String::from_utf8(json) else {
369            tracing::error!(target: LOG_TARGET, "Streamed response is not valid UTF-8");
370            return Self::error(id, ErrorCode::InternalError)
371        };
372        Self {
373            json,
374            success_or_error: MethodResponseResult::Success,
375            kind: ResponseKind::MethodCall,
376        }
377    }
378}
379
380/// Serialized response of a method call, see [`MethodResponse::into_body`].
381#[derive(Debug)]
382pub enum ResponseBody {
383    /// The whole response.
384    Json(String),
385    /// A response whose result is still being produced.
386    Stream(StreamedJson),
387}
388
389/// A response that is serialized while its result is produced.
390///
391/// It drives the producer of the [`ResponseStream`] and yields the response in parts that together
392/// form one JSON-RPC response. Once the result fails or exceeds the response size limit, it yields
393/// an error and ends. Parts that were already sent can't be taken back, so the transport has to
394/// abort the response instead of completing it. Dropping it drops the producer.
395pub struct StreamedJson {
396    id: Id<'static>,
397    /// The parts buffered by [`MethodResponse::stream`], yielded first: the envelope with the
398    /// result up to [`STREAM_THRESHOLD`] bytes, and the part that reached the threshold.
399    head: [Bytes; 2],
400    parts: mpsc::UnboundedReceiver<Bytes>,
401    /// `None` once the producer finished with `outcome`.
402    producer: Option<Producer>,
403    outcome: Result<(), ErrorObjectOwned>,
404    /// See [`ResponseSink::remaining`].
405    remaining: Arc<AtomicUsize>,
406    max_response_size: usize,
407    done: bool,
408}
409
410impl std::fmt::Debug for StreamedJson {
411    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
412        f.debug_struct("StreamedJson").field("id", &self.id).finish_non_exhaustive()
413    }
414}
415
416impl Stream for StreamedJson {
417    type Item = Result<Bytes, ErrorObjectOwned>;
418
419    fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
420        let this = &mut *self;
421        if let Some(part) = this.head.iter_mut().find(|part| !part.is_empty()) {
422            return Poll::Ready(Some(Ok(std::mem::take(part))))
423        }
424        if this.done {
425            return Poll::Ready(None)
426        }
427
428        loop {
429            let Some(producer) = &mut this.producer else {
430                // Unlike `poll_recv`, `try_recv` doesn't return `Pending` for queued parts once the
431                // task used up its cooperative budget.
432                if let Ok(part) = this.parts.try_recv() {
433                    return Poll::Ready(Some(Ok(part)))
434                }
435                this.done = true;
436                let outcome = std::mem::replace(&mut this.outcome, Ok(()));
437                if this.remaining.load(Ordering::Relaxed) == 0 {
438                    return Poll::Ready(Some(Err(reject_too_big_response(this.max_response_size))))
439                }
440                return Poll::Ready(Some(outcome.map(|()| Bytes::from_static(b"}"))))
441            };
442            if let Poll::Ready(Some(part)) = this.parts.poll_recv(cx) {
443                return Poll::Ready(Some(Ok(part)))
444            }
445            this.outcome = ready!(producer.as_mut().poll(cx));
446            this.producer = None;
447        }
448    }
449}
450
451/// A method result that is produced in parts.
452///
453/// Return it from a method registered with
454/// [`RpcModule::register_streaming_method`](crate::server::RpcModule::register_streaming_method).
455pub struct ResponseStream {
456    /// Called once the response size limit is known, so every part counts towards it.
457    producer: Box<dyn FnOnce(ResponseSink) -> Producer + Send>,
458}
459
460type Producer = BoxFuture<'static, Result<(), ErrorObjectOwned>>;
461
462impl ResponseStream {
463    /// Creates a result that `producer` sends in parts through the given sink.
464    ///
465    /// The parts are concatenated as they are, so together they must form the result as one JSON
466    /// value. The transport polls the future while it sends the response and drops it with the
467    /// response. The result is complete once the future returns `Ok` and fails with the error it
468    /// returns or when it panics.
469    pub fn new<F, Fut, E>(producer: F) -> Self
470    where
471        F: FnOnce(ResponseSink) -> Fut + Send + 'static,
472        Fut: Future<Output = Result<(), E>> + Send + 'static,
473        E: Into<ErrorObjectOwned>,
474    {
475        let producer = |sink| {
476            let producer = producer(sink);
477            AssertUnwindSafe(async move { producer.await.map_err(Into::into) })
478                .catch_unwind()
479                .map(|outcome| outcome.unwrap_or_else(|_| Err(ErrorCode::InternalError.into())))
480                .boxed()
481        };
482        Self { producer: Box::new(producer) }
483    }
484}
485
486impl std::fmt::Debug for ResponseStream {
487    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
488        f.debug_struct("ResponseStream").finish_non_exhaustive()
489    }
490}
491
492/// Sends the parts of a [`ResponseStream`].
493///
494/// Sending never waits for the client, so a slow client can't hold the producer's resources. The
495/// parts it has not read yet stay in memory, up to the response size limit.
496#[derive(Debug, Clone)]
497pub struct ResponseSink {
498    parts: mpsc::UnboundedSender<Bytes>,
499    /// Bytes left for the parts and the closing brace of the response, or zero once a part
500    /// exceeded the response size limit.
501    remaining: Arc<AtomicUsize>,
502}
503
504impl ResponseSink {
505    /// Queues the next part of the result.
506    ///
507    /// Fails once the response was dropped or `part` would exceed the response size limit, so the
508    /// producer can stop.
509    pub fn send(&self, part: Bytes) -> Result<(), mpsc::error::SendError<Bytes>> {
510        let fits = self.remaining.try_update(Ordering::Relaxed, Ordering::Relaxed, |left| {
511            left.checked_sub(part.len()).filter(|&left| left > 0)
512        });
513        if fits.is_err() {
514            self.remaining.store(0, Ordering::Relaxed);
515            return Err(mpsc::error::SendError(part))
516        }
517        self.parts.send(part)
518    }
519
520    /// Serializes `value` after `prefix` and queues it as the next part.
521    ///
522    /// Serialization stops once the part exceeds the response size limit, so an oversized value is
523    /// never written in full. Fails with an I/O error once the response was dropped or the part
524    /// would exceed the limit, so the producer can stop, and with a serialization error if `value`
525    /// can't be serialized.
526    pub fn send_json<T: Serialize + ?Sized>(
527        &self,
528        prefix: &[u8],
529        value: &T,
530    ) -> Result<(), serde_json::Error> {
531        // `send` keeps one byte for the closing brace.
532        let max_len = self.remaining.load(Ordering::Relaxed).saturating_sub(1);
533        let mut writer = BoundedWriter::new(max_len, 128);
534        let written = (&mut writer)
535            .write_all(prefix)
536            .map_err(serde_json::Error::io)
537            .and_then(|()| serde_json::to_writer(&mut writer, value));
538        if let Err(err) = written {
539            if err.is_io() {
540                self.remaining.store(0, Ordering::Relaxed);
541            }
542            return Err(err)
543        }
544        self.send(writer.into_bytes().into())
545            .map_err(|_| serde_json::Error::io(io::ErrorKind::BrokenPipe.into()))
546    }
547}
548
549/// Represent the outcome of a method call success or failed.
550#[derive(Debug, Copy, Clone)]
551enum MethodResponseResult {
552    /// The method call was successful.
553    Success,
554    /// The method call failed with error code.
555    Failed(i32),
556}
557
558impl MethodResponseResult {
559    /// Returns whether the call was successful.
560    fn is_success(&self) -> bool {
561        matches!(self, MethodResponseResult::Success)
562    }
563
564    /// Returns whether the call failed.
565    fn is_error(&self) -> bool {
566        matches!(self, MethodResponseResult::Failed(_))
567    }
568
569    /// Get the error code
570    ///
571    /// Returns `Some(error code)` if the call failed.
572    fn as_error_code(&self) -> Option<i32> {
573        match self {
574            Self::Failed(e) => Some(*e),
575            _ => None,
576        }
577    }
578}
579
580/// Builder for the response to a batch request.
581#[derive(Debug)]
582pub struct BatchResponseBuilder {
583    /// Serialized JSON-RPC response,
584    result: String,
585    /// Max limit for the batch
586    max_response_size: usize,
587}
588
589impl BatchResponseBuilder {
590    /// Create a new batch response builder with limit.
591    pub fn new_with_limit(limit: usize) -> Self {
592        let mut initial = String::with_capacity(2048);
593        initial.push('[');
594
595        Self { result: initial, max_response_size: limit }
596    }
597
598    /// Append a result from an individual method to the batch response.
599    ///
600    /// Fails if the max limit is exceeded and returns to error response to
601    /// return early in order to not process method call responses which are thrown away anyway.
602    pub fn append(&mut self, response: MethodResponse) -> Result<(), MethodResponse> {
603        // `,` will occupy one extra byte for each entry
604        // on the last item the `,` is replaced by `]`.
605        let len = response.json.len() + self.result.len() + 1;
606
607        if len > self.max_response_size {
608            Err(MethodResponse::error(
609                Id::Null,
610                reject_too_big_batch_response(self.max_response_size),
611            ))
612        } else {
613            self.result.push_str(&response.json);
614            self.result.push(',');
615            Ok(())
616        }
617    }
618
619    /// Check if the batch is empty.
620    pub fn is_empty(&self) -> bool {
621        self.result.len() <= 1
622    }
623
624    /// Finish the batch response.
625    ///
626    /// An empty batch is answered with an invalid request error.
627    pub fn finish(mut self) -> MethodResponse {
628        if self.is_empty() {
629            return MethodResponse::error(Id::Null, ErrorObject::from(ErrorCode::InvalidRequest))
630        }
631        // Replace the trailing `,` of the last entry.
632        self.result.pop();
633        self.result.push(']');
634        MethodResponse {
635            json: self.result,
636            success_or_error: MethodResponseResult::Success,
637            kind: ResponseKind::Batch,
638        }
639    }
640}
641
642/// Expected size of a method's next successful response.
643///
644/// Responses of the same method tend to have similar sizes, so serializing into a buffer of the
645/// previous size avoids growing (and copying) large responses step by step. The hint is a decaying
646/// maximum of the method's successful responses, so a `null` or a short response between large
647/// ones barely lowers it, and errors don't change it.
648#[derive(Debug)]
649pub(crate) struct ResponseSizeHint(AtomicUsize);
650
651impl ResponseSizeHint {
652    pub(crate) const fn new() -> Self {
653        Self(AtomicUsize::new(128))
654    }
655
656    /// Returns the capacity to reserve for the next response.
657    ///
658    /// It has a quarter more room than the hint, so a response slightly larger than the previous
659    /// ones doesn't double the buffer.
660    fn capacity(&self) -> usize {
661        let hint = self.0.load(Ordering::Relaxed);
662        (hint + hint / 4).min(MAX_RESPONSE_SIZE_HINT)
663    }
664
665    /// Records the size of a successful response.
666    fn record(&self, len: usize) {
667        // Concurrent calls may overwrite each other's update. The hint is only an estimate, so a
668        // lost update costs at most one regrown buffer.
669        let hint = self.0.load(Ordering::Relaxed);
670        let decayed = hint - hint / 8;
671        self.0.store(len.max(decayed).min(MAX_RESPONSE_SIZE_HINT), Ordering::Relaxed);
672    }
673}
674
675/// Largest capacity a [`ResponseSizeHint`] reserves, so one huge response doesn't make every later
676/// call of the method, from any connection, reserve as much.
677const MAX_RESPONSE_SIZE_HINT: usize = 8 * 1024 * 1024;
678
679/// A streamed result is buffered up to this many bytes, see [`MethodResponse::stream`].
680const STREAM_THRESHOLD: usize = 1024 * 1024;
681
682/// A response is shrunk only if more than half of its buffer, and more than this many bytes, is
683/// unused. Smaller buffers aren't worth reallocating.
684const RESPONSE_SHRINK_THRESHOLD: usize = 16 * 1024;
685
686/// Bounded writer that allows writing at most `max_len` bytes.
687#[derive(Debug, Clone)]
688struct BoundedWriter {
689    max_len: usize,
690    buf: Vec<u8>,
691}
692
693impl BoundedWriter {
694    /// Create a new bounded writer with room for `capacity` bytes.
695    pub fn new(max_len: usize, capacity: usize) -> Self {
696        Self { max_len, buf: Vec::with_capacity(capacity.min(max_len)) }
697    }
698
699    /// Consume the writer and extract the written bytes.
700    pub fn into_bytes(self) -> Vec<u8> {
701        self.buf
702    }
703}
704
705// serde_json emits a response as many small writes, so both methods are inlined into the
706// serializer and only check the limit, instead of going through the default `write_all` loop.
707impl io::Write for &mut BoundedWriter {
708    #[inline]
709    fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
710        self.write_all(buf)?;
711        Ok(buf.len())
712    }
713
714    #[inline]
715    fn write_all(&mut self, buf: &[u8]) -> io::Result<()> {
716        if buf.len() > self.max_len - self.buf.len() {
717            return Err(limit_exceeded());
718        }
719        self.buf.extend_from_slice(buf);
720        Ok(())
721    }
722
723    #[inline]
724    fn flush(&mut self) -> io::Result<()> {
725        Ok(())
726    }
727}
728
729#[cold]
730fn limit_exceeded() -> io::Error {
731    io::Error::new(io::ErrorKind::OutOfMemory, "Memory capacity exceeded")
732}
733
734#[cfg(test)]
735mod tests {
736    use super::*;
737    use jsonrpsee_types::error::OVERSIZED_RESPONSE_CODE;
738
739    /// Streams `parts`, which then finish with `outcome`, as the result of a call with id 1.
740    async fn stream(
741        parts: &'static [&'static str],
742        outcome: Result<(), ErrorObjectOwned>,
743        max_response_size: usize,
744    ) -> MethodResponse {
745        let stream = ResponseStream::new(move |tx| async move {
746            for part in parts {
747                let _ = tx.send(Bytes::from_static(part.as_bytes()));
748            }
749            outcome
750        });
751        MethodResponse::stream(Id::Number(1), stream, max_response_size).await
752    }
753
754    #[tokio::test]
755    async fn stream_buffers_parts_and_errors() {
756        let ok = r#"{"jsonrpc":"2.0","id":1,"result":[1,2]}"#;
757        let custom = ErrorObject::owned(1, "custom", None::<()>);
758        let failed = r#"{"jsonrpc":"2.0","id":1,"error":{"code":1,"message":"custom"}}"#;
759
760        // A small result is answered as a whole, so `into_json` doesn't panic.
761        let rp = stream(&["[1", ",2", "]"], Ok(()), usize::MAX).await;
762        assert_eq!(rp.into_json(), ok);
763        // So is one with an id past the threshold.
764        let id = "1".repeat(STREAM_THRESHOLD);
765        let stream_ok = ResponseStream::new(|tx| async move {
766            let _ = tx.send(Bytes::from_static(b"[1,2]"));
767            Ok::<_, ErrorObjectOwned>(())
768        });
769        let rp = MethodResponse::stream(Id::Str(id.clone().into()), stream_ok, usize::MAX).await;
770        assert_eq!(rp.into_json(), format!(r#"{{"jsonrpc":"2.0","id":"{id}","result":[1,2]}}"#));
771        // Fails before the first part, after it, and without any part.
772        let rp = stream(&[], Err(custom.clone()), usize::MAX).await;
773        assert_eq!(rp.into_json(), failed);
774        let rp = stream(&["[1"], Err(custom.clone()), usize::MAX).await;
775        assert_eq!(rp.into_json(), failed);
776        let rp = stream(&[], Ok(()), usize::MAX).await;
777        assert_eq!(rp.as_error_code(), Some(ErrorCode::InternalError.code()));
778        // More parts than tokio's cooperative budget lets a task receive in one poll.
779        let parts = Vec::leak([["[0"].as_slice(), &[",0"; 300], &["]"]].concat());
780        let json = stream(parts, Ok(()), usize::MAX).await.buffer().await.into_json();
781        assert_eq!(json, format!(r#"{{"jsonrpc":"2.0","id":1,"result":[0{}]}}"#, ",0".repeat(300)));
782
783        // Past the buffered bytes, the result is streamed and a failure ends it with the error.
784        // The part that reaches the threshold is not copied to the buffered ones.
785        let big: &'static str = String::leak("1".repeat(STREAM_THRESHOLD));
786        let rp = stream(Vec::leak(vec!["[", big]), Err(custom.clone()), usize::MAX).await;
787        let ResponseBody::Stream(mut body) = rp.into_body() else { panic!("not a stream") };
788        let head = body.next().await.unwrap().unwrap();
789        assert_eq!(head, r#"{"jsonrpc":"2.0","id":1,"result":["#);
790        let part = body.next().await.unwrap().unwrap();
791        assert_eq!((part.as_ptr(), part.len()), (big.as_ptr(), big.len()));
792        assert_eq!(body.next().await.unwrap().unwrap_err(), custom);
793        assert!(body.next().await.is_none());
794
795        // The closing brace, a later part, and the first part each exceed the limit.
796        let rp = stream(&["[1", ",2", "]"], Ok(()), ok.len()).await;
797        assert_eq!(rp.buffer().await.into_json(), ok);
798        for limit in [ok.len() - 1, ok.len() - 2, ok.len() - 4] {
799            let rp = stream(&["[1", ",2", "]"], Ok(()), limit).await;
800            assert_eq!(rp.buffer().await.as_error_code(), Some(OVERSIZED_RESPONSE_CODE));
801        }
802        // An error that exceeds the limit, before and after the first part.
803        let big = ErrorObject::owned(1, "custom", Some("a".repeat(ok.len())));
804        let rp = stream(&[], Err(big.clone()), ok.len()).await;
805        assert_eq!(rp.as_error_code(), Some(OVERSIZED_RESPONSE_CODE));
806        let rp = stream(&["[1"], Err(big), ok.len()).await;
807        assert_eq!(rp.buffer().await.as_error_code(), Some(OVERSIZED_RESPONSE_CODE));
808
809        // A part past the limit isn't queued, and the producer learns it.
810        let (sent_tx, sent_rx) = std::sync::mpsc::channel();
811        let stream = ResponseStream::new(move |tx| async move {
812            let sent = ["[1", ",2", "]"].map(|part| tx.send(Bytes::from_static(part.as_bytes())));
813            sent_tx.send(sent.map(|sent| sent.is_ok())).unwrap();
814            Ok::<_, ErrorObjectOwned>(())
815        });
816        let rp = MethodResponse::stream(Id::Number(1), stream, ok.len() - 2).await;
817        assert_eq!(rp.as_error_code(), Some(OVERSIZED_RESPONSE_CODE));
818        assert_eq!(sent_rx.recv().unwrap(), [true, false, false]);
819        // So is a part sent before the producer returns its future.
820        let stream = ResponseStream::new(|tx| {
821            let _ = tx.send(Bytes::from_static(b"[1,2]"));
822            async { Ok::<_, ErrorObjectOwned>(()) }
823        });
824        let rp = MethodResponse::stream(Id::Number(1), stream, ok.len() - 2).await;
825        assert_eq!(rp.as_error_code(), Some(OVERSIZED_RESPONSE_CODE));
826
827        // A panicking producer fails the result.
828        let panics = || -> Result<(), ErrorObjectOwned> { panic!("producer panicked") };
829        let stream = ResponseStream::new(move |_| async move { panics() });
830        let rp = MethodResponse::stream(Id::Number(1), stream, usize::MAX).await;
831        assert_eq!(rp.as_error_code(), Some(ErrorCode::InternalError.code()));
832    }
833
834    #[tokio::test]
835    async fn send_json_stops_at_limit() {
836        /// A list of 1000 numbers that counts how many of them were serialized.
837        struct Counted(Arc<AtomicUsize>);
838
839        impl Serialize for Counted {
840            fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
841                serializer.collect_seq((0..1000).inspect(|_| {
842                    self.0.fetch_add(1, Ordering::Relaxed);
843                }))
844            }
845        }
846
847        let serialized = Arc::new(AtomicUsize::new(0));
848        let counted = Counted(serialized.clone());
849        let stream = ResponseStream::new(move |sink| async move {
850            sink.send_json(b"", &counted).map_err(|_| ErrorCode::InternalError)
851        });
852        // The envelope leaves 30 bytes, so `[0,1,...,12` fits and `,13` crosses the limit.
853        let rp = MethodResponse::stream(Id::Number(1), stream, 64).await;
854        assert_eq!(rp.as_error_code(), Some(OVERSIZED_RESPONSE_CODE));
855        assert_eq!(serialized.load(Ordering::Relaxed), 14);
856    }
857
858    #[tokio::test]
859    async fn dropped_stream_closes_sender() {
860        let (closed_tx, closed_rx) = std::sync::mpsc::channel();
861        let stream = ResponseStream::new(move |tx| {
862            std::thread::spawn(move || {
863                while tx.send(Bytes::from(vec![b'0'; STREAM_THRESHOLD])).is_ok() {
864                    std::thread::sleep(std::time::Duration::from_millis(1));
865                }
866                closed_tx.send(()).unwrap();
867            });
868            std::future::pending::<Result<(), ErrorObjectOwned>>()
869        });
870        drop(MethodResponse::stream(Id::Number(1), stream, usize::MAX).await);
871        closed_rx.recv_timeout(std::time::Duration::from_secs(5)).unwrap();
872    }
873
874    #[test]
875    fn batch_with_single_works() {
876        let method = MethodResponse::response(
877            Id::Number(1),
878            ResponsePayload::success_borrowed(&"a"),
879            usize::MAX,
880        );
881        assert_eq!(method.json.len(), 37);
882
883        // Recall a batch appends two bytes for the `[]`.
884        let mut builder = BatchResponseBuilder::new_with_limit(39);
885        builder.append(method).unwrap();
886        let batch = builder.finish();
887
888        assert_eq!(batch.json, r#"[{"jsonrpc":"2.0","id":1,"result":"a"}]"#)
889    }
890
891    #[test]
892    fn batch_with_multiple_works() {
893        let m1 = MethodResponse::response(
894            Id::Number(1),
895            ResponsePayload::success_borrowed(&"a"),
896            usize::MAX,
897        );
898        let m11 = MethodResponse::response(
899            Id::Number(1),
900            ResponsePayload::success_borrowed(&"a"),
901            usize::MAX,
902        );
903        assert_eq!(m1.json.len(), 37);
904
905        // Recall a batch appends two bytes for the `[]` and one byte for `,` to append a method
906        // call. so it should be 2 + (37 * n) + (n-1)
907        let limit = 2 + (37 * 2) + 1;
908        let mut builder = BatchResponseBuilder::new_with_limit(limit);
909        builder.append(m1).unwrap();
910        builder.append(m11).unwrap();
911        let batch = builder.finish();
912
913        assert_eq!(
914            batch.json,
915            r#"[{"jsonrpc":"2.0","id":1,"result":"a"},{"jsonrpc":"2.0","id":1,"result":"a"}]"#
916        )
917    }
918
919    #[test]
920    fn batch_empty_err() {
921        let batch = BatchResponseBuilder::new_with_limit(1024).finish();
922
923        let exp_err =
924            r#"{"jsonrpc":"2.0","id":null,"error":{"code":-32600,"message":"Invalid request"}}"#;
925        assert_eq!(batch.json, exp_err);
926    }
927
928    #[test]
929    fn batch_too_big() {
930        let method = MethodResponse::response(
931            Id::Number(1),
932            ResponsePayload::success_borrowed(&"a".repeat(28)),
933            128,
934        );
935        assert_eq!(method.json.len(), 64);
936
937        let batch = BatchResponseBuilder::new_with_limit(63).append(method).unwrap_err();
938
939        let exp_err = r#"{"jsonrpc":"2.0","id":null,"error":{"code":-32011,"message":"The batch response was too large","data":"Exceeded max limit of 63"}}"#;
940        assert_eq!(batch.json, exp_err);
941    }
942
943    #[test]
944    fn bounded_serializer_work() {
945        use jsonrpsee_types::{Response, ResponsePayload};
946
947        let mut writer = BoundedWriter::new(100, 128);
948        let result = ResponsePayload::success(&"success");
949        let rp = &Response::new(result, Id::Number(1));
950
951        assert!(serde_json::to_writer(&mut writer, rp).is_ok());
952        assert_eq!(
953            String::from_utf8(writer.into_bytes()).unwrap(),
954            r#"{"jsonrpc":"2.0","id":1,"result":"success"}"#
955        );
956    }
957
958    #[test]
959    fn bounded_serializer_cap_works() {
960        let mut writer = BoundedWriter::new(100, 128);
961        // NOTE: `"` is part of the serialization so 101 characters.
962        assert!(serde_json::to_writer(&mut writer, &"x".repeat(99)).is_err());
963    }
964
965    /// Serializes `rp` like a method registered on a module.
966    fn sized_response<T: Serialize + Clone>(
967        rp: ResponsePayload<'_, T>,
968        hint: &ResponseSizeHint,
969    ) -> MethodResponse {
970        MethodResponse::sized_response(Id::Number(1), rp, usize::MAX, hint)
971    }
972
973    fn success<T: Clone>(result: &T) -> ResponsePayload<'_, T> {
974        ResponsePayload::success_borrowed(result)
975    }
976
977    #[test]
978    fn size_hint_is_capped_and_small_responses_shrink() {
979        let hint = ResponseSizeHint::new();
980        let big = "x".repeat(MAX_RESPONSE_SIZE_HINT);
981        let rp = sized_response(success(&big), &hint);
982        assert!(rp.json.len() > MAX_RESPONSE_SIZE_HINT);
983        assert_eq!(hint.0.load(Ordering::Relaxed), MAX_RESPONSE_SIZE_HINT);
984        assert_eq!(hint.capacity(), MAX_RESPONSE_SIZE_HINT);
985
986        let rp = sized_response(success(&"a"), &hint);
987        assert_eq!(rp.json, r#"{"jsonrpc":"2.0","id":1,"result":"a"}"#);
988        assert!(rp.json.capacity() < 2 * rp.json.len());
989    }
990
991    #[test]
992    fn size_hint_survives_errors_and_null() {
993        let hint = ResponseSizeHint::new();
994        let big = "x".repeat(100_000);
995        let big_len = sized_response(success(&big), &hint).json.len();
996
997        let rp = sized_response(ResponsePayload::<()>::error(ErrorCode::InternalError), &hint);
998        assert_eq!(rp.as_error_code(), Some(ErrorCode::InternalError.code()));
999        let rp = sized_response(success(&None::<u64>), &hint);
1000        assert_eq!(rp.json, r#"{"jsonrpc":"2.0","id":1,"result":null}"#);
1001
1002        let reserved = hint.capacity();
1003        assert!(reserved >= big_len, "reserved {reserved} for {big_len} bytes");
1004        let rp = sized_response(success(&big), &hint);
1005        // Growing the buffer would at least double it.
1006        assert!(rp.json.capacity() < 2 * reserved);
1007    }
1008
1009    #[test]
1010    fn errors_do_not_reserve_the_hint() {
1011        let hint = ResponseSizeHint::new();
1012        sized_response(success(&"x".repeat(8 * 1024)), &hint);
1013
1014        let rp = sized_response(ResponsePayload::<()>::error(ErrorCode::InternalError), &hint);
1015        assert!(rp.json.capacity() < hint.capacity());
1016    }
1017
1018    #[test]
1019    fn oversized_response_does_not_change_the_hint() {
1020        let hint = ResponseSizeHint::new();
1021        let rp =
1022            MethodResponse::sized_response(Id::Number(1), success(&"x".repeat(100)), 64, &hint);
1023        assert_eq!(rp.as_error_code(), Some(OVERSIZED_RESPONSE_CODE));
1024        assert_eq!(
1025            hint.0.load(Ordering::Relaxed),
1026            ResponseSizeHint::new().0.load(Ordering::Relaxed)
1027        );
1028    }
1029
1030    #[test]
1031    fn slightly_larger_response_fits_the_reserved_buffer() {
1032        let hint = ResponseSizeHint::new();
1033        sized_response(success(&"x".repeat(100_000)), &hint);
1034
1035        let reserved = hint.capacity();
1036        let rp = sized_response(success(&"x".repeat(110_000)), &hint);
1037        // Growing the buffer would at least double it.
1038        assert!(rp.json.capacity() < 2 * reserved);
1039    }
1040
1041    #[test]
1042    fn size_hint_decays_to_smaller_responses() {
1043        let hint = ResponseSizeHint::new();
1044        sized_response(success(&"x".repeat(100_000)), &hint);
1045
1046        let small = sized_response(success(&"a"), &hint).json.len();
1047        assert!(hint.0.load(Ordering::Relaxed) > 80_000);
1048        for _ in 0..100 {
1049            sized_response(success(&"a"), &hint);
1050        }
1051        assert_eq!(hint.0.load(Ordering::Relaxed), small);
1052    }
1053
1054    #[test]
1055    fn small_unused_capacity_is_not_shrunk() {
1056        let hint = ResponseSizeHint::new();
1057        sized_response(success(&"x".repeat(8 * 1024)), &hint);
1058
1059        let reserved = hint.capacity();
1060        let rp = sized_response(success(&"a"), &hint);
1061        // Most of the buffer is unused, but too little to be worth reallocating.
1062        assert!(rp.json.capacity() >= reserved);
1063    }
1064}