Skip to main content

plexus_core/plexus/
wire.rs

1//! PERF-7: the item path — an item encoded once, by its method's own event
2//! type, straight into a buffer its socket writes from.
3//!
4//! | when | then |
5//! | -- | -- |
6//! | a method yields an event under the WebSocket pipe ([`pipe`]) | [`wrap_stream`](super::streaming::wrap_stream) serializes it once, by its own `Serialize`, into the pipe's buffer (a block from its connection's pool); the `Data` item carries it as [`Content`] — JSON bytes, no `Value` |
7//! | the same event anywhere else (in process, a nested route, a test) | it becomes a `Value` as before: in-process items stay what they cost |
8//! | a transformer reads a `Data` item's content | [`Content`] decodes its bytes once, on demand (`Deref` to `Value`); one that rewrites it replaces the whole [`Content`] — an encoded item is a `Data` item, so no rewrite can miss one (PERF-17's finding: the gated view's rewrite did) |
9//! | the pipe writes an item | the notification's prefix (once a call), the metadata (once a stream), the content type and the content's bytes, and the suffix, into the same buffer: one frame, split off as `Bytes` (no allocation while the block has room) |
10//! | the transport offers a [`FrameSink`] (plexus-transport's socket loop) | the frame goes to the socket's writer as it is; the call's first frame is fenced, so it follows the subscription's answer that jsonrpsee queued |
11//! | it does not (jsonrpsee's own sink: stdio, an in-memory module) | the item's bytes go to the sink as one raw value, as before |
12//! | one change fans out to N watchers ([`Shared`]) | the first socket that sends it encodes it, once; every other writes those bytes |
13//!
14//! PERF-8 batches frames from here (`results: […]`), PERF-9 adds an encoding
15//! ([`WireEncoding`]), PERF-13 relays a child's content as bytes.
16
17use std::borrow::Cow;
18use std::cell::{Cell, RefCell};
19use std::sync::{Arc, Mutex, OnceLock};
20
21use bytes::{BufMut, Bytes, BytesMut};
22use serde::{Deserialize, Serialize, Serializer};
23use serde_json::value::RawValue;
24use serde_json::Value;
25
26use super::types::{PlexusStreamItem, StreamMetadata};
27
28// ---------------------------------------------------------------------------
29// Content
30// ---------------------------------------------------------------------------
31
32/// A `data` item's content: the method's event, encoded once (JSON bytes),
33/// or a `Value` — whichever the item was made with. Reads as a `Value`
34/// either way ([`Content::value`], `Deref`), the bytes decoded once on
35/// demand; serializes as its JSON. Equal as JSON is equal.
36#[derive(Clone, Default)]
37pub struct Content(Repr);
38
39#[derive(Clone)]
40enum Repr {
41    Value(Value),
42    /// JSON text serde_json wrote (valid by construction), and its `Value`
43    /// once someone asked for it.
44    Json { text: Bytes, value: OnceLock<Value> },
45}
46
47impl Default for Repr {
48    fn default() -> Self {
49        Repr::Value(Value::Null)
50    }
51}
52
53impl Content {
54    /// Content that is a `Value`.
55    pub fn from_value(value: Value) -> Self {
56        Content(Repr::Value(value))
57    }
58
59    /// Content that is JSON text, checked (a parse, no `Value` built).
60    pub fn from_json(text: Bytes) -> Result<Self, serde_json::Error> {
61        serde_json::from_slice::<serde::de::IgnoredAny>(&text)?;
62        Ok(Self::json(text))
63    }
64
65    /// JSON text serde_json wrote, taken as it is.
66    pub(crate) fn json(text: Bytes) -> Self {
67        Content(Repr::Json { text, value: OnceLock::new() })
68    }
69
70    /// The content as a `Value` (encoded bytes decoded once, kept).
71    pub fn value(&self) -> &Value {
72        match &self.0 {
73            Repr::Value(v) => v,
74            Repr::Json { text, value } => value.get_or_init(|| serde_json::from_slice(text).unwrap_or(Value::Null)),
75        }
76    }
77
78    /// The content as an owned `Value`.
79    pub fn into_value(self) -> Value {
80        match self.0 {
81            Repr::Value(v) => v,
82            Repr::Json { text, value } => value.into_inner().unwrap_or_else(|| serde_json::from_slice(&text).unwrap_or(Value::Null)),
83        }
84    }
85
86    /// A copy of the content as a `Value`.
87    pub fn to_value(&self) -> Value {
88        match &self.0 {
89            Repr::Value(v) => v.clone(),
90            Repr::Json { text, value } => value.get().cloned().unwrap_or_else(|| serde_json::from_slice(text).unwrap_or(Value::Null)),
91        }
92    }
93
94    /// The content as `T`, decoded straight from its bytes when it is
95    /// encoded (no `Value` in between).
96    pub fn decode<T: serde::de::DeserializeOwned>(&self) -> Result<T, serde_json::Error> {
97        match &self.0 {
98            Repr::Value(v) => T::deserialize(v),
99            Repr::Json { text, value } => match value.get() {
100                Some(v) => T::deserialize(v),
101                None => serde_json::from_slice(text),
102            },
103        }
104    }
105
106    /// The JSON text the content was encoded as, when it was.
107    pub fn json_bytes(&self) -> Option<&Bytes> {
108        match &self.0 {
109            Repr::Json { text, .. } => Some(text),
110            Repr::Value(_) => None,
111        }
112    }
113
114    /// Whether the content was encoded once from its event (PERF-7).
115    pub fn is_encoded(&self) -> bool {
116        matches!(self.0, Repr::Json { .. })
117    }
118
119    /// Its JSON text, appended to `out`: the bytes, or the `Value` written.
120    fn write_json(&self, out: &mut BytesMut) {
121        match &self.0 {
122            Repr::Json { text, .. } => out.put_slice(text),
123            Repr::Value(v) => {
124                let _ = serde_json::to_writer((&mut *out).writer(), v);
125            }
126        }
127    }
128}
129
130impl std::ops::Deref for Content {
131    type Target = Value;
132    fn deref(&self) -> &Value {
133        self.value()
134    }
135}
136
137impl From<Value> for Content {
138    fn from(value: Value) -> Self {
139        Content::from_value(value)
140    }
141}
142
143impl From<Content> for Value {
144    fn from(content: Content) -> Self {
145        content.into_value()
146    }
147}
148
149/// Whatever a `Value` compares with — another content, a `Value`, a string,
150/// a number, a bool — a content compares with as its `Value`.
151impl<T: ?Sized> PartialEq<T> for Content
152where
153    Value: PartialEq<T>,
154{
155    fn eq(&self, other: &T) -> bool {
156        self.value() == other
157    }
158}
159
160impl PartialEq<Content> for Value {
161    fn eq(&self, other: &Content) -> bool {
162        self == other.value()
163    }
164}
165
166impl std::fmt::Debug for Content {
167    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
168        match &self.0 {
169            Repr::Value(v) => v.fmt(f),
170            Repr::Json { text, .. } => write!(f, "{}", String::from_utf8_lossy(text)),
171        }
172    }
173}
174
175impl std::fmt::Display for Content {
176    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
177        match &self.0 {
178            Repr::Value(v) => v.fmt(f),
179            Repr::Json { text, .. } => f.write_str(&String::from_utf8_lossy(text)),
180        }
181    }
182}
183
184impl Serialize for Content {
185    fn serialize<S: Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
186        if let Repr::Json { text, value } = &self.0 {
187            // serde_json writes a raw value as it is; any other serializer
188            // gets the `Value`.
189            if writing_json() {
190                if let Ok(raw) = serde_json::from_slice::<&RawValue>(text) {
191                    return raw.serialize(s);
192                }
193            }
194            if let Some(v) = value.get() {
195                return v.serialize(s);
196            }
197        }
198        self.value().serialize(s)
199    }
200}
201
202impl<'de> Deserialize<'de> for Content {
203    fn deserialize<D: serde::Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
204        Value::deserialize(d).map(Content::from_value)
205    }
206}
207
208impl schemars::JsonSchema for Content {
209    fn inline_schema() -> bool {
210        <Value as schemars::JsonSchema>::inline_schema()
211    }
212    fn schema_name() -> Cow<'static, str> {
213        <Value as schemars::JsonSchema>::schema_name()
214    }
215    fn schema_id() -> Cow<'static, str> {
216        <Value as schemars::JsonSchema>::schema_id()
217    }
218    fn json_schema(generator: &mut schemars::SchemaGenerator) -> schemars::Schema {
219        <Value as schemars::JsonSchema>::json_schema(generator)
220    }
221}
222
223// ---------------------------------------------------------------------------
224// The connection's encoding and its frames
225// ---------------------------------------------------------------------------
226
227/// The encoding of every frame on a connection, fixed when it opens. JSON
228/// text until PERF-9 adds msgpack.
229#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
230#[non_exhaustive]
231pub enum WireEncoding {
232    /// JSON-RPC 2.0 objects, one text message each.
233    #[default]
234    Json,
235}
236
237/// A frame ready for a socket, in its connection's encoding.
238#[derive(Debug, Clone)]
239pub struct WireFrame {
240    bytes: Bytes,
241    fence: bool,
242}
243
244impl WireFrame {
245    /// The frame's bytes (JSON text under [`WireEncoding::Json`]).
246    pub fn bytes(&self) -> &Bytes {
247        &self.bytes
248    }
249
250    /// The frame's bytes, owned.
251    pub fn into_bytes(self) -> Bytes {
252        self.bytes
253    }
254
255    /// A call's first frame: written only after every frame the connection's
256    /// method table queued before it (its subscription's answer among them,
257    /// which jsonrpsee queues when the call is accepted).
258    pub fn fenced(&self) -> bool {
259        self.fence
260    }
261}
262
263/// The frames a transport takes from a connection's calls (plexus-transport's
264/// socket loop puts one in each call's extensions): each item a frame, in
265/// order, written as it is. Cheap to clone.
266#[derive(Clone)]
267pub struct FrameSink {
268    tx: tokio::sync::mpsc::Sender<WireFrame>,
269    encoding: WireEncoding,
270    /// The connection's pool: one spare block a call starts in, so a short
271    /// call allocates none.
272    spare: Arc<Mutex<Option<BytesMut>>>,
273}
274
275/// What the transport's writer reads a [`FrameSink`]'s frames from.
276pub type FrameReceiver = tokio::sync::mpsc::Receiver<WireFrame>;
277
278impl FrameSink {
279    /// A connection's frame queue, bounded at `capacity` frames.
280    pub fn channel(capacity: usize, encoding: WireEncoding) -> (FrameSink, FrameReceiver) {
281        let (tx, rx) = tokio::sync::mpsc::channel(capacity.max(1));
282        (FrameSink { tx, encoding, spare: Arc::new(Mutex::new(None)) }, rx)
283    }
284
285    /// The connection's encoding.
286    pub fn encoding(&self) -> WireEncoding {
287        self.encoding
288    }
289
290    /// Whether the connection is gone.
291    pub fn is_closed(&self) -> bool {
292        self.tx.is_closed()
293    }
294
295    fn take_block(&self) -> Option<BytesMut> {
296        self.spare.lock().ok().and_then(|mut s| s.take())
297    }
298
299    fn give_block(&self, block: BytesMut) {
300        if block.capacity() <= Buffer::POOLED {
301            if let Ok(mut s) = self.spare.lock() {
302                if s.is_none() {
303                    *s = Some(block);
304                }
305            }
306        }
307    }
308}
309
310impl std::fmt::Debug for FrameSink {
311    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
312        f.debug_struct("FrameSink").field("encoding", &self.encoding).field("closed", &self.tx.is_closed()).finish()
313    }
314}
315
316// ---------------------------------------------------------------------------
317// The buffer: blocks a call's items and frames are written into
318// ---------------------------------------------------------------------------
319
320/// A call's buffer. Each item and each frame is written at the end of the
321/// current block and split off as `Bytes` sharing it; a block is reused once
322/// every frame cut from it has been written and dropped, and a new one is
323/// allocated only when none is free.
324struct Buffer {
325    cur: BytesMut,
326    /// Blocks still holding frames in flight, kept to be reused once free.
327    spare: Vec<BytesMut>,
328    /// The size a new block is made at: grown with the frames it holds.
329    block: usize,
330    /// Whether a block has been made (or taken from the pool) yet.
331    started: bool,
332}
333
334impl Default for Buffer {
335    fn default() -> Self {
336        Buffer { cur: BytesMut::new(), spare: Vec::new(), block: Self::FIRST, started: false }
337    }
338}
339
340impl Buffer {
341    /// A first block: a short call's frames fit.
342    const FIRST: usize = 8 * 1024;
343    /// The largest block made for a stream's frames (one larger item gets a
344    /// block of its own size).
345    const MOST: usize = 512 * 1024;
346    /// The largest block a connection keeps for its next call.
347    const POOLED: usize = 64 * 1024;
348    /// Blocks kept to be reused.
349    const SPARE: usize = 3;
350
351    fn from_block(block: Option<BytesMut>) -> Self {
352        match block {
353            Some(cur) => Buffer { block: cur.capacity().max(Self::FIRST), cur, spare: Vec::new(), started: true },
354            None => Buffer::default(),
355        }
356    }
357
358    /// Room for `n` more bytes in the current block: it, or a free block, or
359    /// a new one.
360    fn room(&mut self, n: usize) {
361        if self.cur.capacity() - self.cur.len() >= n || self.cur.try_reclaim(n) {
362            return;
363        }
364        // The current block holds unsent frames, or is too small: keep it
365        // for later and take a free one, if any is free.
366        let free = self.spare.iter_mut().position(|b| b.try_reclaim(n));
367        let next = match free {
368            Some(i) => self.spare.swap_remove(i),
369            None => {
370                // Every block is busy: the frames outrun the socket, so the
371                // next block holds more of them.
372                if self.started {
373                    self.block = (self.block * 2).clamp(Self::FIRST, Self::MOST);
374                }
375                self.started = true;
376                BytesMut::with_capacity(self.block.max(n))
377            }
378        };
379        let old = std::mem::replace(&mut self.cur, next);
380        if old.capacity() > 0 {
381            if self.spare.len() >= Self::SPARE {
382                self.spare.remove(0);
383            }
384            self.spare.push(old);
385        }
386    }
387
388    /// What was written since the last split, as `Bytes`.
389    fn split(&mut self) -> Bytes {
390        self.cur.split().freeze()
391    }
392
393    /// The block to give back to the connection's pool: the current one,
394    /// whatever is left of it (frames still in flight keep what they hold).
395    fn into_block(self) -> Option<BytesMut> {
396        (self.cur.capacity() >= 1024).then_some(self.cur)
397    }
398}
399
400// ---------------------------------------------------------------------------
401// The pipe's encoder: the events of the stream the pipe polls
402// ---------------------------------------------------------------------------
403
404/// The pipe's encoder, for the task that polls a call's stream.
405struct Encoder {
406    /// The connection's encoding: JSON until PERF-9 reads it here.
407    #[allow(dead_code)]
408    encoding: WireEncoding,
409    buffer: RefCell<Buffer>,
410    /// How deep the poll is in streams [`wrap_stream`] wrapped: only the
411    /// outermost encodes — a stream polled inside a method's own (a call
412    /// it routes and reads in process) keeps its items as `Value`s.
413    ///
414    /// [`wrap_stream`]: super::streaming::wrap_stream
415    depth: Cell<u32>,
416    /// The last content's size, to make room for the next.
417    last: Cell<usize>,
418}
419
420tokio::task_local! {
421    static WIRE: Encoder;
422}
423
424thread_local! {
425    /// The pipe's serde_json writer is serializing an event on this thread.
426    static WRITING_JSON: Cell<u32> = const { Cell::new(0) };
427}
428
429/// Whether the serializer at work on this thread is the pipe's JSON writer
430/// (so a [`Shared`] event or an encoded [`Content`] may write its bytes as
431/// they are).
432fn writing_json() -> bool {
433    WRITING_JSON.with(|w| w.get() > 0)
434}
435
436struct WritingJson;
437
438impl WritingJson {
439    fn on() -> Self {
440        WRITING_JSON.with(|w| w.set(w.get() + 1));
441        WritingJson
442    }
443}
444
445impl Drop for WritingJson {
446    fn drop(&mut self) {
447        WRITING_JSON.with(|w| w.set(w.get().saturating_sub(1)));
448    }
449}
450
451/// Run `poll` (a wrapped stream's poll of its method's stream) one stream
452/// deeper: what it yields is not the pipe's to encode.
453pub(crate) fn nested<R>(poll: impl FnOnce() -> R) -> R {
454    if WIRE.try_with(|e| e.depth.set(e.depth.get() + 1)).is_err() {
455        return poll();
456    }
457    // Put back after the poll, a panic included.
458    struct Back;
459    impl Drop for Back {
460        fn drop(&mut self) {
461            let _ = WIRE.try_with(|e| e.depth.set(e.depth.get().saturating_sub(1)));
462        }
463    }
464    let _back = Back;
465    poll()
466}
467
468/// `event` encoded once into the pipe's buffer — when the pipe is polling
469/// this stream directly, the event is not a credential's (whose envelope is
470/// assembled as before) and it serializes. `None`: make a `Value` as before.
471pub(crate) fn encode<T: Serialize + ?Sized>(event: &T) -> Option<Content> {
472    WIRE.try_with(|e| {
473        if e.depth.get() > 0 {
474            return None;
475        }
476        let mut buffer = e.buffer.borrow_mut();
477        buffer.room(e.last.get().saturating_mul(2).max(256));
478        debug_assert!(buffer.cur.is_empty());
479        let (written, captured) = plexus_auth_core::credential::run_with_credential_capture(|| {
480            let _json = WritingJson::on();
481            serde_json::to_writer((&mut buffer.cur).writer(), event).is_ok()
482        });
483        if !written || !captured.is_empty() {
484            buffer.cur.clear();
485            return None;
486        }
487        e.last.set(buffer.cur.len());
488        Some(Content::json(buffer.split()))
489    })
490    .ok()
491    .flatten()
492}
493
494/// One call's frames: the notification around each item.
495struct Frames {
496    /// `{"jsonrpc":"2.0","method":M,"params":{"subscription":S,"result":`
497    prefix: Vec<u8>,
498    /// A `data` item's opening, `{"type":"data","metadata":…,"content_type":…,"content":`,
499    /// for the stream's metadata (shared by its items) and content type.
500    head: Option<(Arc<StreamMetadata>, Cow<'static, str>, Vec<u8>)>,
501}
502
503impl Frames {
504    fn new(method: &str, subscription: &jsonrpsee::types::SubscriptionId<'_>) -> Self {
505        let mut prefix = br#"{"jsonrpc":"2.0","method":"#.to_vec();
506        let _ = serde_json::to_writer(&mut prefix, method);
507        prefix.extend_from_slice(br#","params":{"subscription":"#);
508        let _ = serde_json::to_writer(&mut prefix, subscription);
509        prefix.extend_from_slice(br#","result":"#);
510        Frames { prefix, head: None }
511    }
512
513    /// `item`'s JSON, written at the end of `out`.
514    fn item(&mut self, out: &mut BytesMut, item: &PlexusStreamItem) {
515        match item {
516            PlexusStreamItem::Data { metadata, content_type, content } => {
517                let fresh = match &self.head {
518                    Some((m, ct, _)) => !Arc::ptr_eq(m, metadata) || ct != content_type,
519                    None => true,
520                };
521                if fresh {
522                    let mut head = br#"{"type":"data","metadata":"#.to_vec();
523                    let _ = serde_json::to_writer(&mut head, &**metadata);
524                    head.extend_from_slice(br#","content_type":"#);
525                    let _ = serde_json::to_writer(&mut head, content_type.as_ref());
526                    head.extend_from_slice(br#","content":"#);
527                    self.head = Some((metadata.clone(), content_type.clone(), head));
528                }
529                let head = &self.head.as_ref().expect("made above").2;
530                out.reserve(head.len() + content.json_bytes().map_or(64, Bytes::len) + 1);
531                out.put_slice(head);
532                content.write_json(out);
533                out.put_u8(b'}');
534            }
535            other => {
536                let _ = serde_json::to_writer((&mut *out).writer(), other);
537            }
538        }
539    }
540
541    /// The notification carrying `item`: the frame a socket writes.
542    fn frame(&mut self, buffer: &mut Buffer, item: &PlexusStreamItem) -> Bytes {
543        let content = match item {
544            PlexusStreamItem::Data { content, .. } => content.json_bytes().map_or(256, Bytes::len),
545            _ => 256,
546        };
547        buffer.room(self.prefix.len() + content + 256);
548        buffer.cur.put_slice(&self.prefix);
549        self.item(&mut buffer.cur, item);
550        buffer.cur.put_slice(b"}}");
551        buffer.split()
552    }
553
554    /// `item` alone, for jsonrpsee's sink, which wraps it in the notification.
555    fn raw_item(&mut self, buffer: &mut Buffer, item: &PlexusStreamItem) -> Bytes {
556        buffer.room(512);
557        self.item(&mut buffer.cur, item);
558        buffer.split()
559    }
560}
561
562/// Pipe a call's stream to its accepted subscription: each item encoded
563/// once and written as one frame.
564///
565/// With a [`FrameSink`] in the call's extensions (plexus-transport's socket
566/// loop) each frame goes to the socket's writer as it is, the first fenced
567/// behind the subscription's answer; without one, each item goes to
568/// jsonrpsee's sink as one raw value. A `Request` item (an in-call
569/// question) is bound to this connection first (BIDIR-13). The pipe ends
570/// when the stream does, or when the caller lets go (an unsubscribe, a lost
571/// socket), dropping the stream at once.
572pub async fn pipe(sink: jsonrpsee::SubscriptionSink, stream: super::streaming::PlexusStream, ext: &http::Extensions) -> jsonrpsee::core::SubscriptionResult {
573    let frames = ext.get::<FrameSink>().cloned();
574    let encoding = frames.as_ref().map(FrameSink::encoding).unwrap_or_default();
575    let buffer = Buffer::from_block(frames.as_ref().and_then(FrameSink::take_block));
576    let encoder = Encoder { encoding, buffer: RefCell::new(buffer), depth: Cell::new(0), last: Cell::new(0) };
577    WIRE.scope(encoder, run(sink, stream, frames)).await
578}
579
580async fn run(sink: jsonrpsee::SubscriptionSink, mut stream: super::streaming::PlexusStream, frames: Option<FrameSink>) -> jsonrpsee::core::SubscriptionResult {
581    use futures::StreamExt;
582    let connection = sink.connection_id().0;
583    let mut notification = Frames::new(sink.method_name(), &sink.subscription_id());
584    let mut first = true;
585    let out: jsonrpsee::core::SubscriptionResult = async {
586        loop {
587            let item = tokio::select! {
588                biased;
589                _ = sink.closed() => return Ok(()),
590                item = stream.next() => item,
591            };
592            let Some(item) = item else { return Ok(()) };
593            if let PlexusStreamItem::Request { request_id, .. } = &item {
594                super::bidirectional::bind_asker(request_id, connection);
595            }
596            match &frames {
597                Some(to) => {
598                    let bytes = WIRE.with(|e| notification.frame(&mut e.buffer.borrow_mut(), &item));
599                    drop(item);
600                    if to.tx.send(WireFrame { bytes, fence: first }).await.is_err() {
601                        return Ok(());
602                    }
603                }
604                None => {
605                    let bytes = WIRE.with(|e| notification.raw_item(&mut e.buffer.borrow_mut(), &item));
606                    drop(item);
607                    // jsonrpsee's sink takes a raw value, which it wraps in
608                    // the notification: a copy and a check — the price of a
609                    // transport without frames of its own (stdio, a module
610                    // called in memory).
611                    let raw = RawValue::from_string(String::from_utf8(bytes.to_vec()).unwrap_or_default())?;
612                    sink.send(raw).await?;
613                }
614            }
615            first = false;
616        }
617    }
618    .await;
619    drop(stream);
620    if let Some(to) = &frames {
621        if let Some(block) = WIRE.with(|e| std::mem::take(&mut *e.buffer.borrow_mut())).into_block() {
622            to.give_block(block);
623        }
624    }
625    out
626}
627
628// ---------------------------------------------------------------------------
629// Shared: one event, many streams
630// ---------------------------------------------------------------------------
631
632/// An event many streams send — one change fanned out to every watcher.
633/// The first socket that sends it encodes it, once; every other writes
634/// those bytes as they are (PERF-7's fan-out). Anywhere else (in process, a
635/// `Value`, another encoding) it serializes as `T` does. Reads as `T`.
636///
637/// An event that carries a credential is not kept encoded: each stream
638/// encodes it, so each assembles its own `_credentials` envelope.
639pub struct Shared<T>(Arc<SharedInner<T>>);
640
641struct SharedInner<T> {
642    value: T,
643    /// The JSON the first socket wrote (`None`: never kept — a credential).
644    json: OnceLock<Option<Box<RawValue>>>,
645}
646
647impl<T> Shared<T> {
648    /// `value`, to be sent by many streams.
649    pub fn new(value: T) -> Self {
650        Shared(Arc::new(SharedInner { value, json: OnceLock::new() }))
651    }
652
653    /// Whether this event has been encoded (a socket has sent it).
654    pub fn is_encoded(&self) -> bool {
655        matches!(self.0.json.get(), Some(Some(_)))
656    }
657}
658
659impl<T: Serialize> Shared<T> {
660    fn encoded(&self) -> Option<&RawValue> {
661        self.0
662            .json
663            .get_or_init(|| {
664                let (text, captured) = plexus_auth_core::credential::run_with_credential_capture(|| serde_json::to_string(&self.0.value));
665                match text {
666                    Ok(text) if captured.is_empty() => RawValue::from_string(text).ok(),
667                    _ => None,
668                }
669            })
670            .as_deref()
671    }
672}
673
674impl<T> Clone for Shared<T> {
675    fn clone(&self) -> Self {
676        Shared(self.0.clone())
677    }
678}
679
680impl<T> std::ops::Deref for Shared<T> {
681    type Target = T;
682    fn deref(&self) -> &T {
683        &self.0.value
684    }
685}
686
687impl<T: std::fmt::Debug> std::fmt::Debug for Shared<T> {
688    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
689        self.0.value.fmt(f)
690    }
691}
692
693impl<T: Default> Default for Shared<T> {
694    fn default() -> Self {
695        Shared::new(T::default())
696    }
697}
698
699impl<T: Serialize> Serialize for Shared<T> {
700    fn serialize<S: Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
701        if writing_json() {
702            if let Some(raw) = self.encoded() {
703                return raw.serialize(s);
704            }
705        }
706        self.0.value.serialize(s)
707    }
708}
709
710impl<'de, T: Deserialize<'de>> Deserialize<'de> for Shared<T> {
711    fn deserialize<D: serde::Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
712        T::deserialize(d).map(Shared::new)
713    }
714}
715
716impl<T: schemars::JsonSchema> schemars::JsonSchema for Shared<T> {
717    fn inline_schema() -> bool {
718        T::inline_schema()
719    }
720    fn schema_name() -> Cow<'static, str> {
721        T::schema_name()
722    }
723    fn schema_id() -> Cow<'static, str> {
724        T::schema_id()
725    }
726    fn json_schema(generator: &mut schemars::SchemaGenerator) -> schemars::Schema {
727        T::json_schema(generator)
728    }
729}
730
731#[cfg(test)]
732mod tests {
733    use super::*;
734
735    #[test]
736    fn content_reads_as_its_value_either_way() {
737        let v = serde_json::json!({"b": [1, 2], "a": "x"});
738        let encoded = Content::from_json(Bytes::from_static(br#"{"b":[1,2],"a":"x"}"#)).unwrap();
739        let valued = Content::from(v.clone());
740        assert!(encoded.is_encoded() && !valued.is_encoded());
741        assert_eq!(encoded, v);
742        assert_eq!(valued, v);
743        assert_eq!(encoded, valued);
744        assert_eq!(encoded["a"], "x");
745        assert_eq!(encoded.decode::<serde_json::Map<String, Value>>().unwrap().len(), 2);
746        assert_eq!(serde_json::to_value(&encoded).unwrap(), v);
747        assert_eq!(serde_json::to_string(&encoded).unwrap(), serde_json::to_string(&v).unwrap(), "outside the pipe it writes its Value");
748        assert_eq!(encoded.into_value(), v);
749        assert!(Content::from_json(Bytes::from_static(b"{nope")).is_err());
750    }
751
752    #[test]
753    fn a_buffer_reuses_a_block_once_its_frames_are_gone() {
754        let mut b = Buffer::default();
755        b.room(100);
756        b.cur.put_slice(&[1u8; 100]);
757        let first = b.split();
758        let block = b.cur.capacity() + 100;
759        for _ in 0..1000 {
760            b.room(100);
761            b.cur.put_slice(&[2u8; 100]);
762            drop(b.split());
763        }
764        assert_eq!(first.len(), 100, "a frame in flight stays whole");
765        assert!(b.block <= Buffer::FIRST * 2, "blocks are reused, not grown, when frames are written: {} (first {block})", b.block);
766    }
767}