repe 13.0.0

Rust implementation of the REPE RPC protocol (JSON-focused)
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
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
//! C-ABI plugin surface: expose a [`Router`] as a dynamically loadable plugin.
//!
//! Glaze ships a pure-C plugin ABI (`glaze/rpc/repe/plugin.h`) that a REPE host
//! `dlopen`s and drives by resolving five symbols. The payloads crossing it are
//! ordinary REPE frames, so a `cdylib` built on this crate can be loaded by an
//! existing C++ host with no adapter on either side — which is the cheapest way
//! to introduce Rust into an established C++ REPE deployment, one leaf at a
//! time.
//!
//! The whole surface is generated by [`macro@crate::plugin`]:
//!
//! ```ignore
//! // Cargo.toml: [lib] crate-type = ["cdylib"]
//! use repe::server::Router;
//!
//! #[repe::plugin(root = "/example")]
//! fn build() -> Router {
//!     Router::new().with_typed("/example/echo", |body: String| Ok(body))
//! }
//! ```
//!
//! That emits `repe_plugin_interface_version`, `repe_plugin_info`,
//! `repe_plugin_init`, `repe_plugin_shutdown`, and `repe_plugin_call` with C
//! linkage, all delegating to a [`PluginRuntime`] built from your function. The
//! three things a hand-written shim reliably gets wrong — the version handshake,
//! the response-buffer borrow contract, and the panic guard — are the crate's
//! problem rather than yours.
//!
//! # The response-buffer contract
//!
//! [`repe_buffer`](RepeBuffer) is `{ const char* data; uint64_t size; }` borrowed
//! from a plugin-owned thread-local. It stays valid only until that thread's next
//! call, so **the host must copy before calling again**. Nothing is ever freed
//! across the heap boundary, which is what makes this an unusually clean FFI
//! contract: the plugin owns every allocation it hands out, for its own lifetime.
//!
//! Two details this implementation pins down, both of which are silent
//! divergences if a hand-written shim gets them wrong:
//!
//! * **`size == 0` still carries a non-null `data`.** Glaze's helper returns
//!   `std::string::data()`, which is never null; a C++ host that builds a
//!   `std::string_view` or `std::string` from a null pointer with length 0 is
//!   undefined behavior even though it works in practice. This crate points at a
//!   static byte instead, so the host sees what it sees from a C++ plugin.
//! * **A notify request answers with `size == 0`.** REPE notifies produce no
//!   response, and a host must read zero size as "send nothing" rather than as
//!   an error.
//!
//! # Build with `panic = "unwind"`
//!
//! The generated `repe_plugin_call` wraps dispatch in [`catch_unwind`] so a
//! panicking handler becomes an [`InternalError`](ErrorCode::InternalError)
//! response instead of killing the host. Under `panic = "abort"` — routinely set
//! on embedded targets to shrink binaries — that guard is inert and any handler
//! bug takes the whole process down.
//!
//! The rest of what a *host* has to get right (not `dlclose`ing a Rust plugin,
//! one plugin per `cdylib`) is in the plugin guide rather than here, since none
//! of it is visible from the API.
//!
//! # Driving a plugin
//!
//! The other direction is [`host`], behind the `plugin-host` feature:
//! [`host::Plugin`] loads a library, performs the handshake, and copies each
//! response out before the borrow expires. It drives any conforming plugin, so a
//! Rust host loads a C++ one as readily as one built here.
//!
//! # Concurrency
//!
//! `plugin.h` states that `repe_plugin_call` may be invoked concurrently from
//! multiple threads, each with its own response buffer, and this implementation
//! honors that: the buffer is thread-local and [`Router`] is `Sync`.
//!
//! Whether the *work* runs concurrently is a separate question and depends on
//! what the router holds. A router built with
//! [`with_struct`](Router::with_struct) puts the value behind a `Mutex`, so every
//! call against it — including a pure field read — serializes. A plugin whose
//! handlers block (waiting on hardware, say) and whose host runs at concurrency
//! greater than one will find unrelated reads queued behind them.
//!
//! A panicking handler leaves that `Mutex` poisoned, which the crate reports as a
//! `LockError::Poisoned` error response rather than a second panic — so the
//! plugin degrades to answering errors instead of taking the host with it. Note
//! *how far* it degrades: `std` never clears poison, so every later request under
//! that root, including a read of an unrelated field, answers with an error for
//! the life of the host process. One panicking method retires the whole object.
//! A plugin that must survive a handler bug should not publish its state through
//! [`with_struct`](Router::with_struct).

#[cfg(feature = "plugin-host")]
pub mod host;

use std::cell::RefCell;
use std::panic::{AssertUnwindSafe, catch_unwind};
use std::sync::OnceLock;
use std::sync::atomic::{AtomicBool, Ordering};

use core::ffi::c_char;

use crate::constants::{ErrorCode, HEADER_SIZE};
use crate::header::Header;
use crate::message::create_error_message;
use crate::server::Router;

