fv-streams 0.2.0

The FusionVault Streams standalone runner: run a stream pipeline defined in one TOML file against Kafka or Redpanda with no control plane, including the built-in Nexmark event generator.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
//! Run a stream pipeline from one TOML file, with no control plane anywhere.
//!
//! The engine (`fv-streams-engine`) asks its host four questions through the
//! [`ControlPlane`] trait: what is the pipeline's topology, which topic backs a dataset, should I
//! keep running, and here is my build record. This crate answers them from a file. The same engine
//! that a platform hosts over HTTP therefore runs from a laptop, a container, or a test with the
//! same semantics: checkpoints, exactly-once output, stateful windows and joins.
//!
//! ```no_run
//! use std::sync::atomic::AtomicBool;
//! use std::sync::Arc;
//! use fv_streams::Pipeline;
//!
//! # tokio::runtime::Runtime::new().unwrap().block_on(async {
//! let stop = Arc::new(AtomicBool::new(false));      // set it to stop cleanly (Ctrl-C does)
//! Pipeline::load("pipeline.toml")?.run(stop).await;
//! # Ok::<(), String>(())
//! # });
//! ```
//!
//! A pipeline file names its datasets (Kafka topics), its transforms (the engine's own step
//! vocabulary: inline steps, `wasm`/`container` compute, `windowedAggregate`, `sessionAggregate`,
//! `streamJoin`, `topN`, `lastN`) and optional engine settings. The pipeline's `name` is its stable
//! identity: the consumer group `fv-stream-<name>`, the state topic `fv-state-<name>` and the
//! exactly-once transactional namespace all derive from it, so a restarted run restores its
//! checkpoints and fences its own zombies.

/// Every Rust code block in the README is compiled and run as a doctest.
#[cfg(doctest)]
#[doc = include_str!("../README.md")]
pub struct ReadmeDoctests;

use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::Arc;

use async_trait::async_trait;
use fv_streams_engine::{BuildSignal, ControlPlane, StageDef, TopicBinding, Topology};
use serde_json::{json, Value as J};

pub mod arrow_source;
pub mod flight_sql;
pub mod nexmark;
#[cfg(feature = "sandbox")]
pub mod sandbox;

/// Convert a parsed TOML value into the engine's JSON vocabulary (steps are defined by the engine's
/// spec parser, not by this crate — a 1:1 mapping keeps one source of truth).
fn toml_to_json(v: &toml::Value) -> J {
    match v {
        toml::Value::String(s) => J::String(s.clone()),
        toml::Value::Integer(i) => json!(i),
        toml::Value::Float(f) => json!(f),
        toml::Value::Boolean(b) => json!(b),
        toml::Value::Datetime(d) => J::String(d.to_string()),
        toml::Value::Array(a) => J::Array(a.iter().map(toml_to_json).collect()),
        toml::Value::Table(t) => J::Object(t.iter().map(|(k, v)| (k.clone(), toml_to_json(v))).collect()),
    }
}

/// A pipeline definition loaded from a TOML file.
#[derive(Clone, Debug)]
pub struct Pipeline {
    /// The pipeline's stable identity (`name` in the file; `"pipeline"` when absent).
    pub name: String,
    /// Where it was loaded from (for messages only).
    pub path: String,
    /// The definition in the engine's JSON vocabulary.
    pub def: J,
}

impl Pipeline {
    /// Read and parse a pipeline file. Fails with a readable message for a missing file or invalid
    /// TOML; the engine validates the steps themselves when the run starts.
    pub fn load(path: &str) -> Result<Self, String> {
        let raw = std::fs::read_to_string(path).map_err(|e| format!("cannot read {path}: {e}"))?;
        Self::parse(&raw, path)
    }

    /// Parse a pipeline from TOML text (`path` is only used in messages).
    pub fn parse(toml_text: &str, path: &str) -> Result<Self, String> {
        let parsed: toml::Value = toml_text
            .parse()
            .map_err(|e| format!("{path} is not valid TOML: {e}"))?;
        let def = toml_to_json(&parsed);
        let name = def["name"].as_str().unwrap_or("pipeline").to_string();
        Ok(Self {
            name,
            path: path.to_string(),
            def,
        })
    }

    /// The default broker list (`[brokers] default`, else `localhost:9092`).
    pub fn default_brokers(&self) -> String {
        self.def["brokers"]["default"]
            .as_str()
            .unwrap_or("localhost:9092")
            .to_string()
    }

