jd_client_sv2 0.2.0

Job Declarator Client (JDC) role
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
use std::{
    sync::{
        atomic::{AtomicBool, Ordering},
        Arc,
    },
    thread::JoinHandle,
    time::Duration,
};

use async_channel::{unbounded, Receiver, Sender};
use bitcoin_core_sv2::template_distribution_protocol::CancellationToken;
use stratum_apps::{
    fallback_coordinator::FallbackCoordinator,
    stratum_core::{bitcoin::consensus::Encodable, parsers_sv2::JobDeclaration},
    task_manager::TaskManager,
    tp_type::TemplateProviderType,
    utils::types::{Sv2Frame, GRACEFUL_SHUTDOWN_TIMEOUT_SECONDS},
};
use tokio::sync::Notify;
use tracing::{debug, error, info, warn};

use crate::{
    channel_manager::ChannelManager,
    config::JobDeclaratorClientConfig,
    error::JDCErrorKind,
    jd_mode::JDMode,
    job_declarator::JobDeclarator,
    template_receiver::{
        bitcoin_core::{connect_to_bitcoin_core, BitcoinCoreSv2TDPConfig},
        sv2_tp::Sv2Tp,
    },
    upstream::Upstream,
    utils::{UpstreamEntry, UpstreamState},
};

mod channel_manager;
pub mod config;
mod downstream;
pub mod error;
mod io_task;
pub mod jd_mode;
mod job_declarator;
#[cfg(feature = "monitoring")]
pub mod monitoring;
mod template_receiver;
mod upstream;
pub mod utils;

/// Represent Job Declarator Client
#[derive(Clone)]
pub struct JobDeclaratorClient {
    config: JobDeclaratorClientConfig,
    cancellation_token: CancellationToken,
    shutdown_notify: Arc<Notify>,
    is_alive: Arc<AtomicBool>,
}

#[cfg_attr(not(test), hotpath::measure_all)]
impl JobDeclaratorClient {
    /// Creates a new [`JobDeclaratorClient`] instance.
    pub fn new(config: JobDeclaratorClientConfig) -> Self {
        Self {
            config,
            cancellation_token: CancellationToken::new(),
            shutdown_notify: Arc::new(Notify::new()),
            is_alive: Arc::new(AtomicBool::new(true)),
        }
    }

