Skip to main content

pb_mapper_server/
task.rs

1//! The work the routing manager is sent, and the work it sends each connection.
2
3use std::net::SocketAddr;
4use std::time::{Duration, Instant};
5
6use pb_mapper_auth::AuthContext;
7use pb_mapper_core::conn_id::RemoteConnId;
8use pb_mapper_protocol::command::{
9    AdminConnectionPage, AdminServicePage, PbConnResponse, PbConnStatusReq,
10};
11use pb_mapper_protocol::secure::ServerHeaderSession;
12use pb_mapper_protocol::transport::RelayStream;
13use tokio_util::sync::CancellationToken;
14
15use crate::guard::ConnLease;
16use crate::manager::{self, ReceiverChan, SenderChan};
17use crate::routing::ImutableKey;
18use crate::{ServerStatusInfo, direct};
19
20pub enum ManagerTask {
21    Direct(direct::DirectTask),
22    Accept {
23        stream: RelayStream,
24        peer_addr: SocketAddr,
25    },
26    Register {
27        key: ImutableKey,
28        conn_id: RemoteConnId,
29        need_codec: bool,
30        is_datagram: bool,
31        protocol_version: u16,
32        conn_sender: ConnTaskSender,
33        /// Cancelled to tear the control connection's socket down.
34        ///
35        /// Separate from `conn_sender` because the two fail independently: a
36        /// registration that has stopped reading leaves the writer blocked inside
37        /// a single `write_msg`, and a `ConnTask` queued behind it is not observed
38        /// until that write returns — which, for a half-open socket, may be never.
39        /// Retirement has to reach the socket without going through the work queue.
40        retire_token: CancellationToken,
41        direct: Option<AuthContext>,
42    },
43    ServerConnActivity {
44        key: ImutableKey,
45        conn_id: RemoteConnId,
46    },
47    Subcribe {
48        key: ImutableKey,
49        conn_id: RemoteConnId,
50        conn_sender: ConnTaskSender,
51        excluded_server_conns: Vec<(RemoteConnId, u64)>,
52        selected: Option<(RemoteConnId, u64)>,
53    },
54    Stream {
55        data_protocol: Option<u16>,
56        key: ImutableKey,
57        stream: RelayStream,
58        session: ServerHeaderSession,
59        /// The provider stream socket's ID, which goes where the stream goes.
60        server: ConnLease,
61        client_id: RemoteConnId,
62        server_generation: u64,
63    },
64    StreamAck {
65        server_id: RemoteConnId,
66        client_id: RemoteConnId,
67        server_generation: u64,
68    },
69    Status {
70        response_sender: tokio::sync::oneshot::Sender<PbConnResponse>,
71        status: PbConnStatusReq,
72        namespace: u64,
73        conn_id: RemoteConnId,
74    },
75    StatusQuery {
76        response_sender: tokio::sync::oneshot::Sender<ServerStatusInfo>,
77    },
78    AdminServiceList {
79        key_id: Option<u64>,
80        page: u32,
81        page_size: u16,
82        response_sender: tokio::sync::oneshot::Sender<AdminServicePage>,
83    },
84    AdminConnectionList {
85        key_id: Option<u64>,
86        page: u32,
87        page_size: u16,
88        response_sender: tokio::sync::oneshot::Sender<AdminConnectionPage>,
89    },
90    AdminConnectionRetire {
91        key: ImutableKey,
92        /// Absent retires every connection registered under `key`.
93        conn_id: Option<RemoteConnId>,
94        response_sender: tokio::sync::oneshot::Sender<u32>,
95    },
96    DeRegisterServerConn {
97        key: ImutableKey,
98        conn_id: RemoteConnId,
99    },
100    RetireServerConn {
101        key: ImutableKey,
102        conn_id: RemoteConnId,
103        reason: String,
104    },
105    /// A single slow stream requests confirmation, not immediate deregistration.
106    SuspectServerConn {
107        key: ImutableKey,
108        conn_id: RemoteConnId,
109        generation: u64,
110    },
111    /// Retire only if no authenticated activity followed the suspicion.
112    ConfirmServerConn {
113        key: ImutableKey,
114        conn_id: RemoteConnId,
115        generation: u64,
116        observed_at: Instant,
117    },
118    /// Look for registrations that stopped renewing their lease, and retire them.
119    ///
120    /// Sent by a ticker task rather than driven by a timer inside the manager loop:
121    /// that loop's single await is a channel receive, and racing it against a tick
122    /// in `tokio::select!` would drop a task the receive had already taken.
123    SweepServerLeases,
124    /// A connection that registered no service ended: a subscriber, a direct
125    /// control connection, or one that registered nothing under its ID.
126    DeRegisterClientConn {
127        /// The provider stream socket that served this subscriber, once one has:
128        /// the connection that sent `Stream`, not the registered control
129        /// connection the subscribe was routed to.
130        server_id: Option<RemoteConnId>,
131        client_id: RemoteConnId,
132    },
133    Shutdown,
134}
135
136#[derive(Debug)]
137pub enum ConnTask {
138    /// Boxed: rare and large, it must not widen every relay mailbox slot.
139    Direct(Box<pb_mapper_protocol::direct::DirectEvent>),
140    RegisterResp {
141        generation: u64,
142        protocol_version: u16,
143        lease_ttl_ms: u64,
144        direct: Option<pb_mapper_protocol::direct::DirectCapability>,
145    },
146    RegisterFailed {
147        code: String,
148        reason: String,
149        retryable: bool,
150    },
151    SubcribeResp {
152        ack_timeout: Duration,
153        server_conn_id: RemoteConnId,
154        server_generation: u64,
155        need_codec: bool,
156        is_datagram: bool,
157    },
158    SubcribeFailed {
159        code: String,
160        reason: String,
161        retryable: bool,
162    },
163    SubcribeRetry {
164        reason: String,
165    },
166    StreamReq {
167        client_id: RemoteConnId,
168        server_generation: u64,
169    },
170    Retire {
171        reason: String,
172    },
173    StreamAck {
174        server_id: RemoteConnId,
175        server_generation: u64,
176    },
177    StreamResp {
178        data_protocol: Option<u16>,
179        /// The ID of the provider stream socket handed over, not of its
180        /// control connection; returned if the stream is dropped on the way.
181        server: ConnLease,
182        server_generation: u64,
183        stream: RelayStream,
184        session: ServerHeaderSession,
185    },
186}
187
188impl ManagerTask {
189    /// Whether this task ends a connection, releasing its reusable routing ID.
190    pub(crate) fn ends_connection(&self) -> bool {
191        matches!(
192            self,
193            Self::DeRegisterServerConn { .. } | Self::DeRegisterClientConn { .. }
194        )
195    }
196}
197
198pub(crate) type ManagerTaskSender = manager::TaskSender;
199pub(crate) type ConnTaskSender = SenderChan<ConnTask>;
200pub(crate) type ConnTaskReceiver = ReceiverChan<ConnTask>;
201
202#[cfg(test)]
203mod task_tests {
204    use super::*;
205
206    /// A mailbox slot is as wide as the widest task, and every registered
207    /// connection preallocates its slots. Handing over a stream is the one large
208    /// task routing needs; anything wider is boxed, as `ConnTask::Direct` is.
209    #[test]
210    fn no_conn_task_is_wider_than_a_stream_hand_off() {
211        let stream_hand_off = size_of::<RelayStream>()
212            + size_of::<ServerHeaderSession>()
213            + size_of::<(Option<u16>, ConnLease, u64)>();
214        assert!(
215            size_of::<ConnTask>() <= stream_hand_off,
216            "ConnTask is {} bytes, a stream hand-off {stream_hand_off}",
217            size_of::<ConnTask>()
218        );
219    }
220}