link_cli/protocol/ipc/
endpoint.rs1use super::KINDS;
4use std::collections::BTreeMap;
5use std::fmt;
6use std::io;
7use std::time::Duration;
8
9#[derive(Clone, Debug, PartialEq, Eq)]
14pub struct Endpoint {
15 kind: String,
16 address: String,
17 options: BTreeMap<String, String>,
18}
19
20const COMMON: &[&str] = &["timeout"];
21const RENDEZVOUS: &[&str] = &["poll", "accept-poll"];
22const RING: &[&str] = &["capacity"];
23const DATAGRAM: &[&str] = &["chunk", "rto"];
24
25fn options_of(kind: &str) -> Vec<&'static str> {
26 let mut names: Vec<&'static str> = COMMON.to_vec();
27 match kind {
28 "tcp" | "unix" | "stdio" | "exec" => {}
29 "pipe" => {
30 if cfg!(unix) {
31 names.extend(RENDEZVOUS);
32 }
33 }
34 "fifo" => names.extend(RENDEZVOUS),
35 "shm" | "mmap" | "file" => {
36 names.extend(RENDEZVOUS);
37 names.extend(RING);
38 }
39 "signal" => {
40 names.extend(RENDEZVOUS);
41 names.extend(RING);
42 names.push("signo");
43 }
44 "udp" => {
45 names.extend(DATAGRAM);
46 names.extend(["heartbeat", "dead"]);
47 }
48 "mq" => {
49 names.extend(RENDEZVOUS);
50 names.extend(DATAGRAM);
51 names.push("maxmsg");
52 }
53 "sysvmq" | "mailslot" | "copydata" | "alpc" => {
54 names.extend(RENDEZVOUS);
55 names.extend(DATAGRAM);
56 }
57 _ => return Vec::new(),
58 }
59 names
60}
61
62impl Endpoint {
63 pub fn parse(text: &str) -> io::Result<Self> {
65 let text = text.trim();
66 if text.is_empty() {
67 return Err(invalid("an endpoint must not be empty".to_string()));
68 }
69 let (kind, rest) = match text.split_once(':') {
70 Some((prefix, rest)) if is_kind(prefix) => (prefix.to_ascii_lowercase(), rest),
71 None if is_kind(text) => (text.to_ascii_lowercase(), ""),
72 _ => ("tcp".to_string(), text),
73 };
74 if kind == "exec" {
75 if rest.trim().is_empty() {
76 return Err(invalid("`exec:` needs a command".to_string()));
77 }
78 return Ok(Self {
79 kind,
80 address: rest.to_string(),
81 options: BTreeMap::new(),
82 });
83 }
84 let (address, query) = match rest.split_once('?') {
85 Some((address, query)) => (address, Some(query)),
86 None => (rest, None),
87 };
88 let mut options = BTreeMap::new();
89 if let Some(query) = query {
90 let builtin = KINDS.contains(&kind.as_str());
91 let allowed = options_of(&kind);
92 for pair in query.split('&').filter(|pair| !pair.is_empty()) {
93 let (name, value) = pair
94 .split_once('=')
95 .ok_or_else(|| invalid(format!("endpoint option `{pair}` needs a `=value`")))?;
96 let name = name.to_ascii_lowercase();
97 if builtin && !allowed.contains(&name.as_str()) {
98 return Err(invalid(format!(
99 "`{kind}:` endpoints have no option `{name}`{}",
100 if allowed.is_empty() {
101 String::new()
102 } else {
103 format!(" (options: {})", allowed.join(", "))
104 }
105 )));
106 }
107 options.insert(name, value.to_string());
108 }
109 }
110 let endpoint = Self {
111 kind,
112 address: address.to_string(),
113 options,
114 };
115 endpoint.validate()?;
116 Ok(endpoint)
117 }
118
119 fn validate(&self) -> io::Result<()> {
120 let needs_address = !matches!(self.kind.as_str(), "stdio");
121 if needs_address && self.address.is_empty() && KINDS.contains(&self.kind.as_str()) {
122 return Err(invalid(format!(
123 "`{}:` endpoints need an address",
124 self.kind
125 )));
126 }
127 if self.kind == "stdio" && !self.address.is_empty() {
128 return Err(invalid("`stdio` takes no address".to_string()));
129 }
130 for name in ["timeout", "poll", "accept-poll", "heartbeat", "dead", "rto"] {
131 self.millis(name, 1)?;
132 }
133 self.number("capacity", 65536, 64, 1 << 30)?;
134 self.number("chunk", 4096, 16, 65000)?;
135 self.number("maxmsg", 8, 1, 65536)?;
136 self.number("signo", 12, 1, 64)?;
137 Ok(())
138 }
139
140 pub fn kind(&self) -> &str {
142 &self.kind
143 }
144
145 pub fn address(&self) -> &str {
147 &self.address
148 }
149
150 pub fn option(&self, name: &str) -> Option<&str> {
152 self.options.get(name).map(String::as_str)
153 }
154
155 pub fn options(&self) -> &BTreeMap<String, String> {
157 &self.options
158 }
159
160 pub fn number(&self, name: &str, default: u64, min: u64, max: u64) -> io::Result<u64> {
162 match self.option(name) {
163 None => Ok(default),
164 Some(text) => match text.parse::<u64>() {
165 Ok(value) if (min..=max).contains(&value) => Ok(value),
166 _ => Err(invalid(format!(
167 "endpoint option `{name}` must be a whole number from {min} to {max}, found `{text}`"
168 ))),
169 },
170 }
171 }
172
173 pub fn millis(&self, name: &str, default: u64) -> io::Result<Duration> {
175 self.number(name, default, 0, 86_400_000)
176 .map(Duration::from_millis)
177 }
178
179 pub fn timeout(&self) -> Duration {
181 self.millis("timeout", 10_000)
182 .unwrap_or(Duration::from_secs(10))
183 .max(Duration::from_millis(1))
184 }
185}
186
187impl fmt::Display for Endpoint {
188 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
189 if self.address.is_empty() {
190 write!(formatter, "{}", self.kind)?;
191 } else {
192 write!(formatter, "{}:{}", self.kind, self.address)?;
193 }
194 let mut separator = '?';
195 for (name, value) in &self.options {
196 write!(formatter, "{separator}{name}={value}")?;
197 separator = '&';
198 }
199 Ok(())
200 }
201}
202
203impl std::str::FromStr for Endpoint {
204 type Err = io::Error;
205
206 fn from_str(text: &str) -> io::Result<Self> {
207 Self::parse(text)
208 }
209}
210
211fn is_kind(prefix: &str) -> bool {
212 let lower = prefix.to_ascii_lowercase();
213 KINDS.contains(&lower.as_str()) || super::is_registered(&lower)
214}
215
216fn invalid(message: String) -> io::Error {
217 io::Error::new(io::ErrorKind::InvalidInput, message)
218}