    /// Starts the Job Declarator Client (JDC) main loop.
    pub async fn start(&self) {
        info!(
            "Job declarator client starting... setting up subsystems, User Identity: {}",
            self.config.user_identity()
        );

        let miner_coinbase_outputs = vec![self.config.get_txout()];
        let mut encoded_outputs = vec![];
        let mode = JDMode::new(self.config.mode);

        if let Err(e) = miner_coinbase_outputs.consensus_encode(&mut encoded_outputs) {
            error!(error = ?e, "Invalid coinbase output in config");
            self.cancellation_token.cancel();
            self.shutdown_notify.notify_waiters();
            self.is_alive.store(false, Ordering::Relaxed);
            return;
        }

        let mut fallback_coordinator = FallbackCoordinator::new();
        let task_manager = Arc::new(TaskManager::new());

        let (channel_manager_to_upstream_sender, channel_manager_to_upstream_receiver) =
            unbounded();
        let (upstream_to_channel_manager_sender, upstream_to_channel_manager_receiver) =
            unbounded();

        let (channel_manager_to_jd_sender, channel_manager_to_jd_receiver) = unbounded();
        let (jd_to_channel_manager_sender, jd_to_channel_manager_receiver) = unbounded();

        let (downstream_to_channel_manager_sender, downstream_to_channel_manager_receiver) =
            unbounded();

        let (channel_manager_to_tp_sender, channel_manager_to_tp_receiver) = unbounded();
        let (tp_to_channel_manager_sender, tp_to_channel_manager_receiver) = unbounded();

        debug!("Channels initialized.");

        let channel_manager = match ChannelManager::new(
            self.config.clone(),
            channel_manager_to_upstream_sender.clone(),
            upstream_to_channel_manager_receiver.clone(),
            channel_manager_to_jd_sender.clone(),
            jd_to_channel_manager_receiver.clone(),
            channel_manager_to_tp_sender.clone(),
            tp_to_channel_manager_receiver.clone(),
            downstream_to_channel_manager_receiver,
            encoded_outputs.clone(),
            self.config.supported_extensions().to_vec(),
            self.config.required_extensions().to_vec(),
            mode.clone(),
        )
        .await
        {
            Ok(channel_manager) => channel_manager,
            Err(e) => {
                error!(error = ?e, "Failed to initialize channel manager");
                self.cancellation_token.cancel();
                self.shutdown_notify.notify_waiters();
                self.is_alive.store(false, Ordering::Relaxed);
                return;
            }
        };

        // Start monitoring server if configured
        #[cfg(feature = "monitoring")]
        if let Some(monitoring_addr) = self.config.monitoring_address() {
            info!(
                "Initializing monitoring server on http://{}",
                monitoring_addr
            );

            let monitoring_server = match stratum_apps::monitoring::MonitoringServer::new(
                monitoring_addr,
                Some(Arc::new(channel_manager.clone())), // SV2 channels opened with servers
                Some(Arc::new(channel_manager.clone())), // SV2 channels opened with clients
                std::time::Duration::from_secs(
                    self.config.monitoring_cache_refresh_secs().unwrap_or(15),
                ),
            ) {
                Ok(monitoring_server) => Some(monitoring_server),
                Err(e) => {
                    error!(error = ?e, "Failed to initialize monitoring server");
                    None
                }
            };

            if let Some(monitoring_server) = monitoring_server {
                // Create shutdown signal using cancellation token
                let cancellation_token_clone = self.cancellation_token.clone();
                let fallback_coordinator_token = fallback_coordinator.token();
                let shutdown_signal = async move {
                    tokio::select! {
                        _ = cancellation_token_clone.cancelled() => {
                            info!("Monitoring server: received shutdown signal.");
                        }
                        _ = fallback_coordinator_token.cancelled() => {
                            info!("Monitoring server: fallback triggered.");
                        }
                    }
                };

                let fallback_coordinator_clone = fallback_coordinator.clone();
                task_manager.spawn(async move {
                    // we just spawned a new task that's relevant to fallback coordination
                    // so register it with the fallback coordinator
                    let fallback_handler = fallback_coordinator_clone.register();

                    if let Err(e) = monitoring_server.run(shutdown_signal).await {
                        error!("Monitoring server error: {:?}", e);
                    }

                    // signal fallback coordinator that this task has completed its cleanup
                    fallback_handler.done();
                    info!("Monitoring server task exited and signaled fallback coordinator");
                });
            }
        }

        let initial_channel_manager = channel_manager.clone();
        let mut bitcoin_core_sv2_join_handle: Option<JoinHandle<()>> = None;
        let mut bitcoin_core_sv2_cancellation_token: Option<CancellationToken> = None;

        match self.config.template_provider_type().clone() {
            TemplateProviderType::Sv2Tp {
                address,
                public_key,
            } => {
                let template_receiver = match Sv2Tp::new(
                    address.clone(),
                    public_key,
                    channel_manager_to_tp_receiver,
                    tp_to_channel_manager_sender,
                    self.cancellation_token.clone(),
                    task_manager.clone(),
                )
                .await
                {
                    Ok(template_receiver) => template_receiver,
                    Err(e) => {
                        error!(error = ?e, "Failed to initialize SV2 template receiver");
                        self.cancellation_token.cancel();
                        self.shutdown_notify.notify_waiters();
                        self.is_alive.store(false, Ordering::Relaxed);
                        return;
                    }
                };

                let cancellation_token_tp = self.cancellation_token.clone();
                let task_manager_cl = task_manager.clone();

                if let Err(e) = template_receiver
                    .start(address, cancellation_token_tp, task_manager_cl)
                    .await
                {
                    error!(error = ?e, "Failed to start SV2 template receiver");
                    self.cancellation_token.cancel();
                    self.shutdown_notify.notify_waiters();
                    self.is_alive.store(false, Ordering::Relaxed);
                    return;
                }

                info!("Sv2 Template Provider setup done");
            }
            TemplateProviderType::BitcoinCoreIpc {
                network,
                data_dir,
                fee_threshold,
                min_interval,
            } => {
                let unix_socket_path = match stratum_apps::tp_type::resolve_ipc_socket_path(
                    &network, data_dir,
                ) {
                    Some(unix_socket_path) => unix_socket_path,
                    None => {
                        error!(
                                "Could not determine Bitcoin data directory. Please set data_dir in config."
                            );
                        self.cancellation_token.cancel();
                        self.shutdown_notify.notify_waiters();
                        self.is_alive.store(false, Ordering::Relaxed);
                        return;
                    }
                };

                info!(
                    "Using Bitcoin Core IPC socket at: {}",
                    unix_socket_path.display()
                );

                // incoming and outgoing TDP channels from the perspective of BitcoinCoreSv2TDP
                let incoming_tdp_receiver = channel_manager_to_tp_receiver.clone();
                let outgoing_tdp_sender = tp_to_channel_manager_sender.clone();

                let bitcoin_core_cancellation_token = CancellationToken::new();
                let bitcoin_core_config = BitcoinCoreSv2TDPConfig {
                    unix_socket_path,
                    fee_threshold,
                    min_interval,
                    incoming_tdp_receiver,
                    outgoing_tdp_sender,
                    cancellation_token: bitcoin_core_cancellation_token.clone(),
                };

                bitcoin_core_sv2_cancellation_token = Some(bitcoin_core_cancellation_token);
                bitcoin_core_sv2_join_handle = Some(
                    connect_to_bitcoin_core(
                        bitcoin_core_config,
                        self.cancellation_token.clone(),
                        task_manager.clone(),
                    )
                    .await,
                );
            }
        }

        let mut upstream_addresses: Vec<_> = self
            .config
            .upstreams()
            .iter()
            .map(|u| UpstreamEntry {
                pool_host: u.pool_address.clone(),
                pool_port: u.pool_port,
                jds_host: u.jds_address.clone(),
                jds_port: u.jds_port,
                authority_pubkey: u.authority_pubkey,
                tried_or_flagged: false,
            })
            .collect();

        channel_manager
            .clone()
            .start(
                self.cancellation_token.clone(),
                fallback_coordinator.clone(),
                task_manager.clone(),
                miner_coinbase_outputs.clone(),
            )
            .await;

        if self.config.mode == config::ConfigJDCMode::SoloMining {
            if !upstream_addresses.is_empty() {
                warn!(
                    "Solo mining mode configured but upstreams are present - they will be ignored"
                );
            }
            info!("Starting in solo mining mode");
            mode.set_solo_mining();
        } else if upstream_addresses.is_empty() {
            error!(
                "No upstreams configured for {:?} mode - at least one upstream is required",
                self.config.mode
            );
            self.cancellation_token.cancel();
        } else {
            info!("Attempting to initialize upstream...");

            match self
                .initialize_jd(
                    &mut upstream_addresses,
                    channel_manager_to_upstream_receiver.clone(),
                    upstream_to_channel_manager_sender.clone(),
                    channel_manager_to_jd_receiver.clone(),
                    jd_to_channel_manager_sender.clone(),
                    self.cancellation_token.clone(),
                    fallback_coordinator.clone(),
                    mode.clone(),
                    task_manager.clone(),
                )
                .await
            {
                Ok((upstream, job_declarator)) => {
                    upstream
                        .start(
                            self.config.min_supported_version(),
                            self.config.max_supported_version(),
                            self.cancellation_token.clone(),
                            fallback_coordinator.clone(),
                            task_manager.clone(),
                        )
                        .await;

                    job_declarator
                        .start(
                            self.cancellation_token.clone(),
                            fallback_coordinator.clone(),
                            task_manager.clone(),
                        )
                        .await;

                    initial_channel_manager
                        .upstream_state
                        .set(UpstreamState::NoChannel);
                    _ = initial_channel_manager.allocate_tokens(2).await;
                }
                Err(e) => {
                    tracing::error!("Failed to initialize upstream: {:?}", e);
                    mode.set_solo_mining();
                }
            };
        }

        task_manager.spawn({
            let config = self.config.clone();
            let cancellation_token = self.cancellation_token.clone();
            let task_manager = task_manager.clone();
            let fallback_coordinator = fallback_coordinator.clone();
            async move {
                if let Err(e) = initial_channel_manager
                    .start_downstream_server(
                        *config.authority_public_key(),
                        *config.authority_secret_key(),
                        config.cert_validity_sec(),
                        *config.listening_address(),
                        task_manager,
                        cancellation_token.clone(),
                        fallback_coordinator,
                        downstream_to_channel_manager_sender,
                        config.supported_extensions().to_vec(),
                        config.required_extensions().to_vec(),
                    )
                    .await
                {
                    tracing::error!(?e, "Downstream server task exited with error");
                    cancellation_token.cancel();
                }
            }
        });

        info!("Spawning status listener task...");
        let mut fallback_token = fallback_coordinator.token();

        loop {
            tokio::select! {
                biased;

                _ = self.cancellation_token.cancelled() => {
                    break;
                }
                _ = fallback_token.cancelled() => {
                    warn!("Upstream/Job Declarator connection dropped — attempting reconnection...");

                    // trigger fallback and wait for all components to finish cleanup
                    fallback_coordinator.trigger_fallback_and_wait().await;
                    info!("All components finished fallback cleanup");

                    mode.set_solo_mining();
                    info!("Existing Upstream or JD instance taken out. Preparing fallback.");

                    // Create a fresh FallbackCoordinator for the reconnection attempt
                    fallback_coordinator = FallbackCoordinator::new();
                    fallback_token = fallback_coordinator.token();

                    // Recreate channels (old ones were closed during fallback)
                    let (channel_manager_to_upstream_sender_new, channel_manager_to_upstream_receiver_new) =
                        unbounded();
                    let (upstream_to_channel_manager_sender_new, upstream_to_channel_manager_receiver_new) =
                        unbounded();
                    let (channel_manager_to_jd_sender_new, channel_manager_to_jd_receiver_new) = unbounded();
                    let (jd_to_channel_manager_sender_new, jd_to_channel_manager_receiver_new) = unbounded();

                    let (downstream_to_channel_manager_sender_new, downstream_to_channel_manager_receiver_new) =
                        unbounded();

                    // Create a fresh channel_manager with new channels
                    let channel_manager = match ChannelManager::new(
                        self.config.clone(),
                        channel_manager_to_upstream_sender_new.clone(),
                        upstream_to_channel_manager_receiver_new.clone(),
                        channel_manager_to_jd_sender_new.clone(),
                        jd_to_channel_manager_receiver_new.clone(),
                        channel_manager_to_tp_sender.clone(),
                        tp_to_channel_manager_receiver.clone(),
                        downstream_to_channel_manager_receiver_new.clone(),
                        encoded_outputs.clone(),
                        self.config.supported_extensions().to_vec(),
                        self.config.required_extensions().to_vec(),
                        mode.clone(),
                    )
                    .await
                    {
                        Ok(channel_manager) => channel_manager,
                        Err(e) => {
                            error!(error = ?e, "Failed to initialize channel manager during fallback");
                            self.cancellation_token.cancel();
                            break;
                        }
                    };

                    channel_manager.clone()
                        .start(
                            self.cancellation_token.clone(),
                            fallback_coordinator.clone(),
                            task_manager.clone(),
                            miner_coinbase_outputs.clone(),
                        )
                        .await;

                    info!("Attempting to initialize Jd and upstream...");

                    match self
                        .initialize_jd(
                            &mut upstream_addresses,
                            channel_manager_to_upstream_receiver_new.clone(),
                            upstream_to_channel_manager_sender_new.clone(),
                            channel_manager_to_jd_receiver_new.clone(),
                            jd_to_channel_manager_sender_new.clone(),
                            self.cancellation_token.clone(),
                            fallback_coordinator.clone(),
                            mode.clone(),
                            task_manager.clone(),
                        )
                        .await
                    {
                        Ok((upstream, job_declarator)) => {
                            upstream
                                .start(
                                    self.config.min_supported_version(),
                                    self.config.max_supported_version(),
                                    self.cancellation_token.clone(),
                                    fallback_coordinator.clone(),
                                    task_manager.clone(),
                                )
                                .await;

                            job_declarator
                                .start(
                                    self.cancellation_token.clone(),
                                    fallback_coordinator.clone(),
                                    task_manager.clone(),
                                )
                                .await;

                            channel_manager
                                .upstream_state
                                .set(UpstreamState::NoChannel);

                            _ = channel_manager.allocate_tokens(2).await;
                        }
                        Err(e) => {
                            tracing::error!("Failed to initialize upstream: {:?}", e);
                            channel_manager
                                .upstream_state
                                .set(UpstreamState::SoloMining);
                            mode.set_solo_mining();
                            info!("Fallback to solo mining mode");
                        }
                    };

                    // Reinitialize monitoring server if configured
                    #[cfg(feature = "monitoring")]
                    if let Some(monitoring_addr) = self.config.monitoring_address() {
                        info!(
                            "Reinitializing monitoring server on http://{}",
                            monitoring_addr
                        );

                        let monitoring_server = match stratum_apps::monitoring::MonitoringServer::new(
                            monitoring_addr,
                            Some(Arc::new(channel_manager.clone())),
                            Some(Arc::new(channel_manager.clone())),
                            std::time::Duration::from_secs(
                                self.config.monitoring_cache_refresh_secs().map_or(15, |secs| secs),
                            ),
                        )
                        {
                            Ok(monitoring_server) => Some(monitoring_server),
                            Err(e) => {
                                error!(error = ?e, "Failed to initialize monitoring server");
                                None
                            }
                        };

                        if let Some(monitoring_server) = monitoring_server {
                            let cancellation_token_clone = self.cancellation_token.clone();
                            let fallback_coordinator_token = fallback_coordinator.token();
                            let shutdown_signal = async move {
                                tokio::select! {
                                    _ = cancellation_token_clone.cancelled() => {
                                        info!("Monitoring server: received shutdown signal.");
                                    }
                                    _ = fallback_coordinator_token.cancelled() => {
                                        info!("Monitoring server: fallback triggered.");
                                    }
                                }
                            };

                            let fallback_coordinator_clone = fallback_coordinator.clone();
                            task_manager.spawn(async move {
                                // we just spawned a new task that's relevant to fallback coordination
                                // so register it with the fallback coordinator
                                let fallback_handler = fallback_coordinator_clone.register();

                                if let Err(e) = monitoring_server.run(shutdown_signal).await {
                                    error!("Monitoring server error: {:?}", e);
                                }

                                // signal that this task has completed its cleanup
                                // (no-op during normal shutdown, only matters during fallback)
                                fallback_handler.done();
                                info!("Monitoring server task exited and signaled fallback coordinator");
                            });
                        }
                    }

                    task_manager.spawn({
                        let config = self.config.clone();
                        let cancellation_token = self.cancellation_token.clone();
                        let task_manager = task_manager.clone();
                        let fallback_coordinator = fallback_coordinator.clone();
                        async move {
                            if let Err(e) = channel_manager
                                .start_downstream_server(
                                    *config.authority_public_key(),
                                    *config.authority_secret_key(),
                                    config.cert_validity_sec(),
                                    *config.listening_address(),
                                    task_manager,
                                    cancellation_token.clone(),
                                    fallback_coordinator,
                                    downstream_to_channel_manager_sender_new,
                                    config.supported_extensions().to_vec(),
                                    config.required_extensions().to_vec(),
                                )
                                .await {
                                    tracing::error!(?e, "Downstream server task exited with error");
                                    cancellation_token.cancel();
                                }
                        }
                    });
                }
                _ = tokio::signal::ctrl_c() => {
                    info!("Ctrl+C received — initiating graceful shutdown...");
                    self.cancellation_token.cancel();
                    break;
                }
            }
        }

        if let Some(bitcoin_core_sv2_cancellation_token) = bitcoin_core_sv2_cancellation_token {
            bitcoin_core_sv2_cancellation_token.cancel();
        }

        if let Some(bitcoin_core_sv2_join_handle) = bitcoin_core_sv2_join_handle {
            info!("Waiting for BitcoinCoreSv2TDP dedicated thread to shutdown...");
            match bitcoin_core_sv2_join_handle.join() {
                Ok(_) => info!("BitcoinCoreSv2TDP dedicated thread shutdown complete."),
                Err(e) => error!("BitcoinCoreSv2TDP dedicated thread error: {e:?}"),
            }
        }

        warn!(
            "Graceful shutdown: waiting {} seconds for tasks to finish",
            GRACEFUL_SHUTDOWN_TIMEOUT_SECONDS
        );
        match tokio::time::timeout(
            std::time::Duration::from_secs(GRACEFUL_SHUTDOWN_TIMEOUT_SECONDS),
            task_manager.join_all(),
        )
        .await
        {
            Ok(_) => {
                info!("All tasks joined cleanly");
            }
            Err(_) => {
                warn!(
                    "Tasks did not finish within {} seconds, aborting",
                    GRACEFUL_SHUTDOWN_TIMEOUT_SECONDS
                );
                task_manager.abort_all().await;
                info!("Joining aborted tasks...");
                task_manager.join_all().await;
                warn!("Forced shutdown complete");
            }
        }
        self.shutdown_notify.notify_waiters();
        self.is_alive.store(false, Ordering::Relaxed);
        info!("JD Client shutdown complete.");
    }

