plexus-core 0.7.0

Core infrastructure for Plexus RPC: Activation trait, DynamicHub, schemas
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
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
//! PERF-7: the item path — an item encoded once, by its method's own event
//! type, straight into a buffer its socket writes from.
//!
//! | when | then |
//! | -- | -- |
//! | 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` |
//! | 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 |
//! | 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) |
//! | 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) |
//! | 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 |
//! | 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 |
//! | one change fans out to N watchers ([`Shared`]) | the first socket that sends it encodes it, once; every other writes those bytes |
//!
//! PERF-8 batches frames from here (`results: […]`), PERF-9 adds an encoding
//! ([`WireEncoding`]), PERF-13 relays a child's content as bytes.

use std::borrow::Cow;
use std::cell::{Cell, RefCell};
use std::sync::{Arc, Mutex, OnceLock};

use bytes::{BufMut, Bytes, BytesMut};
use serde::{Deserialize, Serialize, Serializer};
use serde_json::value::RawValue;
use serde_json::Value;

use super::types::{PlexusStreamItem, StreamMetadata};

// ---------------------------------------------------------------------------
// Content
// ---------------------------------------------------------------------------

/// A `data` item's content: the method's event, encoded once (JSON bytes),
/// or a `Value` — whichever the item was made with. Reads as a `Value`
/// either way ([`Content::value`], `Deref`), the bytes decoded once on
/// demand; serializes as its JSON. Equal as JSON is equal.
#[derive(Clone, Default)]
pub struct Content(Repr);

#[derive(Clone)]
enum Repr {
    Value(Value),
    /// JSON text serde_json wrote (valid by construction), and its `Value`
    /// once someone asked for it.
    Json { text: Bytes, value: OnceLock<Value> },
}

impl Default for Repr {
    fn default() -> Self {
        Repr::Value(Value::Null)
    }
}

impl Content {
    /// Content that is a `Value`.
    pub fn from_value(value: Value) -> Self {
        Content(Repr::Value(value))
    }

    /// Content that is JSON text, checked (a parse, no `Value` built).
    pub fn from_json(text: Bytes) -> Result<Self, serde_json::Error> {
        serde_json::from_slice::<serde::de::IgnoredAny>(&text)?;
        Ok(Self::json(text))
    }

    /// JSON text serde_json wrote, taken as it is.
    pub(crate) fn json(text: Bytes) -> Self {
        Content(Repr::Json { text, value: OnceLock::new() })
    }

    /// The content as a `Value` (encoded bytes decoded once, kept).
    pub fn value(&self) -> &Value {
        match &self.0 {
            Repr::Value(v) => v,
            Repr::Json { text, value } => value.get_or_init(|| serde_json::from_slice(text).unwrap_or(Value::Null)),
        }
    }

    /// The content as an owned `Value`.
    pub fn into_value(self) -> Value {
        match self.0 {
            Repr::Value(v) => v,
            Repr::Json { text, value } => value.into_inner().unwrap_or_else(|| serde_json::from_slice(&text).unwrap_or(Value::Null)),
        }
    }

    /// A copy of the content as a `Value`.
    pub fn to_value(&self) -> Value {
        match &self.0 {
            Repr::Value(v) => v.clone(),
            Repr::Json { text, value } => value.get().cloned().unwrap_or_else(|| serde_json::from_slice(text).unwrap_or(Value::Null)),
        }
    }

    /// The content as `T`, decoded straight from its bytes when it is
    /// encoded (no `Value` in between).
    pub fn decode<T: serde::de::DeserializeOwned>(&self) -> Result<T, serde_json::Error> {
        match &self.0 {
            Repr::Value(v) => T::deserialize(v),
            Repr::Json { text, value } => match value.get() {
                Some(v) => T::deserialize(v),
                None => serde_json::from_slice(text),
            },
        }
    }

    /// The JSON text the content was encoded as, when it was.
    pub fn json_bytes(&self) -> Option<&Bytes> {
        match &self.0 {
            Repr::Json { text, .. } => Some(text),
            Repr::Value(_) => None,
        }
    }

    /// Whether the content was encoded once from its event (PERF-7).
    pub fn is_encoded(&self) -> bool {
        matches!(self.0, Repr::Json { .. })
    }

    /// Its JSON text, appended to `out`: the bytes, or the `Value` written.
    fn write_json(&self, out: &mut BytesMut) {
        match &self.0 {
            Repr::Json { text, .. } => out.put_slice(text),
            Repr::Value(v) => {
                let _ = serde_json::to_writer((&mut *out).writer(), v);
            }
        }
    }
}