/// The plugin ABI version this crate implements, mirroring
/// `REPE_PLUGIN_INTERFACE_VERSION` in Glaze's `plugin.h`.
///
/// A host must refuse any plugin whose `repe_plugin_interface_version()` it
/// does not support. Glaze's header recommends an exact-equality check; a host
/// should prefer a range, since a host can reasonably drive an older plugin
/// where a plugin must be exact. That is what
/// [`host::supported_interface_versions`] is, and what
/// [`host::Plugin::load`] checks against.
///
/// This constant is deliberate coupling: the ABI is defined by the protocol, not
/// by either implementation, so a bump on the Glaze side needs a repe release
/// before any Rust host or plugin can speak the new version. That is the same
/// coupling already accepted for the wire format itself, and it is managed the
/// same way — by a CI job pinned to a Glaze tag.
pub const REPE_PLUGIN_INTERFACE_VERSION: u32 = 3;

/// ABI-stable borrowed buffer: Rust's view of `repe_buffer`.
///
/// Returned by `repe_plugin_call`. The pointee belongs to the plugin and is
/// valid only until the next `repe_plugin_call` **on the same thread**; a host
/// that needs to retain the bytes must copy them first. `data` is never null,
/// including when `size` is 0.
#[repr(C)]
#[derive(Clone, Copy, Debug)]
pub struct RepeBuffer {
    /// Start of the response frame. Never null.
    pub data: *const c_char,
    /// Length of the response frame in bytes. Zero means "no response",
    /// which is what a notify request produces.
    pub size: u64,
}

/// A one-byte anchor for [`RepeBuffer::empty`].
///
/// A `Vec` that has never allocated yields a dangling (non-null but
/// unmapped) pointer, and a null pointer is undefined behavior for a C++ host
/// that constructs a `string_view` from it. Pointing at a real static byte is
/// unambiguously valid for a zero-length read under every reading of both
/// languages' rules, and matches what Glaze's `std::string`-backed helper hands
/// back.
static EMPTY_RESPONSE_ANCHOR: u8 = 0;

impl RepeBuffer {
    /// The empty response: `size == 0` with a valid, non-null `data`.
    fn empty() -> Self {
        Self {
            data: (&raw const EMPTY_RESPONSE_ANCHOR).cast::<c_char>(),
            size: 0,
        }
    }

    /// Borrow `bytes` as a buffer, preserving the non-null guarantee when empty.
    ///
    /// # Safety
    ///
    /// The caller must keep `bytes` alive and unmodified for as long as the
    /// returned buffer is in use — for the exported ABI, until this thread's
    /// next `repe_plugin_call`.
    unsafe fn borrowing(bytes: &[u8]) -> Self {
        if bytes.is_empty() {
            return Self::empty();
        }
        Self {
            data: bytes.as_ptr().cast::<c_char>(),
            size: bytes.len() as u64,
        }
    }
}

/// Rust's view of `repe_result`.
///
/// `#[repr(C)]` rather than `#[repr(u32)]`: the C declaration is a plain enum,
/// whose underlying type is the C ABI's enum type (`int`), and `#[repr(C)]` is
/// the representation that tracks it per target.
#[repr(C)]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum RepeResult {
    /// `REPE_OK`.
    Ok = 0,
    /// `REPE_ERROR_INIT_FAILED`: the router constructor panicked, or the plugin
    /// has already been shut down.
    InitFailed = 1,
    /// `REPE_ERROR_ALREADY_INITIALIZED`: `repe_plugin_init` was called twice, or
    /// a call arrived first and initialized the router lazily.
    AlreadyInitialized = 2,
}

/// Rust's view of `repe_plugin_data`: the metadata a host reads to learn a
/// plugin's identity and the RPC path prefix it claims.
///
/// Every pointer must be a nul-terminated string valid for the plugin's whole
/// lifetime. The [`macro@crate::plugin`] attribute builds this from string
/// literals, appending the terminator that a Rust `&str` does not carry.
#[repr(C)]
#[derive(Clone, Copy, Debug)]
pub struct RepePluginData {
    /// Plugin name, e.g. `"calculator"`.
    pub name: *const c_char,
    /// Plugin version string, e.g. `"1.0.0"`.
    pub version: *const c_char,
    /// RPC path prefix this plugin claims, e.g. `"/calculator"`.
    pub root_path: *const c_char,
}

// SAFETY: `RepePluginData` is an immutable POD of pointers to `'static`
// nul-terminated strings. Nothing mutates it after construction, so handing
// `&'static RepePluginData` to another thread exposes no interior mutability and
// no dangling reference. Required because the generated `repe_plugin_info` must
// return a pointer to a `static`.
unsafe impl Sync for RepePluginData {}