    /// Apply the file's `[settings]` table as `STREAM_*` environment variables for the engine. An
    /// explicit environment variable always wins, so a deployment can override a file.
    pub fn apply_settings(&self) {
        if let Some(settings) = self.def["settings"].as_object() {
            for (k, v) in settings {
                if std::env::var(k).is_err() {
                    let val = match v {
                        J::String(s) => s.clone(),
                        other => other.to_string(),
                    };
                    std::env::set_var(k, val);
                }
            }
        }
    }

    /// Start a generator for every dataset that declares `connector = "nexmark"`: the topic is
    /// created (like any dataset's), then a detached task streams the deterministic event mix
    /// while the pipeline runs. Returns the datasets that got a generator.
    pub async fn start_generators(&self) -> Result<Vec<String>, String> {
        // In a cluster the input is seeded once, by the leader: a joined worker (`--join`) consumes
        // the topic the leader fills, so it must not run its own generator and double the events.
        if std::env::var("STREAM_JOIN").map(|v| !v.is_empty()).unwrap_or(false) {
            return Ok(Vec::new());
        }
        let default_brokers = self.default_brokers();
        let mut started = Vec::new();
        if let Some(datasets) = self.def["datasets"].as_object() {
            for (ds_name, ds) in datasets {
                if let Some(parsed) = nexmark::parse(ds_name, ds, &default_brokers) {
                    let cfg = parsed?;
                    if cfg.inline {
                        continue; // the runtime opens it as source tasks (`resolve_topic`)
                    }
                    fv_streams_engine::ensure_topic(&cfg.brokers, &cfg.topic, cfg.partitions, &[])
                        .await
                        .map_err(|e| format!("nexmark[{ds_name}]: create topic {}: {e}", cfg.topic))?;
                    println!(
                        "fv-streams: nexmark[{ds_name}] → {} ({} events, seed {}, step {}ms{})",
                        cfg.topic,
                        cfg.events,
                        cfg.seed,
                        cfg.step_ms,
                        if cfg.rate > 0 {
                            format!(", {} ev/s", cfg.rate)
                        } else {
                            String::new()
                        }
                    );
                    nexmark::spawn(cfg); // detached: bounded, prints its own completion line
                    started.push(ds_name.clone());
                }
            }
        }
        Ok(started)
    }

    /// Run the pipeline until `stop` is set, then unwind in order: final checkpoint, flush, commit
    /// offsets. Applies the file's settings and starts any Nexmark generators first. The live
    /// counters print on the terminal as the run progresses.
    pub async fn run(self, stop: Arc<AtomicBool>) -> Result<(), String> {
        self.apply_settings();
        self.start_generators().await?;
        let record = json!({
            "id": self.name,
            "pipeline": self.name,
            "kind": "stream",
            "status": "RUNNING",
            "startedAt": chrono::Utc::now().to_rfc3339(),
        });
        println!(
            "fv-streams: running pipeline '{}' from {} (Ctrl-C to stop)",
            self.name, self.path
        );
        let name = self.name.clone();
        let cp = Arc::new(FileControlPlane { def: self.def, stop });
        fv_streams_engine::run_stream(cp, name.clone(), name, record).await
    }
}

/// The file-defined host: the engine's [`ControlPlane`] answered from a [`Pipeline`] definition.
/// Heartbeat = run until the stop flag; the build record prints as a status line (there is no
/// server to send it to).
pub struct FileControlPlane {
    def: J,
    stop: Arc<AtomicBool>,
}

impl FileControlPlane {
    pub fn new(pipeline: &Pipeline, stop: Arc<AtomicBool>) -> Self {
        Self {
            def: pipeline.def.clone(),
            stop,
        }
    }
}

#[async_trait]
impl ControlPlane for FileControlPlane {
    async fn topology(&self, _pipeline: &str) -> Result<Topology, String> {
        // A `sql = "…"` field is the SQL front door: it compiles to the SAME stages a
        // `[[transforms]]` block would (one runtime, two front doors). Datasets/brokers/settings
        // stay as config; the SQL only replaces the transforms.
        if let Some(sql) = self.def["sql"].as_str() {
            return fv_streams_sql::compile(sql).map_err(|e| format!("pipeline SQL: {e}"));
        }
        let transforms = self.def["transforms"]
            .as_array()
            .ok_or("pipeline.toml: needs at least one [[transforms]] table (or a `sql = \"…\"` field)")?;
        let stages = transforms
            .iter()
            .map(|t| StageDef {
                steps: t["steps"].as_array().cloned().unwrap_or_default(),
                inputs: t["inputs"]
                    .as_array()
                    .map(|a| a.iter().filter_map(|v| v.as_str().map(String::from)).collect())
                    .unwrap_or_default(),
                output: t["output"].as_str().unwrap_or("").to_string(),
            })
            .collect();
        Ok(Topology { stages })
    }

