snarkos_node_tcp/protocols/disconnect.rs
1// Copyright (c) 2019-2026 Provable Inc.
2// This file is part of the snarkOS library.
3
4// Licensed under the Apache License, Version 2.0 (the "License");
5// you may not use this file except in compliance with the License.
6// You may obtain a copy of the License at:
7
8// http://www.apache.org/licenses/LICENSE-2.0
9
10// Unless required by applicable law or agreed to in writing, software
11// distributed under the License is distributed on an "AS IS" BASIS,
12// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13// See the License for the specific language governing permissions and
14// limitations under the License.
15
16use std::{net::SocketAddr, time::Duration};
17
18use tokio::{
19 sync::{mpsc, oneshot},
20 task::JoinHandle,
21 time::timeout,
22};
23use tracing::*;
24
25#[cfg(doc)]
26use crate::{Connection, protocols::Writing};
27use crate::{P2P, connections::create_connection_span, protocols::ProtocolHandler};
28
29/// Can be used to automatically perform some extra actions when the node disconnects from its
30/// peer, which is especially practical if the disconnect is triggered automatically, e.g. due
31/// to the peer exceeding the allowed number of failures or severing its connection with the node
32/// on its own.
33#[async_trait::async_trait]
34pub trait Disconnect: P2P
35where
36 Self: Clone + Send + Sync + 'static,
37{
38 /// The maximum time allowed for the on_disconnect hook to execute.
39 /// If the hook exceeds this time, it will be aborted to ensure the node cleans up
40 /// resources promptly.
41 const TIMEOUT: Duration = Duration::from_secs(3);
42
43 /// Attaches the behavior specified in [`Disconnect::handle_disconnect`] to every occurrence of the
44 /// node disconnecting from a peer.
45 async fn enable_disconnect(&self) {
46 let (from_node_sender, mut from_node_receiver) = mpsc::channel::<(
47 SocketAddr,
48 oneshot::Sender<(JoinHandle<()>, oneshot::Receiver<()>)>,
49 )>(self.tcp().config().max_connections as usize);
50
51 // use a channel to know when the disconnect task is ready
52 let (tx, rx) = oneshot::channel::<()>();
53
54 // spawn a background task dedicated to handling disconnect events
55 let self_clone = self.clone();
56 let disconnect_task = tokio::spawn(async move {
57 trace!(parent: self_clone.tcp().span(), "spawned the Disconnect handler task");
58 tx.send(()).unwrap(); // safe; the channel was just opened
59
60 while let Some((peer_addr, notifier)) = from_node_receiver.recv().await {
61 let self_clone2 = self_clone.clone();
62 // create a channel for waiting on completion
63 let (done_tx, done_rx) = oneshot::channel();
64 let handle = tokio::spawn(async move {
65 // perform the specified extra actions
66 if timeout(Self::TIMEOUT, self_clone2.handle_disconnect(peer_addr)).await.is_err() {
67 let conn_span = create_connection_span(peer_addr, self_clone2.tcp().span());
68 warn!(parent: conn_span, "Disconnect logic timed out");
69 }
70 // notify the node that the extra actions have concluded
71 // and that the related connection can be dropped
72 let _ = done_tx.send(());
73 });
74 // provide the node with a handle to the scheduled task,
75 // and a receiver that will notify it of its completion
76 let _ = notifier.send((handle, done_rx)); // can't really fail
77 }
78 });
79 let _ = rx.await;
80 self.tcp().tasks.lock().push(disconnect_task);
81
82 // register the Disconnect handler with the Tcp
83 let hdl = Box::new(ProtocolHandler(from_node_sender));
84 assert!(
85 self.tcp().protocols.disconnect.set(hdl).is_ok(),
86 "the Disconnect protocol was enabled more than once!"
87 );
88 }
89
90 /// Any extra actions to be executed during a disconnect; in order to still be able to
91 /// communicate with the peer in the usual manner (i.e. via [`Writing`]), only its [`SocketAddr`]
92 /// (as opposed to the related [`Connection`] object) is provided as an argument.
93 async fn handle_disconnect(&self, peer_addr: SocketAddr);
94}