meerkly_sdk/lib.rs
1//! Runtime-agnostic meerkly exit-node core.
2//!
3//! This crate is the single implementation of the exit node, wrapped by every
4//! platform binding (`client-napi` for Node, `client-ffi` for
5//! Kotlin/Go/Swift/Python). It holds exactly one QUIC connection to one gateway,
6//! opens outbound TCP sockets on demand, and reconnects automatically.
7//!
8//! **Runtime ownership.** Unlike a Node addon, the FFI bindings have no ambient
9//! async runtime, so [`ProxyClient`] takes an explicit [`tokio::runtime::Handle`]
10//! and runs the supervisor on it. The endpoint driver and every connection task
11//! therefore share one runtime regardless of which runtime drives `start()`.
12//!
13//! **Ephemeral-session lifecycle.** Built for host apps that cannot run in the
14//! background: fast `start()`, clean fast `stop()`, and no assumption that a
15//! session lasts more than seconds.
16
17mod config;
18mod connection;
19mod guard;
20mod tls;
21
22pub use config::{
23 default_ca_cert_path, CaCert, ClientConfig, DEFAULT_CONNECT_TIMEOUT, DEFAULT_GATEWAY_ADDRESSES,
24 DEFAULT_KEEP_ALIVE, DEFAULT_MAX_BACKOFF, DEFAULT_MAX_IDLE, DEFAULT_MIN_BACKOFF,
25 DEFAULT_START_TIMEOUT,
26};
27pub use connection::{RejectionSlot, State, Supervisor};
28
29use anyhow::{anyhow, Result};
30use std::sync::atomic::{AtomicBool, Ordering};
31use std::sync::Arc;
32use std::time::Duration;
33use tokio::sync::watch;
34
35/// Semantic version of the client core, surfaced to bindings for the register
36/// handshake's `client_version`.
37pub const VERSION: &str = env!("CARGO_PKG_VERSION");
38
39struct Inner {
40 config: ClientConfig,
41 handle: tokio::runtime::Handle,
42 state_tx: watch::Sender<State>,
43 state_rx: watch::Receiver<State>,
44 shutdown_tx: watch::Sender<bool>,
45 started: AtomicBool,
46 rejection: RejectionSlot,
47 /// The host's transport; see [`ProxyClient::set_network`]. Lives here, not
48 /// in the supervisor, so it can be set before `start()` and survives the
49 /// supervisor's reconnects.
50 network_tx: watch::Sender<Option<String>>,
51}
52
53/// A handle to a single exit-node client.
54///
55/// Construction validates the config but does no I/O; [`start`](Self::start)
56/// spawns the connection supervisor on the runtime handle and resolves once the
57/// client has registered with a gateway.
58///
59/// Cheaply cloneable (it is an `Arc` inside); clones share one supervisor, so a
60/// binding can move a clone into an async task without borrowing the handle.
61#[derive(Clone)]
62pub struct ProxyClient {
63 inner: Arc<Inner>,
64}
65
66impl ProxyClient {
67 /// Validate the config and prepare a client bound to `handle`.
68 ///
69 /// The supervisor — and thus the QUIC endpoint and all connection tasks —
70 /// runs on `handle`. A Node binding passes its ambient runtime handle; a JNI
71 /// or PyO3 binding creates a multi-threaded, timer-enabled runtime and passes
72 /// its handle.
73 pub fn new(mut config: ClientConfig, handle: tokio::runtime::Handle) -> Result<Self> {
74 // An empty address list means "wherever Meerkly is", not "nowhere".
75 //
76 // ClientConfig::new already fills this, but every binding builds the
77 // struct literally instead — client-ffi and client-napi both do — so the
78 // default never reached them and an omitted list was rejected as invalid.
79 // Filling it here rather than in each binding is what makes the SDK
80 // documentation true for all of them at once, and means the next binding
81 // cannot forget.
82 //
83 // A host that names its own gateways is untouched; only the empty case
84 // is filled.
85 if config.gateway_addresses.is_empty() {
86 config.gateway_addresses = DEFAULT_GATEWAY_ADDRESSES
87 .iter()
88 .map(|a| (*a).to_owned())
89 .collect();
90 }
91 config.validate()?;
92 let (state_tx, state_rx) = watch::channel(State::Idle);
93 let (shutdown_tx, _) = watch::channel(false);
94 Ok(Self {
95 inner: Arc::new(Inner {
96 config,
97 handle,
98 state_tx,
99 state_rx,
100 shutdown_tx,
101 started: AtomicBool::new(false),
102 rejection: RejectionSlot::default(),
103 network_tx: watch::channel(None).0,
104 }),
105 })
106 }
107
108 /// Connect to a gateway and start serving proxy requests.
109 ///
110 /// Resolves once the client is registered with a gateway. Rejects if no
111 /// gateway accepts the client within `start_timeout`, leaving the client
112 /// stopped so the caller can decide whether to retry.
113 pub async fn start(&self) -> Result<()> {
114 let inner = self.inner.clone();
115 if inner.started.swap(true, Ordering::SeqCst) {
116 return Err(anyhow!("this client has already been started"));
117 }
118
119 // Build and run the supervisor on the client's own runtime, so the QUIC
120 // endpoint driver and all connection tasks share it regardless of which
121 // runtime is driving `start()`. A construction failure (bad CA, endpoint
122 // bind) is surfaced here rather than swallowed by the spawned task.
123 let (created_tx, created_rx) = tokio::sync::oneshot::channel::<Result<()>>();
124 {
125 let config = inner.config.clone();
126 let state_tx = inner.state_tx.clone();
127 let shutdown_tx = inner.shutdown_tx.clone();
128 let rejection = inner.rejection.clone();
129 let network = inner.network_tx.subscribe();
130 inner.handle.spawn(async move {
131 match Supervisor::new(config, state_tx, shutdown_tx) {
132 Ok(supervisor) => {
133 let supervisor = supervisor
134 .with_rejection_slot(rejection)
135 .with_network(network);
136 let _ = created_tx.send(Ok(()));
137 supervisor.run().await;
138 }
139 Err(e) => {
140 let _ = created_tx.send(Err(e));
141 }
142 }
143 });
144 }
145 match created_rx.await {
146 Ok(Ok(())) => {}
147 Ok(Err(e)) => {
148 inner.started.store(false, Ordering::SeqCst);
149 return Err(e);
150 }
151 Err(_) => {
152 inner.started.store(false, Ordering::SeqCst);
153 return Err(anyhow!("supervisor task dropped before starting"));
154 }
155 }
156
157 let mut state_rx = inner.state_rx.clone();
158 let wait = async {
159 loop {
160 if matches!(*state_rx.borrow_and_update(), State::Connected { .. }) {
161 return;
162 }
163 if state_rx.changed().await.is_err() {
164 return;
165 }
166 }
167 };
168
169 match tokio::time::timeout(inner.config.start_timeout, wait).await {
170 Ok(()) if self.connected() => Ok(()),
171 _ => {
172 let _ = inner.shutdown_tx.send(true);
173 inner.started.store(false, Ordering::SeqCst);
174 let base = format!(
175 "no gateway accepted this client within {:?} (tried {})",
176 inner.config.start_timeout,
177 inner.config.gateway_addresses.join(", ")
178 );
179 Err(match self.last_rejection() {
180 Some(reason) => anyhow!("{base}: {reason}"),
181 None => anyhow!(base),
182 })
183 }
184 }
185 }
186
187 /// Close the QUIC connection and stop reconnecting.
188 pub async fn stop(&self) -> Result<()> {
189 let inner = self.inner.clone();
190 let _ = inner.shutdown_tx.send(true);
191
192 let mut state_rx = inner.state_rx.clone();
193 // Bounded so `stop()` cannot hang a shutdown path if the supervisor is
194 // wedged mid-connection.
195 let _ = tokio::time::timeout(Duration::from_secs(5), async {
196 loop {
197 if matches!(*state_rx.borrow_and_update(), State::Stopped) {
198 return;
199 }
200 if state_rx.changed().await.is_err() {
201 return;
202 }
203 }
204 })
205 .await;
206
207 inner.started.store(false, Ordering::SeqCst);
208 Ok(())
209 }
210
211 /// Whether the client currently holds a connection to a gateway.
212 pub fn connected(&self) -> bool {
213 matches!(*self.inner.state_rx.borrow(), State::Connected { .. })
214 }
215
216 /// The gateway currently serving this client, or `None` when disconnected.
217 pub fn gateway_id(&self) -> Option<String> {
218 match &*self.inner.state_rx.borrow() {
219 State::Connected { gateway_id, .. } => Some(gateway_id.clone()),
220 _ => None,
221 }
222 }
223
224 /// One of `idle`, `connecting`, `connected`, `stopped`.
225 pub fn state(&self) -> State {
226 self.inner.state_rx.borrow().clone()
227 }
228
229 /// The reason the gateway gave the last time it refused this client — for
230 /// example "another device is already connected from this IP address" — or
231 /// `None` if it has not refused it since the last successful connection.
232 ///
233 /// Only the gateway's own refusals, which are written to be shown to a
234 /// person; network failures are not reported here. The client keeps
235 /// retrying either way, so this can be set while [`state`](Self::state) is
236 /// `Connecting` or `Idle`.
237 pub fn last_rejection(&self) -> Option<String> {
238 self.inner.rejection.lock().ok().and_then(|r| r.clone())
239 }
240
241 /// The cluster-wide identity the gateway assigned to *this connection*
242 /// (`account:instance-id`), or `None` until connected. Ephemeral: a
243 /// reconnect yields a new one. It is what keeps two concurrent connections
244 /// from one machine distinguishable; the persistent identity, if the host
245 /// keeps one, is [`ClientConfig::device_id`], and is reported separately.
246 /// Tell the gateway which transport the host is on: `"cellular"`,
247 /// `"wifi"`, `"ethernet"` or `"other"`; `None` when unknown.
248 ///
249 /// Call it before `start()` and again whenever the platform reports a
250 /// change (on Android, a `ConnectivityManager` callback). The gateway
251 /// combines it with the network it measures the exit on to classify it as
252 /// mobile, residential or datacenter, which is what proxy customers select
253 /// by. It can only refine that measurement: an exit on a hosting network is
254 /// a datacenter exit whatever it reports.
255 ///
256 /// A live connection passes the change on at once when its gateway
257 /// supports that, and otherwise on the next connection. Values are
258 /// trimmed and lowercased; an empty one means `None`.
259 pub fn set_network(&self, network: Option<String>) {
260 let network = network
261 .map(|n| n.trim().to_ascii_lowercase())
262 .filter(|n| !n.is_empty());
263 self.inner.network_tx.send_if_modified(|current| {
264 let changed = *current != network;
265 *current = network;
266 changed
267 });
268 }
269
270 /// The transport last passed to [`Self::set_network`].
271 pub fn network(&self) -> Option<String> {
272 self.inner.network_tx.borrow().clone()
273 }
274
275 pub fn client_key(&self) -> Option<String> {
276 match &*self.inner.state_rx.borrow() {
277 State::Connected { client_key, .. } => Some(client_key.clone()),
278 _ => None,
279 }
280 }
281}
282
283#[cfg(test)]
284mod client_defaults_tests {
285 use super::*;
286
287 fn runtime() -> tokio::runtime::Runtime {
288 tokio::runtime::Builder::new_multi_thread()
289 .enable_all()
290 .build()
291 .expect("runtime")
292 }
293
294 /// The bug this guards: every binding builds ClientConfig as a struct
295 /// literal rather than through ClientConfig::new, so the default address
296 /// never reached them and an omitted list was rejected as invalid — which
297 /// is exactly what the SDK documentation told hosts to do.
298 #[test]
299 fn an_empty_address_list_falls_back_to_the_production_gateway() {
300 let rt = runtime();
301 let config = ClientConfig {
302 gateway_addresses: Vec::new(),
303 ..ClientConfig::new("pub_test")
304 };
305
306 let client = ProxyClient::new(config, rt.handle().clone())
307 .expect("an empty list must mean the production gateway, not an error");
308
309 assert_eq!(
310 client.inner.config.gateway_addresses,
311 DEFAULT_GATEWAY_ADDRESSES.iter().map(|a| (*a).to_owned()).collect::<Vec<_>>(),
312 );
313 }
314
315 #[test]
316 fn addresses_a_host_names_itself_are_left_alone() {
317 let rt = runtime();
318 let config = ClientConfig {
319 gateway_addresses: vec!["gw.example.test:4443".to_owned()],
320 ..ClientConfig::new("pub_test")
321 };
322
323 let client = ProxyClient::new(config, rt.handle().clone()).expect("valid config");
324
325 assert_eq!(
326 client.inner.config.gateway_addresses,
327 vec!["gw.example.test:4443".to_owned()],
328 );
329 }
330
331 /// Filling the default must not turn other invalid configs into valid ones.
332 #[test]
333 fn an_empty_publisher_id_is_still_rejected() {
334 let rt = runtime();
335 let config = ClientConfig {
336 gateway_addresses: Vec::new(),
337 ..ClientConfig::new("")
338 };
339
340 assert!(ProxyClient::new(config, rt.handle().clone()).is_err());
341 }
342}