fly_ruler_proto_core 0.2.2

Protobuf UDP runtime and time-series state kernel for aerospace simulation
Documentation
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
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
use std::net::SocketAddr;
use std::time::Duration;

use tokio::net::UdpSocket;
use tokio::sync::{mpsc, watch};
use tokio::task::JoinHandle;
use tracing::{debug, error, info, warn};
use uuid::Uuid;

use crate::logging::init_logging;
use crate::pb;
use crate::utils::now_secs;
use crate::LoggingConfig;
use crate::PROTOCOL_VERSION;

use super::TransportError;

/// Low-level UDP client for protobuf transport.
pub struct Client {
    socket: UdpSocket,
    remote_addr: SocketAddr,
}

impl Client {
    fn make_request(command: pb::request_command::Kind, timestamp: Option<f64>) -> pb::Message {
        pb::Message {
            envelope: Some(pb::message::Envelope::Request(pb::Request {
                id: None,
                timestamp: timestamp.unwrap_or_else(now_secs),
                command: Some(pb::RequestCommand {
                    kind: Some(command),
                }),
            })),
        }
    }

    fn build_handshake_message(client_uuid: pb::Uuid) -> pb::Message {
        Self::make_request(
            pb::request_command::Kind::Handshake(pb::Handshake {
                version: PROTOCOL_VERSION.to_string(),
                client_uuid: Some(client_uuid),
            }),
            None,
        )
    }

    fn build_heartbeat_message(seq_num: u64, client_uuid: pb::Uuid) -> pb::Message {
        Self::make_request(
            pb::request_command::Kind::Heartbeat(pb::Heartbeat {
                seq_num,
                client_uuid: Some(client_uuid),
            }),
            None,
        )
    }

    fn build_spawn_message(
        aircraft_uuid: pb::Uuid,
        aircraft_name: String,
        toml_config: String,
        initial_state: pb::AircraftState,
    ) -> pb::Message {
        Self::make_request(
            pb::request_command::Kind::AircraftEvent(pb::AircraftEvent {
                aircraft_id: Some(aircraft_uuid),
                info: Some(pb::AircraftCommandInfo {
                    kind: Some(pb::aircraft_command_info::Kind::Spawn(
                        pb::AircraftSpawnInfo {
                            name: aircraft_name,
                            toml_config,
                            initial_state: Some(initial_state),
                        },
                    )),
                }),
            }),
            None,
        )
    }

    fn build_state_update_message(
        aircraft_uuid: pb::Uuid,
        state: pb::AircraftState,
        timestamp: Option<f64>,
    ) -> pb::Message {
        Self::make_request(
            pb::request_command::Kind::AircraftEvent(pb::AircraftEvent {
                aircraft_id: Some(aircraft_uuid),
                info: Some(pb::AircraftCommandInfo {
                    kind: Some(pb::aircraft_command_info::Kind::StateUpdate(state)),
                }),
            }),
            timestamp,
        )
    }

    fn build_custom_event_message(
        aircraft_uuid: pb::Uuid,
        event_name: String,
        timestamp: Option<f64>,
    ) -> pb::Message {
        Self::make_request(
            pb::request_command::Kind::AircraftEvent(pb::AircraftEvent {
                aircraft_id: Some(aircraft_uuid),
                info: Some(pb::AircraftCommandInfo {
                    kind: Some(pb::aircraft_command_info::Kind::CustomEvent(event_name)),
                }),
            }),
            timestamp,
        )
    }

    fn build_despawn_message(
        aircraft_uuid: pb::Uuid,
        reason: Option<String>,
        timestamp: Option<f64>,
    ) -> pb::Message {
        Self::make_request(
            pb::request_command::Kind::AircraftEvent(pb::AircraftEvent {
                aircraft_id: Some(aircraft_uuid),
                info: Some(pb::AircraftCommandInfo {
                    kind: Some(pb::aircraft_command_info::Kind::Despawn(pb::DespawnInfo {
                        reason,
                    })),
                }),
            }),
            timestamp,
        )
    }