impl std::ops::Deref for Content {
    type Target = Value;
    fn deref(&self) -> &Value {
        self.value()
    }
}

impl From<Value> for Content {
    fn from(value: Value) -> Self {
        Content::from_value(value)
    }
}

impl From<Content> for Value {
    fn from(content: Content) -> Self {
        content.into_value()
    }
}

/// Whatever a `Value` compares with — another content, a `Value`, a string,
/// a number, a bool — a content compares with as its `Value`.
impl<T: ?Sized> PartialEq<T> for Content
where
    Value: PartialEq<T>,
{
    fn eq(&self, other: &T) -> bool {
        self.value() == other
    }
}

impl PartialEq<Content> for Value {
    fn eq(&self, other: &Content) -> bool {
        self == other.value()
    }
}

impl std::fmt::Debug for Content {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match &self.0 {
            Repr::Value(v) => v.fmt(f),
            Repr::Json { text, .. } => write!(f, "{}", String::from_utf8_lossy(text)),
        }
    }
}

impl std::fmt::Display for Content {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match &self.0 {
            Repr::Value(v) => v.fmt(f),
            Repr::Json { text, .. } => f.write_str(&String::from_utf8_lossy(text)),
        }
    }
}

impl Serialize for Content {
    fn serialize<S: Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
        if let Repr::Json { text, value } = &self.0 {
            // serde_json writes a raw value as it is; any other serializer
            // gets the `Value`.
            if writing_json() {
                if let Ok(raw) = serde_json::from_slice::<&RawValue>(text) {
                    return raw.serialize(s);
                }
            }
            if let Some(v) = value.get() {
                return v.serialize(s);
            }
        }
        self.value().serialize(s)
    }
}

impl<'de> Deserialize<'de> for Content {
    fn deserialize<D: serde::Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
        Value::deserialize(d).map(Content::from_value)
    }
}

impl schemars::JsonSchema for Content {
    fn inline_schema() -> bool {
        <Value as schemars::JsonSchema>::inline_schema()
    }
    fn schema_name() -> Cow<'static, str> {
        <Value as schemars::JsonSchema>::schema_name()
    }
    fn schema_id() -> Cow<'static, str> {
        <Value as schemars::JsonSchema>::schema_id()
    }
    fn json_schema(generator: &mut schemars::SchemaGenerator) -> schemars::Schema {
        <Value as schemars::JsonSchema>::json_schema(generator)
    }
}

// ---------------------------------------------------------------------------
// The connection's encoding and its frames
// ---------------------------------------------------------------------------

/// The encoding of every frame on a connection, fixed when it opens. JSON
/// text until PERF-9 adds msgpack.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
#[non_exhaustive]
pub enum WireEncoding {
    /// JSON-RPC 2.0 objects, one text message each.
    #[default]
    Json,
}

/// A frame ready for a socket, in its connection's encoding.
#[derive(Debug, Clone)]
pub struct WireFrame {
    bytes: Bytes,
    fence: bool,
}

impl WireFrame {
    /// The frame's bytes (JSON text under [`WireEncoding::Json`]).
    pub fn bytes(&self) -> &Bytes {
        &self.bytes
    }

    /// The frame's bytes, owned.
    pub fn into_bytes(self) -> Bytes {
        self.bytes
    }

    /// A call's first frame: written only after every frame the connection's
    /// method table queued before it (its subscription's answer among them,
    /// which jsonrpsee queues when the call is accepted).
    pub fn fenced(&self) -> bool {
        self.fence
    }
}

/// The frames a transport takes from a connection's calls (plexus-transport's
/// socket loop puts one in each call's extensions): each item a frame, in
/// order, written as it is. Cheap to clone.
#[derive(Clone)]
pub struct FrameSink {
    tx: tokio::sync::mpsc::Sender<WireFrame>,
    encoding: WireEncoding,
    /// The connection's pool: one spare block a call starts in, so a short
    /// call allocates none.
    spare: Arc<Mutex<Option<BytesMut>>>,
}

/// What the transport's writer reads a [`FrameSink`]'s frames from.
pub type FrameReceiver = tokio::sync::mpsc::Receiver<WireFrame>;

