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
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
/*!
 * # Network Select-Ok Operation
 *
 * Implements a network-aware select operation that races fallible futures across two
 * network endpoints. Similar to `futures::select`, but operates over a network connection
 * with built-in conflict resolution and error handling.
 *
 * ## Features
 * - Races fallible futures between network endpoints
 * - First endpoint to complete successfully wins
 * - Built-in conflict resolution
 * - Error handling with Result type
 * - State synchronization between nodes
 * - Network-aware relative node types
 *
 * ## Usage Example
 * ```rust
 * use netbeam::sync::operations::net_select_ok::NetSelectOk;
 * use netbeam::sync::RelativeNodeType;
 * use netbeam::sync::subscription::Subscribable;
 * use anyhow::Result;
 *
 * async fn example<S: Subscribable>(connection: &S) -> Result<()> {
 *     // Create a select-ok operation
 *     let select = NetSelectOk::new(
 *         connection,
 *         RelativeNodeType::Initiator,
 *         async { Ok::<_, anyhow::Error>(42) }
 *     );
 *
 *     // Wait for first successful completion
 *     let result = select.await?;
 *     println!("Got result: {:?}", result);
 *     Ok(())
 * }
 * ```
 *
 * ## Important Notes
 * - First successful endpoint wins
 * - Handles errors with Result type
 * - State is synchronized between nodes
 * - Includes conflict resolution
 * - Uses multiplexed connections
 *
 * ## Related Components
 * - `net_select.rs`: Basic select operation without error handling
 * - `net_try_join.rs`: Try-join operation for synchronization
 */

use crate::multiplex::MultiplexedConnKey;
use crate::reliable_conn::{ReliableOrderedStreamToTarget, ReliableOrderedStreamToTargetExt};
use crate::sync::subscription::Subscribable;
use crate::sync::subscription::SubscriptionBiStream;
use crate::sync::RelativeNodeType;
use citadel_io::tokio::sync::{Mutex, MutexGuard};
use futures::Future;
use serde::{Deserialize, Serialize};
use std::pin::Pin;
use std::task::{Context, Poll};

/// Two endpoints race to produce Ok(R). The first endpoint to produce Ok(R) wins. Includes conflict-resolution synchronization
pub struct NetSelectOk<'a, R> {
    future: Pin<Box<dyn Future<Output = Result<NetSelectOkResult<R>, anyhow::Error>> + Send + 'a>>,
}

impl<'a, R: Send + 'a> NetSelectOk<'a, R> {
    pub fn new<
        S: Subscribable<ID = K, UnderlyingConn = Conn>,
        K: MultiplexedConnKey + 'a,
        Conn: ReliableOrderedStreamToTarget + 'static,
        F: Future<Output = Result<R, anyhow::Error>> + Send + 'a,
    >(
        conn: &'a S,
        local_node_type: RelativeNodeType,
        future: F,
    ) -> Self {
        Self {
            future: Box::pin(resolve(conn, local_node_type, future)),
        }
    }
}

impl<R> Future for NetSelectOk<'_, R> {
    type Output = Result<NetSelectOkResult<R>, anyhow::Error>;

    fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
        self.future.as_mut().poll(cx)
    }
}

#[derive(Serialize, Deserialize, Debug, Clone, Eq, PartialEq)]
enum State {
    Pending,
    ObtainedValidResult,
    ResolvedLocalWon,
    ResolvedAdjacentWins,
    ResolvedBothFail,
    NonPreferredFinished,
    Error,
    // None if not finished, false if errored, true if success
    Pinging(Option<bool>),
}

impl State {
    /// assumes this is called by the receiving node, not the node that creates the state
    fn implies_remote_success(&self) -> bool {
        matches!(self, Self::ObtainedValidResult | Self::Pinging(Some(true)))
    }

    fn implies_remote_failure(&self) -> bool {
        matches!(self, Self::Error | Self::Pinging(Some(false)))
    }
}

#[derive(Debug)]
pub struct NetSelectOkResult<R> {
    /// This contains a value for the winning side, while containing no value for the losing side
    pub result: Option<R>,
    /// This is not the same as "winning". Winning just means local had preference and obtained a valid value. Other side succeeding just means their result was Ok(R)
    pub other_side_succeeded: bool,
}

impl<R> NetSelectOkResult<R> {
    /// Returns true if both sides failed
    pub fn global_failure(&self) -> bool {
        self.result.is_none() && !self.other_side_succeeded
    }
}

#[allow(clippy::if_same_then_else)]
async fn resolve<
    S: Subscribable<ID = K, UnderlyingConn = Conn>,
    K: MultiplexedConnKey,
    Conn: ReliableOrderedStreamToTarget + 'static,
    F,
    R,
