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
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
use crate::{
DaemonCommunicationWrapper, EventStream,
daemon_connection::{DaemonChannel, IntegrationTestingEvents},
integration_testing::{
TestingCommunication, TestingInput, TestingOptions, TestingOutput,
take_testing_communication,
},
};
use self::{
arrow_utils::{copy_array_into_sample, required_data_size},
control_channel::ControlChannel,
drop_stream::DropStream,
};
use aligned_vec::{AVec, ConstAlign};
use arrow::array::Array;
use colored::Colorize;
use dora_core::{
config::{DataId, NodeId, NodeRunConfig},
descriptor::Descriptor,
metadata::ArrowTypeInfoExt,
topics::{DORA_DAEMON_LOCAL_LISTEN_PORT_DEFAULT, LOCALHOST},
uhlc,
};
use dora_message::{
DataflowId,
daemon_to_node::{DaemonCommunication, DaemonReply, NodeConfig},
metadata::{ArrowTypeInfo, Metadata, MetadataParameters},
node_to_daemon::{DaemonRequest, DataMessage, DropToken, Timestamped},
};
use eyre::{WrapErr, bail};
use is_terminal::IsTerminal;
use shared_memory_extended::{Shmem, ShmemConf};
use std::sync::Mutex;
use std::{
collections::{BTreeSet, HashMap, VecDeque},
ops::{Deref, DerefMut},
path::PathBuf,
sync::Arc,
time::Duration,
};
use tokio::runtime::Handle;
#[cfg(feature = "tracing")]
use dora_tracing::{OtelGuard, TracingBuilder};
use tracing::{info, warn};
pub mod arrow_utils;
mod control_channel;
mod drop_stream;
/// The data size threshold at which we start using shared memory.
///
/// Shared memory works by sharing memory pages. This means that the smallest
/// memory region that can be shared is one memory page, which is typically
/// 4KiB.
///
/// Using shared memory for messages smaller than the page size still requires
/// sharing a full page, so we have some memory overhead. We also have some
/// performance overhead because we need to issue multiple syscalls. For small
/// messages it is faster to send them over a traditional TCP stream (or similar).
///
/// This hardcoded threshold value specifies which messages are sent through
/// shared memory. Messages that are smaller than this threshold are sent through
/// TCP.
pub const ZERO_COPY_THRESHOLD: usize = 4096;
/// Allows sending outputs and retrieving node information.
///
/// The main purpose of this struct is to send outputs via Dora. There are also functions available
/// for retrieving the node configuration.
pub struct DoraNode {
id: NodeId,
dataflow_id: DataflowId,
node_config: NodeRunConfig,
control_channel: ControlChannel,
clock: Arc<uhlc::HLC>,
sent_out_shared_memory: HashMap<DropToken, ShmemHandle>,
drop_stream: DropStream,
cache: VecDeque<ShmemHandle>,
dataflow_descriptor: serde_yaml::Result<Descriptor>,
warned_unknown_output: BTreeSet<DataId>,
interactive: bool,
}
impl DoraNode {
/// Initiate a node from environment variables set by the Dora daemon or fall back to
/// interactive mode.
///
/// This is the recommended initialization function for Dora nodes, which are spawned by
/// Dora daemon instances. The daemon will set a `DORA_NODE_CONFIG` environment variable to
/// configure the node.
///
/// When the node is started manually without the `DORA_NODE_CONFIG` environment variable set,
/// the initialization will fall back to [`init_interactive`](Self::init_interactive) if `stdin`
/// is a terminal (detected through
/// [`isatty`](https://www.man7.org/linux/man-pages/man3/isatty.3.html)).
///
/// If the `DORA_NODE_CONFIG` environment variable is not set and `DORA_TEST_WITH_INPUTS` is
/// set, the node will be initialized in integration test mode. See the
/// [integration testing](crate::integration_testing) module for details.
///
/// This function will also initialize the node in integration test mode when the
/// [`setup_integration_testing`](crate::integration_testing::setup_integration_testing)
/// function was called before. This takes precedence over all environment variables.
///
/// ```no_run
/// use dora_node_api::DoraNode;
///
/// let (mut node, mut events) = DoraNode::init_from_env().expect("Could not init node.");
/// ```
pub fn init_from_env() -> eyre::Result<(Self, EventStream)> {
Self::init_from_env_inner(true)
}
/// Initialize the node from environment variables set by the Dora daemon; error if not set.
///
/// This function behaves the same as [`init_from_env`](Self::init_from_env), but it does _not_
/// fall back to [`init_interactive`](Self::init_interactive). Instead, an error is returned
/// when the `DORA_NODE_CONFIG` environment variable is missing.
pub fn init_from_env_force() -> eyre::Result<(Self, EventStream)> {
Self::init_from_env_inner(false)
}
fn init_from_env_inner(fallback_to_interactive: bool) -> eyre::Result<(Self, EventStream)> {
if let Some(testing_comm) = take_testing_communication() {
let TestingCommunication {
input,
output,
options,
} = *testing_comm;
return Self::init_testing(input, output, options);
}
// normal execution (started by dora daemon)
match std::env::var("DORA_NODE_CONFIG") {
Ok(raw) => {
let node_config: NodeConfig =
serde_yaml::from_str(&raw).context("failed to deserialize node config")?;
return Self::init(node_config);
}
Err(std::env::VarError::NotUnicode(_)) => {
bail!("DORA_NODE_CONFIG env variable is not valid unicode")
}
Err(std::env::VarError::NotPresent) => {} // continue trying other init methods
};
// node integration test mode
match std::env::var("DORA_TEST_WITH_INPUTS") {
Ok(raw) => {
let input_file = PathBuf::from(raw);
let output_file = match std::env::var("DORA_TEST_WRITE_OUTPUTS_TO") {
Ok(raw) => PathBuf::from(raw),
Err(std::env::VarError::NotUnicode(_)) => {
bail!("DORA_TEST_WRITE_OUTPUTS_TO env variable is not valid unicode")
}
Err(std::env::VarError::NotPresent) => {
input_file.with_file_name("outputs.jsonl")
}
};
let skip_output_time_offsets =
std::env::var_os("DORA_TEST_NO_OUTPUT_TIME_OFFSET").is_some();
let input = TestingInput::FromJsonFile(input_file);
let output = TestingOutput::ToFile(output_file);
let options = TestingOptions {
skip_output_time_offsets,
};
return Self::init_testing(input, output, options);
}
Err(std::env::VarError::NotUnicode(_)) => {
bail!("DORA_TEST_WITH_INPUTS env variable is not valid unicode")
}
Err(std::env::VarError::NotPresent) => {} // continue trying other init methods
}
// interactive mode
if fallback_to_interactive && std::io::stdin().is_terminal() {
println!(
"{}",
"Starting node in interactive mode as DORA_NODE_CONFIG env variable is not set"
.green()
);
return Self::init_interactive();
}
// no run mode applicable
bail!("DORA_NODE_CONFIG env variable is not set")
}
/// Initiate a node from a dataflow id and a node id.
///
/// This initialization function should be used for [_dynamic nodes_](index.html#dynamic-nodes).
///
/// ```no_run
/// use dora_node_api::DoraNode;
/// use dora_node_api::dora_core::config::NodeId;
///
/// let (mut node, mut events) = DoraNode::init_from_node_id(NodeId::from("plot".to_string())).expect("Could not init node plot");
/// ```
///
pub fn init_from_node_id(node_id: NodeId) -> eyre::Result<(Self, EventStream)> {
// Make sure that the node is initialized outside of dora start.
let daemon_address = (LOCALHOST, DORA_DAEMON_LOCAL_LISTEN_PORT_DEFAULT).into();
let mut channel =
DaemonChannel::new_tcp(daemon_address).context("Could not connect to the daemon")?;
let clock = Arc::new(uhlc::HLC::default());
let reply = channel
.request(&Timestamped {
inner: DaemonRequest::NodeConfig { node_id },
timestamp: clock.new_timestamp(),
})
.wrap_err("failed to request node config from daemon")?;
match reply {
DaemonReply::NodeConfig {
result: Ok(node_config),
} => Self::init(node_config),
DaemonReply::NodeConfig { result: Err(error) } => {
bail!("failed to get node config from daemon: {error}")
}
_ => bail!("unexpected reply from daemon"),
}
}
/// Dynamic initialization function for nodes that are sometimes used as dynamic nodes.
///
/// This function first tries initializing the traditional way through
/// [`init_from_env`][Self::init_from_env]. If this fails, it falls back to
/// [`init_from_node_id`][Self::init_from_node_id].
pub fn init_flexible(node_id: NodeId) -> eyre::Result<(Self, EventStream)> {
if std::env::var("DORA_NODE_CONFIG").is_ok() {
info!(
"Skipping {node_id} specified within the node initialization in favor of `DORA_NODE_CONFIG` specified by `dora start`"
);
Self::init_from_env()
} else {
Self::init_from_node_id(node_id)
}
}
/// Initialize the node in a standalone mode that prompts for inputs on the terminal.
///
/// Instead of connecting to a `dora daemon`, this interactive mode prompts for node inputs
/// on the terminal. In this mode, the node is completely isolated from the dora daemon and
/// other nodes, so it cannot be part of a dataflow.
///
/// Note that this function will hang indefinitely if no input is supplied to the interactive
/// prompt. So it should be only used through a terminal.
///
/// Because of the above limitations, it is not recommended to use this function directly.
/// Use [**`init_from_env`**](Self::init_from_env) instead, which supports both normal daemon
/// connections and manual interactive runs.
///
/// ## Example
///
/// Run any node that uses `init_interactive` or [`init_from_env`](Self::init_from_env) directly
/// from a terminal. The node will then start in "interactive mode" and prompt you for the next
/// input:
///
/// ```bash
/// > cargo build -p rust-dataflow-example-node
/// > target/debug/rust-dataflow-example-node
/// hello
/// Starting node in interactive mode as DORA_NODE_CONFIG env variable is not set
/// Node asks for next input
/// ? Input ID
/// [empty input ID to stop]
/// ```
///
/// The `rust-dataflow-example-node` expects a `tick` input, so let's set the input ID to
/// `tick`. Tick messages don't have any data, so we leave the "Data" empty when prompted:
///
/// ```bash
/// Node asks for next input
/// > Input ID tick
/// > Data
/// tick 0, sending 0x943ed1be20c711a4
/// node sends output random with data: PrimitiveArray<UInt64>
/// [
/// 10682205980693303716,
/// ]
/// Node asks for next input
/// ? Input ID
/// [empty input ID to stop]
/// ```
///
/// We see that both the `stdout` output of the node and also the output messages that it sends
/// are printed to the terminal. Then we get another prompt for the next input.
///
/// If you want to send an input with data, you can either send it as text (for string data)
/// or as a JSON object (for struct, string, or array data). Other data types are not supported
/// currently.
///
/// Empty input IDs are interpreted as stop instructions:
///
/// ```bash
/// > Input ID
/// given input ID is empty -> stopping
/// Received stop
/// Node asks for next input
/// event channel was stopped -> returning empty event list
/// node reports EventStreamDropped
/// node reports closed outputs []
/// node reports OutputsDone
/// ```
///
/// In addition to the node output, we see log messages for the different events that the node
/// reports. After `OutputsDone`, the node should exit.
///
/// ### JSON data
///
/// In addition to text input, the `Data` prompt also supports JSON objects, which will be
/// converted to Apache Arrow struct arrays:
///
/// ```bash
/// Node asks for next input
/// > Input ID some_input
/// > Data { "field_1": 42, "field_2": { "inner": "foo" } }
/// ```
///
/// This JSON data is converted to the following Arrow array:
///
/// ```text
/// StructArray
/// -- validity: [valid, ]
/// [
/// -- child 0: "field_1" (Int64)
/// PrimitiveArray<Int64>
/// [42,]
/// -- child 1: "field_2" (Struct([Field { name: "inner", data_type: Utf8, nullable: true, dict_id: 0, dict_is_ordered: false, metadata: {} }]))
/// StructArray
/// -- validity: [valid,]
/// [
/// -- child 0: "inner" (Utf8)
/// StringArray
/// ["foo",]
/// ]
/// ]
/// ```
pub fn init_interactive() -> eyre::Result<(Self, EventStream)> {
#[cfg(feature = "tracing")]
{
TracingBuilder::new("node")
.with_stdout("debug", false)
.build()
.wrap_err("failed to set up tracing subscriber")?;
}
let node_config = NodeConfig {
dataflow_id: DataflowId::new_v4(),
node_id: "".parse()?,
run_config: NodeRunConfig {
inputs: Default::default(),
outputs: Default::default(),
},
daemon_communication: Some(DaemonCommunication::Interactive),
dataflow_descriptor: serde_yaml::Value::Null,
dynamic: false,
write_events_to: None,
};
let (mut node, events) = Self::init(node_config)?;
node.interactive = true;
Ok((node, events))
}
/// Initializes a node in integration test mode.
///
/// No connection to a dora daemon is made in this mode. Instead, inputs are read from the
/// specified `TestingInput`, and outputs are written to the specified `TestingOutput`.
/// Additional options for the testing mode can be specified through `TestingOptions`.
///
/// It is recommended to use this function only within test functions.
pub fn init_testing(
input: TestingInput,
output: TestingOutput,
options: TestingOptions,
) -> eyre::Result<(Self, EventStream)> {
let node_config = NodeConfig {
dataflow_id: DataflowId::new_v4(),
node_id: "".parse()?,
run_config: NodeRunConfig {
inputs: Default::default(),
outputs: Default::default(),
},
daemon_communication: None,
dataflow_descriptor: serde_yaml::Value::Null,
dynamic: false,
write_events_to: None,
};
let testing_comm = TestingCommunication {
input,
output,
options,
};
let (mut node, events) = Self::init_with_options(node_config, Some(testing_comm))?;
node.interactive = true;
Ok((node, events))
}
/// Internal initialization routine that should not be used outside of Dora.
#[doc(hidden)]
#[tracing::instrument]
pub fn init(node_config: NodeConfig) -> eyre::Result<(Self, EventStream)> {
Self::init_with_options(node_config, None)
}
#[tracing::instrument(skip(testing_communication))]
fn init_with_options(
node_config: NodeConfig,
testing_communication: Option<TestingCommunication>,
) -> eyre::Result<(Self, EventStream)> {
let NodeConfig {
dataflow_id,
node_id,
run_config,
daemon_communication,
dataflow_descriptor,
dynamic,
write_events_to,
} = node_config;
let clock = Arc::new(uhlc::HLC::default());
let input_config = run_config.inputs.clone();
let daemon_communication = match daemon_communication {
Some(comm) => comm.into(),
None => match testing_communication {
Some(comm) => {
let TestingCommunication {
input,
output,
options,
} = comm;
let (sender, mut receiver) = tokio::sync::mpsc::channel(5);
let new_communication = DaemonCommunicationWrapper::Testing { channel: sender };
let mut events = IntegrationTestingEvents::new(input, output, options)?;
std::thread::spawn(move || {
while let Some((request, reply_sender)) = receiver.blocking_recv() {
let reply = events.request(&request);
if reply_sender
.send(reply.unwrap_or_else(|err| {
DaemonReply::Result(Err(format!("{err:?}")))
}))
.is_err()
{
eprintln!("failed to send reply");
}
}
});
new_communication
}
None => eyre::bail!("no daemon communication method specified"),
},
};
let event_stream = EventStream::init(
dataflow_id,
&node_id,
&daemon_communication,
input_config,
clock.clone(),
write_events_to,
)
.wrap_err("failed to init event stream")?;
let drop_stream =
DropStream::init(dataflow_id, &node_id, &daemon_communication, clock.clone())
.wrap_err("failed to init drop stream")?;
let control_channel =
ControlChannel::init(dataflow_id, &node_id, &daemon_communication, clock.clone())
.wrap_err("failed to init control channel")?;
let node = Self {
id: node_id,
dataflow_id,
node_config: run_config.clone(),
control_channel,
clock,
sent_out_shared_memory: HashMap::new(),
drop_stream,
cache: VecDeque::new(),
dataflow_descriptor: serde_yaml::from_value(dataflow_descriptor),
warned_unknown_output: BTreeSet::new(),
interactive: false,
};
if dynamic {
// Inject env variable from dataflow descriptor.
match &node.dataflow_descriptor {
Ok(descriptor) => {
if let Some(env_vars) = descriptor
.nodes
.iter()
.find(|n| n.id == node.id)
.and_then(|n| n.env.as_ref())
{
for (key, value) in env_vars {
// SAFETY: setting env variable is safe as long as we don't
// have multiple threads doing it at the same time.
unsafe {
std::env::set_var(key, value.to_string());
}
}
}
}
Err(err) => {
warn!("Could not parse dataflow descriptor: {err:#}");
}
}
}
Ok((node, event_stream))
}
fn validate_output(&mut self, output_id: &DataId) -> bool {
if !self.node_config.outputs.contains(output_id) && !self.interactive {
if !self.warned_unknown_output.contains(output_id) {
warn!("Ignoring output `{output_id}` not in node's output list.");
self.warned_unknown_output.insert(output_id.clone());
}
false
} else {
true
}
}
/// Send raw data from the node to the other nodes.
///
/// We take a closure as an input to enable zero copy on send.
///
/// ```no_run
/// use dora_node_api::{DoraNode, MetadataParameters};
/// use dora_core::config::DataId;
///
/// let (mut node, mut events) = DoraNode::init_from_env().expect("Could not init node.");
///
/// let output = DataId::from("output_id".to_owned());
///
/// let data: &[u8] = &[0, 1, 2, 3];
/// let parameters = MetadataParameters::default();
///
/// node.send_output_raw(
/// output,
/// parameters,
/// data.len(),
/// |out| {
/// out.copy_from_slice(data);
/// }).expect("Could not send output");
/// ```
///
/// Ignores the output if the given `output_id` is not specified as node output in the dataflow
/// configuration file.
pub fn send_output_raw<F>(
&mut self,
output_id: DataId,
parameters: MetadataParameters,
data_len: usize,
data: F,
) -> eyre::Result<()>
where
F: FnOnce(&mut [u8]),
{
if !self.validate_output(&output_id) {
return Ok(());
};
let mut sample = self.allocate_data_sample(data_len)?;
data(&mut sample);
let type_info = ArrowTypeInfo::byte_array(data_len);
self.send_output_sample(output_id, type_info, parameters, Some(sample))
}
/// Sends the give Arrow array as an output message.
///
/// Uses shared memory for efficient data transfer if suitable.
///
/// This method might copy the message once to move it to shared memory.
///
/// Ignores the output if the given `output_id` is not specified as node output in the dataflow
/// configuration file.
pub fn send_output(
&mut self,
output_id: DataId,
parameters: MetadataParameters,
data: impl Array,
) -> eyre::Result<()> {
if !self.validate_output(&output_id) {
return Ok(());
};
let arrow_array = data.to_data();
let total_len = required_data_size(&arrow_array);
let mut sample = self.allocate_data_sample(total_len)?;
let type_info = copy_array_into_sample(&mut sample, &arrow_array);
self.send_output_sample(output_id, type_info, parameters, Some(sample))
.wrap_err("failed to send output")?;
Ok(())
}
/// Send the given raw byte data as output.
///
/// Might copy the data once to move it into shared memory.
///
/// Ignores the output if the given `output_id` is not specified as node output in the dataflow
/// configuration file.
pub fn send_output_bytes(
&mut self,
output_id: DataId,
parameters: MetadataParameters,
data_len: usize,
data: &[u8],
) -> eyre::Result<()> {
if !self.validate_output(&output_id) {
return Ok(());
};
self.send_output_raw(output_id, parameters, data_len, |sample| {
sample.copy_from_slice(data)
})
}
/// Send the give raw byte data with the provided type information.
///
/// It is recommended to use a function like [`send_output`][Self::send_output] instead.
///
/// Ignores the output if the given `output_id` is not specified as node output in the dataflow
/// configuration file.
pub fn send_typed_output<F>(
&mut self,
output_id: DataId,
type_info: ArrowTypeInfo,
parameters: MetadataParameters,
data_len: usize,
data: F,
) -> eyre::Result<()>
where
F: FnOnce(&mut [u8]),
{
if !self.validate_output(&output_id) {
return Ok(());
};
let mut sample = self.allocate_data_sample(data_len)?;
data(&mut sample);
self.send_output_sample(output_id, type_info, parameters, Some(sample))
}
/// Sends the given [`DataSample`] as output, combined with the given type information.
///
/// It is recommended to use a function like [`send_output`][Self::send_output] instead.
///
/// Ignores the output if the given `output_id` is not specified as node output in the dataflow
/// configuration file.
pub fn send_output_sample(
&mut self,
output_id: DataId,
type_info: ArrowTypeInfo,
parameters: MetadataParameters,
sample: Option<DataSample>,
) -> eyre::Result<()> {
if !self.interactive {
self.handle_finished_drop_tokens()?;
}
let metadata = Metadata::from_parameters(self.clock.new_timestamp(), type_info, parameters);
let (data, shmem) = match sample {
Some(sample) => sample.finalize(),
None => (None, None),
};
self.control_channel
.send_message(output_id.clone(), metadata, data)
.wrap_err_with(|| format!("failed to send output {output_id}"))?;
if let Some((shared_memory, drop_token)) = shmem {
self.sent_out_shared_memory
.insert(drop_token, shared_memory);
}
Ok(())
}
/// Report the given outputs IDs as closed.
///
/// The node is not allowed to send more outputs with the closed IDs.
///
/// Closing outputs early can be helpful to receivers.
pub fn close_outputs(&mut self, outputs_ids: Vec<DataId>) -> eyre::Result<()> {
for output_id in &outputs_ids {
if !self.node_config.outputs.remove(output_id) {
eyre::bail!("unknown output {output_id}");
}
}
self.control_channel
.report_closed_outputs(outputs_ids)
.wrap_err("failed to report closed outputs to daemon")?;
Ok(())
}
/// Returns the ID of the node as specified in the dataflow configuration file.
pub fn id(&self) -> &NodeId {
&self.id
}
/// Returns the unique identifier for the running dataflow instance.
///
/// Dora assigns each dataflow instance a random identifier when started.
pub fn dataflow_id(&self) -> &DataflowId {
&self.dataflow_id
}
/// Returns the input and output configuration of this node.
pub fn node_config(&self) -> &NodeRunConfig {
&self.node_config
}
/// Allocates a [`DataSample`] of the specified size.
///
/// The data sample will use shared memory when suitable to enable efficient data transfer
/// when sending an output message.
pub fn allocate_data_sample(&mut self, data_len: usize) -> eyre::Result<DataSample> {
let data = if data_len >= ZERO_COPY_THRESHOLD && !self.interactive {
// create shared memory region
let shared_memory = self.allocate_shared_memory(data_len)?;
DataSample {
inner: DataSampleInner::Shmem(shared_memory),
len: data_len,
}
} else {
let avec: AVec<u8, ConstAlign<128>> = AVec::__from_elem(128, 0, data_len);
avec.into()
};
Ok(data)
}
fn allocate_shared_memory(&mut self, data_len: usize) -> eyre::Result<ShmemHandle> {
let cache_index = self
.cache
.iter()
.enumerate()
.rev()
.filter(|(_, s)| s.len() >= data_len)
.min_by_key(|(_, s)| s.len())
.map(|(i, _)| i);
let memory = match cache_index {
Some(i) => {
// we know that this index exists, so we can safely unwrap here
self.cache.remove(i).unwrap()
}
None => ShmemHandle(Box::new(
ShmemConf::new()
.size(data_len)
.writable(true)
.create()
.wrap_err("failed to allocate shared memory")?,
)),
};
assert!(memory.len() >= data_len);
Ok(memory)
}
fn handle_finished_drop_tokens(&mut self) -> eyre::Result<()> {
loop {
match self.drop_stream.try_recv() {
Ok(token) => match self.sent_out_shared_memory.remove(&token) {
Some(region) => self.add_to_cache(region),
None => tracing::warn!("received unknown finished drop token `{token:?}`"),
},
Err(flume::TryRecvError::Empty) => break,
Err(flume::TryRecvError::Disconnected) => {
bail!("event stream was closed before sending all expected drop tokens")
}
}
}
Ok(())
}
fn add_to_cache(&mut self, memory: ShmemHandle) {
const MAX_CACHE_SIZE: usize = 20;
self.cache.push_back(memory);
while self.cache.len() > MAX_CACHE_SIZE {
self.cache.pop_front();
}
}
/// Returns the full dataflow descriptor that this node is part of.
///
/// This method returns the parsed dataflow YAML file.
pub fn dataflow_descriptor(&self) -> eyre::Result<&Descriptor> {
match &self.dataflow_descriptor {
Ok(d) => Ok(d),
Err(err) => eyre::bail!(
"failed to parse dataflow descriptor: {err}\n\n
This might be caused by mismatched version numbers of dora \
daemon and the dora node API"
),
}
}
}
impl Drop for DoraNode {
fn drop(&mut self) {
// close all outputs first to notify subscribers as early as possible
if let Err(err) = self
.control_channel
.report_closed_outputs(
std::mem::take(&mut self.node_config.outputs)
.into_iter()
.collect(),
)
.context("failed to close outputs on drop")
{
tracing::warn!("{err:?}")
}
while !self.sent_out_shared_memory.is_empty() {
if self.drop_stream.is_empty() {
tracing::trace!(
"waiting for {} remaining drop tokens",
self.sent_out_shared_memory.len()
);
}
match self.drop_stream.recv_timeout(Duration::from_secs(2)) {
Ok(token) => {
self.sent_out_shared_memory.remove(&token);
}
Err(flume::RecvTimeoutError::Disconnected) => {
tracing::warn!(
"finished_drop_tokens channel closed while still waiting for drop tokens; \
closing {} shared memory regions that might not yet been mapped.",
self.sent_out_shared_memory.len()
);
break;
}
Err(flume::RecvTimeoutError::Timeout) => {
tracing::warn!(
"timeout while waiting for drop tokens; \
closing {} shared memory regions that might not yet been mapped.",
self.sent_out_shared_memory.len()
);
break;
}
}
}
if let Err(err) = self.control_channel.report_outputs_done() {
tracing::warn!("{err:?}")
}
}
}
/// A data region suitable for sending as an output message.
///
/// The region is stored in shared memory when suitable to enable efficient data transfer.
///
/// `DataSample` implements the [`Deref`] and [`DerefMut`] traits to read and write the mapped data.
pub struct DataSample {
inner: DataSampleInner,
len: usize,
}
impl DataSample {
fn finalize(self) -> (Option<DataMessage>, Option<(ShmemHandle, DropToken)>) {
match self.inner {
DataSampleInner::Shmem(shared_memory) => {
let drop_token = DropToken::generate();
let data = DataMessage::SharedMemory {
shared_memory_id: shared_memory.get_os_id().to_owned(),
len: self.len,
drop_token,
};
(Some(data), Some((shared_memory, drop_token)))
}
DataSampleInner::Vec(buffer) => (Some(DataMessage::Vec(buffer)), None),
}
}
}
impl Deref for DataSample {
type Target = [u8];
fn deref(&self) -> &Self::Target {
let slice = match &self.inner {
DataSampleInner::Shmem(handle) => unsafe { handle.as_slice() },
DataSampleInner::Vec(data) => data,
};
&slice[..self.len]
}
}
impl DerefMut for DataSample {
fn deref_mut(&mut self) -> &mut Self::Target {
let slice = match &mut self.inner {
DataSampleInner::Shmem(handle) => unsafe { handle.as_slice_mut() },
DataSampleInner::Vec(data) => data,
};
&mut slice[..self.len]
}
}
impl From<AVec<u8, ConstAlign<128>>> for DataSample {
fn from(value: AVec<u8, ConstAlign<128>>) -> Self {
Self {
len: value.len(),
inner: DataSampleInner::Vec(value),
}
}
}
impl std::fmt::Debug for DataSample {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let kind = match &self.inner {
DataSampleInner::Shmem(_) => "SharedMemory",
DataSampleInner::Vec(_) => "Vec",
};
f.debug_struct("DataSample")
.field("len", &self.len)
.field("kind", &kind)
.finish_non_exhaustive()
}
}
enum DataSampleInner {
Shmem(ShmemHandle),
Vec(AVec<u8, ConstAlign<128>>),
}
struct ShmemHandle(Box<Shmem>);
impl Deref for ShmemHandle {
type Target = Shmem;
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl DerefMut for ShmemHandle {
fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.0
}
}
unsafe impl Send for ShmemHandle {}
unsafe impl Sync for ShmemHandle {}
/// Init Opentelemetry Tracing
///
/// This requires a tokio runtime spawning this function to be functional
#[cfg(feature = "tracing")]
pub fn init_tracing(
node_id: &NodeId,
dataflow_id: &DataflowId,
) -> eyre::Result<Arc<Mutex<Option<OtelGuard>>>> {
let node_id_str = node_id.to_string();
let guard: Arc<Mutex<Option<OtelGuard>>> = Arc::new(Mutex::new(None));
let clone = guard.clone();
let tracing_monitor = async move {
let mut builder = TracingBuilder::new(node_id_str);
// Only enable OTLP if environment variable is set
if std::env::var("DORA_OTLP_ENDPOINT").is_ok()
|| std::env::var("DORA_JAEGER_TRACING").is_ok()
{
builder = builder
.with_otlp_tracing()
.context("failed to set up OTLP tracing")
.unwrap()
.with_stdout("info", true);
*clone.lock().unwrap() = builder.guard.take();
} else {
builder = builder.with_stdout("info", true);
}
builder
.build()
.wrap_err("failed to set up tracing subscriber")
.unwrap();
};
let rt = Handle::try_current().context("failed to get tokio runtime handle")?;
rt.spawn(tracing_monitor);
#[cfg(feature = "metrics")]
{
let id = format!("{dataflow_id}/{node_id}");
let monitor_task = async move {
use dora_metrics::run_metrics_monitor;
if let Err(e) = run_metrics_monitor(id.clone())
.await
.wrap_err("metrics monitor exited unexpectedly")
{
warn!("metrics monitor failed: {:#?}", e);
}
};
let rt = Handle::try_current().context("failed to get tokio runtime handle")?;
rt.spawn(monitor_task);
};
Ok(guard)
}