impl FrameSink {
    /// A connection's frame queue, bounded at `capacity` frames.
    pub fn channel(capacity: usize, encoding: WireEncoding) -> (FrameSink, FrameReceiver) {
        let (tx, rx) = tokio::sync::mpsc::channel(capacity.max(1));
        (FrameSink { tx, encoding, spare: Arc::new(Mutex::new(None)) }, rx)
    }

    /// The connection's encoding.
    pub fn encoding(&self) -> WireEncoding {
        self.encoding
    }

    /// Whether the connection is gone.
    pub fn is_closed(&self) -> bool {
        self.tx.is_closed()
    }

    fn take_block(&self) -> Option<BytesMut> {
        self.spare.lock().ok().and_then(|mut s| s.take())
    }

    fn give_block(&self, block: BytesMut) {
        if block.capacity() <= Buffer::POOLED {
            if let Ok(mut s) = self.spare.lock() {
                if s.is_none() {
                    *s = Some(block);
                }
            }
        }
    }
}

impl std::fmt::Debug for FrameSink {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("FrameSink").field("encoding", &self.encoding).field("closed", &self.tx.is_closed()).finish()
    }
}

// ---------------------------------------------------------------------------
// The buffer: blocks a call's items and frames are written into
// ---------------------------------------------------------------------------

/// A call's buffer. Each item and each frame is written at the end of the
/// current block and split off as `Bytes` sharing it; a block is reused once
/// every frame cut from it has been written and dropped, and a new one is
/// allocated only when none is free.
struct Buffer {
    cur: BytesMut,
    /// Blocks still holding frames in flight, kept to be reused once free.
    spare: Vec<BytesMut>,
    /// The size a new block is made at: grown with the frames it holds.
    block: usize,
    /// Whether a block has been made (or taken from the pool) yet.
    started: bool,
}

impl Default for Buffer {
    fn default() -> Self {
        Buffer { cur: BytesMut::new(), spare: Vec::new(), block: Self::FIRST, started: false }
    }
}

impl Buffer {
    /// A first block: a short call's frames fit.
    const FIRST: usize = 8 * 1024;
    /// The largest block made for a stream's frames (one larger item gets a
    /// block of its own size).
    const MOST: usize = 512 * 1024;
    /// The largest block a connection keeps for its next call.
    const POOLED: usize = 64 * 1024;
    /// Blocks kept to be reused.
    const SPARE: usize = 3;

    fn from_block(block: Option<BytesMut>) -> Self {
        match block {
            Some(cur) => Buffer { block: cur.capacity().max(Self::FIRST), cur, spare: Vec::new(), started: true },
            None => Buffer::default(),
        }
    }

    /// Room for `n` more bytes in the current block: it, or a free block, or
    /// a new one.
    fn room(&mut self, n: usize) {
        if self.cur.capacity() - self.cur.len() >= n || self.cur.try_reclaim(n) {
            return;
        }
        // The current block holds unsent frames, or is too small: keep it
        // for later and take a free one, if any is free.
        let free = self.spare.iter_mut().position(|b| b.try_reclaim(n));
        let next = match free {
            Some(i) => self.spare.swap_remove(i),
            None => {
                // Every block is busy: the frames outrun the socket, so the
                // next block holds more of them.
                if self.started {
                    self.block = (self.block * 2).clamp(Self::FIRST, Self::MOST);
                }
                self.started = true;
                BytesMut::with_capacity(self.block.max(n))
            }
        };
        let old = std::mem::replace(&mut self.cur, next);
        if old.capacity() > 0 {
            if self.spare.len() >= Self::SPARE {
                self.spare.remove(0);
            }
            self.spare.push(old);
        }
    }

    /// What was written since the last split, as `Bytes`.
    fn split(&mut self) -> Bytes {
        self.cur.split().freeze()
    }

    /// The block to give back to the connection's pool: the current one,
    /// whatever is left of it (frames still in flight keep what they hold).
    fn into_block(self) -> Option<BytesMut> {
        (self.cur.capacity() >= 1024).then_some(self.cur)
    }
}

// ---------------------------------------------------------------------------
// The pipe's encoder: the events of the stream the pipe polls
// ---------------------------------------------------------------------------

/// The pipe's encoder, for the task that polls a call's stream.
struct Encoder {
    /// The connection's encoding: JSON until PERF-9 reads it here.
    #[allow(dead_code)]
    encoding: WireEncoding,
    buffer: RefCell<Buffer>,
    /// How deep the poll is in streams [`wrap_stream`] wrapped: only the
    /// outermost encodes — a stream polled inside a method's own (a call
    /// it routes and reads in process) keeps its items as `Value`s.
    ///
    /// [`wrap_stream`]: super::streaming::wrap_stream
    depth: Cell<u32>,
    /// The last content's size, to make room for the next.
    last: Cell<usize>,
}

