dora-coordinator 1.0.0

`dora` goal is to be a low latency, composable, and distributed data flow.
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
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
use crate::{Event, control::ControlEvent};
use axum::extract::ws::{Message, WebSocket};
use dora_message::{
    TOPIC_DATA_PROTOCOL_VERSION,
    cli_to_coordinator::{ControlRequest, check_cli_version},
    common::Timestamped,
    coordinator_to_cli::ControlRequestReply,
    current_crate_version,
    daemon_to_daemon::InterDaemonEvent,
    metadata::{FRAMING, FRAMING_ARROW_IPC, Metadata, MetadataParameters, Parameter},
    ws_protocol::{WsRequest, WsResponse},
};
use futures::{SinkExt, StreamExt};
use std::sync::Arc;
use tokio::sync::{mpsc, oneshot};
use uuid::Uuid;

/// Maximum topics allowed in a single TopicSubscribe request.
const MAX_TOPICS_PER_SUBSCRIBE: usize = 64;

/// Whether a client's advertised binary-frame encoding is one we can serve.
///
/// `Err` carries the rejection message. Split out from the request handler so
/// the decision is testable without a live WebSocket — the handler itself only
/// runs inside `handle_control_ws`.
fn check_topic_protocol(client_version: Option<u16>) -> Result<(), String> {
    if client_version == Some(TOPIC_DATA_PROTOCOL_VERSION) {
        Ok(())
    } else {
        Err(dora_message::topic_protocol_mismatch_message(
            "client",
            client_version,
        ))
    }
}

/// Maximum concurrent topic subscriptions per WebSocket connection.
const MAX_SUBSCRIPTIONS_PER_CONNECTION: usize = 16;

#[derive(Clone)]
struct ActiveTopicSubscription {
    subscription_id: Uuid,
    dataflow_id: Uuid,
    topics: Vec<(dora_message::id::NodeId, dora_message::id::DataId)>,
}

/// Serialize a `WsResponse` and send it over the WS connection.
/// Returns `Err` if the WS send fails (connection closed).
async fn send_ws_response(
    ws_tx: &mut futures::stream::SplitSink<WebSocket, Message>,
    resp: &WsResponse,
) -> Result<(), ()> {
    let json = match serde_json::to_string(resp) {
        Ok(s) => s,
        Err(e) => {
            tracing::error!("failed to serialize WsResponse: {e}");
            return Err(());
        }
    };
    ws_tx.send(Message::Text(json.into())).await.map_err(|_| ())
}