thread_local! {
    /// This thread's response buffer, reused across calls so a steady-state
    /// plugin allocates nothing per request.
    ///
    /// The `RefCell` is not for interior mutability — the thread owns it — but to
    /// *detect reentrancy*. If a handler calls back into the host and the host
    /// routes that back into this plugin on the same thread, the inner call would
    /// otherwise overwrite the outer call's in-flight buffer. Borrowing turns
    /// that from memory corruption into a diagnosable error response.
    static RESPONSE: RefCell<Vec<u8>> = const { RefCell::new(Vec::new()) };
}

/// A pre-encoded error frame with process lifetime, for the cases where this
/// thread's response buffer cannot be used at all.
///
/// The message is deliberately generic. Every one of `call_unguarded`'s specific
/// errors is encoded *into* the buffer, so when the buffer is what is missing,
/// the specific reason cannot be reported — naming one of them here would
/// mislabel the others.
///
/// A `OnceLock<Vec<u8>>` is never mutated after initialization, so a pointer into
/// it stays valid for as long as the library is loaded, which satisfies the
/// borrow contract trivially.
fn static_error_frame() -> &'static [u8] {
    static FRAME: OnceLock<Vec<u8>> = OnceLock::new();
    FRAME
        .get_or_init(|| {
            create_error_message(
                ErrorCode::InternalError,
                "repe plugin: this thread's response buffer is unavailable — either a \
                 reentrant repe_plugin_call, or a call made during thread teardown",
            )
            .to_vec()
        })
        .as_slice()
}

/// The state behind a plugin's exported symbols: the router, built once, plus
/// the lifecycle flag.
///
/// Constructed by [`macro@crate::plugin`] as a `static`; you only name this type
/// directly if you are writing the five exports by hand, which is worth doing
/// when the generated shape does not fit — a plugin that must consult its
/// environment before choosing a router, for instance.
///
/// ```no_run
/// use repe::plugin::{PluginRuntime, RepeBuffer};
/// use repe::server::Router;
///
/// #[derive(Default)]
/// struct Echo { message: String }
/// structio::object!(Echo { message });
///
/// fn build() -> Router {
///     Router::new().with_typed("/example/echo", |v: Echo| Ok(v))
/// }
///
/// static RUNTIME: PluginRuntime = PluginRuntime::new(build);
///
/// # #[cfg(any())]
/// #[unsafe(no_mangle)]
/// pub unsafe extern "C" fn repe_plugin_call(
///     request: *const core::ffi::c_char,
///     request_size: u64,
/// ) -> RepeBuffer {
///     unsafe { RUNTIME.call(request, request_size) }
/// }
/// ```
pub struct PluginRuntime {
    router: OnceLock<Router>,
    build: fn() -> Router,
    shutdown: AtomicBool,
    /// Set once the constructor has panicked with no router to show for it.
    ///
    /// `OnceLock` does not latch a failed initialization, and a host is not
    /// obliged to call `repe_plugin_init` at all — `plugin.h` says "the host
    /// assumes initialization is handled lazily" — so without this the
    /// constructor is re-entered on every request for the life of the process.
    /// A constructor that panics *after* claiming something (opening a device,
    /// spawning a worker, taking a lock file) would repeat that side effect
    /// once per request. The constructor is a plain `fn() -> Router` with no
    /// input, so a second attempt has nothing new to succeed with.
    build_failed: AtomicBool,
}

impl PluginRuntime {
    /// Create a runtime that will build its router from `build` on first use.
    ///
    /// `const` so it can initialize a `static`: the router itself is built on
    /// the first `init` or `call`, not at load time, which keeps a plugin's
    /// constructor out of the dynamic loader's path.
    pub const fn new(build: fn() -> Router) -> Self {
        Self {
            router: OnceLock::new(),
            build,
            shutdown: AtomicBool::new(false),
            build_failed: AtomicBool::new(false),
        }
    }

    /// Body of `repe_plugin_init`: build the router if it does not exist yet.
    ///
    /// Reports [`AlreadyInitialized`](RepeResult::AlreadyInitialized) if the
    /// router already exists — whether from an earlier `init` or from a call
    /// that initialized it lazily — and [`InitFailed`](RepeResult::InitFailed)
    /// if the constructor panicked or the plugin has been shut down.
    pub fn init(&self) -> RepeResult {
        if self.shutdown.load(Ordering::Acquire) {
            return RepeResult::InitFailed;
        }
        match self.get_or_build() {
            Some((_, true)) => RepeResult::Ok,
            Some((_, false)) => RepeResult::AlreadyInitialized,
            None => RepeResult::InitFailed,
        }
    }

    /// Body of `repe_plugin_shutdown`: refuse further work.
    ///
    /// The router is not dropped, which diverges from the header's "release all
    /// resources" and is worth knowing when writing a plugin: a `Drop` on
    /// anything the router owns — a device handle, a worker thread — does not
    /// run here.
    ///
    /// It cannot run here. `plugin.h` permits concurrent calls, so a call that
    /// passed the shutdown check on another thread is still holding `&Router`
    /// at this instant, and `OnceLock` offers no way to take the value back out
    /// through a shared reference. Dropping it would trade a contract violation
    /// for a use-after-free. Subsequent calls answer with an error frame
    /// instead, which turns a host that ignores its own contract into a
    /// diagnosable fault rather than a silent one.
    ///
    /// A plugin that must release something at shutdown should own it behind
    /// its own handle rather than expect this to do it.
    pub fn shutdown(&self) {
        self.shutdown.store(true, Ordering::Release);
    }