>(
    conn: &S,
    local_node_type: RelativeNodeType,
    future: F,
) -> Result<NetSelectOkResult<R>, anyhow::Error>
where
    F: Future<Output = Result<R, anyhow::Error>>,
{
    let conn = &(conn.initiate_subscription().await?);
    log::trace!(target: "citadel", "NET_SELECT_OK started conv={:?} for {:?}", conn.id(), local_node_type);
    let (stopper_tx, stopper_rx) = citadel_io::tokio::sync::oneshot::channel::<()>();

    struct LocalState<R> {
        local_state: State,
        ret_value: Option<Result<R, anyhow::Error>>,
    }

    let local_state = LocalState {
        local_state: State::Pending,
        ret_value: None,
    };
    let local_state_ref = &Mutex::new(local_state);

    let has_preference = local_node_type == RelativeNodeType::Initiator;

    // the evaluator finishes before the "completer" if this goes successfully
    let evaluator = async move {
        let _stopper_tx = stopper_tx;

        async fn return_sequence<Conn: ReliableOrderedStreamToTarget, R>(
            conn: &Conn,
            new_state: State,
            mut state: MutexGuard<'_, LocalState<R>>,
            adjacent_success: bool,
        ) -> Result<(Option<Result<R, anyhow::Error>>, bool), anyhow::Error> {
            state.local_state = new_state.clone();
            conn.send_serialized(new_state.clone()).await?;
            //conn.recv_until_serialized(|s: &State| *s == State::NonPreferredFinished).await?;
            Ok((state.ret_value.take(), adjacent_success))
        }

        loop {
            log::trace!(target: "citadel", "{local_node_type:?} awaiting ...");
            let received_remote_state = conn.recv_serialized::<State>().await?;
            log::trace!(target: "citadel", "{:?} RECV'd {:?}", local_node_type, &received_remote_state);
            let mut lock = local_state_ref.lock().await;
            let local_state_info = lock.ret_value.as_ref().map(|r| r.is_ok());
            let adjacent_success = received_remote_state.implies_remote_success();
            log::trace!(target: "citadel", "[conv={:?} Node {:?} recv {:?} || Local state: {:?}", conn.id(), local_node_type, received_remote_state, lock.local_state);

            if has_preference {
                // if local has preference, we have the permission to evaluate
                // first, check to make sure local hasn't already obtained a value
                match lock.local_state {
                    State::ObtainedValidResult => {
                        // we win unconditionally, even if remote submitted a valid result
                        return return_sequence(conn, State::ResolvedLocalWon, lock, false).await;
                    }

                    State::Error => {
                        // if adjacent has a valid result, the adjacent side wins unconditionally
                        if received_remote_state.implies_remote_success() {
                            // adjacent node wins unconditionally
                            return return_sequence(
                                conn,
                                State::ResolvedAdjacentWins,
                                lock,
                                adjacent_success,
                            )
                            .await;
                        } else {
                            // if local state is errored, and, remote is errored, then conclude
                            if received_remote_state.implies_remote_failure() {
                                // both nodes failed
                                return return_sequence(conn, State::ResolvedBothFail, lock, false)
                                    .await;
                            } else {
                                // otherwise, keep pinging; we must wait for remote to finish
                                conn.send_serialized(State::Pinging(local_state_info))
                                    .await?;
                            }
                        }
                    }

                    _ => {
                        // if remote won, finish unconditionally
                        if received_remote_state.implies_remote_success() {
                            // adjacent node wins unconditionally
                            return return_sequence(
                                conn,
                                State::ResolvedAdjacentWins,
                                lock,
                                adjacent_success,
                            )
                            .await;
                        } else {
                            // local state is pending, yet, remote is either errored or not done
                            if received_remote_state.implies_remote_failure() {
                                // remote won't be able to conclude; Ping to wait for local to finish
                                conn.send_serialized(State::Pinging(local_state_info))
                                    .await?;
                                // TODO: Properly handle this
                            } else {
                                // both local and remote are pending
                                conn.send_serialized(State::Pinging(local_state_info))
                                    .await?;
                            }
                        }
                    }
                }
            } else {
                // if not, we cannot evaluate UNLESS we are being told that we resolved
                //log::trace!(target: "citadel", "RECV REMT: {:?}", received_remote_state);
                match received_remote_state {
                    State::ResolvedAdjacentWins => {
                        // remote is telling us WE won
                        lock.local_state = State::ResolvedLocalWon;
                        //conn.send_serialized(State::NonPreferredFinished).await?;
                        return Ok((lock.ret_value.take(), false));
                    }

                    State::ResolvedLocalWon => {
                        // remote is telling us THEY won
                        lock.local_state = State::ResolvedAdjacentWins;
                        //conn.send_serialized(State::NonPreferredFinished).await?;
                        return Ok((None, true));
                    }

                    State::ResolvedBothFail => {
                        // both nodes failed
                        std::mem::drop(lock);
                        //conn.send_serialized(State::NonPreferredFinished).await?;
                        return Ok((None, false));
                    }

                    _ => {
                        // even in the case of an error, OR obtained a valid result, we need to let remote determine what to do. Just ping back
                        //std::mem::drop(lock);
                        conn.send_serialized(State::Pinging(local_state_info))
                            .await?;
                    }
                }
            }
        }
    };

    // racer should never finish first
    let completer = async move {
        // both sides start this function
        let res = future.await;
        let mut local_state = local_state_ref.lock().await;

        let state = res
            .as_ref()
            .map(|_| State::ObtainedValidResult)
            .unwrap_or(State::Error);

        // we don't check the local state because the resolution would terminate this task anyways
        //log::trace!(target: "citadel", "[NetRacer] {:?} Old state: {:?} | New state: {:?}", local_node_type, &local_state.local_state, &state);

        local_state.local_state = state.clone();
        local_state.ret_value = Some(res);

        // now, send a packet to the other side
        conn.send_serialized(state).await?;
        std::mem::drop(local_state);
        //log::trace!(target: "citadel", "[NetRacer] {:?} completer done", local_node_type);

        stopper_rx.await?;
        Err(anyhow::Error::msg("Stopped before the resolver"))
    };

    citadel_io::tokio::select! {
        res0 = evaluator => {
            log::trace!(target: "citadel", "[conv={:?}] NET_SELECT_OK Ending for {:?}", conn.id(), local_node_type);
            let (ret, remote_success) = res0?;
            let local_state = local_state_ref.lock().await;
            //log::trace!(target: "citadel", "returning {:?} local state = {:?}", local_node_type, local_state.local_state);
            Ok(wrap_return(ret, local_state.local_state == State::ResolvedLocalWon, remote_success))
        },

        res1 = completer => res1
    }
}