tokio::task_local! {
    static WIRE: Encoder;
}

thread_local! {
    /// The pipe's serde_json writer is serializing an event on this thread.
    static WRITING_JSON: Cell<u32> = const { Cell::new(0) };
}

/// Whether the serializer at work on this thread is the pipe's JSON writer
/// (so a [`Shared`] event or an encoded [`Content`] may write its bytes as
/// they are).
fn writing_json() -> bool {
    WRITING_JSON.with(|w| w.get() > 0)
}

struct WritingJson;

impl WritingJson {
    fn on() -> Self {
        WRITING_JSON.with(|w| w.set(w.get() + 1));
        WritingJson
    }
}

impl Drop for WritingJson {
    fn drop(&mut self) {
        WRITING_JSON.with(|w| w.set(w.get().saturating_sub(1)));
    }
}

/// Run `poll` (a wrapped stream's poll of its method's stream) one stream
/// deeper: what it yields is not the pipe's to encode.
pub(crate) fn nested<R>(poll: impl FnOnce() -> R) -> R {
    if WIRE.try_with(|e| e.depth.set(e.depth.get() + 1)).is_err() {
        return poll();
    }
    // Put back after the poll, a panic included.
    struct Back;
    impl Drop for Back {
        fn drop(&mut self) {
            let _ = WIRE.try_with(|e| e.depth.set(e.depth.get().saturating_sub(1)));
        }
    }
    let _back = Back;
    poll()
}

/// `event` encoded once into the pipe's buffer — when the pipe is polling
/// this stream directly, the event is not a credential's (whose envelope is
/// assembled as before) and it serializes. `None`: make a `Value` as before.
pub(crate) fn encode<T: Serialize + ?Sized>(event: &T) -> Option<Content> {
    WIRE.try_with(|e| {
        if e.depth.get() > 0 {
            return None;
        }
        let mut buffer = e.buffer.borrow_mut();
        buffer.room(e.last.get().saturating_mul(2).max(256));
        debug_assert!(buffer.cur.is_empty());
        let (written, captured) = plexus_auth_core::credential::run_with_credential_capture(|| {
            let _json = WritingJson::on();
            serde_json::to_writer((&mut buffer.cur).writer(), event).is_ok()
        });
        if !written || !captured.is_empty() {
            buffer.cur.clear();
            return None;
        }
        e.last.set(buffer.cur.len());
        Some(Content::json(buffer.split()))
    })
    .ok()
    .flatten()
}