    /// The router, building it on first use, and the sole place the constructor
    /// runs. Returns whether *this* call built it.
    ///
    /// `get_or_init` rather than `get`-then-`set`: `plugin.h` permits concurrent
    /// `repe_plugin_call` **and** permits a host to skip `repe_plugin_init` ("the
    /// host assumes initialization is handled lazily"), so two worker threads
    /// racing their first request is a conforming host. Under `get`-then-`set`
    /// both would run the constructor and the loser's `Router` would be dropped
    /// while the winner served — closing a file descriptor or resetting hardware
    /// the constructor had claimed. `get_or_init` blocks the loser instead, so
    /// the constructor runs exactly once and nothing is built to be discarded.
    ///
    /// `AssertUnwindSafe`: `self` holds a `Router`, whose handlers are not
    /// `RefUnwindSafe`. A panicking constructor leaves the `OnceLock` empty
    /// rather than half-initialized, so nothing observes a broken value.
    fn get_or_build(&self) -> Option<(&Router, bool)> {
        // Both fast paths before the guard: an already-built router is the
        // common case, and a latched failure must not re-enter the constructor.
        if let Some(router) = self.router.get() {
            return Some((router, false));
        }
        if self.build_failed.load(Ordering::Acquire) {
            return None;
        }

        let mut built_here = false;
        let guarded = catch_unwind(AssertUnwindSafe(|| {
            self.router.get_or_init(|| {
                built_here = true;
                (self.build)()
            })
        }));
        match guarded {
            Ok(router) => Some((router, built_here)),
            // Our constructor panicked. Another thread may still have won the
            // race and initialized it since, in which case the plugin is usable
            // and reporting otherwise would strand a working router.
            Err(_) => match self.router.get() {
                Some(router) => Some((router, false)),
                None => {
                    self.build_failed.store(true, Ordering::Release);
                    None
                }
            },
        }
    }

    /// Body of `repe_plugin_call`: dispatch one REPE request frame.
    ///
    /// Never unwinds. A panicking handler, a malformed frame, and a
    /// shut-down plugin all become REPE error responses, because unwinding
    /// across an `extern "C"` boundary would abort the host process at best.
    ///
    /// # Safety
    ///
    /// `request` must point to `request_size` readable, initialized bytes and
    /// stay valid for the duration of the call, or be null with `request_size`
    /// of 0. The returned buffer borrows from this thread's response buffer and
    /// is invalidated by this thread's next call.
    pub unsafe fn call(&self, request: *const c_char, request_size: u64) -> RepeBuffer {
        // SAFETY: the caller's obligation, restated on this closure.
        let dispatched = catch_unwind(AssertUnwindSafe(|| unsafe {
            self.call_unguarded(request, request_size)
        }));
        match dispatched {
            Ok(buffer) => buffer,
            Err(_) => {
                // The dispatch that would have honored the notify flag never
                // returned, so read the flag here. Answering a notify would put
                // an unsolicited id-0 error frame on the wire for a request no
                // client is awaiting — the one place in this file where a
                // non-empty response to a notify is not simply unavoidable,
                // because the frame did parse.
                //
                // SAFETY: the caller's pointer is valid for the whole call, and
                // the request cannot alias the response buffer — that is
                // rejected before dispatch, so reaching a panic rules it out.
                if unsafe { requested_notify(request, request_size) } {
                    return RepeBuffer::empty();
                }
                // The unwind ran the `RefMut`'s destructor on the way out, so
                // this thread's buffer is free again and can carry the report.
                error_response(
                    ErrorCode::InternalError,
                    "repe plugin: handler panicked while serving the request",
                )
            }
        }
    }

