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
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
//! A high-performance Minecraft server proxy written in Rust.
//!
//! This crate can be used as a library to build a custom proxy binary with
//! compile-time plugins, or as a dependency of the default `deepslate` binary.
//!
//! # Usage as a library
//!
//! ```rust,no_run
//! use deepslate::{Proxy, ServerId};
//! use deepslate::event::*;
//! use deepslate::event::events::*;
//!
//! const LOBBY: ServerId = ServerId::new("lobby", "127.0.0.1:25566");
//!
//! struct LobbyPlugin;
//!
//! impl Plugin for LobbyPlugin {
//!     fn register(&self, events: &mut EventManager) {
//!         events.subscribe::<ChooseServerEvent>(PostOrder::NORMAL, |event| {
//!             event.set_result(LOBBY.into());
//!         });
//!
//!         events.observe::<LoginEvent>(Phase::Post, |event| {
//!             println!("Player logged in: {}", event.player.profile.name);
//!         });
//!     }
//! }
//!
//! #[tokio::main]
//! async fn main() {
//!     let proxy = Proxy::builder()
//!         .forwarding_secret("your-secret")
//!         .server(&LOBBY)
//!         .try_servers([&LOBBY])
//!         .plugin(LobbyPlugin)
//!         .build()
//!         .expect("failed to build proxy");
//!     proxy.run().await.expect("proxy error");
//! }
//! ```

/// Authentication and player profiles.
pub mod auth;
/// Proxy configuration.
pub mod config;
/// Connection handling and networking.
pub mod connection;
/// Connection rate limiting and concurrency guards.
pub mod connection_guard;
/// Cryptographic primitives.
pub mod crypto;
/// Event system and lifecycle events.
pub mod event;
/// Metrics instrumentation and Prometheus exporter.
pub mod metrics;
/// gRPC control plane service.
#[cfg(feature = "grpc")]
pub mod rpc;
/// Server registry and backend management.
pub mod server;
/// Server status (MOTD) handling.
pub mod status;

use std::sync::Arc;
use std::sync::atomic::{AtomicUsize, Ordering};
use std::time::Duration;

use tokio::net::TcpListener;
use tokio::task::JoinSet;
use tokio_util::sync::CancellationToken;
use tracing::{Instrument, error, info, info_span, warn};

pub use config::Config;
pub use event::{EventManager, Phase, PlayerInfo, Plugin, PostOrder};
pub use server::{Server, ServerId, ServerRegistry};

use config::ConfigError;

