Skip to main content

nylon_ring_host/
types.rs

1//! Type definitions and aliases for the nylon-ring-host crate.
2
3use crate::error::NylonRingHostError;
4use crate::{PluginCallGuard, context, context::HostContext};
5use dashmap::DashMap;
6use nylon_ring::NrStatus;
7use rustc_hash::FxBuildHasher;
8use std::collections::HashMap;
9use std::sync::Arc;
10use std::task::Waker;
11use tokio::sync::mpsc;
12
13/// Result type alias for this crate.
14pub type Result<T> = std::result::Result<T, NylonRingHostError>;
15
16/// Pending request state.
17#[derive(Debug)]
18pub(crate) enum Pending {
19    Unary(UnaryPending),
20    Stream(mpsc::Sender<StreamFrame>),
21}
22
23/// Completion state stored inline in the pending-request map.
24#[derive(Debug)]
25pub(crate) enum UnaryPending {
26    Waiting(Option<Waker>),
27    Ready(NrStatus, Vec<u8>),
28}
29
30impl UnaryPending {
31    pub(crate) const fn waiting() -> Self {
32        Self::Waiting(None)
33    }
34}
35
36/// A frame in a streaming response.
37#[derive(Debug)]
38pub struct StreamFrame {
39    pub status: NrStatus,
40    pub data: Vec<u8>,
41}
42
43/// A receiver for streaming responses.
44///
45/// Dropping the receiver unregisters its pending stream from the host.
46pub struct StreamReceiver {
47    inner: mpsc::Receiver<StreamFrame>,
48    host_ctx: Arc<HostContext>,
49    sid: u64,
50    _call_guard: Option<PluginCallGuard>,
51}
52
53impl StreamReceiver {
54    pub(crate) fn new(
55        inner: mpsc::Receiver<StreamFrame>,
56        host_ctx: Arc<HostContext>,
57        sid: u64,
58        call_guard: Option<PluginCallGuard>,
59    ) -> Self {
60        Self {
61            inner,
62            host_ctx,
63            sid,
64            _call_guard: call_guard,
65        }
66    }
67
68    /// Waits for the next stream frame.
69    pub async fn recv(&mut self) -> Option<StreamFrame> {
70        self.inner.recv().await
71    }
72}
73
74impl Drop for StreamReceiver {
75    fn drop(&mut self) {
76        context::cleanup_sid(&self.host_ctx, self.sid);
77    }
78}
79
80/// Fast hash map for pending requests using FxHash.
81pub(crate) type FastPendingMap = DashMap<u64, Pending, FxBuildHasher>;
82
83/// Fast hash map for per-SID state using FxHash.
84pub(crate) type FastStateMap = DashMap<u64, HashMap<String, Vec<u8>>, FxBuildHasher>;
85
86/// Result slot for an in-progress synchronous fast-path call.
87pub(crate) struct UnaryResultSlot {
88    pub(crate) sid: u64,
89    pub(crate) result: Option<(NrStatus, Vec<u8>)>,
90}