    /// [`call`](Self::call) without the panic guard, so the guard has exactly
    /// one thing to wrap.
    ///
    /// # Safety
    ///
    /// As [`call`](Self::call).
    unsafe fn call_unguarded(&self, request: *const c_char, request_size: u64) -> RepeBuffer {
        if self.shutdown.load(Ordering::Acquire) {
            return error_response(
                ErrorCode::InternalError,
                "repe plugin: repe_plugin_call after repe_plugin_shutdown",
            );
        }

        // Two bounds, not one. `usize::try_from` catches a 64-bit size on a
        // 32-bit target; `isize::MAX` is `from_raw_parts`'s own limit, which a
        // 64-bit target would otherwise sail past into undefined behavior on a
        // host that read a length field as `-1`.
        let size = match usize::try_from(request_size) {
            Ok(size) if size <= isize::MAX as usize => size,
            _ => {
                return error_response(
                    ErrorCode::InvalidHeader,
                    "repe plugin: request_size exceeds the largest addressable object",
                );
            }
        };

        // `from_raw_parts` requires a non-null, aligned pointer even for a
        // zero-length slice, so the empty case cannot go through it. An empty
        // request is not valid REPE either way; it falls through to the parse
        // error below, which is the right answer for it.
        let request = if size == 0 {
            &[][..]
        } else if request.is_null() {
            return error_response(
                ErrorCode::InvalidHeader,
                "repe plugin: null request pointer with a non-zero request_size",
            );
        } else {
            // SAFETY: non-null and `size` readable bytes, per the caller's
            // obligation. `u8` has no alignment requirement, and the slice does
            // not outlive this call.
            unsafe { std::slice::from_raw_parts(request.cast::<u8>(), size) }
        };

        // Must precede dispatch: `call_into` takes `request` and the response
        // buffer as two arguments and clears the second, so if they alias, the
        // first is invalidated while still borrowed. Undefined behavior, and
        // Miri flags it.
        if aliases_response_buffer(request) {
            return error_response(
                ErrorCode::InvalidHeader,
                "repe plugin: the request aliases this thread's response buffer; \
                 a response must be copied before it is fed back in as a request",
            );
        }

        let Some((router, _)) = self.get_or_build() else {
            return error_response(
                ErrorCode::InternalError,
                "repe plugin: router constructor panicked",
            );
        };

        with_response_buffer(|out| {
            if router.call_into(request, out) {
                // SAFETY: `out` is this thread's response buffer. It is not
                // touched again until this thread's next call, which is exactly
                // the lifetime the ABI promises the host.
                unsafe { RepeBuffer::borrowing(out) }
            } else {
                // A notify: no response by protocol.
                RepeBuffer::empty()
            }
        })
    }
}

/// Whether the frame at `request` set the notify flag.
///
/// Only the fixed header is read, and only the flag is taken from it, so a
/// frame whose *payload* lengths are nonsense still answers this question
/// correctly. Anything unreadable answers `false`: a request that cannot be
/// shown to be a notify is treated as awaiting a response, which errs toward a
/// caller receiving a frame it ignores rather than one waiting forever.
///
/// # Safety
///
/// As [`PluginRuntime::call`]: `request` must point to `request_size` readable
/// bytes, or be null with a `request_size` of 0.
unsafe fn requested_notify(request: *const c_char, request_size: u64) -> bool {
    let Ok(size) = usize::try_from(request_size) else {
        return false;
    };
    if request.is_null() || size < HEADER_SIZE || size > isize::MAX as usize {
        return false;
    }
    // SAFETY: non-null, at least `HEADER_SIZE` readable bytes, per the caller's
    // obligation. `u8` has no alignment requirement.
    let header = unsafe { std::slice::from_raw_parts(request.cast::<u8>(), HEADER_SIZE) };
    Header::decode(header).is_ok_and(|header| header.notify != 0)
}

/// Run `f` against this thread's response buffer, falling back to the static
/// frame when this thread has no usable buffer.
///
/// Two conditions reach that fallback, and both must resolve to a value rather
/// than a panic, because one of the callers is the panic guard's own error path:
/// a panic here would escape `catch_unwind` and unwind out of an `extern "C"`
/// function, aborting the host.
///
/// * **Reentrancy** — an outer call on this thread already holds the buffer.
/// * **Thread teardown** — `try_with` rather than `with`, because `with` panics
///   with an `AccessError` once this thread's thread-locals have been destroyed.
///   A host `thread_local` destructor that issues one last call during thread
///   exit (a flush-on-teardown notify) reaches exactly that.
fn with_response_buffer(f: impl FnOnce(&mut Vec<u8>) -> RepeBuffer) -> RepeBuffer {
    // SAFETY (both fallbacks): `static_error_frame` returns a slice with process
    // lifetime that is never mutated after initialization.
    RESPONSE
        .try_with(|cell| match cell.try_borrow_mut() {
            Ok(mut out) => f(&mut out),
            Err(_) => unsafe { RepeBuffer::borrowing(static_error_frame()) },
        })
        .unwrap_or_else(|_| unsafe { RepeBuffer::borrowing(static_error_frame()) })
}

/// Whether `request` points into this thread's response buffer.
///
/// A host that feeds a previous response straight back in as the next request
/// would otherwise have that buffer cleared out from under the slice being read
/// through. The ABI says a response is valid only until the next call, which a
/// host can reasonably misread as "still valid *for* that next call"; this makes
/// the misreading a diagnosable error instead of undefined behavior.
///
/// Compares addresses only — never dereferences, and never holds a borrow across
/// the dispatch that follows.
///
/// It has to run *before* [`with_response_buffer`] rather than inside it, which
/// looks like a redundant second thread-local lookup and is not: that closure
/// receives `&mut Vec<u8>`, and forming a unique reference to the very
/// allocation `request` is borrowed from is the aliasing violation being
/// detected. The check must therefore be made through a shared borrow, before
/// any `&mut` to the buffer exists.
fn aliases_response_buffer(request: &[u8]) -> bool {
    RESPONSE
        .try_with(|cell| {
            cell.try_borrow().is_ok_and(|buffer| {
                let base = buffer.as_ptr() as usize;
                let start = request.as_ptr() as usize;
                // Against capacity, not length: `call_into` may write up to the
                // full allocation before the length catches up.
                start < base + buffer.capacity() && base < start + request.len()
            })
        })
        .unwrap_or(false)
}

