burrow-client 0.1.1

Embeddable tunnel client library — expose your local server to the internet
Documentation
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
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
//! Embeddable tunnel client library for [burrow](https://github.com/meilisearch/burrow).
//!
//! Expose a local HTTP server to the internet through a public subdomain.
//! Automatically reconnects with exponential backoff if the connection drops.
//!
//! # Example
//!
//! ```no_run
//! use burrow_client::TunnelClient;
//! use std::net::SocketAddr;
//!
//! # #[tokio::main]
//! # async fn main() -> anyhow::Result<()> {
//! let local_addr: SocketAddr = "127.0.0.1:3000".parse()?;
//!
//! let handle = TunnelClient::new("wss://new.meilisearch.link", local_addr)
//!     .subdomain("myapp")
//!     .connect()
//!     .await?;
//!
//! println!("Tunnel live at: {}", handle.url());
//! tokio::signal::ctrl_c().await?;
//! handle.close().await;
//! # Ok(())
//! # }
//! ```

pub use burrow_core;

use std::net::SocketAddr;
use std::sync::Arc;
use std::time::Duration;

use anyhow::{Context, Result};
use bytes::Bytes;
use futures_util::stream::SplitSink;
use futures_util::{SinkExt, StreamExt};
use http_body_util::Full;
use hyper::body::Incoming;
use hyper::client::conn::http1;
use hyper::{Request, Response};
use hyper_util::rt::TokioIo;
use tokio::net::TcpStream;
use tokio::sync::{Mutex, watch};
use tokio::task::JoinHandle;
use tokio_tungstenite::tungstenite::Message;
use tokio_tungstenite::{MaybeTlsStream, WebSocketStream, connect_async};
use tracing::{error, info, warn};

const BACKOFF_INITIAL: Duration = Duration::from_secs(1);
const BACKOFF_MAX: Duration = Duration::from_secs(60);
use burrow_core::{
    ClientMessage, ServerMessage, TUNNEL_WS_PATH, TunnelError, TunnelFrame, TunnelRequest,
    TunnelResponse, decode_frame, encode,
};

type WsSink = SplitSink<WebSocketStream<MaybeTlsStream<TcpStream>>, Message>;

/// A handle to a running tunnel. Dropping it will close the tunnel.
pub struct TunnelHandle {
    url: String,
    _task: JoinHandle<()>,
    shutdown_tx: watch::Sender<bool>,
}

impl TunnelHandle {
    /// The publicly accessible URL assigned by the tunnel server.
    pub fn url(&self) -> &str {
        &self.url
    }

    /// Gracefully shut down the tunnel.
    pub async fn close(self) {
        let _ = self.shutdown_tx.send(true);
        let _ = self._task.await;
    }
}

/// Builder for configuring and connecting a tunnel client.
pub struct TunnelClient {
    server_url: String,
    local_addr: SocketAddr,
    token: Option<String>,
    subdomain: Option<String>,
}

impl TunnelClient {
    pub fn new(server_url: impl Into<String>, local_addr: SocketAddr) -> Self {
        Self {
            server_url: server_url.into(),
            local_addr,
            token: None,
            subdomain: None,
        }
    }

    /// Set an authentication token.
    pub fn token(mut self, token: impl Into<String>) -> Self {
        self.token = Some(token.into());
        self
    }

    /// Request a specific subdomain (e.g. "myapp" → myapp.yourdomain.com).
    pub fn subdomain(mut self, subdomain: impl Into<String>) -> Self {
        self.subdomain = Some(subdomain.into());
        self
    }

    /// Connect to the tunnel server and start forwarding traffic.
    /// Returns a [`TunnelHandle`] with the assigned public URL.
    ///
    /// The client automatically reconnects with exponential backoff if the
    /// connection is lost (e.g. server restart). Reconnection stops when
    /// [`TunnelHandle::close`] is called.
    pub async fn connect(self) -> Result<TunnelHandle> {
        let ws_url = format!(
            "{}/{}",
            self.server_url.trim_end_matches('/'),
            TUNNEL_WS_PATH.trim_start_matches('/')
        );

        info!(url = %ws_url, "connecting to tunnel server");

        let (ws, _response) = connect_async(&ws_url)
            .await
            .context("failed to connect to tunnel server")?;

        let (assigned_url, ws) = handshake(ws, self.token.clone(), self.subdomain.clone()).await?;

        let (shutdown_tx, shutdown_rx) = watch::channel(false);
        let local_addr = self.local_addr;
        let url = assigned_url.clone();
        let token = self.token;
        let subdomain = self.subdomain;

        let task = tokio::spawn(async move {
            run_with_reconnect(ws, ws_url, token, subdomain, local_addr, shutdown_rx).await;
        });

        Ok(TunnelHandle {
            url,
            _task: task,
            shutdown_tx,
        })
    }
}