    pub async fn shutdown(&self) {
        if !self.is_alive.load(Ordering::Relaxed) {
            return;
        }
        // The Notified future is guaranteed to receive wakeups from notify_waiters()
        // as soon as it has been created, even if it has not yet been polled.
        let notified = self.shutdown_notify.notified();
        self.cancellation_token.cancel();
        notified.await;
    }

    /// Initializes an upstream pool + JD connection pair.
    #[allow(clippy::too_many_arguments)]
    pub async fn initialize_jd(
        &self,
        upstreams: &mut [UpstreamEntry],
        channel_manager_to_upstream_receiver: Receiver<Sv2Frame>,
        upstream_to_channel_manager_sender: Sender<Sv2Frame>,
        channel_manager_to_jd_receiver: Receiver<JobDeclaration<'static>>,
        jd_to_channel_manager_sender: Sender<JobDeclaration<'static>>,
        cancellation_token: CancellationToken,
        fallback_coordinator: FallbackCoordinator,
        mode: JDMode,
        task_manager: Arc<TaskManager>,
    ) -> Result<(Upstream, JobDeclarator), JDCErrorKind> {
        const MAX_RETRIES: usize = 3;
        let upstream_len = upstreams.len();
        for (i, upstream_entry) in upstreams.iter_mut().enumerate() {
            info!(
                "Trying upstream {} of {}: pool={}:{}, jds={}:{}",
                i + 1,
                upstream_len,
                upstream_entry.pool_host,
                upstream_entry.pool_port,
                upstream_entry.jds_host,
                upstream_entry.jds_port,
            );

            tokio::select! {
                biased;
                _ = cancellation_token.cancelled() => {
                    info!("Shutdown requested while waiting to initialize upstream, aborting retries");
                    return Err(JDCErrorKind::CouldNotInitiateSystem);
                }
                _ = tokio::time::sleep(Duration::from_secs(1)) => {}
            }

            if upstream_entry.tried_or_flagged {
                info!(
                    "Upstream previously marked as malicious, skipping initial attempt warnings."
                );
                continue;
            }

            for attempt in 1..=MAX_RETRIES {
                if cancellation_token.is_cancelled() {
                    info!(
                        "Shutdown requested before upstream connection attempt, aborting retries"
                    );
                    return Err(JDCErrorKind::CouldNotInitiateSystem);
                }

                info!("Connection attempt {}/{}...", attempt, MAX_RETRIES);

                match try_initialize_single(
                    upstream_entry,
                    upstream_to_channel_manager_sender.clone(),
                    channel_manager_to_upstream_receiver.clone(),
                    jd_to_channel_manager_sender.clone(),
                    channel_manager_to_jd_receiver.clone(),
                    cancellation_token.clone(),
                    fallback_coordinator.clone(),
                    mode.clone(),
                    task_manager.clone(),
                    &self.config,
                )
                .await
                {
                    Ok(pair) => {
                        upstream_entry.tried_or_flagged = true;
                        return Ok(pair);
                    }
                    Err(e) => {
                        tracing::error!("Upstream and JDS connection terminated");

                        tokio::select! {
                            biased;
                            _ = cancellation_token.cancelled() => {
                                info!("Shutdown requested after upstream initialization failure, aborting retries");
                                return Err(JDCErrorKind::CouldNotInitiateSystem);
                            }
                            _ = tokio::time::sleep(Duration::from_secs(1)) => {}
                        }

                        warn!(
                            "Attempt {}/{} failed for pool={}:{}, jds={}:{}: {:?}",
                            attempt,
                            MAX_RETRIES,
                            upstream_entry.pool_host,
                            upstream_entry.pool_port,
                            upstream_entry.jds_host,
                            upstream_entry.jds_port,
                            e
                        );
                        if attempt == MAX_RETRIES {
                            warn!(
                                "Max retries reached for pool={}:{}, jds={}:{}, moving to next upstream",
                                upstream_entry.pool_host,
                                upstream_entry.pool_port,
                                upstream_entry.jds_host,
                                upstream_entry.jds_port,
                            );
                        }
                    }
                }
            }
            upstream_entry.tried_or_flagged = true;
        }

        tracing::error!("All upstreams failed after {} retries each", MAX_RETRIES);
        Err(JDCErrorKind::CouldNotInitiateSystem)
    }
}