/// One call's frames: the notification around each item.
struct Frames {
    /// `{"jsonrpc":"2.0","method":M,"params":{"subscription":S,"result":`
    prefix: Vec<u8>,
    /// A `data` item's opening, `{"type":"data","metadata":…,"content_type":…,"content":`,
    /// for the stream's metadata (shared by its items) and content type.
    head: Option<(Arc<StreamMetadata>, Cow<'static, str>, Vec<u8>)>,
}

impl Frames {
    fn new(method: &str, subscription: &jsonrpsee::types::SubscriptionId<'_>) -> Self {
        let mut prefix = br#"{"jsonrpc":"2.0","method":"#.to_vec();
        let _ = serde_json::to_writer(&mut prefix, method);
        prefix.extend_from_slice(br#","params":{"subscription":"#);
        let _ = serde_json::to_writer(&mut prefix, subscription);
        prefix.extend_from_slice(br#","result":"#);
        Frames { prefix, head: None }
    }

    /// `item`'s JSON, written at the end of `out`.
    fn item(&mut self, out: &mut BytesMut, item: &PlexusStreamItem) {
        match item {
            PlexusStreamItem::Data { metadata, content_type, content } => {
                let fresh = match &self.head {
                    Some((m, ct, _)) => !Arc::ptr_eq(m, metadata) || ct != content_type,
                    None => true,
                };
                if fresh {
                    let mut head = br#"{"type":"data","metadata":"#.to_vec();
                    let _ = serde_json::to_writer(&mut head, &**metadata);
                    head.extend_from_slice(br#","content_type":"#);
                    let _ = serde_json::to_writer(&mut head, content_type.as_ref());
                    head.extend_from_slice(br#","content":"#);
                    self.head = Some((metadata.clone(), content_type.clone(), head));
                }
                let head = &self.head.as_ref().expect("made above").2;
                out.reserve(head.len() + content.json_bytes().map_or(64, Bytes::len) + 1);
                out.put_slice(head);
                content.write_json(out);
                out.put_u8(b'}');
            }
            other => {
                let _ = serde_json::to_writer((&mut *out).writer(), other);
            }
        }
    }

    /// The notification carrying `item`: the frame a socket writes.
    fn frame(&mut self, buffer: &mut Buffer, item: &PlexusStreamItem) -> Bytes {
        let content = match item {
            PlexusStreamItem::Data { content, .. } => content.json_bytes().map_or(256, Bytes::len),
            _ => 256,
        };
        buffer.room(self.prefix.len() + content + 256);
        buffer.cur.put_slice(&self.prefix);
        self.item(&mut buffer.cur, item);
        buffer.cur.put_slice(b"}}");
        buffer.split()
    }

    /// `item` alone, for jsonrpsee's sink, which wraps it in the notification.
    fn raw_item(&mut self, buffer: &mut Buffer, item: &PlexusStreamItem) -> Bytes {
        buffer.room(512);
        self.item(&mut buffer.cur, item);
        buffer.split()
    }
}

/// Pipe a call's stream to its accepted subscription: each item encoded
/// once and written as one frame.
///
/// With a [`FrameSink`] in the call's extensions (plexus-transport's socket
/// loop) each frame goes to the socket's writer as it is, the first fenced
/// behind the subscription's answer; without one, each item goes to
/// jsonrpsee's sink as one raw value. A `Request` item (an in-call
/// question) is bound to this connection first (BIDIR-13). The pipe ends
/// when the stream does, or when the caller lets go (an unsubscribe, a lost
/// socket), dropping the stream at once.
pub async fn pipe(sink: jsonrpsee::SubscriptionSink, stream: super::streaming::PlexusStream, ext: &http::Extensions) -> jsonrpsee::core::SubscriptionResult {
    let frames = ext.get::<FrameSink>().cloned();
    let encoding = frames.as_ref().map(FrameSink::encoding).unwrap_or_default();
    let buffer = Buffer::from_block(frames.as_ref().and_then(FrameSink::take_block));
    let encoder = Encoder { encoding, buffer: RefCell::new(buffer), depth: Cell::new(0), last: Cell::new(0) };
    WIRE.scope(encoder, run(sink, stream, frames)).await
}

async fn run(sink: jsonrpsee::SubscriptionSink, mut stream: super::streaming::PlexusStream, frames: Option<FrameSink>) -> jsonrpsee::core::SubscriptionResult {
    use futures::StreamExt;
    let connection = sink.connection_id().0;
    let mut notification = Frames::new(sink.method_name(), &sink.subscription_id());
    let mut first = true;
    let out: jsonrpsee::core::SubscriptionResult = async {
        loop {
            let item = tokio::select! {
                biased;
                _ = sink.closed() => return Ok(()),
                item = stream.next() => item,
            };
            let Some(item) = item else { return Ok(()) };
            if let PlexusStreamItem::Request { request_id, .. } = &item {
                super::bidirectional::bind_asker(request_id, connection);
            }
            match &frames {
                Some(to) => {
                    let bytes = WIRE.with(|e| notification.frame(&mut e.buffer.borrow_mut(), &item));
                    drop(item);
                    if to.tx.send(WireFrame { bytes, fence: first }).await.is_err() {
                        return Ok(());
                    }
                }
                None => {
                    let bytes = WIRE.with(|e| notification.raw_item(&mut e.buffer.borrow_mut(), &item));
                    drop(item);
                    // jsonrpsee's sink takes a raw value, which it wraps in
                    // the notification: a copy and a check — the price of a
                    // transport without frames of its own (stdio, a module
                    // called in memory).
                    let raw = RawValue::from_string(String::from_utf8(bytes.to_vec()).unwrap_or_default())?;
                    sink.send(raw).await?;
                }
            }
            first = false;
        }
    }
    .await;
    drop(stream);
    if let Some(to) = &frames {
        if let Some(block) = WIRE.with(|e| std::mem::take(&mut *e.buffer.borrow_mut())).into_block() {
            to.give_block(block);
        }
    }
    out
}

// ---------------------------------------------------------------------------
// Shared: one event, many streams
// ---------------------------------------------------------------------------

/// An event many streams send — one change fanned out to every watcher.
/// The first socket that sends it encodes it, once; every other writes
/// those bytes as they are (PERF-7's fan-out). Anywhere else (in process, a
/// `Value`, another encoding) it serializes as `T` does. Reads as `T`.
///
/// An event that carries a credential is not kept encoded: each stream
/// encodes it, so each assembles its own `_credentials` envelope.
pub struct Shared<T>(Arc<SharedInner<T>>);

struct SharedInner<T> {
    value: T,
    /// The JSON the first socket wrote (`None`: never kept — a credential).
    json: OnceLock<Option<Box<RawValue>>>,
}

impl<T> Shared<T> {
    /// `value`, to be sent by many streams.
    pub fn new(value: T) -> Self {
        Shared(Arc::new(SharedInner { value, json: OnceLock::new() }))
    }

    /// Whether this event has been encoded (a socket has sent it).
    pub fn is_encoded(&self) -> bool {
        matches!(self.0.json.get(), Some(Some(_)))
    }
}

impl<T: Serialize> Shared<T> {
    fn encoded(&self) -> Option<&RawValue> {
        self.0
            .json
            .get_or_init(|| {
                let (text, captured) = plexus_auth_core::credential::run_with_credential_capture(|| serde_json::to_string(&self.0.value));
                match text {
                    Ok(text) if captured.is_empty() => RawValue::from_string(text).ok(),
                    _ => None,
                }
            })
            .as_deref()
    }
}

impl<T> Clone for Shared<T> {
    fn clone(&self) -> Self {
        Shared(self.0.clone())
    }
}

impl<T> std::ops::Deref for Shared<T> {
    type Target = T;
    fn deref(&self) -> &T {
        &self.0.value
    }
}

impl<T: std::fmt::Debug> std::fmt::Debug for Shared<T> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        self.0.value.fmt(f)
    }
}

impl<T: Default> Default for Shared<T> {
    fn default() -> Self {
        Shared::new(T::default())
    }
}

impl<T: Serialize> Serialize for Shared<T> {
    fn serialize<S: Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
        if writing_json() {
            if let Some(raw) = self.encoded() {
                return raw.serialize(s);
            }
        }
        self.0.value.serialize(s)
    }
}

impl<'de, T: Deserialize<'de>> Deserialize<'de> for Shared<T> {
    fn deserialize<D: serde::Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
        T::deserialize(d).map(Shared::new)
    }
}