    async fn resolve_topic(&self, dataset: &str) -> Result<TopicBinding, String> {
        let ds = &self.def["datasets"][dataset];
        if ds.is_null() {
            return Err(format!(
                "pipeline.toml: dataset '{dataset}' is not defined under [datasets] — every transform input/output must be"
            ));
        }
        // an in-process source (`connector = "nexmark", inline = true`) and a sink of nothing
        // (`sink = "blackhole"`) need no topic; everything else is a topic.
        let default_brokers = self.def["brokers"]["default"]
            .as_str()
            .unwrap_or("localhost:9092")
            .to_string();
        let source = if let Some(parsed) = arrow_source::parse(dataset, ds) {
            // an Arrow-native source: reads Arrow IPC directly, no JSON decode.
            fv_streams_engine::SourceKind::Inline(std::sync::Arc::new(arrow_source::ArrowInline {
                cfg: parsed?,
            }))
        } else {
            match nexmark::parse(dataset, ds, &default_brokers) {
                Some(parsed) => {
                    let cfg = parsed?;
                    if cfg.inline {
                        fv_streams_engine::SourceKind::Inline(std::sync::Arc::new(nexmark::NexmarkInline { cfg }))
                    } else {
                        fv_streams_engine::SourceKind::Kafka
                    }
                }
                None => fv_streams_engine::SourceKind::Kafka,
            }
        };
        let sink = match ds["sink"].as_str() {
            Some("blackhole") => fv_streams_engine::SinkKind::Blackhole,
            Some("arrow") => fv_streams_engine::SinkKind::Arrow,
            Some("flight") => fv_streams_engine::SinkKind::Flight,
            Some(other) => {
                return Err(format!(
                    "pipeline.toml: [datasets.{dataset}] sink = \"{other}\" is not known (blackhole, arrow, flight)"
                ))
            }
            None => fv_streams_engine::SinkKind::Kafka,
        };
        let topicless = matches!(source, fv_streams_engine::SourceKind::Inline(_))
            || matches!(
                sink,
                fv_streams_engine::SinkKind::Blackhole
                    | fv_streams_engine::SinkKind::Arrow
                    | fv_streams_engine::SinkKind::Flight
            );
        // An Arrow sink carries its file `path` in the binding's `topic`; a Flight sink carries its
        // `host:port` there (host defaults to 127.0.0.1 — an edge endpoint, bound locally by default).
        let topic = if matches!(sink, fv_streams_engine::SinkKind::Arrow) {
            ds["path"]
                .as_str()
                .ok_or_else(|| format!("pipeline.toml: [datasets.{dataset}] sink = \"arrow\" needs `path = \"…\"`"))?
                .to_string()
        } else if matches!(sink, fv_streams_engine::SinkKind::Flight) {
            let port = ds["port"]
                .as_i64()
                .filter(|p| (1..=65535).contains(p))
                .ok_or_else(|| format!("pipeline.toml: [datasets.{dataset}] sink = \"flight\" needs `port = <1..=65535>`"))?;
            let host = ds["host"].as_str().unwrap_or("127.0.0.1");
            format!("{host}:{port}")
        } else {
            match ds["topic"].as_str() {
                Some(t) => t.to_string(),
                None if topicless => String::new(),
                None => return Err(format!("pipeline.toml: [datasets.{dataset}] needs `topic = \"…\"`")),
            }
        };
        let brokers = ds["brokers"]
            .as_str()
            .or_else(|| self.def["brokers"]["default"].as_str())
            .unwrap_or("localhost:9092")
            .to_string();
        // The decode policy: `schema = [{ name, type }, …]` declares the columns (else the schema
        // is inferred from the first `infer_sample` messages and frozen); `on_bad_data` is
        // fail | drop | rescue.
        let schema = match ds["schema"].as_array() {
            Some(cols) => {
                let fields = cols
                    .iter()
                    .map(|c| {
                        let name = c["name"]
                            .as_str()
                            .ok_or_else(|| format!("pipeline.toml: [datasets.{dataset}] schema column needs `name`"))?;
                        let ty = c["type"].as_str().unwrap_or("string");
                        fv_streams_engine::decode::declared_field(name, ty)
                            .map_err(|e| format!("pipeline.toml: [datasets.{dataset}] {e}"))
                    })
                    .collect::<Result<Vec<_>, String>>()?;
                fv_streams_engine::decode::SchemaMode::Declared(std::sync::Arc::new(
                    fv_streams_engine::decode::arrow_schema(fields),
                ))
            }
            None => fv_streams_engine::decode::SchemaMode::Inferred {
                sample: ds["infer_sample"].as_u64().unwrap_or(5000) as usize,
            },
        };
        let on_bad_data = match ds["on_bad_data"].as_str() {
            Some(s) => fv_streams_engine::decode::OnBadData::parse(s)
                .map_err(|e| format!("pipeline.toml: [datasets.{dataset}] {e}"))?,
            None => Default::default(),
        };
        Ok(TopicBinding {
            api_name: dataset.to_string(),
            topic,
            brokers,
            policy: fv_streams_engine::decode::SourcePolicy { schema, on_bad_data },
            source,
            sink,
        })
    }

