rust-mc-status 3.0.0

High-performance asynchronous Rust library for querying Minecraft server status (Java & Bedrock)
Documentation
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
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
#![cfg_attr(docsrs, feature(doc_cfg))]
pub mod builder;
pub mod facade;

pub use builder::{JavaPingBuilder, BedrockPingBuilder, ServerPingBuilder};
pub use facade::{ping_java, ping_bedrock};

use std::time::Duration;

use crate::core::{dns::DnsResolver, cache::{ResponseCache, DEFAULT_RESPONSE_CACHE_SIZE}, address};
use crate::error::McError;
use crate::models::*;
use crate::protocol::{
    bedrock::BedrockProtocol,
    java_modern::JavaModernProtocol,
    PingProtocol, ResolvedTarget,
};
use crate::proxy::ProxyConfig;
use crate::status::{BedrockServerStatus, JavaServerStatus};

const DEFAULT_TIMEOUT:        Duration = Duration::from_secs(10);
const DEFAULT_MAX_PARALLEL:   usize    = 10;
const JAVA_DEFAULT_PORT:      u16      = 25565;
const BEDROCK_DEFAULT_PORT:   u16      = 19132;

// ─── McClient ─────────────────────────────────────────────────────────────────

/// Async client for pinging Minecraft Java and Bedrock servers.
///
/// Constructed via [`McClient::builder()`] — there is no `new()`.
/// Cheaply `Clone`-able — all clones share the same DNS/SRV and response caches.
///
/// # Example
///
/// ```rust,no_run
/// use rust_mc_status::McClient;
/// use std::time::Duration;
///
/// # #[tokio::main] async fn main() -> Result<(), rust_mc_status::McError> {
/// let client = McClient::builder()
///     .timeout(Duration::from_secs(5))
///     .max_parallel(20)
///     .response_cache(Duration::from_secs(30), 256)
///     .build();
///
/// let status = client.java("mc.hypixel.net").await?;
/// # Ok(()) }
/// ```
#[derive(Clone)]
pub struct McClient {
    pub(crate) timeout:        Duration,
    pub(crate) max_parallel:   usize,
    pub(crate) dns:            DnsResolver,
    pub(crate) response_cache: ResponseCache,
    #[cfg(feature = "proxy")]
    pub(crate) proxy:          Option<ProxyConfig>,
}

impl McClient {
    /// Return a [`McClientBuilder`] — the only way to construct a [`McClient`].
    pub fn builder() -> McClientBuilder { McClientBuilder::new() }

    // ─── Accessors ────────────────────────────────────────────────────────────

    /// Returns the configured request timeout.
    pub fn timeout(&self) -> Duration { self.timeout }

    /// Returns the configured maximum number of concurrent pings in [`ping_many`](Self::ping_many).
    pub fn max_parallel(&self) -> usize { self.max_parallel }

    // ─── Tower ────────────────────────────────────────────────────────────────

    /// Wrap this client in a [`tower::Service`] to add middleware such as
    /// rate limiting, retries, timeouts, and buffering.
    ///
    /// See [`McService`](crate::service::McService) and the `tower_usage` example
    /// for detailed usage.
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// use rust_mc_status::{McClient, McRetryPolicy};
    /// use tower::ServiceBuilder;
    /// use std::time::Duration;
    ///
    /// # #[tokio::main] async fn main() -> Result<(), Box<dyn std::error::Error>> {
    /// let svc = ServiceBuilder::new()
    ///     .buffer(64)
    ///     .retry(McRetryPolicy::new(3))
    ///     .service(McClient::builder().build().into_service());
    /// # Ok(()) }
    /// ```
    #[cfg(feature = "tower")]
    #[cfg_attr(docsrs, doc(cfg(feature = "tower")))]
    pub fn into_service(self) -> crate::service::McService {
        crate::service::McService::new(self)
    }

    // ─── Cache control ────────────────────────────────────────────────────────

    /// Clear the DNS and SRV caches.
    ///
    /// The next ping to any host will re-resolve DNS from scratch.
    /// The response cache is unaffected — use [`clear_response_cache`](Self::clear_response_cache)
    /// to clear it separately.
    pub async fn clear_caches(&self) { self.dns.clear().await; }

    /// Clear the response cache only.
    ///
    /// The next ping to any cached server will perform a live network request.
    /// DNS/SRV caches are unaffected.
    pub async fn clear_response_cache(&self) { self.response_cache.clear().await; }