/// Run the tunnel loop, reconnecting with exponential backoff on disconnect.
async fn run_with_reconnect(
    ws: WebSocketStream<MaybeTlsStream<TcpStream>>,
    ws_url: String,
    token: Option<String>,
    subdomain: Option<String>,
    local_addr: SocketAddr,
    mut shutdown_rx: watch::Receiver<bool>,
) {
    // Run the first connection (already established by connect()).
    if let Err(e) = tunnel_loop(ws, local_addr, shutdown_rx.clone()).await {
        error!(error = %e, "tunnel loop exited with error");
    }

    // If shutdown was requested, don't reconnect.
    if *shutdown_rx.borrow() {
        return;
    }

    let mut backoff = BACKOFF_INITIAL;

    loop {
        warn!(delay = ?backoff, "connection lost, reconnecting");

        tokio::select! {
            _ = shutdown_rx.changed() => {
                info!("shutdown requested, stopping reconnection");
                return;
            }
            _ = tokio::time::sleep(backoff) => {}
        }

        if *shutdown_rx.borrow() {
            return;
        }

        match connect_async(&ws_url).await {
            Ok((ws, _)) => match handshake(ws, token.clone(), subdomain.clone()).await {
                Ok((_url, ws)) => {
                    info!("reconnected to tunnel server");
                    backoff = BACKOFF_INITIAL;

                    if let Err(e) = tunnel_loop(ws, local_addr, shutdown_rx.clone()).await {
                        error!(error = %e, "tunnel loop exited with error");
                    }

                    if *shutdown_rx.borrow() {
                        return;
                    }
                }
                Err(e) => {
                    error!(error = %e, "handshake failed after reconnect");
                }
            },
            Err(e) => {
                error!(error = %e, "reconnection failed");
            }
        }

        backoff = (backoff * 2).min(BACKOFF_MAX);
    }
}

/// Perform the Hello/Assigned handshake over the WebSocket.
async fn handshake(
    mut ws: WebSocketStream<MaybeTlsStream<TcpStream>>,
    token: Option<String>,
    subdomain: Option<String>,
) -> Result<(String, WebSocketStream<MaybeTlsStream<TcpStream>>)> {
    let hello = ClientMessage::Hello {
        token,
        requested_subdomain: subdomain,
    };
    let msg = serde_json::to_string(&hello)?;
    ws.send(Message::Text(msg.into())).await?;

    // Wait for the server's Assigned or Error response.
    while let Some(frame) = ws.next().await {
        let frame = frame.context("WebSocket error during handshake")?;
        match frame {
            Message::Text(text) => {
                let server_msg: ServerMessage = serde_json::from_str(&text)?;
                match server_msg {
                    ServerMessage::Assigned { url, subdomain } => {
                        info!(url = %url, subdomain = %subdomain, "tunnel assigned");
                        return Ok((url, ws));
                    }
                    ServerMessage::Error { message } => {
                        anyhow::bail!("server rejected tunnel: {message}");
                    }
                    _ => continue,
                }
            }
            Message::Ping(_) => continue,
            Message::Close(_) => anyhow::bail!("server closed connection during handshake"),
            _ => continue,
        }
    }
    anyhow::bail!("WebSocket closed before handshake completed")
}

