rpc_io/config.rs
1//! [`Config`]: how an endpoint behaves, with [`Gate`] and [`Cancellation`].
2
3use std::{borrow::Cow, time::Duration};
4
5use crate::{error_object::ErrorCode, limits::Limits};
6
7/// An endpoint's settings.
8///
9/// | Setting | Default | Meaning |
10/// |---|---|---|
11/// | `limits` | [`Limits::new`] | budgets on incoming messages |
12/// | `max_pending` | 1024 | our requests awaiting answers; one more evicts the oldest |
13/// | `max_in_flight` | 1024 | deferred requests being answered; more are refused with `SERVER_OVERLOADED` |
14/// | `request_timeout` | none | deadline for our requests that set none themselves |
15/// | `cancellation` | [`Cancellation::lsp`] | the cancel notification, both ways; `None` turns cancellation off |
16/// | `gate` | none | an opening request every other request must wait for |
17///
18/// `#[non_exhaustive]`: start from [`Config::new`] and chain `with_*`.
19///
20/// # Examples
21///
22/// ```
23/// use std::time::Duration;
24/// use rpc_io::{Cancellation, Config, Gate};
25///
26/// let lsp = Config::new()
27/// .with_gate(Some(Gate::new("initialize").allow("exit")))
28/// .with_request_timeout(Some(Duration::from_secs(30)));
29/// let mcp = Config::new().with_cancellation(Some(Cancellation::mcp()));
30/// assert_eq!(lsp.max_pending, 1024);
31/// assert_eq!(mcp.cancellation.map(|c| c.id_member), Some("requestId".into()));
32/// ```
33#[derive(Clone, Debug, PartialEq, Eq)]
34#[non_exhaustive]
35pub struct Config {
36 /// Budgets on incoming messages.
37 pub limits: Limits,
38 /// Most of our requests awaiting an answer at once (at least one).
39 pub max_pending: usize,
40 /// Most deferred requests being answered at once.
41 pub max_in_flight: usize,
42 /// The deadline for our requests that do not set their own.
43 pub request_timeout: Option<Duration>,
44 /// How cancellation is spelled, or `None` for none.
45 pub cancellation: Option<Cancellation>,
46 /// The opening request, if the protocol has one.
47 pub gate: Option<Gate>,
48}
49
50impl Config {
51 /// The defaults in the table above.
52 ///
53 /// # Examples
54 ///
55 /// ```
56 /// assert!(rpc_io::Config::new().gate.is_none());
57 /// ```
58 #[must_use]
59 pub fn new() -> Self {
60 Self {
61 limits: Limits::new(),
62 max_pending: 1024,
63 max_in_flight: 1024,
64 request_timeout: None,
65 cancellation: Some(Cancellation::lsp()),
66 gate: None,
67 }
68 }
69
70 /// Sets `limits`.
71 ///
72 /// # Examples
73 ///
74 /// ```
75 /// use rpc_io::{Config, Limits};
76 ///
77 /// let c = Config::new().with_limits(Limits::new().with_max_batch(4));
78 /// assert_eq!(c.limits.max_batch, 4);
79 /// ```
80 #[must_use]
81 pub fn with_limits(mut self, limits: Limits) -> Self {
82 self.limits = limits;
83 self
84 }
85
86 /// Sets `max_pending`.
87 ///
88 /// # Examples
89 ///
90 /// ```
91 /// assert_eq!(rpc_io::Config::new().with_max_pending(8).max_pending, 8);
92 /// ```
93 #[must_use]
94 pub fn with_max_pending(mut self, count: usize) -> Self {
95 self.max_pending = count;
96 self
97 }
98
99 /// Sets `max_in_flight`.
100 ///
101 /// # Examples
102 ///
103 /// ```
104 /// assert_eq!(rpc_io::Config::new().with_max_in_flight(8).max_in_flight, 8);
105 /// ```
106 #[must_use]
107 pub fn with_max_in_flight(mut self, count: usize) -> Self {
108 self.max_in_flight = count;
109 self
110 }
111
112 /// Sets `request_timeout`.
113 ///
114 /// # Examples
115 ///
116 /// ```
117 /// use std::time::Duration;
118 ///
119 /// let c = rpc_io::Config::new().with_request_timeout(Some(Duration::from_secs(5)));
120 /// assert_eq!(c.request_timeout, Some(Duration::from_secs(5)));
121 /// ```
122 #[must_use]
123 pub fn with_request_timeout(mut self, timeout: Option<Duration>) -> Self {
124 self.request_timeout = timeout;
125 self
126 }
127
128 /// Sets `cancellation`.
129 ///
130 /// # Examples
131 ///
132 /// ```
133 /// assert!(rpc_io::Config::new().with_cancellation(None).cancellation.is_none());
134 /// ```
135 #[must_use]
136 pub fn with_cancellation(mut self, cancellation: Option<Cancellation>) -> Self {
137 self.cancellation = cancellation;
138 self
139 }
140
141 /// Sets `gate`.
142 ///
143 /// # Examples
144 ///
145 /// ```
146 /// use rpc_io::{Config, Gate};
147 ///
148 /// let c = Config::new().with_gate(Some(Gate::new("initialize")));
149 /// assert_eq!(c.gate.map(|g| g.method), Some("initialize".into()));
150 /// ```
151 #[must_use]
152 pub fn with_gate(mut self, gate: Option<Gate>) -> Self {
153 self.gate = gate;
154 self
155 }
156}
157
158impl Default for Config {
159 fn default() -> Self {
160 Self::new()
161 }
162}
163
164/// How a protocol spells request cancellation: a notification naming the id
165/// of the request to cancel.
166///
167/// Both directions use it. When the peer sends it for one of our deferred
168/// requests, the request's [`CancelToken`](crate::CancelToken) is set and, if
169/// `reply` is set, the request is answered at once with that error code (LSP:
170/// a cancelled request still gets exactly one response); with `reply: None`
171/// it gets no response at all (MCP: the receiver "SHOULD NOT send a response
172/// for the cancelled request"), and a reply the handler sends later is
173/// dropped. When one of our requests times out, is evicted, or is cancelled,
174/// the peer is sent this notification.
175///
176/// The cancel notification is consumed by the endpoint; it never reaches the
177/// [`Router`](crate::Router).
178///
179/// # Examples
180///
181/// ```
182/// use rpc_io::{Cancellation, ErrorCode};
183///
184/// let lsp = Cancellation::lsp();
185/// assert_eq!((lsp.method.as_ref(), lsp.id_member.as_ref()), ("$/cancelRequest", "id"));
186/// assert_eq!(lsp.reply, Some(ErrorCode::REQUEST_CANCELLED));
187///
188/// // LexerSketch's API (specs/STUDIO.md ยง7.1): `$/cancel {id}`, error 1005.
189/// let studio = Cancellation::new("$/cancel", "id", Some(ErrorCode(1005)));
190/// assert_eq!(studio.reply, Some(ErrorCode(1005)));
191/// ```
192#[derive(Clone, Debug, PartialEq, Eq, Hash)]
193#[non_exhaustive]
194pub struct Cancellation {
195 /// The notification's method.
196 pub method: Cow<'static, str>,
197 /// The `params` member holding the request id.
198 pub id_member: Cow<'static, str>,
199 /// The error code a cancelled request is answered with, or `None` to send
200 /// no response.
201 pub reply: Option<ErrorCode>,
202}
203
204impl Cancellation {
205 /// A cancellation spelled `method {id_member: <id>}`.
206 ///
207 /// # Examples
208 ///
209 /// ```
210 /// let c = rpc_io::Cancellation::new("cancel", "target", None);
211 /// assert_eq!(c.id_member, "target");
212 /// ```
213 #[must_use]
214 pub fn new(
215 method: impl Into<Cow<'static, str>>,
216 id_member: impl Into<Cow<'static, str>>,
217 reply: Option<ErrorCode>,
218 ) -> Self {
219 Self {
220 method: method.into(),
221 id_member: id_member.into(),
222 reply,
223 }
224 }
225
226 /// LSP: `$/cancelRequest {id}`, answered with `RequestCancelled`
227 /// (`-32800`).
228 ///
229 /// # Examples
230 ///
231 /// ```
232 /// assert_eq!(rpc_io::Cancellation::lsp().method, "$/cancelRequest");
233 /// ```
234 #[must_use]
235 pub fn lsp() -> Self {
236 Self::new("$/cancelRequest", "id", Some(ErrorCode::REQUEST_CANCELLED))
237 }
238
239 /// MCP: `notifications/cancelled {requestId}`, and no response for the
240 /// cancelled request.
241 ///
242 /// # Examples
243 ///
244 /// ```
245 /// assert_eq!(rpc_io::Cancellation::mcp().reply, None);
246 /// ```
247 #[must_use]
248 pub fn mcp() -> Self {
249 Self::new("notifications/cancelled", "requestId", None)
250 }
251}
252
253/// An opening request that must succeed before anything else is served (LSP's
254/// `initialize`, MCP's `initialize`, LexerSketch's `auth`).
255///
256/// Until the opening request has been answered successfully:
257///
258/// - other requests are answered with `code` (default
259/// [`SERVER_NOT_INITIALIZED`](ErrorCode::SERVER_NOT_INITIALIZED));
260/// - notifications are dropped (reported as [`Event::Dropped`](crate::Event)),
261/// except the methods in `allow` (LSP's `exit`);
262/// - everything this side sends other than responses (notifications and
263/// requests, from handlers or other threads) is held back, then sent in
264/// order right after the opening response; if the opening request fails,
265/// what was held is discarded and held requests end with
266/// [`CallError::Cancelled`](crate::CallError::Cancelled). A held request
267/// that times out or is cancelled is simply never sent, and an "answer" to
268/// one is treated as unmatched: the peer has never seen it.
269///
270/// The opening request fails when it is answered with an error, and also when
271/// the peer cancels it under a [`Cancellation`] that sends no reply; the gate
272/// then shuts again and a new opening request is served. Afterwards (once it
273/// succeeded) a repeated opening request is answered with `INVALID_REQUEST`,
274/// as is an opening request inside a batch. A gate belongs on the side that
275/// receives the opening request; on the side that sends it, it would hold that
276/// side's own messages forever.
277///
278/// Held messages are kept in memory without a limit (only requests are
279/// bounded, by [`Config::max_pending`]): send little before the gate opens.
280///
281/// # Examples
282///
283/// ```
284/// use rpc_io::{ErrorCode, Gate};
285///
286/// let gate = Gate::new("initialize").allow("exit");
287/// assert_eq!(gate.code, ErrorCode::SERVER_NOT_INITIALIZED);
288/// assert_eq!(gate.allow, ["exit"]);
289/// ```
290#[derive(Clone, Debug, PartialEq, Eq, Hash)]
291#[non_exhaustive]
292pub struct Gate {
293 /// The opening request's method.
294 pub method: Cow<'static, str>,
295 /// The error code for requests that arrive before the gate opens.
296 pub code: ErrorCode,
297 /// Notifications delivered even before the gate opens.
298 pub allow: Vec<Cow<'static, str>>,
299}
300
301impl Gate {
302 /// A gate opened by a successful `method` request.
303 ///
304 /// # Examples
305 ///
306 /// ```
307 /// assert!(rpc_io::Gate::new("auth").allow.is_empty());
308 /// ```
309 #[must_use]
310 pub fn new(method: impl Into<Cow<'static, str>>) -> Self {
311 Self {
312 method: method.into(),
313 code: ErrorCode::SERVER_NOT_INITIALIZED,
314 allow: Vec::new(),
315 }
316 }
317
318 /// Lets the notification `method` through before the gate opens.
319 ///
320 /// # Examples
321 ///
322 /// ```
323 /// let gate = rpc_io::Gate::new("initialize").allow("exit").allow("$/logTrace");
324 /// assert_eq!(gate.allow.len(), 2);
325 /// ```
326 #[must_use]
327 pub fn allow(mut self, method: impl Into<Cow<'static, str>>) -> Self {
328 self.allow.push(method.into());
329 self
330 }
331
332 /// Sets the error code for requests before the gate opens.
333 ///
334 /// # Examples
335 ///
336 /// ```
337 /// use rpc_io::{ErrorCode, Gate};
338 ///
339 /// assert_eq!(Gate::new("auth").with_code(ErrorCode(1010)).code, ErrorCode(1010));
340 /// ```
341 #[must_use]
342 pub fn with_code(mut self, code: ErrorCode) -> Self {
343 self.code = code;
344 self
345 }
346
347 /// Whether the notification `method` passes before the gate opens.
348 pub(crate) fn allows(&self, method: &str) -> bool {
349 self.allow.iter().any(|m| m == method)
350 }
351}