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
extern crate http;
use std::{
convert::{TryInto, TryFrom},
path::Path,
};
use std::io::{Error as IoError, ErrorKind};
use http::Uri;
use crate::tonic;
use tonic::transport::Channel;
#[derive(Debug, Clone)]
pub enum Endpoint {
Http(Http),
Ipc(Ipc),
}
impl Endpoint {
pub async fn connect(self) -> Result<Channel, Box<dyn std::error::Error>> {
match self {
Endpoint::Http(inner) => futures::future::Either::Left(inner.connect()),
Endpoint::Ipc(inner) => futures::future::Either::Right(inner.connect()),
}
.await
}
pub fn is_ipc(&self) -> bool {
use Endpoint::*;
match self {
Ipc(_) => true,
Http(_) => false,
}
}
pub fn is_http(&self) -> bool {
use Endpoint::*;
match self {
Ipc(_) => false,
Http(_) => true,
}
}
}
#[derive(Debug, Clone)]
pub struct Http(pub(crate) Uri);
#[derive(Debug, Clone)]
pub struct Ipc(pub(crate) std::path::PathBuf);
impl Http {
pub async fn connect(self) -> Result<Channel, Box<dyn std::error::Error>> {
trace!("connecting tcp/ip {:?}", &self.0);
let conn = tonic::transport::Endpoint::new(self.0.to_string())?
.connect()
.await?;
trace!("connected tcp/ip {:?}", &self.0);
Ok(conn)
}
#[allow(clippy::inherent_to_string)]
pub fn to_string(&self) -> String {
self.0.to_string()
}
}
impl Ipc {
pub(crate) async fn create_dir_all(path: &Path) -> Result<(), std::io::Error> {
trace!("preparing ipc fs-path {:?}", &path);
tokio::fs::create_dir_all(path.parent().unwrap_or(path)).await?;
Ok(())
}
pub async fn connect(self) -> Result<Channel, Box<dyn std::error::Error>> {
use tonic::transport::Endpoint;
use crate::transport::Stream;
use tower::service_fn;
trace!("connecting ipc {:?}", &self.0);
let channel = Endpoint::try_from("ipc://dummy")?
.connect_with_connector(service_fn(move |_: Uri| Stream::connect(self.0.clone())))
.await?;
trace!("connected ipc");
Ok(channel)
}
pub fn as_str(&self) -> Option<&str> {
self.0.to_str()
}
}
impl TryInto<std::net::SocketAddr> for Http {
type Error = std::io::Error;
fn try_into(self) -> Result<std::net::SocketAddr, Self::Error> {
let uri = self.0;
let parts = uri.into_parts();
if let Some(scheme) = parts.scheme {
debug_assert!(scheme.as_str().starts_with("http"));
let mut addr = parts
.authority
.as_ref()
.map(|a| a.as_str())
.unwrap_or("")
.to_owned();
if let Some(path) = parts.path_and_query.as_ref() {
match path.as_str() {
"" | "/" => { }
s => addr.push_str(s),
}
}
addr.parse()
.map_err(|err| IoError::new(ErrorKind::Other, format!("{}", err)))
} else {
Err(IoError::new(
ErrorKind::InvalidInput,
"Scheme missed in the uri.",
))
}
}
}
impl TryInto<std::net::SocketAddr> for Endpoint {
type Error = std::io::Error;
fn try_into(self) -> Result<std::net::SocketAddr, Self::Error> {
match self {
Endpoint::Http(http) => http.try_into(),
_ => Err(IoError::new(
ErrorKind::InvalidInput,
"Only `Http` can `into` `SocketAddr`.",
)),
}
}
}
fn uri_to_addr(uri: Uri) -> String {
uri_parts_to_addr(&uri.into_parts())
}
fn uri_parts_to_addr(parts: &http::uri::Parts) -> String {
let mut addr = parts
.authority
.as_ref()
.map(|a| a.as_str())
.unwrap_or("")
.to_owned();
if let Some(path) = parts.path_and_query.as_ref() {
match path.as_str() {
"" | "/" => { }
s => addr.push_str(s),
}
}
addr
}
impl std::str::FromStr for Endpoint {
type Err = crate::StdError;
fn from_str(s: &str) -> Result<Self, Self::Err> {
from_uri(s.parse()?)
}
}
impl TryFrom<Uri> for Endpoint {
type Error = crate::StdError;
fn try_from(uri: Uri) -> Result<Self, Self::Error> {
from_uri(uri)
}
}
impl<'a> TryInto<&'a Path> for &'a Endpoint {
type Error = std::io::Error;
fn try_into(self) -> Result<&'a Path, Self::Error> {
match self {
Endpoint::Ipc(Ipc(pb)) => Ok(pb.as_path()),
_ => Err(IoError::new(
ErrorKind::InvalidInput,
"Only IPC can `into` `Path`.",
)),
}
}
}
pub fn from_uri(uri: Uri) -> Result<Endpoint, crate::StdError> {
if let Some(scheme) = uri.scheme_str() {
match scheme {
"http" | "https" => Ok(Endpoint::Http(Http(uri))),
"ipc" | "uds" => {
let mut addr = uri_to_addr(uri);
match addr.chars().next() {
Some('.') | Some('~') => { }
Some('/') => { }
_ => addr = "/".to_owned() + &addr,
}
Ok(Endpoint::Ipc(Ipc(addr.parse()?)))
}
_ => Err(IoError::new(
ErrorKind::InvalidInput,
format!("Protocol {} not supported", scheme),
)
.into()),
}
} else {
Err(IoError::new(ErrorKind::InvalidInput, "Protocol scheme is missed").into())
}
}
impl TryInto<Uri> for Endpoint {
type Error = http::Error;
fn try_into(self) -> Result<Uri, Self::Error> {
match self {
Endpoint::Ipc(Ipc(pb)) => format!(
"ipc:{}{}",
if pb.is_absolute() { "/" } else { "//" },
pb.to_string_lossy()
)
.parse()
.map_err(|e: http::uri::InvalidUri| e.into()),
Endpoint::Http(Http(uri)) => Ok(uri),
}
}
}
impl std::fmt::Display for Endpoint {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Endpoint::Http(Http(endpoint)) => write!(f, "{}", endpoint.to_string()),
Endpoint::Ipc(Ipc(endpoint)) => write!(f, "{}", endpoint.to_string_lossy()),
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::path::PathBuf;
const IPC_ABS: &str = "ipc://tmp/dir/file";
const IPC_REL: [&str; 2] = ["ipc://./tmp/file", "ipc://../tmp/file"];
const HTTP_URI: [&str; 3] = [
"http://[::1]:50042/",
"http://127.0.0.1:50042/",
"http://sub.example.com:61191/",
];
const HTTP_SOC: [&str; 2] = ["[::1]:50042", "127.0.0.1:50042"];
#[test]
fn from_str_absolete_ipc() {
let endpoint: Result<Endpoint, _> = IPC_ABS.parse();
assert!(endpoint.is_ok());
if let Ok(endpoint) = endpoint {
match endpoint {
Endpoint::Http(_) => panic!("expected IPC"),
Endpoint::Ipc(inner) => {
const INV_PATH: &str = "invalid path";
let path: PathBuf = inner.as_str().expect(INV_PATH).parse().expect(INV_PATH);
assert!(path.is_absolute());
}
}
} else {
unreachable!();
}
}
#[test]
fn from_str_relative_ipc() {
for path in IPC_REL.iter() {
let endpoint: Result<Endpoint, _> = path.parse();
assert!(endpoint.is_ok());
if let Ok(endpoint) = endpoint {
match endpoint {
Endpoint::Http(_) => panic!("expected IPC"),
Endpoint::Ipc(inner) => {
const INV_PATH: &str = "invalid path";
let path: PathBuf =
inner.as_str().expect(INV_PATH).parse().expect(INV_PATH);
assert!(path.is_relative());
}
}
} else {
unreachable!();
}
}
}
#[test]
fn from_str_http() {
for (i, uri) in HTTP_URI.iter().enumerate() {
let endpoint: Result<Endpoint, _> = uri.parse();
assert!(endpoint.is_ok());
if let Ok(endpoint) = endpoint {
match endpoint {
Endpoint::Http(inner) => {
assert_eq!(HTTP_URI[i], &inner.to_string());
}
Endpoint::Ipc(_) => panic!("expected HTTP"),
}
} else {
unreachable!();
}
}
}
#[test]
fn to_uri_absolete_ipc() {
let endpoint: Endpoint = IPC_ABS.parse().unwrap();
let result: Result<Uri, _> = endpoint.try_into();
assert!(result.is_ok());
let uri = result.unwrap();
assert_eq!(IPC_ABS, uri.to_string())
}
#[test]
fn to_uri_relative_ipc() {
for uri in IPC_REL.iter() {
let endpoint: Endpoint = uri.parse().unwrap();
let result: Result<Uri, _> = endpoint.try_into();
assert!(result.is_ok());
assert_eq!(uri, &result.unwrap().to_string())
}
}
#[test]
fn to_uri_http() {
for expected in HTTP_URI.iter() {
let endpoint: Endpoint = expected.parse().unwrap();
let result: Result<Uri, _> = endpoint.try_into();
assert!(result.is_ok());
let uri = result.unwrap().to_string();
assert_eq!(expected, &uri);
}
}
#[test]
fn to_soc_http() {
for (i, uri) in HTTP_URI[..1].iter().enumerate() {
let endpoint: Endpoint = uri.parse().unwrap();
let result: Result<std::net::SocketAddr, _> = endpoint.try_into();
assert!(result.is_ok());
let soc = result.unwrap().to_string();
assert_eq!(HTTP_SOC[i], &soc);
}
}
}