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
use crate::prefabs::client::single_connection::SingleClientServerConnectionKernel;
use crate::prefabs::ClientServerRemote;
use crate::prelude::*;
use std::net::ToSocketAddrs;
use uuid::Uuid;

/// A kernel that assists in creating and/or connecting to a group
pub mod broadcast;
/// A kernel that assists in allowing multiple possible peer-to-peer connections
pub mod peer_connection;
/// A kernel that only makes a single client-to-server connection
pub mod single_connection;

#[async_trait]
pub trait PrefabFunctions<'a, Arg: Send + 'a>: Sized + 'a {
    type UserLevelInputFunction: Send + 'a;
    /// Shared between the kernel and the on_c2s_channel_received function
    type SharedBundle: Send + 'a;

    fn get_shared_bundle(&self) -> Self::SharedBundle;

    async fn on_c2s_channel_received(
        connect_success: ConnectionSuccess,
        remote: ClientServerRemote,
        arg: Arg,
        fx: Self::UserLevelInputFunction,
        shared: Self::SharedBundle,
    ) -> Result<(), NetworkError>;

    fn construct(kernel: Box<dyn NetKernel + 'a>) -> Self;

    /// Creates a new connection with a central server entailed by the user information
    fn new_connect<T: Into<String>, P: Into<SecBuffer>>(
        username: T,
        password: P,
        arg: Arg,
        udp_mode: UdpMode,
        session_security_settings: SessionSecuritySettings,
        server_password: Option<PreSharedKey>,
        on_channel_received: Self::UserLevelInputFunction,
    ) -> Self {
        let (tx, rx) = tokio::sync::oneshot::channel();
        let server_conn_kernel = SingleClientServerConnectionKernel::new_connect(
            username,
            password,
            udp_mode,
            session_security_settings,
            server_password,
            |connect_success, remote| {
                on_channel_received_fn::<_, Self>(
                    connect_success,
                    remote,
                    rx,
                    arg,
                    on_channel_received,
                )
            },
        );

        let this = Self::construct(Box::new(server_conn_kernel));
        assert!(tx.send(this.get_shared_bundle()).is_ok());
        this
    }

    /// Crates a new connection with a central server entailed by the user information and default configuration
    fn new_connect_defaults<T: Into<String>, P: Into<SecBuffer>>(
        username: T,
        password: P,
        arg: Arg,
        on_channel_received: Self::UserLevelInputFunction,
    ) -> Self {
        Self::new_connect(
            username,
            password,
            arg,
            Default::default(),
            Default::default(),
            Default::default(),
            on_channel_received,
        )
    }

    /// First registers with a central server with the proposed credentials, and thereafter, establishes a connection with custom parameters
    #[allow(clippy::too_many_arguments)]
    fn new_register<T: Into<String>, R: Into<String>, P: Into<SecBuffer>, V: ToSocketAddrs>(
        full_name: T,
        username: R,
        password: P,
        arg: Arg,
        server_addr: V,
        udp_mode: UdpMode,
        session_security_settings: SessionSecuritySettings,
        server_password: Option<PreSharedKey>,
        on_channel_received: Self::UserLevelInputFunction,
    ) -> Result<Self, NetworkError> {
        let (tx, rx) = tokio::sync::oneshot::channel();
        let server_conn_kernel = SingleClientServerConnectionKernel::new_register(
            full_name,
            username,
            password,
            server_addr,
            udp_mode,
            session_security_settings,
            server_password,
            |connect_success, remote| {
                on_channel_received_fn::<_, Self>(
                    connect_success,
                    remote,
                    rx,
                    arg,
                    on_channel_received,
                )
            },
        )?;

        let this = Self::construct(Box::new(server_conn_kernel));
        assert!(tx.send(this.get_shared_bundle()).is_ok());
        Ok(this)
    }

    /// First registers with a central server with the proposed credentials, and thereafter, establishes a connection with default parameters
    fn new_register_defaults<
        T: Into<String>,
        R: Into<String>,
        P: Into<SecBuffer>,
        V: ToSocketAddrs,
    >(
        full_name: T,
        username: R,
        password: P,
        arg: Arg,
        server_addr: V,
        on_channel_received: Self::UserLevelInputFunction,
    ) -> Result<Self, NetworkError> {
        Self::new_register(
            full_name,
            username,
            password,
            arg,
            server_addr,
            Default::default(),
            Default::default(),
            Default::default(),
            on_channel_received,
        )
    }

    /// Creates a new authless connection with custom arguments
    fn new_authless<V: ToSocketAddrs>(
        uuid: Uuid,
        server_addr: V,
        arg: Arg,
        udp_mode: UdpMode,
        session_security_settings: SessionSecuritySettings,
        server_password: Option<PreSharedKey>,
        on_channel_received: Self::UserLevelInputFunction,
    ) -> Result<Self, NetworkError> {
        let (tx, rx) = tokio::sync::oneshot::channel();
        let server_conn_kernel = SingleClientServerConnectionKernel::new_authless(
            uuid,
            server_addr,
            udp_mode,
            session_security_settings,
            server_password,
            |connect_success, remote| {
                on_channel_received_fn::<_, Self>(
                    connect_success,
                    remote,
                    rx,
                    arg,
                    on_channel_received,
                )
            },
        )?;

        let this = Self::construct(Box::new(server_conn_kernel));
        assert!(tx.send(this.get_shared_bundle()).is_ok());
        Ok(this)
    }

    /// Creates a new authless connection with default arguments
    fn new_authless_defaults<V: ToSocketAddrs>(
        uuid: Uuid,
        server_addr: V,
        arg: Arg,
        on_channel_received: Self::UserLevelInputFunction,
    ) -> Result<Self, NetworkError> {
        Self::new_authless(
            uuid,
            server_addr,
            arg,
            Default::default(),
            Default::default(),
            Default::default(),
            on_channel_received,
        )
    }
}

async fn on_channel_received_fn<'a, Arg: Send + 'a, T: PrefabFunctions<'a, Arg>>(
    connect_success: ConnectionSuccess,
    remote: ClientServerRemote,
    rx_bundle: tokio::sync::oneshot::Receiver<T::SharedBundle>,
    arg: Arg,
    on_channel_received: T::UserLevelInputFunction,
) -> Result<(), NetworkError> {
    let shared = rx_bundle
        .await
        .map_err(|err| NetworkError::Generic(err.to_string()))?;
    T::on_c2s_channel_received(connect_success, remote, arg, on_channel_received, shared).await
}