/// Encode an id-0 REPE error frame into this thread's response buffer.
///
/// Id 0 because these are the conditions under which the request id is unknown
/// or untrustworthy — an unparseable frame, a panic mid-dispatch, a call against
/// a shut-down plugin. It matches what Glaze's `plugin_error_response` emits.
fn error_response(code: ErrorCode, message: &str) -> RepeBuffer {
    with_response_buffer(|out| {
        out.clear();
        create_error_message(code, message)
            .write_to(out)
            .expect("`Vec<u8>` as a `Write` sink is infallible");
        // SAFETY: as in `call_unguarded` — `out` is this thread's buffer and is
        // untouched until this thread's next call.
        unsafe { RepeBuffer::borrowing(out) }
    })
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::constants::QueryFormat;
    use crate::message::Message;
    use std::sync::atomic::AtomicUsize;

    fn request<T: structio::json::Write + ?Sized>(path: &str, body: &T, notify: bool) -> Vec<u8> {
        Message::builder()
            .id(9)
            .notify(notify)
            .query_str(path)
            .query_format(QueryFormat::JsonPointer)
            .body_json(body)
            .build()
            .to_vec()
    }

    fn router() -> Router {
        Router::new()
            .with_typed("/double", |v: i64| Ok(v * 2))
            .with_typed(
                "/boom",
                |_: Option<i64>| -> Result<i64, (ErrorCode, String)> { panic!("handler exploded") },
            )
    }

    /// SAFETY helper: every call in this module hands a live slice to
    /// `PluginRuntime::call` and copies the response before returning, so no
    /// borrowed buffer outlives the next call.
    fn call(runtime: &PluginRuntime, frame: &[u8]) -> Vec<u8> {
        let buffer = unsafe { runtime.call(frame.as_ptr().cast::<c_char>(), frame.len() as u64) };
        assert!(
            !buffer.data.is_null(),
            "data is never null, even when empty"
        );
        if buffer.size == 0 {
            return Vec::new();
        }
        unsafe {
            std::slice::from_raw_parts(buffer.data.cast::<u8>(), buffer.size as usize).to_vec()
        }
    }

    #[test]
    fn call_round_trips_a_request() {
        let runtime = PluginRuntime::new(router);
        assert_eq!(runtime.init(), RepeResult::Ok);

        let response = call(&runtime, &request("/double", &21i64, false));
        let message = Message::from_slice(&response).unwrap();
        assert_eq!(message.header.id, 9);
        assert_eq!(message.query_str().unwrap(), "/double");
        assert_eq!(message.json_body::<i64>().unwrap(), 42);
    }

    #[test]
    fn notify_answers_with_an_empty_non_null_buffer() {
        let runtime = PluginRuntime::new(router);
        let frame = request("/double", &1i64, true);
        let buffer = unsafe { runtime.call(frame.as_ptr().cast::<c_char>(), frame.len() as u64) };
        assert_eq!(buffer.size, 0);
        assert!(
            !buffer.data.is_null(),
            "a C++ host may build a string_view from this pointer"
        );
        // Dereferenceable, which a dangling `Vec::new()` pointer would not be.
        assert_eq!(unsafe { *buffer.data.cast::<u8>() }, 0);
    }

    #[test]
    fn a_panicking_handler_becomes_an_error_response() {
        let runtime = PluginRuntime::new(router);
        let previous = std::panic::take_hook();
        std::panic::set_hook(Box::new(|_| {}));
        let response = call(&runtime, &request("/boom", &None::<i64>, false));
        std::panic::set_hook(previous);

        let message = Message::from_slice(&response).unwrap();
        assert_eq!(message.error_code(), Some(ErrorCode::InternalError));
        assert!(message.error_message_utf8().unwrap().contains("panicked"));
    }

    #[test]
    fn a_notify_to_a_panicking_handler_answers_nothing() {
        // The panic guard sits outside dispatch, so the notify flag that
        // `route_request_view` would have honored is never read there. Left
        // unhandled, this puts an unsolicited id-0 error frame on the wire for a
        // request no client is awaiting.
        let runtime = PluginRuntime::new(router);
        let previous = std::panic::take_hook();
        std::panic::set_hook(Box::new(|_| {}));
        let response = call(&runtime, &request("/boom", &None::<i64>, true));
        std::panic::set_hook(previous);

        assert!(
            response.is_empty(),
            "a notify gets no response even when the handler panics, got {} bytes",
            response.len()
        );
    }

    #[test]
    fn a_panicking_constructor_is_not_re_entered_on_every_call() {
        // `OnceLock` does not latch a failed initialization, and a host need
        // never call `repe_plugin_init`, so an unlatched failure re-runs the
        // constructor once per request for the life of the process — repeating
        // whatever it had claimed before it panicked.
        static ATTEMPTS: AtomicUsize = AtomicUsize::new(0);
        fn explode() -> Router {
            ATTEMPTS.fetch_add(1, Ordering::SeqCst);
            panic!("constructor exploded")
        }

        let runtime = PluginRuntime::new(explode);
        let previous = std::panic::take_hook();
        std::panic::set_hook(Box::new(|_| {}));
        let frame = request("/double", &1i64, false);
        for _ in 0..5 {
            let response = call(&runtime, &frame);
            let message = Message::from_slice(&response).unwrap();
            assert_eq!(message.error_code(), Some(ErrorCode::InternalError));
        }
        // Init after the latch reports the failure rather than trying again.
        let result = runtime.init();
        std::panic::set_hook(previous);

        assert_eq!(result, RepeResult::InitFailed);
        assert_eq!(
            ATTEMPTS.load(Ordering::SeqCst),
            1,
            "the constructor ran more than once"
        );
    }

    #[test]
    fn a_malformed_frame_is_an_id_zero_error_response() {
        let runtime = PluginRuntime::new(router);
        let response = call(&runtime, b"not a repe frame");
        let message = Message::from_slice(&response).unwrap();
        assert!(message.is_error());
        assert_eq!(message.header.id, 0, "the id was unreadable");
    }

    #[test]
    fn a_null_request_with_a_nonzero_size_is_rejected() {
        let runtime = PluginRuntime::new(router);
        let buffer = unsafe { runtime.call(std::ptr::null(), 32) };
        let response = unsafe {
            std::slice::from_raw_parts(buffer.data.cast::<u8>(), buffer.size as usize).to_vec()
        };
        let message = Message::from_slice(&response).unwrap();
        assert_eq!(message.error_code(), Some(ErrorCode::InvalidHeader));
    }

    #[test]
    fn init_is_idempotent_and_reports_the_second_call() {
        let runtime = PluginRuntime::new(router);
        assert_eq!(runtime.init(), RepeResult::Ok);
        assert_eq!(runtime.init(), RepeResult::AlreadyInitialized);
    }

    #[test]
    fn a_lazily_initialized_router_reports_already_initialized() {
        let runtime = PluginRuntime::new(router);
        call(&runtime, &request("/double", &2i64, false));
        assert_eq!(runtime.init(), RepeResult::AlreadyInitialized);
    }

    #[test]
    fn a_panicking_constructor_fails_init_rather_than_unwinding() {
        fn explode() -> Router {
            panic!("constructor exploded")
        }
        let runtime = PluginRuntime::new(explode);
        let previous = std::panic::take_hook();
        std::panic::set_hook(Box::new(|_| {}));
        let result = runtime.init();
        let response = call(&runtime, &request("/double", &1i64, false));
        std::panic::set_hook(previous);

        assert_eq!(result, RepeResult::InitFailed);
        let message = Message::from_slice(&response).unwrap();
        assert_eq!(message.error_code(), Some(ErrorCode::InternalError));
    }

    #[test]
    fn calls_after_shutdown_are_refused() {
        let runtime = PluginRuntime::new(router);
        assert_eq!(runtime.init(), RepeResult::Ok);
        runtime.shutdown();

        let response = call(&runtime, &request("/double", &1i64, false));
        let message = Message::from_slice(&response).unwrap();
        assert_eq!(message.error_code(), Some(ErrorCode::InternalError));
        assert!(message.error_message_utf8().unwrap().contains("shutdown"));
        assert_eq!(runtime.init(), RepeResult::InitFailed);
    }

    #[test]
    fn the_constructor_runs_once_however_many_threads_race_the_first_call() {
        // `plugin.h` permits concurrent calls and permits skipping
        // `repe_plugin_init`, so racing first requests is a conforming host.
        // Under `get`-then-`set` both threads built and the loser's `Router` was
        // dropped while the winner served.
        static BUILDS: AtomicUsize = AtomicUsize::new(0);
        static RUNTIME: OnceLock<PluginRuntime> = OnceLock::new();
        fn counted() -> Router {
            BUILDS.fetch_add(1, Ordering::Relaxed);
            Router::new().with_typed("/double", |v: i64| Ok(v))
        }
        let _ = RUNTIME.set(PluginRuntime::new(counted));
        let runtime = RUNTIME.get().unwrap();

        std::thread::scope(|scope| {
            for _ in 0..8 {
                scope.spawn(|| {
                    call(runtime, &request("/double", &1i64, false));
                });
            }
        });
        assert_eq!(BUILDS.load(Ordering::Relaxed), 1);
    }

    #[test]
    fn a_request_size_past_the_addressable_limit_is_rejected() {
        // `usize::try_from` alone accepts this on a 64-bit target, and
        // `from_raw_parts` above `isize::MAX` is undefined behavior. A host that
        // read a length field as `-1` lands here.
        let runtime = PluginRuntime::new(router);
        let frame = request("/double", &1i64, false);
        let buffer = unsafe { runtime.call(frame.as_ptr().cast::<c_char>(), u64::MAX) };
        let response = unsafe {
            std::slice::from_raw_parts(buffer.data.cast::<u8>(), buffer.size as usize).to_vec()
        };
        let message = Message::from_slice(&response).unwrap();
        assert_eq!(message.error_code(), Some(ErrorCode::InvalidHeader));
    }

    #[test]
    fn a_request_aliasing_the_response_buffer_is_refused_rather_than_served() {
        // Feeding a response straight back in as the next request. `call_into`
        // would hold it as one argument while clearing the other.
        let runtime = PluginRuntime::new(router);
        let frame = request("/double", &21i64, false);
        let previous = unsafe { runtime.call(frame.as_ptr().cast::<c_char>(), frame.len() as u64) };

        let aliased = unsafe { runtime.call(previous.data, previous.size) };
        let response = unsafe {
            std::slice::from_raw_parts(aliased.data.cast::<u8>(), aliased.size as usize).to_vec()
        };
        let message = Message::from_slice(&response).unwrap();
        assert_eq!(message.error_code(), Some(ErrorCode::InvalidHeader));
        assert!(message.error_message_utf8().unwrap().contains("aliases"));
    }

    #[test]
    fn a_call_during_thread_teardown_answers_instead_of_aborting() {
        // A host `thread_local` destructor issuing one last call. If this
        // thread's `RESPONSE` key was destroyed first, `LocalKey::with` panics
        // with `AccessError` — and that panic would be raised on the guard's own
        // error path, escaping `catch_unwind` and unwinding out of an
        // `extern "C"` function, which aborts the process.
        //
        // Destructor order is not guaranteed, so this exercises the interesting
        // ordering only on platforms that run them in reverse registration
        // order. It cannot fail spuriously: either ordering must answer.
        static RUNTIME: OnceLock<PluginRuntime> = OnceLock::new();
        static ANSWERED: AtomicBool = AtomicBool::new(false);
        let _ = RUNTIME.set(PluginRuntime::new(router));

        struct LastRites;
        impl Drop for LastRites {
            fn drop(&mut self) {
                let runtime = RUNTIME.get().unwrap();
                let frame = request("/double", &1i64, false);
                let buffer =
                    unsafe { runtime.call(frame.as_ptr().cast::<c_char>(), frame.len() as u64) };
                ANSWERED.store(buffer.size > 0 && !buffer.data.is_null(), Ordering::Release);
            }
        }
        thread_local! {
            static LAST_RITES: LastRites = const { LastRites };
        }

        std::thread::spawn(|| {
            // Register the teardown call's destructor first, so `RESPONSE` —
            // registered by the call below — is torn down before it.
            LAST_RITES.with(|_| {});
            call(RUNTIME.get().unwrap(), &request("/double", &1i64, false));
        })
        .join()
        .unwrap();

        assert!(
            ANSWERED.load(Ordering::Acquire),
            "the teardown call must return a frame rather than unwind"
        );
    }

    #[test]
    fn a_reentrant_call_gets_the_static_error_rather_than_a_clobbered_buffer() {
        // A handler that calls back into the same plugin on the same thread —
        // what happens when a plugin asks its host something and the host routes
        // the question back. Without the borrow check, the inner call would
        // overwrite the buffer the outer call is about to return.
        static RUNTIME: OnceLock<PluginRuntime> = OnceLock::new();
        fn reentrant() -> Router {
            Router::new().with_typed("/reenter", |_: Option<i64>| {
                let runtime = RUNTIME.get().expect("runtime is set before dispatch");
                let inner = request("/reenter", &None::<i64>, false);
                let buffer =
                    unsafe { runtime.call(inner.as_ptr().cast::<c_char>(), inner.len() as u64) };
                let bytes = unsafe {
                    std::slice::from_raw_parts(buffer.data.cast::<u8>(), buffer.size as usize)
                };
                let message = Message::from_slice(bytes).unwrap();
                Ok(message.error_message_utf8())
            })
        }
        let _ = RUNTIME.set(PluginRuntime::new(reentrant));
        let runtime = RUNTIME.get().unwrap();

        let response = call(runtime, &request("/reenter", &None::<i64>, false));
        let message = Message::from_slice(&response).unwrap();
        assert!(
            !message.is_error(),
            "the outer call still returns its own intact response"
        );
        let reported: String = message.json_body().unwrap();
        assert!(
            reported.contains("reentrant"),
            "the inner call was told why it could not be served, got: {reported}"
        );
    }
}