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
use serde::Deserialize;
use std::io;
use std::marker::PhantomData;
use std::process::{Command, Stdio};
use std::sync::mpsc::{channel, Receiver, Sender, TryRecvError};
use std::thread;
use std::time::{Duration, Instant};
use thiserror::Error;
use url::Url;
#[derive(Debug, Deserialize)]
struct GetTunnels {
tunnels: Vec<ApiTunnel>,
}
#[derive(Debug, Deserialize)]
struct Config {
addr: Url,
}
#[derive(Debug, Deserialize)]
struct ApiTunnel {
config: Config,
public_url: Url,
}
#[derive(Error, Debug)]
pub enum Error {
#[error(transparent)]
DeserializationError(#[from] serde_json::Error),
#[error("Expected a tunnel but found none")]
TunnelNotFound,
#[error(transparent)]
IOError(#[from] io::Error),
}
#[derive(Debug)]
pub struct Ngrok {
port: u16,
stop: Sender<()>,
exited: Receiver<io::Result<()>>,
started_at: Instant,
}
pub struct Tunnel<'a> {
url: Url,
phantom: PhantomData<&'a str>,
}
impl<'a> Tunnel<'a> {
pub fn http(&self) -> Url {
self.url.clone()
}
pub fn https(&self) -> Url {
let mut http = self.url.clone();
http.set_scheme("https").expect("what could go wrong?");
http
}
}
impl Ngrok {
pub fn tunnel(&self) -> Result<Tunnel<'_>, Error> {
while self.started_at.elapsed().as_secs() < 4 {
thread::sleep(Duration::from_secs(1));
}
match self.exited.try_recv() {
Err(TryRecvError::Disconnected) => Err(TryRecvError::Disconnected),
_ => Ok(()),
}
.expect("Exit channel remains open because instance has not dropped");
let response = ureq::get("http://localhost:4040/api/tunnels")
.call()
.into_json()?;
let response: GetTunnels = serde_json::from_value(response)?;
let url = response
.tunnels
.into_iter()
.find(|tunnel| match tunnel.config.addr.port() {
Some(port) => port == self.port,
None => false,
})
.map(|t| Ok(t.public_url))
.unwrap_or(Err(Error::TunnelNotFound))?;
Ok(Tunnel {
url,
phantom: PhantomData::default(),
})
}
}
impl Drop for Ngrok {
fn drop(&mut self) {
let _result: io::Result<()> = if let Ok(result) = self.exited.try_recv() {
result
} else {
self.stop.send(()).expect("channel is standing");
self.exited.recv().expect("channel is standing")
};
}
}
#[derive(Debug, Clone, Default)]
pub struct NgrokBuilder {
http: Option<()>,
port: Option<u16>,
executable: Option<String>,
}
pub fn builder() -> NgrokBuilder {
NgrokBuilder {
..Default::default()
}
}
impl NgrokBuilder {
pub fn http(&mut self) -> Self {
self.http = Some(());
self.clone()
}
pub fn port(&mut self, port: u16) -> Self {
self.port = Some(port);
self.clone()
}
pub fn executable(&mut self, executable: &str) -> Self {
self.executable = Some(executable.to_string());
self.clone()
}
pub fn run(self) -> Result<Ngrok, &'static str> {
if let NgrokBuilder {
http: Some(()),
port: Some(port),
executable,
} = self
{
let (tx_stop, rx_stop) = channel();
let (tx_exit, rx_exit) = channel();
thread::spawn(move || {
match Command::new(executable.unwrap_or_else(|| "ngrok".to_string()))
.stdout(Stdio::piped())
.arg("http")
.arg(port.to_string())
.spawn()
{
Ok(mut proc) => {
loop {
if let Err(e) = proc.try_wait() {
tx_exit.send(Err(e)).unwrap();
break;
}
match rx_stop.try_recv() {
Ok(()) => {
tx_exit.send(proc.kill()).unwrap();
break;
}
Err(TryRecvError::Empty) => (),
Err(TryRecvError::Disconnected) => {
break;
}
};
}
}
Err(err) => tx_exit.send(Err(err)).unwrap(),
};
});
Ok(Ngrok {
stop: tx_stop,
exited: rx_exit,
port,
started_at: Instant::now(),
})
} else {
Err("You should have specified http and port")
}
}
}
#[cfg(test)]
mod tests {
#[ignore]
#[test]
fn simple() {
let ngrok = crate::builder().http().port(3030).run().unwrap();
ngrok.tunnel().unwrap();
}
}