simplejrpc 0.1.0

Unix-socket JSON-RPC 2.0 SDK with middleware, config, and validation
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
//! VSCode / LSP style `Content-Length` framing (compatible with Go `VSCodeObjectCodec`).
//!
//! # Wire format
//!
//! ```text
//! Content-Length: 32\r\n
//! \r\n
//! {"jsonrpc":"2.0","id":1,...}
//! ```
//!
//! Frames larger than [`DEFAULT_MAX_FRAME_LEN`] (16 MiB) are rejected to avoid
//! unbounded allocation from a malicious peer. Override with
//! [`FrameReader::with_max_frame_len`] or [`decode_frame_limited`] when needed.
//!
//! # Examples
//!
//! ```
//! use simplejrpc::codec::{encode_frame, decode_frame, FrameReader};
//!
//! let body = br#"{"jsonrpc":"2.0","id":1,"method":"ping"}"#;
//! let framed = encode_frame(body);
//! assert_eq!(decode_frame(&framed).unwrap(), body);
//!
//! // Incremental (split TCP/UDS reads)
//! let mut r = FrameReader::new();
//! r.push(&framed[..8]);
//! assert!(r.try_next().unwrap().is_none());
//! r.push(&framed[8..]);
//! assert_eq!(r.try_next().unwrap().unwrap(), body);
//! ```

use crate::error::{Error, Result};

const HEADER_SEP: &[u8] = b"\r\n\r\n"; // end of LSP-style header block

/// Default maximum JSON-RPC body size accepted by the codec (16 MiB).
///
/// # Examples
///
/// ```
/// use simplejrpc::codec::DEFAULT_MAX_FRAME_LEN;
/// assert_eq!(DEFAULT_MAX_FRAME_LEN, 16 * 1024 * 1024);
/// ```
pub const DEFAULT_MAX_FRAME_LEN: usize = 16 * 1024 * 1024;

/// Encode a JSON body into a framed message.
///
/// # Examples
///
/// ```
/// use simplejrpc::codec::encode_frame;
/// let framed = encode_frame(b"{}");
/// assert!(framed.starts_with(b"Content-Length:"));
/// ```
pub fn encode_frame(body: &[u8]) -> Vec<u8> {
    let header = format!("Content-Length: {}\r\n\r\n", body.len());
    let mut out = Vec::with_capacity(header.len() + body.len());
    out.extend_from_slice(header.as_bytes());
    out.extend_from_slice(body);
    out
}

/// Decode one framed message from a buffer that **starts** at a frame boundary.
///
/// Returns the JSON body bytes (without headers).
/// Uses [`DEFAULT_MAX_FRAME_LEN`] as the size limit.
///
/// # Examples
///
/// ```
/// use simplejrpc::codec::{encode_frame, decode_frame};
/// let framed = encode_frame(b"hi");
/// assert_eq!(decode_frame(&framed).unwrap(), b"hi");
/// ```
pub fn decode_frame(buf: &[u8]) -> Result<Vec<u8>> {
    decode_frame_limited(buf, DEFAULT_MAX_FRAME_LEN)
}

/// Decode one framed message with an explicit body size limit.
///
/// # Examples
///
/// ```
/// use simplejrpc::codec::{encode_frame, decode_frame_limited};
/// let framed = encode_frame(b"abc");
/// assert!(decode_frame_limited(&framed, 2).is_err()); // body len 3 > max 2
/// assert_eq!(decode_frame_limited(&framed, 3).unwrap(), b"abc");
/// ```
pub fn decode_frame_limited(buf: &[u8], max_frame_len: usize) -> Result<Vec<u8>> {
    let sep = buf
        .windows(HEADER_SEP.len())
        .position(|w| w == HEADER_SEP)
        .ok_or_else(|| Error::Protocol("missing header terminator".into()))?;

    let header = std::str::from_utf8(&buf[..sep])
        .map_err(|e| Error::Protocol(format!("invalid header utf8: {e}")))?;

    let len = parse_content_length(header)?;
    ensure_frame_len(len, max_frame_len)?;

    let body_start = sep + HEADER_SEP.len();
    let body_end = body_start
        .checked_add(len)
        .ok_or_else(|| Error::Protocol("content length overflow".into()))?;
    if body_end > buf.len() {
        return Err(Error::Protocol(format!(
            "incomplete body: need {len}, have {}",
            buf.len().saturating_sub(body_start)
        )));
    }
    Ok(buf[body_start..body_end].to_vec())
}

fn parse_content_length(header: &str) -> Result<usize> {
    // Accept multi-line headers; ignore unknown keys; require Content-Length.
    let mut content_length: Option<usize> = None;
    for line in header.split("\r\n") {
        let line = line.trim();
        if line.is_empty() {
            continue;
        }
        let Some((k, v)) = line.split_once(':') else {
            continue;
        };
        if k.eq_ignore_ascii_case("Content-Length") {
            content_length = Some(
                v.trim()
                    .parse()
                    .map_err(|_| Error::Protocol(format!("bad Content-Length: {v}")))?,
            );
        }
    }
    content_length.ok_or_else(|| Error::Protocol("Content-Length header required".into()))
}