fn wrap_return<R>(
    result: Option<Result<R, anyhow::Error>>,
    did_win: bool,
    other_side_succeeded: bool,
) -> NetSelectOkResult<R> {
    NetSelectOkResult {
        result: if did_win {
            result.and_then(|r| r.ok())
        } else {
            None
        },
        other_side_succeeded,
    }
}

#[cfg(test)]
mod tests {
    use crate::sync::network_application::NetworkApplication;
    use crate::sync::test_utils::create_streams;
    use citadel_io::tokio;
    use std::fmt::Debug;
    use std::future::Future;
    use std::time::Duration;

    #[tokio::test]
    async fn racer() {
        citadel_logging::setup_log();

        let (server_stream, client_stream) = create_streams().await;

        const COUNT: i32 = 100;

        for idx in 0..COUNT {
            log::trace!(target: "citadel", "[Meta] ERR:ERR ({idx}/{COUNT})");
            inner(
                server_stream.clone(),
                client_stream.clone(),
                dummy_function_err(),
                dummy_function_err(),
            )
            .await;
        }

        for idx in 0..COUNT {
            log::trace!(target: "citadel", "[Meta] OK:OK ({idx}/{COUNT})");
            inner(
                server_stream.clone(),
                client_stream.clone(),
                dummy_function(),
                dummy_function(),
            )
            .await;
        }

        for idx in 0..COUNT {
            log::trace!(target: "citadel", "[Meta] ERR:OK ({idx}/{COUNT})");
            inner(
                server_stream.clone(),
                client_stream.clone(),
                dummy_function_err(),
                dummy_function(),
            )
            .await;
        }

        for idx in 0..COUNT {
            log::trace!(target: "citadel", "[Meta] OK:ERR ({idx}/{COUNT})");
            inner(
                server_stream.clone(),
                client_stream.clone(),
                dummy_function(),
                dummy_function_err(),
            )
            .await;
        }
    }

    async fn inner<
        R: Send + Debug + 'static,
        F: Future<Output = Result<R, anyhow::Error>> + Send + 'static,
        Y: Future<Output = Result<R, anyhow::Error>> + Send + 'static,
    >(
        conn0: NetworkApplication,
        conn1: NetworkApplication,
        fx_1: F,
        fx_2: Y,
    ) {
        let server = async move {
            let res = conn0.net_select_ok(fx_1).await.unwrap();
            log::trace!(target: "citadel", "Server res: {res:?}");
            res
        };

        let client = async move {
            let res = conn1.net_select_ok(fx_2).await.unwrap();
            log::trace!(target: "citadel", "Client res: {res:?}");
            res
        };

        let server = citadel_io::tokio::spawn(server);
        let client = citadel_io::tokio::spawn(client);
        let (res0, res1) = citadel_io::tokio::join!(server, client);
        let (res0, res1) = (res0.unwrap(), res1.unwrap());

        if res0.result.is_some() {
            assert!(!res0.other_side_succeeded);
            assert!(res1.result.is_none());
            assert!(res1.other_side_succeeded);
        }

        if res1.result.is_some() {
            assert!(!res1.other_side_succeeded);
            assert!(res0.result.is_none());
            assert!(res0.other_side_succeeded);
        }

        if res0.result.is_none() && res1.result.is_none() {
            assert!(!res0.other_side_succeeded);
            assert!(!res1.other_side_succeeded);
            assert!(res0.global_failure());
            assert!(res1.global_failure());
        }

        log::trace!(target: "citadel", "DONE executing")
    }

    async fn dummy_function() -> Result<(), anyhow::Error> {
        citadel_io::time::sleep(Duration::from_millis(50)).await;
        Ok(())
    }

    async fn dummy_function_err() -> Result<(), anyhow::Error> {
        Err(anyhow::Error::msg("Error!!"))
    }
}