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
//! DNS IO specific code and implementations
// IO task which holds the state of the DNS pool and performs DNS resolve actions
pub mod resolver;
// IO task which performs NTP requests to a DNS-resolved address
pub mod ntp_source;
use std::collections::HashMap;
use std::net::SocketAddr;
use tokio::sync::mpsc;
use tokio_util::task::TaskTracker;
use tracing::{debug, error, info, warn};
use super::{ControlRequest, Source, SourceState};
use crate::daemon::{io::in_use_ip_addrs::InUseIpAddrs, message::Dns as DnsMessage};
use ntp_source::NtpSource;
use resolver::{Message as ResolverMessage, Resolver};
/// Struct that lives in [`SourceIO`](super::SourceIO)
/// to act as the interface to a DNS pool
#[derive(Debug)]
pub struct Pool {
domain: String,
/// Live NTP source tasks for this pool, keyed by socket address
ntp_sources: HashMap<SocketAddr, Source<NtpSource>>,
/// The resolver task for this pool
resolver: Source<Resolver>,
/// Sender half of the resolver message channel — cloned into each `NtpSource`
resolver_message_tx: mpsc::Sender<ResolverMessage>,
}
impl Pool {
/// Constructs a new `Pool` with all internal channels and a ready-to-spawn Resolver.
///
/// `max_sources` is the maximum number of healthy NTP tasks the pool's
/// resolver maintains.
pub fn construct(
pool_domain: String,
daemon_tx: mpsc::Sender<DnsMessage>,
in_use_ip_addrs: InUseIpAddrs,
max_sources: usize,
) -> Self {
// Channel for NTP sources to communicate with the Resolver
let (resolver_message_tx, ntp_receiver) = mpsc::channel::<ResolverMessage>(16);
// Control channel for the Resolver
let (ctrl_sender, ctrl_receiver) = mpsc::channel::<ControlRequest>(1);
let resolver = Resolver::construct(
pool_domain.clone(),
daemon_tx,
ctrl_receiver,
ntp_receiver,
in_use_ip_addrs,
max_sources,
);
Self {
domain: pool_domain,
ntp_sources: HashMap::new(),
resolver: Source {
state: SourceState::Initialized(resolver),
ctrl_sender,
},
resolver_message_tx,
}
}
/// Returns a clone of the resolver message sender for use by NTP sources.
pub fn resolver_message_sender(&self) -> mpsc::Sender<ResolverMessage> {
self.resolver_message_tx.clone()
}
/// Test-only snapshot of the IP addresses tracked by this pool's resolver.
///
/// # Panics
/// Panics if the resolver has already been spawned (its state is no longer
/// `Initialized`), which never happens for a freshly constructed pool.
#[cfg(test)]
pub(crate) fn resolver_in_use_ip_addrs_snapshot(&self) -> Vec<std::net::IpAddr> {
match &self.resolver.state {
SourceState::Initialized(resolver) => resolver.in_use_ip_addrs_snapshot(),
SourceState::Running => panic!("resolver already spawned"),
}
}
/// Inserts a running NTP source into the pool.
///
/// # Panics
/// Panics if the address is already in the pool
pub(super) fn add_source(&mut self, addr: SocketAddr, source: Source<NtpSource>) {
let inserted = self.ntp_sources.insert(addr, source);
if inserted.is_some() {
error!(pool_domain = self.domain, %addr, "Attempted to add duplicate addr to pool");
panic!("Attempted to add an already-existing pool source");
}
}
/// Removes an NTP source from the pool, returning it.
///
/// # Panics
/// Panics if the address is not in the pool
pub(super) fn remove_source(&mut self, addr: &SocketAddr) -> Source<NtpSource> {
let removed = self.ntp_sources.remove(addr);
if let Some(removed) = removed {
removed
} else {
error!(pool_domain = self.domain, %addr, "Attempted to remove non-existent addr from pool");
panic!("Attempted to remove a pool source that does not exist");
}
}
/// Spawns the Resolver task on the given tracker.
///
/// # Panics
/// Panics if the NTP source `HashMap` is not empty (invariant: no sources exist before
/// the Resolver has started), or if the Resolver has already been spawned.
#[tracing::instrument(level = "info", skip_all, fields(pool = %self.domain))]
pub fn spawn_resolver(&mut self, tracker: &TaskTracker) {
assert!(
self.ntp_sources.is_empty(),
"NTP source HashMap must be empty when spawning the Resolver"
);
debug!("Attempting to spawn Resolver.");
if let SourceState::Initialized(mut resolver) = self.resolver.state.transition_to_running()
{
tracker.spawn(async move { resolver.run().await });
info!("Successfully spawned Resolver.");
} else {
warn!("Attempted to spawn Resolver when it is already running.");
}
}
/// Returns the number of NTP sources in this pool.
pub fn ntp_source_count(&self) -> usize {
self.ntp_sources.len()
}
/// Gracefully shuts down the pool: NTP sources first, then the Resolver.
///
/// NTP sources are shut down before the Resolver to ensure they stop sending
/// messages on `resolver_tx` before the Resolver exits and drops its receiver.
pub async fn shutdown(&mut self) {
// Shutdown all NTP sources first
// take to iterate while draining hashmap
let ntp_sources = std::mem::take(&mut self.ntp_sources);
for (address, source) in ntp_sources {
#[expect(
clippy::missing_panics_doc,
reason = "NTP task can only be shutdown from here. No race possible"
)]
source
.ctrl_sender
.send(ControlRequest::Shutdown)
.await
.unwrap();
debug!(%address, pool = %self.domain, "Sent shutdown to DNS pool NTP source");
}
// Shutdown the Resolver
#[expect(
clippy::missing_panics_doc,
reason = "resolver lives for entire app lifetime"
)]
self.resolver
.ctrl_sender
.send(ControlRequest::Shutdown)
.await
.unwrap();
}
}