// Attempts to initialize a single upstream (pool + JDS pair).
#[allow(clippy::too_many_arguments)]
#[cfg_attr(not(test), hotpath::measure)]
async fn try_initialize_single(
    upstream_entry: &UpstreamEntry,
    upstream_to_channel_manager_sender: Sender<Sv2Frame>,
    channel_manager_to_upstream_receiver: Receiver<Sv2Frame>,
    jd_to_channel_manager_sender: Sender<JobDeclaration<'static>>,
    channel_manager_to_jd_receiver: Receiver<JobDeclaration<'static>>,
    cancellation_token: CancellationToken,
    fallback_coordinator: FallbackCoordinator,
    mode: JDMode,
    task_manager: Arc<TaskManager>,
    config: &JobDeclaratorClientConfig,
) -> Result<(Upstream, JobDeclarator), JDCErrorKind> {
    info!("Upstream connection in-progress at initialize single");
    let upstream = Upstream::new(
        upstream_entry,
        upstream_to_channel_manager_sender,
        channel_manager_to_upstream_receiver,
        cancellation_token.clone(),
        fallback_coordinator.clone(),
        task_manager.clone(),
        config.required_extensions().to_vec(),
    )
    .await
    .map_err(|error| error.kind)?;

    info!("Upstream connection done at initialize single");

    let job_declarator = JobDeclarator::new(
        upstream_entry,
        jd_to_channel_manager_sender,
        channel_manager_to_jd_receiver,
        cancellation_token,
        fallback_coordinator,
        mode,
        task_manager.clone(),
    )
    .await
    .map_err(|error| error.kind)?;

    Ok((upstream, job_declarator))
}

impl Drop for JobDeclaratorClient {
    fn drop(&mut self) {
        info!("JobDeclaratorClient dropped");
        self.cancellation_token.cancel();
    }
}