dora_node_api/lib.rs
1//! This crate enables you to create nodes for the [Dora] dataflow framework.
2//!
3//! [Dora]: https://dora-rs.ai/
4//!
5//! ## The Dora Framework
6//!
7//! Dora is a dataflow frame work that models applications as a directed graph, with nodes
8//! representing operations and edges representing data transfer.
9//! The layout of the dataflow graph is defined through a YAML file in Dora.
10//! For details, see our [Dataflow Specification](https://dora-rs.ai/docs/api/dataflow-config/)
11//! chapter.
12//!
13//! Dora nodes are typically spawned by the Dora framework, instead of spawning them manually.
14//! If you want to spawn a node manually, define it as a [_dynamic_ node](#dynamic-nodes).
15//!
16//! ## Normal Usage
17//!
18//! In order to connect your executable to Dora, you need to initialize a [`DoraNode`].
19//! For standard nodes, the recommended initialization function is [`init_from_env`][`DoraNode::init_from_env`].
20//! This function will return two values, a [`DoraNode`] instance and an [`EventStream`]:
21//!
22//! ```no_run
23//! use dora_node_api::DoraNode;
24//!
25//! let (mut node, mut events) = DoraNode::init_from_env()?;
26//! # Ok::<(), eyre::Report>(())
27//! ```
28//!
29//! You can use the `node` instance to send outputs and retrieve information about the node and
30//! the dataflow. The `events` stream yields the inputs that the node defines in the dataflow
31//! YAML file and other incoming events.
32//!
33//! ### Sending Outputs
34//!
35//! The [`DoraNode`] instance enables you to send outputs in different formats.
36//! For best performance, use the [Arrow](https://arrow.apache.org/docs/index.html) data format
37//! and one of the output functions that utilizes shared memory.
38//!
39//! ### Receiving Events
40//!
41//! The [`EventStream`] is an [`AsyncIterator`][std::async_iter::AsyncIterator] that yields the incoming [`Event`]s.
42//!
43//! Nodes should iterate over this event stream and react to events that they are interested in.
44//! Typically, the most important event type is [`Event::Input`].
45//! You don't need to handle all events, it's fine to ignore events that are not relevant to your node.
46//!
47//! The event stream will close itself after a [`Event::Stop`] was received.
48//! A manual `break` on [`Event::Stop`] is typically not needed.
49//! _(You probably do need to use a manual `break` on stop events when using the
50//! [`StreamExt::merge`][`futures_concurrency::stream::StreamExt::merge`] implementation on
51//! [`EventStream`] to combine the stream with an external one.)_
52//!
53//! Once the event stream finished, nodes should exit.
54//! Note that Dora kills nodes that don't exit quickly after a [`Event::Stop`] of type
55//! [`StopCause::Manual`] was received.
56//!
57//!
58//!
59//! ## Dynamic Nodes
60//!
61//! <div class="warning">
62//!
63//! Dynamic nodes have certain [limitations](#limitations). Use with care.
64//!
65//! </div>
66//!
67//! Nodes can be defined as `dynamic` by setting their `path` attribute to `dynamic` in the
68//! dataflow YAML file. Dynamic nodes are not spawned by the Dora framework and need to be started
69//! manually.
70//!
71//! Dynamic nodes cannot use the [`DoraNode::init_from_env`] function for initialization.
72//! Instead, they can be initialized through the [`DoraNode::init_from_node_id`] function.
73//!
74//! ### Limitations
75//!
76//! - Dynamic nodes **don't work with `dora run`**.
77//! - As dynamic nodes are identified by their node ID, this **ID must be unique**
78//! across all running dataflows.
79//! - For distributed dataflows, nodes need to be manually spawned on the correct machine.
80//!
81//!
82//! ## Node Integration Testing
83//!
84//! Dora provides built-in support for integration testing of nodes. See the [integration_testing]
85//! module for details.
86
87#![warn(missing_docs)]
88
89/// Apache Arrow 59, dora's current **internal** major.
90///
91/// Enabled by the `arrow-v59` feature, which pulls no extra dependency: this
92/// is the same copy of Arrow 59 dora itself links, so
93/// [`DoraArray::as_array`] hands it back for free and arrays built with it
94/// need no conversion.
95///
96/// This is deliberately not `pub use arrow;`. A bare `arrow` re-export changes
97/// meaning silently when dora bumps its internal major; `arrow_v59` either
98/// exists and means Arrow 59, or it is visibly gone. See
99/// `docs/plan-arrow-version-decoupling.md`.
100#[cfg(feature = "arrow-v59")]
101pub use arrow as arrow_v59;
102/// Apache Arrow 58, for nodes that name that major.
103///
104/// Enabled by the `arrow-v58` feature. Arrow 58 is **not** dora's internal
105/// major, so payloads cross a C Data Interface hop, exposed as `TryFrom`
106/// impls in both directions (`DoraArray::try_from(&arr as &dyn arrow58 Array)`
107/// and `arrow_v58::array::ArrayRef::try_from(&dora)`). The hop is fallible —
108/// hence `TryFrom` and not `From` — but does not copy buffers.
109#[cfg(feature = "arrow-v58")]
110pub use arrow58 as arrow_v58;
111// Deliberately *not* a glob re-export: `dora_arrow_convert::internal` is an
112// Arrow-typed, semver-exempt seam for dora's own crates and must not become
113// reachable through the frozen `dora-node-api` surface.
114pub use dora_arrow_convert::{DoraArray, IntoArrow, into_vec};
115pub use dora_core::uhlc;
116
117/// The subset of [`dora_core`] that is part of dora's public API.
118///
119/// Deliberately not `pub use dora_core::self`. Re-exporting the whole crate
120/// froze `dora_core`'s descriptor, topics, build, manifest and type-registry
121/// surface into dora's 1.0 guarantee, none of which a node needs — the only
122/// items reached through this path anywhere are the three id types below and
123/// `uhlc`, which is re-exported at the crate root.
124///
125/// The `config` path is preserved verbatim because
126/// `dora_node_api::dora_core::config::DataId` is what `dora new` scaffolds and
127/// what the Rust API reference documents.
128pub mod dora_core {
129 /// Identifier types used in node and dataflow configuration.
130 pub mod config {
131 pub use dora_core::config::{DataId, NodeId, OperatorId};
132 }
133 pub use dora_core::uhlc;
134}
135pub use dora_message::{
136 DataflowId,
137 metadata::{
138 self, FIN, FLUSH, GOAL_ID, GOAL_STATUS, GOAL_STATUS_ABORTED, GOAL_STATUS_CANCELED,
139 GOAL_STATUS_SUCCEEDED, Metadata, MetadataParameters, OPEN_TELEMETRY_CONTEXT, Parameter,
140 REQUEST_ID, SEGMENT_ID, SEQ, SESSION_ID, get_bool_param, get_integer_param,
141 get_string_param,
142 },
143};
144use dora_message::{
145 common::Timestamped,
146 daemon_to_node::{DaemonCommunication, DaemonReply},
147 node_to_daemon::DaemonRequest,
148};
149pub use event_stream::{
150 Event, EventScheduler, EventStream, StopCause, TryRecvError,
151 input_tracker::{InputState, InputTracker},
152 merged,
153};
154pub use futures;
155#[cfg(feature = "tracing")]
156pub use node::init_tracing;
157pub use node::{
158 DataSample, DoraNode, DoraNodeBuilder, EncodedSample, SampleAllocator, StreamSegment,
159 ZERO_COPY_THRESHOLD, arrow_utils,
160};
161pub use uuid;
162
163pub use serde_json;
164use tokio::sync::oneshot;
165
166mod daemon_connection;
167mod error;
168/// Asynchronous event stream and daemon communication.
169pub mod event_stream;
170pub mod integration_testing;
171mod node;
172mod orphan_guard;
173
174pub use error::{NodeError, NodeResult, PatternError};
175
176/// Backward-compatible alias for [`Event`], so code using the old `DoraEvent`
177/// name still compiles.
178pub use Event as DoraEvent;
179
180#[derive(Debug)]
181enum DaemonCommunicationWrapper {
182 Standard(DaemonCommunication),
183 Testing {
184 channel:
185 tokio::sync::mpsc::Sender<(Timestamped<DaemonRequest>, oneshot::Sender<DaemonReply>)>,
186 /// Shared with the testing daemon so Drop can interrupt a scheduled
187 /// `next_event` sleep (dora-rs/dora#2855).
188 shutdown: std::sync::Arc<std::sync::atomic::AtomicBool>,
189 },
190}
191
192impl From<DaemonCommunication> for DaemonCommunicationWrapper {
193 fn from(value: DaemonCommunication) -> Self {
194 DaemonCommunicationWrapper::Standard(value)
195 }
196}