ts_runtime/control_runner.rs
1use core::{
2 net::{Ipv4Addr, Ipv6Addr},
3 time::Duration,
4};
5use std::sync::Arc;
6
7use futures::StreamExt;
8use kameo::{
9 actor::{ActorRef, Spawn},
10 message::{Context, StreamMessage},
11 prelude::Message,
12};
13use tokio::sync::watch;
14use ts_control::{
15 AsyncControlClient, Endpoint, EndpointType, Error as ControlError, IdTokenError, LogoutError,
16 Node, SshPolicy, StateUpdate, TkaStatus,
17};
18use ts_magicsock::SelfEndpointType;
19
20use crate::{
21 derp_latency::{DerpLatencyMeasurement, DerpLatencyMeasurer},
22 direct::EndpointAdvertisement,
23};
24
25/// Actor responsible for maintaining the connection to control.
26///
27/// This actor is responsible for proxying the map response stream onto the message bus.
28pub struct ControlRunner {
29 client: AsyncControlClient,
30 params: Params,
31
32 self_node: watch::Sender<Option<Node>>,
33 /// Latest Tailscale SSH policy pushed by control, or `None` until control sends one. The SSH
34 /// server reads this to authorize incoming connections; absent policy means deny-all.
35 ssh_policy: watch::Sender<Option<SshPolicy>>,
36 /// Latest Tailnet Lock status pushed by control, or `None` until control sends one.
37 tka: watch::Sender<Option<TkaStatus>>,
38 /// The locally-synced Tailnet-Lock state (verified `Authority` + AUM store), or `None` until a
39 /// successful bootstrap+sync. Held here because `ControlRunner` owns the netmap stream that
40 /// triggers resync. Mutated only on the actor thread (the netmap handler spawns the sync RPC and
41 /// the result returns via the [`TkaSynced`] self-message).
42 tka_synced: Option<crate::tka_sync::SyncedTka>,
43 /// Published copy of the synced TKA [`Authority`](ts_tka::Authority) for the verify-and-log
44 /// consumer. `None` until the first successful sync. Observe-only: a reader uses it to *log*
45 /// whether a peer's node-key signature verifies, never to drop a peer (enforcement is a separate
46 /// gated decision).
47 tka_authority: watch::Sender<Option<Arc<ts_tka::Authority>>>,
48 /// In-flight guard: `true` while a sync RPC task is running, so a burst of netmap updates does
49 /// not spawn overlapping syncs (Go serializes sync under `b.mu`).
50 tka_syncing: bool,
51 /// Latest cert-domain list from control's netmap DNS config (Go `nm.DNS.CertDomains`), or empty
52 /// until control sends a DNS config carrying one. The facade reads this for `Device::cert_domains`.
53 cert_domains: watch::Sender<Vec<String>>,
54 /// Latest full DNS config from control's netmap (Go `netmap.NetworkMap.DNS`), or `None` until
55 /// control sends one. The facade reads this for `Device::dns_config` (the daemon's
56 /// `tnet dns status`). A superset of [`cert_domains`](Self::cert_domains), which is kept as its
57 /// own cell for the narrower TLS-cert use.
58 dns_config: watch::Sender<Option<ts_control::DnsConfig>>,
59}
60
61/// Control runner args.
62pub struct Params {
63 /// Control config.
64 pub(crate) config: ts_control::Config,
65
66 /// Auth key (if needed).
67 pub(crate) auth_key: Option<String>,
68
69 /// The [`crate::Env`] for this actor.
70 pub(crate) env: crate::Env,
71
72 /// Sender for the device connection-state cell. Created in [`Runtime::spawn`](crate::Runtime)
73 /// so it outlives the actor's `on_start` (which may publish [`DeviceState::Failed`] and then
74 /// return `Err`, before `Self` exists). The runtime keeps the matching `Receiver` for
75 /// [`watch_state`](crate::Runtime::watch_state) / [`wait_until_running`](crate::Runtime::wait_until_running).
76 pub(crate) state_tx: watch::Sender<crate::DeviceState>,
77}
78
79#[doc(hidden)]
80#[derive(Debug, thiserror::Error)]
81pub enum ControlRunnerError {
82 #[error(transparent)]
83 Control(#[from] ControlError),
84
85 #[error(transparent)]
86 Crate(#[from] crate::Error),
87}
88
89impl kameo::Actor for ControlRunner {
90 type Args = Params;
91 type Error = ControlRunnerError;
92
93 async fn on_start(params: Params, slf: ActorRef<Self>) -> Result<Self, Self::Error> {
94 loop {
95 match AsyncControlClient::check_auth(
96 ¶ms.config,
97 ¶ms.env.keys,
98 params.auth_key.as_deref(),
99 )
100 .await
101 {
102 Ok(()) => break,
103 Err(ControlError::MachineNotAuthorized(u)) => {
104 tracing::info!(auth_url = %u, "please authorize this machine or pass an auth key");
105 // Surface "interactive login required" so a watcher / `wait_until_running` can
106 // tell the user to authorize, instead of seeing an opaque timeout. Registration
107 // keeps retrying (transient), so this is not a terminal `Failed`.
108 params
109 .state_tx
110 .send_replace(crate::DeviceState::NeedsLogin(u.clone()));
111 tokio::time::sleep(Duration::from_secs(5)).await;
112 }
113 Err(e) => {
114 // A hard registration failure (bad/expired/unknown auth key, etc.). Log the
115 // specific reason control gave AND publish it as a typed `Failed` state so
116 // `Device::wait_until_running` returns the actionable reason (tsr-kqj) instead
117 // of the opaque `Internal(Actor)` the caller would otherwise see once the
118 // stopped actor is next asked. Publishing before `return Err` is why the state
119 // sender lives on `Runtime`, not on `Self` (which never gets constructed here).
120 let reason = crate::RegistrationError::from(&e);
121 tracing::error!(error = %e, "registration failed; control runner stopping");
122 params
123 .state_tx
124 .send_replace(crate::DeviceState::Failed(reason));
125 return Err(e.into());
126 }
127 }
128 }
129 // check_auth succeeded, but the node is not "up" until the netmap stream is actually
130 // attached below. Publish `Running` only AFTER `attach_stream` so `wait_until_running` never
131 // resolves `Ok` for a device whose stream connect failed (which would leave a stopped actor
132 // behind). If the connect/subscribe steps fail, publish a transient `Failed` first so the
133 // waiter sees an actionable reason instead of the opaque post-mortem `Internal(Actor)`.
134 let bring_up = async {
135 let (client, stream) = AsyncControlClient::connect(
136 ¶ms.config,
137 ¶ms.env.keys,
138 params.auth_key.as_deref(),
139 )
140 .await?;
141
142 DerpLatencyMeasurer::spawn_link(&slf, params.env.clone()).await;
143
144 params.env.subscribe::<DerpLatencyMeasurement>(&slf).await?;
145 params.env.subscribe::<EndpointAdvertisement>(&slf).await?;
146 slf.attach_stream(stream.boxed(), (), ());
147 Ok::<_, ControlRunnerError>(client)
148 };
149
150 let client = match bring_up.await {
151 Ok(client) => client,
152 Err(e) => {
153 tracing::error!(error = %e, "bringing up the control session failed");
154 // The control session never came up; surface it as a transient registration
155 // failure (a retry / fresh `Device::new` may succeed) rather than leaving the state
156 // stuck at `Connecting`.
157 params.state_tx.send_replace(crate::DeviceState::Failed(
158 crate::RegistrationError::NetworkUnreachable,
159 ));
160 return Err(e);
161 }
162 };
163
164 // The netmap stream is attached: the node is up. The stream `Next` handler keeps this
165 // current (and flips to `Expired` if the self-node's key lapses).
166 params.state_tx.send_replace(crate::DeviceState::Running);
167
168 Ok(Self {
169 client,
170 params,
171 self_node: Default::default(),
172 ssh_policy: Default::default(),
173 tka: Default::default(),
174 tka_synced: None,
175 tka_authority: Default::default(),
176 tka_syncing: false,
177 cert_domains: Default::default(),
178 dns_config: Default::default(),
179 })
180 }
181}
182
183impl ControlRunner {
184 /// Decide whether the latest netmap's Tailnet-Lock status warrants a (re)sync and, if so, spawn
185 /// the bootstrap+sync RPC off the actor thread (so the netmap stream never blocks on a control
186 /// round-trip). The result returns via the [`TkaSynced`] self-message.
187 ///
188 /// Triggers when control reports TKA enabled (`is_enabled`) AND we are not already syncing AND
189 /// either we hold no `Authority` yet (→ bootstrap) or control's head differs from ours (→ catch
190 /// up). When TKA is disabled, clears any synced state (the lock was turned off). Mirrors Go's
191 /// `tkaSyncIfNeeded`: a no-op when our head already matches.
192 fn maybe_sync_tka(&mut self, tka: &TkaStatus, self_ref: ActorRef<Self>) {
193 if !tka.is_enabled() {
194 // Lock disabled (or never enabled): drop any synced state and stop publishing an
195 // Authority. Never an error; peers are unaffected.
196 if self.tka_synced.is_some() {
197 self.tka_synced = None;
198 self.tka_authority.send_replace(None);
199 }
200 return;
201 }
202 if self.tka_syncing {
203 return; // a sync is already in flight; the next netmap will re-trigger if still stale
204 }
205 // Up-to-date check: if we already have an Authority whose head matches control's, nothing to
206 // do. A malformed control head is treated as "different" (we'll attempt a sync, which
207 // fail-closes harmlessly).
208 if let Some(synced) = &self.tka_synced
209 && let Some(control_head) = ts_tka::AumHash::from_base32(&tka.head)
210 && synced.authority.head_matches(&control_head)
211 {
212 return;
213 }
214
215 // Spawn the sync. Move the current synced state out (the driver takes it by value and returns
216 // the advanced state); `tka_synced` stays `None` until the result lands, guarded by
217 // `tka_syncing` so we don't spawn a second concurrent sync.
218 self.tka_syncing = true;
219 let current = self.tka_synced.take();
220 let config = self.params.config.clone();
221 let keys = self.params.env.keys.clone();
222 tokio::spawn(async move {
223 let result = crate::tka_sync::sync_tka(&config, &keys, current).await;
224 // Hand the outcome back to the actor thread to apply (mutating actor state off-thread is
225 // not allowed). A send failure just means the actor is gone — nothing to do.
226 if let Err(e) = self_ref.tell(TkaSynced { result }).await {
227 tracing::debug!(error = ?e, "TKA sync result not delivered (actor gone)");
228 }
229 });
230 }
231
232 /// Apply the outcome of a spawned [`maybe_sync_tka`] task on the actor thread: store the advanced
233 /// state + publish the `Authority` (or, on inert/failed sync, leave peers unaffected). Always
234 /// clears the in-flight guard.
235 fn apply_tka_synced(
236 &mut self,
237 result: Result<Option<crate::tka_sync::SyncedTka>, crate::tka_sync::TkaSyncDriverError>,
238 ) {
239 self.tka_syncing = false;
240 match result {
241 Ok(Some(synced)) => {
242 tracing::info!(
243 head = %synced.authority.head().to_base32(),
244 "TKA sync succeeded; publishing verified Authority (observe-only)"
245 );
246 self.tka_authority
247 .send_replace(Some(synced.authority.clone()));
248 self.tka_synced = Some(synced);
249 }
250 Ok(None) => {
251 // Control has no lock for us (no genesis / disabled): stay inert. Not an error.
252 tracing::debug!("TKA sync: control reported no lock for this node (inert)");
253 }
254 Err(e) => {
255 // Transport or verify failure: log and stay inert. NEVER errors the netmap or drops a
256 // peer. The next netmap update re-triggers a sync attempt.
257 tracing::warn!(error = %e, "TKA sync failed; staying inert (no peer impact)");
258 }
259 }
260 }
261
262 fn with_self_node<F, R>(&self, f: F) -> impl Future<Output = Option<R>> + use<F, R>
263 where
264 F: FnOnce(&Node) -> R,
265 {
266 let mut sub = self.self_node.subscribe();
267 let mut shutdown = self.params.env.shutdown.clone();
268
269 async move {
270 tokio::select! {
271 _ = shutdown.wait_for(|x| *x) => {
272 None
273 },
274 node = sub.wait_for(Option::is_some) => {
275 Some(f(node.ok()?.as_ref()?))
276 },
277 }
278 }
279 }
280}
281
282// The `#[kameo::messages]` macro generates message structs whose fields mirror the method params;
283// those generated fields carry no doc and can't take attributes, so wrap in a module where
284// missing-docs is allowed (same pattern as PeerTracker's `msg_impl`). The generated message structs
285// are re-exported so callers keep referencing them at `control_runner::<Name>`.
286pub use msg_impl::*;
287
288#[allow(missing_docs)]
289mod msg_impl {
290 use kameo::{message::Context, reply::DelegatedReply};
291
292 use super::*;
293
294 #[kameo::messages]
295 impl ControlRunner {
296 /// Fetch the IPv4 address for this tailscale device.
297 #[message(ctx)]
298 pub fn ipv4(
299 &self,
300 ctx: &mut Context<Self, DelegatedReply<Option<Ipv4Addr>>>,
301 ) -> DelegatedReply<Option<Ipv4Addr>> {
302 let (deleg, replier) = ctx.reply_sender();
303
304 if let Some(replier) = replier {
305 let fut = self.with_self_node(|node| node.tailnet_address.ipv4.addr());
306
307 tokio::spawn(async move {
308 let ip = fut.await;
309 replier.send(ip);
310 });
311 }
312
313 deleg
314 }
315
316 /// Fetch the IPv6 address for this tailscale device.
317 #[message(ctx)]
318 pub fn ipv6(
319 &self,
320 ctx: &mut Context<Self, DelegatedReply<Option<Ipv6Addr>>>,
321 ) -> DelegatedReply<Option<Ipv6Addr>> {
322 let (deleg, replier) = ctx.reply_sender();
323
324 if let Some(replier) = replier {
325 let fut = self.with_self_node(|node| node.tailnet_address.ipv6.addr());
326
327 tokio::spawn(async move {
328 let ip = fut.await;
329 replier.send(ip);
330 });
331 }
332
333 deleg
334 }
335
336 /// Fetch the self node for this tailscale device.
337 #[message(ctx)]
338 pub fn self_node(
339 &self,
340 ctx: &mut Context<Self, DelegatedReply<Option<Node>>>,
341 ) -> DelegatedReply<Option<Node>> {
342 let (deleg, replier) = ctx.reply_sender();
343
344 if let Some(replier) = replier {
345 let node = self.with_self_node(|node| node.clone());
346
347 tokio::spawn(async move {
348 let node = node.await;
349 replier.send(node)
350 });
351 }
352
353 deleg
354 }
355
356 /// Fetch the current Tailscale SSH policy, if control has pushed one.
357 ///
358 /// Returns `None` when control has not sent an SSH policy (the SSH server treats this as
359 /// deny-all — fail-closed). Unlike `self_node` this does not block waiting
360 /// for a value: an absent policy is a legitimate, immediate answer.
361 #[message]
362 pub fn current_ssh_policy(&self) -> Option<SshPolicy> {
363 self.ssh_policy.borrow().clone()
364 }
365
366 /// Fetch the current Tailnet Lock status, if control has pushed one.
367 ///
368 /// Returns `None` when control has sent no `TKAInfo` (tailnet lock not in use / no change seen).
369 #[message]
370 pub fn current_tka_status(&self) -> Option<TkaStatus> {
371 self.tka.borrow().clone()
372 }
373
374 /// The cert-eligible DNS names from control's netmap DNS config (Go `nm.DNS.CertDomains`).
375 ///
376 /// Returns an empty `Vec` when control has sent no DNS config, or one carrying no cert
377 /// domains (an empty list is a legitimate, immediate answer — like `current_ssh_policy`, this
378 /// does not block waiting for a value).
379 #[message]
380 pub fn cert_domains(&self) -> Vec<String> {
381 self.cert_domains.borrow().clone()
382 }
383
384 /// The full DNS config from control's netmap (Go `netmap.NetworkMap.DNS`), or `None` when
385 /// control has sent no DNS config yet. An immediate answer (does not block); the facade
386 /// surfaces this for `Device::dns_config` (the daemon's `tnet dns status`).
387 #[message]
388 pub fn dns_config(&self) -> Option<ts_control::DnsConfig> {
389 self.dns_config.borrow().clone()
390 }
391
392 /// Request an OIDC ID token from control scoped to `audience` (workload-identity federation).
393 ///
394 /// Opens a fresh Noise channel and POSTs `/machine/id-token`; returns the signed JWT or an
395 /// [`IdTokenError`]. Runs on a spawned task (delegated reply) so the actor mailbox isn't blocked
396 /// for the round-trip.
397 #[message(ctx)]
398 pub fn fetch_id_token(
399 &self,
400 ctx: &mut Context<Self, DelegatedReply<Result<String, IdTokenError>>>,
401 audience: String,
402 ) -> DelegatedReply<Result<String, IdTokenError>> {
403 let (deleg, replier) = ctx.reply_sender();
404
405 if let Some(replier) = replier {
406 let config = self.params.config.clone();
407 let keys = self.params.env.keys.clone();
408 tokio::spawn(async move {
409 let result = ts_control::fetch_id_token(&config, &keys, &audience).await;
410 replier.send(result);
411 });
412 }
413
414 deleg
415 }
416
417 /// Log this node out of the tailnet: deregister it by expiring its current node key.
418 ///
419 /// Mirrors [`fetch_id_token`](Self::fetch_id_token): clones the control config + node keys
420 /// into a spawned task (delegated reply, so the round-trip doesn't block the mailbox) and
421 /// re-POSTs `/machine/register` with a past expiry over a fresh Noise channel. This is a
422 /// control-plane state change only — it does NOT stop this actor or tear down the datapath
423 /// (the caller follows up with the normal runtime shutdown), and it does not touch the
424 /// on-disk node key, so re-registering with the same key is the re-login path.
425 #[message(ctx)]
426 pub fn logout(
427 &self,
428 ctx: &mut Context<Self, DelegatedReply<Result<(), LogoutError>>>,
429 ) -> DelegatedReply<Result<(), LogoutError>> {
430 let (deleg, replier) = ctx.reply_sender();
431
432 if let Some(replier) = replier {
433 let config = self.params.config.clone();
434 let keys = self.params.env.keys.clone();
435 tokio::spawn(async move {
436 let result = ts_control::logout(&config, &keys).await;
437 replier.send(result);
438 });
439 }
440
441 deleg
442 }
443 }
444
445 // The `acme`-gated cert-issuance message lives in its own `#[kameo::messages]` impl block so the
446 // proc-macro never sees it in a non-`acme` build (a `#[cfg]` *inside* a single messages-impl
447 // block is not honored by the macro's generated dispatch — it would emit a `GetCertificate`
448 // handler calling a `get_certificate` method that the same `#[cfg]` strips). A separate gated
449 // block keeps the default build clean.
450 #[cfg(feature = "acme")]
451 #[kameo::messages]
452 impl ControlRunner {
453 /// Issue a real Let's Encrypt certificate for this node's MagicDNS `name` via the
454 /// client-side ACME DNS-01 engine (`acme` feature).
455 ///
456 /// Mirrors [`fetch_id_token`](Self::fetch_id_token): clones the control config + node keys
457 /// into a spawned task (delegated reply, so the round-trip doesn't block the mailbox), loads
458 /// or generates the ACME account key, and runs issuance against Let's Encrypt production,
459 /// publishing the DNS-01 challenge TXT through the node's `POST /machine/set-dns` RPC.
460 ///
461 /// The account key is loaded from [`ts_keys::NodeState::acme_account_key`] (PKCS#8 DER) when
462 /// present, so the same ACME account persists across renewals; otherwise an ephemeral key is
463 /// generated for this call only (a fresh ACME account each issuance — acceptable for v1; LE
464 /// allows it). Persisting a generated key back into the key file is the embedder's job (no
465 /// write-back path here). SaaS-only: against a self-hosted control plane the set-dns
466 /// publish 501s.
467 #[message(ctx)]
468 pub fn get_certificate(
469 &self,
470 ctx: &mut Context<
471 Self,
472 DelegatedReply<Result<ts_control::tls::CertifiedKey, ts_control::CertError>>,
473 >,
474 name: String,
475 ) -> DelegatedReply<Result<ts_control::tls::CertifiedKey, ts_control::CertError>> {
476 let (deleg, replier) = ctx.reply_sender();
477
478 if let Some(replier) = replier {
479 let config = self.params.config.clone();
480 let keys = self.params.env.keys.clone();
481 tokio::spawn(async move {
482 let result = issue_certificate(&config, &keys, &name).await;
483 replier.send(result);
484 });
485 }
486
487 deleg
488 }
489 }
490}
491
492/// Load or generate the ACME account key, then issue a cert for `name` via set-dns DNS-01.
493///
494/// Reuses the persisted [`ts_keys::NodeState::acme_account_key`] (PKCS#8 DER) when present so the
495/// same Let's Encrypt account survives renewals; otherwise generates an ephemeral per-call key
496/// (logged at debug — a new ACME account each issuance, with no write-back). Always targets Let's
497/// Encrypt production ([`ts_control::acme::LETS_ENCRYPT_PRODUCTION_DIRECTORY`]).
498#[cfg(feature = "acme")]
499async fn issue_certificate(
500 config: &ts_control::Config,
501 keys: &ts_keys::NodeState,
502 name: &str,
503) -> Result<ts_control::tls::CertifiedKey, ts_control::CertError> {
504 let account_key = match keys.acme_account_key.as_deref() {
505 Some(der) => ts_control::acme::AcmeAccountKey::from_pkcs8(der)?,
506 None => {
507 tracing::debug!(
508 "no persisted ACME account key in key state; generating an ephemeral per-call key \
509 (a new ACME account this issuance — not persisted back)"
510 );
511 ts_control::acme::AcmeAccountKey::generate()?.0
512 }
513 };
514 let directory = ts_control::acme::LETS_ENCRYPT_PRODUCTION_DIRECTORY
515 .parse()
516 .map_err(|e| {
517 ts_control::CertError::Acme(format!("parsing Let's Encrypt directory URL: {e}"))
518 })?;
519 ts_control::issue_certificate_via_setdns(config, keys, name, &account_key, &directory).await
520}
521
522impl Message<StreamMessage<Arc<StateUpdate>, (), ()>> for ControlRunner {
523 type Reply = ();
524
525 async fn handle(
526 &mut self,
527 msg: StreamMessage<Arc<StateUpdate>, (), ()>,
528 ctx: &mut Context<Self, Self::Reply>,
529 ) {
530 match msg {
531 StreamMessage::Started(_) => {
532 tracing::trace!("started listening to state updates");
533 }
534
535 StreamMessage::Next(msg) => {
536 if let Some(node) = msg.node.as_ref() {
537 // Reflect node-key expiry into the device state: control delivering a self-node
538 // whose key is in the past means the node must re-authenticate. Otherwise the
539 // arrival of a fresh self-node confirms we are Running (recovers the state if a
540 // prior update had flipped it to Expired).
541 let now_unix = std::time::SystemTime::now()
542 .duration_since(std::time::UNIX_EPOCH)
543 .map(|d| d.as_secs() as i64)
544 .unwrap_or(0);
545 let next = if node.key_expired_at_unix(now_unix) {
546 crate::DeviceState::Expired
547 } else {
548 crate::DeviceState::Running
549 };
550 // `send_if_modified` avoids waking watchers when the state is unchanged (a fresh
551 // self-node arrives on every netmap update).
552 self.params.state_tx.send_if_modified(|s| {
553 if *s != next {
554 *s = next.clone();
555 true
556 } else {
557 false
558 }
559 });
560
561 self.self_node.send_replace(Some(node.clone()));
562 }
563
564 if let Some(policy) = msg.ssh_policy.as_ref() {
565 self.ssh_policy.send_replace(Some(policy.clone()));
566 }
567
568 if let Some(tka) = msg.tka.as_ref() {
569 self.tka.send_replace(Some(tka.clone()));
570 self.maybe_sync_tka(tka, ctx.actor_ref().clone());
571 }
572
573 // Track the cert-domain list from the netmap DNS config (Go `nm.DNS.CertDomains`).
574 // An update with no DNS config, or one carrying no cert domains, means "none" — Go
575 // reads an empty slice off an absent config too, so mirror that as an empty `Vec`.
576 let cert_domains = msg
577 .dns_config
578 .as_ref()
579 .map(|d| d.cert_domains.clone())
580 .unwrap_or_default();
581 self.cert_domains.send_replace(cert_domains);
582
583 // Track the full DNS config for `Device::dns_config` (the daemon's `tnet dns status`).
584 // `None` when control sent no DNS config on this update — distinct from a present but
585 // empty config (Go `netmap.NetworkMap.DNS`).
586 self.dns_config.send_replace(msg.dns_config.clone());
587
588 if let Err(e) = self.params.env.publish(msg).await {
589 tracing::error!(error = %e, "publishing netmap update");
590 }
591 }
592
593 StreamMessage::Finished(_) => {
594 tracing::error!("state update stream terminated")
595 }
596 }
597 }
598}
599
600/// The outcome of a spawned TKA bootstrap+sync task, delivered back to the actor thread so the
601/// result can be applied to actor state (which a spawned task cannot touch directly). Sent by
602/// [`ControlRunner::maybe_sync_tka`]; handled by applying via
603/// [`ControlRunner::apply_tka_synced`](ControlRunner).
604#[doc(hidden)]
605pub struct TkaSynced {
606 pub(crate) result:
607 Result<Option<crate::tka_sync::SyncedTka>, crate::tka_sync::TkaSyncDriverError>,
608}
609
610impl Message<TkaSynced> for ControlRunner {
611 type Reply = ();
612
613 async fn handle(&mut self, msg: TkaSynced, _ctx: &mut Context<Self, Self::Reply>) {
614 self.apply_tka_synced(msg.result);
615 }
616}
617
618impl Message<DerpLatencyMeasurement> for ControlRunner {
619 type Reply = ();
620
621 async fn handle(&mut self, msg: DerpLatencyMeasurement, _ctx: &mut Context<Self, Self::Reply>) {
622 let measurements = msg.measurement.as_ref().clone();
623
624 let Some(result) = measurements.first() else {
625 tracing::debug!("derp latency measurements empty");
626 return;
627 };
628
629 let iter = measurements.iter().map(|result| {
630 (
631 result.latency_map_key.as_str(),
632 result.latency.as_secs_f64(),
633 )
634 });
635
636 tracing::debug!(selected_region_id = ?result.id, "updating home region");
637
638 self.client.set_home_region(result.id, iter).await;
639 }
640}
641
642impl Message<EndpointAdvertisement> for ControlRunner {
643 type Reply = ();
644
645 async fn handle(&mut self, msg: EndpointAdvertisement, _ctx: &mut Context<Self, Self::Reply>) {
646 let endpoints: Vec<Endpoint> = msg
647 .endpoints
648 .iter()
649 .map(|ep| Endpoint {
650 endpoint: ep.addr,
651 ty: match ep.ty {
652 SelfEndpointType::Local => EndpointType::Local,
653 SelfEndpointType::Stun => EndpointType::Stun,
654 SelfEndpointType::Stun4LocalPort => EndpointType::Stun4LocalPort,
655 },
656 })
657 .collect();
658
659 tracing::debug!(
660 n_endpoints = endpoints.len(),
661 "advertising endpoints to control"
662 );
663
664 self.client.set_endpoints(endpoints).await;
665 }
666}