fv-streams 0.7.0

The FusionVault Streams standalone runner: run a stream pipeline defined in one TOML file (steps or SQL) with no control plane — every connector built in, the Nexmark event generator, checkpoints to a local directory or an object store, scale-out across workers.
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
//! 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 fv_streams_types::settings::{Section, Setting};
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::Arc;

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

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

/// 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. Refused
    /// before anything is set: a key that is no setting, or a value its setting does not take
    /// (either would be silently ignored). Then the whole environment is checked: a value no
    /// setting takes is an error, a `STREAM_…` variable that is no setting a printed warning.
    pub fn apply_settings(&self) -> Result<(), String> {
        let known = settings();
        fv_streams_types::settings::check_table(&self.def["settings"], &format!("{}: [settings]", self.path), &known)?;
        if let Some(table) = self.def["settings"].as_object() {
            for (k, v) in table {
                if std::env::var_os(k).is_none() {
                    std::env::set_var(k, fv_streams_types::settings::as_env(v));
                }
            }
        }
        for warning in fv_streams_types::settings::check_environment(&known)? {
            eprintln!("fv-streams: {warning}");
        }
        Ok(())
    }

    /// 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 !fv_streams_engine::settings::JOIN.raw().is_empty() {
            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) = fv_streams_connectors::nexmark::parse(ds_name, ds, &default_brokers) {
                    // a misspelt option fails here, before the generator writes a single event
                    // (its warnings print once, when the dataset resolves)
                    fv_streams_connectors::check_dataset(&fv_streams_connectors::Ctx {
                        dataset: ds_name,
                        ds,
                        default_brokers: &default_brokers,
                    })?;
                    let cfg = parsed?;
                    if cfg.inline {
                        continue; // the runtime opens it as source tasks (`resolve_dataset`)
                    }
                    fv_streams_connectors::kafka::ensure_topic(&cfg.brokers, &cfg.topic, cfg.partitions, 1, &[]) // a benchmark topic: one copy
                        .await
                        .map_err(|e| format!("nexmark[{ds_name}]: create topic {}: {e}", cfg.topic))?;
                    let probe = cfg.clone();
                    let written = tokio::task::spawn_blocking(move || fv_streams_connectors::nexmark::written(&probe))
                        .await
                        .map_err(|e| format!("nexmark[{ds_name}]: {e}"))??;
                    if let fv_streams_connectors::nexmark::Written::All(n) = written {
                        // a restart: the events are there, and the pipeline's position is in them
                        println!(
                            "fv-streams: nexmark[{ds_name}] → {}: the topic already holds all {n} messages; not writing them again (delete the topic to generate it afresh)",
                            cfg.topic
                        );
                        continue;
                    }
                    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()
                        }
                    );
                    fv_streams_connectors::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.run_serving(stop, None).await
    }

    /// [`Pipeline::run`] with the observability surface on `serve` (`--serve <addr>` /
    /// `STREAM_SERVE`): `/health`, `/ready`, `/status`, `/metrics`.
    pub async fn run_serving(self, stop: Arc<AtomicBool>, serve: Option<&str>) -> 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,
            live: tokio::sync::watch::channel(json!({ "status": "STARTING", "metrics": {} })).0,
        });
        if let Some(addr) = serve {
            let bound = serve::start(addr, cp.live()).await?;
            println!("fv-streams: serving /health /ready /status /metrics on http://{bound}");
        }
        fv_streams_engine::run_stream(cp, name.clone(), name, record).await
    }
}

/// `STREAM_SERVE`: the runner's observability listener (`--serve`).
pub const SERVE: Setting = Setting {
    key: "STREAM_SERVE",
    kind: fv_streams_types::options::Kind::Text,
    default: "",
    doc: "Serve `/health`, `/ready`, `/status` and `/metrics` on this address, `host:port`. Set by `--serve`. Empty: not served.",
};

static RUNNER: Section = Section {
    title: "The runner",
    intro: "The `fv-streams` command's own settings.",
    settings: &[SERVE],
};

/// Every setting this runner reads, by area — the engine's, the connectors', its own — what a
/// pipeline's `[settings]` and the environment are checked against, and what `docs/settings.md`
/// lists.
pub fn settings() -> Vec<&'static Section> {
    fv_streams_engine::settings::SECTIONS
        .iter()
        .chain(fv_streams_connectors::settings())
        .chain([&RUNNER])
        .collect()
}

/// 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>,
    /// The live build record, for the observability surface (`--serve`).
    live: tokio::sync::watch::Sender<J>,
}

impl FileControlPlane {
    pub fn new(pipeline: &Pipeline, stop: Arc<AtomicBool>) -> Self {
        Self {
            def: pipeline.def.clone(),
            stop,
            live: tokio::sync::watch::channel(json!({ "status": "STARTING", "metrics": {} })).0,
        }
    }

    /// A receiver of the live build record (every heartbeat's record).
    pub fn live(&self) -> serve::Live {
        self.live.subscribe()
    }
}

#[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_dataset(&self, dataset: &str) -> Result<Binding, 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"
            ));
        }
        // The connectors crate's registry resolves both halves: `connector = "…"` names the
        // source (Kafka when absent), `sink = "…"` the sink (Kafka when absent). An input's sink
        // and an output's source are resolved and never opened.
        let default_brokers = self.def["brokers"]["default"]
            .as_str()
            .unwrap_or("localhost:9092")
            .to_string();
        let cx = fv_streams_connectors::Ctx {
            dataset,
            ds,
            default_brokers: &default_brokers,
        };
        for warning in fv_streams_connectors::check_dataset(&cx)? {
            eprintln!("fv-streams: {warning}");
        }
        Ok(Binding {
            api_name: dataset.to_string(),
            source: fv_streams_connectors::resolve_source(&cx)?,
            sink: fv_streams_connectors::resolve_sink(&cx)?,
        })
    }

    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 — publish to the observability surface and print the counters.
        let _ = self.live.send(record.clone());
        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_datasets_through_the_registry_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_dataset("events")).unwrap();
        assert_eq!(events.source.name(), "in");
        assert!(
            events.source.describe().contains("broker:9092"),
            "{}",
            events.source.describe()
        );
        let out = rt.block_on(cp.resolve_dataset("out")).unwrap();
        assert!(out.sink.describe().contains("other:9092"), "{}", out.sink.describe());
        let err = rt.block_on(cp.resolve_dataset("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}");
    }
}