hatchery_node/
uplink_calls.rs1use crate::restream_session::{NodeSession, NodeUplink, UpstreamKeys};
14use hatchery_core::ChannelKind;
15use hatchery_enroll::NodeIdentity;
16use serde_json::Value;
17use std::net::SocketAddr;
18use std::sync::Arc;
19use std::time::{Duration, Instant};
20use tokio::sync::Mutex;
21
22pub const NODE_CALL_CHANNEL: u32 = 2;
24const HANDSHAKE: Duration = Duration::from_secs(8);
25const CALL_TIMEOUT: Duration = Duration::from_secs(15);
26const OPEN_BACKOFF: Duration = Duration::from_secs(60);
28
29#[derive(Default)]
30struct Link {
31 uplink: Option<Arc<NodeUplink>>,
32 session: Option<NodeSession>,
33 open_not_before: Option<Instant>,
35}
36
37#[derive(Clone)]
39pub struct NodeCalls {
40 link: Arc<Mutex<Link>>,
41 node_id: String,
42 keys: Option<UpstreamKeys>,
43 legacy: Option<(SocketAddr, Arc<NodeIdentity>)>,
44 config_http: Option<(SocketAddr, Arc<NodeIdentity>)>,
47}
48
49#[derive(Debug)]
50pub enum CallError {
51 Refused,
52 Unavailable(String),
53}
54
55impl NodeCalls {
56 pub fn new(
57 node_id: String,
58 keys: Option<UpstreamKeys>,
59 legacy: Option<(SocketAddr, Arc<NodeIdentity>)>,
60 config_http: Option<(SocketAddr, Arc<NodeIdentity>)>,
61 ) -> Self {
62 Self { link: Arc::default(), node_id, keys, legacy, config_http }
63 }
64
65 pub async fn set_uplink(&self, uplink: Option<Arc<NodeUplink>>) {
67 let connected = uplink.is_some();
68 let mut l = self.link.lock().await;
69 l.uplink = uplink;
70 l.session = None;
71 l.open_not_before = None;
73 drop(l);
74 if connected {
75 self.refresh_product_url().await;
76 } else {
77 crate::m4a_accounts::set_c2_product_url(None);
78 }
79 }
80
81 pub async fn refresh_product_url(&self) {
83 let Some((c2, identity)) = self.config_http.clone().or_else(|| self.legacy.clone()) else {
84 return;
85 };
86 match crate::enroll_client::node_call(
87 c2,
88 &identity,
89 &self.node_id,
90 hatchery_enroll::call::NODE_CONFIG_OP,
91 &serde_json::json!({}),
92 )
93 .await
94 {
95 Ok(v) => {
96 let url = v
97 .get("m4a_product_url")
98 .and_then(|u| u.as_str())
99 .filter(|u| !u.is_empty())
100 .map(str::to_owned);
101 crate::m4a_accounts::set_c2_product_url(url.clone());
102 match url {
103 Some(u) => tracing::info!(product = %u, "m4a product url from C2"),
104 None => tracing::info!("m4a product url from C2 is empty; accounts stay local"),
105 }
106 }
107 Err(e) => tracing::warn!(error = ?e, "m4a product url from C2 failed"),
108 }
109 }
110
111 pub async fn call(&self, op: &str, payload: &Value) -> Result<Value, CallError> {
112 if let Some(keys) = self.keys {
113 let mut l = self.link.lock().await;
114 if let Some(uplink) = l.uplink.clone() {
115 if l.session.is_none() {
116 let gated = l.open_not_before.is_some_and(|t| Instant::now() < t);
117 if gated {
118 } else {
120 match uplink.open(&self.node_id, NODE_CALL_CHANNEL, ChannelKind::M4a, keys, HANDSHAKE).await {
121 Ok(s) => {
122 tracing::info!("node calls over the uplink: channel open");
123 l.session = Some(s);
124 l.open_not_before = None;
125 }
126 Err(e) => {
127 tracing::warn!(error = %e, "node-call channel open failed; backing off {}s", OPEN_BACKOFF.as_secs());
128 l.open_not_before = Some(Instant::now() + OPEN_BACKOFF);
129 }
130 }
131 }
132 }
133 if let Some(session) = l.session.as_mut() {
134 return match session.call(op, payload, CALL_TIMEOUT).await {
135 Ok(v) => Ok(v),
136 Err(e) if e.starts_with("403") => Err(CallError::Refused),
137 Err(e) if e.chars().take(3).all(|c| c.is_ascii_digit()) && e.contains(':') => {
138 Err(CallError::Unavailable(e))
140 }
141 Err(e) => {
142 l.session = None;
145 l.open_not_before = Some(Instant::now() + OPEN_BACKOFF);
146 Err(CallError::Unavailable(e))
147 }
148 };
149 }
150 }
151 }
152 match &self.legacy {
153 Some((c2, identity)) => match crate::enroll_client::node_call(*c2, identity, &self.node_id, op, payload).await {
154 Ok(v) => Ok(v),
155 Err(crate::enroll_client::EnrollClientError::Refused) => Err(CallError::Refused),
156 Err(e) => Err(CallError::Unavailable(format!("{e:?}"))),
157 },
158 None => Err(CallError::Unavailable("no uplink".into())),
159 }
160 }
161}