    /// Return a snapshot of current cache entry counts.
    ///
    /// Useful for monitoring and debugging — does not block any in-flight pings.
    pub async fn cache_stats(&self) -> CacheStats {
        CacheStats {
            dns_entries:      self.dns.dns_len().await,
            srv_entries:      self.dns.srv_len().await,
            response_entries: self.response_cache.len().await,
        }
    }

    // ─── Ping API ─────────────────────────────────────────────────────────────

    /// Start a Java Edition ping for `address`.
    ///
    /// Returns a [`JavaPingBuilder`] — call `.await` to execute, or chain
    /// `.timeout(Duration)` to override the timeout for this request only.
    ///
    /// # Errors
    ///
    /// The returned future may fail with:
    /// - [`McError::Config`] — if `address` is malformed (bad port, missing `]`).
    /// - [`McError::Network`] — DNS failure, connection refused, or timeout.
    /// - [`McError::Protocol`] — unexpected server response.
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// use rust_mc_status::{McClient, StatusExt};
    /// use std::time::Duration;
    ///
    /// # #[tokio::main] async fn main() -> Result<(), rust_mc_status::McError> {
    /// let client = McClient::builder().build();
    ///
    /// // Default timeout
    /// let s = client.java("mc.hypixel.net").await?;
    ///
    /// // Per-request timeout
    /// let s = client.java("mc.hypixel.net")
    ///     .timeout(Duration::from_secs(3))
    ///     .await?;
    /// # Ok(()) }
    /// ```
    pub fn java(&self, address: impl Into<String>) -> JavaPingBuilder {
        JavaPingBuilder::new(self.clone(), address)
    }

    /// Start a Bedrock Edition ping for `address`.
    ///
    /// Returns a [`BedrockPingBuilder`] — call `.await` to execute, or chain
    /// `.timeout(Duration)` to override the timeout for this request only.
    ///
    /// # Errors
    ///
    /// The returned future may fail with:
    /// - [`McError::Config`] — if `address` is malformed.
    /// - [`McError::Network`] — DNS failure, UDP send/receive error, or timeout.
    /// - [`McError::Protocol`] — pong packet too short or malformed MOTD.
    /// - [`McError::Proxy`] — proxy does not support UDP *(feature = "proxy")*.
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// use rust_mc_status::{McClient, StatusExt};
    ///
    /// # #[tokio::main] async fn main() -> Result<(), rust_mc_status::McError> {
    /// let client = McClient::builder().build();
    /// let s = client.bedrock("geo.hivebedrock.network:19132").await?;
    /// println!("{} — {}", s.edition(), s.display_players());
    /// # Ok(()) }
    /// ```
    pub fn bedrock(&self, address: impl Into<String>) -> BedrockPingBuilder {
        BedrockPingBuilder::new(self.clone(), address)
    }

    /// Start a ping where the edition is chosen at runtime.
    ///
    /// Useful when edition comes from user input or a config file.
    /// Returns a [`ServerPingBuilder`] — call `.await` for a raw [`ServerStatus`],
    /// or `.is_online().await` for a simple boolean reachability check.
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// use rust_mc_status::{McClient, ServerEdition};
    /// use std::time::Duration;
    ///
    /// # #[tokio::main] async fn main() -> Result<(), rust_mc_status::McError> {
    /// let client = McClient::builder().build();
    /// let edition: ServerEdition = "java".parse()?;
    ///
    /// let online = client
    ///     .server("mc.hypixel.net", edition)
    ///     .timeout(Duration::from_secs(5))
    ///     .is_online()
    ///     .await;
    ///
    /// println!("online: {online}");
    /// # Ok(()) }
    /// ```
    pub fn server(&self, address: impl Into<String>, edition: ServerEdition) -> ServerPingBuilder {
        ServerPingBuilder::new(self.clone(), address, edition)
    }

    // ─── Batch ────────────────────────────────────────────────────────────────