impl<T: schemars::JsonSchema> schemars::JsonSchema for Shared<T> {
    fn inline_schema() -> bool {
        T::inline_schema()
    }
    fn schema_name() -> Cow<'static, str> {
        T::schema_name()
    }
    fn schema_id() -> Cow<'static, str> {
        T::schema_id()
    }
    fn json_schema(generator: &mut schemars::SchemaGenerator) -> schemars::Schema {
        T::json_schema(generator)
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn content_reads_as_its_value_either_way() {
        let v = serde_json::json!({"b": [1, 2], "a": "x"});
        let encoded = Content::from_json(Bytes::from_static(br#"{"b":[1,2],"a":"x"}"#)).unwrap();
        let valued = Content::from(v.clone());
        assert!(encoded.is_encoded() && !valued.is_encoded());
        assert_eq!(encoded, v);
        assert_eq!(valued, v);
        assert_eq!(encoded, valued);
        assert_eq!(encoded["a"], "x");
        assert_eq!(encoded.decode::<serde_json::Map<String, Value>>().unwrap().len(), 2);
        assert_eq!(serde_json::to_value(&encoded).unwrap(), v);
        assert_eq!(serde_json::to_string(&encoded).unwrap(), serde_json::to_string(&v).unwrap(), "outside the pipe it writes its Value");
        assert_eq!(encoded.into_value(), v);
        assert!(Content::from_json(Bytes::from_static(b"{nope")).is_err());
    }

    #[test]
    fn a_buffer_reuses_a_block_once_its_frames_are_gone() {
        let mut b = Buffer::default();
        b.room(100);
        b.cur.put_slice(&[1u8; 100]);
        let first = b.split();
        let block = b.cur.capacity() + 100;
        for _ in 0..1000 {
            b.room(100);
            b.cur.put_slice(&[2u8; 100]);
            drop(b.split());
        }
        assert_eq!(first.len(), 100, "a frame in flight stays whole");
        assert!(b.block <= Buffer::FIRST * 2, "blocks are reused, not grown, when frames are written: {} (first {block})", b.block);
    }
}