fn ensure_frame_len(len: usize, max_frame_len: usize) -> Result<()> {
    if len > max_frame_len {
        return Err(Error::Protocol(format!(
            "frame too large: {len} > max {max_frame_len}"
        )));
    }
    Ok(())
}

/// Read access to a frame buffer / size limit.
///
/// # Examples
///
/// ```
/// use simplejrpc::codec::{FrameReader, FrameReaderView};
/// let r = FrameReader::with_max_frame_len(64);
/// assert_eq!(FrameReaderView::max_frame_len(&r), 64);
/// assert_eq!(FrameReaderView::buffered_len(&r), 0);
/// ```
pub trait FrameReaderView: Send + Sync {
    /// Maximum accepted body size in bytes.
    fn max_frame_len(&self) -> usize;
    /// Bytes currently buffered (incomplete frame and/or leftovers).
    fn buffer(&self) -> &[u8];

    /// Length of [`Self::buffer`].
    fn buffered_len(&self) -> usize {
        self.buffer().len()
    }
}

/// Push bytes and extract frames. Override [`Self::try_next`] for custom checks.
///
/// Default [`Self::try_next`] implements the standard `Content-Length` codec.
/// Override in application wrappers to harden, metrics, or alternate framing.
///
/// # Examples
///
/// Reject empty JSON bodies after a successful parse:
///
/// ```
/// use simplejrpc::codec::{
///     encode_frame, FrameReader, FrameReaderMut, FrameReaderView,
/// };
/// use simplejrpc::error::{Error, Result};
///
/// struct NoEmpty(FrameReader);
///
/// impl FrameReaderView for NoEmpty {
///     fn max_frame_len(&self) -> usize { FrameReaderView::max_frame_len(&self.0) }
///     fn buffer(&self) -> &[u8] { FrameReaderView::buffer(&self.0) }
/// }
///
/// impl FrameReaderMut for NoEmpty {
///     fn buffer_mut(&mut self) -> &mut Vec<u8> { FrameReaderMut::buffer_mut(&mut self.0) }
///     fn set_max_frame_len(&mut self, max: usize) {
///         FrameReaderMut::set_max_frame_len(&mut self.0, max)
///     }
///     fn try_next(&mut self) -> Result<Option<Vec<u8>>> {
///         match FrameReaderMut::try_next(&mut self.0)? {
///             Some(body) if body.is_empty() => {
///                 Err(Error::Protocol("empty body rejected".into()))
///             }
///             other => Ok(other),
///         }
///     }
/// }
///
/// let mut r = NoEmpty(FrameReader::new());
/// FrameReaderMut::push(&mut r, &encode_frame(b""));
/// assert!(FrameReaderMut::try_next(&mut r).is_err());
/// ```
pub trait FrameReaderMut: FrameReaderView {
    /// Mutable access to the internal byte buffer.
    fn buffer_mut(&mut self) -> &mut Vec<u8>;
    /// Replace the maximum body size.
    fn set_max_frame_len(&mut self, max: usize);

    /// Append bytes from the socket into the internal buffer.
    fn push(&mut self, data: &[u8]) {
        self.buffer_mut().extend_from_slice(data);
    }

    /// Drop all buffered bytes.
    fn clear(&mut self) {
        self.buffer_mut().clear();
    }

    /// Try to pop one complete frame body.
    ///
    /// Returns:
    /// - `Ok(None)` — need more bytes
    /// - `Ok(Some(body))` — one complete JSON body
    /// - `Err(_)` — protocol / size violation
    fn try_next(&mut self) -> Result<Option<Vec<u8>>> {
        let max = self.max_frame_len();
        try_next_frame(self.buffer_mut(), max)
    }
}

fn try_next_frame(buf: &mut Vec<u8>, max_frame_len: usize) -> Result<Option<Vec<u8>>> {
    // Ok(None) = need more bytes; Ok(Some) drains one complete frame from `buf`.
    let sep = match buf.windows(HEADER_SEP.len()).position(|w| w == HEADER_SEP) {
        Some(p) => p,
        None => return Ok(None),
    };

    let header = std::str::from_utf8(&buf[..sep])
        .map_err(|e| Error::Protocol(format!("invalid header utf8: {e}")))?;

    let len = parse_content_length(header)?;
    ensure_frame_len(len, max_frame_len)?;

    let body_start = sep + HEADER_SEP.len();
    let body_end = body_start
        .checked_add(len)
        .ok_or_else(|| Error::Protocol("content length overflow".into()))?;
    if buf.len() < body_end {
        return Ok(None);
    }

    let body = buf[body_start..body_end].to_vec();
    buf.drain(..body_end);
    Ok(Some(body))
}

/// Incremental reader for async byte streams (TCP/UDS chunked reads).
///
/// Call [`Self::push`] for each read, then [`Self::try_next`] until it returns
/// `Ok(None)` (need more bytes) or `Ok(Some(body))`.
///
/// Implements [`FrameReaderView`] / [`FrameReaderMut`] for custom framing wrappers.
///
/// # Examples
///
/// ```
/// use simplejrpc::codec::{encode_frame, FrameReader};
/// let mut r = FrameReader::new();
/// let framed = encode_frame(b"{}");
/// r.push(&framed);
/// assert_eq!(r.try_next().unwrap().unwrap(), b"{}");
/// ```
#[derive(Debug)]
pub struct FrameReader {
    buf: Vec<u8>,
    max_frame_len: usize,
}

