deepslate 0.3.1

A high-performance Minecraft server proxy written in Rust.
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
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
//! Named server registry with ordered try-list and forced-host routing for
//! initial server selection.

use std::collections::HashMap;
use std::sync::{
    Arc,
    atomic::{AtomicBool, Ordering},
};

use arc_swap::ArcSwap;
use tracing::info;

/// A compile-time server identifier for use with the builder API.
///
/// `ServerId` uses `&'static str` fields, making it `const`-constructible and
/// `Copy`. Declare your servers as constants and pass them to
/// [`ProxyBuilder::server`] and [`ProxyBuilder::try_servers`] for type-safe
/// server references that prevent accidental typos.
///
/// ```rust
/// use deepslate::ServerId;
///
/// const LOBBY: ServerId = ServerId::new("lobby", "127.0.0.1:25566");
/// const SURVIVAL: ServerId = ServerId::new("survival", "127.0.0.1:25567");
/// ```
#[derive(Debug, Clone, Copy)]
pub struct ServerId {
    /// Unique identifier (e.g., "lobby", "survival").
    pub id: &'static str,
    /// Upstream address (host:port).
    pub addr: &'static str,
}

impl ServerId {
    /// Create a new server identifier.
    #[must_use]
    pub const fn new(id: &'static str, addr: &'static str) -> Self {
        Self { id, addr }
    }
}

/// A single upstream backend server.
#[derive(Debug, Clone)]
pub struct Server {
    /// Unique identifier (e.g., "lobby", "survival").
    pub id: String,
    /// Upstream address (host:port).
    pub addr: String,
}

impl Server {
    /// Create a new server with the given ID and address.
    #[must_use]
    pub fn new(id: impl Into<String>, addr: impl Into<String>) -> Self {
        Self {
            id: id.into(),
            addr: addr.into(),
        }
    }
}

impl From<&ServerId> for Server {
    fn from(server_id: &ServerId) -> Self {
        Self {
            id: server_id.id.to_owned(),
            addr: server_id.addr.to_owned(),
        }
    }
}

/// Thread-safe registry of named backend servers.
///
/// Servers are registered by ID and looked up by name. A configurable
/// "try" list determines the order in which servers are tried for a
/// player's initial connection. An optional forced-hosts map overrides
/// the try list on a per-hostname basis.
///
/// Uses [`ArcSwap`] internally for wait-free reads, making lookups during
/// connection setup contention-free even under high connection rates.
pub struct ServerRegistry {
    servers: ArcSwap<Vec<Server>>,
    try_order: ArcSwap<Vec<String>>,
    forced_hosts: ArcSwap<HashMap<String, Vec<String>>>,
}

impl ServerRegistry {
    /// Create an empty server registry.
    #[must_use]
    pub fn new() -> Self {
        Self {
            servers: ArcSwap::from_pointee(Vec::new()),
            try_order: ArcSwap::from_pointee(Vec::new()),
            forced_hosts: ArcSwap::from_pointee(HashMap::new()),
        }
    }

    /// Register a new server.
    /// Returns `true` if the server was added, `false` if a server with the
    /// same ID already exists.
    pub fn register(&self, server: &Server) -> bool {
        let added = AtomicBool::new(false);
        self.servers.rcu(|current| {
            if current.iter().any(|s| s.id == server.id) {
                Vec::clone(current)
            } else {
                added.store(true, Ordering::Relaxed);
                let mut new = Vec::clone(current);
                new.push(server.clone());
                new
            }
        });

        let was_added = added.load(Ordering::Relaxed);
        if was_added {
            info!(id = server.id, addr = server.addr, "registered server");
        }
        was_added
    }

    /// Deregister a server by ID.
    /// Returns the removed server, or `None` if not found.
    pub fn deregister(&self, id: &str) -> Option<Server> {
        let current = self.servers.load();
        let pos = current.iter().position(|s| s.id == id)?;
        let removed = current[pos].clone();
        self.servers.rcu(|current| {
            let mut new = Vec::clone(current);
            if let Some(pos) = new.iter().position(|s| s.id == id) {
                new.remove(pos);
            }
            new
        });
        Some(removed)
    }

    /// Look up a server by ID.
    pub fn get(&self, id: &str) -> Option<Server> {
        let servers = self.servers.load();
        servers.iter().find(|s| s.id == id).cloned()
    }

    /// List all registered servers.
    pub fn list(&self) -> Vec<Server> {
        self.servers.load().as_ref().clone()
    }

    /// Set the try order for initial server selection.
    ///
    /// The try list is an ordered list of server IDs. When a player first
    /// connects, the proxy tries each server in order until one is found
    /// in the registry.
    pub fn set_try_order(&self, ids: Vec<String>) {
        self.try_order.store(Arc::new(ids));
    }

