Skip to main content

hyperlane_plugin_rpc/
impl.rs

1use super::*;
2
3/// Implements [`Hasher`] for [`FxHasher`] with zero heap allocations and 8-byte word mixing.
4impl Hasher for FxHasher {
5    /// Finalizes the 64-bit hash state.
6    ///
7    /// # Returns
8    ///
9    /// - `u64` - Finalized 64-bit hash.
10    #[inline(always)]
11    fn finish(&self) -> u64 {
12        let Self { state } = *self;
13        state
14    }
15
16    /// Mixes `bytes` into the hash state 8 bytes at a time without heap allocation.
17    ///
18    /// # Arguments
19    ///
20    /// - `&[u8]` - Input byte slice.
21    #[inline(always)]
22    fn write(&mut self, bytes: &[u8]) {
23        let Self { state } = self;
24        let mut h: u64 = *state;
25        let (chunks, rem): (&[[u8; 8]], &[u8]) = bytes.as_chunks::<8>();
26        for chunk in chunks {
27            h = (h.rotate_left(5) ^ u64::from_ne_bytes(*chunk)).wrapping_mul(FX_HASH_K);
28        }
29        let mut tail: &[u8] = rem;
30        if tail.len() >= 4 {
31            let word: u32 = u32::from_ne_bytes([tail[0], tail[1], tail[2], tail[3]]);
32            h = (h.rotate_left(5) ^ u64::from(word)).wrapping_mul(FX_HASH_K);
33            tail = &tail[4..];
34        }
35        if tail.len() >= 2 {
36            let half: u16 = u16::from_ne_bytes([tail[0], tail[1]]);
37            h = (h.rotate_left(5) ^ u64::from(half)).wrapping_mul(FX_HASH_K);
38            tail = &tail[2..];
39        }
40        if let Some(&b) = tail.first() {
41            h = (h.rotate_left(5) ^ u64::from(b)).wrapping_mul(FX_HASH_K);
42        }
43        *state = h;
44    }
45
46    /// Mixes a single `u8` byte directly into the hash state.
47    ///
48    /// # Arguments
49    ///
50    /// - `u8` - Input byte.
51    #[inline(always)]
52    fn write_u8(&mut self, i: u8) {
53        let Self { state } = self;
54        *state = (state.rotate_left(5) ^ u64::from(i)).wrapping_mul(FX_HASH_K);
55    }
56}
57
58/// Implements [`Visitor`] for [`RpcFieldKeyVisitor`] without string allocation.
59impl<'de> Visitor<'de> for RpcFieldKeyVisitor {
60    type Value = RpcFieldKey;
61
62    /// Describes the expected JSON-RPC field key for diagnostics.
63    ///
64    /// # Arguments
65    ///
66    /// - `&mut Formatter<'_>` - Output formatter.
67    ///
68    /// # Returns
69    ///
70    /// - `fmt::Result` - Formatting outcome.
71    fn expecting(&self, formatter: &mut Formatter<'_>) -> fmt::Result {
72        formatter.write_str(EXPECT_FIELD_KEY)
73    }
74
75    /// Maps a field name slice directly to [`RpcFieldKey`].
76    ///
77    /// # Arguments
78    ///
79    /// - `&str` - Field key string slice.
80    ///
81    /// # Returns
82    ///
83    /// - `Result<Self::Value, E>` - Matched field key variant.
84    #[inline(always)]
85    fn visit_str<E>(self, v: &str) -> Result<Self::Value, E>
86    where
87        E: de::Error,
88    {
89        Ok(match v {
90            FIELD_JSONRPC => RpcFieldKey::Jsonrpc,
91            FIELD_METHOD => RpcFieldKey::Method,
92            FIELD_PARAMS => RpcFieldKey::Params,
93            FIELD_ID => RpcFieldKey::Id,
94            _ => RpcFieldKey::Other,
95        })
96    }
97}
98
99/// Zero-copy [`Deserialize`] implementation for [`RpcFieldKey`].
100impl<'de> Deserialize<'de> for RpcFieldKey {
101    /// Deserializes an object key identifier directly via [`RpcFieldKeyVisitor`].
102    ///
103    /// # Arguments
104    ///
105    /// - `D` - Serde deserializer.
106    ///
107    /// # Returns
108    ///
109    /// - `Result<Self, D::Error>` - Parsed key variant.
110    #[inline(always)]
111    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
112    where
113        D: Deserializer<'de>,
114    {
115        deserializer.deserialize_identifier(RpcFieldKeyVisitor)
116    }
117}
118
119/// Implements [`Visitor`] for [`LenientStrVisitor`], borrowing escape-free strings and discarding mismatched JSON types.
120impl<'de> Visitor<'de> for LenientStrVisitor {
121    type Value = LenientStr<'de>;
122
123    /// Describes the expected JSON value for diagnostics.
124    ///
125    /// # Arguments
126    ///
127    /// - `&mut Formatter<'_>` - Output formatter.
128    ///
129    /// # Returns
130    ///
131    /// - `fmt::Result` - Formatting outcome.
132    fn expecting(&self, formatter: &mut Formatter<'_>) -> fmt::Result {
133        formatter.write_str(EXPECT_LENIENT_STR)
134    }
135
136    /// Borrows an unescaped JSON string directly from the input buffer.
137    ///
138    /// # Arguments
139    ///
140    /// - `&'de str` - Borrowed string slice.
141    ///
142    /// # Returns
143    ///
144    /// - `Result<Self::Value, E>` - Valid borrowed string.
145    #[inline(always)]
146    fn visit_borrowed_str<E>(self, v: &'de str) -> Result<Self::Value, E>
147    where
148        E: de::Error,
149    {
150        Ok(LenientStr::Valid(Cow::Borrowed(v)))
151    }
152
153    /// Clones a transient string slice when escaping required decoding.
154    ///
155    /// # Arguments
156    ///
157    /// - `&str` - Decoded string slice.
158    ///
159    /// # Returns
160    ///
161    /// - `Result<Self::Value, E>` - Valid owned string.
162    #[inline]
163    fn visit_str<E>(self, v: &str) -> Result<Self::Value, E>
164    where
165        E: de::Error,
166    {
167        Ok(LenientStr::Valid(Cow::Owned(v.to_owned())))
168    }
169
170    /// Takes ownership of an already-allocated string.
171    ///
172    /// # Arguments
173    ///
174    /// - `String` - Decoded owned string.
175    ///
176    /// # Returns
177    ///
178    /// - `Result<Self::Value, E>` - Valid owned string.
179    #[inline]
180    fn visit_string<E>(self, v: String) -> Result<Self::Value, E>
181    where
182        E: de::Error,
183    {
184        Ok(LenientStr::Valid(Cow::Owned(v)))
185    }
186
187    /// Marks boolean field values invalid.
188    ///
189    /// # Arguments
190    ///
191    /// - `bool` - Ignored boolean.
192    ///
193    /// # Returns
194    ///
195    /// - `Result<Self::Value, E>` - Always `Invalid`.
196    fn visit_bool<E>(self, _: bool) -> Result<Self::Value, E>
197    where
198        E: de::Error,
199    {
200        Ok(LenientStr::Invalid)
201    }
202
203    /// Marks signed integer field values invalid.
204    ///
205    /// # Arguments
206    ///
207    /// - `i64` - Ignored integer.
208    ///
209    /// # Returns
210    ///
211    /// - `Result<Self::Value, E>` - Always `Invalid`.
212    fn visit_i64<E>(self, _: i64) -> Result<Self::Value, E>
213    where
214        E: de::Error,
215    {
216        Ok(LenientStr::Invalid)
217    }
218
219    /// Marks unsigned integer field values invalid.
220    ///
221    /// # Arguments
222    ///
223    /// - `u64` - Ignored integer.
224    ///
225    /// # Returns
226    ///
227    /// - `Result<Self::Value, E>` - Always `Invalid`.
228    fn visit_u64<E>(self, _: u64) -> Result<Self::Value, E>
229    where
230        E: de::Error,
231    {
232        Ok(LenientStr::Invalid)
233    }
234
235    /// Marks floating-point field values invalid.
236    ///
237    /// # Arguments
238    ///
239    /// - `f64` - Ignored float.
240    ///
241    /// # Returns
242    ///
243    /// - `Result<Self::Value, E>` - Always `Invalid`.
244    fn visit_f64<E>(self, _: f64) -> Result<Self::Value, E>
245    where
246        E: de::Error,
247    {
248        Ok(LenientStr::Invalid)
249    }
250
251    /// Accepts JSON `null` matching `Option<Cow<'de, str>>` semantics while preserving correlation `id`.
252    ///
253    /// # Returns
254    ///
255    /// - `Result<Self::Value, E>` - Always `Null`.
256    fn visit_unit<E>(self) -> Result<Self::Value, E>
257    where
258        E: de::Error,
259    {
260        Ok(LenientStr::Null)
261    }
262
263    /// Drains an unexpected JSON array and marks the field invalid.
264    ///
265    /// # Arguments
266    ///
267    /// - `A` - Sequence access.
268    ///
269    /// # Returns
270    ///
271    /// - `Result<Self::Value, A::Error>` - Always `Invalid`.
272    fn visit_seq<A>(self, mut seq: A) -> Result<Self::Value, A::Error>
273    where
274        A: SeqAccess<'de>,
275    {
276        while seq.next_element::<IgnoredAny>()?.is_some() {}
277        Ok(LenientStr::Invalid)
278    }
279
280    /// Drains an unexpected JSON object and marks the field invalid.
281    ///
282    /// # Arguments
283    ///
284    /// - `A` - Map access.
285    ///
286    /// # Returns
287    ///
288    /// - `Result<Self::Value, A::Error>` - Always `Invalid`.
289    fn visit_map<A>(self, mut map: A) -> Result<Self::Value, A::Error>
290    where
291        A: MapAccess<'de>,
292    {
293        while map.next_entry::<IgnoredAny, IgnoredAny>()?.is_some() {}
294        Ok(LenientStr::Invalid)
295    }
296}
297
298/// Streaming [`Deserialize`] implementation for [`LenientStr`].
299impl<'de> Deserialize<'de> for LenientStr<'de> {
300    /// Deserializes a JSON string or discards a wrong JSON type in one pass.
301    ///
302    /// # Arguments
303    ///
304    /// - `D` - Serde deserializer.
305    ///
306    /// # Returns
307    ///
308    /// - `Result<Self, D::Error>` - Parsed lenient string outcome.
309    #[inline(always)]
310    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
311    where
312        D: Deserializer<'de>,
313    {
314        deserializer.deserialize_any(LenientStrVisitor)
315    }
316}
317
318/// Implements [`Visitor`] for [`LenientIdVisitor`] without `#[serde(untagged)]` content buffering.
319impl<'de> Visitor<'de> for LenientIdVisitor {
320    type Value = LenientId;
321
322    /// Describes the expected JSON-RPC correlation id for diagnostics.
323    ///
324    /// # Arguments
325    ///
326    /// - `&mut Formatter<'_>` - Output formatter.
327    ///
328    /// # Returns
329    ///
330    /// - `fmt::Result` - Formatting outcome.
331    fn expecting(&self, formatter: &mut Formatter<'_>) -> fmt::Result {
332        formatter.write_str(EXPECT_RPC_ID)
333    }
334
335    /// Accepts a signed integer correlation id directly.
336    ///
337    /// # Arguments
338    ///
339    /// - `i64` - Signed integer id.
340    ///
341    /// # Returns
342    ///
343    /// - `Result<Self::Value, E>` - Valid numeric id.
344    #[inline(always)]
345    fn visit_i64<E>(self, v: i64) -> Result<Self::Value, E>
346    where
347        E: de::Error,
348    {
349        Ok(LenientId::Valid(Some(RpcId::Number(v))))
350    }
351
352    /// Accepts an unsigned integer correlation id when representable as `i64`.
353    ///
354    /// # Arguments
355    ///
356    /// - `u64` - Unsigned integer id.
357    ///
358    /// # Returns
359    ///
360    /// - `Result<Self::Value, E>` - Valid numeric id or `Invalid` on overflow.
361    #[inline(always)]
362    fn visit_u64<E>(self, v: u64) -> Result<Self::Value, E>
363    where
364        E: de::Error,
365    {
366        Ok(match i64::try_from(v) {
367            Ok(n) => LenientId::Valid(Some(RpcId::Number(n))),
368            Err(_) => LenientId::Invalid,
369        })
370    }
371
372    /// Accepts a string correlation id.
373    ///
374    /// # Arguments
375    ///
376    /// - `&str` - String id slice.
377    ///
378    /// # Returns
379    ///
380    /// - `Result<Self::Value, E>` - Valid text id.
381    #[inline]
382    fn visit_str<E>(self, v: &str) -> Result<Self::Value, E>
383    where
384        E: de::Error,
385    {
386        Ok(LenientId::Valid(Some(RpcId::Text(v.to_owned()))))
387    }
388
389    /// Accepts an owned string correlation id without re-cloning.
390    ///
391    /// # Arguments
392    ///
393    /// - `String` - Owned string id.
394    ///
395    /// # Returns
396    ///
397    /// - `Result<Self::Value, E>` - Valid text id.
398    #[inline]
399    fn visit_string<E>(self, v: String) -> Result<Self::Value, E>
400    where
401        E: de::Error,
402    {
403        Ok(LenientId::Valid(Some(RpcId::Text(v))))
404    }
405
406    /// Accepts explicit JSON `null` matching `Option<RpcId>` notification semantics.
407    ///
408    /// # Returns
409    ///
410    /// - `Result<Self::Value, E>` - `Valid(None)`.
411    #[inline(always)]
412    fn visit_unit<E>(self) -> Result<Self::Value, E>
413    where
414        E: de::Error,
415    {
416        Ok(LenientId::Valid(None))
417    }
418
419    /// Marks boolean ids invalid.
420    ///
421    /// # Arguments
422    ///
423    /// - `bool` - Ignored boolean.
424    ///
425    /// # Returns
426    ///
427    /// - `Result<Self::Value, E>` - Always `Invalid`.
428    fn visit_bool<E>(self, _: bool) -> Result<Self::Value, E>
429    where
430        E: de::Error,
431    {
432        Ok(LenientId::Invalid)
433    }
434
435    /// Marks floating-point ids invalid.
436    ///
437    /// # Arguments
438    ///
439    /// - `f64` - Ignored float.
440    ///
441    /// # Returns
442    ///
443    /// - `Result<Self::Value, E>` - Always `Invalid`.
444    fn visit_f64<E>(self, _: f64) -> Result<Self::Value, E>
445    where
446        E: de::Error,
447    {
448        Ok(LenientId::Invalid)
449    }
450
451    /// Drains an unexpected JSON array id and marks it invalid.
452    ///
453    /// # Arguments
454    ///
455    /// - `A` - Sequence access.
456    ///
457    /// # Returns
458    ///
459    /// - `Result<Self::Value, A::Error>` - Always `Invalid`.
460    fn visit_seq<A>(self, mut seq: A) -> Result<Self::Value, A::Error>
461    where
462        A: SeqAccess<'de>,
463    {
464        while seq.next_element::<IgnoredAny>()?.is_some() {}
465        Ok(LenientId::Invalid)
466    }
467
468    /// Drains an unexpected JSON object id and marks it invalid.
469    ///
470    /// # Arguments
471    ///
472    /// - `A` - Map access.
473    ///
474    /// # Returns
475    ///
476    /// - `Result<Self::Value, A::Error>` - Always `Invalid`.
477    fn visit_map<A>(self, mut map: A) -> Result<Self::Value, A::Error>
478    where
479        A: MapAccess<'de>,
480    {
481        while map.next_entry::<IgnoredAny, IgnoredAny>()?.is_some() {}
482        Ok(LenientId::Invalid)
483    }
484}
485
486/// Streaming [`Deserialize`] implementation for [`LenientId`].
487impl<'de> Deserialize<'de> for LenientId {
488    /// Deserializes a JSON-RPC correlation id directly via [`LenientIdVisitor`].
489    ///
490    /// # Arguments
491    ///
492    /// - `D` - Serde deserializer.
493    ///
494    /// # Returns
495    ///
496    /// - `Result<Self, D::Error>` - Parsed lenient id outcome.
497    #[inline(always)]
498    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
499    where
500        D: Deserializer<'de>,
501    {
502        deserializer.deserialize_any(LenientIdVisitor)
503    }
504}
505
506/// Implements single-pass streaming [`Visitor`] for [`BorrowedBatchItemVisitor`].
507impl<'de> Visitor<'de> for BorrowedBatchItemVisitor {
508    type Value = BorrowedBatchItem<'de>;
509
510    /// Describes the expected JSON-RPC request item for diagnostics.
511    ///
512    /// # Arguments
513    ///
514    /// - `&mut Formatter<'_>` - Output formatter.
515    ///
516    /// # Returns
517    ///
518    /// - `fmt::Result` - Formatting outcome.
519    fn expecting(&self, formatter: &mut Formatter<'_>) -> fmt::Result {
520        formatter.write_str(EXPECT_BATCH_ITEM)
521    }
522
523    /// Streams a JSON object directly into [`BorrowedRpcRequest`] without intermediate buffering.
524    ///
525    /// # Arguments
526    ///
527    /// - `A` - Serde map access.
528    ///
529    /// # Returns
530    ///
531    /// - `Result<Self::Value, A::Error>` - Parsed request or `Invalid` on field type mismatch.
532    #[inline]
533    fn visit_map<A>(self, mut map: A) -> Result<Self::Value, A::Error>
534    where
535        A: MapAccess<'de>,
536    {
537        let mut jsonrpc: Option<Cow<'de, str>> = None;
538        let mut method: Option<Cow<'de, str>> = None;
539        let mut params: Option<Value> = None;
540        let mut id: Option<RpcId> = None;
541        let mut seen: u8 = 0;
542        let mut bad: bool = false;
543        while let Some(key) = map.next_key::<RpcFieldKey>()? {
544            match key {
545                RpcFieldKey::Jsonrpc => {
546                    if (seen & 0x01) != 0 {
547                        bad = true;
548                    }
549                    seen |= 0x01;
550                    match map.next_value::<LenientStr<'de>>()? {
551                        LenientStr::Valid(s) => jsonrpc = Some(s),
552                        LenientStr::Null => jsonrpc = None,
553                        LenientStr::Invalid => bad = true,
554                    }
555                }
556                RpcFieldKey::Method => {
557                    if (seen & 0x02) != 0 {
558                        bad = true;
559                    }
560                    seen |= 0x02;
561                    match map.next_value::<LenientStr<'de>>()? {
562                        LenientStr::Valid(s) => method = Some(s),
563                        LenientStr::Null => method = None,
564                        LenientStr::Invalid => bad = true,
565                    }
566                }
567                RpcFieldKey::Params => {
568                    if (seen & 0x04) != 0 {
569                        bad = true;
570                    }
571                    seen |= 0x04;
572                    params = map.next_value::<Option<Value>>()?;
573                }
574                RpcFieldKey::Id => {
575                    if (seen & 0x08) != 0 {
576                        bad = true;
577                    }
578                    seen |= 0x08;
579                    match map.next_value::<LenientId>()? {
580                        LenientId::Valid(parsed) => id = parsed,
581                        LenientId::Invalid => bad = true,
582                    }
583                }
584                RpcFieldKey::Other => {
585                    let _: IgnoredAny = map.next_value()?;
586                }
587            }
588        }
589        if bad {
590            return Ok(BorrowedBatchItem::Invalid);
591        }
592        Ok(BorrowedBatchItem::Request(BorrowedRpcRequest {
593            jsonrpc,
594            method,
595            params,
596            id,
597        }))
598    }
599
600    /// Marks boolean JSON elements invalid.
601    ///
602    /// # Arguments
603    ///
604    /// - `bool` - Ignored boolean.
605    ///
606    /// # Returns
607    ///
608    /// - `Result<Self::Value, E>` - Always `Invalid`.
609    fn visit_bool<E>(self, _: bool) -> Result<Self::Value, E>
610    where
611        E: de::Error,
612    {
613        Ok(BorrowedBatchItem::Invalid)
614    }
615
616    /// Marks signed integer JSON elements invalid.
617    ///
618    /// # Arguments
619    ///
620    /// - `i64` - Ignored integer.
621    ///
622    /// # Returns
623    ///
624    /// - `Result<Self::Value, E>` - Always `Invalid`.
625    fn visit_i64<E>(self, _: i64) -> Result<Self::Value, E>
626    where
627        E: de::Error,
628    {
629        Ok(BorrowedBatchItem::Invalid)
630    }
631
632    /// Marks unsigned integer JSON elements invalid.
633    ///
634    /// # Arguments
635    ///
636    /// - `u64` - Ignored integer.
637    ///
638    /// # Returns
639    ///
640    /// - `Result<Self::Value, E>` - Always `Invalid`.
641    fn visit_u64<E>(self, _: u64) -> Result<Self::Value, E>
642    where
643        E: de::Error,
644    {
645        Ok(BorrowedBatchItem::Invalid)
646    }
647
648    /// Marks floating-point JSON elements invalid.
649    ///
650    /// # Arguments
651    ///
652    /// - `f64` - Ignored float.
653    ///
654    /// # Returns
655    ///
656    /// - `Result<Self::Value, E>` - Always `Invalid`.
657    fn visit_f64<E>(self, _: f64) -> Result<Self::Value, E>
658    where
659        E: de::Error,
660    {
661        Ok(BorrowedBatchItem::Invalid)
662    }
663
664    /// Marks string JSON elements invalid.
665    ///
666    /// # Arguments
667    ///
668    /// - `&str` - Ignored string.
669    ///
670    /// # Returns
671    ///
672    /// - `Result<Self::Value, E>` - Always `Invalid`.
673    fn visit_str<E>(self, _: &str) -> Result<Self::Value, E>
674    where
675        E: de::Error,
676    {
677        Ok(BorrowedBatchItem::Invalid)
678    }
679
680    /// Marks JSON `null` elements invalid.
681    ///
682    /// # Returns
683    ///
684    /// - `Result<Self::Value, E>` - Always `Invalid`.
685    fn visit_unit<E>(self) -> Result<Self::Value, E>
686    where
687        E: de::Error,
688    {
689        Ok(BorrowedBatchItem::Invalid)
690    }
691
692    /// Drains nested JSON array elements and marks them invalid.
693    ///
694    /// # Arguments
695    ///
696    /// - `A` - Sequence access.
697    ///
698    /// # Returns
699    ///
700    /// - `Result<Self::Value, A::Error>` - Always `Invalid`.
701    fn visit_seq<A>(self, mut seq: A) -> Result<Self::Value, A::Error>
702    where
703        A: SeqAccess<'de>,
704    {
705        while seq.next_element::<IgnoredAny>()?.is_some() {}
706        Ok(BorrowedBatchItem::Invalid)
707    }
708}
709
710/// Zero-copy streaming [`Deserialize`] implementation for [`BorrowedBatchItem`].
711impl<'de> Deserialize<'de> for BorrowedBatchItem<'de> {
712    /// Parses a JSON-RPC object or invalid JSON element in a single pass with zero content buffering.
713    ///
714    /// # Arguments
715    ///
716    /// - `D` - Serde deserializer.
717    ///
718    /// # Returns
719    ///
720    /// - `Result<Self, D::Error>` - Parsed batch/single item.
721    #[inline(always)]
722    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
723    where
724        D: Deserializer<'de>,
725    {
726        deserializer.deserialize_any(BorrowedBatchItemVisitor)
727    }
728}
729
730/// Formatting / debug-printing for [`RpcError`].
731impl Display for RpcError {
732    /// Formats the [`RpcError`] via the supplied formatter.
733    ///
734    /// # Arguments
735    ///
736    /// - `&mut Formatter<'_>` - The formatter receiving the formatted output.
737    ///
738    /// # Returns
739    ///
740    /// - `fmt::Result` - A `fmt::Result` value.
741    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
742        write!(
743            f,
744            "JSON-RPC error {}: {}",
745            self.get_code(),
746            self.get_message()
747        )
748    }
749}
750
751/// Implements [`Error`] for [`RpcError`].
752impl Error for RpcError {}
753
754/// Inherent implementation of [`RpcError`].
755impl RpcError {
756    /// Builds a JSON-RPC 2.0 Parse Error (`-32700`).
757    ///
758    /// # Returns
759    ///
760    /// - `Self` - Parse error object.
761    pub fn parse_error() -> Self {
762        Self::custom(RPC_PARSE_ERROR, MSG_PARSE_ERROR, None)
763    }
764
765    /// Builds a JSON-RPC 2.0 Invalid Request error (`-32600`).
766    ///
767    /// # Returns
768    ///
769    /// - `Self` - Invalid request error object.
770    pub fn invalid_request() -> Self {
771        Self::custom(RPC_INVALID_REQUEST, MSG_INVALID_REQUEST, None)
772    }
773
774    /// Builds a JSON-RPC 2.0 Method Not Found error (`-32601`).
775    ///
776    /// # Returns
777    ///
778    /// - `Self` - Method not found error object.
779    pub fn method_not_found() -> Self {
780        Self::custom(RPC_METHOD_NOT_FOUND, MSG_METHOD_NOT_FOUND, None)
781    }
782
783    /// Builds a JSON-RPC 2.0 Invalid Params error (`-32602`).
784    ///
785    /// # Arguments
786    ///
787    /// - `Option<Value>` - Optional detail describing the parameter validation failure.
788    ///
789    /// # Returns
790    ///
791    /// - `Self` - Invalid params error object.
792    pub fn invalid_params(data: Option<Value>) -> Self {
793        Self::custom(RPC_INVALID_PARAMS, MSG_INVALID_PARAMS, data)
794    }
795
796    /// Builds a JSON-RPC 2.0 Internal Error (`-32603`).
797    ///
798    /// # Arguments
799    ///
800    /// - `Option<Value>` - Optional detail payload.
801    ///
802    /// # Returns
803    ///
804    /// - `Self` - Internal error object.
805    pub fn internal_error(data: Option<Value>) -> Self {
806        Self::custom(RPC_INTERNAL_ERROR, MSG_INTERNAL_ERROR, data)
807    }
808
809    /// Builds a custom JSON-RPC error with explicit code, message, and optional data.
810    ///
811    /// # Arguments
812    ///
813    /// - `i64` - Numeric error code.
814    /// - `M` - Error message convertible into `String`.
815    /// - `Option<Value>` - Optional structured error payload.
816    ///
817    /// # Returns
818    ///
819    /// - `Self` - Custom error object.
820    pub fn custom<M>(code: i64, message: M, data: Option<Value>) -> Self
821    where
822        M: Into<String>,
823    {
824        Self {
825            code,
826            message: message.into(),
827            data,
828        }
829    }
830}
831
832/// Inherent implementation of [`RpcResponse`].
833impl RpcResponse {
834    /// Creates a success [`RpcResponse`] carrying `result`.
835    ///
836    /// # Arguments
837    ///
838    /// - `RpcId` - Request correlation identifier.
839    /// - `Value` - Method return value.
840    ///
841    /// # Returns
842    ///
843    /// - `Self` - JSON-RPC 2.0 success response.
844    pub fn success(id: RpcId, result: Value) -> Self {
845        Self {
846            jsonrpc: JSONRPC_VERSION.to_owned(),
847            result: Some(result),
848            error: None,
849            id,
850        }
851    }
852
853    /// Creates an error [`RpcResponse`] carrying `error`.
854    ///
855    /// # Arguments
856    ///
857    /// - `RpcId` - Request correlation identifier (`RpcId::Null` when unparseable).
858    /// - `RpcError` - Structured error object.
859    ///
860    /// # Returns
861    ///
862    /// - `Self` - JSON-RPC 2.0 error response.
863    pub fn failure(id: RpcId, error: RpcError) -> Self {
864        Self {
865            jsonrpc: JSONRPC_VERSION.to_owned(),
866            result: None,
867            error: Some(error),
868            id,
869        }
870    }
871}
872
873/// Default construction for [`RpcConfig`].
874impl Default for RpcConfig {
875    /// Constructs a default [`RpcConfig`] value.
876    fn default() -> Self {
877        Self {
878            endpoint: DEFAULT_RPC_ENDPOINT.to_owned(),
879            max_body_size: DEFAULT_RPC_MAX_BODY_SIZE,
880            max_batch_size: DEFAULT_RPC_MAX_BATCH_SIZE,
881        }
882    }
883}
884
885/// Inherent implementation of [`RpcConfig`].
886impl RpcConfig {
887    /// Sets the HTTP endpoint path matched by [`RpcHook`].
888    ///
889    /// # Arguments
890    ///
891    /// - `E` - Endpoint path convertible into `String`.
892    ///
893    /// # Returns
894    ///
895    /// - `Self` - Updated configuration.
896    pub fn with_endpoint<E>(mut self, endpoint: E) -> Self
897    where
898        E: Into<String>,
899    {
900        self.set_endpoint(endpoint.into());
901        self
902    }
903
904    /// Sets the maximum accepted JSON-RPC request body size in bytes.
905    ///
906    /// # Arguments
907    ///
908    /// - `usize` - Maximum body size in bytes.
909    ///
910    /// # Returns
911    ///
912    /// - `Self` - Updated configuration.
913    pub fn with_max_body_size(mut self, max_body_size: usize) -> Self {
914        self.set_max_body_size(max_body_size);
915        self
916    }
917
918    /// Sets the maximum batch array length permitted per request.
919    ///
920    /// # Arguments
921    ///
922    /// - `usize` - Maximum items per batch.
923    ///
924    /// # Returns
925    ///
926    /// - `Self` - Updated configuration.
927    pub fn with_max_batch_size(mut self, max_batch_size: usize) -> Self {
928        self.set_max_batch_size(max_batch_size);
929        self
930    }
931}
932
933/// Default construction for [`RpcRouter`].
934impl Default for RpcRouter {
935    /// Constructs an empty [`RpcRouter`].
936    fn default() -> Self {
937        Self {
938            methods: HashMap::default(),
939            interceptors: Vec::new(),
940        }
941    }
942}
943
944/// Inherent constructors for [`CompactRpcResponse`].
945impl CompactRpcResponse {
946    /// Builds a compact success envelope borrowing the static JSON-RPC version string.
947    ///
948    /// # Arguments
949    ///
950    /// - `RpcId` - Correlation identifier.
951    /// - `Value` - Result payload.
952    ///
953    /// # Returns
954    ///
955    /// - `Self` - Success response envelope.
956    #[inline(always)]
957    pub(crate) fn success(id: RpcId, result: Value) -> Self {
958        Self {
959            body: CompactRpcBody::Result(result),
960            id,
961        }
962    }
963
964    /// Builds a compact dynamic error envelope serialized directly with static framing.
965    ///
966    /// # Arguments
967    ///
968    /// - `RpcId` - Correlation identifier.
969    /// - `RpcError` - Structured error object.
970    ///
971    /// # Returns
972    ///
973    /// - `Self` - Error response envelope.
974    #[inline(always)]
975    pub(crate) fn failure(id: RpcId, error: RpcError) -> Self {
976        Self {
977            body: CompactRpcBody::Error(error),
978            id,
979        }
980    }
981
982    /// Builds a zero-allocation compact error envelope referencing a pre-serialized error fragment.
983    ///
984    /// # Arguments
985    ///
986    /// - `RpcId` - Correlation identifier.
987    /// - `&'static [u8]` - Pre-serialized JSON error object bytes.
988    ///
989    /// # Returns
990    ///
991    /// - `Self` - Static error response envelope.
992    #[inline(always)]
993    pub(crate) fn static_error(id: RpcId, raw_error: &'static [u8]) -> Self {
994        Self {
995            body: CompactRpcBody::StaticError(raw_error),
996            id,
997        }
998    }
999}
1000
1001/// Inherent implementation of [`RpcRouter`].
1002impl RpcRouter {
1003    /// Creates an empty [`RpcRouter`].
1004    ///
1005    /// # Returns
1006    ///
1007    /// - `Self` - Empty router.
1008    pub fn new() -> Self {
1009        Self::default()
1010    }
1011
1012    /// Registers an extensible [`RpcInterceptor`] invoked before every method dispatch.
1013    ///
1014    /// # Arguments
1015    ///
1016    /// - `Arc<dyn RpcInterceptor>` - Interceptor implementation.
1017    ///
1018    /// # Returns
1019    ///
1020    /// - `&mut Self` - This router for fluent chaining.
1021    pub fn add_interceptor(&mut self, interceptor: Arc<dyn RpcInterceptor>) -> &mut Self {
1022        let Self { interceptors, .. } = self;
1023        interceptors.push(interceptor);
1024        self
1025    }
1026
1027    /// Registers an async method handler under `name`.
1028    ///
1029    /// # Arguments
1030    ///
1031    /// - `N` - Method name convertible into `String`.
1032    /// - `F` - Async callback accepting `Option<Value>` and returning `Fut`.
1033    ///
1034    /// # Returns
1035    ///
1036    /// - `&mut Self` - This router for fluent chaining.
1037    pub fn register<N, F, Fut>(&mut self, name: N, handler: F) -> &mut Self
1038    where
1039        N: Into<String>,
1040        F: Fn(Option<Value>) -> Fut + Send + Sync + 'static,
1041        Fut: Future<Output = Result<Value, RpcError>> + Send + 'static,
1042    {
1043        let Self { methods, .. } = self;
1044        let boxed: RpcHandler = Arc::new(move |params: Option<Value>| Box::pin(handler(params)));
1045        methods.insert(name.into(), boxed);
1046        self
1047    }
1048
1049    /// Reports whether `name` is registered on this router.
1050    ///
1051    /// # Arguments
1052    ///
1053    /// - `&str` - Method name to check.
1054    ///
1055    /// # Returns
1056    ///
1057    /// - `bool` - `true` when registered.
1058    pub fn has_method(&self, name: &str) -> bool {
1059        let Self { methods, .. } = self;
1060        methods.contains_key(name)
1061    }
1062
1063    /// Returns a list of all registered method names.
1064    ///
1065    /// # Returns
1066    ///
1067    /// - `Vec<String>` - Registered method names.
1068    pub fn method_names(&self) -> Vec<String> {
1069        let Self { methods, .. } = self;
1070        methods.keys().cloned().collect()
1071    }
1072
1073    /// Resolves one incoming JSON value into either an immediate response or a ready async call.
1074    ///
1075    /// # Arguments
1076    ///
1077    /// - `Value` - Raw JSON object value.
1078    ///
1079    /// # Returns
1080    ///
1081    /// - `PreparedRpcCall` - Executable handler tuple or immediate reply/notification skip.
1082    fn prepare_call(&self, raw: Value) -> PreparedRpcCall {
1083        let Self {
1084            methods,
1085            interceptors,
1086        } = self;
1087        let req: RpcRequest = match from_value(raw) {
1088            Ok(parsed) => parsed,
1089            Err(_) => {
1090                return Err(Some(Box::new(RpcResponse::failure(
1091                    RpcId::Null,
1092                    RpcError::invalid_request(),
1093                ))));
1094            }
1095        };
1096        let RpcRequest {
1097            jsonrpc,
1098            method,
1099            params,
1100            id,
1101        }: RpcRequest = req;
1102        if jsonrpc != JSONRPC_VERSION || method.is_empty() {
1103            return Err(Some(Box::new(RpcResponse::failure(
1104                id.unwrap_or(RpcId::Null),
1105                RpcError::invalid_request(),
1106            ))));
1107        }
1108        for interceptor in interceptors {
1109            if let Err(err) = interceptor.before_call(&method, &params) {
1110                return Err(id.map(|corr: RpcId| Box::new(RpcResponse::failure(corr, err))));
1111            }
1112        }
1113        let Some(handler) = methods.get(method.as_str()) else {
1114            return Err(id.map(|corr: RpcId| {
1115                Box::new(RpcResponse::failure(corr, RpcError::method_not_found()))
1116            }));
1117        };
1118        Ok((Arc::clone(handler), params, id))
1119    }
1120
1121    /// Resolves one zero-copy [`BorrowedRpcRequest`] into an immediate compact reply or a borrowed handler call.
1122    ///
1123    /// # Arguments
1124    ///
1125    /// - `BorrowedRpcRequest<'_>` - Deserialized request envelope borrowing method/version slices.
1126    ///
1127    /// # Returns
1128    ///
1129    /// - `PreparedBorrowedCall<'_>` - Ready call or unboxed short-circuit reply.
1130    #[inline]
1131    fn prepare_borrowed_call(&self, req: BorrowedRpcRequest<'_>) -> PreparedBorrowedCall<'_> {
1132        let Self {
1133            methods,
1134            interceptors,
1135        } = self;
1136        let BorrowedRpcRequest {
1137            jsonrpc,
1138            method,
1139            params,
1140            id,
1141        }: BorrowedRpcRequest<'_> = req;
1142        let Some(method_name) = method else {
1143            return Err(Some(CompactRpcResponse::static_error(
1144                id.unwrap_or(RpcId::Null),
1145                STATIC_ERR_INVALID_REQUEST,
1146            )));
1147        };
1148        let version_ok: bool = matches!(
1149            jsonrpc.as_deref(),
1150            Some(ver) if ver == JSONRPC_VERSION
1151        );
1152        if !version_ok || method_name.is_empty() {
1153            return Err(Some(CompactRpcResponse::static_error(
1154                id.unwrap_or(RpcId::Null),
1155                STATIC_ERR_INVALID_REQUEST,
1156            )));
1157        }
1158        let method_str: &str = method_name.as_ref();
1159        for interceptor in interceptors {
1160            if let Err(err) = interceptor.before_call(method_str, &params) {
1161                return Err(id.map(|corr: RpcId| CompactRpcResponse::failure(corr, err)));
1162            }
1163        }
1164        let Some(handler) = methods.get(method_str) else {
1165            return Err(id.map(|corr: RpcId| {
1166                CompactRpcResponse::static_error(corr, STATIC_ERR_METHOD_NOT_FOUND)
1167            }));
1168        };
1169        Ok((handler, params, id))
1170    }
1171
1172    /// Evaluates one single JSON-RPC object payload (`first_byte == '{'`) into a [`CompactRpcResponse`].
1173    ///
1174    /// # Arguments
1175    ///
1176    /// - `&[u8]` - Raw single-object JSON payload bytes.
1177    ///
1178    /// # Returns
1179    ///
1180    /// - `Result<Option<CompactRpcResponse>, &'static [u8]>` - Compact response (`None` for notification) or prebuilt static error bytes.
1181    #[inline]
1182    async fn dispatch_single_object(
1183        &self,
1184        raw: &[u8],
1185    ) -> Result<Option<CompactRpcResponse>, &'static [u8]> {
1186        let item: BorrowedBatchItem<'_> = match from_slice(raw) {
1187            Ok(parsed) => parsed,
1188            Err(_) => return Err(PREBUILT_PARSE_ERROR),
1189        };
1190        let BorrowedBatchItem::Request(req) = item else {
1191            return Err(PREBUILT_INVALID_REQUEST);
1192        };
1193        match self.prepare_borrowed_call(req) {
1194            Ok((handler, params, id_opt)) => {
1195                let outcome: Result<Value, RpcError> = handler(params).await;
1196                let Some(id) = id_opt else {
1197                    return Ok(None);
1198                };
1199                let compact: CompactRpcResponse = match outcome {
1200                    Ok(value) => CompactRpcResponse::success(id, value),
1201                    Err(err) => CompactRpcResponse::failure(id, err),
1202                };
1203                Ok(Some(compact))
1204            }
1205            Err(immediate) => Ok(immediate),
1206        }
1207    }
1208
1209    /// Dispatches one parsed JSON value representing a single JSON-RPC 2.0 call or notification.
1210    ///
1211    /// # Arguments
1212    ///
1213    /// - `Value` - Raw JSON object value.
1214    ///
1215    /// # Returns
1216    ///
1217    /// - `Option<RpcResponse>` - `None` for valid notifications, otherwise the response envelope.
1218    pub async fn dispatch_value(&self, raw: Value) -> Option<RpcResponse> {
1219        match self.prepare_call(raw) {
1220            Ok((handler, params, id_opt)) => {
1221                let outcome: Result<Value, RpcError> = handler(params).await;
1222                let id: RpcId = id_opt?;
1223                match outcome {
1224                    Ok(value) => Some(RpcResponse::success(id, value)),
1225                    Err(err) => Some(RpcResponse::failure(id, err)),
1226                }
1227            }
1228            Err(immediate) => immediate.map(|resp: Box<RpcResponse>| *resp),
1229        }
1230    }
1231
1232    /// Parses and dispatches raw JSON-RPC 2.0 request bytes (single call, notification, or concurrent batch).
1233    ///
1234    /// # Arguments
1235    ///
1236    /// - `&[u8]` - Raw HTTP request payload bytes.
1237    /// - `&RpcConfig` - Batch and payload safety bounds.
1238    ///
1239    /// # Returns
1240    ///
1241    /// - `Option<Vec<u8>>` - Serialized JSON response bytes, or `None` when every call was a notification.
1242    pub async fn dispatch_bytes(&self, raw: &[u8], config: &RpcConfig) -> Option<Vec<u8>> {
1243        let Some(first_byte) = first_non_ws_byte(raw) else {
1244            return Some(PREBUILT_PARSE_ERROR.to_vec());
1245        };
1246        if first_byte == BYTE_LBRACE {
1247            return match self.dispatch_single_object(raw).await {
1248                Ok(Some(compact)) => Some(encode_compact_response(&compact)),
1249                Ok(None) => None,
1250                Err(static_err) => Some(static_err.to_vec()),
1251            };
1252        }
1253        if first_byte == BYTE_LBRACKET {
1254            let items: Vec<BorrowedBatchItem<'_>> = match from_slice(raw) {
1255                Ok(parsed) => parsed,
1256                Err(_) => return Some(PREBUILT_PARSE_ERROR.to_vec()),
1257            };
1258            if items.is_empty() {
1259                return Some(PREBUILT_INVALID_REQUEST.to_vec());
1260            }
1261            if items.len() > config.get_max_batch_size() {
1262                return Some(PREBUILT_BATCH_TOO_LARGE.to_vec());
1263            }
1264            let mut slots: Vec<Option<BatchDispatchSlot>> = Vec::with_capacity(items.len());
1265            let mut stack_active: [usize; DEFAULT_RPC_MAX_BATCH_SIZE] =
1266                [0usize; DEFAULT_RPC_MAX_BATCH_SIZE];
1267            let mut stack_active_len: usize = 0;
1268            let mut heap_active: Vec<usize> = Vec::new();
1269            for item in items {
1270                match item {
1271                    BorrowedBatchItem::Request(req) => match self.prepare_borrowed_call(req) {
1272                        Ok((handler, params, id)) => {
1273                            let idx: usize = slots.len();
1274                            if stack_active_len < DEFAULT_RPC_MAX_BATCH_SIZE {
1275                                stack_active[stack_active_len] = idx;
1276                                stack_active_len += 1;
1277                            } else {
1278                                if heap_active.is_empty() {
1279                                    heap_active.extend_from_slice(&stack_active);
1280                                }
1281                                heap_active.push(idx);
1282                            }
1283                            slots.push(Some(BatchDispatchSlot::Pending {
1284                                future: handler(params),
1285                                id,
1286                            }));
1287                        }
1288                        Err(immediate) => {
1289                            slots.push(immediate.map(BatchDispatchSlot::Ready));
1290                        }
1291                    },
1292                    BorrowedBatchItem::Invalid => {
1293                        slots.push(Some(BatchDispatchSlot::Ready(
1294                            CompactRpcResponse::static_error(
1295                                RpcId::Null,
1296                                STATIC_ERR_INVALID_REQUEST,
1297                            ),
1298                        )));
1299                    }
1300                }
1301            }
1302            if !heap_active.is_empty() {
1303                poll_fn(|cx: &mut task::Context<'_>| {
1304                    let mut i: usize = 0;
1305                    while i < heap_active.len() {
1306                        let slot_idx: usize = heap_active[i];
1307                        let slot_opt: &mut Option<BatchDispatchSlot> = &mut slots[slot_idx];
1308                        if let Some(BatchDispatchSlot::Pending { future, .. }) = slot_opt
1309                            && let Poll::Ready(outcome) = future.as_mut().poll(cx)
1310                        {
1311                            let ready_slot: Option<BatchDispatchSlot> = match slot_opt.take() {
1312                                Some(BatchDispatchSlot::Pending { id: Some(corr), .. }) => {
1313                                    let compact: CompactRpcResponse = match outcome {
1314                                        Ok(value) => CompactRpcResponse::success(corr, value),
1315                                        Err(err) => CompactRpcResponse::failure(corr, err),
1316                                    };
1317                                    Some(BatchDispatchSlot::Ready(compact))
1318                                }
1319                                _ => None,
1320                            };
1321                            *slot_opt = ready_slot;
1322                            let _: usize = heap_active.swap_remove(i);
1323                        } else {
1324                            i += 1;
1325                        }
1326                    }
1327                    if heap_active.is_empty() {
1328                        Poll::Ready(())
1329                    } else {
1330                        Poll::Pending
1331                    }
1332                })
1333                .await;
1334            } else if stack_active_len > 0 {
1335                poll_fn(|cx: &mut task::Context<'_>| {
1336                    let mut i: usize = 0;
1337                    while i < stack_active_len {
1338                        let slot_idx: usize = stack_active[i];
1339                        let slot_opt: &mut Option<BatchDispatchSlot> = &mut slots[slot_idx];
1340                        if let Some(BatchDispatchSlot::Pending { future, .. }) = slot_opt
1341                            && let Poll::Ready(outcome) = future.as_mut().poll(cx)
1342                        {
1343                            let ready_slot: Option<BatchDispatchSlot> = match slot_opt.take() {
1344                                Some(BatchDispatchSlot::Pending { id: Some(corr), .. }) => {
1345                                    let compact: CompactRpcResponse = match outcome {
1346                                        Ok(value) => CompactRpcResponse::success(corr, value),
1347                                        Err(err) => CompactRpcResponse::failure(corr, err),
1348                                    };
1349                                    Some(BatchDispatchSlot::Ready(compact))
1350                                }
1351                                _ => None,
1352                            };
1353                            *slot_opt = ready_slot;
1354                            stack_active_len -= 1;
1355                            stack_active[i] = stack_active[stack_active_len];
1356                        } else {
1357                            i += 1;
1358                        }
1359                    }
1360                    if stack_active_len == 0 {
1361                        Poll::Ready(())
1362                    } else {
1363                        Poll::Pending
1364                    }
1365                })
1366                .await;
1367            }
1368            return encode_ready_batch_slots(&slots);
1369        }
1370        if from_slice::<IgnoredAny>(raw).is_ok() {
1371            Some(PREBUILT_INVALID_REQUEST.to_vec())
1372        } else {
1373            Some(PREBUILT_PARSE_ERROR.to_vec())
1374        }
1375    }
1376
1377    /// Dispatches `raw` and writes the HTTP/1.1 JSON response directly onto `stream` with zero header-map overhead.
1378    ///
1379    /// # Arguments
1380    ///
1381    /// - `&mut Stream` - Active client connection stream.
1382    /// - `&[u8]` - Raw HTTP request body bytes.
1383    /// - `&RpcConfig` - Batch and payload safety bounds.
1384    #[inline]
1385    pub(crate) async fn dispatch_and_send_http11(
1386        &self,
1387        stream: &mut Stream,
1388        raw: &[u8],
1389        config: &RpcConfig,
1390    ) {
1391        let Some(first_byte) = first_non_ws_byte(raw) else {
1392            let mut wire_stack: [u8; RPC_WIRE_STACK_CAP] = [0u8; RPC_WIRE_STACK_CAP];
1393            if let Some(len) = format_http11_json_wire_stack(PREBUILT_PARSE_ERROR, &mut wire_stack)
1394            {
1395                let _: Result<(), ResponseError> = stream.try_send(&wire_stack[..len]).await;
1396            }
1397            return;
1398        };
1399        if first_byte == BYTE_LBRACE {
1400            match self.dispatch_single_object(raw).await {
1401                Ok(Some(compact)) => {
1402                    let mut payload_stack: [u8; RPC_PAYLOAD_STACK_CAP] =
1403                        [0u8; RPC_PAYLOAD_STACK_CAP];
1404                    if let Some(plen) = write_compact_response_stack(&compact, &mut payload_stack) {
1405                        let mut wire_stack: [u8; RPC_WIRE_STACK_CAP] = [0u8; RPC_WIRE_STACK_CAP];
1406                        if let Some(wlen) =
1407                            format_http11_json_wire_stack(&payload_stack[..plen], &mut wire_stack)
1408                        {
1409                            let _: Result<(), ResponseError> =
1410                                stream.try_send(&wire_stack[..wlen]).await;
1411                            return;
1412                        }
1413                    }
1414                    let payload: Vec<u8> = encode_compact_response(&compact);
1415                    let wire: Vec<u8> = build_http11_json_wire_vec(&payload);
1416                    let _: Result<(), ResponseError> = stream.try_send(&wire).await;
1417                }
1418                Ok(None) => {
1419                    let wire: &[u8] =
1420                        get_prebuilt_empty_wire(&WIRE_204_CACHE, HttpStatus::NoContent);
1421                    let _: Result<(), ResponseError> = stream.try_send(wire).await;
1422                }
1423                Err(static_err) => {
1424                    let mut wire_stack: [u8; RPC_WIRE_STACK_CAP] = [0u8; RPC_WIRE_STACK_CAP];
1425                    if let Some(wlen) = format_http11_json_wire_stack(static_err, &mut wire_stack) {
1426                        let _: Result<(), ResponseError> =
1427                            stream.try_send(&wire_stack[..wlen]).await;
1428                    }
1429                }
1430            }
1431            return;
1432        }
1433        match self.dispatch_bytes(raw, config).await {
1434            Some(payload) => {
1435                let mut wire_stack: [u8; RPC_WIRE_STACK_CAP] = [0u8; RPC_WIRE_STACK_CAP];
1436                if let Some(wlen) = format_http11_json_wire_stack(&payload, &mut wire_stack) {
1437                    let _: Result<(), ResponseError> = stream.try_send(&wire_stack[..wlen]).await;
1438                } else {
1439                    let wire: Vec<u8> = build_http11_json_wire_vec(&payload);
1440                    let _: Result<(), ResponseError> = stream.try_send(&wire).await;
1441                }
1442            }
1443            None => {
1444                let wire: &[u8] = get_prebuilt_empty_wire(&WIRE_204_CACHE, HttpStatus::NoContent);
1445                let _: Result<(), ResponseError> = stream.try_send(wire).await;
1446            }
1447        }
1448    }
1449}
1450
1451/// Inherent implementation of [`RpcPlugin`].
1452impl RpcPlugin {
1453    /// Initializes the global [`RpcPlugin`] once with `config` and `router`.
1454    ///
1455    /// # Arguments
1456    ///
1457    /// - `RpcConfig` - JSON-RPC server configuration.
1458    /// - `RpcRouter` - Registered method router.
1459    ///
1460    /// # Returns
1461    ///
1462    /// - `&'static Self` - Reference to the initialized global plugin.
1463    pub fn init(config: RpcConfig, router: RpcRouter) -> &'static Self {
1464        RPC_PLUGIN.get_or_init(|| Self { config, router })
1465    }
1466
1467    /// Returns the initialized global [`RpcPlugin`], if [`RpcPlugin::init`] was called.
1468    ///
1469    /// # Returns
1470    ///
1471    /// - `Option<&'static Self>` - Reference to the global plugin, or `None`.
1472    pub fn get() -> Option<&'static Self> {
1473        RPC_PLUGIN.get()
1474    }
1475
1476    /// Returns the active [`RpcConfig`].
1477    ///
1478    /// # Returns
1479    ///
1480    /// - `&RpcConfig` - Active configuration.
1481    pub fn get_config(&self) -> &RpcConfig {
1482        let Self { config, .. } = self;
1483        config
1484    }
1485
1486    /// Returns the active [`RpcRouter`].
1487    ///
1488    /// # Returns
1489    ///
1490    /// - `&RpcRouter` - Registered method router.
1491    pub fn get_router(&self) -> &RpcRouter {
1492        let Self { router, .. } = self;
1493        router
1494    }
1495}
1496
1497/// Implements [`ServerHook`] for [`RpcHook`].
1498impl ServerHook for RpcHook {
1499    /// Constructs a per-request [`RpcHook`].
1500    ///
1501    /// # Arguments
1502    ///
1503    /// - `&mut Stream` - Connection stream.
1504    /// - `&mut Context` - Request context.
1505    ///
1506    /// # Returns
1507    ///
1508    /// - `Self` - Hook instance.
1509    async fn new(_: &mut Stream, _: &mut Context) -> Self {
1510        Self
1511    }
1512
1513    /// Handles JSON-RPC 2.0 `POST` requests matching the configured endpoint.
1514    ///
1515    /// # Arguments
1516    ///
1517    /// - `Self` - Hook instance.
1518    /// - `&mut Stream` - Connection stream.
1519    /// - `&mut Context` - Request context.
1520    ///
1521    /// # Returns
1522    ///
1523    /// - `Status` - `Status::Continue` when unconfigured or path does not match; `Status::Reject` once answered.
1524    async fn handle(self, stream: &mut Stream, ctx: &mut Context) -> Status {
1525        let Some(plugin) = RpcPlugin::get() else {
1526            return Status::Continue;
1527        };
1528        let config: &RpcConfig = plugin.get_config();
1529        if ctx.get_request().get_path() != config.get_endpoint() {
1530            return Status::Continue;
1531        }
1532        let resp: &Response = ctx.get_response();
1533        let can_fast_wire: bool = ctx.get_request().get_version().is_http1_1()
1534            && resp.get_version().is_http1_1()
1535            && resp.get_headers().is_empty()
1536            && (resp.get_reason_phrase().is_empty() || resp.get_reason_phrase().as_str() == OK);
1537        if !ctx.get_request().get_method().is_post() {
1538            if can_fast_wire {
1539                let wire: &[u8] =
1540                    get_prebuilt_empty_wire(&WIRE_405_CACHE, HttpStatus::MethodNotAllowed);
1541                let _: Result<(), ResponseError> = stream.try_send(wire).await;
1542                return Status::Reject;
1543            }
1544            ctx.get_mut_response()
1545                .set_status_code(HttpStatus::MethodNotAllowed.code())
1546                .set_body(Vec::new());
1547            let wire: Vec<u8> = ctx.get_mut_response().build();
1548            let _: Result<(), ResponseError> = stream.try_send(&wire).await;
1549            return Status::Reject;
1550        }
1551        let body: &[u8] = ctx.get_request().get_body();
1552        if body.len() > config.get_max_body_size() {
1553            if can_fast_wire {
1554                let wire: &[u8] =
1555                    get_prebuilt_empty_wire(&WIRE_413_CACHE, HttpStatus::PayloadTooLarge);
1556                let _: Result<(), ResponseError> = stream.try_send(wire).await;
1557                return Status::Reject;
1558            }
1559            ctx.get_mut_response()
1560                .set_status_code(HttpStatus::PayloadTooLarge.code())
1561                .set_body(Vec::new());
1562            let wire: Vec<u8> = ctx.get_mut_response().build();
1563            let _: Result<(), ResponseError> = stream.try_send(&wire).await;
1564            return Status::Reject;
1565        }
1566        if can_fast_wire {
1567            plugin
1568                .get_router()
1569                .dispatch_and_send_http11(stream, body, config)
1570                .await;
1571            return Status::Reject;
1572        }
1573        match plugin.get_router().dispatch_bytes(body, config).await {
1574            Some(payload) => {
1575                ctx.get_mut_response()
1576                    .set_status_code(HttpStatus::Ok.code())
1577                    .set_header(CONTENT_TYPE, APPLICATION_JSON);
1578                *ctx.get_mut_response().get_mut_body() = payload;
1579            }
1580            None => {
1581                ctx.get_mut_response()
1582                    .set_status_code(HttpStatus::NoContent.code())
1583                    .get_mut_body()
1584                    .clear();
1585            }
1586        }
1587        let wire: Vec<u8> = ctx.get_mut_response().build();
1588        let _: Result<(), ResponseError> = stream.try_send(&wire).await;
1589        Status::Reject
1590    }
1591}