    /// Ping multiple servers concurrently with bounded parallelism.
    ///
    /// All tasks are spawned immediately — a [`Semaphore`] limits how many run
    /// at once (`max_parallel`, default 10). Results are streamed back as they
    /// complete so a slow or timed-out server never blocks the rest.
    ///
    /// When the response cache is enabled, duplicate addresses in the list
    /// benefit from in-flight deduplication — only one real ping is made per
    /// unique key regardless of how many times it appears.
    ///
    /// # Return value
    ///
    /// A `Vec` of `(ServerInfo, Result<ServerStatus, McError>)` pairs in
    /// completion order (not input order).  Each entry either contains the
    /// full [`ServerStatus`] or the error that occurred for that server.
    ///
    /// [`Semaphore`]: tokio::sync::Semaphore
    ///
    /// All tasks are spawned immediately — a [`Semaphore`] limits how many run
    /// at once. Results stream back as they complete, so a slow or timed-out
    /// server never blocks the rest.
    ///
    /// Duplicate addresses benefit from in-flight deduplication when the
    /// response cache is enabled.
    ///
    /// [`Semaphore`]: tokio::sync::Semaphore
    pub async fn ping_many(
        &self,
        servers: &[ServerInfo],
    ) -> Vec<(ServerInfo, Result<ServerStatus, McError>)> {
        use std::sync::Arc;
        use tokio::sync::Semaphore;
        use tokio::task::JoinSet;

        let sem = Arc::new(Semaphore::new(self.max_parallel));
        let mut set = JoinSet::new();

        for s in servers {
            let s   = s.clone();
            let c   = self.clone();
            let sem = Arc::clone(&sem);
            set.spawn(async move {
                let _permit = sem.acquire().await;
                let result  = match s.edition {
                    ServerEdition::Java    => c.ping_java_inner(&s.address).await.map(|j| j.0),
                    ServerEdition::Bedrock => c.ping_bedrock_inner(&s.address).await.map(|b| b.0),
                };
                (s, result)
            });
        }

        let mut out = Vec::with_capacity(servers.len());
        while let Some(Ok(item)) = set.join_next().await {
            out.push(item);
        }
        out
    }

    // ─── Internal ─────────────────────────────────────────────────────────────

    #[inline]
    fn proxy_ref(&self) -> Option<&ProxyConfig> {
        #[cfg(feature = "proxy")]
        return self.proxy.as_ref();
        #[cfg(not(feature = "proxy"))]
        return None;
    }

    pub(crate) async fn ping_java_inner(&self, address: &str) -> Result<JavaServerStatus, McError> {
        let s = self.ping_with(address, JAVA_DEFAULT_PORT, &JavaModernProtocol, true).await?;
        Ok(JavaServerStatus(s))
    }

    pub(crate) async fn ping_bedrock_inner(&self, address: &str) -> Result<BedrockServerStatus, McError> {
        let s = self.ping_with(address, BEDROCK_DEFAULT_PORT, &BedrockProtocol, false).await?;
        Ok(BedrockServerStatus(s))
    }

    pub(crate) async fn ping_with<P: PingProtocol>(
        &self,
        addr:         &str,
        default_port: u16,
        protocol:     &P,
        try_srv:      bool,
    ) -> Result<ServerStatus, McError> {
        let cache_key = format!("{}:{}", protocol.name(), addr);

        // 1. Completed cache
        if let Some(cached) = self.response_cache.get(&cache_key).await {
            return Ok(cached);
        }

        // 2. In-flight deduplication (thundering herd protection)
        if let Some(mut rx) = self.response_cache.join_or_register(&cache_key).await {
            return match rx.recv().await {
                Ok(Ok(status)) => {
                    let mut s = status;
                    s.cached  = true;
                    s.latency = 0.0;
                    Ok(s)
                }
                Ok(Err(msg)) => Err(McError::invalid_response(msg)),
                Err(_)       => self.do_ping(addr, default_port, protocol, try_srv, &cache_key).await,
            };
        }

        // 3. We are the designated pinger
        self.do_ping(addr, default_port, protocol, try_srv, &cache_key).await
    }

    async fn do_ping<P: PingProtocol>(
        &self,
        addr:         &str,
        default_port: u16,
        protocol:     &P,
        try_srv:      bool,
        cache_key:    &str,
    ) -> Result<ServerStatus, McError> {
        let (host, port, explicit_port) = address::parse(addr, default_port)?;

        let (actual_host, actual_port) = if try_srv && !explicit_port {
            self.dns.lookup_srv(host, self.timeout).await
                .unwrap_or_else(|| (host.to_string(), port))
        } else {
            (host.to_string(), port)
        };

        let (resolved_addr, dns_info) = self.dns.resolve(&actual_host, actual_port).await?;

        let target = ResolvedTarget {
            addr:     resolved_addr,
            hostname: host.to_string(),
            dns_info,
        };

        match protocol.ping(&target, self.timeout, self.proxy_ref()).await {
            Ok(result) => {
                let status = ServerStatus {
                    online:   true,
                    ip:       resolved_addr.ip().to_string(),
                    port:     resolved_addr.port(),
                    hostname: host.to_string(),
                    latency:  result.latency,
                    dns:      Some(target.dns_info),
                    data:     result.data,
                    cached:   false,
                    meta:     result.meta,
                };
                self.response_cache.insert(cache_key.to_string(), status.clone()).await;
                Ok(status)
            }
            Err(e) => {
                self.response_cache.insert_error(cache_key, &e).await;
                Err(e)
            }
        }
    }
}

