p2p/connection/
p2p_connection_state.rs1use openmina_core::requests::RpcId;
2use redux::Timestamp;
3
4use malloc_size_of_derive::MallocSizeOf;
5use serde::{Deserialize, Serialize};
6
7use crate::P2pTimeouts;
8
9use super::{
10 incoming::{P2pConnectionIncomingInitOpts, P2pConnectionIncomingState},
11 outgoing::{P2pConnectionOutgoingInitOpts, P2pConnectionOutgoingState},
12};
13
14#[derive(Serialize, Deserialize, Debug, Clone, MallocSizeOf)]
15#[serde(tag = "direction")]
16pub enum P2pConnectionState {
17 Outgoing(P2pConnectionOutgoingState),
18 Incoming(P2pConnectionIncomingState),
19}
20
21impl P2pConnectionState {
22 pub fn outgoing_init(opts: &P2pConnectionOutgoingInitOpts) -> Self {
23 Self::Outgoing(P2pConnectionOutgoingState::Init {
24 time: Timestamp::ZERO,
25 opts: opts.clone(),
26 rpc_id: None,
27 on_success: None,
28 })
29 }
30
31 pub fn incoming_init(opts: &P2pConnectionIncomingInitOpts) -> Self {
32 Self::Incoming(P2pConnectionIncomingState::Init {
33 time: Timestamp::ZERO,
34 signaling: opts.signaling,
35 offer: opts.offer.clone(),
36 rpc_id: None,
37 })
38 }
39
40 pub fn as_outgoing(&self) -> Option<&P2pConnectionOutgoingState> {
41 match self {
42 Self::Outgoing(v) => Some(v),
43 _ => None,
44 }
45 }
46
47 pub fn as_incoming(&self) -> Option<&P2pConnectionIncomingState> {
48 match self {
49 Self::Incoming(v) => Some(v),
50 _ => None,
51 }
52 }
53
54 pub fn rpc_id(&self) -> Option<RpcId> {
55 match self {
56 Self::Outgoing(v) => v.rpc_id(),
57 Self::Incoming(v) => v.rpc_id(),
58 }
59 }
60
61 pub fn is_timed_out(&self, now: Timestamp, timeouts: &P2pTimeouts) -> bool {
62 match self {
63 Self::Outgoing(v) => v.is_timed_out(now, timeouts),
64 Self::Incoming(v) => v.is_timed_out(now, timeouts),
65 }
66 }
67
68 pub fn is_error(&self) -> bool {
69 match self {
70 Self::Outgoing(P2pConnectionOutgoingState::Error { .. }) => true,
71 Self::Outgoing(_) => false,
72 Self::Incoming(P2pConnectionIncomingState::Error { .. }) => true,
73 Self::Incoming(_) => false,
74 }
75 }
76
77 pub fn is_success(&self) -> bool {
78 match self {
79 Self::Outgoing(P2pConnectionOutgoingState::Success { .. }) => true,
80 Self::Outgoing(_) => false,
81 Self::Incoming(P2pConnectionIncomingState::Success { .. }) => true,
82 Self::Incoming(P2pConnectionIncomingState::Libp2pReceived { .. }) => true,
83 Self::Incoming(_) => false,
84 }
85 }
86
87 pub fn time(&self) -> redux::Timestamp {
88 match self {
89 P2pConnectionState::Outgoing(o) => o.time(),
90 P2pConnectionState::Incoming(i) => i.time(),
91 }
92 }
93}