1pub mod context;
2
3use context::CommonContext;
4use hightower_client::HightowerConnection;
5use tracing::{debug, error};
6
7pub async fn run(context: &CommonContext) -> Result<HightowerConnection, String> {
8 let gateway_url = context
10 .kv
11 .get_bytes(context::GATEWAY_URL_KEY)
12 .ok()
13 .flatten()
14 .and_then(|bytes| String::from_utf8(bytes).ok())
15 .unwrap_or_else(|| "http://127.0.0.1:8008".to_string());
16
17 let auth_token = context
19 .kv
20 .get_bytes(context::HT_AUTH_KEY)
21 .map_err(|e| format!("Failed to get auth token: {:?}", e))?
22 .ok_or_else(|| "Auth token not found in context".to_string())?;
23
24 let auth_token = String::from_utf8(auth_token)
25 .map_err(|e| format!("Invalid auth token encoding: {:?}", e))?;
26
27 debug!(gateway_url = %gateway_url, "Connecting to gateway");
28
29 let connection = HightowerConnection::connect(&gateway_url, &auth_token)
37 .await
38 .map_err(|e| {
39 error!(error = ?e, "Failed to connect to gateway");
40 format!("Failed to connect to gateway: {:?}", e)
41 })?;
42
43 debug!(
44 node_id = %connection.node_id(),
45 assigned_ip = %connection.assigned_ip(),
46 "Connected to gateway"
47 );
48
49 if let Err(e) = connection.ping_gateway().await {
51 error!(error = ?e, "Failed to ping gateway over WireGuard");
52 } else {
53 debug!("Successfully pinged gateway over WireGuard");
54 }
55
56 Ok(connection)
57}
58
59pub async fn deregister(connection: HightowerConnection) -> Result<(), String> {
60 connection
61 .disconnect()
62 .await
63 .map_err(|e| format!("Failed to disconnect: {:?}", e))
64}