    /// Connect to a remote endpoint over UDP.
    pub async fn connect(addr: &str, config: &LoggingConfig) -> Result<Self, TransportError> {
        init_logging(config);
        let remote_addr = addr
            .parse::<SocketAddr>()
            .map_err(|e| TransportError::InvalidMessage(format!("invalid socket addr: {e}")))?;
        let socket = UdpSocket::bind("0.0.0.0:0").await?;
        socket.connect(remote_addr).await?;
        info!(target: "fly_ruler_proto_core.transport", remote_addr = %remote_addr, "udp connection established");
        Ok(Self {
            socket,
            remote_addr,
        })
    }

    /// Send one protobuf message.
    pub async fn send(&mut self, msg: pb::Message) -> Result<(), TransportError> {
        let payload = prost::Message::encode_to_vec(&msg);
        self.socket.send(&payload).await?;
        debug!(target: "fly_ruler_proto_core.transport", remote_addr = %self.remote_addr, bytes = payload.len(), "datagram sent");
        Ok(())
    }

    /// Receive one protobuf message.
    pub async fn recv(&mut self) -> Result<Option<pb::Message>, TransportError> {
        let mut buf = vec![0_u8; 64 * 1024];
        let n = self.socket.recv(&mut buf).await?;
        if n == 0 {
            return Ok(None);
        }
        let msg = prost::Message::decode(&buf[..n])?;
        debug!(target: "fly_ruler_proto_core.transport", remote_addr = %self.remote_addr, bytes = n, "datagram received");
        Ok(Some(msg))
    }

    /// Get remote address.
    pub fn remote_addr(&self) -> SocketAddr {
        self.remote_addr
    }

    /// Close connection.
    pub async fn close(&mut self) -> Result<(), TransportError> {
        info!(target: "fly_ruler_proto_core.transport", remote_addr = %self.remote_addr, "udp connection closed");
        Ok(())
    }
}

/// Outbound message or control signal for the sender task.
enum Outbound {
    /// Send a protobuf message to the remote endpoint.
    Send(Box<pb::Message>),
    /// Stop the sender task.
    Shutdown,
}

/// Operations queued by user-facing methods and processed by the operation task.
enum Operation {
    /// Update the aircraft state.
    UpdateState {
        /// New aircraft state.
        state: Box<pb::AircraftState>,
        /// Optional explicit timestamp; `None` uses the current time.
        timestamp: Option<f64>,
    },
    /// Create a custom event.
    CreateEvent {
        /// Event name.
        event_name: String,
        /// Optional explicit timestamp.
        timestamp: Option<f64>,
    },
    /// Despawn the aircraft.
    Despawn {
        /// Optional reason string.
        reason: Option<String>,
        /// Optional explicit timestamp.
        timestamp: Option<f64>,
    },
    /// Stop the operation task.
    Stop,
}

fn uuid_to_pb(u: Uuid) -> pb::Uuid {
    pb::Uuid {
        value: u.as_bytes().to_vec(),
    }
}

/// High-level aircraft lifecycle client.
///
/// One instance represents one aircraft and manages:
/// - handshake + spawn bootstrap
/// - operation queue (update/event/despawn)
/// - heartbeat background task
pub struct AircraftClient {
    addr: String,
    client_uuid: Uuid,
    aircraft_uuid: Uuid,
    op_tx: Option<mpsc::UnboundedSender<Operation>>,
    heartbeat_stop_tx: Option<watch::Sender<bool>>,
    sender_handle: Option<JoinHandle<()>>,
    operation_handle: Option<JoinHandle<()>>,
    heartbeat_handle: Option<JoinHandle<()>>,
    closed: bool,
    despawned: bool,
}

