cistine commited on
Commit
b98ffbb
1 Parent(s): cdf137b

Upload 490 files

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. CONTRIBUTING.md +44 -0
  2. Cargo.lock +0 -0
  3. Cargo.toml +151 -0
  4. Changelog.md +334 -0
  5. NOTICE.md +7 -0
  6. apis/c++/node/Cargo.toml +41 -0
  7. apis/c++/node/README.md +321 -0
  8. apis/c++/node/build.rs +159 -0
  9. apis/c++/node/src/lib.rs +225 -0
  10. apis/c++/operator/Cargo.toml +17 -0
  11. apis/c++/operator/build.rs +4 -0
  12. apis/c++/operator/src/lib.rs +98 -0
  13. apis/c/node/Cargo.toml +26 -0
  14. apis/c/node/node_api.h +22 -0
  15. apis/c/node/src/lib.rs +260 -0
  16. apis/c/operator/Cargo.toml +16 -0
  17. apis/c/operator/build.rs +11 -0
  18. apis/c/operator/operator_api.h +36 -0
  19. apis/c/operator/operator_types.h +180 -0
  20. apis/c/operator/src/lib.rs +4 -0
  21. apis/python/node/Cargo.toml +31 -0
  22. apis/python/node/README.md +21 -0
  23. apis/python/node/dora/__init__.py +42 -0
  24. apis/python/node/dora/__init__.pyi +320 -0
  25. apis/python/node/dora/__pycache__/__init__.cpython-38.pyc +0 -0
  26. apis/python/node/generate_stubs.py +517 -0
  27. apis/python/node/pyproject.toml +11 -0
  28. apis/python/node/src/lib.rs +264 -0
  29. apis/python/operator/Cargo.toml +20 -0
  30. apis/python/operator/src/lib.rs +259 -0
  31. apis/rust/node/Cargo.toml +31 -0
  32. apis/rust/node/src/daemon_connection/mod.rs +74 -0
  33. apis/rust/node/src/daemon_connection/tcp.rs +68 -0
  34. apis/rust/node/src/event_stream/event.rs +128 -0
  35. apis/rust/node/src/event_stream/merged.rs +115 -0
  36. apis/rust/node/src/event_stream/mod.rs +226 -0
  37. apis/rust/node/src/event_stream/thread.rs +269 -0
  38. apis/rust/node/src/lib.rs +26 -0
  39. apis/rust/node/src/node/arrow_utils.rs +71 -0
  40. apis/rust/node/src/node/control_channel.rs +106 -0
  41. apis/rust/node/src/node/drop_stream.rs +178 -0
  42. apis/rust/node/src/node/mod.rs +475 -0
  43. apis/rust/operator/Cargo.toml +14 -0
  44. apis/rust/operator/macros/Cargo.toml +17 -0
  45. apis/rust/operator/macros/src/lib.rs +74 -0
  46. apis/rust/operator/src/lib.rs +69 -0
  47. apis/rust/operator/src/raw.rs +80 -0
  48. apis/rust/operator/types/Cargo.toml +17 -0
  49. apis/rust/operator/types/src/lib.rs +212 -0
  50. binaries/cli/Cargo.toml +44 -0