    /// Get the current try order.
    pub fn try_order(&self) -> Vec<String> {
        self.try_order.load().as_ref().clone()
    }

    /// Select the first available server from the try list.
    ///
    /// Iterates the try order and returns the first server that exists
    /// in the registry. Returns `None` if no try-list server is registered.
    pub fn select_initial(&self) -> Option<Server> {
        let try_order = self.try_order.load();
        let servers = self.servers.load();

        for id in try_order.iter() {
            if let Some(server) = servers.iter().find(|s| s.id == *id) {
                return Some(server.clone());
            }
        }

        // Fallback: if the try list is empty or has no matches, return the first
        // registered server (if any).
        servers.first().cloned()
    }

    /// Set the forced-hosts map.
    ///
    /// Each key is a hostname (lowercased) and each value is an ordered list
    /// of server IDs to try when a player connects using that hostname.
    pub fn set_forced_hosts(&self, map: HashMap<String, Vec<String>>) {
        self.forced_hosts.store(Arc::new(map));
    }

    /// Get a snapshot of the current forced-hosts map.
    pub fn forced_hosts(&self) -> HashMap<String, Vec<String>> {
        self.forced_hosts.load().as_ref().clone()
    }

    /// Select a server for the given virtual hostname.
    ///
    /// Resolution order:
    /// 1. If `hostname` matches a forced-host entry, try those servers in order.
    /// 2. Otherwise fall back to [`select_initial`](Self::select_initial).
    pub fn select_for_host(&self, hostname: &str) -> Option<Server> {
        let forced = self.forced_hosts.load();
        if let Some(ids) = forced.get(hostname) {
            let servers = self.servers.load();
            for id in ids {
                if let Some(server) = servers.iter().find(|s| s.id == *id) {
                    return Some(server.clone());
                }
            }
            // All forced-host servers are unregistered — fall through to the
            // global try list rather than returning None, so the player still
            // has a chance to connect somewhere.
        }
        self.select_initial()
    }

    /// Return all candidate servers for the given virtual hostname, in
    /// priority order.
    ///
    /// Resolution order mirrors [`select_for_host`](Self::select_for_host):
    /// 1. If `hostname` matches a forced-host entry, resolve those IDs to
    ///    registered servers (skipping any that are not in the registry).
    /// 2. If the forced-host list is empty or yields no registered servers,
    ///    resolve the global try-order IDs instead.
    /// 3. If the try-order is also empty or yields nothing, return all
    ///    registered servers in registration order.
    ///
    /// The caller can iterate the returned list and attempt connections in
    /// order, falling back to the next candidate when one is unreachable.
    pub fn candidates_for_host(&self, hostname: &str) -> Vec<Server> {
        let forced = self.forced_hosts.load();
        let servers = self.servers.load();

        // Try forced-host IDs first.
        if let Some(ids) = forced.get(hostname) {
            let resolved: Vec<Server> = ids
                .iter()
                .filter_map(|id| servers.iter().find(|s| s.id == *id).cloned())
                .collect();
            if !resolved.is_empty() {
                return resolved;
            }
            // All forced-host servers are unregistered — fall through to the
            // global try list.
        }

        // Resolve try-order IDs.
        let try_order = self.try_order.load();
        let resolved: Vec<Server> = try_order
            .iter()
            .filter_map(|id| servers.iter().find(|s| s.id == *id).cloned())
            .collect();
        if !resolved.is_empty() {
            return resolved;
        }

        // Final fallback: all registered servers.
        servers.as_ref().clone()
    }
}