/// Error type for public proxy operations.
///
/// Returned by [`ProxyBuilder::build`] and [`Proxy::run`] to allow callers to
/// match on specific failure modes rather than relying on string messages.
#[derive(Debug, thiserror::Error)]
pub enum ProxyError {
    /// Configuration loading or validation failed.
    #[error("configuration error: {0}")]
    Config(#[from] ConfigError),

    /// RSA key pair generation failed.
    #[error("RSA key generation failed")]
    KeyGeneration(#[source] Box<dyn std::error::Error + Send + Sync>),

    /// The HTTP client could not be initialised.
    #[error("HTTP client initialization failed")]
    HttpClient(#[from] reqwest::Error),

    /// A server with the given ID was already registered.
    #[error("duplicate server ID: {0}")]
    DuplicateServer(String),

    /// The TCP listener could not bind to the configured address.
    #[error("failed to bind listener")]
    Bind(#[source] std::io::Error),
}

use connection::MinecraftConnection;
use crypto::ServerKeyPair;
#[cfg(feature = "grpc")]
use rpc::DeepslateService;
#[cfg(feature = "grpc")]
use rpc::proto::deepslate_server::DeepslateServer;

/// The Deepslate proxy server.
pub struct Proxy {
    config: Arc<Config>,
    registry: Arc<ServerRegistry>,
    key_pair: Arc<ServerKeyPair>,
    event_manager: Arc<EventManager>,
    http_client: reqwest::Client,
}

impl Proxy {
    /// Create a new proxy builder.
    #[must_use]
    pub fn builder() -> ProxyBuilder {
        ProxyBuilder {
            config: None,
            config_overrides: ConfigOverrides::default(),
            bootstrap_servers: Vec::new(),
            try_servers: None,
            forced_hosts: Vec::new(),
            plugins: Vec::new(),
        }
    }

    /// Get a reference to the proxy configuration.
    #[must_use]
    pub const fn config(&self) -> &Arc<Config> {
        &self.config
    }

    /// Get a reference to the server registry for external management.
    #[must_use]
    pub const fn registry(&self) -> &Arc<ServerRegistry> {
        &self.registry
    }

    /// Get a reference to the event manager.
    #[must_use]
    pub const fn event_manager(&self) -> &Arc<EventManager> {
        &self.event_manager
    }

    /// Run the proxy server.
    ///
    /// This starts the Minecraft listener and, when the `grpc` feature is
    /// enabled, the gRPC control plane. The proxy runs until a shutdown signal
    /// is received (SIGINT/SIGTERM).
    ///
    /// # Errors
    ///
    /// Returns [`ProxyError::Bind`] if the TCP listener cannot bind to the
    /// configured address.
    ///
    /// # Panics
    ///
    /// Panics if the gRPC reflection service fails to build (should not happen
    /// with a valid compiled proto descriptor).
    #[allow(clippy::too_many_lines)]
    pub async fn run(&self) -> Result<(), ProxyError> {
        // Bind the proxy listener first (fail fast on port conflicts)
        let listener = TcpListener::bind(self.config.listen_addr)
            .await
            .map_err(ProxyError::Bind)?;
        info!(addr = %self.config.listen_addr, "proxy listening");

        // Start gRPC control plane
        #[cfg(feature = "grpc")]
        if self.config.grpc_auth_token.is_none() && !self.config.grpc_addr.ip().is_loopback() {
            tracing::warn!(
                addr = %self.config.grpc_addr,
                "gRPC control plane is bound to a non-loopback address without authentication; \
                 set DEEPSLATE_GRPC_AUTH_TOKEN to require a bearer token"
            );
        }
        #[cfg(feature = "grpc")]
        let grpc_addr = self.config.grpc_addr;
        #[cfg(feature = "grpc")]
        let grpc_registry = Arc::clone(&self.registry);
        #[cfg(feature = "grpc")]
        let grpc_auth_token = self.config.grpc_auth_token.clone();
        #[cfg(feature = "grpc")]
        let mut grpc_handle = tokio::spawn(async move {
            let grpc_service = DeepslateService::new(grpc_registry);

            #[cfg(feature = "grpc-reflection")]
            let reflection_service = tonic_reflection::server::Builder::configure()
                .register_encoded_file_descriptor_set(rpc::proto::FILE_DESCRIPTOR_SET)
                .build_v1()
                .expect("failed to build reflection service");

            info!(addr = %grpc_addr, "gRPC control plane listening");

            let mut builder = tonic::transport::Server::builder();

            if let Some(token) = grpc_auth_token {
                let interceptor = rpc::bearer_auth_interceptor(Arc::new(token));
                let builder = builder
                    .add_service(DeepslateServer::with_interceptor(grpc_service, interceptor));

                #[cfg(feature = "grpc-reflection")]
                let builder = builder.add_service(reflection_service);

                builder.serve(grpc_addr).await
            } else {
                let builder = builder.add_service(DeepslateServer::new(grpc_service));

                #[cfg(feature = "grpc-reflection")]
                let builder = builder.add_service(reflection_service);

                builder.serve(grpc_addr).await
            }
        });

        // Start Prometheus metrics exporter
        #[cfg(feature = "metrics")]
        {
            info!(addr = %self.config.metrics_addr, "metrics exporter listening");
            metrics::init_metrics(self.config.metrics_addr);
        }

        // Shared shutdown signal for all connection tasks
        let shutdown = CancellationToken::new();

        // Connection rate limiting — global + per-IP concurrency caps
        let conn_guard = connection_guard::ConnectionGuard::new(
            self.config.max_connections,
            self.config.max_connections_per_ip,
        );
        info!(
            max_connections = self.config.max_connections,
            max_per_ip = self.config.max_connections_per_ip,
            "connection limits configured"
        );

        // Track active connection tasks for graceful drain
        let mut connections = JoinSet::new();
        let session_counter = AtomicUsize::new(0);

        // Accept loop — runs until a shutdown signal or gRPC exit
        loop {
            // When the `grpc` feature is disabled, this future never resolves so
            // the select loop is not affected.
            #[cfg(feature = "grpc")]
            let grpc_fut = &mut grpc_handle;
            #[cfg(not(feature = "grpc"))]
            let grpc_fut = std::future::pending::<Result<(), String>>();

            tokio::select! {
                result = listener.accept() => {
                    match result {
                        Ok((stream, addr)) => {
                            if let Err(e) = stream.set_nodelay(true) {
                                tracing::warn!(error = %e, "failed to set TCP_NODELAY on client stream");
                            }

                            metrics::counter!("connections_accepted_total");

                            // Enforce global + per-IP connection limits.
                            let permit = match conn_guard.try_acquire(addr.ip()) {
                                Ok(permit) => permit,
                                Err(connection_guard::RejectReason::GlobalLimit) => {
                                    metrics::counter!("connections_rejected_total", "reason" => "global_limit");
                                    tracing::debug!(
                                        ip = %addr.ip(),
                                        "rejected connection: global limit reached"
                                    );
                                    continue;
                                }
                                Err(connection_guard::RejectReason::PerIpLimit) => {
                                    metrics::counter!("connections_rejected_total", "reason" => "per_ip_limit");
                                    tracing::debug!(
                                        ip = %addr.ip(),
                                        "rejected connection: per-IP limit reached"
                                    );
                                    continue;
                                }
                            };

                            let session_id = session_counter.fetch_add(1, Ordering::Relaxed);
                            let config = Arc::clone(&self.config);
                            let key_pair = Arc::clone(&self.key_pair);
                            let registry = Arc::clone(&self.registry);
                            let http_client = self.http_client.clone();
                            let event_manager = Arc::clone(&self.event_manager);
                            let conn_shutdown = shutdown.clone();

                            connections.spawn(
                                async move {
                                    // Hold the permit for the connection's lifetime.
                                    let _permit = permit;
                                    metrics::gauge_increment!("connections_active", 1.0);
                                    let conn = MinecraftConnection::new(
                                        stream,
                                        libdeflater::CompressionLvl::new(config.compression_level)
                                            .expect("validated in Config::validate"),
                                        config.read_timeout,
                                    );
                                    if let Err(e) = Box::pin(connection::client::handle_client(
                                        conn,
                                        addr,
                                        config,
                                        key_pair,
                                        registry,
                                        http_client,
                                        event_manager,
                                        conn_shutdown,
                                    ))
                                    .await
                                    {
                                        if e.is_expected() {
                                            tracing::debug!(error = %e, "client disconnected");
                                        } else {
                                            warn!(error = %e, "client connection error");
                                        }
                                    }
                                    metrics::gauge_decrement!("connections_active", 1.0);
                                }
                .instrument(info_span!(
                    "conn",
                    sid = session_id,
                    ip = %addr.ip(),
                    port = addr.port(),
                    username = tracing::field::Empty,
                    uuid = tracing::field::Empty,
                    protocol = tracing::field::Empty,
                )),
                            );
                        }
                        Err(e) => {
                            error!(error = %e, "failed to accept connection");
                            tokio::time::sleep(Duration::from_millis(100)).await;
                        }
                    }
                }

                // Reap completed connection tasks to avoid unbounded growth
                Some(result) = connections.join_next(), if !connections.is_empty() => {
                    if let Err(e) = result {
                        tracing::debug!(error = %e, "connection task panicked");
                    }
                }

                _ = tokio::signal::ctrl_c() => {
                    info!("received shutdown signal");
                    break;
                }

                result = grpc_fut => {
                    if let Err(e) = result {
                        error!(error = %e, "gRPC server error");
                    }
                    break;
                }
            }
        }

        // Begin graceful shutdown
        info!("shutting down");

        // 1. Signal all connection tasks to send disconnect messages
        shutdown.cancel();

        // 2. Wait for active connections to drain (send disconnects and clean up)
        let drain = self.config.shutdown_drain;
        if !connections.is_empty() {
            info!(
                connections = connections.len(),
                drain_ms = u64::try_from(drain.as_millis()).unwrap_or(u64::MAX),
                "draining active connections"
            );
            let _ = tokio::time::timeout(drain, async {
                while connections.join_next().await.is_some() {}
            })
            .await;

            let remaining = connections.len();
            if remaining > 0 {
                info!(
                    remaining,
                    "drain timeout reached, dropping remaining connections"
                );
                connections.abort_all();
            }
        }

        Ok(())
    }
}

/// Builder for constructing a [`Proxy`] instance.
pub struct ProxyBuilder {
    config: Option<Config>,
    config_overrides: ConfigOverrides,
    bootstrap_servers: Vec<ServerId>,
    try_servers: Option<Vec<&'static str>>,
    forced_hosts: Vec<(String, Vec<&'static str>)>,
    plugins: Vec<Box<dyn Plugin>>,
}

impl ProxyBuilder {
    /// Set the proxy configuration. If not called, configuration is loaded
    /// from environment variables.
    #[must_use]
    pub fn config(mut self, config: Config) -> Self {
        self.config = Some(config);
        self
    }

    /// Set the proxy listen address.
    #[must_use]
    pub const fn listen_addr(mut self, listen_addr: std::net::SocketAddr) -> Self {
        self.config_overrides.listen_addr = Some(listen_addr);
        self
    }

    /// Set the gRPC control plane listen address.
    #[cfg(feature = "grpc")]
    #[must_use]
    pub const fn grpc_addr(mut self, grpc_addr: std::net::SocketAddr) -> Self {
        self.config_overrides.grpc_addr = Some(grpc_addr);
        self
    }

    /// Set a bearer token for gRPC control plane authentication.
    ///
    /// When set, every gRPC request must include an `authorization: Bearer <token>`
    /// metadata header. Pass `None` to disable authentication.
    #[cfg(feature = "grpc")]
    #[must_use]
    pub fn grpc_auth_token(mut self, token: impl Into<Option<String>>) -> Self {
        self.config_overrides.grpc_auth_token = Some(token.into());
        self
    }

    /// Enable or disable Mojang authentication.
    #[must_use]
    pub const fn online_mode(mut self, online_mode: bool) -> Self {
        self.config_overrides.online_mode = Some(online_mode);
        self
    }

    /// Set the Velocity modern forwarding secret.
    #[must_use]
    pub fn forwarding_secret(mut self, forwarding_secret: impl AsRef<[u8]>) -> Self {
        self.config_overrides.forwarding_secret = Some(forwarding_secret.as_ref().to_vec());
        self
    }

    /// Set the login compression threshold.
    #[must_use]
    pub const fn compression_threshold(mut self, compression_threshold: i32) -> Self {
        self.config_overrides.compression_threshold = Some(compression_threshold);
        self
    }

    /// Set the zlib compression level.
    #[must_use]
    pub const fn compression_level(mut self, compression_level: i32) -> Self {
        self.config_overrides.compression_level = Some(compression_level);
        self
    }

    /// Set the server list MOTD.
    #[must_use]
    pub fn motd(mut self, motd: impl Into<String>) -> Self {
        self.config_overrides.motd = Some(motd.into());
        self
    }

    /// Set the advertised maximum player count.
    #[must_use]
    pub const fn max_players(mut self, max_players: i32) -> Self {
        self.config_overrides.max_players = Some(max_players);
        self
    }

    /// Set the client read timeout.
    #[must_use]
    pub const fn read_timeout(mut self, read_timeout: Duration) -> Self {
        self.config_overrides.read_timeout = Some(read_timeout);
        self
    }

    /// Set the backend connection timeout.
    ///
    /// Limits how long the proxy waits for a TCP connection to a backend
    /// server. Defaults to 5 seconds.
    #[must_use]
    pub const fn connect_timeout(mut self, connect_timeout: Duration) -> Self {
        self.config_overrides.connect_timeout = Some(connect_timeout);
        self
    }

    /// Set the maximum number of concurrent connections the proxy will accept.
    ///
    /// When this limit is reached, new connections are immediately dropped.
    #[must_use]
    pub const fn max_connections(mut self, max_connections: u32) -> Self {
        self.config_overrides.max_connections = Some(max_connections);
        self
    }

    /// Set the maximum number of concurrent connections from a single IP address.
    ///
    /// When this limit is reached for a given IP, additional connections from
    /// that IP are immediately dropped.
    #[must_use]
    pub const fn max_connections_per_ip(mut self, max_connections_per_ip: u32) -> Self {
        self.config_overrides.max_connections_per_ip = Some(max_connections_per_ip);
        self
    }

    /// Set the initial server try order.
    ///
    /// Accepts an iterable of [`ServerId`] references. The try order determines
    /// which backend server a player is connected to first.
    #[must_use]
    pub fn try_servers<I>(mut self, try_servers: I) -> Self
    where
        I: IntoIterator<Item = &'static ServerId>,
    {
        self.try_servers = Some(try_servers.into_iter().map(|s| s.id).collect());
        self
    }

    /// Add a forced-host entry mapping a hostname to an ordered list of servers.
    ///
    /// When a player connects using the given `hostname`, the proxy tries the
    /// listed servers (in order) instead of the global try list. Only applies
    /// to the initial connection, not server switches.
    ///
    /// The hostname is lowercased for case-insensitive matching.
    ///
    /// Can be called multiple times for different hostnames.
    #[must_use]
    pub fn forced_host<I>(mut self, hostname: impl Into<String>, servers: I) -> Self
    where
        I: IntoIterator<Item = &'static ServerId>,
    {
        let ids: Vec<&'static str> = servers.into_iter().map(|s| s.id).collect();
        self.forced_hosts
            .push((hostname.into().to_lowercase(), ids));
        self
    }

    /// Set the tracing filter string.
    #[must_use]
    pub fn log_level(mut self, log_level: impl Into<String>) -> Self {
        self.config_overrides.log_level = Some(log_level.into());
        self
    }

    /// Enable or disable JSON log output.
    #[must_use]
    pub const fn log_json(mut self, log_json: bool) -> Self {
        self.config_overrides.log_json = Some(log_json);
        self
    }

    /// Set how long to wait for active connections to drain on shutdown.
    #[must_use]
    pub const fn shutdown_drain(mut self, shutdown_drain: std::time::Duration) -> Self {
        self.config_overrides.shutdown_drain = Some(shutdown_drain);
        self
    }

    /// Set the Prometheus metrics exporter listen address.
    #[cfg(feature = "metrics")]
    #[must_use]
    pub const fn metrics_addr(mut self, metrics_addr: std::net::SocketAddr) -> Self {
        self.config_overrides.metrics_addr = Some(metrics_addr);
        self
    }

    /// Register a backend server during proxy construction.
    #[must_use]
    pub fn server(mut self, server: &'static ServerId) -> Self {
        self.bootstrap_servers.push(*server);
        self
    }

    /// Register multiple backend servers during proxy construction.
    #[must_use]
    pub fn servers<I>(mut self, servers: I) -> Self
    where
        I: IntoIterator<Item = &'static ServerId>,
    {
        self.bootstrap_servers.extend(servers.into_iter().copied());
        self
    }

    /// Add a plugin. Multiple plugins can be added; each registers its own
    /// event handlers. Plugins are registered in the order they are added.
    #[must_use]
    pub fn plugin(mut self, plugin: impl Plugin) -> Self {
        self.plugins.push(Box::new(plugin));
        self
    }

    /// Build the proxy.
    ///
    /// All registered plugins will have their [`Plugin::register`] method called
    /// to populate the event manager.
    ///
    /// If builder setters are used without calling [`ProxyBuilder::config`], the
    /// remaining configuration fields fall back to [`Config::default`]. If
    /// [`ProxyBuilder::config`] is provided, builder setters override fields from
    /// that config.
    ///
    /// # Errors
    ///
    /// Returns a [`ProxyError`] if configuration loading, RSA key generation,
    /// HTTP client creation, or server registration fails.
    pub fn build(self) -> Result<Proxy, ProxyError> {
        let mut config = match self.config {
            Some(config) => config,
            None if self.config_overrides.has_any() || !self.bootstrap_servers.is_empty() => {
                Config::default()
            }
            None => Config::from_env()?,
        };
        self.config_overrides.apply(&mut config);
        let config = config.validate()?;

        let key_pair = ServerKeyPair::generate().map_err(ProxyError::KeyGeneration)?;
        info!("generated RSA key pair");

        let mut event_manager = EventManager::new();
        for plugin in &self.plugins {
            plugin.register(&mut event_manager);
        }

        let http_client = reqwest::Client::builder()
            .user_agent(concat!("Deepslate/", env!("CARGO_PKG_VERSION")))
            .connect_timeout(Duration::from_secs(5))
            .timeout(Duration::from_secs(10))
            .build()?;

        let registry = ServerRegistry::new();
        for server_id in &self.bootstrap_servers {
            let server = Server::from(server_id);
            if !registry.register(&server) {
                return Err(ProxyError::DuplicateServer(server_id.id.to_string()));
            }
        }

        // Builder try_servers (typed) takes precedence, then config (string-based
        // from env vars / explicit Config struct).
        if let Some(try_servers) = self.try_servers {
            let order: Vec<String> = try_servers.into_iter().map(String::from).collect();
            registry.set_try_order(order);
        } else if !config.try_servers.is_empty() {
            registry.set_try_order(config.try_servers.clone());
        }

        // Builder forced_hosts (typed) takes precedence, then config (string-based
        // from env vars / explicit Config struct).
        if !self.forced_hosts.is_empty() {
            let map: std::collections::HashMap<String, Vec<String>> = self
                .forced_hosts
                .into_iter()
                .map(|(host, ids)| (host, ids.into_iter().map(String::from).collect()))
                .collect();
            registry.set_forced_hosts(map);
        } else if !config.forced_hosts.is_empty() {
            registry.set_forced_hosts(config.forced_hosts.clone());
        }

        Ok(Proxy {
            config: Arc::new(config),
            registry: Arc::new(registry),
            key_pair: Arc::new(key_pair),
            event_manager: Arc::new(event_manager),
            http_client,
        })
    }
}

#[derive(Default)]
struct ConfigOverrides {
    listen_addr: Option<std::net::SocketAddr>,
    #[cfg(feature = "grpc")]
    grpc_addr: Option<std::net::SocketAddr>,
    #[cfg(feature = "grpc")]
    #[allow(clippy::option_option)]
    // None = no override, Some(None) = disable auth, Some(Some) = set token
    grpc_auth_token: Option<Option<String>>,
    online_mode: Option<bool>,
    forwarding_secret: Option<Vec<u8>>,
    compression_threshold: Option<i32>,
    compression_level: Option<i32>,
    motd: Option<String>,
    max_players: Option<i32>,
    read_timeout: Option<Duration>,
    connect_timeout: Option<Duration>,
    max_connections: Option<u32>,
    max_connections_per_ip: Option<u32>,
    log_level: Option<String>,
    log_json: Option<bool>,
    shutdown_drain: Option<std::time::Duration>,
    #[cfg(feature = "metrics")]
    metrics_addr: Option<std::net::SocketAddr>,
}

impl ConfigOverrides {
    const fn has_any(&self) -> bool {
        // NOTE: `grpc_addr` is checked separately below when the feature is on.
        let base = self.listen_addr.is_some()
            || self.online_mode.is_some()
            || self.forwarding_secret.is_some()
            || self.compression_threshold.is_some()
            || self.compression_level.is_some()
            || self.motd.is_some()
            || self.max_players.is_some()
            || self.read_timeout.is_some()
            || self.connect_timeout.is_some()
            || self.max_connections.is_some()
            || self.max_connections_per_ip.is_some()
            || self.log_level.is_some()
            || self.log_json.is_some()
            || self.shutdown_drain.is_some();

        #[cfg(feature = "grpc")]
        let base = base || self.grpc_addr.is_some() || self.grpc_auth_token.is_some();

        #[cfg(feature = "metrics")]
        let base = base || self.metrics_addr.is_some();

        base
    }

    fn apply(self, config: &mut Config) {
        if let Some(listen_addr) = self.listen_addr {
            config.listen_addr = listen_addr;
        }
        #[cfg(feature = "grpc")]
        if let Some(grpc_addr) = self.grpc_addr {
            config.grpc_addr = grpc_addr;
        }
        #[cfg(feature = "grpc")]
        if let Some(grpc_auth_token) = self.grpc_auth_token {
            config.grpc_auth_token = grpc_auth_token;
        }
        if let Some(online_mode) = self.online_mode {
            config.online_mode = online_mode;
        }
        if let Some(forwarding_secret) = self.forwarding_secret {
            config.forwarding_secret = forwarding_secret;
        }
        if let Some(compression_threshold) = self.compression_threshold {
            config.compression_threshold = compression_threshold;
        }
        if let Some(compression_level) = self.compression_level {
            config.compression_level = compression_level;
        }
        if let Some(motd) = self.motd {
            config.motd = motd;
        }
        if let Some(max_players) = self.max_players {
            config.max_players = max_players;
        }
        if let Some(read_timeout) = self.read_timeout {
            config.read_timeout = read_timeout;
        }
        if let Some(connect_timeout) = self.connect_timeout {
            config.connect_timeout = connect_timeout;
        }
        if let Some(max_connections) = self.max_connections {
            config.max_connections = max_connections;
        }
        if let Some(max_connections_per_ip) = self.max_connections_per_ip {
            config.max_connections_per_ip = max_connections_per_ip;
        }
        if let Some(log_level) = self.log_level {
            config.log_level = log_level;
        }
        if let Some(log_json) = self.log_json {
            config.log_json = log_json;
        }
        if let Some(shutdown_drain) = self.shutdown_drain {
            config.shutdown_drain = shutdown_drain;
        }
        #[cfg(feature = "metrics")]
        if let Some(metrics_addr) = self.metrics_addr {
            config.metrics_addr = metrics_addr;
        }
    }
}

/// Initialize the tracing subscriber based on configuration.
pub fn init_tracing(config: &Config) {
    use tracing_subscriber::EnvFilter;

    let filter = EnvFilter::try_new(&config.log_level).unwrap_or_else(|_| EnvFilter::new("info"));

    if config.log_json {
        tracing_subscriber::fmt()
            .with_env_filter(filter)
            .json()
            .init();
    } else {
        tracing_subscriber::fmt().with_env_filter(filter).init();
    }
}

#[cfg(test)]
mod tests {
    use std::net::{Ipv4Addr, SocketAddr};

    use super::*;

    #[test]
    fn builder_uses_code_config_without_env() {
        let proxy = Proxy::builder()
            .forwarding_secret("secret")
            .listen_addr(SocketAddr::from((Ipv4Addr::LOCALHOST, 25_565)))
            .motd("Configured in code")
            .build()
            .unwrap();

        assert_eq!(
            proxy.config.listen_addr,
            SocketAddr::from((Ipv4Addr::LOCALHOST, 25_565))
        );
        assert_eq!(proxy.config.motd, "Configured in code");
    }

    #[cfg(feature = "grpc")]
    #[test]
    fn builder_sets_grpc_addr() {
        let proxy = Proxy::builder()
            .forwarding_secret("secret")
            .grpc_addr(SocketAddr::from((Ipv4Addr::LOCALHOST, 25_577)))
            .build()
            .unwrap();

        assert_eq!(
            proxy.config.grpc_addr,
            SocketAddr::from((Ipv4Addr::LOCALHOST, 25_577))
        );
    }

    #[test]
    fn builder_rejects_invalid_manual_config() {
        let result = Proxy::builder()
            .forwarding_secret("secret")
            .compression_level(13)
            .build();

        assert!(result.is_err());
    }

    #[test]
    fn builder_bootstraps_servers_and_try_order() {
        static LOBBY: ServerId = ServerId::new("lobby", "127.0.0.1:25566");
        static SURVIVAL: ServerId = ServerId::new("survival", "127.0.0.1:25567");

        let proxy = Proxy::builder()
            .forwarding_secret("secret")
            .server(&LOBBY)
            .server(&SURVIVAL)
            .try_servers([&SURVIVAL, &LOBBY])
            .build()
            .unwrap();

        assert_eq!(proxy.registry.list().len(), 2);
        assert_eq!(proxy.registry.try_order(), vec!["survival", "lobby"]);
        assert_eq!(proxy.registry.select_initial().unwrap().id, "survival");
    }

    #[test]
    fn builder_overrides_explicit_config_fields() {
        let proxy = Proxy::builder()
            .config(Config {
                forwarding_secret: b"base-secret".to_vec(),
                motd: "Base MOTD".to_string(),
                ..Config::default()
            })
            .forwarding_secret("override-secret")
            .motd("Override MOTD")
            .build()
            .unwrap();

        assert_eq!(proxy.config.forwarding_secret, b"override-secret".to_vec());
        assert_eq!(proxy.config.motd, "Override MOTD");
    }
}