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::{
28 P2P,
29 connections::{DisconnectOrigin, create_connection_span},
30 protocols::ProtocolHandler,
31};
32
33/// Can be used to automatically perform some extra actions when the node disconnects from its
34/// peer, which is especially practical if the disconnect is triggered automatically, e.g. due
35/// to the peer exceeding the allowed number of failures or severing its connection with the node
36/// on its own.
37#[async_trait::async_trait]
38pub trait Disconnect: P2P
39where
40 Self: Clone + Send + Sync + 'static,
41{
42 /// The maximum time allowed for the on_disconnect hook to execute.
43 /// If the hook exceeds this time, it will be aborted to ensure the node cleans up
44 /// resources promptly.
45 const TIMEOUT: Duration = Duration::from_secs(3);
46
47 /// Attaches the behavior specified in [`Disconnect::handle_disconnect`] to every occurrence of the
48 /// node disconnecting from a peer.
49 async fn enable_disconnect(&self) {
50 let (from_node_sender, mut from_node_receiver) = mpsc::channel::<(
51 (SocketAddr, DisconnectOrigin),
52 oneshot::Sender<(JoinHandle<()>, oneshot::Receiver<()>)>,
53 )>(self.tcp().config().max_connections as usize);
54
55 // use a channel to know when the disconnect task is ready
56 let (tx, rx) = oneshot::channel::<()>();
57
58 // spawn a background task dedicated to handling disconnect events
59 let self_clone = self.clone();
60 let disconnect_task = tokio::spawn(async move {
61 trace!(parent: self_clone.tcp().span(), "spawned the Disconnect handler task");
62 tx.send(()).unwrap(); // safe; the channel was just opened
63
64 while let Some(((peer_addr, origin), notifier)) = from_node_receiver.recv().await {
65 let self_clone2 = self_clone.clone();
66 // create a channel for waiting on completion
67 let (done_tx, done_rx) = oneshot::channel();
68 let handle = tokio::spawn(async move {
69 // perform the specified extra actions
70 if timeout(Self::TIMEOUT, self_clone2.handle_disconnect(peer_addr, origin)).await.is_err() {
71 let conn_span = create_connection_span(peer_addr, self_clone2.tcp().span());
72 warn!(parent: conn_span, "Disconnect logic timed out");
73 }
74 // notify the node that the extra actions have concluded
75 // and that the related connection can be dropped
76 let _ = done_tx.send(());
77 });
78 // provide the node with a handle to the scheduled task,
79 // and a receiver that will notify it of its completion
80 let _ = notifier.send((handle, done_rx)); // can't really fail
81 }
82 });
83 let _ = rx.await;
84 self.tcp().tasks.lock().push(disconnect_task);
85
86 // register the Disconnect handler with the Tcp
87 let hdl = Box::new(ProtocolHandler(from_node_sender));
88 assert!(
89 self.tcp().protocols.disconnect.set(hdl).is_ok(),
90 "the Disconnect protocol was enabled more than once!"
91 );
92 }
93
94 /// Any extra actions to be executed during a disconnect; in order to still be able to
95 /// communicate with the peer in the usual manner (i.e. via [`Writing`]), only its [`SocketAddr`]
96 /// (as opposed to the related [`Connection`] object) is provided as an argument.
97 async fn handle_disconnect(&self, peer_addr: SocketAddr, origin: DisconnectOrigin);
98}