-
Notifications
You must be signed in to change notification settings - Fork 57
Expand file tree
/
Copy pathworkspace.rs
More file actions
220 lines (197 loc) · 7.86 KB
/
Copy pathworkspace.rs
File metadata and controls
220 lines (197 loc) · 7.86 KB
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
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
//! Tracker workspace and URL discovery helpers.
use std::net::SocketAddr;
use std::path::{Path, PathBuf};
use std::sync::Arc;
use tempfile::TempDir;
use torrust_net_primitives::service_binding::ServiceBinding;
use torrust_tracker_lib::app;
use torrust_tracker_lib::bootstrap::jobs::manager::JobManager;
use torrust_tracker_lib::container::AppContainer;
use torrust_tracker_primitives::{ConfigurationInstanceId, ServiceRole};
use url::Url;
/// A temporary workspace for an integration test.
///
/// Creates an isolated directory with config file and storage directory.
/// The `{STORAGE_PATH}` placeholder in the config TOML is replaced with
/// the absolute path to the temp storage directory.
pub struct EphemeralTrackerWorkspace {
_temp_dir: TempDir,
config_path: PathBuf,
}
impl EphemeralTrackerWorkspace {
#[must_use]
pub fn new(config_toml: &str) -> Self {
let temp_dir = TempDir::new().expect("failed to create temp dir");
let storage_path = temp_dir.path().join("tracker-storage");
std::fs::create_dir_all(&storage_path).expect("failed to create storage dir");
let config_path = temp_dir.path().join("tracker-config.toml");
let resolved = config_toml.replace("{STORAGE_PATH}", &storage_path.to_string_lossy());
std::fs::write(&config_path, resolved).expect("failed to write config file");
Self {
_temp_dir: temp_dir,
config_path,
}
}
#[must_use]
pub fn config_path(&self) -> &Path {
&self.config_path
}
}
/// Starts the tracker application with the given workspace config.
///
/// Since the application reads its configuration from the
/// `TORRUST_TRACKER_CONFIG_TOML_PATH` environment variable,
/// tests in this binary must not run concurrently with other tests
/// that modify the same variable.
///
pub async fn start_tracker_with_config(workspace: &EphemeralTrackerWorkspace) -> (Arc<AppContainer>, JobManager) {
// SAFETY: This binary must be the only test executable setting
// `TORRUST_TRACKER_CONFIG_TOML_PATH`. Cargo may run different
// integration-test binaries in parallel, but each binary is a
// separate OS process with its own environment.
#[allow(unsafe_code)]
unsafe {
std::env::set_var(
"TORRUST_TRACKER_CONFIG_TOML_PATH",
workspace.config_path().to_str().expect("config path must be valid UTF-8"),
);
}
let (container, jobs) = app::run().await;
// Each service acknowledges registry insertion only after binding its
// final listener. Wait for the exact configuration identities, rather than
// a map-size threshold or a registration delay.
let expected_identities = expected_service_identities(&container);
let deadline = std::time::Instant::now() + std::time::Duration::from_secs(10);
loop {
let services = container.registar.services().await;
if expected_identities.iter().all(|identity| {
services
.iter()
.any(|service| service.metadata().configuration_instance_id() == *identity)
}) {
break;
}
assert!(
std::time::Instant::now() < deadline,
"timeout waiting for configured services to register in the registar"
);
tokio::time::sleep(std::time::Duration::from_millis(50)).await;
}
(container, jobs)
}
/// Returns the HTTP tracker URLs from the registar.
///
/// Uses the canonical HTTP tracker role, not a bind-IP convention. Wildcard
/// addresses are converted to `127.0.0.1` for client requests.
pub async fn http_tracker_urls(container: &AppContainer) -> Vec<Url> {
container
.registar
.services_matching(|metadata| metadata.service_role() == ServiceRole::HttpTracker)
.await
.iter()
.map(|service| loopback_url(service.service_binding().bind_address()))
.collect()
}
/// Returns the UDP tracker URLs from the registar.
///
/// Uses the canonical UDP tracker role, not a bind-IP convention. Wildcard
/// addresses are converted to `127.0.0.1` for client requests.
//
// Each integration-test binary compiles this module independently. Not all
// binaries call every function here, so the compiler emits dead_code warnings
// for the binaries that don't. The attribute suppresses those per-binary
// false positives without hiding genuine dead code in the workspace as a whole.
#[allow(dead_code)]
pub async fn udp_tracker_urls(container: &AppContainer) -> Vec<Url> {
container
.registar
.services_matching(|metadata| metadata.service_role() == ServiceRole::UdpTracker)
.await
.iter()
.map(|service| udp_loopback_url(service.service_binding().bind_address()))
.collect()
}
/// Returns the HTTP API URL from the registar.
///
/// Uses the canonical REST API role, not a bind-IP convention.
pub async fn http_api_url(container: &AppContainer) -> Option<Url> {
container
.registar
.services_matching(|metadata| metadata.service_role() == ServiceRole::RestApi)
.await
.first()
.map(|service| loopback_url(service.service_binding().bind_address()))
}
/// Returns the final binding for one exact canonical configuration identity.
///
/// This is side-effect free: registry visibility acknowledges that the service
/// has bound this listener.
#[allow(dead_code)]
pub async fn service_binding_for_identity(
container: &AppContainer,
configuration_instance_id: ConfigurationInstanceId,
) -> Option<ServiceBinding> {
container
.registar
.services_matching(|metadata| metadata.configuration_instance_id() == configuration_instance_id)
.await
.into_iter()
.next()
.map(|service| service.service_binding().clone())
}
fn expected_service_identities(container: &AppContainer) -> Vec<ConfigurationInstanceId> {
let mut identities: Vec<_> = container
.http_tracker_instance_containers
.iter()
.map(|(identity, _)| *identity)
.chain(
container
.udp_tracker_instance_containers
.iter()
.map(|(identity, _)| *identity),
)
.collect();
if container.http_api_config.is_some() {
identities.push(ConfigurationInstanceId::new(ServiceRole::RestApi, 0));
}
identities.push(ConfigurationInstanceId::new(ServiceRole::HealthCheckApi, 0));
identities
}
/// Convert a socket address to a connectable loopback URL.
///
/// Tracker services bind to `0.0.0.0` (all interfaces), but clients must
/// connect to a reachable address. This replaces wildcard IPv4 with the
/// loopback address `127.0.0.1`, preserving the OS-assigned port.
fn loopback_url(addr: SocketAddr) -> Url {
if addr.ip().is_unspecified() {
Url::parse(&format!("http://127.0.0.1:{port}", port = addr.port()))
} else {
Url::parse(&format!("http://{addr}")) // DevSkim: ignore DS137138
}
.expect("loopback URL should always be valid")
}
/// Convert a UDP socket address to a connectable loopback URL.
// Not called by every integration-test binary — see note on `udp_tracker_urls`.
#[allow(dead_code)]
fn udp_loopback_url(addr: SocketAddr) -> Url {
if addr.ip().is_unspecified() {
Url::parse(&format!("udp://127.0.0.1:{port}", port = addr.port()))
} else {
Url::parse(&format!("udp://{addr}"))
}
.expect("loopback URL should always be valid")
}
/// Extract the `SocketAddr` from a `udp://` URL.
//
// Uses the `Url` host/port accessors rather than slicing the URL string.
// Not called by every integration-test binary — see note on `udp_tracker_urls`.
#[allow(dead_code)]
pub fn udp_socket_addr(url: &Url) -> SocketAddr {
let host = url
.host_str()
.expect("UDP URL must have a host")
.parse()
.expect("UDP URL host must be a valid IP");
let port = url.port().expect("UDP URL must have a port");
SocketAddr::new(host, port)
}