impl Default for ServerRegistry {
    fn default() -> Self {
        Self::new()
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_register_and_list() {
        let reg = ServerRegistry::new();
        let server = Server::new("lobby", "127.0.0.1:25565");

        assert!(reg.register(&server));
        assert!(!reg.register(&server)); // Duplicate

        let servers = reg.list();
        assert_eq!(servers.len(), 1);
        assert_eq!(servers[0].id, "lobby");
    }

    #[test]
    fn test_deregister() {
        let reg = ServerRegistry::new();
        reg.register(&Server::new("lobby", "127.0.0.1:25565"));

        let removed = reg.deregister("lobby");
        assert!(removed.is_some());
        assert_eq!(removed.unwrap().id, "lobby");
        assert!(reg.list().is_empty());

        assert!(reg.deregister("nonexistent").is_none());
    }

    #[test]
    fn test_get() {
        let reg = ServerRegistry::new();
        reg.register(&Server::new("lobby", "127.0.0.1:25565"));
        reg.register(&Server::new("survival", "127.0.0.1:25566"));

        let server = reg.get("survival").unwrap();
        assert_eq!(server.addr, "127.0.0.1:25566");

        assert!(reg.get("nonexistent").is_none());
    }

    #[test]
    fn test_try_order_selection() {
        let reg = ServerRegistry::new();
        reg.register(&Server::new("survival", "127.0.0.1:25566"));
        reg.register(&Server::new("lobby", "127.0.0.1:25565"));

        // Without a try order, fallback returns the first registered server
        assert_eq!(reg.select_initial().unwrap().id, "survival");

        // With a try order, it respects the order
        reg.set_try_order(vec!["lobby".to_string(), "survival".to_string()]);
        assert_eq!(reg.select_initial().unwrap().id, "lobby");
    }

    #[test]
    fn test_try_order_skips_missing() {
        let reg = ServerRegistry::new();
        reg.register(&Server::new("survival", "127.0.0.1:25566"));

        // "lobby" isn't registered, so it skips to "survival"
        reg.set_try_order(vec!["lobby".to_string(), "survival".to_string()]);
        assert_eq!(reg.select_initial().unwrap().id, "survival");
    }

    #[test]
    fn test_select_initial_empty() {
        let reg = ServerRegistry::new();
        assert!(reg.select_initial().is_none());
    }

    #[test]
    fn test_try_order_roundtrip() {
        let reg = ServerRegistry::new();
        let order = vec!["a".to_string(), "b".to_string(), "c".to_string()];
        reg.set_try_order(order.clone());
        assert_eq!(reg.try_order(), order);
    }

    #[test]
    fn test_forced_hosts_roundtrip() {
        let reg = ServerRegistry::new();
        let mut map = HashMap::new();
        map.insert("pvp.example.com".to_string(), vec!["pvp".to_string()]);
        reg.set_forced_hosts(map.clone());
        assert_eq!(reg.forced_hosts(), map);
    }

    #[test]
    fn test_select_for_host_exact_match() {
        let reg = ServerRegistry::new();
        reg.register(&Server::new("lobby", "127.0.0.1:25565"));
        reg.register(&Server::new("pvp", "127.0.0.1:25566"));
        reg.set_try_order(vec!["lobby".to_string()]);

        let mut forced = HashMap::new();
        forced.insert("pvp.example.com".to_string(), vec!["pvp".to_string()]);
        reg.set_forced_hosts(forced);

        assert_eq!(reg.select_for_host("pvp.example.com").unwrap().id, "pvp");
    }

    #[test]
    fn test_select_for_host_falls_back_to_try_order() {
        let reg = ServerRegistry::new();
        reg.register(&Server::new("lobby", "127.0.0.1:25565"));
        reg.register(&Server::new("pvp", "127.0.0.1:25566"));
        reg.set_try_order(vec!["lobby".to_string()]);

        let mut forced = HashMap::new();
        forced.insert("pvp.example.com".to_string(), vec!["pvp".to_string()]);
        reg.set_forced_hosts(forced);

        // Unknown hostname falls back to try_order
        assert_eq!(
            reg.select_for_host("unknown.example.com").unwrap().id,
            "lobby"
        );
    }

    #[test]
    fn test_select_for_host_skips_missing_servers() {
        let reg = ServerRegistry::new();
        reg.register(&Server::new("lobby", "127.0.0.1:25565"));
        reg.register(&Server::new("pvp2", "127.0.0.1:25567"));
        reg.set_try_order(vec!["lobby".to_string()]);

        let mut forced = HashMap::new();
        forced.insert(
            "pvp.example.com".to_string(),
            vec!["pvp-gone".to_string(), "pvp2".to_string()],
        );
        reg.set_forced_hosts(forced);

        // "pvp-gone" isn't registered, so it skips to "pvp2"
        assert_eq!(reg.select_for_host("pvp.example.com").unwrap().id, "pvp2");
    }

    #[test]
    fn test_select_for_host_all_forced_missing_falls_back() {
        let reg = ServerRegistry::new();
        reg.register(&Server::new("lobby", "127.0.0.1:25565"));
        reg.set_try_order(vec!["lobby".to_string()]);

        let mut forced = HashMap::new();
        forced.insert(
            "pvp.example.com".to_string(),
            vec!["gone1".to_string(), "gone2".to_string()],
        );
        reg.set_forced_hosts(forced);

        // All forced servers missing — fall back to try order
        assert_eq!(reg.select_for_host("pvp.example.com").unwrap().id, "lobby");
    }

    #[test]
    fn test_select_for_host_empty_hostname() {
        let reg = ServerRegistry::new();
        reg.register(&Server::new("lobby", "127.0.0.1:25565"));
        reg.set_try_order(vec!["lobby".to_string()]);

        // Empty hostname — no forced host match, falls back to try order
        assert_eq!(reg.select_for_host("").unwrap().id, "lobby");
    }

    #[test]
    fn test_candidates_for_host_forced_hosts() {
        let reg = ServerRegistry::new();
        reg.register(&Server::new("lobby", "127.0.0.1:25565"));
        reg.register(&Server::new("pvp1", "127.0.0.1:25566"));
        reg.register(&Server::new("pvp2", "127.0.0.1:25567"));
        reg.set_try_order(vec!["lobby".to_string()]);

        let mut forced = HashMap::new();
        forced.insert(
            "pvp.example.com".to_string(),
            vec!["pvp1".to_string(), "pvp2".to_string()],
        );
        reg.set_forced_hosts(forced);

        let candidates = reg.candidates_for_host("pvp.example.com");
        let ids: Vec<&str> = candidates.iter().map(|s| s.id.as_str()).collect();
        assert_eq!(ids, vec!["pvp1", "pvp2"]);
    }

    #[test]
    fn test_candidates_for_host_forced_skips_missing() {
        let reg = ServerRegistry::new();
        reg.register(&Server::new("lobby", "127.0.0.1:25565"));
        reg.register(&Server::new("pvp2", "127.0.0.1:25567"));
        reg.set_try_order(vec!["lobby".to_string()]);

        let mut forced = HashMap::new();
        forced.insert(
            "pvp.example.com".to_string(),
            vec!["pvp-gone".to_string(), "pvp2".to_string()],
        );
        reg.set_forced_hosts(forced);

        // "pvp-gone" is not registered, only "pvp2" appears
        let candidates = reg.candidates_for_host("pvp.example.com");
        let ids: Vec<&str> = candidates.iter().map(|s| s.id.as_str()).collect();
        assert_eq!(ids, vec!["pvp2"]);
    }

    #[test]
    fn test_candidates_for_host_forced_all_missing_falls_back() {
        let reg = ServerRegistry::new();
        reg.register(&Server::new("lobby", "127.0.0.1:25565"));
        reg.register(&Server::new("survival", "127.0.0.1:25566"));
        reg.set_try_order(vec!["lobby".to_string(), "survival".to_string()]);

        let mut forced = HashMap::new();
        forced.insert(
            "pvp.example.com".to_string(),
            vec!["gone1".to_string(), "gone2".to_string()],
        );
        reg.set_forced_hosts(forced);

        // All forced servers are unregistered — falls back to try-order
        let candidates = reg.candidates_for_host("pvp.example.com");
        let ids: Vec<&str> = candidates.iter().map(|s| s.id.as_str()).collect();
        assert_eq!(ids, vec!["lobby", "survival"]);
    }

    #[test]
    fn test_candidates_for_host_try_order() {
        let reg = ServerRegistry::new();
        reg.register(&Server::new("survival", "127.0.0.1:25566"));
        reg.register(&Server::new("lobby", "127.0.0.1:25565"));
        reg.set_try_order(vec!["lobby".to_string(), "survival".to_string()]);

        // No forced host match — uses try-order
        let candidates = reg.candidates_for_host("unknown.example.com");
        let ids: Vec<&str> = candidates.iter().map(|s| s.id.as_str()).collect();
        assert_eq!(ids, vec!["lobby", "survival"]);
    }

    #[test]
    fn test_candidates_for_host_try_order_skips_missing() {
        let reg = ServerRegistry::new();
        reg.register(&Server::new("survival", "127.0.0.1:25566"));
        reg.set_try_order(vec![
            "gone".to_string(),
            "survival".to_string(),
            "also-gone".to_string(),
        ]);

        let candidates = reg.candidates_for_host("any.host");
        let ids: Vec<&str> = candidates.iter().map(|s| s.id.as_str()).collect();
        assert_eq!(ids, vec!["survival"]);
    }

    #[test]
    fn test_candidates_for_host_no_try_order_falls_back_to_all() {
        let reg = ServerRegistry::new();
        reg.register(&Server::new("alpha", "127.0.0.1:25565"));
        reg.register(&Server::new("beta", "127.0.0.1:25566"));
        // No try-order set

        let candidates = reg.candidates_for_host("any.host");
        let ids: Vec<&str> = candidates.iter().map(|s| s.id.as_str()).collect();
        assert_eq!(ids, vec!["alpha", "beta"]);
    }

    #[test]
    fn test_candidates_for_host_empty_registry() {
        let reg = ServerRegistry::new();
        let candidates = reg.candidates_for_host("any.host");
        assert!(candidates.is_empty());
    }
}