impl Default for FrameReader {
    fn default() -> Self {
        Self::new()
    }
}

impl FrameReader {
    /// Create a reader with [`DEFAULT_MAX_FRAME_LEN`].
    ///
    /// # Examples
    ///
    /// ```
    /// use simplejrpc::codec::FrameReader;
    /// let _ = FrameReader::new();
    /// ```
    pub fn new() -> Self {
        Self::from_parts(Vec::new(), DEFAULT_MAX_FRAME_LEN)
    }

    /// Create a reader with a custom maximum body size (bytes).
    ///
    /// # Examples
    ///
    /// ```
    /// use simplejrpc::codec::{encode_frame, FrameReader};
    /// let mut r = FrameReader::with_max_frame_len(4);
    /// r.push(&encode_frame(b"12345"));
    /// assert!(r.try_next().is_err());
    /// ```
    pub fn with_max_frame_len(max_frame_len: usize) -> Self {
        Self::from_parts(Vec::new(), max_frame_len)
    }

    /// Build from raw parts.
    ///
    /// # Examples
    ///
    /// ```
    /// use simplejrpc::codec::{FrameReader, DEFAULT_MAX_FRAME_LEN};
    /// let r = FrameReader::from_parts(Vec::new(), DEFAULT_MAX_FRAME_LEN);
    /// assert_eq!(r.buffered_len(), 0);
    /// ```
    pub fn from_parts(buf: Vec<u8>, max_frame_len: usize) -> Self {
        Self { buf, max_frame_len }
    }

    /// Split into raw parts (pair with [`Self::from_parts`]).
    ///
    /// # Examples
    ///
    /// ```
    /// use simplejrpc::codec::FrameReader;
    /// let (buf, max) = FrameReader::with_max_frame_len(8).into_parts();
    /// assert!(buf.is_empty());
    /// assert_eq!(max, 8);
    /// ```
    pub fn into_parts(self) -> (Vec<u8>, usize) {
        (self.buf, self.max_frame_len)
    }

    /// Maximum accepted body size in bytes.
    ///
    /// # Examples
    ///
    /// ```
    /// use simplejrpc::codec::{FrameReader, DEFAULT_MAX_FRAME_LEN};
    /// assert_eq!(FrameReader::new().max_frame_len(), DEFAULT_MAX_FRAME_LEN);
    /// ```
    pub fn max_frame_len(&self) -> usize {
        FrameReaderView::max_frame_len(self)
    }

    /// Bytes currently buffered.
    ///
    /// # Examples
    ///
    /// ```
    /// use simplejrpc::codec::FrameReader;
    /// assert_eq!(FrameReader::new().buffered_len(), 0);
    /// ```
    pub fn buffered_len(&self) -> usize {
        FrameReaderView::buffered_len(self)
    }

    /// Append bytes from the socket into the internal buffer.
    ///
    /// # Examples
    ///
    /// ```
    /// use simplejrpc::codec::FrameReader;
    /// let mut r = FrameReader::new();
    /// r.push(b"Content-Length: ");
    /// ```
    pub fn push(&mut self, data: &[u8]) {
        FrameReaderMut::push(self, data)
    }

    /// Drop all buffered bytes.
    ///
    /// # Examples
    ///
    /// ```
    /// use simplejrpc::codec::FrameReader;
    /// let mut r = FrameReader::new();
    /// r.push(b"x");
    /// r.clear();
    /// assert_eq!(r.buffered_len(), 0);
    /// ```
    pub fn clear(&mut self) {
        FrameReaderMut::clear(self)
    }

    /// Try to pop one complete frame body.
    ///
    /// Returns:
    /// - `Ok(None)` — need more bytes
    /// - `Ok(Some(body))` — one complete JSON body
    /// - `Err(_)` — protocol / size violation
    ///
    /// # Examples
    ///
    /// ```
    /// use simplejrpc::codec::{encode_frame, FrameReader};
    /// let mut r = FrameReader::new();
    /// let f = encode_frame(b"x");
    /// r.push(&f[..3]);
    /// assert!(r.try_next().unwrap().is_none());
    /// r.push(&f[3..]);
    /// assert_eq!(r.try_next().unwrap().unwrap(), b"x");
    /// ```
    pub fn try_next(&mut self) -> Result<Option<Vec<u8>>> {
        FrameReaderMut::try_next(self)
    }
}

impl FrameReaderView for FrameReader {
    fn max_frame_len(&self) -> usize {
        self.max_frame_len
    }

    fn buffer(&self) -> &[u8] {
        &self.buf
    }
}

impl FrameReaderMut for FrameReader {
    fn buffer_mut(&mut self) -> &mut Vec<u8> {
        &mut self.buf
    }

    fn set_max_frame_len(&mut self, max: usize) {
        self.max_frame_len = max;
    }
}