impl AircraftClient {
    /// Connect to a remote server and start the aircraft lifecycle.
    ///
    /// This sends a `Handshake` and `Spawn` message automatically.
    pub async fn connect(
        addr: &str,
        logging_config: &LoggingConfig,
        aircraft_name: String,
        initial_state: pb::AircraftState,
        toml_config: String,
        heartbeat_interval_secs: f64,
    ) -> Result<Self, TransportError> {
        let client_uuid = Uuid::new_v4();
        let aircraft_uuid = Uuid::new_v4();
        let client_uuid_for_handshake = client_uuid;
        let client_uuid_for_heartbeat = client_uuid;
        let aircraft_uuid_for_ops = aircraft_uuid;

        info!(
            target: "fly_ruler_proto_core.transport",
            addr = addr,
            client_uuid = %client_uuid,
            aircraft_uuid = %aircraft_uuid,
            "starting aircraft lifecycle client"
        );

        let rust_client = Client::connect(addr, logging_config).await?;

        let (out_tx, mut out_rx) = mpsc::unbounded_channel::<Outbound>();
        let (op_tx, mut op_rx) = mpsc::unbounded_channel::<Operation>();
        let (heartbeat_stop_tx, heartbeat_stop_rx) = watch::channel(false);

        let sender_handle = tokio::spawn(async move {
            let mut client = rust_client;
            while let Some(outbound) = out_rx.recv().await {
                match outbound {
                    Outbound::Send(msg) => {
                        if let Err(e) = client.send(*msg).await {
                            error!(target: "fly_ruler_proto_core.transport", error = %e, "client send failed");
                            break;
                        }
                    }
                    Outbound::Shutdown => {
                        info!(target: "fly_ruler_proto_core.transport", "client sender received shutdown");
                        break;
                    }
                }
            }
            if let Err(e) = client.close().await {
                warn!(target: "fly_ruler_proto_core.transport", error = %e, "client close returned error");
            }
            info!(target: "fly_ruler_proto_core.transport", "client sender task exited");
        });

        send_outbound(
            &out_tx,
            Outbound::Send(Box::new(Client::build_handshake_message(uuid_to_pb(
                client_uuid_for_handshake,
            )))),
            "handshake",
        );

        let op_out_tx = out_tx.clone();
        let operation_handle = tokio::spawn(async move {
            send_outbound(
                &op_out_tx,
                Outbound::Send(Box::new(Client::build_spawn_message(
                    uuid_to_pb(aircraft_uuid_for_ops),
                    aircraft_name,
                    toml_config,
                    initial_state,
                ))),
                "spawn",
            );

            while let Some(op) = op_rx.recv().await {
                match op {
                    Operation::UpdateState { state, timestamp } => {
                        send_outbound(
                            &op_out_tx,
                            Outbound::Send(Box::new(Client::build_state_update_message(
                                uuid_to_pb(aircraft_uuid_for_ops),
                                *state,
                                timestamp,
                            ))),
                            "state_update",
                        );
                    }
                    Operation::CreateEvent {
                        event_name,
                        timestamp,
                    } => {
                        send_outbound(
                            &op_out_tx,
                            Outbound::Send(Box::new(Client::build_custom_event_message(
                                uuid_to_pb(aircraft_uuid_for_ops),
                                event_name,
                                timestamp,
                            ))),
                            "custom_event",
                        );
                    }
                    Operation::Despawn { reason, timestamp } => {
                        send_outbound(
                            &op_out_tx,
                            Outbound::Send(Box::new(Client::build_despawn_message(
                                uuid_to_pb(aircraft_uuid_for_ops),
                                reason,
                                timestamp,
                            ))),
                            "despawn",
                        );
                    }
                    Operation::Stop => {
                        send_outbound(&op_out_tx, Outbound::Shutdown, "shutdown");
                        break;
                    }
                }
            }
            info!(target: "fly_ruler_proto_core.transport", "client operation task exited");
        });

        let hb_out_tx = out_tx;
        let heartbeat_handle = tokio::spawn(async move {
            let interval = Duration::from_secs_f64(heartbeat_interval_secs.max(0.1));
            let mut ticker = tokio::time::interval(interval);
            let mut stop_rx = heartbeat_stop_rx;
            let mut seq_num: u64 = 0;

            loop {
                tokio::select! {
                    _ = ticker.tick() => {
                        if *stop_rx.borrow() {
                            break;
                        }
                        seq_num = seq_num.saturating_add(1);
                        send_outbound(
                            &hb_out_tx,
                            Outbound::Send(Box::new(Client::build_heartbeat_message(
                                seq_num,
                                uuid_to_pb(client_uuid_for_heartbeat),
                            ))),
                            "heartbeat",
                        );
                        debug!(target: "fly_ruler_proto_core.transport", seq_num, "client heartbeat queued");
                    }
                    changed = stop_rx.changed() => {
                        if changed.is_err() || *stop_rx.borrow() {
                            break;
                        }
                    }
                }
            }
            info!(target: "fly_ruler_proto_core.transport", "client heartbeat task exited");
        });

        Ok(Self {
            addr: addr.to_string(),
            client_uuid,
            aircraft_uuid,
            op_tx: Some(op_tx),
            heartbeat_stop_tx: Some(heartbeat_stop_tx),
            sender_handle: Some(sender_handle),
            operation_handle: Some(operation_handle),
            heartbeat_handle: Some(heartbeat_handle),
            closed: false,
            despawned: false,
        })
    }