CONTRIBUTING.md ADDED
@@ -0,0 +1,44 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # How to contribute to `dora-rs`
2
+
3
+ We welcome bug reports, feature requests, and pull requests!
4
+
5
+ Please discuss non-trivial changes in a Github issue or on Discord first before implementing them.
6
+ This way, we can avoid unnecessary work on both sides.
7
+
8
+ ## Building
9
+
10
+ The `dora` project is set up as a [cargo workspace](https://doc.rust-lang.org/cargo/reference/workspaces.html).
11
+ You can use the standard `cargo check`, `cargo build`, `cargo run`, and `cargo test` commands.
12
+ To run a command for a specific package only, pass e.g. `--package dora-daemon`.
13
+ Running a command for the whole workspace is possible by passing `--workspace`.
14
+
15
+ ## Continuous Integration (CI)
16
+
17
+ We're using [GitHub Actions](https://github.com/features/actions) to run automated checks on all commits and pull requests.
18
+ These checks ensure that our `main` branch always builds successfully and that it passes all tests.
19
+ Please ensure that your pull request passes all checks.
20
+ You don't need to fix warnings that are unrelated to your changes.
21
+ Feel free to ask for help if you're unsure about a check failure.
22
+
23
+ We're currently running the following kind of checks:
24
+
25
+ - **CI / Test:** Ensures that the project builds and that all unit tests pass. This check is run on Linux, Windows, and macOS.
26
+ - **CI / Examples:** Builds and runs the Rust, C, and C++ dataflows from the `examples` subdirectory. This check is run on Linux, Windows, and macOS.
27
+ - **CI-python / Python Examples:** Builds and runs the Python dataflows from the `examples` subdirectory. This check is run on Linux only.
28
+ - **github pages / deploy:** Generates our website from the `docs` subfolder.
29
+ - **CI / CLI Test:** Runs some basic tests of the `dora` command-line application. This check is run on Linux, Windows, and macOS.
30
+ - **CI / Clippy:** Runs the additional checks of the [`clippy`](https://github.com/rust-lang/rust-clippy) project.
31
+ - **CI / Formatting:** Ensures that the code is formatted using `rustfmt` (see [below](#style))
32
+ - **CI / License Checks:** Scans the dependency tree and tries to detect possible license incompatibilities.
33
+
34
+ ## Style
35
+
36
+ We use [`rustfmt`](https://github.com/rust-lang/rustfmt) with its default settings to format our code.
37
+ Please run `cargo fmt --all` on your code before submitting a pull request.
38
+ Our CI will run an automatic formatting check of your code.
39
+
40
+ ## Publishing new Versions
41
+
42
+ The maintainers are responsible for publishing new versions of the `dora` crates.
43
+ Please don't open unsolicited pull requests to create new releases.
44
+ Instead, request a new version by opening an issue or by leaving a comment on a merged PR.
Cargo.lock ADDED
The diff for this file is too large to render. See raw diff
 
Cargo.toml ADDED
@@ -0,0 +1,151 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ [workspace]
2
+ members = [
3
+ "apis/c/node",
4
+ "apis/c/operator",
5
+ "apis/c++/node",
6
+ "apis/c++/operator",
7
+ "apis/python/node",
8
+ "apis/python/operator",
9
+ "apis/rust/*",
10
+ "apis/rust/operator/macros",
11
+ "apis/rust/operator/types",
12
+ "binaries/cli",
13
+ "binaries/coordinator",
14
+ "binaries/daemon",
15
+ "binaries/runtime",
16
+ "examples/rust-dataflow/node",
17
+ "examples/rust-dataflow/status-node",
18
+ "examples/rust-dataflow/sink",
19
+ "examples/rust-ros2-dataflow/node",
20
+ "examples/benchmark/node",
21
+ "examples/benchmark/sink",
22
+ "examples/multiple-daemons/node",
23
+ "examples/multiple-daemons/operator",
24
+ "examples/multiple-daemons/sink",
25
+ "libraries/arrow-convert",
26
+ "libraries/communication-layer/*",
27
+ "libraries/core",
28
+ "libraries/message",
29
+ "libraries/shared-memory-server",
30
+ "libraries/extensions/download",
31
+ "libraries/extensions/telemetry/*",
32
+ "tool_nodes/dora-record",
33
+ "tool_nodes/dora-rerun",
34
+ "libraries/extensions/ros2-bridge",
35
+ "libraries/extensions/ros2-bridge/msg-gen",
36
+ "libraries/extensions/ros2-bridge/python",
37
+ ]
38
+
39
+ [workspace.package]
40
+ # Make sure to also bump `apis/node/python/__init__.py` version.
41
+ version = "0.3.4"
42
+ description = "`dora` goal is to be a low latency, composable, and distributed data flow."
43
+ documentation = "https://dora.carsmos.ai"
44
+ license = "Apache-2.0"
45
+
46
+ [workspace.dependencies]
47
+ dora-node-api = { version = "0.3.4", path = "apis/rust/node", default-features = false }
48
+ dora-node-api-python = { version = "0.3.4", path = "apis/python/node", default-features = false }
49
+ dora-operator-api = { version = "0.3.4", path = "apis/rust/operator", default-features = false }
50
+ dora-operator-api-macros = { version = "0.3.4", path = "apis/rust/operator/macros" }
51
+ dora-operator-api-types = { version = "0.3.4", path = "apis/rust/operator/types" }
52
+ dora-operator-api-python = { version = "0.3.4", path = "apis/python/operator" }
53
+ dora-operator-api-c = { version = "0.3.4", path = "apis/c/operator" }
54
+ dora-node-api-c = { version = "0.3.4", path = "apis/c/node" }
55
+ dora-core = { version = "0.3.4", path = "libraries/core" }
56
+ dora-arrow-convert = { version = "0.3.4", path = "libraries/arrow-convert" }
57
+ dora-tracing = { version = "0.3.4", path = "libraries/extensions/telemetry/tracing" }
58
+ dora-metrics = { version = "0.3.4", path = "libraries/extensions/telemetry/metrics" }
59
+ dora-download = { version = "0.3.4", path = "libraries/extensions/download" }
60
+ shared-memory-server = { version = "0.3.4", path = "libraries/shared-memory-server" }
61
+ communication-layer-request-reply = { version = "0.3.4", path = "libraries/communication-layer/request-reply" }
62
+ dora-message = { version = "0.3.4", path = "libraries/message" }
63
+ dora-runtime = { version = "0.3.4", path = "binaries/runtime" }
64
+ dora-daemon = { version = "0.3.4", path = "binaries/daemon" }
65
+ dora-coordinator = { version = "0.3.4", path = "binaries/coordinator" }
66
+ dora-ros2-bridge = { path = "libraries/extensions/ros2-bridge" }
67
+ dora-ros2-bridge-msg-gen = { path = "libraries/extensions/ros2-bridge/msg-gen" }
68
+ dora-ros2-bridge-python = { path = "libraries/extensions/ros2-bridge/python" }
69
+ arrow = { version = "52" }
70
+ arrow-schema = { version = "52" }
71
+ arrow-data = { version = "52" }
72
+ arrow-array = { version = "52" }
73
+ pyo3 = "0.21"
74
+ pythonize = "0.21"
75
+
76
+ [package]
77
+ name = "dora-examples"
78
+ version = "0.0.0"
79
+ edition = "2021"
80
+ license = "Apache-2.0"
81
+
82
+
83
+ [features]
84
+ # enables examples that depend on a sourced ROS2 installation
85
+ ros2-examples = []
86
+
87
+ [dev-dependencies]
88
+ eyre = "0.6.8"
89
+ tokio = "1.24.2"
90
+ dora-coordinator = { workspace = true }
91
+ dora-core = { workspace = true }
92
+ dora-tracing = { workspace = true }
93
+ dora-download = { workspace = true }
94
+ dunce = "1.0.2"
95
+ serde_yaml = "0.8.23"
96
+ uuid = { version = "1.7", features = ["v7", "serde"] }
97
+ tracing = "0.1.36"
98
+ futures = "0.3.25"
99
+ tokio-stream = "0.1.11"
100
+
101
+ [[example]]
102
+ name = "c-dataflow"
103
+ path = "examples/c-dataflow/run.rs"
104
+
105
+ [[example]]
106
+ name = "rust-dataflow"
107
+ path = "examples/rust-dataflow/run.rs"
108
+
109
+ [[example]]
110
+ name = "rust-ros2-dataflow"
111
+ path = "examples/rust-ros2-dataflow/run.rs"
112
+ required-features = ["ros2-examples"]
113
+
114
+ # TODO: Fix example #192
115
+ [[example]]
116
+ name = "rust-dataflow-url"
117
+ path = "examples/rust-dataflow-url/run.rs"
118
+
119
+ [[example]]
120
+ name = "cxx-dataflow"
121
+ path = "examples/c++-dataflow/run.rs"
122
+
123
+ [[example]]
124
+ name = "python-dataflow"
125
+ path = "examples/python-dataflow/run.rs"
126
+
127
+ [[example]]
128
+ name = "python-ros2-dataflow"
129
+ path = "examples/python-ros2-dataflow/run.rs"
130
+ required-features = ["ros2-examples"]
131
+
132
+ [[example]]
133
+ name = "python-operator-dataflow"
134
+ path = "examples/python-operator-dataflow/run.rs"
135
+
136
+ [[example]]
137
+ name = "benchmark"
138
+ path = "examples/benchmark/run.rs"
139
+
140
+ [[example]]
141
+ name = "multiple-daemons"
142
+ path = "examples/multiple-daemons/run.rs"
143
+
144
+ [[example]]
145
+ name = "cmake-dataflow"
146
+ path = "examples/cmake-dataflow/run.rs"
147
+
148
+ [[example]]
149
+ name = "cxx-ros2-dataflow"
150
+ path = "examples/c++-ros2-dataflow/run.rs"
151
+ required-features = ["ros2-examples"]
Changelog.md ADDED
@@ -0,0 +1,334 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Changelog
2
+
3
+ ## v0.3.4 (2024-05-17)
4
+
5
+ ## What's Changed
6
+
7
+ - Remove `cxx_build` call, which is no longer used by @phil-opp in https://github.com/dora-rs/dora/pull/470
8
+ - Update `ros2-client` to latest version by @phil-opp in https://github.com/dora-rs/dora/pull/457
9
+ - Configurable bind addrs by @Michael-J-Ward in https://github.com/dora-rs/dora/pull/471
10
+ - Simple warning fixes by @Michael-J-Ward in https://github.com/dora-rs/dora/pull/477
11
+ - Adding `dora-rerun` as a visualization tool by @haixuanTao in https://github.com/dora-rs/dora/pull/479
12
+ - Fix Clippy and RERUN_MEMORY_LIMIT env variable default by @haixuanTao in https://github.com/dora-rs/dora/pull/490
13
+ - Fix CI build errors by @phil-opp in https://github.com/dora-rs/dora/pull/491
14
+ - Use `resolver = 2` for in workspace in Rust template by @phil-opp in https://github.com/dora-rs/dora/pull/492
15
+ - Add grace duration and kill process by @haixuanTao in https://github.com/dora-rs/dora/pull/487
16
+ - Simplify parsing of `AMENT_PREFIX_PATH` by @haixuanTao in https://github.com/dora-rs/dora/pull/489
17
+ - Convert rust example to node by @Michael-J-Ward in https://github.com/dora-rs/dora/pull/494
18
+ - Adding python IDE typing by @haixuanTao in https://github.com/dora-rs/dora/pull/493
19
+ - Fix: Wait until dora daemon is connected to coordinator on `dora up` by @phil-opp in https://github.com/dora-rs/dora/pull/496
20
+
21
+ ## New Contributors
22
+
23
+ - @Michael-J-Ward made their first contribution in https://github.com/dora-rs/dora/pull/471
24
+
25
+ **Full Changelog**: https://github.com/dora-rs/dora/compare/v0.3.3...v0.3.4
26
+
27
+ ## v0.3.3 (2024-04-08)
28
+
29
+ ## What's Changed
30
+
31
+ - Metrics refactoring by @haixuanTao in https://github.com/dora-rs/dora/pull/423
32
+ - Add ROS2 bridge support for C++ nodes by @phil-opp in https://github.com/dora-rs/dora/pull/425
33
+ - Provide function to create empty `CombinedEvents` stream by @phil-opp in https://github.com/dora-rs/dora/pull/432
34
+ - Expose ROS2 constants in generated bindings (Rust and C++) by @phil-opp in https://github.com/dora-rs/dora/pull/428
35
+ - Add option to send `stdout` as node/operator output by @haixuanTao in https://github.com/dora-rs/dora/pull/388
36
+ - Fix warning about `#pragma once` in main file by @phil-opp in https://github.com/dora-rs/dora/pull/433
37
+ - Send runs artefacts into a dedicated `out` folder by @haixuanTao in https://github.com/dora-rs/dora/pull/429
38
+ - Create README.md for cxx-ros2-example by @bobd988 in https://github.com/dora-rs/dora/pull/431
39
+ - Use Async Parquet Writer for `dora-record` by @haixuanTao in https://github.com/dora-rs/dora/pull/434
40
+ - Update mio to fix security vulnerability by @phil-opp in https://github.com/dora-rs/dora/pull/440
41
+ - Add initial support for calling ROS2 services from Rust nodes by @phil-opp in https://github.com/dora-rs/dora/pull/439
42
+ - Enable ROS2 service calls from C++ nodes by @phil-opp in https://github.com/dora-rs/dora/pull/441
43
+ - Use `Debug` formatting for eyre errors when returning to C++ by @phil-opp in https://github.com/dora-rs/dora/pull/450
44
+ - Fix out-of-tree builds in cmake example by @phil-opp in https://github.com/dora-rs/dora/pull/453
45
+ - Fix broken link in README by @mshr-h in https://github.com/dora-rs/dora/pull/462
46
+ - fix cargo run --example cmake-dataflow compile bugs by @XxChang in https://github.com/dora-rs/dora/pull/460
47
+ - Llm example by @haixuanTao in https://github.com/dora-rs/dora/pull/451
48
+ - Fix meter conflict by @haixuanTao in https://github.com/dora-rs/dora/pull/461
49
+ - Update README.md by @bobd988 in https://github.com/dora-rs/dora/pull/458
50
+ - Refactor `README` by @haixuanTao in https://github.com/dora-rs/dora/pull/463
51
+ - Specify conda env for Python Operators by @haixuanTao in https://github.com/dora-rs/dora/pull/468
52
+
53
+ ## Minor
54
+
55
+ - Bump h2 from 0.3.24 to 0.3.26 by @dependabot in https://github.com/dora-rs/dora/pull/456
56
+ - Update `bat` dependency to v0.24 by @phil-opp in https://github.com/dora-rs/dora/pull/424
57
+
58
+ ## New Contributors
59
+
60
+ - @bobd988 made their first contribution in https://github.com/dora-rs/dora/pull/431
61
+
62
+ * @mshr-h made their first contribution in https://github.com/dora-rs/dora/pull/462
63
+
64
+ **Full Changelog**: https://github.com/dora-rs/dora/compare/v0.3.2...v0.3.3
65
+
66
+ ## v0.3.2 (2024-01-26)
67
+
68
+ ## Features
69
+
70
+ - Wait until `DestroyResult` is sent before exiting dora-daemon by @phil-opp in https://github.com/dora-rs/dora/pull/413
71
+ - Reduce dora-rs to a single binary by @haixuanTao in https://github.com/dora-rs/dora/pull/410
72
+ - Rework python ROS2 (de)serialization using parsed ROS2 messages directly by @phil-opp in https://github.com/dora-rs/dora/pull/415
73
+ - Fix ros2 array bug by @haixuanTao in https://github.com/dora-rs/dora/pull/412
74
+ - Test ros2 type info by @haixuanTao in https://github.com/dora-rs/dora/pull/418
75
+ - Use forward slash as it is default way of defining ros2 topic by @haixuanTao in https://github.com/dora-rs/dora/pull/419
76
+
77
+ ## Minor
78
+
79
+ - Bump h2 from 0.3.21 to 0.3.24 by @dependabot in https://github.com/dora-rs/dora/pull/414
80
+
81
+ ## v0.3.1 (2024-01-09)
82
+
83
+ ## Features
84
+
85
+ - Support legacy python by @haixuanTao in https://github.com/dora-rs/dora/pull/382
86
+ - Add an error catch in python `on_event` when using hot-reloading by @haixuanTao in https://github.com/dora-rs/dora/pull/372
87
+ - add cmake example by @XxChang in https://github.com/dora-rs/dora/pull/381
88
+ - Bump opentelemetry metrics to 0.21 by @haixuanTao in https://github.com/dora-rs/dora/pull/383
89
+ - Trace send_output as it can be a big source of overhead for large messages by @haixuanTao in https://github.com/dora-rs/dora/pull/384
90
+ - Adding a timeout method to not block indefinitely next event by @haixuanTao in https://github.com/dora-rs/dora/pull/386
91
+ - Adding `Vec<u8>` conversion by @haixuanTao in https://github.com/dora-rs/dora/pull/387
92
+ - Dora cli renaming by @haixuanTao in https://github.com/dora-rs/dora/pull/399
93
+ - Update `ros2-client` and `rustdds` dependencies to latest fork version by @phil-opp in https://github.com/dora-rs/dora/pull/397
94
+
95
+ ## Fix
96
+
97
+ - Fix window path error by @haixuanTao in https://github.com/dora-rs/dora/pull/398
98
+ - Fix read error in C++ node input by @haixuanTao in https://github.com/dora-rs/dora/pull/406
99
+ - Bump unsafe-libyaml from 0.2.9 to 0.2.10 by @dependabot in https://github.com/dora-rs/dora/pull/400
100
+
101
+ ## New Contributors
102
+
103
+ - @XxChang made their first contribution in https://github.com/dora-rs/dora/pull/381
104
+
105
+ **Full Changelog**: https://github.com/dora-rs/dora/compare/v0.3.0...v0.3.1
106
+
107
+ ## v0.3.0 (2023-11-01)
108
+
109
+ ## Features
110
+
111
+ - Rust node API typed using arrow by @phil-opp in https://github.com/dora-rs/dora/pull/353
112
+ - Dora record by @haixuanTao in https://github.com/dora-rs/dora/pull/365
113
+ - beautify graph visualisation by @haixuanTao in https://github.com/dora-rs/dora/pull/370
114
+ - Remove `Ros2Value` encapsulation of `ArrayData` by @haixuanTao in https://github.com/dora-rs/dora/pull/359
115
+ - Refactor python typing by @haixuanTao in https://github.com/dora-rs/dora/pull/369
116
+ - Update README discord link by @Felixhuangsiling in https://github.com/dora-rs/dora/pull/361
117
+
118
+ ### Other
119
+
120
+ - Update `rustix` v0.38 dependency by @phil-opp in https://github.com/dora-rs/dora/pull/366
121
+ - Bump rustix from 0.37.24 to 0.37.25 by @dependabot in https://github.com/dora-rs/dora/pull/364
122
+ - Bump quinn-proto from 0.9.3 to 0.9.5 by @dependabot in https://github.com/dora-rs/dora/pull/357
123
+ - Bump webpki from 0.22.1 to 0.22.2 by @dependabot in https://github.com/dora-rs/dora/pull/358
124
+ - Update README discord link by @Felixhuangsiling in https://github.com/dora-rs/dora/pull/361
125
+
126
+ ## New Contributors
127
+
128
+ - @Felixhuangsiling made their first contribution in https://github.com/dora-rs/dora/pull/361
129
+
130
+ ## v0.2.6 (2023-09-14)
131
+
132
+ - Update dependencies to fix some security advisories by @phil-opp in https://github.com/dora-rs/dora/pull/354
133
+ - Fixes `cargo install dora-daemon`
134
+
135
+ ## v0.2.5 (2023-09-06)
136
+
137
+ ### Features
138
+
139
+ - Use cargo instead of git in Rust `Cargo.toml` template by @haixuanTao in https://github.com/dora-rs/dora/pull/326
140
+ - Use read_line instead of next_line in stderr by @haixuanTao in https://github.com/dora-rs/dora/pull/325
141
+ - Add a `rust-ros2-dataflow` example using the dora-ros2-bridge by @phil-opp in https://github.com/dora-rs/dora/pull/324
142
+ - Removing patchelf by @haixuanTao in https://github.com/dora-rs/dora/pull/333
143
+ - Improving python example readability by @haixuanTao in https://github.com/dora-rs/dora/pull/334
144
+ - Use `serde_bytes` to serialize `Vec<u8>` by @haixuanTao in https://github.com/dora-rs/dora/pull/336
145
+ - Adding support for `Arrow List(*)` for Python by @haixuanTao in https://github.com/dora-rs/dora/pull/337
146
+ - Bump rustls-webpki from 0.100.1 to 0.100.2 by @dependabot in https://github.com/dora-rs/dora/pull/340
147
+ - Add support for event stream merging for Python node API by @phil-opp in https://github.com/dora-rs/dora/pull/339
148
+ - Merge `dora-ros2-bridge` by @phil-opp in https://github.com/dora-rs/dora/pull/341
149
+ - Update dependencies by @phil-opp in https://github.com/dora-rs/dora/pull/345
150
+ - Add support for arbitrary Arrow types in Python API by @phil-opp in https://github.com/dora-rs/dora/pull/343
151
+ - Use typed inputs in Python ROS2 example by @phil-opp in https://github.com/dora-rs/dora/pull/346
152
+ - Use struct type instead of array for ros2 messages by @haixuanTao in https://github.com/dora-rs/dora/pull/349
153
+
154
+ ### Other
155
+
156
+ - Add Discord :speech_balloon: by @haixuanTao in https://github.com/dora-rs/dora/pull/348
157
+ - Small refactoring by @haixuanTao in https://github.com/dora-rs/dora/pull/342
158
+
159
+ ## v0.2.4 (2023-07-18)
160
+
161
+ ### Features
162
+
163
+ - Return dataflow result to CLI on `dora stop` by @phil-opp in https://github.com/dora-rs/dora/pull/300
164
+ - Make dataflow descriptor available to Python nodes and operators by @phil-opp in https://github.com/dora-rs/dora/pull/301
165
+ - Create a `CONTRIBUTING.md` guide by @phil-opp in https://github.com/dora-rs/dora/pull/307
166
+ - Distribute prebuilt arm macos dora-rs by @haixuanTao in https://github.com/dora-rs/dora/pull/308
167
+
168
+ ### Other
169
+
170
+ - Fix the typos and add dora code branch by @meua in https://github.com/dora-rs/dora/pull/290
171
+ - For consistency with other examples, modify python -> python3 by @meua in https://github.com/dora-rs/dora/pull/299
172
+ - Add timestamps generated by hybrid logical clocks to all sent events by @phil-opp in https://github.com/dora-rs/dora/pull/302
173
+ - Don't recompile the `dora-operator-api-c` crate on every build/run by @phil-opp in https://github.com/dora-rs/dora/pull/304
174
+ - Remove deprecated `proc_macros` feature from `safer-ffi` dependency by @phil-opp in https://github.com/dora-rs/dora/pull/305
175
+ - Update to Rust v1.70 by @phil-opp in https://github.com/dora-rs/dora/pull/303
176
+ - Fix issue with not finding a custom nodes path by @haixuanTao in https://github.com/dora-rs/dora/pull/315
177
+ - Implement `Stream` for `EventStream` by @phil-opp in https://github.com/dora-rs/dora/pull/309
178
+ - Replace unmaintained `atty` crate with `std::io::IsTerminal` by @phil-opp in https://github.com/dora-rs/dora/pull/318
179
+
180
+ **Full Changelog**: https://github.com/dora-rs/dora/compare/v0.2.3...v0.2.4
181
+
182
+ ## v0.2.3 (2023-05-24)
183
+
184
+ ## What's Changed
185
+
186
+ - Check that coordinator, daemon, and node versions match by @phil-opp in https://github.com/dora-rs/dora/pull/245
187
+ - Share events to Python without copying via `arrow` crate by @phil-opp in https://github.com/dora-rs/dora/pull/228
188
+ - Upgrading the operator example to use `dora-arrow` by @haixuanTao in https://github.com/dora-rs/dora/pull/251
189
+ - [Python] Show node name in process and put Traceback before the actual Error for more natural error by @haixuanTao in https://github.com/dora-rs/dora/pull/255
190
+ - CLI: Improve error messages when coordinator is not running by @phil-opp in https://github.com/dora-rs/dora/pull/254
191
+ - Integrate `dora-runtime` into `dora-daemon` by @phil-opp in https://github.com/dora-rs/dora/pull/257
192
+ - Filter default log level at `warn` for `tokio::tracing` by @haixuanTao in https://github.com/dora-rs/dora/pull/269
193
+ - Make log level filtering be `WARN` or below by @haixuanTao in https://github.com/dora-rs/dora/pull/274
194
+ - Add support for distributed deployments with multiple daemons by @phil-opp in https://github.com/dora-rs/dora/pull/256
195
+ - Provide a way to access logs through the CLI by @haixuanTao in https://github.com/dora-rs/dora/pull/259
196
+ - Handle node errors during initialization phase by @phil-opp in https://github.com/dora-rs/dora/pull/275
197
+ - Replace watchdog by asynchronous heartbeat messages by @phil-opp in https://github.com/dora-rs/dora/pull/278
198
+ - Remove pyo3 in runtime and daemon as it generates `libpython` depende… by @haixuanTao in https://github.com/dora-rs/dora/pull/281
199
+ - Release v0.2.3 with aarch64 support by @haixuanTao in https://github.com/dora-rs/dora/pull/279
200
+
201
+ ## Fix
202
+
203
+ - Fix yolov5 dependency issue by @haixuanTao in https://github.com/dora-rs/dora/pull/291
204
+ - To solve this bug https://github.com/dora-rs/dora/issues/283, unify t… by @meua in https://github.com/dora-rs/dora/pull/285
205
+ - Fix: Don't try to create two global tracing subscribers when using bundled runtime by @phil-opp in https://github.com/dora-rs/dora/pull/277
206
+ - CI: Increase timeout for 'build CLI and binaries' step by @phil-opp in https://github.com/dora-rs/dora/pull/282
207
+
208
+ ## Other
209
+
210
+ - Update `pyo3` to `v0.18` by @phil-opp in https://github.com/dora-rs/dora/pull/246
211
+ - Bump h2 from 0.3.13 to 0.3.17 by @dependabot in https://github.com/dora-rs/dora/pull/249
212
+ - Add automatic issue labeler to organize opened issues by @haixuanTao in https://github.com/dora-rs/dora/pull/265
213
+ - Allow the issue labeler to write issues by @phil-opp in https://github.com/dora-rs/dora/pull/272
214
+ - Add a support matrix with planned feature to clarify dora status by @haixuanTao in https://github.com/dora-rs/dora/pull/264
215
+
216
+ **Full Changelog**: https://github.com/dora-rs/dora/compare/v0.2.2...v0.2.3
217
+
218
+ ## v0.2.2 (2023-04-01)
219
+
220
+ ### Features
221
+
222
+ - Make queue length configurable through the dataflow file by @phil-opp in https://github.com/dora-rs/dora/pull/231
223
+ - Hot reloading Python Operator by @haixuanTao in https://github.com/dora-rs/dora/pull/239
224
+ - Synchronize node and operator start by @phil-opp in https://github.com/dora-rs/dora/pull/236
225
+ - Add opentelemetry capability at runtime instead of compile time by @haixuanTao in https://github.com/dora-rs/dora/pull/234
226
+
227
+ ### Others
228
+
229
+ - Wait on events and messages simultaneously to prevent queue buildup by @phil-opp in https://github.com/dora-rs/dora/pull/235
230
+ - Fix looping in daemon listener loop by @phil-opp in https://github.com/dora-rs/dora/pull/244
231
+ - Validate shell command as source and url source by @haixuanTao in https://github.com/dora-rs/dora/pull/243
232
+ - Push error into the `init_done` channel for debugging context by @haixuanTao in https://github.com/dora-rs/dora/pull/238
233
+ - Option communication config by @haixuanTao in https://github.com/dora-rs/dora/pull/241
234
+ - Validate yaml when reading by @haixuanTao in https://github.com/dora-rs/dora/pull/237
235
+
236
+ **Full Changelog**: https://github.com/dora-rs/dora/compare/v0.2.1...v0.2.2
237
+
238
+ ## v0.2.1 (2023-03-22)
239
+
240
+ ### Features
241
+
242
+ - [Make dora-rs publishable on crates.io](https://github.com/dora-rs/dora/pull/211)
243
+
244
+ ### Fixes
245
+
246
+ - [Avoid blocking the daemon main loop by using unbounded queue](https://github.com/dora-rs/dora/pull/230)
247
+ - [Inject YAML declared env variable into the runtime](https://github.com/dora-rs/dora/pull/227)
248
+ - [Use rustls instead of system SSL implementation](https://github.com/dora-rs/dora/pull/216)
249
+
250
+ ### Other
251
+
252
+ - [Refactor python error](https://github.com/dora-rs/dora/pull/229)
253
+ - [The first letter of rust should be lowercase in the command](https://github.com/dora-rs/dora/pull/226)
254
+ - [Add documentation to the cli within the helper mode](https://github.com/dora-rs/dora/pull/225)
255
+ - [Update to safer-ffi v0.1.0-rc1](https://github.com/dora-rs/dora/pull/218)
256
+ - [remove unused variable: data_bytes](https://github.com/dora-rs/dora/pull/215)
257
+ - [Clean up: Remove workspace path](https://github.com/dora-rs/dora/pull/210)
258
+ - [Decouple opentelemetry from tracing](https://github.com/dora-rs/dora/pull/222)
259
+ - [Remove zenoh dependency from dora node API to speed up build](https://github.com/dora-rs/dora/pull/220)
260
+ - [Update to Rust v1.68](https://github.com/dora-rs/dora/pull/221)
261
+ - [Deny unknown fields to avoid typos](https://github.com/dora-rs/dora/pull/223)
262
+ - [Add an internal cli argument to create template with path dependencies](https://github.com/dora-rs/dora/pull/212)
263
+
264
+ ## v0.2.0 (2023-03-14)
265
+
266
+ ### Breaking
267
+
268
+ - [Redesign: Create a `dora-daemon` as a communication broker](https://github.com/dora-rs/dora/pull/162)
269
+ - New `dora-daemon` executable that acts as a communication hub for all local nodes
270
+ - Large messages are passed through shared memory without any copying
271
+ - [Replaces the previous `iceoryx` communication layer](https://github.com/dora-rs/dora/pull/201)
272
+ - Small API change: Nodes and operators now receive _events_ instead of just inputs
273
+ - Inputs are one type of event
274
+ - Other supported events: `InputClosed` when an input stream is closed and `Stop` when the user stops the dataflow (e.g. through the CLI)
275
+
276
+ ### Features
277
+
278
+ - Better Error handling when operator fails
279
+ - [Send small messages directly without shared memory](https://github.com/dora-rs/dora/pull/193)
280
+ - [Send all queued incoming events at once on `NextEvent` request](https://github.com/dora-rs/dora/pull/194)
281
+ - [Don't send replies for `SendMessage` requests when using TCP](https://github.com/dora-rs/dora/pull/195)
282
+ - [Allocate shared memory in nodes to improve throughput](https://github.com/dora-rs/dora/pull/200)
283
+
284
+ ### Fixes
285
+
286
+ - [Manage node failure: Await all nodes to finish before marking dataflow as finished](https://github.com/dora-rs/dora/pull/183)
287
+
288
+ ### Other
289
+
290
+ - [Use `DoraStatus` from dora library in template](https://github.com/dora-rs/dora/pull/182)
291
+ - [Simplify: Replace `library_filename` function with `format!` call](https://github.com/dora-rs/dora/pull/191)
292
+ - [Refactor Rust node API implementation](https://github.com/dora-rs/dora/pull/196)
293
+ - [Remove code duplicate for tracing subscriber and use env variable to manage log level.](https://github.com/dora-rs/dora/pull/197)
294
+ - [Add daemon to the release archive](https://github.com/dora-rs/dora/pull/199)
295
+ - [Remove `remove_dir_all` from `Cargo.lock`as it is vulnerable to a race condition according to dependabot](https://github.com/dora-rs/dora/pull/202)
296
+ - [Update the documentation to the new daemon format](https://github.com/dora-rs/dora/pull/198)
297
+ - [Removing legacy `libacl` which was required by Iceoryx](https://github.com/dora-rs/dora/pull/205)
298
+ - [Remove unimplemented CLI arguments for now](https://github.com/dora-rs/dora/pull/207)
299
+ - [Update zenoh to remove git dependencies](https://github.com/dora-rs/dora/pull/203)
300
+ - [Fix cli template to new daemon API](https://github.com/dora-rs/dora/pull/204)
301
+ - [Cleanup warnings](https://github.com/dora-rs/dora/pull/208)
302
+ - Dependency updates
303
+
304
+ ## v0.1.3 (2023-01-18)
305
+
306
+ - Package `DoraStatus` into dora python package: https://github.com/dora-rs/dora/pull/172
307
+ - Force removal of Pyo3 Object to avoid memory leak: https://github.com/dora-rs/dora/pull/168
308
+ - Bump tokio from 1.21.2 to 1.23.1: https://github.com/dora-rs/dora/pull/171
309
+ - Create a changelog file: https://github.com/dora-rs/dora/pull/174
310
+
311
+ ## v0.1.2 (2022-12-15)
312
+
313
+ - Fix infinite loop in the coordinator: https://github.com/dora-rs/dora/pull/155
314
+ - Simplify the release process: https://github.com/dora-rs/dora/pull/157
315
+ - Use generic linux distribution: https://github.com/dora-rs/dora/pull/159
316
+
317
+ ## v0.1.1 (2022-12-05)
318
+
319
+ This release contains fixes for:
320
+
321
+ - Python linking using pypi release but also a redesigned python thread model within the runtime to avoid deadlock of the `GIL`. This also fix an issue with `patchelf`.
322
+ - A deployment separation for `ubuntu` as the `20.04` version of `dora` and `22.04` version of dora are non-compatible.
323
+ - A better tagging of api for `dora` Rust API.
324
+
325
+ ## v0.1.0 (2022-11-15)
326
+
327
+ This is our first release of `dora-rs`!
328
+
329
+ The current release includes:
330
+
331
+ - `dora-cli` which enables creating, starting and stopping dataflow.
332
+ - `dora-coordinator` which is our control plane.
333
+ - `dora-runtime` which is manage the runtime of operators.
334
+ - `custom-nodes` API which enables bridges from different languages.
NOTICE.md ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ ## Copyright
2
+
3
+ All content is the property of the respective authors or their employers. For more information regarding authorship of content, please consult the listed source code repository logs.
4
+
5
+ ## License
6
+
7
+ This project is licensed under the Apache License, Version 2.0 ([LICENSE](LICENSE) or <http://www.apache.org/licenses/LICENSE-2.0>). Unless you explicitly state otherwise, any contribution intentionally submitted for inclusion in the work by you, as defined in the Apache-2.0 license, shall be licensed as above, without any additional terms or conditions.
apis/c++/node/Cargo.toml ADDED
@@ -0,0 +1,41 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ [package]
2
+ name = "dora-node-api-cxx"
3
+ version.workspace = true
4
+ edition = "2021"
5
+ documentation.workspace = true
6
+ description.workspace = true
7
+ license.workspace = true
8
+
9
+ # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
10
+
11
+ [lib]
12
+ crate-type = ["staticlib"]
13
+
14
+ [features]
15
+ default = ["tracing"]
16
+ tracing = ["dora-node-api/tracing"]
17
+ ros2-bridge = [
18
+ "dep:dora-ros2-bridge",
19
+ "dep:dora-ros2-bridge-msg-gen",
20
+ "dep:rust-format",
21
+ "dep:prettyplease",
22
+ "dep:serde",
23
+ "dep:serde-big-array",
24
+ ]
25
+
26
+ [dependencies]
27
+ cxx = "1.0.73"
28
+ dora-node-api = { workspace = true }
29
+ eyre = "0.6.8"
30
+ dora-ros2-bridge = { workspace = true, optional = true }
31
+ futures-lite = { version = "2.2" }
32
+ serde = { version = "1.0.164", features = ["derive"], optional = true }
33
+ serde-big-array = { version = "0.5.1", optional = true }
34
+
35
+ [build-dependencies]
36
+ cxx-build = "1.0.73"
37
+ dora-ros2-bridge-msg-gen = { workspace = true, optional = true }
38
+ rust-format = { version = "0.3.4", features = [
39
+ "pretty_please",
40
+ ], optional = true }
41
+ prettyplease = { version = "0.1", features = ["verbatim"], optional = true }
apis/c++/node/README.md ADDED
@@ -0,0 +1,321 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Dora Node API for C++
2
+
3
+ Dora supports nodes written in C++ through this API crate.
4
+
5
+ ## Build
6
+
7
+ - Clone the `dora` repository:
8
+ ```bash
9
+ > git clone https://github.com/dora-rs/dora.git
10
+ > cd dora
11
+ ```
12
+ - Build the `dora-node-api-cxx` package:
13
+ ```bash
14
+ cargo build --package dora-node-api-cxx
15
+ ```
16
+ - This will result in `dora-node-api.h` and `dora-node-api.cc` files in the `target/cxxbridge/dora-node-api-cxx` directory.
17
+ - Include the `dora-node-api.h` header file in your source file.
18
+ - Add the `dora-node-api.cc` file to your compile and link steps.
19
+
20
+ ### Build with ROS2 Bridge
21
+
22
+ Dora features an experimental ROS2 Bridge that enables dora nodes to publish and subscribe to ROS2 topics.
23
+ To enable the bridge, use these steps:
24
+
25
+ - Clone the `dora` repository (see above).
26
+ - Source the ROS2 setup files (see [ROS2 docs](https://docs.ros.org/en/rolling/Tutorials/Beginner-CLI-Tools/Configuring-ROS2-Environment.html#source-the-setup-files))
27
+ - Optional: Source package-specific ROS2 setup files if you want to use custom package-specific ROS2 messages in the bridge (see [ROS2 docs](https://docs.ros.org/en/rolling/Tutorials/Beginner-Client-Libraries/Creating-Your-First-ROS2-Package.html#source-the-setup-file))
28
+ - Build the `dora-node-api-cxx` package **with the `ros2-bridge` feature enabled**:
29
+ ```bash
30
+ cargo build --package dora-node-api-cxx --features ros2-bridge
31
+ ```
32
+ - In addition to the `dora-node-api.h` and `dora-node-api.cc` files, this will place a `dora-ros2-bindings.h` and a `dora-ros2-bindings.cc` file in the `target/cxxbridge/dora-node-api-cxx` directory.
33
+ - Include both the `dora-node-api.h` and the `dora-ros2-bindings.h` header files in your source file.
34
+ - Add the `dora-node-api.cc` and `dora-ros2-bindings.cc` files to your compile and link steps.
35
+
36
+ ## Usage
37
+
38
+ The `dora-node-api.h` header provides various functions to interact with Dora.
39
+
40
+ ### Init Dora Node
41
+
42
+ All nodes need to register themselves with Dora at startup.
43
+ To do that, call the `init_dora_node()` function.
44
+ The function returns a `DoraNode` instance, which gives access to dora events and enables sending Dora outputs.
45
+
46
+ ```c++
47
+ auto dora_node = init_dora_node();
48
+ ```
49
+
50
+ ### Receiving Events
51
+
52
+ The `dora_node.events` field is a stream of incoming events.
53
+ To wait for the next incoming event, call `dora_node.events->next()`:
54
+
55
+ ```c++
56
+ auto event = dora_node.events->next();
57
+ ```
58
+
59
+ The `next` function returns an opaque `DoraEvent` type, which cannot be inspected from C++ directly.
60
+ Instead, use the following functions to read and destructure the event:
61
+
62
+ - `event_type(event)` returns a `DoraEventType`, which describes the kind of event. For example, an event could be an input or a stop instruction.
63
+ - when receiving a `DoraEventType::AllInputsClosed`, the node should exit and not call `next` anymore
64
+ - Events of type `DoraEventType::Input` can be downcasted using `event_as_input`:
65
+ ```c++
66
+ auto input = event_as_input(std::move(event));
67
+ ```
68
+ The function returns a `DoraInput` instance, which has an `id` and `data` field.
69
+ - The input `id` can be converted to a C++ string through `std::string(input.id)`.
70
+ - The `data` of inputs is currently of type [`rust::Vec<uint8_t>`](https://cxx.rs/binding/vec.html). Use the provided methods for reading or converting the data.
71
+ - **Note:** In the future, we plan to change the data type to the [Apache Arrow](https://arrow.apache.org/) data format to support typed inputs.
72
+
73
+ ### Sending Outputs
74
+
75
+ Nodes can send outputs using the `send_output` output function and the `dora_node.send_output` field.
76
+ Note that all outputs need to be listed in the dataflow YAML declaration file, otherwise an error will occur.
77
+
78
+ **Example:**
79
+
80
+ ```c++
81
+ // the data you want to send (NOTE: only byte vectors are supported right now)
82
+ std::vector<uint8_t> out_vec{42};
83
+ // create a Rust slice from the output vector
84
+ rust::Slice<const uint8_t> out_slice{out_vec.data(), out_vec.size()};
85
+ // send the slice as output
86
+ auto result = send_output(dora_node.send_output, "output_id", out_slice);
87
+
88
+ // check for errors
89
+ auto error = std::string(result.error);
90
+ if (!error.empty())
91
+ {
92
+ std::cerr << "Error: " << error << std::endl;
93
+ return -1;
94
+ }
95
+ ```
96
+
97
+ ## Using the ROS2 Bridge
98
+
99
+ The `dora-ros2-bindings.h` contains function and struct definitions that allow interacting with ROS2 nodes.
100
+ Currently, the bridge supports publishing and subscribing to ROS2 topics.
101
+ In the future, we plan to support ROS2 services and ROS2 actions as well.
102
+
103
+ ### Initializing the ROS2 Context
104
+
105
+ The first step is to initialize a ROS2 context:
106
+
107
+ ```c++
108
+ auto ros2_context = init_ros2_context();
109
+ ```
110
+
111
+ ### Creating Nodes
112
+
113
+ After initializing a ROS2 context, you can use it to create ROS2 nodes:
114
+
115
+ ```c++
116
+ auto node = ros2_context->new_node("/ros2_demo", "turtle_teleop");
117
+ ```
118
+
119
+ The first argument is the namespace of the node and the second argument is its name.
120
+
121
+ ### Creating Topics
122
+
123
+ After creating a node, you can use one of the `create_topic_<TYPE>` functions to create a topic on it.
124
+ The `<TYPE>` describes the message type that will be sent on the topic.
125
+ The Dora ROS2 bridge automatically creates `create_topic_<TYPE>` functions for all messages types found in the sourced ROS2 environment.
126
+
127
+ ```c++
128
+ auto vel_topic = node->create_topic_geometry_msgs_Twist("/turtle1", "cmd_vel", qos_default());
129
+ ```
130
+
131
+ The first argument is the namespace of the topic and the second argument is its name.
132
+ The third argument is the QoS (quality of service) setting for the topic.
133
+ It can be adjusted as desired, for example:
134
+
135
+ ```c++
136
+ auto qos = qos_default();
137
+ qos.durability = Ros2Durability::Volatile;
138
+ qos.liveliness = Ros2Liveliness::Automatic;
139
+ auto vel_topic = node->create_topic_geometry_msgs_Twist("/turtle1", "cmd_vel", qos);
140
+ ```
141
+
142
+ ### Publish
143
+
144
+ After creating a topic, it is possible to publish messages on it.
145
+ First, create a publisher:
146
+
147
+ ```c++
148
+ auto vel_publisher = node->create_publisher(vel_topic, qos);
149
+ ```
150
+
151
+ The returned publisher is typed by the chosen topic.
152
+ It will only accept messages of the topic's type, otherwise a compile error will occur.
153
+
154
+ After creating a publisher, you can use the `publish` function to publish one or more messages.
155
+ For example:
156
+
157
+ ```c++
158
+ geometry_msgs::Twist twist = {
159
+ .linear = {.x = 1, .y = 0, .z = 0},
160
+ .angular = {.x = 0, .y = 0, .z = 0.5}
161
+ };
162
+ vel_publisher->publish(twist);
163
+ ```
164
+
165
+ The `geometry_msgs::Twist` struct is automatically generated from the sourced ROS2 environment.
166
+ Since the publisher is typed, its `publish` method only accepts `geometry_msgs::Twist` messages.
167
+
168
+
169
+ ### Subscriptions
170
+
171
+ Subscribing to a topic is possible through the `create_subscription` function on nodes:
172
+
173
+ ```c++
174
+ auto pose_topic = node->create_topic_turtlesim_Pose("/turtle1", "pose", qos_default());
175
+ auto pose_subscription = node->create_subscription(pose_topic, qos_default(), event_stream);
176
+ ```
177
+
178
+ The `topic` is the topic you want to subscribe to, created using a `create_topic_<TYPE>` function.
179
+ The second argument is the quality of service setting, which can be customized as described above.
180
+
181
+ The third parameter is the event stream that the received messages should be merged into.
182
+ Multiple subscriptions can be merged into the same event stream.
183
+
184
+ #### Combined Event Streams
185
+
186
+ Combined event streams enable the merging of multiple event streams into one.
187
+ The combined stream will then deliver messages from all sources, in order of arrival.
188
+
189
+ You can create such a event stream from Dora's event stream using the `dora_events_into_combined` function:
190
+
191
+ ```c++
192
+ auto event_stream = dora_events_into_combined(std::move(dora_node.events));
193
+ ```
194
+
195
+ Alternatively, if you don't want to use Dora, you can also create an empty event stream:
196
+
197
+ ```c++
198
+ auto event_stream = empty_combined_events();
199
+ ```
200
+
201
+ **Note:** You should only use `empty_combined_events` if you're running your executable independent of Dora.
202
+ Ignoring the events from the `dora_node.events` channel can result in unintended behavior.
203
+
204
+ #### Receiving Messages from Combined Event Stream
205
+
206
+ The merged event stream will receive all incoming events of the node, including Dora events and ROS2 messages.
207
+ To wait for the next incoming event, use its `next` method:
208
+
209
+ ```c++
210
+ auto event = event_stream.next();
211
+ ```
212
+
213
+ This returns a `event` instance of type `CombinedEvent`, which can be downcasted to Dora events or ROS2 messages.
214
+ To handle an event, you should check it's type and then downcast it:
215
+
216
+ - To check for a Dora event, you can use the `is_dora()` function. If it returns `true`, you can downcast the combined event to a Dora event using the `downcast_dora` function.
217
+ - ROS2 subscriptions support a `matches` function to check whether a combined event is an instance of the respective ROS2 subscription. If it returns true, you can downcast the event to the respective ROS2 message struct using the subscription's `downcast` function.
218
+
219
+ **Example:**
220
+
221
+ ```c++
222
+ if (event.is_dora())
223
+ {
224
+ auto dora_event = downcast_dora(std::move(event));
225
+ // handle dora_event as described above
226
+ auto ty = event_type(dora_event);
227
+ if (ty == DoraEventType::Input)
228
+ {
229
+ auto input = event_as_input(std::move(dora_event));
230
+ // etc
231
+ }
232
+ // .. else if
233
+ }
234
+ else if (pose_subscription->matches(event))
235
+ {
236
+ auto pose = pose_subscription->downcast(std::move(event));
237
+ std::cout << "Received pose x:" << pose.x << ", y:" << pose.y << std::endl;
238
+ }
239
+ else
240
+ {
241
+ std::cout << "received unexpected event" << std::endl;
242
+ }
243
+ ```
244
+
245
+ ### Constants
246
+
247
+ Some ROS2 message definitions define constants, e.g. to specify the values of an enum-like integer field.
248
+ The Dora ROS2 bridge exposes these constants in the generated bindings as functions.
249
+
250
+ For example, the `STATUS_NO_FIX` constant of the [`NavSatStatus` message](https://docs.ros.org/en/jade/api/sensor_msgs/html/msg/NavSatStatus.html) can be accessed as follows:
251
+
252
+ ```c++
253
+ assert((sensor_msgs::const_NavSatStatus_STATUS_NO_FIX() == -1));
254
+ ```
255
+
256
+ (Note: Exposing them as C++ constants is not possible because it's [not supported by `cxx` yet](https://github.com/dtolnay/cxx/issues/1051).)
257
+
258
+ ### Service Clients
259
+
260
+ To create a service client, use one of the `create_client_<TYPE>` functions.
261
+ The `<TYPE>` describes the service type, which specifies the request and response types.
262
+ The Dora ROS2 bridge automatically creates `create_client_<TYPE>` functions for all service types found in the sourced ROS2 environment.
263
+
264
+ ```c++
265
+ auto add_two_ints = node->create_client_example_interfaces_AddTwoInts(
266
+ "/",
267
+ "add_two_ints",
268
+ qos,
269
+ merged_events
270
+ );
271
+ ```
272
+
273
+ - The first argument is the namespace of the service and the second argument is its name.
274
+ - The third argument is the QoS (quality of service) setting for the service.
275
+ It can be set to `qos_default()` or adjusted as desired, for example:
276
+ ```c++
277
+ auto qos = qos_default();
278
+ qos.reliable = true;
279
+ qos.max_blocking_time = 0.1;
280
+ qos.keep_last = 1;
281
+ ```
282
+ - The last argument is the [combined event stream](#combined-event-streams) that the received service responses should be merged into.
283
+
284
+ #### Waiting for the Service
285
+
286
+ In order to achieve reliable service communication, it is recommended to wait until the service is available before sending requests.
287
+ Use the `wait_for_service()` method for that, e.g.:
288
+
289
+ ```c++
290
+ add_two_ints->wait_for_service(node)
291
+ ```
292
+
293
+ The given `node` must be the node on which the service was created.
294
+
295
+ #### Sending Requests
296
+
297
+ To send a request, use the `send_request` method:
298
+
299
+ ```c++
300
+ add_two_ints->send_request(request);
301
+ ```
302
+
303
+ The method sends the request asynchronously without waiting for a response.
304
+ When the response is received, it is automatically sent to the [combined event stream](#combined-event-streams) that was given on client creation.
305
+
306
+ #### Receiving Responses
307
+
308
+ See the [_"Receiving Messages from Combined Event Stream"_](#receiving-messages-from-combined-event-stream) section for how to receive events from the combined event stream.
309
+ To check if a received event is a service response, use the `matches` method.
310
+ If it returns `true`, you can use the `downcast` method to convert the event to the correct service response type.
311
+
312
+ Example:
313
+
314
+ ```c++
315
+ if (add_two_ints->matches(event))
316
+ {
317
+ auto response = add_two_ints->downcast(std::move(event));
318
+ std::cout << "Received sum response with value " << response.sum << std::endl;
319
+ ...
320
+ }
321
+ ```
apis/c++/node/build.rs ADDED
@@ -0,0 +1,159 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ use std::path::{Path, PathBuf};
2
+
3
+ fn main() {
4
+ let mut bridge_files = vec![PathBuf::from("src/lib.rs")];
5
+ #[cfg(feature = "ros2-bridge")]
6
+ bridge_files.push(ros2::generate());
7
+
8
+ let _build = cxx_build::bridges(&bridge_files);
9
+ println!("cargo:rerun-if-changed=src/lib.rs");
10
+
11
+ // rename header files
12
+ let src_dir = target_dir()
13
+ .join("cxxbridge")
14
+ .join("dora-node-api-cxx")
15
+ .join("src");
16
+ let target_dir = src_dir.parent().unwrap();
17
+ std::fs::copy(src_dir.join("lib.rs.h"), target_dir.join("dora-node-api.h")).unwrap();
18
+ std::fs::copy(
19
+ src_dir.join("lib.rs.cc"),
20
+ target_dir.join("dora-node-api.cc"),
21
+ )
22
+ .unwrap();
23
+
24
+ #[cfg(feature = "ros2-bridge")]
25
+ ros2::generate_ros2_message_header(bridge_files.last().unwrap());
26
+
27
+ // to avoid unnecessary `mut` warning
28
+ bridge_files.clear();
29
+ }
30
+
31
+ fn target_dir() -> PathBuf {
32
+ std::env::var("CARGO_TARGET_DIR")
33
+ .map(PathBuf::from)
34
+ .unwrap_or_else(|_| {
35
+ let root = Path::new(env!("CARGO_MANIFEST_DIR"))
36
+ .ancestors()
37
+ .nth(3)
38
+ .unwrap();
39
+ root.join("target")
40
+ })
41
+ }
42
+
43
+ #[cfg(feature = "ros2-bridge")]
44
+ mod ros2 {
45
+ use super::target_dir;
46
+ use std::{
47
+ io::{BufRead, BufReader},
48
+ path::{Component, Path, PathBuf},
49
+ };
50
+
51
+ pub fn generate() -> PathBuf {
52
+ use rust_format::Formatter;
53
+ let paths = ament_prefix_paths();
54
+ let generated = dora_ros2_bridge_msg_gen::gen(paths.as_slice(), true);
55
+ let generated_string = rust_format::PrettyPlease::default()
56
+ .format_tokens(generated)
57
+ .unwrap();
58
+ let out_dir = PathBuf::from(std::env::var("OUT_DIR").unwrap());
59
+ let target_file = out_dir.join("ros2_bindings.rs");
60
+ std::fs::write(&target_file, generated_string).unwrap();
61
+ println!(
62
+ "cargo:rustc-env=ROS2_BINDINGS_PATH={}",
63
+ target_file.display()
64
+ );
65
+
66
+ target_file
67
+ }
68
+
69
+ fn ament_prefix_paths() -> Vec<PathBuf> {
70
+ let ament_prefix_path: String = match std::env::var("AMENT_PREFIX_PATH") {
71
+ Ok(path) => path,
72
+ Err(std::env::VarError::NotPresent) => {
73
+ println!("cargo:warning='AMENT_PREFIX_PATH not set'");
74
+ String::new()
75
+ }
76
+ Err(std::env::VarError::NotUnicode(s)) => {
77
+ panic!(
78
+ "AMENT_PREFIX_PATH is not valid unicode: `{}`",
79
+ s.to_string_lossy()
80
+ );
81
+ }
82
+ };
83
+ println!("cargo:rerun-if-env-changed=AMENT_PREFIX_PATH");
84
+
85
+ let paths: Vec<_> = ament_prefix_path.split(':').map(PathBuf::from).collect();
86
+ for path in &paths {
87
+ println!("cargo:rerun-if-changed={}", path.display());
88
+ }
89
+
90
+ paths
91
+ }
92
+
93
+ pub fn generate_ros2_message_header(source_file: &Path) {
94
+ use std::io::Write as _;
95
+
96
+ let out_dir = source_file.parent().unwrap();
97
+ let relative_path = local_relative_path(&source_file)
98
+ .ancestors()
99
+ .nth(2)
100
+ .unwrap()
101
+ .join("out");
102
+ let header_path = out_dir
103
+ .join("cxxbridge")
104
+ .join("include")
105
+ .join("dora-node-api-cxx")
106
+ .join(&relative_path)
107
+ .join("ros2_bindings.rs.h");
108
+ let code_path = out_dir
109
+ .join("cxxbridge")
110
+ .join("sources")
111
+ .join("dora-node-api-cxx")
112
+ .join(&relative_path)
113
+ .join("ros2_bindings.rs.cc");
114
+
115
+ // copy message files to target directory
116
+ let target_path = target_dir()
117
+ .join("cxxbridge")
118
+ .join("dora-node-api-cxx")
119
+ .join("dora-ros2-bindings.h");
120
+
121
+ std::fs::copy(&header_path, &target_path).unwrap();
122
+ println!("cargo:rerun-if-changed={}", header_path.display());
123
+
124
+ let node_header =
125
+ std::fs::File::open(target_path.with_file_name("dora-node-api.h")).unwrap();
126
+ let mut code_file = std::fs::File::open(&code_path).unwrap();
127
+ println!("cargo:rerun-if-changed={}", code_path.display());
128
+ let mut code_target_file =
129
+ std::fs::File::create(target_path.with_file_name("dora-ros2-bindings.cc")).unwrap();
130
+
131
+ // copy both the node header and the code file to prevent import errors
132
+ let mut header_reader = {
133
+ let mut reader = BufReader::new(node_header);
134
+
135
+ // read first line to skip `#pragma once`, which is not allowed in main files
136
+ let mut first_line = String::new();
137
+ reader.read_line(&mut first_line).unwrap();
138
+ assert_eq!(first_line.trim(), "#pragma once");
139
+
140
+ reader
141
+ };
142
+ std::io::copy(&mut header_reader, &mut code_target_file).unwrap();
143
+ std::io::copy(&mut code_file, &mut code_target_file).unwrap();
144
+ code_target_file.flush().unwrap();
145
+ }
146
+
147
+ // copy from cxx-build source
148
+ fn local_relative_path(path: &Path) -> PathBuf {
149
+ let mut rel_path = PathBuf::new();
150
+ for component in path.components() {
151
+ match component {
152
+ Component::Prefix(_) | Component::RootDir | Component::CurDir => {}
153
+ Component::ParentDir => drop(rel_path.pop()), // noop if empty
154
+ Component::Normal(name) => rel_path.push(name),
155
+ }
156
+ }
157
+ rel_path
158
+ }
159
+ }
apis/c++/node/src/lib.rs ADDED
@@ -0,0 +1,225 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ use std::any::Any;
2
+
3
+ use dora_node_api::{
4
+ self,
5
+ arrow::array::{AsArray, BinaryArray},
6
+ merged::{MergeExternal, MergedEvent},
7
+ Event, EventStream,
8
+ };
9
+ use eyre::bail;
10
+
11
+ #[cfg(feature = "ros2-bridge")]
12
+ use dora_ros2_bridge::{_core, ros2_client};
13
+ use futures_lite::{stream, Stream, StreamExt};
14
+
15
+ #[cxx::bridge]
16
+ #[allow(clippy::needless_lifetimes)]
17
+ mod ffi {
18
+ struct DoraNode {
19
+ events: Box<Events>,
20
+ send_output: Box<OutputSender>,
21
+ }
22
+
23
+ pub enum DoraEventType {
24
+ Stop,
25
+ Input,
26
+ InputClosed,
27
+ Error,
28
+ Unknown,
29
+ AllInputsClosed,
30
+ }
31
+
32
+ struct DoraInput {
33
+ id: String,
34
+ data: Vec<u8>,
35
+ }
36
+
37
+ struct DoraResult {
38
+ error: String,
39
+ }
40
+
41
+ pub struct CombinedEvents {
42
+ events: Box<MergedEvents>,
43
+ }
44
+
45
+ pub struct CombinedEvent {
46
+ event: Box<MergedDoraEvent>,
47
+ }
48
+
49
+ extern "Rust" {
50
+ type Events;
51
+ type OutputSender;
52
+ type DoraEvent;
53
+ type MergedEvents;
54
+ type MergedDoraEvent;
55
+
56
+ fn init_dora_node() -> Result<DoraNode>;
57
+
58
+ fn dora_events_into_combined(events: Box<Events>) -> CombinedEvents;
59
+ fn empty_combined_events() -> CombinedEvents;
60
+ fn next(self: &mut Events) -> Box<DoraEvent>;
61
+ fn next_event(events: &mut Box<Events>) -> Box<DoraEvent>;
62
+ fn event_type(event: &Box<DoraEvent>) -> DoraEventType;
63
+ fn event_as_input(event: Box<DoraEvent>) -> Result<DoraInput>;
64
+ fn send_output(
65
+ output_sender: &mut Box<OutputSender>,
66
+ id: String,
67
+ data: &[u8],
68
+ ) -> DoraResult;
69
+
70
+ fn next(self: &mut CombinedEvents) -> CombinedEvent;
71
+
72
+ fn is_dora(self: &CombinedEvent) -> bool;
73
+ fn downcast_dora(event: CombinedEvent) -> Result<Box<DoraEvent>>;
74
+ }
75
+ }
76
+
77
+ #[cfg(feature = "ros2-bridge")]
78
+ pub mod ros2 {
79
+ pub use dora_ros2_bridge::*;
80
+ include!(env!("ROS2_BINDINGS_PATH"));
81
+ }
82
+
83
+ fn init_dora_node() -> eyre::Result<ffi::DoraNode> {
84
+ let (node, events) = dora_node_api::DoraNode::init_from_env()?;
85
+ let events = Events(events);
86
+ let send_output = OutputSender(node);
87
+
88
+ Ok(ffi::DoraNode {
89
+ events: Box::new(events),
90
+ send_output: Box::new(send_output),
91
+ })
92
+ }
93
+
94
+ pub struct Events(EventStream);
95
+
96
+ impl Events {
97
+ fn next(&mut self) -> Box<DoraEvent> {
98
+ Box::new(DoraEvent(self.0.recv()))
99
+ }
100
+ }
101
+
102
+ fn next_event(events: &mut Box<Events>) -> Box<DoraEvent> {
103
+ events.next()
104
+ }
105
+
106
+ fn dora_events_into_combined(events: Box<Events>) -> ffi::CombinedEvents {
107
+ let events = events.0.map(MergedEvent::Dora);
108
+ ffi::CombinedEvents {
109
+ events: Box::new(MergedEvents {
110
+ events: Some(Box::new(events)),
111
+ next_id: 1,
112
+ }),
113
+ }
114
+ }
115
+
116
+ fn empty_combined_events() -> ffi::CombinedEvents {
117
+ ffi::CombinedEvents {
118
+ events: Box::new(MergedEvents {
119
+ events: Some(Box::new(stream::empty())),
120
+ next_id: 1,
121
+ }),
122
+ }
123
+ }
124
+
125
+ pub struct DoraEvent(Option<Event>);
126
+
127
+ fn event_type(event: &DoraEvent) -> ffi::DoraEventType {
128
+ match &event.0 {
129
+ Some(event) => match event {
130
+ Event::Stop => ffi::DoraEventType::Stop,
131
+ Event::Input { .. } => ffi::DoraEventType::Input,
132
+ Event::InputClosed { .. } => ffi::DoraEventType::InputClosed,
133
+ Event::Error(_) => ffi::DoraEventType::Error,
134
+ _ => ffi::DoraEventType::Unknown,
135
+ },
136
+ None => ffi::DoraEventType::AllInputsClosed,
137
+ }
138
+ }
139
+
140
+ fn event_as_input(event: Box<DoraEvent>) -> eyre::Result<ffi::DoraInput> {
141
+ let Some(Event::Input {
142
+ id,
143
+ metadata: _,
144
+ data,
145
+ }) = event.0
146
+ else {
147
+ bail!("not an input event");
148
+ };
149
+ let data: Option<&BinaryArray> = data.as_binary_opt();
150
+ Ok(ffi::DoraInput {
151
+ id: id.into(),
152
+ data: data.map(|d| d.value(0).to_owned()).unwrap_or_default(),
153
+ })
154
+ }
155
+
156
+ pub struct OutputSender(dora_node_api::DoraNode);
157
+
158
+ fn send_output(sender: &mut Box<OutputSender>, id: String, data: &[u8]) -> ffi::DoraResult {
159
+ let result = sender
160
+ .0
161
+ .send_output_raw(id.into(), Default::default(), data.len(), |out| {
162
+ out.copy_from_slice(data)
163
+ });
164
+ let error = match result {
165
+ Ok(()) => String::new(),
166
+ Err(err) => format!("{err:?}"),
167
+ };
168
+ ffi::DoraResult { error }
169
+ }
170
+
171
+ pub struct MergedEvents {
172
+ events: Option<Box<dyn Stream<Item = MergedEvent<ExternalEvent>> + Unpin>>,
173
+ next_id: u32,
174
+ }
175
+
176
+ impl MergedEvents {
177
+ fn next(&mut self) -> MergedDoraEvent {
178
+ let event = futures_lite::future::block_on(self.events.as_mut().unwrap().next());
179
+ MergedDoraEvent(event)
180
+ }
181
+
182
+ pub fn merge(&mut self, events: impl Stream<Item = Box<dyn Any>> + Unpin + 'static) -> u32 {
183
+ let id = self.next_id;
184
+ self.next_id += 1;
185
+ let events = Box::pin(events.map(move |event| ExternalEvent { event, id }));
186
+
187
+ let inner = self.events.take().unwrap();
188
+ let merged: Box<dyn Stream<Item = _> + Unpin + 'static> =
189
+ Box::new(inner.merge_external(events).map(|event| match event {
190
+ MergedEvent::Dora(event) => MergedEvent::Dora(event),
191
+ MergedEvent::External(event) => MergedEvent::External(event.flatten()),
192
+ }));
193
+ self.events = Some(merged);
194
+
195
+ id
196
+ }
197
+ }
198
+
199
+ impl ffi::CombinedEvents {
200
+ fn next(&mut self) -> ffi::CombinedEvent {
201
+ ffi::CombinedEvent {
202
+ event: Box::new(self.events.next()),
203
+ }
204
+ }
205
+ }
206
+
207
+ pub struct MergedDoraEvent(Option<MergedEvent<ExternalEvent>>);
208
+
209
+ pub struct ExternalEvent {
210
+ pub event: Box<dyn Any>,
211
+ pub id: u32,
212
+ }
213
+
214
+ impl ffi::CombinedEvent {
215
+ fn is_dora(&self) -> bool {
216
+ matches!(&self.event.0, Some(MergedEvent::Dora(_)))
217
+ }
218
+ }
219
+
220
+ fn downcast_dora(event: ffi::CombinedEvent) -> eyre::Result<Box<DoraEvent>> {
221
+ match event.event.0 {
222
+ Some(MergedEvent::Dora(event)) => Ok(Box::new(DoraEvent(Some(event)))),
223
+ _ => eyre::bail!("not an external event"),
224
+ }
225
+ }
apis/c++/operator/Cargo.toml ADDED
@@ -0,0 +1,17 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ [package]
2
+ name = "dora-operator-api-cxx"
3
+ version.workspace = true
4
+ edition = "2021"
5
+ documentation.workspace = true
6
+ description.workspace = true
7
+ license.workspace = true
8
+
9
+ [lib]
10
+ crate-type = ["staticlib"]
11
+
12
+ [dependencies]
13
+ cxx = "1.0.73"
14
+ dora-operator-api = { workspace = true }
15
+
16
+ [build-dependencies]
17
+ cxx-build = "1.0.73"
apis/c++/operator/build.rs ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ fn main() {
2
+ let _ = cxx_build::bridge("src/lib.rs");
3
+ println!("cargo:rerun-if-changed=src/lib.rs");
4
+ }
apis/c++/operator/src/lib.rs ADDED
@@ -0,0 +1,98 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #![cfg(not(test))]
2
+ #![warn(unsafe_op_in_unsafe_fn)]
3
+
4
+ use dora_operator_api::{
5
+ self, register_operator, DoraOperator, DoraOutputSender, DoraStatus, Event, IntoArrow,
6
+ };
7
+ use ffi::DoraSendOutputResult;
8
+
9
+ #[cxx::bridge]
10
+ #[allow(unsafe_op_in_unsafe_fn)]
11
+ mod ffi {
12
+ struct DoraOnInputResult {
13
+ error: String,
14
+ stop: bool,
15
+ }
16
+
17
+ struct DoraSendOutputResult {
18
+ error: String,
19
+ }
20
+
21
+ extern "Rust" {
22
+ type OutputSender<'a, 'b>;
23
+
24
+ fn send_output(sender: &mut OutputSender, id: &str, data: &[u8]) -> DoraSendOutputResult;
25
+ }
26
+
27
+ unsafe extern "C++" {
28
+ include!("operator.h");
29
+
30
+ type Operator;
31
+
32
+ fn new_operator() -> UniquePtr<Operator>;
33
+
34
+ fn on_input(
35
+ op: Pin<&mut Operator>,
36
+ id: &str,
37
+ data: &[u8],
38
+ output_sender: &mut OutputSender,
39
+ ) -> DoraOnInputResult;
40
+ }
41
+ }
42
+
43
+ pub struct OutputSender<'a, 'b>(&'a mut DoraOutputSender<'b>);
44
+
45
+ fn send_output(sender: &mut OutputSender, id: &str, data: &[u8]) -> DoraSendOutputResult {
46
+ let error = sender
47
+ .0
48
+ .send(id.into(), data.to_owned().into_arrow())
49
+ .err()
50
+ .unwrap_or_default();
51
+ DoraSendOutputResult { error }
52
+ }
53
+
54
+ register_operator!(OperatorWrapper);
55
+
56
+ struct OperatorWrapper {
57
+ operator: cxx::UniquePtr<ffi::Operator>,
58
+ }
59
+
60
+ impl Default for OperatorWrapper {
61
+ fn default() -> Self {
62
+ Self {
63
+ operator: ffi::new_operator(),
64
+ }
65
+ }
66
+ }
67
+
68
+ impl DoraOperator for OperatorWrapper {
69
+ fn on_event(
70
+ &mut self,
71
+ event: &Event,
72
+ output_sender: &mut DoraOutputSender,
73
+ ) -> Result<DoraStatus, std::string::String> {
74
+ match event {
75
+ Event::Input { id, data } => {
76
+ let operator = self.operator.as_mut().unwrap();
77
+ let mut output_sender = OutputSender(output_sender);
78
+ let data: &[u8] = data
79
+ .try_into()
80
+ .map_err(|err| format!("expected byte array: {err}"))?;
81
+
82
+ let result = ffi::on_input(operator, id, data, &mut output_sender);
83
+ if result.error.is_empty() {
84
+ Ok(match result.stop {
85
+ false => DoraStatus::Continue,
86
+ true => DoraStatus::Stop,
87
+ })
88
+ } else {
89
+ Err(result.error)
90
+ }
91
+ }
92
+ _ => {
93
+ // ignore other events for now
94
+ Ok(DoraStatus::Continue)
95
+ }
96
+ }
97
+ }
98
+ }
apis/c/node/Cargo.toml ADDED
@@ -0,0 +1,26 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ [package]
2
+ name = "dora-node-api-c"
3
+ version.workspace = true
4
+ edition = "2021"
5
+
6
+ documentation.workspace = true
7
+ description.workspace = true
8
+ license.workspace = true
9
+
10
+ # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
11
+
12
+ [lib]
13
+ crate-type = ["staticlib", "lib"]
14
+
15
+
16
+ [features]
17
+ default = ["tracing"]
18
+ tracing = ["dora-node-api/tracing"]
19
+
20
+ [dependencies]
21
+ eyre = "0.6.8"
22
+ tracing = "0.1.33"
23
+ arrow-array = { workspace = true }
24
+
25
+ [dependencies.dora-node-api]
26
+ workspace = true
apis/c/node/node_api.h ADDED
@@ -0,0 +1,22 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #include <stddef.h>
2
+
3
+ void *init_dora_context_from_env();
4
+ void free_dora_context(void *dora_context);
5
+
6
+ void *dora_next_event(void *dora_context);
7
+ void free_dora_event(void *dora_event);
8
+
9
+ enum DoraEventType
10
+ {
11
+ DoraEventType_Stop,
12
+ DoraEventType_Input,
13
+ DoraEventType_InputClosed,
14
+ DoraEventType_Error,
15
+ DoraEventType_Unknown,
16
+ };
17
+ enum DoraEventType read_dora_event_type(void *dora_event);
18
+
19
+ void read_dora_input_id(void *dora_event, char **out_ptr, size_t *out_len);
20
+ void read_dora_input_data(void *dora_event, char **out_ptr, size_t *out_len);
21
+
22
+ int dora_send_output(void *dora_context, char *id_ptr, size_t id_len, char *data_ptr, size_t data_len);
apis/c/node/src/lib.rs ADDED
@@ -0,0 +1,260 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #![deny(unsafe_op_in_unsafe_fn)]
2
+
3
+ use arrow_array::UInt8Array;
4
+ use dora_node_api::{arrow::array::AsArray, DoraNode, Event, EventStream};
5
+ use eyre::Context;
6
+ use std::{ffi::c_void, ptr, slice};
7
+
8
+ pub const HEADER_NODE_API: &str = include_str!("../node_api.h");
9
+
10
+ struct DoraContext {
11
+ node: &'static mut DoraNode,
12
+ events: EventStream,
13
+ }
14
+
15
+ /// Initializes a dora context from the environment variables that were set by
16
+ /// the dora-coordinator.
17
+ ///
18
+ /// Returns a pointer to the dora context on success. This pointer can be
19
+ /// used to call dora API functions that expect a `context` argument. Any
20
+ /// other use is prohibited. To free the dora context when it is no longer
21
+ /// needed, use the [`free_dora_context`] function.
22
+ ///
23
+ /// On error, a null pointer is returned.
24
+ #[no_mangle]
25
+ pub extern "C" fn init_dora_context_from_env() -> *mut c_void {
26
+ let context = || {
27
+ let (node, events) = DoraNode::init_from_env()?;
28
+ let node = Box::leak(Box::new(node));
29
+ Result::<_, eyre::Report>::Ok(DoraContext { node, events })
30
+ };
31
+ let context = match context().context("failed to initialize node") {
32
+ Ok(n) => n,
33
+ Err(err) => {
34
+ let err: eyre::Error = err;
35
+ tracing::error!("{err:?}");
36
+ return ptr::null_mut();
37
+ }
38
+ };
39
+
40
+ Box::into_raw(Box::new(context)).cast()
41
+ }
42
+
43
+ /// Frees the given dora context.
44
+ ///
45
+ /// ## Safety
46
+ ///
47
+ /// Only pointers created through [`init_dora_context_from_env`] are allowed
48
+ /// as arguments. Each context pointer must be freed exactly once. After
49
+ /// freeing, the pointer must not be used anymore.
50
+ #[no_mangle]
51
+ pub unsafe extern "C" fn free_dora_context(context: *mut c_void) {
52
+ let context: Box<DoraContext> = unsafe { Box::from_raw(context.cast()) };
53
+ // drop all fields except for `node`
54
+ let DoraContext { node, .. } = *context;
55
+ // convert the `'static` reference back to a Box, then drop it
56
+ let _ = unsafe { Box::from_raw(node as *const DoraNode as *mut DoraNode) };
57
+ }
58
+
59
+ /// Waits for the next incoming event for the node.
60
+ ///
61
+ /// Returns a pointer to the event on success. This pointer must not be used
62
+ /// directly. Instead, use the `read_dora_event_*` functions to read out the
63
+ /// type and payload of the event. When the event is not needed anymore, use
64
+ /// [`free_dora_event`] to free it again.
65
+ ///
66
+ /// Returns a null pointer when all event streams were closed. This means that
67
+ /// no more event will be available. Nodes typically react by stopping.
68
+ ///
69
+ /// ## Safety
70
+ ///
71
+ /// The `context` argument must be a dora context created through
72
+ /// [`init_dora_context_from_env`]. The context must be still valid, i.e., not
73
+ /// freed yet.
74
+ #[no_mangle]
75
+ pub unsafe extern "C" fn dora_next_event(context: *mut c_void) -> *mut c_void {
76
+ let context: &mut DoraContext = unsafe { &mut *context.cast() };
77
+ match context.events.recv() {
78
+ Some(event) => Box::into_raw(Box::new(event)).cast(),
79
+ None => ptr::null_mut(),
80
+ }
81
+ }
82
+
83
+ /// Reads out the type of the given event.
84
+ ///
85
+ /// ## Safety
86
+ ///
87
+ /// The `event` argument must be a dora event received through
88
+ /// [`dora_next_event`]. The event must be still valid, i.e., not
89
+ /// freed yet.
90
+ #[no_mangle]
91
+ pub unsafe extern "C" fn read_dora_event_type(event: *const ()) -> EventType {
92
+ let event: &Event = unsafe { &*event.cast() };
93
+ match event {
94
+ Event::Stop => EventType::Stop,
95
+ Event::Input { .. } => EventType::Input,
96
+ Event::InputClosed { .. } => EventType::InputClosed,
97
+ Event::Error(_) => EventType::Error,
98
+ _ => EventType::Unknown,
99
+ }
100
+ }
101
+
102
+ #[repr(C)]
103
+ pub enum EventType {
104
+ Stop,
105
+ Input,
106
+ InputClosed,
107
+ Error,
108
+ Unknown,
109
+ }
110
+
111
+ /// Reads out the ID of the given input event.
112
+ ///
113
+ /// Writes the `out_ptr` and `out_len` with the start pointer and length of the
114
+ /// ID string of the input. The ID is guaranteed to be valid UTF-8.
115
+ ///
116
+ /// Writes a null pointer and length `0` if the given event is not an input event.
117
+ ///
118
+ /// ## Safety
119
+ ///
120
+ /// The `event` argument must be a dora event received through
121
+ /// [`dora_next_event`]. The event must be still valid, i.e., not
122
+ /// freed yet. The returned `out_ptr` must not be used after
123
+ /// freeing the `event`, since it points directly into the event's
124
+ /// memory.
125
+ #[no_mangle]
126
+ pub unsafe extern "C" fn read_dora_input_id(
127
+ event: *const (),
128
+ out_ptr: *mut *const u8,
129
+ out_len: *mut usize,
130
+ ) {
131
+ let event: &Event = unsafe { &*event.cast() };
132
+ match event {
133
+ Event::Input { id, .. } => {
134
+ let id = id.as_str().as_bytes();
135
+ let ptr = id.as_ptr();
136
+ let len = id.len();
137
+ unsafe {
138
+ *out_ptr = ptr;
139
+ *out_len = len;
140
+ }
141
+ }
142
+ _ => unsafe {
143
+ *out_ptr = ptr::null();
144
+ *out_len = 0;
145
+ },
146
+ }
147
+ }
148
+
149
+ /// Reads out the data of the given input event.
150
+ ///
151
+ /// Writes the `out_ptr` and `out_len` with the start pointer and length of the
152
+ /// input's data array. The data array is a raw byte array, whose format
153
+ /// depends on the source operator/node.
154
+ ///
155
+ /// Writes a null pointer and length `0` if the given event is not an input event
156
+ /// or when an input event has no associated data.
157
+ ///
158
+ /// ## Safety
159
+ ///
160
+ /// The `event` argument must be a dora event received through
161
+ /// [`dora_next_event`]. The event must be still valid, i.e., not
162
+ /// freed yet. The returned `out_ptr` must not be used after
163
+ /// freeing the `event`, since it points directly into the event's
164
+ /// memory.
165
+ #[no_mangle]
166
+ pub unsafe extern "C" fn read_dora_input_data(
167
+ event: *const (),
168
+ out_ptr: *mut *const u8,
169
+ out_len: *mut usize,
170
+ ) {
171
+ let event: &Event = unsafe { &*event.cast() };
172
+ match event {
173
+ Event::Input { data, metadata, .. } => match metadata.type_info.data_type {
174
+ dora_node_api::arrow::datatypes::DataType::UInt8 => {
175
+ let array: &UInt8Array = data.as_primitive();
176
+ let ptr = array.values().as_ptr();
177
+ unsafe {
178
+ *out_ptr = ptr;
179
+ *out_len = metadata.type_info.len;
180
+ }
181
+ }
182
+ dora_node_api::arrow::datatypes::DataType::Null => unsafe {
183
+ *out_ptr = ptr::null();
184
+ *out_len = 0;
185
+ },
186
+ _ => {
187
+ todo!("dora C++ Node does not yet support higher level type of arrow. Only UInt8.
188
+ The ultimate solution should be based on arrow FFI interface. Feel free to contribute :)")
189
+ }
190
+ },
191
+ _ => unsafe {
192
+ *out_ptr = ptr::null();
193
+ *out_len = 0;
194
+ },
195
+ }
196
+ }
197
+
198
+ /// Frees the given dora event.
199
+ ///
200
+ /// ## Safety
201
+ ///
202
+ /// Only pointers created through [`dora_next_event`] are allowed
203
+ /// as arguments. Each context pointer must be freed exactly once. After
204
+ /// freeing, the pointer and all derived pointers must not be used anymore.
205
+ /// This also applies to the `read_dora_event_*` functions, which return
206
+ /// pointers into the original event structure.
207
+ #[no_mangle]
208
+ pub unsafe extern "C" fn free_dora_event(event: *mut c_void) {
209
+ let _: Box<Event> = unsafe { Box::from_raw(event.cast()) };
210
+ }
211
+
212
+ /// Sends the given output to subscribed dora nodes/operators.
213
+ ///
214
+ /// The `id_ptr` and `id_len` fields must be the start pointer and length of an
215
+ /// UTF8-encoded string. The ID string must correspond to one of the node's
216
+ /// outputs specified in the dataflow YAML file.
217
+ ///
218
+ /// The `data_ptr` and `data_len` fields must be the start pointer and length
219
+ /// a byte array. The dora API sends this data as-is, without any processing.
220
+ ///
221
+ /// ## Safety
222
+ ///
223
+ /// - The `id_ptr` and `id_len` fields must be the start pointer and length of an
224
+ /// UTF8-encoded string.
225
+ /// - The `data_ptr` and `data_len` fields must be the start pointer and length
226
+ /// a byte array.
227
+ #[no_mangle]
228
+ pub unsafe extern "C" fn dora_send_output(
229
+ context: *mut c_void,
230
+ id_ptr: *const u8,
231
+ id_len: usize,
232
+ data_ptr: *const u8,
233
+ data_len: usize,
234
+ ) -> isize {
235
+ match unsafe { try_send_output(context, id_ptr, id_len, data_ptr, data_len) } {
236
+ Ok(()) => 0,
237
+ Err(err) => {
238
+ tracing::error!("{err:?}");
239
+ -1
240
+ }
241
+ }
242
+ }
243
+
244
+ unsafe fn try_send_output(
245
+ context: *mut c_void,
246
+ id_ptr: *const u8,
247
+ id_len: usize,
248
+ data_ptr: *const u8,
249
+ data_len: usize,
250
+ ) -> eyre::Result<()> {
251
+ let context: &mut DoraContext = unsafe { &mut *context.cast() };
252
+ let id = std::str::from_utf8(unsafe { slice::from_raw_parts(id_ptr, id_len) })?;
253
+ let output_id = id.to_owned().into();
254
+ let data = unsafe { slice::from_raw_parts(data_ptr, data_len) };
255
+ context
256
+ .node
257
+ .send_output_raw(output_id, Default::default(), data.len(), |out| {
258
+ out.copy_from_slice(data);
259
+ })
260
+ }
apis/c/operator/Cargo.toml ADDED
@@ -0,0 +1,16 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ [package]
2
+ name = "dora-operator-api-c"
3
+ version.workspace = true
4
+ edition = "2021"
5
+ description = "C API implementation for Dora Operator"
6
+ documentation.workspace = true
7
+ license.workspace = true
8
+
9
+ [lib]
10
+ crate-type = ["staticlib", "lib"]
11
+
12
+ [dependencies]
13
+ dora-operator-api-types = { workspace = true }
14
+
15
+ [build-dependencies]
16
+ dora-operator-api-types = { workspace = true }
apis/c/operator/build.rs ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+ use std::path::Path;
2
+
3
+ fn main() {
4
+ dora_operator_api_types::generate_headers(Path::new("operator_types.h"))
5
+ .expect("failed to create operator_types.h");
6
+
7
+ // don't rebuild on changes (otherwise we rebuild on every run as we're
8
+ // writing the `operator_types.h` file; cargo will still rerun this script
9
+ // when the `dora_operator_api_types` crate changes)
10
+ println!("cargo:rerun-if-changed=build.rs");
11
+ }
apis/c/operator/operator_api.h ADDED
@@ -0,0 +1,36 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #ifndef __RUST_DORA_OPERATOR_API_C_WRAPPER__
2
+ #define __RUST_DORA_OPERATOR_API_C_WRAPPER__
3
+ #ifdef __cplusplus
4
+ extern "C"
5
+ {
6
+ #endif
7
+
8
+ #include <stddef.h>
9
+ #include "operator_types.h"
10
+
11
+ #ifdef _WIN32
12
+ #define EXPORT __declspec(dllexport)
13
+ #else
14
+ #define EXPORT __attribute__((visibility("default")))
15
+ #endif
16
+
17
+ EXPORT DoraInitResult_t dora_init_operator(void);
18
+
19
+ EXPORT DoraResult_t dora_drop_operator(void *operator_context);
20
+
21
+ EXPORT OnEventResult_t dora_on_event(
22
+ RawEvent_t *event,
23
+ const SendOutput_t *send_output,
24
+ void *operator_context);
25
+
26
+ static void __dora_type_assertions()
27
+ {
28
+ DoraInitOperator_t __dora_init_operator = {.init_operator = dora_init_operator};
29
+ DoraDropOperator_t __dora_drop_operator = {.drop_operator = dora_drop_operator};
30
+ DoraOnEvent_t __dora_on_event = {.on_event = dora_on_event};
31
+ }
32
+ #ifdef __cplusplus
33
+ } /* extern \"C\" */
34
+ #endif
35
+
36
+ #endif /* __RUST_DORA_OPERATOR_API_C_WRAPPER__ */
apis/c/operator/operator_types.h ADDED
@@ -0,0 +1,180 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /*! \file */
2
+ /*******************************************
3
+ * *
4
+ * File auto-generated by `::safer_ffi`. *
5
+ * *
6
+ * Do not manually edit this file. *
7
+ * *
8
+ *******************************************/
9
+
10
+ #ifndef __RUST_DORA_OPERATOR_API_C__
11
+ #define __RUST_DORA_OPERATOR_API_C__
12
+ #ifdef __cplusplus
13
+ extern "C" {
14
+ #endif
15
+
16
+
17
+ #include <stddef.h>
18
+ #include <stdint.h>
19
+
20
+ /** \brief
21
+ * Same as [`Vec<T>`][`rust::Vec`], but with guaranteed `#[repr(C)]` layout
22
+ */
23
+ typedef struct Vec_uint8 {
24
+ /** <No documentation available> */
25
+ uint8_t * ptr;
26
+
27
+ /** <No documentation available> */
28
+ size_t len;
29
+
30
+ /** <No documentation available> */
31
+ size_t cap;
32
+ } Vec_uint8_t;
33
+
34
+ /** <No documentation available> */
35
+ typedef struct DoraResult {
36
+ /** <No documentation available> */
37
+ Vec_uint8_t * error;
38
+ } DoraResult_t;
39
+
40
+ /** <No documentation available> */
41
+ typedef struct DoraDropOperator {
42
+ /** <No documentation available> */
43
+ DoraResult_t (*drop_operator)(void *);
44
+ } DoraDropOperator_t;
45
+
46
+ /** <No documentation available> */
47
+ typedef struct DoraInitResult {
48
+ /** <No documentation available> */
49
+ DoraResult_t result;
50
+
51
+ /** <No documentation available> */
52
+ void * operator_context;
53
+ } DoraInitResult_t;
54
+
55
+ /** <No documentation available> */
56
+ typedef struct DoraInitOperator {
57
+ /** <No documentation available> */
58
+ DoraInitResult_t (*init_operator)(void);
59
+ } DoraInitOperator_t;
60
+
61
+ /** <No documentation available> */
62
+ /** \remark Has the same ABI as `uint8_t` **/
63
+ #ifdef DOXYGEN
64
+ typedef
65
+ #endif
66
+ enum DoraStatus {
67
+ /** <No documentation available> */
68
+ DORA_STATUS_CONTINUE = 0,
69
+ /** <No documentation available> */
70
+ DORA_STATUS_STOP = 1,
71
+ /** <No documentation available> */
72
+ DORA_STATUS_STOP_ALL = 2,
73
+ }
74
+ #ifndef DOXYGEN
75
+ ; typedef uint8_t
76
+ #endif
77
+ DoraStatus_t;
78
+
79
+ /** <No documentation available> */
80
+ typedef struct OnEventResult {
81
+ /** <No documentation available> */
82
+ DoraResult_t result;
83
+
84
+ /** <No documentation available> */
85
+ DoraStatus_t status;
86
+ } OnEventResult_t;
87
+
88
+ /** <No documentation available> */
89
+ typedef struct Input Input_t;
90
+
91
+
92
+ #include <stdbool.h>
93
+
94
+ /** <No documentation available> */
95
+ typedef struct RawEvent {
96
+ /** <No documentation available> */
97
+ Input_t * input;
98
+
99
+ /** <No documentation available> */
100
+ Vec_uint8_t input_closed;
101
+
102
+ /** <No documentation available> */
103
+ bool stop;
104
+
105
+ /** <No documentation available> */
106
+ Vec_uint8_t error;
107
+ } RawEvent_t;
108
+
109
+ /** <No documentation available> */
110
+ typedef struct Output Output_t;
111
+
112
+ /** \brief
113
+ * `Arc<dyn Send + Sync + Fn(A1) -> Ret>`
114
+ */
115
+ typedef struct ArcDynFn1_DoraResult_Output {
116
+ /** <No documentation available> */
117
+ void * env_ptr;
118
+
119
+ /** <No documentation available> */
120
+ DoraResult_t (*call)(void *, Output_t);
121
+
122
+ /** <No documentation available> */
123
+ void (*release)(void *);
124
+
125
+ /** <No documentation available> */
126
+ void (*retain)(void *);
127
+ } ArcDynFn1_DoraResult_Output_t;
128
+
129
+ /** <No documentation available> */
130
+ typedef struct SendOutput {
131
+ /** <No documentation available> */
132
+ ArcDynFn1_DoraResult_Output_t send_output;
133
+ } SendOutput_t;
134
+
135
+ /** <No documentation available> */
136
+ typedef struct DoraOnEvent {
137
+ /** <No documentation available> */
138
+ OnEventResult_t (*on_event)(RawEvent_t *, SendOutput_t const *, void *);
139
+ } DoraOnEvent_t;
140
+
141
+ /** <No documentation available> */
142
+ typedef struct Metadata {
143
+ /** <No documentation available> */
144
+ Vec_uint8_t open_telemetry_context;
145
+ } Metadata_t;
146
+
147
+ /** <No documentation available> */
148
+ void
149
+ dora_free_data (
150
+ Vec_uint8_t _data);
151
+
152
+ /** <No documentation available> */
153
+ void
154
+ dora_free_input_id (
155
+ char * _input_id);
156
+
157
+ /** <No documentation available> */
158
+ Vec_uint8_t
159
+ dora_read_data (
160
+ Input_t * input);
161
+
162
+ /** <No documentation available> */
163
+ char *
164
+ dora_read_input_id (
165
+ Input_t const * input);
166
+
167
+ /** <No documentation available> */
168
+ DoraResult_t
169
+ dora_send_operator_output (
170
+ SendOutput_t const * send_output,
171
+ char const * id,
172
+ uint8_t const * data_ptr,
173
+ size_t data_len);
174
+
175
+
176
+ #ifdef __cplusplus
177
+ } /* extern \"C\" */
178
+ #endif
179
+
180
+ #endif /* __RUST_DORA_OPERATOR_API_C__ */
apis/c/operator/src/lib.rs ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ pub const HEADER_OPERATOR_API: &str = include_str!("../operator_api.h");
2
+ pub const HEADER_OPERATOR_TYPES: &str = include_str!("../operator_types.h");
3
+
4
+ pub use dora_operator_api_types;
apis/python/node/Cargo.toml ADDED
@@ -0,0 +1,31 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ [package]
2
+ version.workspace = true
3
+ name = "dora-node-api-python"
4
+ edition = "2021"
5
+ documentation.workspace = true
6
+ description.workspace = true
7
+ license.workspace = true
8
+
9
+ # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
10
+
11
+ [features]
12
+ default = ["tracing", "telemetry"]
13
+ tracing = ["dora-node-api/tracing"]
14
+ telemetry = ["dora-runtime/telemetry"]
15
+
16
+ [dependencies]
17
+ dora-node-api = { workspace = true }
18
+ dora-operator-api-python = { workspace = true }
19
+ pyo3 = { workspace = true, features = ["eyre", "abi3-py37"] }
20
+ eyre = "0.6"
21
+ serde_yaml = "0.8.23"
22
+ flume = "0.10.14"
23
+ dora-runtime = { workspace = true, features = ["tracing", "metrics", "python"] }
24
+ arrow = { workspace = true, features = ["pyarrow"] }
25
+ pythonize = { workspace = true }
26
+ futures = "0.3.28"
27
+ dora-ros2-bridge-python = { workspace = true }
28
+
29
+ [lib]
30
+ name = "dora"
31
+ crate-type = ["cdylib"]
apis/python/node/README.md ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ This crate corresponds to the Node API for Dora.
2
+
3
+ ## Building
4
+
5
+ To build the Python module for development:
6
+
7
+ ```bash
8
+ python -m venv .env
9
+ source .env/bin/activate
10
+ pip install maturin
11
+ maturin develop
12
+ ```
13
+
14
+ ## Type hinting
15
+
16
+ Type hinting requires to run a second step
17
+
18
+ ```bash
19
+ python generate_stubs.py dora dora/__init__.pyi
20
+ maturin develop
21
+ ```
apis/python/node/dora/__init__.py ADDED
@@ -0,0 +1,42 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ # dora-rs
3
+ This is the dora python client for interacting with dora dataflow.
4
+ You can install it via:
5
+ ```bash
6
+ pip install dora-rs
7
+ ```
8
+ """
9
+
10
+ from enum import Enum
11
+
12
+ from .dora import *
13
+
14
+ from .dora import (
15
+ Node,
16
+ PyEvent,
17
+ Ros2Context,
18
+ Ros2Node,
19
+ Ros2NodeOptions,
20
+ Ros2Topic,
21
+ Ros2Publisher,
22
+ Ros2Subscription,
23
+ start_runtime,
24
+ __version__,
25
+ __author__,
26
+ Ros2QosPolicies,
27
+ Ros2Durability,
28
+ Ros2Liveliness,
29
+ )
30
+
31
+
32
+ class DoraStatus(Enum):
33
+ """Dora status to indicate if operator `on_input` loop
34
+ should be stopped.
35
+ Args:
36
+ Enum (u8): Status signaling to dora operator to
37
+ stop or continue the operator.
38
+ """
39
+
40
+ CONTINUE = 0
41
+ STOP = 1
42
+ STOP_ALL = 2
apis/python/node/dora/__init__.pyi ADDED
@@ -0,0 +1,320 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import dora
2
+ import pyarrow
3
+ import typing
4
+
5
+ @typing.final
6
+ class Enum:
7
+ """Generic enumeration.
8
+
9
+ Derive from this class to define new enumerations."""
10
+ __members__: mappingproxy = ...
11
+
12
+ @typing.final
13
+ class Node:
14
+ """The custom node API lets you integrate `dora` into your application.
15
+ It allows you to retrieve input and send output in any fashion you want.
16
+
17
+ Use with:
18
+
19
+ ```python
20
+ from dora import Node
21
+
22
+ node = Node()
23
+ ```"""
24
+
25
+ def __init__(self) -> None:
26
+ """The custom node API lets you integrate `dora` into your application.
27
+ It allows you to retrieve input and send output in any fashion you want.
28
+
29
+ Use with:
30
+
31
+ ```python
32
+ from dora import Node
33
+
34
+ node = Node()
35
+ ```"""
36
+
37
+ def dataflow_descriptor(self) -> dict:
38
+ """Returns the full dataflow descriptor that this node is part of.
39
+
40
+ This method returns the parsed dataflow YAML file."""
41
+
42
+ def dataflow_id(self) -> str:
43
+ """Returns the dataflow id."""
44
+
45
+ def merge_external_events(self, subscription: dora.Ros2Subscription) -> None:
46
+ """Merge an external event stream with dora main loop.
47
+ This currently only work with ROS2."""
48
+
49
+ def next(self, timeout: float=None) -> dora.PyEvent:
50
+ """`.next()` gives you the next input that the node has received.
51
+ It blocks until the next event becomes available.
52
+ You can use timeout in seconds to return if no input is available.
53
+ It will return `None` when all senders has been dropped.
54
+
55
+ ```python
56
+ event = node.next()
57
+ ```
58
+
59
+ You can also iterate over the event stream with a loop
60
+
61
+ ```python
62
+ for event in node:
63
+ match event["type"]:
64
+ case "INPUT":
65
+ match event["id"]:
66
+ case "image":
67
+ ```"""
68
+
69
+ def send_output(self, output_id: str, data: pyarrow.Array, metadata: dict=None) -> None:
70
+ """`send_output` send data from the node.
71
+
72
+ ```python
73
+ Args:
74
+ output_id: str,
75
+ data: pyarrow.Array,
76
+ metadata: Option[Dict],
77
+ ```
78
+
79
+ ex:
80
+
81
+ ```python
82
+ node.send_output("string", b"string", {"open_telemetry_context": "7632e76"})
83
+ ```"""
84
+
85
+ def __iter__(self) -> typing.Any:
86
+ """Implement iter(self)."""
87
+
88
+ def __next__(self) -> typing.Any:
89
+ """Implement next(self)."""
90
+
91
+ @typing.final
92
+ class PyEvent:
93
+ """Dora Event"""
94
+
95
+ def inner(self):...
96
+
97
+ def __getitem__(self, key: typing.Any) -> typing.Any:
98
+ """Return self[key]."""
99
+
100
+ @typing.final
101
+ class Ros2Context:
102
+ """ROS2 Context holding all messages definition for receiving and sending messages to ROS2.
103
+
104
+ By default, Ros2Context will use env `AMENT_PREFIX_PATH` to search for message definition.
105
+
106
+ AMENT_PREFIX_PATH folder structure should be the following:
107
+
108
+ - For messages: <namespace>/msg/<name>.msg
109
+ - For services: <namespace>/srv/<name>.srv
110
+
111
+ You can also use `ros_paths` if you don't want to use env variable.
112
+
113
+ warning::
114
+ dora Ros2 bridge functionality is considered **unstable**. It may be changed
115
+ at any point without it being considered a breaking change.
116
+
117
+ ```python
118
+ context = Ros2Context()
119
+ ```"""
120
+
121
+ def __init__(self, ros_paths: typing.List[str]=None) -> None:
122
+ """ROS2 Context holding all messages definition for receiving and sending messages to ROS2.
123
+
124
+ By default, Ros2Context will use env `AMENT_PREFIX_PATH` to search for message definition.
125
+
126
+ AMENT_PREFIX_PATH folder structure should be the following:
127
+
128
+ - For messages: <namespace>/msg/<name>.msg
129
+ - For services: <namespace>/srv/<name>.srv
130
+
131
+ You can also use `ros_paths` if you don't want to use env variable.
132
+
133
+ warning::
134
+ dora Ros2 bridge functionality is considered **unstable**. It may be changed
135
+ at any point without it being considered a breaking change.
136
+
137
+ ```python
138
+ context = Ros2Context()
139
+ ```"""
140
+
141
+ def new_node(self, name: str, namespace: str, options: dora.Ros2NodeOptions) -> dora.Ros2Node:
142
+ """Create a new ROS2 node
143
+
144
+ ```python
145
+ ros2_node = ros2_context.new_node(
146
+ "turtle_teleop",
147
+ "/ros2_demo",
148
+ Ros2NodeOptions(rosout=True),
149
+ )
150
+ ```
151
+
152
+ warning::
153
+ dora Ros2 bridge functionality is considered **unstable**. It may be changed
154
+ at any point without it being considered a breaking change."""
155
+
156
+ @typing.final
157
+ class Ros2Durability:
158
+ """DDS 2.2.3.4 DURABILITY"""
159
+
160
+ def __eq__(self, value: typing.Any) -> bool:
161
+ """Return self==value."""
162
+
163
+ def __ge__(self, value: typing.Any) -> bool:
164
+ """Return self>=value."""
165
+
166
+ def __gt__(self, value: typing.Any) -> bool:
167
+ """Return self>value."""
168
+
169
+ def __int__(self) -> None:
170
+ """int(self)"""
171
+
172
+ def __le__(self, value: typing.Any) -> bool:
173
+ """Return self<=value."""
174
+
175
+ def __lt__(self, value: typing.Any) -> bool:
176
+ """Return self<value."""
177
+
178
+ def __ne__(self, value: typing.Any) -> bool:
179
+ """Return self!=value."""
180
+
181
+ def __repr__(self) -> str:
182
+ """Return repr(self)."""
183
+ Persistent: Ros2Durability = ...
184
+ Transient: Ros2Durability = ...
185
+ TransientLocal: Ros2Durability = ...
186
+ Volatile: Ros2Durability = ...
187
+
188
+ @typing.final
189
+ class Ros2Liveliness:
190
+ """DDS 2.2.3.11 LIVELINESS"""
191
+
192
+ def __eq__(self, value: typing.Any) -> bool:
193
+ """Return self==value."""
194
+
195
+ def __ge__(self, value: typing.Any) -> bool:
196
+ """Return self>=value."""
197
+
198
+ def __gt__(self, value: typing.Any) -> bool:
199
+ """Return self>value."""
200
+
201
+ def __int__(self) -> None:
202
+ """int(self)"""
203
+
204
+ def __le__(self, value: typing.Any) -> bool:
205
+ """Return self<=value."""
206
+
207
+ def __lt__(self, value: typing.Any) -> bool:
208
+ """Return self<value."""
209
+
210
+ def __ne__(self, value: typing.Any) -> bool:
211
+ """Return self!=value."""
212
+
213
+ def __repr__(self) -> str:
214
+ """Return repr(self)."""
215
+ Automatic: Ros2Liveliness = ...
216
+ ManualByParticipant: Ros2Liveliness = ...
217
+ ManualByTopic: Ros2Liveliness = ...
218
+
219
+ @typing.final
220
+ class Ros2Node:
221
+ """ROS2 Node
222
+
223
+ warnings::
224
+ - dora Ros2 bridge functionality is considered **unstable**. It may be changed
225
+ at any point without it being considered a breaking change.
226
+ - There's a known issue about ROS2 nodes not being discoverable by ROS2
227
+ See: https://github.com/jhelovuo/ros2-client/issues/4"""
228
+
229
+ def create_publisher(self, topic: dora.Ros2Topic, qos: dora.Ros2QosPolicies=None) -> dora.Ros2Publisher:
230
+ """Create a ROS2 publisher
231
+
232
+ ```python
233
+ pose_publisher = ros2_node.create_publisher(turtle_pose_topic)
234
+ ```
235
+ warnings:
236
+ - dora Ros2 bridge functionality is considered **unstable**. It may be changed
237
+ at any point without it being considered a breaking change."""
238
+
239
+ def create_subscription(self, topic: dora.Ros2Topic, qos: dora.Ros2QosPolicies=None) -> dora.Ros2Subscription:
240
+ """Create a ROS2 subscription
241
+
242
+ ```python
243
+ pose_reader = ros2_node.create_subscription(turtle_pose_topic)
244
+ ```
245
+
246
+ warnings:
247
+ - dora Ros2 bridge functionality is considered **unstable**. It may be changed
248
+ at any point without it being considered a breaking change."""
249
+
250
+ def create_topic(self, name: str, message_type: str, qos: dora.Ros2QosPolicies) -> dora.Ros2Topic:
251
+ """Create a ROS2 topic to connect to.
252
+
253
+ ```python
254
+ turtle_twist_topic = ros2_node.create_topic(
255
+ "/turtle1/cmd_vel", "geometry_msgs/Twist", topic_qos
256
+ )
257
+ ```"""
258
+
259
+ @typing.final
260
+ class Ros2NodeOptions:
261
+ """ROS2 Node Options"""
262
+
263
+ def __init__(self, rosout: bool=None) -> None:
264
+ """ROS2 Node Options"""
265
+
266
+ @typing.final
267
+ class Ros2Publisher:
268
+ """ROS2 Publisher
269
+
270
+ warnings:
271
+ - dora Ros2 bridge functionality is considered **unstable**. It may be changed
272
+ at any point without it being considered a breaking change."""
273
+
274
+ def publish(self, data: pyarrow.Array) -> None:
275
+ """Publish a message into ROS2 topic.
276
+
277
+ Remember that the data format should respect the structure of the ROS2 message using an arrow Structure.
278
+
279
+ ex:
280
+ ```python
281
+ gripper_command.publish(
282
+ pa.array(
283
+ [
284
+ {
285
+ "name": "gripper",
286
+ "cmd": np.float32(5),
287
+ }
288
+ ]
289
+ ),
290
+ )
291
+ ```"""
292
+
293
+ @typing.final
294
+ class Ros2QosPolicies:
295
+ """ROS2 QoS Policy"""
296
+
297
+ def __init__(self, durability: dora.Ros2Durability=None, liveliness: dora.Ros2Liveliness=None, reliable: bool=None, keep_all: bool=None, lease_duration: float=None, max_blocking_time: float=None, keep_last: int=None) -> dora.Ros2QoSPolicies:
298
+ """ROS2 QoS Policy"""
299
+
300
+ @typing.final
301
+ class Ros2Subscription:
302
+ """ROS2 Subscription
303
+
304
+
305
+ warnings:
306
+ - dora Ros2 bridge functionality is considered **unstable**. It may be changed
307
+ at any point without it being considered a breaking change."""
308
+
309
+ def next(self):...
310
+
311
+ @typing.final
312
+ class Ros2Topic:
313
+ """ROS2 Topic
314
+
315
+ warnings:
316
+ - dora Ros2 bridge functionality is considered **unstable**. It may be changed
317
+ at any point without it being considered a breaking change."""
318
+
319
+ def start_runtime() -> None:
320
+ """Start a runtime for Operators"""
apis/python/node/dora/__pycache__/__init__.cpython-38.pyc ADDED
Binary file (1.09 kB). View file
 
apis/python/node/generate_stubs.py ADDED
@@ -0,0 +1,517 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import argparse
2
+ import ast
3
+ import importlib
4
+ import inspect
5
+ import logging
6
+ import re
7
+ import subprocess
8
+ from functools import reduce
9
+ from typing import Any, Dict, List, Mapping, Optional, Set, Tuple, Union
10
+
11
+
12
+ def path_to_type(*elements: str) -> ast.AST:
13
+ base: ast.AST = ast.Name(id=elements[0], ctx=ast.Load())
14
+ for e in elements[1:]:
15
+ base = ast.Attribute(value=base, attr=e, ctx=ast.Load())
16
+ return base
17
+
18
+
19
+ OBJECT_MEMBERS = dict(inspect.getmembers(object))
20
+ BUILTINS: Dict[str, Union[None, Tuple[List[ast.AST], ast.AST]]] = {
21
+ "__annotations__": None,
22
+ "__bool__": ([], path_to_type("bool")),
23
+ "__bytes__": ([], path_to_type("bytes")),
24
+ "__class__": None,
25
+ "__contains__": ([path_to_type("typing", "Any")], path_to_type("bool")),
26
+ "__del__": None,
27
+ "__delattr__": ([path_to_type("str")], path_to_type("None")),
28
+ "__delitem__": ([path_to_type("typing", "Any")], path_to_type("typing", "Any")),
29
+ "__dict__": None,
30
+ "__dir__": None,
31
+ "__doc__": None,
32
+ "__eq__": ([path_to_type("typing", "Any")], path_to_type("bool")),
33
+ "__format__": ([path_to_type("str")], path_to_type("str")),
34
+ "__ge__": ([path_to_type("typing", "Any")], path_to_type("bool")),
35
+ "__getattribute__": ([path_to_type("str")], path_to_type("typing", "Any")),
36
+ "__getitem__": ([path_to_type("typing", "Any")], path_to_type("typing", "Any")),
37
+ "__gt__": ([path_to_type("typing", "Any")], path_to_type("bool")),
38
+ "__hash__": ([], path_to_type("int")),
39
+ "__init__": ([], path_to_type("None")),
40
+ "__init_subclass__": None,
41
+ "__iter__": ([], path_to_type("typing", "Any")),
42
+ "__le__": ([path_to_type("typing", "Any")], path_to_type("bool")),
43
+ "__len__": ([], path_to_type("int")),
44
+ "__lt__": ([path_to_type("typing", "Any")], path_to_type("bool")),
45
+ "__module__": None,
46
+ "__ne__": ([path_to_type("typing", "Any")], path_to_type("bool")),
47
+ "__new__": None,
48
+ "__next__": ([], path_to_type("typing", "Any")),
49
+ "__int__": ([], path_to_type("None")),
50
+ "__reduce__": None,
51
+ "__reduce_ex__": None,
52
+ "__repr__": ([], path_to_type("str")),
53
+ "__setattr__": (
54
+ [path_to_type("str"), path_to_type("typing", "Any")],
55
+ path_to_type("None"),
56
+ ),
57
+ "__setitem__": (
58
+ [path_to_type("typing", "Any"), path_to_type("typing", "Any")],
59
+ path_to_type("typing", "Any"),
60
+ ),
61
+ "__sizeof__": None,
62
+ "__str__": ([], path_to_type("str")),
63
+ "__subclasshook__": None,
64
+ }
65
+
66
+
67
+ def module_stubs(module: Any) -> ast.Module:
68
+ types_to_import = {"typing"}
69
+ classes = []
70
+ functions = []
71
+ for member_name, member_value in inspect.getmembers(module):
72
+ element_path = [module.__name__, member_name]
73
+ if member_name.startswith("__"):
74
+ pass
75
+ elif member_name.startswith("DoraStatus"):
76
+ pass
77
+ elif inspect.isclass(member_value):
78
+ classes.append(
79
+ class_stubs(member_name, member_value, element_path, types_to_import)
80
+ )
81
+ elif inspect.isbuiltin(member_value):
82
+ functions.append(
83
+ function_stub(
84
+ member_name,
85
+ member_value,
86
+ element_path,
87
+ types_to_import,
88
+ in_class=False,
89
+ )
90
+ )
91
+ else:
92
+ logging.warning(f"Unsupported root construction {member_name}")
93
+ return ast.Module(
94
+ body=[ast.Import(names=[ast.alias(name=t)]) for t in sorted(types_to_import)]
95
+ + classes
96
+ + functions,
97
+ type_ignores=[],
98
+ )
99
+
100
+
101
+ def class_stubs(
102
+ cls_name: str, cls_def: Any, element_path: List[str], types_to_import: Set[str]
103
+ ) -> ast.ClassDef:
104
+ attributes: List[ast.AST] = []
105
+ methods: List[ast.AST] = []
106
+ magic_methods: List[ast.AST] = []
107
+ constants: List[ast.AST] = []
108
+ for member_name, member_value in inspect.getmembers(cls_def):
109
+ current_element_path = [*element_path, member_name]
110
+ if member_name == "__init__":
111
+ try:
112
+ inspect.signature(cls_def) # we check it actually exists
113
+ methods = [
114
+ function_stub(
115
+ member_name,
116
+ cls_def,
117
+ current_element_path,
118
+ types_to_import,
119
+ in_class=True,
120
+ ),
121
+ *methods,
122
+ ]
123
+ except ValueError as e:
124
+ if "no signature found" not in str(e):
125
+ raise ValueError(
126
+ f"Error while parsing signature of {cls_name}.__init_"
127
+ ) from e
128
+ elif (
129
+ member_value == OBJECT_MEMBERS.get(member_name)
130
+ or BUILTINS.get(member_name, ()) is None
131
+ ):
132
+ pass
133
+ elif inspect.isdatadescriptor(member_value):
134
+ attributes.extend(
135
+ data_descriptor_stub(
136
+ member_name, member_value, current_element_path, types_to_import
137
+ )
138
+ )
139
+ elif inspect.isroutine(member_value):
140
+ (magic_methods if member_name.startswith("__") else methods).append(
141
+ function_stub(
142
+ member_name,
143
+ member_value,
144
+ current_element_path,
145
+ types_to_import,
146
+ in_class=True,
147
+ )
148
+ )
149
+ elif member_name == "__match_args__":
150
+ constants.append(
151
+ ast.AnnAssign(
152
+ target=ast.Name(id=member_name, ctx=ast.Store()),
153
+ annotation=ast.Subscript(
154
+ value=path_to_type("tuple"),
155
+ slice=ast.Tuple(
156
+ elts=[path_to_type("str"), ast.Ellipsis()], ctx=ast.Load()
157
+ ),
158
+ ctx=ast.Load(),
159
+ ),
160
+ value=ast.Constant(member_value),
161
+ simple=1,
162
+ )
163
+ )
164
+ elif member_value is not None:
165
+ constants.append(
166
+ ast.AnnAssign(
167
+ target=ast.Name(id=member_name, ctx=ast.Store()),
168
+ annotation=concatenated_path_to_type(
169
+ member_value.__class__.__name__, element_path, types_to_import
170
+ ),
171
+ value=ast.Ellipsis(),
172
+ simple=1,
173
+ )
174
+ )
175
+ else:
176
+ logging.warning(
177
+ f"Unsupported member {member_name} of class {'.'.join(element_path)}"
178
+ )
179
+
180
+ doc = inspect.getdoc(cls_def)
181
+ doc_comment = build_doc_comment(doc) if doc else None
182
+ return ast.ClassDef(
183
+ cls_name,
184
+ bases=[],
185
+ keywords=[],
186
+ body=(
187
+ ([doc_comment] if doc_comment else [])
188
+ + attributes
189
+ + methods
190
+ + magic_methods
191
+ + constants
192
+ )
193
+ or [ast.Ellipsis()],
194
+ decorator_list=[path_to_type("typing", "final")],
195
+ )
196
+
197
+
198
+ def data_descriptor_stub(
199
+ data_desc_name: str,
200
+ data_desc_def: Any,
201
+ element_path: List[str],
202
+ types_to_import: Set[str],
203
+ ) -> Union[Tuple[ast.AnnAssign, ast.Expr], Tuple[ast.AnnAssign]]:
204
+ annotation = None
205
+ doc_comment = None
206
+
207
+ doc = inspect.getdoc(data_desc_def)
208
+ if doc is not None:
209
+ annotation = returns_stub(data_desc_name, doc, element_path, types_to_import)
210
+ m = re.findall(r"^ *:return: *(.*) *$", doc, re.MULTILINE)
211
+ if len(m) == 1:
212
+ doc_comment = m[0]
213
+ elif len(m) > 1:
214
+ raise ValueError(
215
+ f"Multiple return annotations found with :return: in {'.'.join(element_path)} documentation"
216
+ )
217
+
218
+ assign = ast.AnnAssign(
219
+ target=ast.Name(id=data_desc_name, ctx=ast.Store()),
220
+ annotation=annotation or path_to_type("typing", "Any"),
221
+ simple=1,
222
+ )
223
+ doc_comment = build_doc_comment(doc_comment) if doc_comment else None
224
+ return (assign, doc_comment) if doc_comment else (assign,)
225
+
226
+
227
+ def function_stub(
228
+ fn_name: str,
229
+ fn_def: Any,
230
+ element_path: List[str],
231
+ types_to_import: Set[str],
232
+ *,
233
+ in_class: bool,
234
+ ) -> ast.FunctionDef:
235
+ body: List[ast.AST] = []
236
+ doc = inspect.getdoc(fn_def)
237
+ if doc is not None:
238
+ doc_comment = build_doc_comment(doc)
239
+ if doc_comment is not None:
240
+ body.append(doc_comment)
241
+
242
+ decorator_list = []
243
+ if in_class and hasattr(fn_def, "__self__"):
244
+ decorator_list.append(ast.Name("staticmethod"))
245
+
246
+ return ast.FunctionDef(
247
+ fn_name,
248
+ arguments_stub(fn_name, fn_def, doc or "", element_path, types_to_import),
249
+ body or [ast.Ellipsis()],
250
+ decorator_list=decorator_list,
251
+ returns=(
252
+ returns_stub(fn_name, doc, element_path, types_to_import) if doc else None
253
+ ),
254
+ lineno=0,
255
+ )
256
+
257
+
258
+ def arguments_stub(
259
+ callable_name: str,
260
+ callable_def: Any,
261
+ doc: str,
262
+ element_path: List[str],
263
+ types_to_import: Set[str],
264
+ ) -> ast.arguments:
265
+ real_parameters: Mapping[str, inspect.Parameter] = inspect.signature(
266
+ callable_def
267
+ ).parameters
268
+ if callable_name == "__init__":
269
+ real_parameters = {
270
+ "self": inspect.Parameter("self", inspect.Parameter.POSITIONAL_ONLY),
271
+ **real_parameters,
272
+ }
273
+
274
+ parsed_param_types = {}
275
+ optional_params = set()
276
+
277
+ # Types for magic functions types
278
+ builtin = BUILTINS.get(callable_name)
279
+ if isinstance(builtin, tuple):
280
+ param_names = list(real_parameters.keys())
281
+ if param_names and param_names[0] == "self":
282
+ del param_names[0]
283
+ for name, t in zip(param_names, builtin[0]):
284
+ parsed_param_types[name] = t
285
+
286
+ # Types from comment
287
+ for match in re.findall(
288
+ r"^ *:type *([a-zA-Z0-9_]+): ([^\n]*) *$", doc, re.MULTILINE
289
+ ):
290
+ if match[0] not in real_parameters:
291
+ raise ValueError(
292
+ f"The parameter {match[0]} of {'.'.join(element_path)} "
293
+ "is defined in the documentation but not in the function signature"
294
+ )
295
+ type = match[1]
296
+ if type.endswith(", optional"):
297
+ optional_params.add(match[0])
298
+ type = type[:-10]
299
+ parsed_param_types[match[0]] = convert_type_from_doc(
300
+ type, element_path, types_to_import
301
+ )
302
+
303
+ # we parse the parameters
304
+ posonlyargs = []
305
+ args = []
306
+ vararg = None
307
+ kwonlyargs = []
308
+ kw_defaults = []
309
+ kwarg = None
310
+ defaults = []
311
+ for param in real_parameters.values():
312
+ if param.name != "self" and param.name not in parsed_param_types:
313
+ raise ValueError(
314
+ f"The parameter {param.name} of {'.'.join(element_path)} "
315
+ "has no type definition in the function documentation"
316
+ )
317
+ param_ast = ast.arg(
318
+ arg=param.name, annotation=parsed_param_types.get(param.name)
319
+ )
320
+
321
+ default_ast = None
322
+ if param.default != param.empty:
323
+ default_ast = ast.Constant(param.default)
324
+ if param.name not in optional_params:
325
+ raise ValueError(
326
+ f"Parameter {param.name} of {'.'.join(element_path)} "
327
+ "is optional according to the type but not flagged as such in the doc"
328
+ )
329
+ elif param.name in optional_params:
330
+ raise ValueError(
331
+ f"Parameter {param.name} of {'.'.join(element_path)} "
332
+ "is optional according to the documentation but has no default value"
333
+ )
334
+
335
+ if param.kind == param.POSITIONAL_ONLY:
336
+ args.append(param_ast)
337
+ # posonlyargs.append(param_ast)
338
+ # defaults.append(default_ast)
339
+ elif param.kind == param.POSITIONAL_OR_KEYWORD:
340
+ args.append(param_ast)
341
+ defaults.append(default_ast)
342
+ elif param.kind == param.VAR_POSITIONAL:
343
+ vararg = param_ast
344
+ elif param.kind == param.KEYWORD_ONLY:
345
+ kwonlyargs.append(param_ast)
346
+ kw_defaults.append(default_ast)
347
+ elif param.kind == param.VAR_KEYWORD:
348
+ kwarg = param_ast
349
+
350
+ return ast.arguments(
351
+ posonlyargs=posonlyargs,
352
+ args=args,
353
+ vararg=vararg,
354
+ kwonlyargs=kwonlyargs,
355
+ kw_defaults=kw_defaults,
356
+ defaults=defaults,
357
+ kwarg=kwarg,
358
+ )
359
+
360
+
361
+ def returns_stub(
362
+ callable_name: str, doc: str, element_path: List[str], types_to_import: Set[str]
363
+ ) -> Optional[ast.AST]:
364
+ m = re.findall(r"^ *:rtype: *([^\n]*) *$", doc, re.MULTILINE)
365
+ if len(m) == 0:
366
+ builtin = BUILTINS.get(callable_name)
367
+ if isinstance(builtin, tuple) and builtin[1] is not None:
368
+ return builtin[1]
369
+ raise ValueError(
370
+ f"The return type of {'.'.join(element_path)} "
371
+ "has no type definition using :rtype: in the function documentation"
372
+ )
373
+ if len(m) > 1:
374
+ raise ValueError(
375
+ f"Multiple return type annotations found with :rtype: for {'.'.join(element_path)}"
376
+ )
377
+ return convert_type_from_doc(m[0], element_path, types_to_import)
378
+
379
+
380
+ def convert_type_from_doc(
381
+ type_str: str, element_path: List[str], types_to_import: Set[str]
382
+ ) -> ast.AST:
383
+ type_str = type_str.strip()
384
+ return parse_type_to_ast(type_str, element_path, types_to_import)
385
+
386
+
387
+ def parse_type_to_ast(
388
+ type_str: str, element_path: List[str], types_to_import: Set[str]
389
+ ) -> ast.AST:
390
+ # let's tokenize
391
+ tokens = []
392
+ current_token = ""
393
+ for c in type_str:
394
+ if "a" <= c <= "z" or "A" <= c <= "Z" or c == ".":
395
+ current_token += c
396
+ else:
397
+ if current_token:
398
+ tokens.append(current_token)
399
+ current_token = ""
400
+ if c != " ":
401
+ tokens.append(c)
402
+ if current_token:
403
+ tokens.append(current_token)
404
+
405
+ # let's first parse nested parenthesis
406
+ stack: List[List[Any]] = [[]]
407
+ for token in tokens:
408
+ if token == "[":
409
+ children: List[str] = []
410
+ stack[-1].append(children)
411
+ stack.append(children)
412
+ elif token == "]":
413
+ stack.pop()
414
+ else:
415
+ stack[-1].append(token)
416
+
417
+ # then it's easy
418
+ def parse_sequence(sequence: List[Any]) -> ast.AST:
419
+ # we split based on "or"
420
+ or_groups: List[List[str]] = [[]]
421
+ print(sequence)
422
+ # TODO: Fix sequence
423
+ if "Ros" in sequence and "2" in sequence:
424
+ sequence = ["".join(sequence)]
425
+ elif "dora.Ros" in sequence and "2" in sequence:
426
+ sequence = ["".join(sequence)]
427
+
428
+ for e in sequence:
429
+ if e == "or":
430
+ or_groups.append([])
431
+ else:
432
+ or_groups[-1].append(e)
433
+ if any(not g for g in or_groups):
434
+ raise ValueError(
435
+ f"Not able to parse type '{type_str}' used by {'.'.join(element_path)}"
436
+ )
437
+
438
+ new_elements: List[ast.AST] = []
439
+ for group in or_groups:
440
+ if len(group) == 1 and isinstance(group[0], str):
441
+ new_elements.append(
442
+ concatenated_path_to_type(group[0], element_path, types_to_import)
443
+ )
444
+ elif (
445
+ len(group) == 2
446
+ and isinstance(group[0], str)
447
+ and isinstance(group[1], list)
448
+ ):
449
+ new_elements.append(
450
+ ast.Subscript(
451
+ value=concatenated_path_to_type(
452
+ group[0], element_path, types_to_import
453
+ ),
454
+ slice=parse_sequence(group[1]),
455
+ ctx=ast.Load(),
456
+ )
457
+ )
458
+ else:
459
+ raise ValueError(
460
+ f"Not able to parse type '{type_str}' used by {'.'.join(element_path)}"
461
+ )
462
+ return reduce(
463
+ lambda left, right: ast.BinOp(left=left, op=ast.BitOr(), right=right),
464
+ new_elements,
465
+ )
466
+
467
+ return parse_sequence(stack[0])
468
+
469
+
470
+ def concatenated_path_to_type(
471
+ path: str, element_path: List[str], types_to_import: Set[str]
472
+ ) -> ast.AST:
473
+ parts = path.split(".")
474
+ if any(not p for p in parts):
475
+ raise ValueError(
476
+ f"Not able to parse type '{path}' used by {'.'.join(element_path)}"
477
+ )
478
+ if len(parts) > 1:
479
+ types_to_import.add(".".join(parts[:-1]))
480
+ return path_to_type(*parts)
481
+
482
+
483
+ def build_doc_comment(doc: str) -> Optional[ast.Expr]:
484
+ lines = [line.strip() for line in doc.split("\n")]
485
+ clean_lines = []
486
+ for line in lines:
487
+ if line.startswith((":type", ":rtype")):
488
+ continue
489
+ clean_lines.append(line)
490
+ text = "\n".join(clean_lines).strip()
491
+ return ast.Expr(value=ast.Constant(text)) if text else None
492
+
493
+
494
+ def format_with_ruff(file: str) -> None:
495
+ subprocess.check_call(["python", "-m", "ruff", "format", file])
496
+
497
+
498
+ if __name__ == "__main__":
499
+ parser = argparse.ArgumentParser(
500
+ description="Extract Python type stub from a python module."
501
+ )
502
+ parser.add_argument(
503
+ "module_name", help="Name of the Python module for which generate stubs"
504
+ )
505
+ parser.add_argument(
506
+ "out",
507
+ help="Name of the Python stub file to write to",
508
+ type=argparse.FileType("wt"),
509
+ )
510
+ parser.add_argument(
511
+ "--ruff", help="Formats the generated stubs using Ruff", action="store_true"
512
+ )
513
+ args = parser.parse_args()
514
+ stub_content = ast.unparse(module_stubs(importlib.import_module(args.module_name)))
515
+ args.out.write(stub_content)
516
+ if args.ruff:
517
+ format_with_ruff(args.out.name)
apis/python/node/pyproject.toml ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+ [build-system]
2
+ requires = ["maturin>=0.13.2"]
3
+ build-backend = "maturin"
4
+
5
+ [project]
6
+ name = "dora-rs"
7
+ # Install pyarrow at the same time of dora-rs
8
+ dependencies = ['pyarrow']
9
+
10
+ [tool.maturin]
11
+ features = ["pyo3/extension-module"]
apis/python/node/src/lib.rs ADDED
@@ -0,0 +1,264 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #![allow(clippy::borrow_deref_ref)] // clippy warns about code generated by #[pymethods]
2
+
3
+ use std::time::Duration;
4
+
5
+ use arrow::pyarrow::{FromPyArrow, ToPyArrow};
6
+ use dora_node_api::merged::{MergeExternalSend, MergedEvent};
7
+ use dora_node_api::{DoraNode, EventStream};
8
+ use dora_operator_api_python::{pydict_to_metadata, PyEvent};
9
+ use dora_ros2_bridge_python::Ros2Subscription;
10
+ use eyre::Context;
11
+ use futures::{Stream, StreamExt};
12
+ use pyo3::prelude::*;
13
+ use pyo3::types::{PyBytes, PyDict};
14
+
15
+ /// The custom node API lets you integrate `dora` into your application.
16
+ /// It allows you to retrieve input and send output in any fashion you want.
17
+ ///
18
+ /// Use with:
19
+ ///
20
+ /// ```python
21
+ /// from dora import Node
22
+ ///
23
+ /// node = Node()
24
+ /// ```
25
+ ///
26
+ #[pyclass]
27
+ pub struct Node {
28
+ events: Events,
29
+ node: DoraNode,
30
+ }
31
+
32
+ #[pymethods]
33
+ impl Node {
34
+ #[new]
35
+ pub fn new() -> eyre::Result<Self> {
36
+ let (node, events) = DoraNode::init_from_env()?;
37
+
38
+ Ok(Node {
39
+ events: Events::Dora(events),
40
+ node,
41
+ })
42
+ }
43
+
44
+ /// `.next()` gives you the next input that the node has received.
45
+ /// It blocks until the next event becomes available.
46
+ /// You can use timeout in seconds to return if no input is available.
47
+ /// It will return `None` when all senders has been dropped.
48
+ ///
49
+ /// ```python
50
+ /// event = node.next()
51
+ /// ```
52
+ ///
53
+ /// You can also iterate over the event stream with a loop
54
+ ///
55
+ /// ```python
56
+ /// for event in node:
57
+ /// match event["type"]:
58
+ /// case "INPUT":
59
+ /// match event["id"]:
60
+ /// case "image":
61
+ /// ```
62
+ ///
63
+ /// :type timeout: float, optional
64
+ /// :rtype: dora.PyEvent
65
+ #[allow(clippy::should_implement_trait)]
66
+ pub fn next(&mut self, py: Python, timeout: Option<f32>) -> PyResult<Option<PyEvent>> {
67
+ let event = py.allow_threads(|| self.events.recv(timeout.map(Duration::from_secs_f32)));
68
+ Ok(event)
69
+ }
70
+
71
+ /// You can iterate over the event stream with a loop
72
+ ///
73
+ /// ```python
74
+ /// for event in node:
75
+ /// match event["type"]:
76
+ /// case "INPUT":
77
+ /// match event["id"]:
78
+ /// case "image":
79
+ /// ```
80
+ ///
81
+ /// :rtype: dora.PyEvent
82
+ pub fn __next__(&mut self, py: Python) -> PyResult<Option<PyEvent>> {
83
+ let event = py.allow_threads(|| self.events.recv(None));
84
+ Ok(event)
85
+ }
86
+
87
+ /// You can iterate over the event stream with a loop
88
+ ///
89
+ /// ```python
90
+ /// for event in node:
91
+ /// match event["type"]:
92
+ /// case "INPUT":
93
+ /// match event["id"]:
94
+ /// case "image":
95
+ /// ```
96
+ ///
97
+ /// :rtype: dora.PyEvent
98
+ fn __iter__(slf: PyRef<'_, Self>) -> PyRef<'_, Self> {
99
+ slf
100
+ }
101
+
102
+ /// `send_output` send data from the node.
103
+ ///
104
+ /// ```python
105
+ /// Args:
106
+ /// output_id: str,
107
+ /// data: pyarrow.Array,
108
+ /// metadata: Option[Dict],
109
+ /// ```
110
+ ///
111
+ /// ex:
112
+ ///
113
+ /// ```python
114
+ /// node.send_output("string", b"string", {"open_telemetry_context": "7632e76"})
115
+ /// ```
116
+ ///
117
+ /// :type output_id: str
118
+ /// :type data: pyarrow.Array
119
+ /// :type metadata: dict, optional
120
+ /// :rtype: None
121
+ pub fn send_output(
122
+ &mut self,
123
+ output_id: String,
124
+ data: PyObject,
125
+ metadata: Option<Bound<'_, PyDict>>,
126
+ py: Python,
127
+ ) -> eyre::Result<()> {
128
+ let parameters = pydict_to_metadata(metadata)?;
129
+
130
+ if let Ok(py_bytes) = data.downcast_bound::<PyBytes>(py) {
131
+ let data = py_bytes.as_bytes();
132
+ self.node
133
+ .send_output_bytes(output_id.into(), parameters, data.len(), data)
134
+ .wrap_err("failed to send output")?;
135
+ } else if let Ok(arrow_array) = arrow::array::ArrayData::from_pyarrow_bound(data.bind(py)) {
136
+ self.node.send_output(
137
+ output_id.into(),
138
+ parameters,
139
+ arrow::array::make_array(arrow_array),
140
+ )?;
141
+ } else {
142
+ eyre::bail!("invalid `data` type, must by `PyBytes` or arrow array")
143
+ }
144
+
145
+ Ok(())
146
+ }
147
+
148
+ /// Returns the full dataflow descriptor that this node is part of.
149
+ ///
150
+ /// This method returns the parsed dataflow YAML file.
151
+ ///
152
+ /// :rtype: dict
153
+ pub fn dataflow_descriptor(&self, py: Python) -> pythonize::Result<PyObject> {
154
+ pythonize::pythonize(py, self.node.dataflow_descriptor())
155
+ }
156
+
157
+ /// Returns the dataflow id.
158
+ ///
159
+ /// :rtype: str
160
+ pub fn dataflow_id(&self) -> String {
161
+ self.node.dataflow_id().to_string()
162
+ }
163
+
164
+ /// Merge an external event stream with dora main loop.
165
+ /// This currently only work with ROS2.
166
+ ///
167
+ /// :type subscription: dora.Ros2Subscription
168
+ /// :rtype: None
169
+ pub fn merge_external_events(
170
+ &mut self,
171
+ subscription: &mut Ros2Subscription,
172
+ ) -> eyre::Result<()> {
173
+ let subscription = subscription.into_stream()?;
174
+ let stream = futures::stream::poll_fn(move |cx| {
175
+ let s = subscription.as_stream().map(|item| {
176
+ match item.context("failed to read ROS2 message") {
177
+ Ok((value, _info)) => Python::with_gil(|py| {
178
+ value
179
+ .to_pyarrow(py)
180
+ .context("failed to convert value to pyarrow")
181
+ .unwrap_or_else(|err| PyErr::from(err).to_object(py))
182
+ }),
183
+ Err(err) => Python::with_gil(|py| PyErr::from(err).to_object(py)),
184
+ }
185
+ });
186
+ futures::pin_mut!(s);
187
+ s.poll_next_unpin(cx)
188
+ });
189
+
190
+ // take out the event stream and temporarily replace it with a dummy
191
+ let events = std::mem::replace(
192
+ &mut self.events,
193
+ Events::Merged(Box::new(futures::stream::empty())),
194
+ );
195
+ // update self.events with the merged stream
196
+ self.events = Events::Merged(events.merge_external_send(Box::pin(stream)));
197
+
198
+ Ok(())
199
+ }
200
+ }
201
+
202
+ enum Events {
203
+ Dora(EventStream),
204
+ Merged(Box<dyn Stream<Item = MergedEvent<PyObject>> + Unpin + Send>),
205
+ }
206
+
207
+ impl Events {
208
+ fn recv(&mut self, timeout: Option<Duration>) -> Option<PyEvent> {
209
+ match self {
210
+ Events::Dora(events) => match timeout {
211
+ Some(timeout) => events.recv_timeout(timeout).map(PyEvent::from),
212
+ None => events.recv().map(PyEvent::from),
213
+ },
214
+ Events::Merged(events) => futures::executor::block_on(events.next()).map(PyEvent::from),
215
+ }
216
+ }
217
+ }
218
+
219
+ impl<'a> MergeExternalSend<'a, PyObject> for Events {
220
+ type Item = MergedEvent<PyObject>;
221
+
222
+ fn merge_external_send(
223
+ self,
224
+ external_events: impl Stream<Item = PyObject> + Unpin + Send + 'a,
225
+ ) -> Box<dyn Stream<Item = Self::Item> + Unpin + Send + 'a> {
226
+ match self {
227
+ Events::Dora(events) => events.merge_external_send(external_events),
228
+ Events::Merged(events) => {
229
+ let merged = events.merge_external_send(external_events);
230
+ Box::new(merged.map(|event| match event {
231
+ MergedEvent::Dora(e) => MergedEvent::Dora(e),
232
+ MergedEvent::External(e) => MergedEvent::External(e.flatten()),
233
+ }))
234
+ }
235
+ }
236
+ }
237
+ }
238
+
239
+ impl Node {
240
+ pub fn id(&self) -> String {
241
+ self.node.id().to_string()
242
+ }
243
+ }
244
+
245
+ /// Start a runtime for Operators
246
+ ///
247
+ /// :rtype: None
248
+ #[pyfunction]
249
+ pub fn start_runtime() -> eyre::Result<()> {
250
+ dora_runtime::main().wrap_err("Dora Runtime raised an error.")
251
+ }
252
+
253
+ #[pymodule]
254
+ fn dora(_py: Python, m: Bound<'_, PyModule>) -> PyResult<()> {
255
+ dora_ros2_bridge_python::create_dora_ros2_bridge_module(&m)?;
256
+
257
+ m.add_function(wrap_pyfunction!(start_runtime, &m)?)?;
258
+ m.add_class::<Node>()?;
259
+ m.add_class::<PyEvent>()?;
260
+ m.setattr("__version__", env!("CARGO_PKG_VERSION"))?;
261
+ m.setattr("__author__", "Dora-rs Authors")?;
262
+
263
+ Ok(())
264
+ }
apis/python/operator/Cargo.toml ADDED
@@ -0,0 +1,20 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ [package]
2
+ name = "dora-operator-api-python"
3
+ version.workspace = true
4
+ edition = "2021"
5
+
6
+ documentation.workspace = true
7
+ description.workspace = true
8
+ license.workspace = true
9
+
10
+ # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
11
+
12
+ [dependencies]
13
+ dora-node-api = { workspace = true }
14
+ pyo3 = { workspace = true, features = ["eyre", "abi3-py37"] }
15
+ eyre = "0.6"
16
+ serde_yaml = "0.8.23"
17
+ flume = "0.10.14"
18
+ arrow = { workspace = true, features = ["pyarrow"] }
19
+ arrow-schema = { workspace = true }
20
+ aligned-vec = "0.5.0"
apis/python/operator/src/lib.rs ADDED
@@ -0,0 +1,259 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ use arrow::{array::ArrayRef, pyarrow::ToPyArrow};
2
+ use dora_node_api::{merged::MergedEvent, Event, Metadata, MetadataParameters};
3
+ use eyre::{Context, Result};
4
+ use pyo3::{exceptions::PyLookupError, prelude::*, pybacked::PyBackedStr, types::PyDict};
5
+
6
+ /// Dora Event
7
+ #[pyclass]
8
+ #[derive(Debug)]
9
+ pub struct PyEvent {
10
+ event: MergedEvent<PyObject>,
11
+ data: Option<ArrayRef>,
12
+ }
13
+
14
+ // Dora Event
15
+ #[pymethods]
16
+ impl PyEvent {
17
+ ///
18
+ /// :rtype: dora.PyObject
19
+ pub fn __getitem__(&self, key: &str, py: Python<'_>) -> PyResult<Option<PyObject>> {
20
+ if key == "kind" {
21
+ let kind = match &self.event {
22
+ MergedEvent::Dora(_) => "dora",
23
+ MergedEvent::External(_) => "external",
24
+ };
25
+ return Ok(Some(kind.to_object(py)));
26
+ }
27
+ match &self.event {
28
+ MergedEvent::Dora(event) => {
29
+ let value = match key {
30
+ "type" => Some(Self::ty(event).to_object(py)),
31
+ "id" => Self::id(event).map(|v| v.to_object(py)),
32
+ "value" => self.value(py)?,
33
+ "metadata" => Self::metadata(event, py),
34
+ "error" => Self::error(event).map(|v| v.to_object(py)),
35
+ other => {
36
+ return Err(PyLookupError::new_err(format!(
37
+ "event has no property `{other}`"
38
+ )))
39
+ }
40
+ };
41
+ Ok(value)
42
+ }
43
+ MergedEvent::External(event) => {
44
+ let value = match key {
45
+ "value" => event,
46
+ _ => todo!(),
47
+ };
48
+
49
+ Ok(Some(value.clone()))
50
+ }
51
+ }
52
+ }
53
+
54
+ pub fn inner(&mut self) -> Option<&PyObject> {
55
+ match &self.event {
56
+ MergedEvent::Dora(_) => None,
57
+ MergedEvent::External(event) => Some(event),
58
+ }
59
+ }
60
+
61
+ fn __str__(&self) -> PyResult<String> {
62
+ Ok(format!("{:#?}", &self.event))
63
+ }
64
+ }
65
+
66
+ impl PyEvent {
67
+ fn ty(event: &Event) -> &str {
68
+ match event {
69
+ Event::Stop => "STOP",
70
+ Event::Input { .. } => "INPUT",
71
+ Event::InputClosed { .. } => "INPUT_CLOSED",
72
+ Event::Error(_) => "ERROR",
73
+ _other => "UNKNOWN",
74
+ }
75
+ }
76
+
77
+ fn id(event: &Event) -> Option<&str> {
78
+ match event {
79
+ Event::Input { id, .. } => Some(id),
80
+ Event::InputClosed { id } => Some(id),
81
+ _ => None,
82
+ }
83
+ }
84
+
85
+ /// Returns the payload of an input event as an arrow array (if any).
86
+ fn value(&self, py: Python<'_>) -> PyResult<Option<PyObject>> {
87
+ match (&self.event, &self.data) {
88
+ (MergedEvent::Dora(Event::Input { .. }), Some(data)) => {
89
+ // TODO: Does this call leak data?
90
+ let array_data = data.to_data().to_pyarrow(py)?;
91
+ Ok(Some(array_data))
92
+ }
93
+ _ => Ok(None),
94
+ }
95
+ }
96
+
97
+ fn metadata(event: &Event, py: Python<'_>) -> Option<PyObject> {
98
+ match event {
99
+ Event::Input { metadata, .. } => Some(metadata_to_pydict(metadata, py).to_object(py)),
100
+ _ => None,
101
+ }
102
+ }
103
+
104
+ fn error(event: &Event) -> Option<&str> {
105
+ match event {
106
+ Event::Error(error) => Some(error),
107
+ _other => None,
108
+ }
109
+ }
110
+ }
111
+
112
+ impl From<Event> for PyEvent {
113
+ fn from(event: Event) -> Self {
114
+ Self::from(MergedEvent::Dora(event))
115
+ }
116
+ }
117
+
118
+ impl From<MergedEvent<PyObject>> for PyEvent {
119
+ fn from(mut event: MergedEvent<PyObject>) -> Self {
120
+ let data = if let MergedEvent::Dora(Event::Input { data, .. }) = &mut event {
121
+ Some(data.clone())
122
+ } else {
123
+ None
124
+ };
125
+ Self { event, data }
126
+ }
127
+ }
128
+
129
+ pub fn pydict_to_metadata(dict: Option<Bound<'_, PyDict>>) -> Result<MetadataParameters> {
130
+ let mut default_metadata = MetadataParameters::default();
131
+ if let Some(metadata) = dict {
132
+ for (key, value) in metadata.iter() {
133
+ match key
134
+ .extract::<PyBackedStr>()
135
+ .context("Parsing metadata keys")?
136
+ .as_ref()
137
+ {
138
+ "watermark" => {
139
+ default_metadata.watermark =
140
+ value.extract().context("parsing watermark failed")?;
141
+ }
142
+ "deadline" => {
143
+ default_metadata.deadline =
144
+ value.extract().context("parsing deadline failed")?;
145
+ }
146
+ "open_telemetry_context" => {
147
+ let otel_context: PyBackedStr = value
148
+ .extract()
149
+ .context("parsing open telemetry context failed")?;
150
+ default_metadata.open_telemetry_context = otel_context.to_string();
151
+ }
152
+ _ => (),
153
+ }
154
+ }
155
+ }
156
+ Ok(default_metadata)
157
+ }
158
+
159
+ pub fn metadata_to_pydict<'a>(metadata: &'a Metadata, py: Python<'a>) -> pyo3::Bound<'a, PyDict> {
160
+ let dict = PyDict::new_bound(py);
161
+ dict.set_item(
162
+ "open_telemetry_context",
163
+ &metadata.parameters.open_telemetry_context,
164
+ )
165
+ .wrap_err("could not make metadata a python dictionary item")
166
+ .unwrap();
167
+ dict
168
+ }
169
+
170
+ #[cfg(test)]
171
+ mod tests {
172
+ use std::sync::Arc;
173
+
174
+ use aligned_vec::{AVec, ConstAlign};
175
+ use arrow::{
176
+ array::{
177
+ ArrayData, ArrayRef, BooleanArray, Float64Array, Int32Array, Int64Array, Int8Array,
178
+ ListArray, StructArray,
179
+ },
180
+ buffer::Buffer,
181
+ };
182
+
183
+ use arrow_schema::{DataType, Field};
184
+ use dora_node_api::{
185
+ arrow_utils::{copy_array_into_sample, required_data_size},
186
+ RawData,
187
+ };
188
+ use eyre::{Context, Result};
189
+
190
+ fn assert_roundtrip(arrow_array: &ArrayData) -> Result<()> {
191
+ let size = required_data_size(arrow_array);
192
+ let mut sample: AVec<u8, ConstAlign<128>> = AVec::__from_elem(128, 0, size);
193
+
194
+ let info = copy_array_into_sample(&mut sample, arrow_array);
195
+
196
+ let serialized_deserialized_arrow_array = RawData::Vec(sample)
197
+ .into_arrow_array(&info)
198
+ .context("Could not create arrow array")?;
199
+ assert_eq!(arrow_array, &serialized_deserialized_arrow_array);
200
+
201
+ Ok(())
202
+ }
203
+
204
+ #[test]
205
+ fn serialize_deserialize_arrow() -> Result<()> {
206
+ // Int8
207
+ let arrow_array = Int8Array::from(vec![1, -2, 3, 4]).into();
208
+ assert_roundtrip(&arrow_array).context("Int8Array roundtrip failed")?;
209
+
210
+ // Int64
211
+ let arrow_array = Int64Array::from(vec![1, -2, 3, 4]).into();
212
+ assert_roundtrip(&arrow_array).context("Int64Array roundtrip failed")?;
213
+
214
+ // Float64
215
+ let arrow_array = Float64Array::from(vec![1., -2., 3., 4.]).into();
216
+ assert_roundtrip(&arrow_array).context("Float64Array roundtrip failed")?;
217
+
218
+ // Struct
219
+ let boolean = Arc::new(BooleanArray::from(vec![false, false, true, true]));
220
+ let int = Arc::new(Int32Array::from(vec![42, 28, 19, 31]));
221
+
222
+ let struct_array = StructArray::from(vec![
223
+ (
224
+ Arc::new(Field::new("b", DataType::Boolean, false)),
225
+ boolean as ArrayRef,
226
+ ),
227
+ (
228
+ Arc::new(Field::new("c", DataType::Int32, false)),
229
+ int as ArrayRef,
230
+ ),
231
+ ])
232
+ .into();
233
+ assert_roundtrip(&struct_array).context("StructArray roundtrip failed")?;
234
+
235
+ // List
236
+ let value_data = ArrayData::builder(DataType::Int32)
237
+ .len(8)
238
+ .add_buffer(Buffer::from_slice_ref([0, 1, 2, 3, 4, 5, 6, 7]))
239
+ .build()
240
+ .unwrap();
241
+
242
+ // Construct a buffer for value offsets, for the nested array:
243
+ // [[0, 1, 2], [3, 4, 5], [6, 7]]
244
+ let value_offsets = Buffer::from_slice_ref([0, 3, 6, 8]);
245
+
246
+ // Construct a list array from the above two
247
+ let list_data_type = DataType::List(Arc::new(Field::new("item", DataType::Int32, false)));
248
+ let list_data = ArrayData::builder(list_data_type)
249
+ .len(3)
250
+ .add_buffer(value_offsets)
251
+ .add_child_data(value_data)
252
+ .build()
253
+ .unwrap();
254
+ let list_array = ListArray::from(list_data).into();
255
+ assert_roundtrip(&list_array).context("ListArray roundtrip failed")?;
256
+
257
+ Ok(())
258
+ }
259
+ }
apis/rust/node/Cargo.toml ADDED
@@ -0,0 +1,31 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ [package]
2
+ name = "dora-node-api"
3
+ version.workspace = true
4
+ edition = "2021"
5
+ documentation.workspace = true
6
+ description.workspace = true
7
+ license.workspace = true
8
+
9
+ [features]
10
+ default = ["tracing"]
11
+ tracing = ["dep:dora-tracing"]
12
+
13
+ [dependencies]
14
+ dora-core = { workspace = true }
15
+ shared-memory-server = { workspace = true }
16
+ eyre = "0.6.7"
17
+ serde_yaml = "0.8.23"
18
+ tracing = "0.1.33"
19
+ flume = "0.10.14"
20
+ bincode = "1.3.3"
21
+ shared_memory_extended = "0.13.0"
22
+ dora-tracing = { workspace = true, optional = true }
23
+ arrow = { workspace = true }
24
+ futures = "0.3.28"
25
+ futures-concurrency = "7.3.0"
26
+ futures-timer = "3.0.2"
27
+ dora-arrow-convert = { workspace = true }
28
+ aligned-vec = "0.5.0"
29
+
30
+ [dev-dependencies]
31
+ tokio = { version = "1.24.2", features = ["rt"] }
apis/rust/node/src/daemon_connection/mod.rs ADDED
@@ -0,0 +1,74 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ use dora_core::{
2
+ config::NodeId,
3
+ daemon_messages::{DaemonReply, DaemonRequest, DataflowId, Timestamped},
4
+ message::uhlc::Timestamp,
5
+ };
6
+ use eyre::{bail, eyre, Context};
7
+ use shared_memory_server::{ShmemClient, ShmemConf};
8
+ use std::{
9
+ net::{SocketAddr, TcpStream},
10
+ time::Duration,
11
+ };
12
+
13
+ mod tcp;
14
+
15
+ pub enum DaemonChannel {
16
+ Shmem(ShmemClient<Timestamped<DaemonRequest>, DaemonReply>),
17
+ Tcp(TcpStream),
18
+ }
19
+
20
+ impl DaemonChannel {
21
+ #[tracing::instrument(level = "trace")]
22
+ pub fn new_tcp(socket_addr: SocketAddr) -> eyre::Result<Self> {
23
+ let stream = TcpStream::connect(socket_addr).wrap_err("failed to open TCP connection")?;
24
+ stream.set_nodelay(true).context("failed to set nodelay")?;
25
+ Ok(DaemonChannel::Tcp(stream))
26
+ }
27
+
28
+ #[tracing::instrument(level = "trace")]
29
+ pub unsafe fn new_shmem(daemon_control_region_id: &str) -> eyre::Result<Self> {
30
+ let daemon_events_region = ShmemConf::new()
31
+ .os_id(daemon_control_region_id)
32
+ .open()
33
+ .wrap_err("failed to connect to dora-daemon")?;
34
+ let channel = DaemonChannel::Shmem(
35
+ unsafe { ShmemClient::new(daemon_events_region, Some(Duration::from_secs(5))) }
36
+ .wrap_err("failed to create ShmemChannel")?,
37
+ );
38
+ Ok(channel)
39
+ }
40
+
41
+ pub fn register(
42
+ &mut self,
43
+ dataflow_id: DataflowId,
44
+ node_id: NodeId,
45
+ timestamp: Timestamp,
46
+ ) -> eyre::Result<()> {
47
+ let msg = Timestamped {
48
+ inner: DaemonRequest::Register {
49
+ dataflow_id,
50
+ node_id,
51
+ dora_version: env!("CARGO_PKG_VERSION").to_owned(),
52
+ },
53
+ timestamp,
54
+ };
55
+ let reply = self
56
+ .request(&msg)
57
+ .wrap_err("failed to send register request to dora-daemon")?;
58
+
59
+ match reply {
60
+ dora_core::daemon_messages::DaemonReply::Result(result) => result
61
+ .map_err(|e| eyre!(e))
62
+ .wrap_err("failed to register node with dora-daemon")?,
63
+ other => bail!("unexpected register reply: {other:?}"),
64
+ }
65
+ Ok(())
66
+ }
67
+
68
+ pub fn request(&mut self, request: &Timestamped<DaemonRequest>) -> eyre::Result<DaemonReply> {
69
+ match self {
70
+ DaemonChannel::Shmem(client) => client.request(request),
71
+ DaemonChannel::Tcp(stream) => tcp::request(stream, request),
72
+ }
73
+ }
74
+ }
apis/rust/node/src/daemon_connection/tcp.rs ADDED
@@ -0,0 +1,68 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ use dora_core::daemon_messages::{DaemonReply, DaemonRequest, Timestamped};
2
+ use eyre::{eyre, Context};
3
+ use std::{
4
+ io::{Read, Write},
5
+ net::TcpStream,
6
+ };
7
+
8
+ pub fn request(
9
+ connection: &mut TcpStream,
10
+ request: &Timestamped<DaemonRequest>,
11
+ ) -> eyre::Result<DaemonReply> {
12
+ send_message(connection, request)?;
13
+ if request.inner.expects_tcp_reply() {
14
+ receive_reply(connection)
15
+ .and_then(|reply| reply.ok_or_else(|| eyre!("server disconnected unexpectedly")))
16
+ } else {
17
+ Ok(DaemonReply::Empty)
18
+ }
19
+ }
20
+
21
+ fn send_message(
22
+ connection: &mut TcpStream,
23
+ message: &Timestamped<DaemonRequest>,
24
+ ) -> eyre::Result<()> {
25
+ let serialized = bincode::serialize(&message).wrap_err("failed to serialize DaemonRequest")?;
26
+ tcp_send(connection, &serialized).wrap_err("failed to send DaemonRequest")?;
27
+ Ok(())
28
+ }
29
+
30
+ fn receive_reply(connection: &mut TcpStream) -> eyre::Result<Option<DaemonReply>> {
31
+ let raw = match tcp_receive(connection) {
32
+ Ok(raw) => raw,
33
+ Err(err) => match err.kind() {
34
+ std::io::ErrorKind::UnexpectedEof | std::io::ErrorKind::ConnectionAborted => {
35
+ return Ok(None)
36
+ }
37
+ other => {
38
+ return Err(err).with_context(|| {
39
+ format!(
40
+ "unexpected I/O error (kind {other:?}) while trying to receive DaemonReply"
41
+ )
42
+ })
43
+ }
44
+ },
45
+ };
46
+ bincode::deserialize(&raw)
47
+ .wrap_err("failed to deserialize DaemonReply")
48
+ .map(Some)
49
+ }
50
+
51
+ fn tcp_send(connection: &mut (impl Write + Unpin), message: &[u8]) -> std::io::Result<()> {
52
+ let len_raw = (message.len() as u64).to_le_bytes();
53
+ connection.write_all(&len_raw)?;
54
+ connection.write_all(message)?;
55
+ connection.flush()?;
56
+ Ok(())
57
+ }
58
+
59
+ fn tcp_receive(connection: &mut (impl Read + Unpin)) -> std::io::Result<Vec<u8>> {
60
+ let reply_len = {
61
+ let mut raw = [0; 8];
62
+ connection.read_exact(&mut raw)?;
63
+ u64::from_le_bytes(raw) as usize
64
+ };
65
+ let mut reply = vec![0; reply_len];
66
+ connection.read_exact(&mut reply)?;
67
+ Ok(reply)
68
+ }
apis/rust/node/src/event_stream/event.rs ADDED
@@ -0,0 +1,128 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ use std::{ptr::NonNull, sync::Arc};
2
+
3
+ use aligned_vec::{AVec, ConstAlign};
4
+ use dora_arrow_convert::{ArrowData, IntoArrow};
5
+ use dora_core::{
6
+ config::{DataId, OperatorId},
7
+ message::{ArrowTypeInfo, BufferOffset, Metadata},
8
+ };
9
+ use eyre::{Context, Result};
10
+ use shared_memory_extended::{Shmem, ShmemConf};
11
+
12
+ #[derive(Debug)]
13
+ #[non_exhaustive]
14
+ pub enum Event {
15
+ Stop,
16
+ Reload {
17
+ operator_id: Option<OperatorId>,
18
+ },
19
+ Input {
20
+ id: DataId,
21
+ metadata: Metadata,
22
+ data: ArrowData,
23
+ },
24
+ InputClosed {
25
+ id: DataId,
26
+ },
27
+ Error(String),
28
+ }
29
+
30
+ pub enum RawData {
31
+ Empty,
32
+ Vec(AVec<u8, ConstAlign<128>>),
33
+ SharedMemory(SharedMemoryData),
34
+ }
35
+
36
+ impl RawData {
37
+ pub fn into_arrow_array(self, type_info: &ArrowTypeInfo) -> Result<arrow::array::ArrayData> {
38
+ let raw_buffer = match self {
39
+ RawData::Empty => return Ok(().into_arrow().into()),
40
+ RawData::Vec(data) => {
41
+ let ptr = NonNull::new(data.as_ptr() as *mut _).unwrap();
42
+ let len = data.len();
43
+
44
+ unsafe { arrow::buffer::Buffer::from_custom_allocation(ptr, len, Arc::new(data)) }
45
+ }
46
+ RawData::SharedMemory(data) => {
47
+ let ptr = NonNull::new(data.data.as_ptr() as *mut _).unwrap();
48
+ let len = data.data.len();
49
+
50
+ unsafe { arrow::buffer::Buffer::from_custom_allocation(ptr, len, Arc::new(data)) }
51
+ }
52
+ };
53
+
54
+ buffer_into_arrow_array(&raw_buffer, type_info)
55
+ }
56
+ }
57
+
58
+ pub struct SharedMemoryData {
59
+ pub data: MappedInputData,
60
+ pub _drop: flume::Sender<()>,
61
+ }
62
+
63
+ fn buffer_into_arrow_array(
64
+ raw_buffer: &arrow::buffer::Buffer,
65
+ type_info: &ArrowTypeInfo,
66
+ ) -> eyre::Result<arrow::array::ArrayData> {
67
+ if raw_buffer.is_empty() {
68
+ return Ok(arrow::array::ArrayData::new_empty(&type_info.data_type));
69
+ }
70
+
71
+ let mut buffers = Vec::new();
72
+ for BufferOffset { offset, len } in &type_info.buffer_offsets {
73
+ buffers.push(raw_buffer.slice_with_length(*offset, *len));
74
+ }
75
+
76
+ let mut child_data = Vec::new();
77
+ for child_type_info in &type_info.child_data {
78
+ child_data.push(buffer_into_arrow_array(raw_buffer, child_type_info)?)
79
+ }
80
+
81
+ arrow::array::ArrayData::try_new(
82
+ type_info.data_type.clone(),
83
+ type_info.len,
84
+ type_info
85
+ .validity
86
+ .clone()
87
+ .map(arrow::buffer::Buffer::from_vec),
88
+ type_info.offset,
89
+ buffers,
90
+ child_data,
91
+ )
92
+ .context("Error creating Arrow array")
93
+ }
94
+
95
+ impl std::fmt::Debug for RawData {
96
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
97
+ f.debug_struct("Data").finish_non_exhaustive()
98
+ }
99
+ }
100
+
101
+ pub struct MappedInputData {
102
+ memory: Box<Shmem>,
103
+ len: usize,
104
+ }
105
+
106
+ impl MappedInputData {
107
+ pub(crate) unsafe fn map(shared_memory_id: &str, len: usize) -> eyre::Result<Self> {
108
+ let memory = Box::new(
109
+ ShmemConf::new()
110
+ .os_id(shared_memory_id)
111
+ .writable(false)
112
+ .open()
113
+ .wrap_err("failed to map shared memory input")?,
114
+ );
115
+ Ok(MappedInputData { memory, len })
116
+ }
117
+ }
118
+
119
+ impl std::ops::Deref for MappedInputData {
120
+ type Target = [u8];
121
+
122
+ fn deref(&self) -> &Self::Target {
123
+ unsafe { &self.memory.as_slice()[..self.len] }
124
+ }
125
+ }
126
+
127
+ unsafe impl Send for MappedInputData {}
128
+ unsafe impl Sync for MappedInputData {}
apis/rust/node/src/event_stream/merged.rs ADDED
@@ -0,0 +1,115 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ use futures::{Stream, StreamExt};
2
+ use futures_concurrency::stream::Merge;
3
+
4
+ #[derive(Debug)]
5
+ pub enum MergedEvent<E> {
6
+ Dora(super::Event),
7
+ External(E),
8
+ }
9
+
10
+ pub enum Either<A, B> {
11
+ First(A),
12
+ Second(B),
13
+ }
14
+
15
+ impl<A> Either<A, A> {
16
+ pub fn flatten(self) -> A {
17
+ match self {
18
+ Either::First(a) => a,
19
+ Either::Second(a) => a,
20
+ }
21
+ }
22
+ }
23
+
24
+ // TODO: use impl trait return type once stable
25
+ pub trait MergeExternal<'a, E> {
26
+ type Item;
27
+
28
+ fn merge_external(
29
+ self,
30
+ external_events: impl Stream<Item = E> + Unpin + 'a,
31
+ ) -> Box<dyn Stream<Item = Self::Item> + Unpin + 'a>;
32
+ }
33
+
34
+ pub trait MergeExternalSend<'a, E> {
35
+ type Item;
36
+
37
+ fn merge_external_send(
38
+ self,
39
+ external_events: impl Stream<Item = E> + Unpin + Send + 'a,
40
+ ) -> Box<dyn Stream<Item = Self::Item> + Unpin + Send + 'a>;
41
+ }
42
+
43
+ impl<'a, E> MergeExternal<'a, E> for super::EventStream
44
+ where
45
+ E: 'static,
46
+ {
47
+ type Item = MergedEvent<E>;
48
+
49
+ fn merge_external(
50
+ self,
51
+ external_events: impl Stream<Item = E> + Unpin + 'a,
52
+ ) -> Box<dyn Stream<Item = Self::Item> + Unpin + 'a> {
53
+ let dora = self.map(MergedEvent::Dora);
54
+ let external = external_events.map(MergedEvent::External);
55
+ Box::new((dora, external).merge())
56
+ }
57
+ }
58
+
59
+ impl<'a, E> MergeExternalSend<'a, E> for super::EventStream
60
+ where
61
+ E: 'static,
62
+ {
63
+ type Item = MergedEvent<E>;
64
+
65
+ fn merge_external_send(
66
+ self,
67
+ external_events: impl Stream<Item = E> + Unpin + Send + 'a,
68
+ ) -> Box<dyn Stream<Item = Self::Item> + Unpin + Send + 'a> {
69
+ let dora = self.map(MergedEvent::Dora);
70
+ let external = external_events.map(MergedEvent::External);
71
+ Box::new((dora, external).merge())
72
+ }
73
+ }
74
+
75
+ impl<'a, E, F, S> MergeExternal<'a, F> for S
76
+ where
77
+ S: Stream<Item = MergedEvent<E>> + Unpin + 'a,
78
+ E: 'a,
79
+ F: 'a,
80
+ {
81
+ type Item = MergedEvent<Either<E, F>>;
82
+
83
+ fn merge_external(
84
+ self,
85
+ external_events: impl Stream<Item = F> + Unpin + 'a,
86
+ ) -> Box<dyn Stream<Item = Self::Item> + Unpin + 'a> {
87
+ let first = self.map(|e| match e {
88
+ MergedEvent::Dora(d) => MergedEvent::Dora(d),
89
+ MergedEvent::External(e) => MergedEvent::External(Either::First(e)),
90
+ });
91
+ let second = external_events.map(|e| MergedEvent::External(Either::Second(e)));
92
+ Box::new((first, second).merge())
93
+ }
94
+ }
95
+
96
+ impl<'a, E, F, S> MergeExternalSend<'a, F> for S
97
+ where
98
+ S: Stream<Item = MergedEvent<E>> + Unpin + Send + 'a,
99
+ E: 'a,
100
+ F: 'a,
101
+ {
102
+ type Item = MergedEvent<Either<E, F>>;
103
+
104
+ fn merge_external_send(
105
+ self,
106
+ external_events: impl Stream<Item = F> + Unpin + Send + 'a,
107
+ ) -> Box<dyn Stream<Item = Self::Item> + Unpin + Send + 'a> {
108
+ let first = self.map(|e| match e {
109
+ MergedEvent::Dora(d) => MergedEvent::Dora(d),
110
+ MergedEvent::External(e) => MergedEvent::External(Either::First(e)),
111
+ });
112
+ let second = external_events.map(|e| MergedEvent::External(Either::Second(e)));
113
+ Box::new((first, second).merge())
114
+ }
115
+ }
apis/rust/node/src/event_stream/mod.rs ADDED
@@ -0,0 +1,226 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ use std::{sync::Arc, time::Duration};
2
+
3
+ pub use event::{Event, MappedInputData, RawData};
4
+ use futures::{
5
+ future::{select, Either},
6
+ Stream, StreamExt,
7
+ };
8
+ use futures_timer::Delay;
9
+
10
+ use self::{
11
+ event::SharedMemoryData,
12
+ thread::{EventItem, EventStreamThreadHandle},
13
+ };
14
+ use crate::daemon_connection::DaemonChannel;
15
+ use dora_core::{
16
+ config::NodeId,
17
+ daemon_messages::{
18
+ self, DaemonCommunication, DaemonRequest, DataflowId, NodeEvent, Timestamped,
19
+ },
20
+ message::uhlc,
21
+ };
22
+ use eyre::{eyre, Context};
23
+
24
+ mod event;
25
+ pub mod merged;
26
+ mod thread;
27
+
28
+ pub struct EventStream {
29
+ node_id: NodeId,
30
+ receiver: flume::r#async::RecvStream<'static, EventItem>,
31
+ _thread_handle: EventStreamThreadHandle,
32
+ close_channel: DaemonChannel,
33
+ clock: Arc<uhlc::HLC>,
34
+ }
35
+
36
+ impl EventStream {
37
+ #[tracing::instrument(level = "trace", skip(clock))]
38
+ pub(crate) fn init(
39
+ dataflow_id: DataflowId,
40
+ node_id: &NodeId,
41
+ daemon_communication: &DaemonCommunication,
42
+ clock: Arc<uhlc::HLC>,
43
+ ) -> eyre::Result<Self> {
44
+ let channel = match daemon_communication {
45
+ DaemonCommunication::Shmem {
46
+ daemon_events_region_id,
47
+ ..
48
+ } => unsafe { DaemonChannel::new_shmem(daemon_events_region_id) }.wrap_err_with(
49
+ || format!("failed to create shmem event stream for node `{node_id}`"),
50
+ )?,
51
+ DaemonCommunication::Tcp { socket_addr } => DaemonChannel::new_tcp(*socket_addr)
52
+ .wrap_err_with(|| format!("failed to connect event stream for node `{node_id}`"))?,
53
+ };
54
+
55
+ let close_channel = match daemon_communication {
56
+ DaemonCommunication::Shmem {
57
+ daemon_events_close_region_id,
58
+ ..
59
+ } => unsafe { DaemonChannel::new_shmem(daemon_events_close_region_id) }.wrap_err_with(
60
+ || format!("failed to create shmem event close channel for node `{node_id}`"),
61
+ )?,
62
+ DaemonCommunication::Tcp { socket_addr } => DaemonChannel::new_tcp(*socket_addr)
63
+ .wrap_err_with(|| {
64
+ format!("failed to connect event close channel for node `{node_id}`")
65
+ })?,
66
+ };
67
+
68
+ Self::init_on_channel(dataflow_id, node_id, channel, close_channel, clock)
69
+ }
70
+
71
+ pub(crate) fn init_on_channel(
72
+ dataflow_id: DataflowId,
73
+ node_id: &NodeId,
74
+ mut channel: DaemonChannel,
75
+ mut close_channel: DaemonChannel,
76
+ clock: Arc<uhlc::HLC>,
77
+ ) -> eyre::Result<Self> {
78
+ channel.register(dataflow_id, node_id.clone(), clock.new_timestamp())?;
79
+ let reply = channel
80
+ .request(&Timestamped {
81
+ inner: DaemonRequest::Subscribe,
82
+ timestamp: clock.new_timestamp(),
83
+ })
84
+ .map_err(|e| eyre!(e))
85
+ .wrap_err("failed to create subscription with dora-daemon")?;
86
+
87
+ match reply {
88
+ daemon_messages::DaemonReply::Result(Ok(())) => {}
89
+ daemon_messages::DaemonReply::Result(Err(err)) => {
90
+ eyre::bail!("subscribe failed: {err}")
91
+ }
92
+ other => eyre::bail!("unexpected subscribe reply: {other:?}"),
93
+ }
94
+
95
+ close_channel.register(dataflow_id, node_id.clone(), clock.new_timestamp())?;
96
+
97
+ let (tx, rx) = flume::bounded(0);
98
+ let thread_handle = thread::init(node_id.clone(), tx, channel, clock.clone())?;
99
+
100
+ Ok(EventStream {
101
+ node_id: node_id.clone(),
102
+ receiver: rx.into_stream(),
103
+ _thread_handle: thread_handle,
104
+ close_channel,
105
+ clock,
106
+ })
107
+ }
108
+
109
+ /// wait for the next event on the events stream.
110
+ pub fn recv(&mut self) -> Option<Event> {
111
+ futures::executor::block_on(self.recv_async())
112
+ }
113
+
114
+ /// wait for the next event on the events stream until timeout
115
+ pub fn recv_timeout(&mut self, dur: Duration) -> Option<Event> {
116
+ futures::executor::block_on(self.recv_async_timeout(dur))
117
+ }
118
+
119
+ pub async fn recv_async(&mut self) -> Option<Event> {
120
+ self.receiver.next().await.map(Self::convert_event_item)
121
+ }
122
+
123
+ pub async fn recv_async_timeout(&mut self, dur: Duration) -> Option<Event> {
124
+ let next_event = match select(Delay::new(dur), self.receiver.next()).await {
125
+ Either::Left((_elapsed, _)) => {
126
+ Some(EventItem::TimeoutError(eyre!("Receiver timed out")))
127
+ }
128
+ Either::Right((event, _)) => event,
129
+ };
130
+ next_event.map(Self::convert_event_item)
131
+ }
132
+
133
+ fn convert_event_item(item: EventItem) -> Event {
134
+ match item {
135
+ EventItem::NodeEvent { event, ack_channel } => match event {
136
+ NodeEvent::Stop => Event::Stop,
137
+ NodeEvent::Reload { operator_id } => Event::Reload { operator_id },
138
+ NodeEvent::InputClosed { id } => Event::InputClosed { id },
139
+ NodeEvent::Input { id, metadata, data } => {
140
+ let data = match data {
141
+ None => Ok(None),
142
+ Some(daemon_messages::DataMessage::Vec(v)) => Ok(Some(RawData::Vec(v))),
143
+ Some(daemon_messages::DataMessage::SharedMemory {
144
+ shared_memory_id,
145
+ len,
146
+ drop_token: _, // handled in `event_stream_loop`
147
+ }) => unsafe {
148
+ MappedInputData::map(&shared_memory_id, len).map(|data| {
149
+ Some(RawData::SharedMemory(SharedMemoryData {
150
+ data,
151
+ _drop: ack_channel,
152
+ }))
153
+ })
154
+ },
155
+ };
156
+ let data = data.and_then(|data| {
157
+ let raw_data = data.unwrap_or(RawData::Empty);
158
+ raw_data
159
+ .into_arrow_array(&metadata.type_info)
160
+ .map(arrow::array::make_array)
161
+ });
162
+ match data {
163
+ Ok(data) => Event::Input {
164
+ id,
165
+ metadata,
166
+ data: data.into(),
167
+ },
168
+ Err(err) => Event::Error(format!("{err:?}")),
169
+ }
170
+ }
171
+ NodeEvent::AllInputsClosed => {
172
+ let err = eyre!(
173
+ "received `AllInputsClosed` event, which should be handled by background task"
174
+ );
175
+ tracing::error!("{err:?}");
176
+ Event::Error(err.wrap_err("internal error").to_string())
177
+ }
178
+ },
179
+
180
+ EventItem::FatalError(err) => {
181
+ Event::Error(format!("fatal event stream error: {err:?}"))
182
+ }
183
+ EventItem::TimeoutError(err) => {
184
+ Event::Error(format!("Timeout event stream error: {err:?}"))
185
+ }
186
+ }
187
+ }
188
+ }
189
+
190
+ impl Stream for EventStream {
191
+ type Item = Event;
192
+
193
+ fn poll_next(
194
+ mut self: std::pin::Pin<&mut Self>,
195
+ cx: &mut std::task::Context<'_>,
196
+ ) -> std::task::Poll<Option<Self::Item>> {
197
+ self.receiver
198
+ .poll_next_unpin(cx)
199
+ .map(|item| item.map(Self::convert_event_item))
200
+ }
201
+ }
202
+
203
+ impl Drop for EventStream {
204
+ #[tracing::instrument(skip(self), fields(%self.node_id))]
205
+ fn drop(&mut self) {
206
+ let request = Timestamped {
207
+ inner: DaemonRequest::EventStreamDropped,
208
+ timestamp: self.clock.new_timestamp(),
209
+ };
210
+ let result = self
211
+ .close_channel
212
+ .request(&request)
213
+ .map_err(|e| eyre!(e))
214
+ .wrap_err("failed to signal event stream closure to dora-daemon")
215
+ .and_then(|r| match r {
216
+ daemon_messages::DaemonReply::Result(Ok(())) => Ok(()),
217
+ daemon_messages::DaemonReply::Result(Err(err)) => {
218
+ Err(eyre!("EventStreamClosed failed: {err}"))
219
+ }
220
+ other => Err(eyre!("unexpected EventStreamClosed reply: {other:?}")),
221
+ });
222
+ if let Err(err) = result {
223
+ tracing::warn!("{err:?}")
224
+ }
225
+ }
226
+ }
apis/rust/node/src/event_stream/thread.rs ADDED
@@ -0,0 +1,269 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ use dora_core::{
2
+ config::NodeId,
3
+ daemon_messages::{DaemonReply, DaemonRequest, DropToken, NodeEvent, Timestamped},
4
+ message::uhlc::{self, Timestamp},
5
+ };
6
+ use eyre::{eyre, Context};
7
+ use flume::RecvTimeoutError;
8
+ use std::{
9
+ sync::Arc,
10
+ time::{Duration, Instant},
11
+ };
12
+
13
+ use crate::daemon_connection::DaemonChannel;
14
+
15
+ pub fn init(
16
+ node_id: NodeId,
17
+ tx: flume::Sender<EventItem>,
18
+ channel: DaemonChannel,
19
+ clock: Arc<uhlc::HLC>,
20
+ ) -> eyre::Result<EventStreamThreadHandle> {
21
+ let node_id_cloned = node_id.clone();
22
+ let join_handle = std::thread::spawn(|| event_stream_loop(node_id_cloned, tx, channel, clock));
23
+ Ok(EventStreamThreadHandle::new(node_id, join_handle))
24
+ }
25
+
26
+ #[derive(Debug)]
27
+ pub enum EventItem {
28
+ NodeEvent {
29
+ event: NodeEvent,
30
+ ack_channel: flume::Sender<()>,
31
+ },
32
+ FatalError(eyre::Report),
33
+ TimeoutError(eyre::Report),
34
+ }
35
+
36
+ pub struct EventStreamThreadHandle {
37
+ node_id: NodeId,
38
+ handle: flume::Receiver<std::thread::Result<()>>,
39
+ }
40
+
41
+ impl EventStreamThreadHandle {
42
+ fn new(node_id: NodeId, join_handle: std::thread::JoinHandle<()>) -> Self {
43
+ let (tx, rx) = flume::bounded(1);
44
+ std::thread::spawn(move || {
45
+ let _ = tx.send(join_handle.join());
46
+ });
47
+ Self {
48
+ node_id,
49
+ handle: rx,
50
+ }
51
+ }
52
+ }
53
+
54
+ impl Drop for EventStreamThreadHandle {
55
+ #[tracing::instrument(skip(self), fields(node_id = %self.node_id))]
56
+ fn drop(&mut self) {
57
+ if self.handle.is_empty() {
58
+ tracing::trace!("waiting for event stream thread");
59
+ }
60
+ match self.handle.recv_timeout(Duration::from_secs(20)) {
61
+ Ok(Ok(())) => {
62
+ tracing::trace!("event stream thread finished");
63
+ }
64
+ Ok(Err(_)) => {
65
+ tracing::error!("event stream thread panicked");
66
+ }
67
+ Err(RecvTimeoutError::Timeout) => {
68
+ tracing::warn!("timeout while waiting for event stream thread");
69
+ }
70
+ Err(RecvTimeoutError::Disconnected) => {
71
+ tracing::warn!("event stream thread result channel closed unexpectedly");
72
+ }
73
+ }
74
+ }
75
+ }
76
+
77
+ #[tracing::instrument(skip(tx, channel, clock))]
78
+ fn event_stream_loop(
79
+ node_id: NodeId,
80
+ tx: flume::Sender<EventItem>,
81
+ mut channel: DaemonChannel,
82
+ clock: Arc<uhlc::HLC>,
83
+ ) {
84
+ let mut tx = Some(tx);
85
+ let mut pending_drop_tokens: Vec<(DropToken, flume::Receiver<()>, Instant, u64)> = Vec::new();
86
+ let mut drop_tokens = Vec::new();
87
+
88
+ let result = 'outer: loop {
89
+ if let Err(err) = handle_pending_drop_tokens(&mut pending_drop_tokens, &mut drop_tokens) {
90
+ break 'outer Err(err);
91
+ }
92
+
93
+ let daemon_request = Timestamped {
94
+ inner: DaemonRequest::NextEvent {
95
+ drop_tokens: std::mem::take(&mut drop_tokens),
96
+ },
97
+ timestamp: clock.new_timestamp(),
98
+ };
99
+ let events = match channel.request(&daemon_request) {
100
+ Ok(DaemonReply::NextEvents(events)) => {
101
+ if events.is_empty() {
102
+ tracing::trace!("event stream closed for node `{node_id}`");
103
+ break Ok(());
104
+ } else {
105
+ events
106
+ }
107
+ }
108
+ Ok(other) => {
109
+ let err = eyre!("unexpected control reply: {other:?}");
110
+ tracing::warn!("{err:?}");
111
+ continue;
112
+ }
113
+ Err(err) => {
114
+ let err = eyre!(err).wrap_err("failed to receive incoming event");
115
+ tracing::warn!("{err:?}");
116
+ continue;
117
+ }
118
+ };
119
+ for Timestamped { inner, timestamp } in events {
120
+ if let Err(err) = clock.update_with_timestamp(&timestamp) {
121
+ tracing::warn!("failed to update HLC: {err}");
122
+ }
123
+ let drop_token = match &inner {
124
+ NodeEvent::Input {
125
+ data: Some(data), ..
126
+ } => data.drop_token(),
127
+ NodeEvent::AllInputsClosed => {
128
+ // close the event stream
129
+ tx = None;
130
+ // skip this internal event
131
+ continue;
132
+ }
133
+ _ => None,
134
+ };
135
+
136
+ if let Some(tx) = tx.as_ref() {
137
+ let (drop_tx, drop_rx) = flume::bounded(0);
138
+ match tx.send(EventItem::NodeEvent {
139
+ event: inner,
140
+ ack_channel: drop_tx,
141
+ }) {
142
+ Ok(()) => {}
143
+ Err(send_error) => {
144
+ let event = send_error.into_inner();
145
+ tracing::trace!(
146
+ "event channel was closed already, could not forward `{event:?}`"
147
+ );
148
+
149
+ break 'outer Ok(());
150
+ }
151
+ }
152
+
153
+ if let Some(token) = drop_token {
154
+ pending_drop_tokens.push((token, drop_rx, Instant::now(), 1));
155
+ }
156
+ } else {
157
+ tracing::warn!("dropping event because event `tx` was already closed: `{inner:?}`");
158
+ }
159
+ }
160
+ };
161
+ if let Err(err) = result {
162
+ if let Some(tx) = tx.as_ref() {
163
+ if let Err(flume::SendError(item)) = tx.send(EventItem::FatalError(err)) {
164
+ let err = match item {
165
+ EventItem::FatalError(err) => err,
166
+ _ => unreachable!(),
167
+ };
168
+ tracing::error!("failed to report fatal EventStream error: {err:?}");
169
+ }
170
+ } else {
171
+ tracing::error!("received error event after `tx` was closed: {err:?}");
172
+ }
173
+ }
174
+
175
+ if let Err(err) = report_remaining_drop_tokens(
176
+ channel,
177
+ drop_tokens,
178
+ pending_drop_tokens,
179
+ clock.new_timestamp(),
180
+ )
181
+ .context("failed to report remaining drop tokens")
182
+ {
183
+ tracing::warn!("{err:?}");
184
+ }
185
+ }
186
+
187
+ fn handle_pending_drop_tokens(
188
+ pending_drop_tokens: &mut Vec<(DropToken, flume::Receiver<()>, Instant, u64)>,
189
+ drop_tokens: &mut Vec<DropToken>,
190
+ ) -> eyre::Result<()> {
191
+ let mut still_pending = Vec::new();
192
+ for (token, rx, since, warn) in pending_drop_tokens.drain(..) {
193
+ match rx.try_recv() {
194
+ Ok(()) => return Err(eyre!("Node API should not send anything on ACK channel")),
195
+ Err(flume::TryRecvError::Disconnected) => {
196
+ // the event was dropped -> add the drop token to the list
197
+ drop_tokens.push(token);
198
+ }
199
+ Err(flume::TryRecvError::Empty) => {
200
+ let duration = Duration::from_secs(30 * warn);
201
+ if since.elapsed() > duration {
202
+ tracing::warn!("timeout: token {token:?} was not dropped after {duration:?}");
203
+ }
204
+ still_pending.push((token, rx, since, warn + 1));
205
+ }
206
+ }
207
+ }
208
+ *pending_drop_tokens = still_pending;
209
+ Ok(())
210
+ }
211
+
212
+ fn report_remaining_drop_tokens(
213
+ mut channel: DaemonChannel,
214
+ mut drop_tokens: Vec<DropToken>,
215
+ mut pending_drop_tokens: Vec<(DropToken, flume::Receiver<()>, Instant, u64)>,
216
+ timestamp: Timestamp,
217
+ ) -> eyre::Result<()> {
218
+ while !(pending_drop_tokens.is_empty() && drop_tokens.is_empty()) {
219
+ report_drop_tokens(&mut drop_tokens, &mut channel, timestamp)?;
220
+
221
+ let mut still_pending = Vec::new();
222
+ for (token, rx, since, _) in pending_drop_tokens.drain(..) {
223
+ match rx.recv_timeout(Duration::from_millis(100)) {
224
+ Ok(()) => return Err(eyre!("Node API should not send anything on ACK channel")),
225
+ Err(flume::RecvTimeoutError::Disconnected) => {
226
+ // the event was dropped -> add the drop token to the list
227
+ drop_tokens.push(token);
228
+ }
229
+ Err(flume::RecvTimeoutError::Timeout) => {
230
+ let duration = Duration::from_secs(30);
231
+ if since.elapsed() > duration {
232
+ tracing::warn!(
233
+ "timeout: node finished, but token {token:?} was still not \
234
+ dropped after {duration:?} -> ignoring it"
235
+ );
236
+ } else {
237
+ still_pending.push((token, rx, since, 0));
238
+ }
239
+ }
240
+ }
241
+ }
242
+ pending_drop_tokens = still_pending;
243
+ if !pending_drop_tokens.is_empty() {
244
+ tracing::trace!("waiting for drop for {} events", pending_drop_tokens.len());
245
+ }
246
+ }
247
+
248
+ Ok(())
249
+ }
250
+
251
+ fn report_drop_tokens(
252
+ drop_tokens: &mut Vec<DropToken>,
253
+ channel: &mut DaemonChannel,
254
+ timestamp: Timestamp,
255
+ ) -> Result<(), eyre::ErrReport> {
256
+ if drop_tokens.is_empty() {
257
+ return Ok(());
258
+ }
259
+ let daemon_request = Timestamped {
260
+ inner: DaemonRequest::ReportDropTokens {
261
+ drop_tokens: std::mem::take(drop_tokens),
262
+ },
263
+ timestamp,
264
+ };
265
+ match channel.request(&daemon_request)? {
266
+ dora_core::daemon_messages::DaemonReply::Empty => Ok(()),
267
+ other => Err(eyre!("unexpected ReportDropTokens reply: {other:?}")),
268
+ }
269
+ }
apis/rust/node/src/lib.rs ADDED
@@ -0,0 +1,26 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ //! The custom node API allow you to integrate `dora` into your application.
2
+ //! It allows you to retrieve input and send output in any fashion you want.
3
+ //!
4
+ //! Try it out with:
5
+ //!
6
+ //! ```bash
7
+ //! dora new node --kind node
8
+ //! ```
9
+ //!
10
+ //! You can also generate a dora rust project with
11
+ //!
12
+ //! ```bash
13
+ //! dora new project_xyz --kind dataflow
14
+ //! ```
15
+ //!
16
+ pub use arrow;
17
+ pub use dora_arrow_convert::*;
18
+ pub use dora_core;
19
+ pub use dora_core::message::{uhlc, Metadata, MetadataParameters};
20
+ pub use event_stream::{merged, Event, EventStream, MappedInputData, RawData};
21
+ pub use flume::Receiver;
22
+ pub use node::{arrow_utils, DataSample, DoraNode, ZERO_COPY_THRESHOLD};
23
+
24
+ mod daemon_connection;
25
+ mod event_stream;
26
+ mod node;
apis/rust/node/src/node/arrow_utils.rs ADDED
@@ -0,0 +1,71 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ use arrow::array::{ArrayData, BufferSpec};
2
+ use dora_core::message::{ArrowTypeInfo, BufferOffset};
3
+
4
+ pub fn required_data_size(array: &ArrayData) -> usize {
5
+ let mut next_offset = 0;
6
+ required_data_size_inner(array, &mut next_offset);
7
+ next_offset
8
+ }
9
+ fn required_data_size_inner(array: &ArrayData, next_offset: &mut usize) {
10
+ let layout = arrow::array::layout(array.data_type());
11
+ for (buffer, spec) in array.buffers().iter().zip(&layout.buffers) {
12
+ // consider alignment padding
13
+ if let BufferSpec::FixedWidth { alignment, .. } = spec {
14
+ *next_offset = (*next_offset + alignment - 1) / alignment * alignment;
15
+ }
16
+ *next_offset += buffer.len();
17
+ }
18
+ for child in array.child_data() {
19
+ required_data_size_inner(child, next_offset);
20
+ }
21
+ }
22
+
23
+ pub fn copy_array_into_sample(target_buffer: &mut [u8], arrow_array: &ArrayData) -> ArrowTypeInfo {
24
+ let mut next_offset = 0;
25
+ copy_array_into_sample_inner(target_buffer, &mut next_offset, arrow_array)
26
+ }
27
+
28
+ fn copy_array_into_sample_inner(
29
+ target_buffer: &mut [u8],
30
+ next_offset: &mut usize,
31
+ arrow_array: &ArrayData,
32
+ ) -> ArrowTypeInfo {
33
+ let mut buffer_offsets = Vec::new();
34
+ let layout = arrow::array::layout(arrow_array.data_type());
35
+ for (buffer, spec) in arrow_array.buffers().iter().zip(&layout.buffers) {
36
+ let len = buffer.len();
37
+ assert!(
38
+ target_buffer[*next_offset..].len() >= len,
39
+ "target buffer too small (total_len: {}, offset: {}, required_len: {len})",
40
+ target_buffer.len(),
41
+ *next_offset,
42
+ );
43
+ // add alignment padding
44
+ if let BufferSpec::FixedWidth { alignment, .. } = spec {
45
+ *next_offset = (*next_offset + alignment - 1) / alignment * alignment;
46
+ }
47
+
48
+ target_buffer[*next_offset..][..len].copy_from_slice(buffer.as_slice());
49
+ buffer_offsets.push(BufferOffset {
50
+ offset: *next_offset,
51
+ len,
52
+ });
53
+ *next_offset += len;
54
+ }
55
+
56
+ let mut child_data = Vec::new();
57
+ for child in arrow_array.child_data() {
58
+ let child_type_info = copy_array_into_sample_inner(target_buffer, next_offset, child);
59
+ child_data.push(child_type_info);
60
+ }
61
+
62
+ ArrowTypeInfo {
63
+ data_type: arrow_array.data_type().clone(),
64
+ len: arrow_array.len(),
65
+ null_count: arrow_array.null_count(),
66
+ validity: arrow_array.nulls().map(|b| b.validity().to_owned()),
67
+ offset: arrow_array.offset(),
68
+ buffer_offsets,
69
+ child_data,
70
+ }
71
+ }
apis/rust/node/src/node/control_channel.rs ADDED
@@ -0,0 +1,106 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ use std::sync::Arc;
2
+
3
+ use crate::daemon_connection::DaemonChannel;
4
+ use dora_core::{
5
+ config::{DataId, NodeId},
6
+ daemon_messages::{DaemonCommunication, DaemonRequest, DataMessage, DataflowId, Timestamped},
7
+ message::{uhlc::HLC, Metadata},
8
+ };
9
+ use eyre::{bail, eyre, Context};
10
+
11
+ pub(crate) struct ControlChannel {
12
+ channel: DaemonChannel,
13
+ clock: Arc<HLC>,
14
+ }
15
+
16
+ impl ControlChannel {
17
+ #[tracing::instrument(level = "trace", skip(clock))]
18
+ pub(crate) fn init(
19
+ dataflow_id: DataflowId,
20
+ node_id: &NodeId,
21
+ daemon_communication: &DaemonCommunication,
22
+ clock: Arc<HLC>,
23
+ ) -> eyre::Result<Self> {
24
+ let channel = match daemon_communication {
25
+ DaemonCommunication::Shmem {
26
+ daemon_control_region_id,
27
+ ..
28
+ } => unsafe { DaemonChannel::new_shmem(daemon_control_region_id) }
29
+ .wrap_err("failed to create shmem control channel")?,
30
+ DaemonCommunication::Tcp { socket_addr } => DaemonChannel::new_tcp(*socket_addr)
31
+ .wrap_err("failed to connect control channel")?,
32
+ };
33
+
34
+ Self::init_on_channel(dataflow_id, node_id, channel, clock)
35
+ }
36
+
37
+ #[tracing::instrument(skip(channel, clock), level = "trace")]
38
+ pub fn init_on_channel(
39
+ dataflow_id: DataflowId,
40
+ node_id: &NodeId,
41
+ mut channel: DaemonChannel,
42
+ clock: Arc<HLC>,
43
+ ) -> eyre::Result<Self> {
44
+ channel.register(dataflow_id, node_id.clone(), clock.new_timestamp())?;
45
+
46
+ Ok(Self { channel, clock })
47
+ }
48
+
49
+ pub fn report_outputs_done(&mut self) -> eyre::Result<()> {
50
+ let reply = self
51
+ .channel
52
+ .request(&Timestamped {
53
+ inner: DaemonRequest::OutputsDone,
54
+ timestamp: self.clock.new_timestamp(),
55
+ })
56
+ .wrap_err("failed to report outputs done to dora-daemon")?;
57
+ match reply {
58
+ dora_core::daemon_messages::DaemonReply::Result(result) => result
59
+ .map_err(|e| eyre!(e))
60
+ .wrap_err("failed to report outputs done event to dora-daemon")?,
61
+ other => bail!("unexpected outputs done reply: {other:?}"),
62
+ }
63
+ Ok(())
64
+ }
65
+
66
+ pub fn report_closed_outputs(&mut self, outputs: Vec<DataId>) -> eyre::Result<()> {
67
+ let reply = self
68
+ .channel
69
+ .request(&Timestamped {
70
+ inner: DaemonRequest::CloseOutputs(outputs),
71
+ timestamp: self.clock.new_timestamp(),
72
+ })
73
+ .wrap_err("failed to report closed outputs to dora-daemon")?;
74
+ match reply {
75
+ dora_core::daemon_messages::DaemonReply::Result(result) => result
76
+ .map_err(|e| eyre!(e))
77
+ .wrap_err("failed to receive closed outputs reply from dora-daemon")?,
78
+ other => bail!("unexpected closed outputs reply: {other:?}"),
79
+ }
80
+ Ok(())
81
+ }
82
+
83
+ pub fn send_message(
84
+ &mut self,
85
+ output_id: DataId,
86
+ metadata: Metadata,
87
+ data: Option<DataMessage>,
88
+ ) -> eyre::Result<()> {
89
+ let request = DaemonRequest::SendMessage {
90
+ output_id,
91
+ metadata,
92
+ data,
93
+ };
94
+ let reply = self
95
+ .channel
96
+ .request(&Timestamped {
97
+ inner: request,
98
+ timestamp: self.clock.new_timestamp(),
99
+ })
100
+ .wrap_err("failed to send SendMessage request to dora-daemon")?;
101
+ match reply {
102
+ dora_core::daemon_messages::DaemonReply::Empty => Ok(()),
103
+ other => bail!("unexpected SendMessage reply: {other:?}"),
104
+ }
105
+ }
106
+ }
apis/rust/node/src/node/drop_stream.rs ADDED
@@ -0,0 +1,178 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ use std::{sync::Arc, time::Duration};
2
+
3
+ use crate::daemon_connection::DaemonChannel;
4
+ use dora_core::{
5
+ config::NodeId,
6
+ daemon_messages::{
7
+ self, DaemonCommunication, DaemonReply, DaemonRequest, DataflowId, DropToken,
8
+ NodeDropEvent, Timestamped,
9
+ },
10
+ message::uhlc,
11
+ };
12
+ use eyre::{eyre, Context};
13
+ use flume::RecvTimeoutError;
14
+
15
+ pub struct DropStream {
16
+ receiver: flume::Receiver<DropToken>,
17
+ _thread_handle: DropStreamThreadHandle,
18
+ }
19
+
20
+ impl DropStream {
21
+ #[tracing::instrument(level = "trace", skip(hlc))]
22
+ pub(crate) fn init(
23
+ dataflow_id: DataflowId,
24
+ node_id: &NodeId,
25
+ daemon_communication: &DaemonCommunication,
26
+ hlc: Arc<uhlc::HLC>,
27
+ ) -> eyre::Result<Self> {
28
+ let channel = match daemon_communication {
29
+ DaemonCommunication::Shmem {
30
+ daemon_drop_region_id,
31
+ ..
32
+ } => {
33
+ unsafe { DaemonChannel::new_shmem(daemon_drop_region_id) }.wrap_err_with(|| {
34
+ format!("failed to create shmem drop stream for node `{node_id}`")
35
+ })?
36
+ }
37
+ DaemonCommunication::Tcp { socket_addr } => DaemonChannel::new_tcp(*socket_addr)
38
+ .wrap_err_with(|| format!("failed to connect drop stream for node `{node_id}`"))?,
39
+ };
40
+
41
+ Self::init_on_channel(dataflow_id, node_id, channel, hlc)
42
+ }
43
+
44
+ pub fn init_on_channel(
45
+ dataflow_id: DataflowId,
46
+ node_id: &NodeId,
47
+ mut channel: DaemonChannel,
48
+ clock: Arc<uhlc::HLC>,
49
+ ) -> eyre::Result<Self> {
50
+ channel.register(dataflow_id, node_id.clone(), clock.new_timestamp())?;
51
+
52
+ let reply = channel
53
+ .request(&Timestamped {
54
+ inner: DaemonRequest::SubscribeDrop,
55
+ timestamp: clock.new_timestamp(),
56
+ })
57
+ .map_err(|e| eyre!(e))
58
+ .wrap_err("failed to create subscription with dora-daemon")?;
59
+
60
+ match reply {
61
+ daemon_messages::DaemonReply::Result(Ok(())) => {}
62
+ daemon_messages::DaemonReply::Result(Err(err)) => {
63
+ eyre::bail!("drop subscribe failed: {err}")
64
+ }
65
+ other => eyre::bail!("unexpected drop subscribe reply: {other:?}"),
66
+ }
67
+
68
+ let (tx, rx) = flume::bounded(0);
69
+ let node_id_cloned = node_id.clone();
70
+
71
+ let handle = std::thread::spawn(|| drop_stream_loop(node_id_cloned, tx, channel, clock));
72
+
73
+ Ok(Self {
74
+ receiver: rx,
75
+ _thread_handle: DropStreamThreadHandle::new(node_id.clone(), handle),
76
+ })
77
+ }
78
+ }
79
+
80
+ impl std::ops::Deref for DropStream {
81
+ type Target = flume::Receiver<DropToken>;
82
+
83
+ fn deref(&self) -> &Self::Target {
84
+ &self.receiver
85
+ }
86
+ }
87
+
88
+ #[tracing::instrument(skip(tx, channel, clock))]
89
+ fn drop_stream_loop(
90
+ node_id: NodeId,
91
+ tx: flume::Sender<DropToken>,
92
+ mut channel: DaemonChannel,
93
+ clock: Arc<uhlc::HLC>,
94
+ ) {
95
+ 'outer: loop {
96
+ let daemon_request = Timestamped {
97
+ inner: DaemonRequest::NextFinishedDropTokens,
98
+ timestamp: clock.new_timestamp(),
99
+ };
100
+ let events = match channel.request(&daemon_request) {
101
+ Ok(DaemonReply::NextDropEvents(events)) => {
102
+ if events.is_empty() {
103
+ tracing::trace!("drop stream closed for node `{node_id}`");
104
+ break;
105
+ } else {
106
+ events
107
+ }
108
+ }
109
+ Ok(other) => {
110
+ let err = eyre!("unexpected drop reply: {other:?}");
111
+ tracing::warn!("{err:?}");
112
+ continue;
113
+ }
114
+ Err(err) => {
115
+ let err = eyre!(err).wrap_err("failed to receive incoming drop event");
116
+ tracing::warn!("{err:?}");
117
+ continue;
118
+ }
119
+ };
120
+ for Timestamped { inner, timestamp } in events {
121
+ if let Err(err) = clock.update_with_timestamp(&timestamp) {
122
+ tracing::warn!("failed to update HLC: {err}");
123
+ }
124
+ match inner {
125
+ NodeDropEvent::OutputDropped { drop_token } => {
126
+ if tx.send(drop_token).is_err() {
127
+ tracing::warn!(
128
+ "drop channel was closed already, could not forward \
129
+ drop token`{drop_token:?}`"
130
+ );
131
+ break 'outer;
132
+ }
133
+ }
134
+ }
135
+ }
136
+ }
137
+ }
138
+
139
+ struct DropStreamThreadHandle {
140
+ node_id: NodeId,
141
+ handle: flume::Receiver<std::thread::Result<()>>,
142
+ }
143
+
144
+ impl DropStreamThreadHandle {
145
+ fn new(node_id: NodeId, join_handle: std::thread::JoinHandle<()>) -> Self {
146
+ let (tx, rx) = flume::bounded(1);
147
+ std::thread::spawn(move || {
148
+ let _ = tx.send(join_handle.join());
149
+ });
150
+ Self {
151
+ node_id,
152
+ handle: rx,
153
+ }
154
+ }
155
+ }
156
+
157
+ impl Drop for DropStreamThreadHandle {
158
+ #[tracing::instrument(skip(self), fields(node_id = %self.node_id))]
159
+ fn drop(&mut self) {
160
+ if self.handle.is_empty() {
161
+ tracing::trace!("waiting for drop stream thread");
162
+ }
163
+ match self.handle.recv_timeout(Duration::from_secs(2)) {
164
+ Ok(Ok(())) => {
165
+ tracing::trace!("drop stream thread done");
166
+ }
167
+ Ok(Err(_)) => {
168
+ tracing::error!("drop stream thread panicked");
169
+ }
170
+ Err(RecvTimeoutError::Timeout) => {
171
+ tracing::warn!("timeout while waiting for drop stream thread");
172
+ }
173
+ Err(RecvTimeoutError::Disconnected) => {
174
+ tracing::warn!("drop stream thread result channel closed unexpectedly");
175
+ }
176
+ }
177
+ }
178
+ }
apis/rust/node/src/node/mod.rs ADDED
@@ -0,0 +1,475 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ use crate::EventStream;
2
+
3
+ use self::{
4
+ arrow_utils::{copy_array_into_sample, required_data_size},
5
+ control_channel::ControlChannel,
6
+ drop_stream::DropStream,
7
+ };
8
+ use aligned_vec::{AVec, ConstAlign};
9
+ use arrow::array::Array;
10
+ use dora_core::{
11
+ config::{DataId, NodeId, NodeRunConfig},
12
+ daemon_messages::{DataMessage, DataflowId, DropToken, NodeConfig},
13
+ descriptor::Descriptor,
14
+ message::{uhlc, ArrowTypeInfo, Metadata, MetadataParameters},
15
+ };
16
+ use eyre::{bail, WrapErr};
17
+ use shared_memory_extended::{Shmem, ShmemConf};
18
+ use std::{
19
+ collections::{HashMap, VecDeque},
20
+ ops::{Deref, DerefMut},
21
+ sync::Arc,
22
+ time::Duration,
23
+ };
24
+
25
+ #[cfg(feature = "tracing")]
26
+ use dora_tracing::set_up_tracing;
27
+
28
+ pub mod arrow_utils;
29
+ mod control_channel;
30
+ mod drop_stream;
31
+
32
+ pub const ZERO_COPY_THRESHOLD: usize = 4096;
33
+
34
+ pub struct DoraNode {
35
+ id: NodeId,
36
+ dataflow_id: DataflowId,
37
+ node_config: NodeRunConfig,
38
+ control_channel: ControlChannel,
39
+ clock: Arc<uhlc::HLC>,
40
+
41
+ sent_out_shared_memory: HashMap<DropToken, ShmemHandle>,
42
+ drop_stream: DropStream,
43
+ cache: VecDeque<ShmemHandle>,
44
+
45
+ dataflow_descriptor: Descriptor,
46
+ }
47
+
48
+ impl DoraNode {
49
+ /// Initiate a node from environment variables set by `dora-coordinator`
50
+ ///
51
+ /// ```no_run
52
+ /// use dora_node_api::DoraNode;
53
+ ///
54
+ /// let (mut node, mut events) = DoraNode::init_from_env().expect("Could not init node.");
55
+ /// ```
56
+ ///
57
+ pub fn init_from_env() -> eyre::Result<(Self, EventStream)> {
58
+ let node_config: NodeConfig = {
59
+ let raw = std::env::var("DORA_NODE_CONFIG")
60
+ .wrap_err("env variable DORA_NODE_CONFIG must be set")?;
61
+ serde_yaml::from_str(&raw).context("failed to deserialize operator config")?
62
+ };
63
+ #[cfg(feature = "tracing")]
64
+ set_up_tracing(&node_config.node_id.to_string())
65
+ .context("failed to set up tracing subscriber")?;
66
+ Self::init(node_config)
67
+ }
68
+
69
+ #[tracing::instrument]
70
+ pub fn init(node_config: NodeConfig) -> eyre::Result<(Self, EventStream)> {
71
+ let NodeConfig {
72
+ dataflow_id,
73
+ node_id,
74
+ run_config,
75
+ daemon_communication,
76
+ dataflow_descriptor,
77
+ } = node_config;
78
+
79
+ let clock = Arc::new(uhlc::HLC::default());
80
+
81
+ let event_stream =
82
+ EventStream::init(dataflow_id, &node_id, &daemon_communication, clock.clone())
83
+ .wrap_err("failed to init event stream")?;
84
+ let drop_stream =
85
+ DropStream::init(dataflow_id, &node_id, &daemon_communication, clock.clone())
86
+ .wrap_err("failed to init drop stream")?;
87
+ let control_channel =
88
+ ControlChannel::init(dataflow_id, &node_id, &daemon_communication, clock.clone())
89
+ .wrap_err("failed to init control channel")?;
90
+
91
+ let node = Self {
92
+ id: node_id,
93
+ dataflow_id,
94
+ node_config: run_config,
95
+ control_channel,
96
+ clock,
97
+ sent_out_shared_memory: HashMap::new(),
98
+ drop_stream,
99
+ cache: VecDeque::new(),
100
+
101
+ dataflow_descriptor,
102
+ };
103
+ Ok((node, event_stream))
104
+ }
105
+
106
+ /// Send data from the node to the other nodes.
107
+ /// We take a closure as an input to enable zero copy on send.
108
+ ///
109
+ /// ```no_run
110
+ /// use dora_node_api::{DoraNode, MetadataParameters};
111
+ /// use dora_core::config::DataId;
112
+ ///
113
+ /// let (mut node, mut events) = DoraNode::init_from_env().expect("Could not init node.");
114
+ ///
115
+ /// let output = DataId::from("output_id".to_owned());
116
+ ///
117
+ /// let data: &[u8] = &[0, 1, 2, 3];
118
+ /// let parameters = MetadataParameters::default();
119
+ ///
120
+ /// node.send_output_raw(
121
+ /// output,
122
+ /// parameters,
123
+ /// data.len(),
124
+ /// |out| {
125
+ /// out.copy_from_slice(data);
126
+ /// }).expect("Could not send output");
127
+ /// ```
128
+ ///
129
+ pub fn send_output_raw<F>(
130
+ &mut self,
131
+ output_id: DataId,
132
+ parameters: MetadataParameters,
133
+ data_len: usize,
134
+ data: F,
135
+ ) -> eyre::Result<()>
136
+ where
137
+ F: FnOnce(&mut [u8]),
138
+ {
139
+ let mut sample = self.allocate_data_sample(data_len)?;
140
+ data(&mut sample);
141
+
142
+ let type_info = ArrowTypeInfo::byte_array(data_len);
143
+
144
+ self.send_output_sample(output_id, type_info, parameters, Some(sample))
145
+ }
146
+
147
+ pub fn send_output(
148
+ &mut self,
149
+ output_id: DataId,
150
+ parameters: MetadataParameters,
151
+ data: impl Array,
152
+ ) -> eyre::Result<()> {
153
+ let arrow_array = data.to_data();
154
+
155
+ let total_len = required_data_size(&arrow_array);
156
+
157
+ let mut sample = self.allocate_data_sample(total_len)?;
158
+ let type_info = copy_array_into_sample(&mut sample, &arrow_array);
159
+
160
+ self.send_output_sample(output_id, type_info, parameters, Some(sample))
161
+ .wrap_err("failed to send output")?;
162
+
163
+ Ok(())
164
+ }
165
+
166
+ pub fn send_output_bytes(
167
+ &mut self,
168
+ output_id: DataId,
169
+ parameters: MetadataParameters,
170
+ data_len: usize,
171
+ data: &[u8],
172
+ ) -> eyre::Result<()> {
173
+ self.send_output_raw(output_id, parameters, data_len, |sample| {
174
+ sample.copy_from_slice(data)
175
+ })
176
+ }
177
+
178
+ pub fn send_typed_output<F>(
179
+ &mut self,
180
+ output_id: DataId,
181
+ type_info: ArrowTypeInfo,
182
+ parameters: MetadataParameters,
183
+ data_len: usize,
184
+ data: F,
185
+ ) -> eyre::Result<()>
186
+ where
187
+ F: FnOnce(&mut [u8]),
188
+ {
189
+ let mut sample = self.allocate_data_sample(data_len)?;
190
+ data(&mut sample);
191
+
192
+ self.send_output_sample(output_id, type_info, parameters, Some(sample))
193
+ }
194
+
195
+ pub fn send_output_sample(
196
+ &mut self,
197
+ output_id: DataId,
198
+ type_info: ArrowTypeInfo,
199
+ parameters: MetadataParameters,
200
+ sample: Option<DataSample>,
201
+ ) -> eyre::Result<()> {
202
+ self.handle_finished_drop_tokens()?;
203
+
204
+ if !self.node_config.outputs.contains(&output_id) {
205
+ eyre::bail!("unknown output");
206
+ }
207
+ let metadata = Metadata::from_parameters(
208
+ self.clock.new_timestamp(),
209
+ type_info,
210
+ parameters.into_owned(),
211
+ );
212
+
213
+ let (data, shmem) = match sample {
214
+ Some(sample) => sample.finalize(),
215
+ None => (None, None),
216
+ };
217
+
218
+ self.control_channel
219
+ .send_message(output_id.clone(), metadata, data)
220
+ .wrap_err_with(|| format!("failed to send output {output_id}"))?;
221
+
222
+ if let Some((shared_memory, drop_token)) = shmem {
223
+ self.sent_out_shared_memory
224
+ .insert(drop_token, shared_memory);
225
+ }
226
+
227
+ Ok(())
228
+ }
229
+
230
+ pub fn close_outputs(&mut self, outputs: Vec<DataId>) -> eyre::Result<()> {
231
+ for output_id in &outputs {
232
+ if !self.node_config.outputs.remove(output_id) {
233
+ eyre::bail!("unknown output {output_id}");
234
+ }
235
+ }
236
+
237
+ self.control_channel
238
+ .report_closed_outputs(outputs)
239
+ .wrap_err("failed to report closed outputs to daemon")?;
240
+
241
+ Ok(())
242
+ }
243
+
244
+ pub fn id(&self) -> &NodeId {
245
+ &self.id
246
+ }
247
+
248
+ pub fn dataflow_id(&self) -> &DataflowId {
249
+ &self.dataflow_id
250
+ }
251
+
252
+ pub fn node_config(&self) -> &NodeRunConfig {
253
+ &self.node_config
254
+ }
255
+
256
+ pub fn allocate_data_sample(&mut self, data_len: usize) -> eyre::Result<DataSample> {
257
+ let data = if data_len >= ZERO_COPY_THRESHOLD {
258
+ // create shared memory region
259
+ let shared_memory = self.allocate_shared_memory(data_len)?;
260
+
261
+ DataSample {
262
+ inner: DataSampleInner::Shmem(shared_memory),
263
+ len: data_len,
264
+ }
265
+ } else {
266
+ let avec: AVec<u8, ConstAlign<128>> = AVec::__from_elem(128, 0, data_len);
267
+
268
+ avec.into()
269
+ };
270
+
271
+ Ok(data)
272
+ }
273
+
274
+ fn allocate_shared_memory(&mut self, data_len: usize) -> eyre::Result<ShmemHandle> {
275
+ let cache_index = self
276
+ .cache
277
+ .iter()
278
+ .enumerate()
279
+ .rev()
280
+ .filter(|(_, s)| s.len() >= data_len)
281
+ .min_by_key(|(_, s)| s.len())
282
+ .map(|(i, _)| i);
283
+ let memory = match cache_index {
284
+ Some(i) => {
285
+ // we know that this index exists, so we can safely unwrap here
286
+ self.cache.remove(i).unwrap()
287
+ }
288
+ None => ShmemHandle(Box::new(
289
+ ShmemConf::new()
290
+ .size(data_len)
291
+ .writable(true)
292
+ .create()
293
+ .wrap_err("failed to allocate shared memory")?,
294
+ )),
295
+ };
296
+ assert!(memory.len() >= data_len);
297
+
298
+ Ok(memory)
299
+ }
300
+
301
+ fn handle_finished_drop_tokens(&mut self) -> eyre::Result<()> {
302
+ loop {
303
+ match self.drop_stream.try_recv() {
304
+ Ok(token) => match self.sent_out_shared_memory.remove(&token) {
305
+ Some(region) => self.add_to_cache(region),
306
+ None => tracing::warn!("received unknown finished drop token `{token:?}`"),
307
+ },
308
+ Err(flume::TryRecvError::Empty) => break,
309
+ Err(flume::TryRecvError::Disconnected) => {
310
+ bail!("event stream was closed before sending all expected drop tokens")
311
+ }
312
+ }
313
+ }
314
+ Ok(())
315
+ }
316
+
317
+ fn add_to_cache(&mut self, memory: ShmemHandle) {
318
+ const MAX_CACHE_SIZE: usize = 20;
319
+
320
+ self.cache.push_back(memory);
321
+ while self.cache.len() > MAX_CACHE_SIZE {
322
+ self.cache.pop_front();
323
+ }
324
+ }
325
+
326
+ /// Returns the full dataflow descriptor that this node is part of.
327
+ ///
328
+ /// This method returns the parsed dataflow YAML file.
329
+ pub fn dataflow_descriptor(&self) -> &Descriptor {
330
+ &self.dataflow_descriptor
331
+ }
332
+ }
333
+
334
+ impl Drop for DoraNode {
335
+ #[tracing::instrument(skip(self), fields(self.id = %self.id), level = "trace")]
336
+ fn drop(&mut self) {
337
+ // close all outputs first to notify subscribers as early as possible
338
+ if let Err(err) = self
339
+ .control_channel
340
+ .report_closed_outputs(
341
+ std::mem::take(&mut self.node_config.outputs)
342
+ .into_iter()
343
+ .collect(),
344
+ )
345
+ .context("failed to close outputs on drop")
346
+ {
347
+ tracing::warn!("{err:?}")
348
+ }
349
+
350
+ while !self.sent_out_shared_memory.is_empty() {
351
+ if self.drop_stream.len() == 0 {
352
+ tracing::trace!(
353
+ "waiting for {} remaining drop tokens",
354
+ self.sent_out_shared_memory.len()
355
+ );
356
+ }
357
+
358
+ match self.drop_stream.recv_timeout(Duration::from_secs(10)) {
359
+ Ok(token) => {
360
+ self.sent_out_shared_memory.remove(&token);
361
+ }
362
+ Err(flume::RecvTimeoutError::Disconnected) => {
363
+ tracing::warn!(
364
+ "finished_drop_tokens channel closed while still waiting for drop tokens; \
365
+ closing {} shared memory regions that might still be used",
366
+ self.sent_out_shared_memory.len()
367
+ );
368
+ break;
369
+ }
370
+ Err(flume::RecvTimeoutError::Timeout) => {
371
+ tracing::warn!(
372
+ "timeout while waiting for drop tokens; \
373
+ closing {} shared memory regions that might still be used",
374
+ self.sent_out_shared_memory.len()
375
+ );
376
+ break;
377
+ }
378
+ }
379
+ }
380
+
381
+ if let Err(err) = self.control_channel.report_outputs_done() {
382
+ tracing::warn!("{err:?}")
383
+ }
384
+ }
385
+ }
386
+
387
+ pub struct DataSample {
388
+ inner: DataSampleInner,
389
+ len: usize,
390
+ }
391
+
392
+ impl DataSample {
393
+ fn finalize(self) -> (Option<DataMessage>, Option<(ShmemHandle, DropToken)>) {
394
+ match self.inner {
395
+ DataSampleInner::Shmem(shared_memory) => {
396
+ let drop_token = DropToken::generate();
397
+ let data = DataMessage::SharedMemory {
398
+ shared_memory_id: shared_memory.get_os_id().to_owned(),
399
+ len: self.len,
400
+ drop_token,
401
+ };
402
+ (Some(data), Some((shared_memory, drop_token)))
403
+ }
404
+ DataSampleInner::Vec(buffer) => (Some(DataMessage::Vec(buffer)), None),
405
+ }
406
+ }
407
+ }
408
+
409
+ impl Deref for DataSample {
410
+ type Target = [u8];
411
+
412
+ fn deref(&self) -> &Self::Target {
413
+ let slice = match &self.inner {
414
+ DataSampleInner::Shmem(handle) => unsafe { handle.as_slice() },
415
+ DataSampleInner::Vec(data) => data,
416
+ };
417
+ &slice[..self.len]
418
+ }
419
+ }
420
+
421
+ impl DerefMut for DataSample {
422
+ fn deref_mut(&mut self) -> &mut Self::Target {
423
+ let slice = match &mut self.inner {
424
+ DataSampleInner::Shmem(handle) => unsafe { handle.as_slice_mut() },
425
+ DataSampleInner::Vec(data) => data,
426
+ };
427
+ &mut slice[..self.len]
428
+ }
429
+ }
430
+
431
+ impl From<AVec<u8, ConstAlign<128>>> for DataSample {
432
+ fn from(value: AVec<u8, ConstAlign<128>>) -> Self {
433
+ Self {
434
+ len: value.len(),
435
+ inner: DataSampleInner::Vec(value),
436
+ }
437
+ }
438
+ }
439
+
440
+ impl std::fmt::Debug for DataSample {
441
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
442
+ let kind = match &self.inner {
443
+ DataSampleInner::Shmem(_) => "SharedMemory",
444
+ DataSampleInner::Vec(_) => "Vec",
445
+ };
446
+ f.debug_struct("DataSample")
447
+ .field("len", &self.len)
448
+ .field("kind", &kind)
449
+ .finish_non_exhaustive()
450
+ }
451
+ }
452
+
453
+ enum DataSampleInner {
454
+ Shmem(ShmemHandle),
455
+ Vec(AVec<u8, ConstAlign<128>>),
456
+ }
457
+
458
+ struct ShmemHandle(Box<Shmem>);
459
+
460
+ impl Deref for ShmemHandle {
461
+ type Target = Shmem;
462
+
463
+ fn deref(&self) -> &Self::Target {
464
+ &self.0
465
+ }
466
+ }
467
+
468
+ impl DerefMut for ShmemHandle {
469
+ fn deref_mut(&mut self) -> &mut Self::Target {
470
+ &mut self.0
471
+ }
472
+ }
473
+
474
+ unsafe impl Send for ShmemHandle {}
475
+ unsafe impl Sync for ShmemHandle {}
apis/rust/operator/Cargo.toml ADDED
@@ -0,0 +1,14 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ [package]
2
+ name = "dora-operator-api"
3
+ version.workspace = true
4
+ edition = "2021"
5
+ documentation.workspace = true
6
+ description.workspace = true
7
+ license.workspace = true
8
+
9
+ # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
10
+
11
+ [dependencies]
12
+ dora-operator-api-macros = { workspace = true }
13
+ dora-operator-api-types = { workspace = true }
14
+ dora-arrow-convert = { workspace = true }
apis/rust/operator/macros/Cargo.toml ADDED
@@ -0,0 +1,17 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ [package]
2
+ name = "dora-operator-api-macros"
3
+ version.workspace = true
4
+ edition = "2021"
5
+ description = "Rust API Macros for Dora Operator"
6
+ documentation.workspace = true
7
+ license.workspace = true
8
+
9
+ # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
10
+
11
+ [lib]
12
+ proc-macro = true
13
+
14
+ [dependencies]
15
+ syn = { version = "1.0.81", features = ["full"] }
16
+ quote = "1.0.10"
17
+ proc-macro2 = "1.0.32"
apis/rust/operator/macros/src/lib.rs ADDED
@@ -0,0 +1,74 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ use proc_macro::TokenStream;
2
+ use proc_macro2::TokenStream as TokenStream2;
3
+ use quote::quote;
4
+
5
+ extern crate proc_macro;
6
+
7
+ #[proc_macro]
8
+ pub fn register_operator(item: TokenStream) -> TokenStream {
9
+ // convert from `TokenStream` to `TokenStream2`, which is used by the
10
+ // `syn` crate
11
+ let item = TokenStream2::from(item);
12
+ // generate the dora wrapper functions
13
+ let generated = register_operator_impl(&item).unwrap_or_else(|err| err.to_compile_error());
14
+ // output the generated functions
15
+ let tokens = quote! {
16
+ #generated
17
+ };
18
+ // convert the type back from `TokenStream2` to `TokenStream`
19
+ tokens.into()
20
+ }
21
+
22
+ /// Generates the wrapper functions for the annotated function.
23
+ fn register_operator_impl(item: &TokenStream2) -> syn::Result<TokenStream2> {
24
+ // parse the type given to the `register_operator` macro
25
+ let operator_ty: syn::TypePath = syn::parse2(item.clone())
26
+ .map_err(|e| syn::Error::new(e.span(), "expected type as argument"))?;
27
+
28
+ let init = quote! {
29
+ #[no_mangle]
30
+ pub unsafe extern "C" fn dora_init_operator() -> dora_operator_api::types::DoraInitResult {
31
+ dora_operator_api::raw::dora_init_operator::<#operator_ty>()
32
+ }
33
+
34
+ const _DORA_INIT_OPERATOR: dora_operator_api::types::DoraInitOperator = dora_operator_api::types::DoraInitOperator {
35
+ init_operator: dora_init_operator,
36
+ };
37
+ };
38
+
39
+ let drop = quote! {
40
+ #[no_mangle]
41
+ pub unsafe extern "C" fn dora_drop_operator(operator_context: *mut std::ffi::c_void)
42
+ -> dora_operator_api::types::DoraResult
43
+ {
44
+ dora_operator_api::raw::dora_drop_operator::<#operator_ty>(operator_context)
45
+ }
46
+
47
+ const _DORA_DROP_OPERATOR: dora_operator_api::types::DoraDropOperator = dora_operator_api::types::DoraDropOperator {
48
+ drop_operator: dora_drop_operator,
49
+ };
50
+ };
51
+
52
+ let on_event = quote! {
53
+ #[no_mangle]
54
+ pub unsafe extern "C" fn dora_on_event(
55
+ event: &mut dora_operator_api::types::RawEvent,
56
+ send_output: &dora_operator_api::types::SendOutput,
57
+ operator_context: *mut std::ffi::c_void,
58
+ ) -> dora_operator_api::types::OnEventResult {
59
+ dora_operator_api::raw::dora_on_event::<#operator_ty>(
60
+ event, send_output, operator_context
61
+ )
62
+ }
63
+
64
+ const _DORA_ON_EVENT: dora_operator_api::types::DoraOnEvent = dora_operator_api::types::DoraOnEvent {
65
+ on_event: dora_operator_api::types::OnEventFn(dora_on_event),
66
+ };
67
+ };
68
+
69
+ Ok(quote! {
70
+ #init
71
+ #drop
72
+ #on_event
73
+ })
74
+ }
apis/rust/operator/src/lib.rs ADDED
@@ -0,0 +1,69 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ //! The operator API is a framework to implement dora operators.
2
+ //! The implemented operator will be managed by `dora`.
3
+ //!
4
+ //! This framework enable us to make optimisation and provide advanced features.
5
+ //! It is the recommended way of using `dora`.
6
+ //!
7
+ //! An operator requires to be registered and implement the `DoraOperator` trait.
8
+ //! It is composed of an `on_event` method that defines the behaviour
9
+ //! of the operator when there is an event such as receiving an input for example.
10
+ //!
11
+ //! Try it out with:
12
+ //!
13
+ //! ```bash
14
+ //! dora new op --kind operator
15
+ //! ```
16
+ //!
17
+
18
+ #![warn(unsafe_op_in_unsafe_fn)]
19
+ #![allow(clippy::missing_safety_doc)]
20
+
21
+ pub use dora_arrow_convert::*;
22
+ pub use dora_operator_api_macros::register_operator;
23
+ pub use dora_operator_api_types as types;
24
+ pub use types::DoraStatus;
25
+ use types::{
26
+ arrow::{self, array::Array},
27
+ Metadata, Output, SendOutput,
28
+ };
29
+
30
+ pub mod raw;
31
+
32
+ #[derive(Debug)]
33
+ #[non_exhaustive]
34
+ pub enum Event<'a> {
35
+ Input { id: &'a str, data: ArrowData },
36
+ InputParseError { id: &'a str, error: String },
37
+ InputClosed { id: &'a str },
38
+ Stop,
39
+ }
40
+
41
+ pub trait DoraOperator: Default {
42
+ #[allow(clippy::result_unit_err)] // we use a () error type only for testing
43
+ fn on_event(
44
+ &mut self,
45
+ event: &Event,
46
+ output_sender: &mut DoraOutputSender,
47
+ ) -> Result<DoraStatus, String>;
48
+ }
49
+
50
+ pub struct DoraOutputSender<'a>(&'a SendOutput);
51
+
52
+ impl DoraOutputSender<'_> {
53
+ /// Send an output from the operator:
54
+ /// - `id` is the `output_id` as defined in your dataflow.
55
+ /// - `data` is the data that should be sent
56
+ pub fn send(&mut self, id: String, data: impl Array) -> Result<(), String> {
57
+ let (data_array, schema) =
58
+ arrow::ffi::to_ffi(&data.into_data()).map_err(|err| err.to_string())?;
59
+ let result = self.0.send_output.call(Output {
60
+ id: id.into(),
61
+ data_array,
62
+ schema,
63
+ metadata: Metadata {
64
+ open_telemetry_context: String::new().into(), // TODO
65
+ },
66
+ });
67
+ result.into_result()
68
+ }
69
+ }
apis/rust/operator/src/raw.rs ADDED
@@ -0,0 +1,80 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ use crate::{DoraOperator, DoraOutputSender, DoraStatus, Event};
2
+ use dora_operator_api_types::{
3
+ arrow, DoraInitResult, DoraResult, OnEventResult, RawEvent, SendOutput,
4
+ };
5
+ use std::ffi::c_void;
6
+
7
+ pub type OutputFnRaw = unsafe extern "C" fn(
8
+ id_start: *const u8,
9
+ id_len: usize,
10
+ data_start: *const u8,
11
+ data_len: usize,
12
+ output_context: *const c_void,
13
+ ) -> isize;
14
+
15
+ pub unsafe fn dora_init_operator<O: DoraOperator>() -> DoraInitResult {
16
+ let operator: O = Default::default();
17
+ let ptr: *mut O = Box::leak(Box::new(operator));
18
+ let operator_context: *mut c_void = ptr.cast();
19
+ DoraInitResult {
20
+ result: DoraResult { error: None },
21
+ operator_context,
22
+ }
23
+ }
24
+
25
+ pub unsafe fn dora_drop_operator<O>(operator_context: *mut c_void) -> DoraResult {
26
+ let raw: *mut O = operator_context.cast();
27
+ drop(unsafe { Box::from_raw(raw) });
28
+ DoraResult { error: None }
29
+ }
30
+
31
+ pub unsafe fn dora_on_event<O: DoraOperator>(
32
+ event: &mut RawEvent,
33
+ send_output: &SendOutput,
34
+ operator_context: *mut std::ffi::c_void,
35
+ ) -> OnEventResult {
36
+ let mut output_sender = DoraOutputSender(send_output);
37
+
38
+ let operator: &mut O = unsafe { &mut *operator_context.cast() };
39
+
40
+ let event_variant = if let Some(input) = &mut event.input {
41
+ let Some(data_array) = input.data_array.take() else {
42
+ return OnEventResult {
43
+ result: DoraResult::from_error("data already taken".to_string()),
44
+ status: DoraStatus::Continue,
45
+ };
46
+ };
47
+ let data = unsafe { arrow::ffi::from_ffi(data_array, &input.schema) };
48
+
49
+ match data {
50
+ Ok(data) => Event::Input {
51
+ id: &input.id,
52
+ data: arrow::array::make_array(data).into(),
53
+ },
54
+ Err(err) => Event::InputParseError {
55
+ id: &input.id,
56
+ error: format!("{err}"),
57
+ },
58
+ }
59
+ } else if let Some(input_id) = &event.input_closed {
60
+ Event::InputClosed { id: input_id }
61
+ } else if event.stop {
62
+ Event::Stop
63
+ } else {
64
+ // ignore unknown events
65
+ return OnEventResult {
66
+ result: DoraResult { error: None },
67
+ status: DoraStatus::Continue,
68
+ };
69
+ };
70
+ match operator.on_event(&event_variant, &mut output_sender) {
71
+ Ok(status) => OnEventResult {
72
+ result: DoraResult { error: None },
73
+ status,
74
+ },
75
+ Err(error) => OnEventResult {
76
+ result: DoraResult::from_error(error),
77
+ status: DoraStatus::Stop,
78
+ },
79
+ }
80
+ }
apis/rust/operator/types/Cargo.toml ADDED
@@ -0,0 +1,17 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ [package]
2
+ name = "dora-operator-api-types"
3
+ version.workspace = true
4
+ edition = "2021"
5
+ documentation.workspace = true
6
+ description.workspace = true
7
+ license.workspace = true
8
+
9
+ # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
10
+
11
+ [dependencies]
12
+ arrow = { workspace = true, features = ["ffi"] }
13
+ dora-arrow-convert = { workspace = true }
14
+
15
+ [dependencies.safer-ffi]
16
+ version = "0.1.4"
17
+ features = ["headers", "inventory-0-3-1"]
apis/rust/operator/types/src/lib.rs ADDED
@@ -0,0 +1,212 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #![deny(elided_lifetimes_in_paths)] // required for safer-ffi
2
+ #![allow(improper_ctypes_definitions)]
3
+ #![allow(clippy::missing_safety_doc)]
4
+
5
+ pub use arrow;
6
+ use dora_arrow_convert::{ArrowData, IntoArrow};
7
+ pub use safer_ffi;
8
+
9
+ use arrow::{
10
+ array::Array,
11
+ ffi::{FFI_ArrowArray, FFI_ArrowSchema},
12
+ };
13
+ use core::slice;
14
+ use safer_ffi::{
15
+ char_p::{self, char_p_boxed},
16
+ closure::ArcDynFn1,
17
+ derive_ReprC, ffi_export,
18
+ };
19
+ use std::{ops::Deref, path::Path};
20
+
21
+ #[derive_ReprC]
22
+ #[ffi_export]
23
+ #[repr(C)]
24
+ pub struct DoraInitOperator {
25
+ pub init_operator: unsafe extern "C" fn() -> DoraInitResult,
26
+ }
27
+
28
+ #[derive_ReprC]
29
+ #[ffi_export]
30
+ #[repr(C)]
31
+ #[derive(Debug)]
32
+ pub struct DoraInitResult {
33
+ pub result: DoraResult,
34
+ pub operator_context: *mut std::ffi::c_void,
35
+ }
36
+ #[derive_ReprC]
37
+ #[ffi_export]
38
+ #[repr(C)]
39
+ pub struct DoraDropOperator {
40
+ pub drop_operator: unsafe extern "C" fn(operator_context: *mut std::ffi::c_void) -> DoraResult,
41
+ }
42
+
43
+ #[derive_ReprC]
44
+ #[ffi_export]
45
+ #[repr(C)]
46
+ #[derive(Debug)]
47
+ pub struct DoraResult {
48
+ pub error: Option<safer_ffi::boxed::Box<safer_ffi::String>>,
49
+ }
50
+
51
+ impl DoraResult {
52
+ pub const SUCCESS: Self = Self { error: None };
53
+
54
+ pub fn from_error(error: String) -> Self {
55
+ Self {
56
+ error: Some(Box::new(safer_ffi::String::from(error)).into()),
57
+ }
58
+ }
59
+
60
+ pub fn error(&self) -> Option<&str> {
61
+ self.error.as_deref().map(|s| s.deref())
62
+ }
63
+
64
+ pub fn into_result(self) -> Result<(), String> {
65
+ match self.error {
66
+ None => Ok(()),
67
+ Some(error) => {
68
+ let converted = safer_ffi::boxed::Box_::into(error);
69
+ Err((*converted).into())
70
+ }
71
+ }
72
+ }
73
+ }
74
+
75
+ #[derive_ReprC]
76
+ #[ffi_export]
77
+ #[repr(C)]
78
+ pub struct DoraOnEvent {
79
+ pub on_event: OnEventFn,
80
+ }
81
+
82
+ #[derive_ReprC]
83
+ #[ffi_export]
84
+ #[repr(transparent)]
85
+ pub struct OnEventFn(
86
+ pub unsafe extern "C" fn(
87
+ event: &mut RawEvent,
88
+ send_output: &SendOutput,
89
+ operator_context: *mut std::ffi::c_void,
90
+ ) -> OnEventResult,
91
+ );
92
+
93
+ #[derive_ReprC]
94
+ #[ffi_export]
95
+ #[repr(C)]
96
+ #[derive(Debug)]
97
+ pub struct RawEvent {
98
+ pub input: Option<safer_ffi::boxed::Box<Input>>,
99
+ pub input_closed: Option<safer_ffi::String>,
100
+ pub stop: bool,
101
+ pub error: Option<safer_ffi::String>,
102
+ }
103
+
104
+ #[derive_ReprC]
105
+ #[repr(opaque)]
106
+ #[derive(Debug)]
107
+ pub struct Input {
108
+ pub id: safer_ffi::String,
109
+ pub data_array: Option<FFI_ArrowArray>,
110
+ pub schema: FFI_ArrowSchema,
111
+ pub metadata: Metadata,
112
+ }
113
+
114
+ #[derive_ReprC]
115
+ #[ffi_export]
116
+ #[repr(C)]
117
+ #[derive(Debug)]
118
+ pub struct Metadata {
119
+ pub open_telemetry_context: safer_ffi::String,
120
+ }
121
+
122
+ #[derive_ReprC]
123
+ #[ffi_export]
124
+ #[repr(C)]
125
+ pub struct SendOutput {
126
+ pub send_output: ArcDynFn1<DoraResult, Output>,
127
+ }
128
+
129
+ #[derive_ReprC]
130
+ #[repr(opaque)]
131
+ #[derive(Debug)]
132
+ pub struct Output {
133
+ pub id: safer_ffi::String,
134
+ pub data_array: FFI_ArrowArray,
135
+ pub schema: FFI_ArrowSchema,
136
+ pub metadata: Metadata,
137
+ }
138
+
139
+ #[derive_ReprC]
140
+ #[ffi_export]
141
+ #[repr(C)]
142
+ #[derive(Debug)]
143
+ pub struct OnEventResult {
144
+ pub result: DoraResult,
145
+ pub status: DoraStatus,
146
+ }
147
+
148
+ #[derive_ReprC]
149
+ #[ffi_export]
150
+ #[derive(Debug)]
151
+ #[repr(u8)]
152
+ pub enum DoraStatus {
153
+ Continue = 0,
154
+ Stop = 1,
155
+ StopAll = 2,
156
+ }
157
+
158
+ #[ffi_export]
159
+ pub fn dora_read_input_id(input: &Input) -> char_p_boxed {
160
+ char_p::new(&*input.id)
161
+ }
162
+
163
+ #[ffi_export]
164
+ pub fn dora_free_input_id(_input_id: char_p_boxed) {}
165
+
166
+ #[ffi_export]
167
+ pub fn dora_read_data(input: &mut Input) -> Option<safer_ffi::Vec<u8>> {
168
+ let data_array = input.data_array.take()?;
169
+ let data = unsafe { arrow::ffi::from_ffi(data_array, &input.schema).ok()? };
170
+ let array = ArrowData(arrow::array::make_array(data));
171
+ let bytes: &[u8] = TryFrom::try_from(&array).ok()?;
172
+ Some(bytes.to_owned().into())
173
+ }
174
+
175
+ #[ffi_export]
176
+ pub fn dora_free_data(_data: safer_ffi::Vec<u8>) {}
177
+
178
+ #[ffi_export]
179
+ pub unsafe fn dora_send_operator_output(
180
+ send_output: &SendOutput,
181
+ id: safer_ffi::char_p::char_p_ref<'_>,
182
+ data_ptr: *const u8,
183
+ data_len: usize,
184
+ ) -> DoraResult {
185
+ let result = || {
186
+ let data = unsafe { slice::from_raw_parts(data_ptr, data_len) };
187
+ let arrow_data = data.to_owned().into_arrow();
188
+ let (data_array, schema) =
189
+ arrow::ffi::to_ffi(&arrow_data.into_data()).map_err(|err| err.to_string())?;
190
+ let output = Output {
191
+ id: id.to_str().to_owned().into(),
192
+ data_array,
193
+ schema,
194
+ metadata: Metadata {
195
+ open_telemetry_context: String::new().into(), // TODO
196
+ },
197
+ };
198
+ Result::<_, String>::Ok(output)
199
+ };
200
+ match result() {
201
+ Ok(output) => send_output.send_output.call(output),
202
+ Err(error) => DoraResult {
203
+ error: Some(Box::new(safer_ffi::String::from(error)).into()),
204
+ },
205
+ }
206
+ }
207
+
208
+ pub fn generate_headers(target_file: &Path) -> ::std::io::Result<()> {
209
+ ::safer_ffi::headers::builder()
210
+ .to_file(target_file)?
211
+ .generate()
212
+ }
binaries/cli/Cargo.toml ADDED
@@ -0,0 +1,44 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ [package]
2
+ name = "dora-cli"
3
+ version.workspace = true
4
+ edition = "2021"
5
+ documentation.workspace = true
6
+ description.workspace = true
7
+ license.workspace = true
8
+
9
+ # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
10
+
11
+ [[bin]]
12
+ name = "dora"
13
+ path = "src/main.rs"
14
+
15
+ [features]
16
+ default = ["tracing"]
17
+ tracing = ["dep:dora-tracing"]
18
+
19
+ [dependencies]
20
+ clap = { version = "4.0.3", features = ["derive"] }
21
+ eyre = "0.6.8"
22
+ dora-core = { workspace = true }
23
+ dora-node-api-c = { workspace = true }
24
+ dora-operator-api-c = { workspace = true }
25
+ serde = { version = "1.0.136", features = ["derive"] }
26
+ serde_yaml = "0.9.11"
27
+ webbrowser = "0.8.3"
28
+ serde_json = "1.0.86"
29
+ termcolor = "1.1.3"
30
+ uuid = { version = "1.7", features = ["v7", "serde"] }
31
+ inquire = "0.5.2"
32
+ communication-layer-request-reply = { workspace = true }
33
+ notify = "5.1.0"
34
+ ctrlc = "3.2.5"
35
+ tracing = "0.1.36"
36
+ dora-tracing = { workspace = true, optional = true }
37
+ bat = "0.24.0"
38
+ dora-daemon = { workspace = true }
39
+ dora-coordinator = { workspace = true }
40
+ dora-runtime = { workspace = true }
41
+ tokio = { version = "1.20.1", features = ["full"] }
42
+ tokio-stream = { version = "0.1.8", features = ["io-util", "net"] }
43
+ futures = "0.3.21"
44
+ duration-str = "0.5"