/// Format a `WsResponse`-shaped JSON envelope using `serde_json::to_string`.
///
/// Used instead of `send_ws_response` where the reply is already a concrete
/// type: it serializes straight into the envelope rather than materializing an
/// intermediate `serde_json::Value` for the `WsResponse::result` field.
fn format_response_json(id: Uuid, reply: &impl serde::Serialize) -> String {
    match serde_json::to_string(reply) {
        Ok(result_json) => {
            format!(r#"{{"id":"{id}","result":{result_json}}}"#)
        }
        Err(e) => {
            let err_json = serde_json::to_string(&format!("{e}"))
                .unwrap_or_else(|_| "\"serialization error\"".to_string());
            format!(r#"{{"id":"{id}","error":{err_json}}}"#)
        }
    }
}

/// Handle a single CLI WebSocket connection on `/api/control`.
///
/// For normal requests: deserialize ControlRequest from WsRequest.params,
/// send ControlEvent to coordinator via `event_tx`, await oneshot reply, send WsResponse.
///
/// For LogSubscribe/BuildLogSubscribe: ack via WsResponse, then push WsEvent{event:"log"}
/// on the same connection.
///
/// For TopicSubscribe: register a daemon-backed debug stream via coordinator
/// and forward binary frames with `subscription_id ++ payload` format.
pub(crate) async fn handle_control_ws(
    socket: WebSocket,
    event_tx: mpsc::Sender<Event>,
    clock: Arc<dora_core::uhlc::HLC>,
) {
    let (mut ws_tx, mut ws_rx) = socket.split();
    // Channel for log events to push back on same WS connection
    let (log_tx, mut log_rx) = mpsc::channel::<String>(64);
    // Channel for binary topic data frames
    let (binary_tx, mut binary_rx) = mpsc::channel::<crate::topic_subscriber::TopicFrame>(64);
    let mut topic_subscriptions: Vec<ActiveTopicSubscription> = Vec::new();
    let mut publish_session: Option<zenoh::Session> = None;

    loop {
        tokio::select! {
            // Incoming WS messages from CLI
            msg = ws_rx.next() => {
                let Some(msg) = msg else { break };
                let msg = match msg {
                    Ok(Message::Text(text)) => text,
                    Ok(Message::Close(_)) => break,
                    Ok(Message::Ping(data)) => {
                        let _ = ws_tx.send(Message::Pong(data)).await;
                        continue;
                    }
                    Ok(_) => continue,
                    Err(e) => {
                        tracing::trace!("WS control connection error: {e}");
                        break;
                    }
                };

                let req: WsRequest = match serde_json::from_str(&msg) {
                    Ok(r) => r,
                    Err(e) => {
                        let resp = WsResponse::err(Uuid::nil(), format!("invalid request: {e}"));
                        let _ = send_ws_response(&mut ws_tx, &resp).await;
                        continue;
                    }
                };

                let control_request: ControlRequest = match serde_json::from_value(req.params.clone()) {
                    Ok(r) => r,
                    Err(e) => {
                        let resp = WsResponse::err(req.id, format!("invalid params: {e}"));
                        let _ = send_ws_response(&mut ws_tx, &resp).await;
                        continue;
                    }
                };

                // Handle Hello / LogSubscribe / BuildLogSubscribe / TopicSubscribe / TopicUnsubscribe specially
                match &control_request {
                    ControlRequest::Hello { dora_version } => {
                        // Protocol version handshake — reply directly from
                        // this loop rather than forwarding to the event
                        // loop, so mismatched CLIs fail fast before any
                        // stateful interaction (dora-rs/adora#151).
                        let resp = match check_cli_version(dora_version) {
                            Ok(()) => {
                                let reply = ControlRequestReply::HelloOk {
                                    dora_version: current_crate_version(),
                                };
                                match serde_json::to_value(&reply) {
                                    Ok(val) => WsResponse::ok(req.id, val),
                                    Err(e) => WsResponse::err(
                                        req.id,
                                        format!("failed to serialize HelloOk: {e}"),
                                    ),
                                }
                            }
                            Err(msg) => {
                                tracing::warn!("rejecting CLI with {msg}");
                                WsResponse::err(req.id, msg)
                            }
                        };
                        let _ = send_ws_response(&mut ws_tx, &resp).await;
                        continue;
                    }
                    ControlRequest::LogSubscribe { dataflow_id, level } => {
                        let (found_tx, found_rx) = oneshot::channel();
                        let _ = event_tx.send(Event::Control(ControlEvent::LogSubscribe {
                            dataflow_id: *dataflow_id,
                            level: *level,
                            sender: log_tx.clone(),
                            found_tx,
                        })).await;

                        let found = found_rx.await.unwrap_or(false);
                        let resp = if found {
                            WsResponse::ok(req.id, serde_json::json!({"subscribed": true}))
                        } else {
                            WsResponse::err(req.id, format!("no running dataflow with id {dataflow_id}"))
                        };
                        let _ = send_ws_response(&mut ws_tx, &resp).await;
                        continue;
                    }
                    ControlRequest::BuildLogSubscribe { build_id, level } => {
                        let (found_tx, found_rx) = oneshot::channel();
                        let _ = event_tx.send(Event::Control(ControlEvent::BuildLogSubscribe {
                            build_id: *build_id,
                            level: *level,
                            sender: log_tx.clone(),
                            found_tx,
                        })).await;

                        let found = found_rx.await.unwrap_or(false);
                        let resp = if found {
                            WsResponse::ok(req.id, serde_json::json!({"subscribed": true}))
                        } else {
                            WsResponse::err(req.id, format!("no running build with id {build_id}"))
                        };
                        let _ = send_ws_response(&mut ws_tx, &resp).await;
                        continue;
                    }
                    ControlRequest::TopicSubscribe {
                        dataflow_id,
                        topics,
                        protocol_version,
                    } => {
                        // Reject before doing any work: the frames this
                        // subscription would produce are positionally encoded,
                        // so a client on the other encoding misparses them
                        // instead of erroring (dora-rs/dora#3153).
                        if let Err(msg) = check_topic_protocol(*protocol_version) {
                            let resp = WsResponse::err(req.id, msg);
                            let _ = send_ws_response(&mut ws_tx, &resp).await;
                            continue;
                        }

                        let mut normalized_topics = topics.clone();
                        normalized_topics.sort();

                        if let Some(existing) = topic_subscriptions.iter().find(|subscription| {
                            subscription.dataflow_id == *dataflow_id
                                && subscription.topics == normalized_topics
                        }) {
                            let reply = ControlRequestReply::TopicSubscribed {
                                subscription_id: existing.subscription_id,
                                protocol_version: Some(TOPIC_DATA_PROTOCOL_VERSION),
                            };
                            let resp_json = format_response_json(req.id, &reply);
                            if ws_tx.send(Message::Text(resp_json.into())).await.is_err() {
                                break;
                            }
                            continue;
                        }

                        // Validate topic count
                        if topics.len() > MAX_TOPICS_PER_SUBSCRIBE {
                            let resp = WsResponse::err(
                                req.id,
                                format!(
                                    "too many topics ({}, max {})",
                                    topics.len(),
                                    MAX_TOPICS_PER_SUBSCRIBE
                                ),
                            );
                            let _ = send_ws_response(&mut ws_tx, &resp).await;
                            continue;
                        }

                        // Validate subscription count
                        if topic_subscriptions.len() >= MAX_SUBSCRIPTIONS_PER_CONNECTION {
                            let resp = WsResponse::err(
                                req.id,
                                format!(
                                    "too many active subscriptions ({}, max {})",
                                    topic_subscriptions.len(),
                                    MAX_SUBSCRIPTIONS_PER_CONNECTION
                                ),
                            );
                            let _ = send_ws_response(&mut ws_tx, &resp).await;
                            continue;
                        }

                        let (done_tx, done_rx) = oneshot::channel();
                        let _ = event_tx.send(Event::Control(ControlEvent::TopicSubscribe {
                            dataflow_id: *dataflow_id,
                            topics: topics.clone(),
                            sender: binary_tx.clone(),
                            done_tx,
                        })).await;

                        let subscription_id = match done_rx.await {
                            Ok(Ok(subscription_id)) => {
                                topic_subscriptions.push(ActiveTopicSubscription {
                                    subscription_id,
                                    dataflow_id: *dataflow_id,
                                    topics: normalized_topics,
                                });
                                subscription_id
                            }
                            Ok(Err(err)) => {
                                let resp = WsResponse::err(req.id, err);
                                let _ = send_ws_response(&mut ws_tx, &resp).await;
                                continue;
                            }
                            Err(_) => {
                                let resp = WsResponse::err(
                                    req.id,
                                    "topic subscribe request dropped before completion".to_string(),
                                );
                                let _ = send_ws_response(&mut ws_tx, &resp).await;
                                continue;
                            }
                        };

                        let reply = ControlRequestReply::TopicSubscribed {
                            subscription_id,
                            protocol_version: Some(TOPIC_DATA_PROTOCOL_VERSION),
                        };
                        let resp_json = format_response_json(req.id, &reply);
                        if ws_tx.send(Message::Text(resp_json.into())).await.is_err() {
                            break;
                        }
                        continue;
                    }
                    ControlRequest::TopicUnsubscribe { subscription_id } => {
                        topic_subscriptions
                            .retain(|active| active.subscription_id != *subscription_id);
                        let (done_tx, done_rx) = oneshot::channel();
                        let _ = event_tx
                            .send(Event::Control(ControlEvent::TopicUnsubscribe {
                                subscription_id: *subscription_id,
                                done_tx,
                            }))
                            .await;
                        let _ = done_rx.await;
                        let resp = WsResponse::ok(
                            req.id,
                            serde_json::json!({"unsubscribed": true, "subscription_id": subscription_id}),
                        );
                        let _ = send_ws_response(&mut ws_tx, &resp).await;
                        continue;
                    }
                    ControlRequest::TopicPublish {
                        dataflow_id,
                        node_id,
                        output_id,
                        data_json,
                    } => {
                        // Validate that the dataflow has debug publishing enabled
                        let (found_tx, found_rx) = oneshot::channel();
                        let _ = event_tx.send(Event::Control(ControlEvent::TopicCheck {
                            dataflow_id: *dataflow_id,
                            topics: vec![(node_id.clone(), output_id.clone())],
                            found_tx,
                        })).await;
                        let found = found_rx.await.unwrap_or(false);
                        if !found {
                            let resp = WsResponse::err(
                                req.id,
                                format!(
                                    "dataflow {dataflow_id} not found, output unavailable, or topic publish requires `debug.enable_debug_inspection: true`"
                                ),
                            );
                            let _ = send_ws_response(&mut ws_tx, &resp).await;
                            continue;
                        }

                        let resp = match publish_topic(
                            *dataflow_id,
                            node_id,
                            output_id,
                            data_json,
                            &clock,
                            &mut publish_session,
                        )
                        .await
                        {
                            Ok(()) => {
                                let reply = ControlRequestReply::TopicPublished;
                                format_response_json(req.id, &reply)
                            }
                            Err(e) => {
                                let reply = ControlRequestReply::Error(e);
                                format_response_json(req.id, &reply)
                            }
                        };
                        if ws_tx.send(Message::Text(resp.into())).await.is_err() {
                            break;
                        }
                        continue;
                    }
                    _ => {}
                }

                // Normal request-reply
                let (reply_tx, reply_rx) = oneshot::channel();
                let event = ControlEvent::IncomingRequest {
                    request: Box::new(control_request),
                    reply_sender: reply_tx,
                };

                if event_tx.send(Event::Control(event)).await.is_err() {
                    let resp = WsResponse::err(req.id, "coordinator stopped".to_string());
                    let _ = send_ws_response(&mut ws_tx, &resp).await;
                    break;
                }

                let reply = match reply_rx.await {
                    Ok(Ok(reply)) => reply,
                    Ok(Err(err)) => {
                        tracing::error!("control request failed: {err:?}");
                        // Send only the root error message to the client, not the
                        // full internal chain (which may leak implementation details).
                        let root = err.root_cause().to_string();
                        ControlRequestReply::Error(root)
                    }
                    Err(_) => ControlRequestReply::Error(
                        "coordinator dropped the request without a reply \
                         (it may have shut down or the dataflow exited unexpectedly)"
                            .to_string(),
                    ),
                };

                let stop = matches!(reply, ControlRequestReply::CoordinatorStopped);

                let resp_json = format_response_json(req.id, &reply);
                if ws_tx.send(Message::Text(resp_json.into())).await.is_err() || stop {
                    break;
                }
            }
            // Log events to push to CLI
            Some(log_json) = log_rx.recv() => {
                if ws_tx.send(Message::Text(log_json.into())).await.is_err() {
                    break;
                }
            }
            // Binary topic data to push to CLI
            Some(frame) = binary_rx.recv() => {
                let mut data = Vec::with_capacity(16 + frame.payload.len());
                data.extend_from_slice(&frame.subscription_id.into_bytes());
                data.extend_from_slice(&frame.payload);
                if ws_tx.send(Message::Binary(data.into())).await.is_err() {
                    break;
                }
            }
        }
    }

    for subscription_id in topic_subscriptions
        .into_iter()
        .map(|active| active.subscription_id)
    {
        let (done_tx, done_rx) = oneshot::channel();
        let _ = event_tx
            .send(Event::Control(ControlEvent::TopicUnsubscribe {
                subscription_id,
                done_tx,
            }))
            .await;
        let _ = done_rx.await;
    }
}

/// Publish JSON data as a serialized `InterDaemonEvent::Output`.
///
/// The JSON string is stored as raw UTF-8 bytes in a UInt8 Arrow array.
async fn publish_topic(
    dataflow_id: Uuid,
    node_id: &dora_message::id::NodeId,
    output_id: &dora_message::id::DataId,
    data_json: &str,
    clock: &dora_core::uhlc::HLC,
    session: &mut Option<zenoh::Session>,
) -> Result<(), String> {
    let topic = dora_core::topics::zenoh_daemon_control_topic(dataflow_id, node_id, output_id);

    // Encode the JSON (as a UInt8 array) into a self-describing Arrow IPC
    // stream — the framing every data-plane payload now uses, so the receiving
    // node's IPC decode reconstructs it.
    let array = arrow::array::UInt8Array::from(data_json.as_bytes().to_vec());
    let ipc_bytes = encode_topic_ipc(&array)
        .map_err(|e| format!("failed to Arrow-IPC-encode topic data: {e}"))?;
    let data = dora_message::aligned_vec::AVec::from_slice(128, &ipc_bytes);

    let mut params = MetadataParameters::new();
    params.insert(
        FRAMING.to_string(),
        Parameter::String(FRAMING_ARROW_IPC.to_string()),
    );

    let timestamp = clock.new_timestamp();
    let metadata = Metadata::from_parameters(timestamp, params);

    let event = Timestamped {
        inner: InterDaemonEvent::Output {
            dataflow_id,
            node_id: node_id.clone(),
            output_id: output_id.clone(),
            metadata,
            data: Some(data),
        },
        timestamp,
    };

    let payload = event
        .serialize()
        .map_err(|e| format!("failed to serialize event: {e}"))?;

    if session.is_none() {
        *session = Some(
            dora_core::topics::open_zenoh_session(None)
                .await
                .map_err(|e| format!("failed to open zenoh session: {e}"))?,
        );
    }

    session
        .as_mut()
        .expect("zenoh publish session initialized")
        .put(&topic, payload)
        .await
        .map_err(|e| format!("failed to publish to zenoh: {e}"))?;

    Ok(())
}

/// Encode `array` into a single-column Arrow IPC stream (column named `data`),
/// matching the framing produced by `dora_node_api::arrow_utils::encode_arrow_ipc`
/// so the node-side IPC decode reconstructs it.
fn encode_topic_ipc(array: &arrow::array::UInt8Array) -> eyre::Result<Vec<u8>> {
    use arrow::datatypes::{DataType, Field, Schema};
    use arrow::ipc::writer::StreamWriter;
    use arrow::record_batch::RecordBatch;
    use eyre::Context;
    use std::sync::Arc;

    let schema = Arc::new(Schema::new(vec![Field::new("data", DataType::UInt8, true)]));
    let batch = RecordBatch::try_new(schema.clone(), vec![Arc::new(array.clone())])
        .context("failed to create RecordBatch for topic IPC encoding")?;

    let mut buf = Vec::new();
    {
        let mut writer = StreamWriter::try_new(&mut buf, &schema)
            .context("failed to create Arrow IPC StreamWriter")?;
        writer
            .write(&batch)
            .context("failed to write RecordBatch to IPC stream")?;
        writer
            .finish()
            .context("failed to finish Arrow IPC stream")?;
    }
    Ok(buf)
}

#[cfg(test)]
mod tests {
    use super::*;

    /// The rejection has to be actionable: an operator seeing it should know
    /// which side is old without reading the source. Both arms name our
    /// version and say why a mismatch cannot simply be tolerated — binary
    /// topic frames are positionally encoded, so the wrong encoding misparses
    /// instead of erroring (dora-rs/dora#3153).
    /// The accept/reject decision itself, not just its wording: inverting or
    /// deleting the guard in the request handler must fail here.
    #[test]
    fn only_our_exact_protocol_version_is_accepted() {
        assert!(
            check_topic_protocol(Some(TOPIC_DATA_PROTOCOL_VERSION)).is_ok(),
            "our own version must be accepted"
        );
        assert!(
            check_topic_protocol(None).is_err(),
            "a pre-handshake client must be rejected, not defaulted to compatible"
        );
        for version in [0, 1, TOPIC_DATA_PROTOCOL_VERSION + 1, u16::MAX] {
            assert!(
                check_topic_protocol(Some(version)).is_err(),
                "version {version} must be rejected: binary frames are positional, \
                 so a mismatch misparses rather than failing"
            );
        }
    }

    /// The rejection must actually carry the shared explanation, not an empty
    /// or generic string — that text is what tells an operator which side is old.
    #[test]
    fn rejection_carries_the_shared_mismatch_message() {
        let err = check_topic_protocol(Some(1)).expect_err("version 1 must be rejected");
        assert_eq!(
            err,
            dora_message::topic_protocol_mismatch_message("client", Some(1)),
            "should reuse the shared message rather than a local variant"
        );
    }
}