// ─── McClientBuilder ──────────────────────────────────────────────────────────

/// Builder for [`McClient`].
///
/// Obtain via [`McClient::builder()`].
///
/// All fields are optional — unset fields use sensible defaults.
///
/// # Defaults
///
/// | Field              | Default  |
/// |--------------------|----------|
/// | `timeout`          | 10 s     |
/// | `max_parallel`     | 10       |
/// | `dns_cache_size`   | 1024     |
/// | `response_cache`   | disabled |
/// | `proxy`            | none     |
#[must_use = "call .build() to create the McClient"]
pub struct McClientBuilder {
    timeout:             Duration,
    max_parallel:        usize,
    dns_cache_size:      Option<usize>,
    response_cache_ttl:  Option<Duration>,
    response_cache_size: usize,
    #[cfg(feature = "proxy")]
    proxy:               Option<ProxyConfig>,
}

impl Default for McClientBuilder {
    fn default() -> Self {
        Self {
            timeout:             DEFAULT_TIMEOUT,
            max_parallel:        DEFAULT_MAX_PARALLEL,
            dns_cache_size:      None,
            response_cache_ttl:  None,
            response_cache_size: DEFAULT_RESPONSE_CACHE_SIZE,
            #[cfg(feature = "proxy")]
            proxy:               None,
        }
    }
}

impl McClientBuilder {
    pub(crate) fn new() -> Self { Self::default() }

    /// Maximum time to wait for a single ping (default: 10 s).
    pub fn timeout(mut self, timeout: Duration) -> Self {
        self.timeout = timeout;
        self
    }

    /// Maximum number of concurrent pings in [`McClient::ping_many`] (default: 10).
    pub fn max_parallel(mut self, n: usize) -> Self {
        self.max_parallel = n;
        self
    }

    /// LRU capacity for the DNS/SRV cache (default: 1024).
    pub fn dns_cache_size(mut self, size: usize) -> Self {
        self.dns_cache_size = Some(size);
        self
    }

    /// Enable the response cache with the given TTL and LRU capacity.
    ///
    /// A cached response is returned instantly with `latency = 0` and
    /// `is_cached() = true`.
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// use rust_mc_status::McClient;
    /// use std::time::Duration;
    ///
    /// let client = McClient::builder()
    ///     .response_cache(Duration::from_secs(30), 100)
    ///     .build();
    /// ```
    pub fn response_cache(mut self, ttl: Duration, size: usize) -> Self {
        self.response_cache_ttl  = Some(ttl);
        self.response_cache_size = size;
        self
    }

    /// Enable the response cache with only a TTL (capacity defaults to 256).
    pub fn response_cache_ttl(mut self, ttl: Duration) -> Self {
        self.response_cache_ttl = Some(ttl);
        self
    }

    /// Route all pings through a SOCKS5 proxy.
    ///
    /// Java Edition (TCP) is fully supported.
    /// Bedrock Edition (UDP) requires [`ProxyConfig::socks5_with_udp`].
    #[cfg(feature = "proxy")]
    #[cfg_attr(docsrs, doc(cfg(feature = "proxy")))]
    pub fn proxy(mut self, proxy: ProxyConfig) -> Self {
        self.proxy = Some(proxy);
        self
    }

    /// Consume the builder and return a configured [`McClient`].
    pub fn build(self) -> McClient {
        let dns = match self.dns_cache_size {
            Some(size) => DnsResolver::with_cache_size(size),
            None       => DnsResolver::new(),
        };
        let response_cache = match self.response_cache_ttl {
            Some(ttl) => ResponseCache::new(ttl, self.response_cache_size),
            None      => ResponseCache::disabled(),
        };
        McClient {
            timeout:        self.timeout,
            max_parallel:   self.max_parallel,
            dns,
            response_cache,
            #[cfg(feature = "proxy")]
            proxy:          self.proxy,
        }
    }
}