    async fn heartbeat(&self, _build_id: &str) -> BuildSignal {
        if self.stop.load(Ordering::Relaxed) {
            BuildSignal::Stop
        } else {
            BuildSignal::Continue
        }
    }

    async fn put_record(&self, _build_id: &str, record: &J) {
        // No server to persist to — surface the live counters on the terminal instead.
        let m = &record["metrics"];
        let status = record["status"].as_str().unwrap_or("RUNNING");
        println!(
            "▸ {status}  consumed={} emitted={} dropped={}",
            m["consumed"].as_u64().unwrap_or(0),
            m["emitted"].as_u64().unwrap_or(0),
            m["dropped"].as_u64().unwrap_or(0)
        );
    }
}

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

    const FILE: &str = r#"
        name = "demo"
        [settings]
        STREAM_BATCH_MAX = "10"
        [brokers]
        default = "broker:9092"
        [datasets.events]
        topic = "in"
        [datasets.out]
        topic = "out"
        brokers = "other:9092"
        [[transforms]]
        inputs = ["events"]
        output = "out"
          [[transforms.steps]]
          op = "filter"
          expression = "x > 1"
    "#;

    #[test]
    fn parses_name_brokers_and_topology() {
        let p = Pipeline::parse(FILE, "demo.toml").unwrap();
        assert_eq!(p.name, "demo");
        assert_eq!(p.default_brokers(), "broker:9092");
        let cp = FileControlPlane::new(&p, Arc::new(AtomicBool::new(false)));
        let topo = tokio::runtime::Runtime::new()
            .unwrap()
            .block_on(cp.topology("demo"))
            .unwrap();
        assert_eq!(topo.stages.len(), 1);
        assert_eq!(topo.stages[0].inputs, vec!["events".to_string()]);
        assert_eq!(topo.stages[0].steps[0]["op"], "filter");
    }

    #[test]
    fn resolves_topics_with_per_dataset_broker_override() {
        let p = Pipeline::parse(FILE, "demo.toml").unwrap();
        let cp = FileControlPlane::new(&p, Arc::new(AtomicBool::new(false)));
        let rt = tokio::runtime::Runtime::new().unwrap();
        let events = rt.block_on(cp.resolve_topic("events")).unwrap();
        assert_eq!((events.topic.as_str(), events.brokers.as_str()), ("in", "broker:9092"));
        let out = rt.block_on(cp.resolve_topic("out")).unwrap();
        assert_eq!(out.brokers, "other:9092");
        let err = rt.block_on(cp.resolve_topic("nope")).unwrap_err();
        assert!(err.contains("not defined under [datasets]"), "{err}");
    }

    #[test]
    fn the_stop_flag_drives_the_heartbeat() {
        let p = Pipeline::parse(FILE, "demo.toml").unwrap();
        let stop = Arc::new(AtomicBool::new(false));
        let cp = FileControlPlane::new(&p, stop.clone());
        let rt = tokio::runtime::Runtime::new().unwrap();
        assert_eq!(rt.block_on(cp.heartbeat("demo")), BuildSignal::Continue);
        stop.store(true, Ordering::Relaxed);
        assert_eq!(rt.block_on(cp.heartbeat("demo")), BuildSignal::Stop);
    }

    #[test]
    fn invalid_toml_is_a_readable_error() {
        let err = Pipeline::parse("name = [", "bad.toml").unwrap_err();
        assert!(err.starts_with("bad.toml is not valid TOML"), "{err}");
    }
}