/// Main loop: listen for control messages and binary request frames,
/// proxy each request to the local service, and send back the response.
async fn tunnel_loop(
    ws: WebSocketStream<MaybeTlsStream<TcpStream>>,
    local_addr: SocketAddr,
    mut shutdown_rx: watch::Receiver<bool>,
) -> Result<()> {
    let (ws_tx, mut ws_rx) = ws.split();
    let ws_tx = Arc::new(Mutex::new(ws_tx));

    loop {
        tokio::select! {
            _ = shutdown_rx.changed() => {
                info!("tunnel shutting down");
                let mut tx = ws_tx.lock().await;
                let _ = tx.close().await;
                return Ok(());
            }
            frame = ws_rx.next() => {
                let Some(frame) = frame else {
                    warn!("tunnel WebSocket closed by server");
                    return Ok(());
                };
                let frame = frame?;
                match frame {
                    Message::Text(text) => {
                        let server_msg: ServerMessage = serde_json::from_str(&text)?;
                        match server_msg {
                            ServerMessage::NewConnection { stream_id } => {
                                info!(%stream_id, "new visitor connection");
                            }
                            ServerMessage::Heartbeat => {
                                let pong = serde_json::to_string(&ClientMessage::Heartbeat)?;
                                let mut tx = ws_tx.lock().await;
                                let _ = tx.send(Message::Text(pong.into())).await;
                            }
                            ServerMessage::Error { message } => {
                                error!(%message, "server error");
                            }
                            _ => {}
                        }
                    }
                    Message::Binary(data) => {
                        let ws_tx = ws_tx.clone();
                        let local = local_addr;
                        tokio::spawn(async move {
                            handle_binary_frame(data.to_vec(), local, ws_tx).await;
                        });
                    }
                    Message::Ping(data) => {
                        let mut tx = ws_tx.lock().await;
                        let _ = tx.send(Message::Pong(data)).await;
                    }
                    Message::Close(_) => {
                        info!("server closed tunnel");
                        return Ok(());
                    }
                    _ => {}
                }
            }
        }
    }
}

/// Decode a binary request frame, proxy to local, and send back the response.
async fn handle_binary_frame(data: Vec<u8>, local_addr: SocketAddr, ws_tx: Arc<Mutex<WsSink>>) {
    let (stream_id, frame) = match decode_frame(&data) {
        Ok(f) => f,
        Err(e) => {
            warn!(error = %e, "failed to decode binary frame");
            return;
        }
    };

    let TunnelFrame::Request(request) = frame else {
        warn!(%stream_id, "expected request frame, got something else");
        return;
    };

    // Proxy to local service
    let response_frame = match proxy_to_local(local_addr, &request).await {
        Ok(resp) => TunnelFrame::Response(resp),
        Err(e) => {
            warn!(%stream_id, error = %e, "local proxy failed");
            TunnelFrame::Error(TunnelError {
                message: e.to_string(),
            })
        }
    };

    // Encode and send back
    let binary = encode(stream_id, &response_frame);
    let mut tx = ws_tx.lock().await;
    if let Err(e) = tx.send(Message::Binary(binary.into())).await {
        warn!(%stream_id, error = %e, "failed to send response frame");
    }
}

/// Forward a TunnelRequest to the local service and collect the response.
async fn proxy_to_local(local_addr: SocketAddr, request: &TunnelRequest) -> Result<TunnelResponse> {
    let stream = TcpStream::connect(local_addr)
        .await
        .context("failed to connect to local service")?;

    let io = TokioIo::new(stream);

    let (mut sender, conn) = http1::Builder::new()
        .handshake::<_, Full<Bytes>>(io)
        .await
        .context("HTTP handshake with local service failed")?;

    // Drive the connection in the background
    tokio::spawn(async move {
        if let Err(e) = conn.await {
            warn!(error = %e, "local HTTP connection error");
        }
    });

    // Build the hyper request from the TunnelRequest
    let method: hyper::Method = request.method.parse().context("invalid HTTP method")?;

    let mut builder = Request::builder().method(method).uri(&request.uri);

    for (name, value) in &request.headers {
        builder = builder.header(name.as_str(), value.as_slice());
    }

    let body = if request.body.is_empty() {
        Full::new(Bytes::new())
    } else {
        Full::new(Bytes::from(request.body.clone()))
    };

    let hyper_req = builder.body(body).context("failed to build request")?;

    // Send and collect response
    let resp: Response<Incoming> = sender
        .send_request(hyper_req)
        .await
        .context("local service request failed")?;

    let status = resp.status().as_u16();
    let headers: Vec<(String, Vec<u8>)> = resp
        .headers()
        .iter()
        .map(|(name, value)| (name.to_string(), value.as_bytes().to_vec()))
        .collect();

    let body = http_body_util::BodyExt::collect(resp.into_body())
        .await
        .context("failed to read local response body")?
        .to_bytes()
        .to_vec();

    Ok(TunnelResponse {
        status,
        headers,
        body,
    })
}