snarkos_node_tcp/protocols/disconnect.rs
1// Copyright (c) 2019-2025 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;
17
18use tokio::sync::{mpsc, oneshot};
19use tracing::*;
20
21#[cfg(doc)]
22use crate::{Connection, protocols::Writing};
23use crate::{P2P, protocols::ProtocolHandler};
24
25/// Can be used to automatically perform some extra actions when the node disconnects from its
26/// peer, which is especially practical if the disconnect is triggered automatically, e.g. due
27/// to the peer exceeding the allowed number of failures or severing its connection with the node
28/// on its own.
29#[async_trait::async_trait]
30pub trait Disconnect: P2P
31where
32 Self: Clone + Send + Sync + 'static,
33{
34 /// Attaches the behavior specified in [`Disconnect::handle_disconnect`] to every occurrence of the
35 /// node disconnecting from a peer.
36 async fn enable_disconnect(&self) {
37 let (from_node_sender, mut from_node_receiver) = mpsc::unbounded_channel::<(SocketAddr, oneshot::Sender<()>)>();
38
39 // use a channel to know when the disconnect task is ready
40 let (tx, rx) = oneshot::channel::<()>();
41
42 // spawn a background task dedicated to handling disconnect events
43 let self_clone = self.clone();
44 let disconnect_task = tokio::spawn(async move {
45 trace!(parent: self_clone.tcp().span(), "spawned the Disconnect handler task");
46 tx.send(()).unwrap(); // safe; the channel was just opened
47
48 while let Some((peer_addr, notifier)) = from_node_receiver.recv().await {
49 let self_clone2 = self_clone.clone();
50 tokio::spawn(async move {
51 // perform the specified extra actions
52 self_clone2.handle_disconnect(peer_addr).await;
53 // notify the node that the extra actions have concluded
54 // and that the related connection can be dropped
55 let _ = notifier.send(()); // can't really fail
56 });
57 }
58 });
59 let _ = rx.await;
60 self.tcp().tasks.lock().push(disconnect_task);
61
62 // register the Disconnect handler with the Tcp
63 let hdl = Box::new(ProtocolHandler(from_node_sender));
64 assert!(
65 self.tcp().protocols.disconnect.set(hdl).is_ok(),
66 "the Disconnect protocol was enabled more than once!"
67 );
68 }
69
70 /// Any extra actions to be executed during a disconnect; in order to still be able to
71 /// communicate with the peer in the usual manner (i.e. via [`Writing`]), only its [`SocketAddr`]
72 /// (as opposed to the related [`Connection`] object) is provided as an argument.
73 async fn handle_disconnect(&self, peer_addr: SocketAddr);
74}