    /// Return the client UUID as a string.
    pub fn client_uuid(&self) -> String {
        self.client_uuid.to_string()
    }

    /// Return the aircraft UUID as a string.
    pub fn aircraft_uuid(&self) -> String {
        self.aircraft_uuid.to_string()
    }

    /// Enqueue a state update for the aircraft.
    pub fn update_state(
        &self,
        state: pb::AircraftState,
        timestamp: Option<f64>,
    ) -> Result<(), TransportError> {
        self.ensure_open()?;
        self.send_operation(Operation::UpdateState {
            state: Box::new(state),
            timestamp,
        })
    }

    /// Enqueue a custom event for the aircraft.
    pub fn create_event(
        &self,
        event_name: String,
        timestamp: Option<f64>,
    ) -> Result<(), TransportError> {
        self.ensure_open()?;
        self.send_operation(Operation::CreateEvent {
            event_name,
            timestamp,
        })
    }

    /// Enqueue a despawn command for the aircraft.
    pub fn despawn(
        &mut self,
        reason: Option<String>,
        timestamp: Option<f64>,
    ) -> Result<(), TransportError> {
        self.ensure_open()?;
        if self.despawned {
            return Ok(());
        }
        self.send_operation(Operation::Despawn { reason, timestamp })?;
        self.despawned = true;
        Ok(())
    }

    /// Close the client, sending a despawn if needed and stopping background tasks.
    pub async fn close(&mut self) -> Result<(), TransportError> {
        if self.closed {
            return Ok(());
        }

        info!(
            target: "fly_ruler_proto_core.transport",
            addr = self.addr,
            client_uuid = %self.client_uuid,
            aircraft_uuid = %self.aircraft_uuid,
            "closing aircraft lifecycle client"
        );

        if !self.despawned {
            if let Err(e) = self.send_operation(Operation::Despawn {
                reason: Some("client_close".to_string()),
                timestamp: None,
            }) {
                warn!(target: "fly_ruler_proto_core.transport", error = %e, "failed to enqueue close-despawn");
            }
            self.despawned = true;
        }

        if let Some(stop_tx) = self.heartbeat_stop_tx.take() {
            if stop_tx.send(true).is_err() {
                warn!(target: "fly_ruler_proto_core.transport", "heartbeat stop channel already closed");
            }
        }

        if let Some(op_tx) = self.op_tx.as_ref() {
            if op_tx.send(Operation::Stop).is_err() {
                warn!(target: "fly_ruler_proto_core.transport", "operation stop channel already closed");
            }
        }
        self.op_tx = None;

        if let Some(handle) = self.heartbeat_handle.take() {
            let _ = handle.await;
        }
        if let Some(handle) = self.operation_handle.take() {
            let _ = handle.await;
        }
        if let Some(handle) = self.sender_handle.take() {
            let _ = handle.await;
        }

        self.closed = true;
        Ok(())
    }

    fn ensure_open(&self) -> Result<(), TransportError> {
        if self.closed {
            return Err(TransportError::ClientChannelClosed("client is closed"));
        }
        Ok(())
    }

    fn send_operation(&self, op: Operation) -> Result<(), TransportError> {
        let tx = self
            .op_tx
            .as_ref()
            .ok_or(TransportError::ClientChannelClosed(
                "operation queue is closed",
            ))?;

        tx.send(op)
            .map_err(|_| TransportError::ClientChannelClosed("failed to enqueue operation"))
    }
}

/// Send an outbound message, logging a warning if the channel has closed.
fn send_outbound(tx: &mpsc::UnboundedSender<Outbound>, outbound: Outbound, kind: &str) {
    if let Err(e) = tx.send(outbound) {
        warn!(
            target: "fly_ruler_proto_core.transport",
            kind = kind,
            error = %e,
            "failed to enqueue outbound message; sender task may have exited"
        );
    }
}