fv-streams 0.3.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
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
//! Flight-SQL statement submission (5d-ii): a Flight **control endpoint** where a client submits a
//! 5c SQL statement and gets back an Arrow result stream — the streams#6 sandbox tie-in.
//!
//! The loop, reusing the tested pieces wholesale (DRY): a `do_action("query", <sql>)` compiles the
//! statement through the SQL front door ([`fv_streams_sql`]), synthesises a pipeline from a **catalog**
//! (the available datasets, declared once) plus the statement plus a Flight output sink on a fresh
//! port, spawns it in-process, and returns that `grpc://…` endpoint. The client then reads the result
//! with an ordinary Flight `do_get` against the endpoint — the same [`crate`]-engine Flight output
//! sink the console and the globe already use. No new sink, no result registry: the control plane
//! just compiles and launches; the data plane is the existing edge.
//!
//! Submit a `SELECT …` (optionally `WITH …`); it is wrapped as `INSERT INTO <result> …` and the
//! result streams back. A bounded source (an inline generator, an Arrow file) makes the stream end on
//! its own (the bounded-drain stop); an unbounded source streams until the server stops.
//!
//! This is a plain-Flight protocol (a `query` action carrying the SQL), not the full Flight-SQL
//! protobuf catalog — enough for our own sandbox client, and a seam a `CommandStatementQuery` handler
//! slots behind later.

use std::collections::HashMap;
use std::pin::Pin;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{Arc, Mutex};
use std::time::Duration;

use arrow_flight::flight_service_server::{FlightService, FlightServiceServer};
use arrow_flight::{
    Action, ActionType, Criteria, Empty, FlightData, FlightDescriptor, FlightInfo, HandshakeRequest, HandshakeResponse,
    PollInfo, PutResult, SchemaResult, Ticket,
};
use futures::stream;
use serde_json::json;
use tonic::transport::Server;
use tonic::{Request, Response, Status, Streaming};

use crate::Pipeline;

type FlightStream<T> = Pin<Box<dyn futures::Stream<Item = Result<T, Status>> + Send + 'static>>;

/// The control service: a catalog of datasets, the runtime a submitted pipeline spawns onto, and the
/// host its Flight output binds. Every `do_action("query")` compiles + launches one pipeline.
/// Each running query's stop flag, keyed by its endpoint (setting the flag unwinds the pipeline).
type QueryRegistry = Arc<Mutex<HashMap<String, Arc<AtomicBool>>>>;

pub struct SqlService {
    /// The catalog definition — `[datasets.*]` and `[settings]` only, no transforms/`sql` (those come
    /// from the statement). Cloned per query and extended with the statement and a Flight result sink.
    catalog: serde_json::Value,
    host: String,
    /// The running queries, so a `cancel` action (or a server shutdown) can stop one.
    queries: QueryRegistry,
}

impl SqlService {
    /// Build a service from a catalog pipeline (its datasets/settings). The statement supplies the
    /// transforms, so a catalog carrying its own `sql`/`transforms` is rejected (ambiguous).
    pub fn new(catalog: &Pipeline, host: &str) -> Result<Self, String> {
        if catalog.def.get("sql").is_some() || catalog.def.get("transforms").is_some() {
            return Err("a flight-sql catalog declares only [datasets.*] (+ [settings]); the SQL comes from each submitted statement".into());
        }
        Ok(SqlService {
            catalog: catalog.def.clone(),
            host: host.to_string(),
            queries: Arc::new(Mutex::new(HashMap::new())),
        })
    }

    /// Compile the statement, spawn its pipeline with a Flight output on a fresh port, and return the
    /// endpoint once that output is listening.
    async fn spawn_query(&self, sql: &str) -> Result<String, String> {
        let stmt = sql.trim().trim_end_matches(';').trim();
        let head = stmt.split_whitespace().next().unwrap_or("").to_ascii_uppercase();
        if !matches!(head.as_str(), "SELECT" | "WITH") {
            return Err("submit a `SELECT …` (optionally `WITH …`) — its result streams back to you".into());
        }
        let wrapped = format!("INSERT INTO __flight_result {stmt}");
        // fail fast, with the SQL front door's own streaming-aware error, before launching anything.
        fv_streams_sql::compile(&wrapped).map_err(|e| format!("SQL: {e}"))?;

        let port = free_port()?;
        let mut def = self.catalog.clone();
        def["sql"] = json!(wrapped);
        def["datasets"]["__flight_result"] = json!({ "sink": "flight", "host": self.host, "port": port });
        let pipeline = Pipeline {
            name: format!("flightsql-{port}"),
            path: "<flight-sql>".to_string(),
            def,
        };

        // The stop flag is registered under the endpoint so a `cancel` action (or shutdown) can
        // unwind this query — an unbounded statement otherwise runs until the process exits.
        let endpoint = format!("grpc://{}:{port}", self.host);
        let stop = Arc::new(AtomicBool::new(false));
        self.queries
            .lock()
            .expect("queries")
            .insert(endpoint.clone(), stop.clone());

        // Launch it on its OWN multi-thread runtime on a dedicated thread — the dataflow run future
        // is not `Send` (its runtime drives OS-thread bridges), so it cannot ride `tokio::spawn`, and
        // it needs a multi-thread runtime (a current-thread one deadlocks the exchange bridges). The
        // Flight output sink binds `port` during that run's build. When the run ends (a bounded source
        // drains, or a cancel), its registry entry is removed.
        let name = pipeline.name.clone();
        let queries = Arc::clone(&self.queries);
        let key = endpoint.clone();
        std::thread::Builder::new()
            .name(name.clone())
            .spawn(move || {
                let rt = match tokio::runtime::Builder::new_multi_thread().enable_all().build() {
                    Ok(rt) => rt,
                    Err(e) => {
                        eprintln!("flight-sql: query runtime for {name}: {e}");
                        queries.lock().expect("queries").remove(&key);
                        return;
                    }
                };
                if let Err(e) = rt.block_on(pipeline.run(stop)) {
                    eprintln!("flight-sql: query pipeline {name} ended: {e}");
                }
                queries.lock().expect("queries").remove(&key);
            })
            .map_err(|e| format!("flight-sql: spawn query thread: {e}"))?;

        // Return the endpoint only once the output is actually accepting connections, so the client's
        // do_get never races the bind.
        wait_listening(&self.host, port, Duration::from_secs(10)).await?;
        Ok(endpoint)
    }
}

#[tonic::async_trait]
impl FlightService for SqlService {
    type HandshakeStream = FlightStream<HandshakeResponse>;
    type ListFlightsStream = FlightStream<FlightInfo>;
    type DoGetStream = FlightStream<FlightData>;
    type DoPutStream = FlightStream<PutResult>;
    type DoActionStream = FlightStream<arrow_flight::Result>;
    type ListActionsStream = FlightStream<ActionType>;
    type DoExchangeStream = FlightStream<FlightData>;

    async fn do_action(&self, request: Request<Action>) -> Result<Response<Self::DoActionStream>, Status> {
        let action = request.into_inner();
        let body_str = || String::from_utf8(action.body.to_vec());
        let reply = match action.r#type.as_str() {
            "query" => {
                let sql = body_str().map_err(|_| Status::invalid_argument("the query body must be UTF-8 SQL"))?;
                self.spawn_query(&sql).await.map_err(Status::invalid_argument)?
            }
            "cancel" => {
                // stop the query at the endpoint the `query` action returned; its pipeline unwinds and
                // its Flight output stream ends. Idempotent-ish: an already-finished query is `not_found`.
                let endpoint =
                    body_str().map_err(|_| Status::invalid_argument("the cancel body must be the endpoint string"))?;
                match self.queries.lock().expect("queries").remove(endpoint.trim()) {
                    Some(flag) => {
                        flag.store(true, Ordering::Relaxed);
                        format!("cancelled {}", endpoint.trim())
                    }
                    None => return Err(Status::not_found(format!("no running query at {}", endpoint.trim()))),
                }
            }
            other => {
                return Err(Status::unimplemented(format!(
                    "unknown action '{other}' — use 'query' (body = SQL) or 'cancel' (body = the endpoint)"
                )))
            }
        };
        let out = stream::once(async move {
            Ok(arrow_flight::Result {
                body: reply.into_bytes().into(),
            })
        });
        Ok(Response::new(Box::pin(out)))
    }

    async fn list_actions(&self, _: Request<Empty>) -> Result<Response<Self::ListActionsStream>, Status> {
        let actions = vec![
            ActionType {
                r#type: "query".to_string(),
                description:
                    "Compile and run a SQL statement; returns the grpc:// Flight endpoint of its Arrow result stream."
                        .to_string(),
            },
            ActionType {
                r#type: "cancel".to_string(),
                description: "Stop a running query; the body is the endpoint the 'query' action returned.".to_string(),
            },
        ];
        Ok(Response::new(Box::pin(stream::iter(actions.into_iter().map(Ok)))))
    }

    async fn handshake(
        &self,
        _: Request<Streaming<HandshakeRequest>>,
    ) -> Result<Response<Self::HandshakeStream>, Status> {
        Err(Status::unimplemented(
            "the flight-sql control endpoint takes a 'query' do_action",
        ))
    }
    async fn list_flights(&self, _: Request<Criteria>) -> Result<Response<Self::ListFlightsStream>, Status> {
        Err(Status::unimplemented(
            "the flight-sql control endpoint takes a 'query' do_action",
        ))
    }
    async fn get_flight_info(&self, _: Request<FlightDescriptor>) -> Result<Response<FlightInfo>, Status> {
        Err(Status::unimplemented(
            "the flight-sql control endpoint takes a 'query' do_action",
        ))
    }
    async fn poll_flight_info(&self, _: Request<FlightDescriptor>) -> Result<Response<PollInfo>, Status> {
        Err(Status::unimplemented(
            "the flight-sql control endpoint takes a 'query' do_action",
        ))
    }
    async fn get_schema(&self, _: Request<FlightDescriptor>) -> Result<Response<SchemaResult>, Status> {
        Err(Status::unimplemented(
            "the flight-sql control endpoint takes a 'query' do_action",
        ))
    }
    async fn do_get(&self, _: Request<Ticket>) -> Result<Response<Self::DoGetStream>, Status> {
        Err(Status::unimplemented(
            "read results from the endpoint the 'query' action returns",
        ))
    }
    async fn do_put(&self, _: Request<Streaming<FlightData>>) -> Result<Response<Self::DoPutStream>, Status> {
        Err(Status::unimplemented(
            "the flight-sql control endpoint takes a 'query' do_action",
        ))
    }
    async fn do_exchange(&self, _: Request<Streaming<FlightData>>) -> Result<Response<Self::DoExchangeStream>, Status> {
        Err(Status::unimplemented(
            "the flight-sql control endpoint takes a 'query' do_action",
        ))
    }
}

/// Run the control endpoint on `port` until `shutdown` is set. `host` is where each query's Flight
/// output binds (the endpoint handed back to clients).
pub async fn serve(catalog: Pipeline, host: &str, port: u16, shutdown: Arc<AtomicBool>) -> Result<(), String> {
    let svc = SqlService::new(&catalog, host)?;
    let queries = Arc::clone(&svc.queries); // to stop every running query when the server stops
    let addr = format!("{host}:{port}")
        .parse()
        .map_err(|e| format!("flight-sql: bad address {host}:{port}: {e}"))?;
    println!("fv-streams: flight-sql control endpoint on grpc://{addr} — submit a 'query' action with your SQL");
    let poll = async move {
        while !shutdown.load(Ordering::Relaxed) {
            tokio::time::sleep(Duration::from_millis(200)).await;
        }
    };
    let result = Server::builder()
        .add_service(FlightServiceServer::new(svc))
        .serve_with_shutdown(addr, poll)
        .await;
    // no query outlives the endpoint: unwind each still-running one.
    for (_, flag) in queries.lock().expect("queries").drain() {
        flag.store(true, Ordering::Relaxed);
    }
    result.map_err(|e| format!("flight-sql server: {e}"))
}

/// A free ephemeral TCP port on the loopback (bound then released — the small reuse window is fine
/// for a sandbox, and the query's output rebinds it immediately).
fn free_port() -> Result<u16, String> {
    let l = std::net::TcpListener::bind("127.0.0.1:0").map_err(|e| format!("flight-sql: no free port: {e}"))?;
    l.local_addr()
        .map(|a| a.port())
        .map_err(|e| format!("flight-sql: local_addr: {e}"))
}

/// Wait until `host:port` accepts a connection (the query's Flight output has bound), so the endpoint
/// is usable the moment it is returned.
async fn wait_listening(host: &str, port: u16, within: Duration) -> Result<(), String> {
    let deadline = tokio::time::Instant::now() + within;
    loop {
        if tokio::net::TcpStream::connect((host, port)).await.is_ok() {
            return Ok(());
        }
        if tokio::time::Instant::now() >= deadline {
            return Err(format!(
                "the query's Flight output did not bind {host}:{port} within {within:?}"
            ));
        }
        tokio::time::sleep(Duration::from_millis(50)).await;
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use arrow::array::Int64Array;
    use futures::StreamExt;

    #[tokio::test]
    async fn submit_a_sql_statement_and_read_its_arrow_result_over_flight() {
        // A catalog with one bounded inline Nexmark source. The submitted statement supplies the
        // transforms; its result streams back over Flight.
        let catalog = Pipeline::parse(
            r#"
name = "catalog"
[settings]
STREAM_STATE_STORE = "memory"
STREAM_CONSUMERS = "1"
STREAM_HEARTBEAT_SECONDS = "1"
[brokers]
default = "localhost:9092"
[datasets.events]
connector = "nexmark"
inline = true
events = 4000
rate = 1500          # pace the source so the live result stream stays up for the client to read
seed = 42
partitions = 1
"#,
            "catalog.toml",
        )
        .unwrap();

        let shutdown = Arc::new(AtomicBool::new(false));
        // Bind a control port, then serve on it.
        let ctl_port = free_port().unwrap();
        let server = {
            let shutdown = shutdown.clone();
            tokio::spawn(async move { serve(catalog, "127.0.0.1", ctl_port, shutdown).await })
        };
        wait_listening("127.0.0.1", ctl_port, Duration::from_secs(10))
            .await
            .unwrap();

        // Submit a SELECT; get back the result endpoint.
        let mut ctl = arrow_flight::FlightClient::new(
            tonic::transport::Channel::from_shared(format!("http://127.0.0.1:{ctl_port}"))
                .unwrap()
                .connect()
                .await
                .unwrap(),
        );
        let mut results = ctl
            .do_action(Action {
                r#type: "query".to_string(),
                body: "SELECT auction, price FROM events WHERE type = 'bid'".into(),
            })
            .await
            .unwrap();
        let endpoint = {
            let body = results.next().await.unwrap().unwrap();
            String::from_utf8(body.to_vec()).unwrap()
        };
        assert!(endpoint.starts_with("grpc://127.0.0.1:"), "got endpoint {endpoint}");

        // Read the Arrow result stream from that endpoint — the bounded source makes it end on its own.
        let data_addr = endpoint.strip_prefix("grpc://").unwrap();
        let mut data = arrow_flight::FlightClient::new(
            tonic::transport::Channel::from_shared(format!("http://{data_addr}"))
                .unwrap()
                .connect()
                .await
                .unwrap(),
        );
        let mut stream = data
            .do_get(Ticket {
                ticket: Default::default(),
            })
            .await
            .unwrap();
        let mut rows = 0usize;
        let mut saw_auction = false;
        while let Some(b) = stream.next().await {
            let batch = b.unwrap();
            rows += batch.num_rows();
            if let Some(c) = batch.column_by_name("auction") {
                saw_auction = c.as_any().downcast_ref::<Int64Array>().is_some();
            }
        }
        assert!(rows > 0, "the submitted query streamed some bids back");
        assert!(saw_auction, "the result carries the projected `auction` column");

        shutdown.store(true, Ordering::Relaxed);
        let _ = server.await;
    }

    #[tokio::test]
    async fn a_running_query_can_be_cancelled() {
        // A paced source that would run for a long time, so the query is still running when we cancel.
        let catalog = Pipeline::parse(
            r#"
name = "catalog"
[settings]
STREAM_STATE_STORE = "memory"
STREAM_CONSUMERS = "1"
STREAM_HEARTBEAT_SECONDS = "1"
STREAM_BATCH_MAX = "100"      # small batches so the paced source returns from poll and sees a stop
[brokers]
default = "localhost:9092"
[datasets.events]
connector = "nexmark"
inline = true
events = 10000000
rate = 1000                   # a long-running paced source (10000s at this rate), responsive to stop
seed = 42
partitions = 1
"#,
            "catalog.toml",
        )
        .unwrap();

        let shutdown = Arc::new(AtomicBool::new(false));
        let ctl_port = free_port().unwrap();
        let server = {
            let shutdown = shutdown.clone();
            tokio::spawn(async move { serve(catalog, "127.0.0.1", ctl_port, shutdown).await })
        };
        wait_listening("127.0.0.1", ctl_port, Duration::from_secs(10))
            .await
            .unwrap();
        let mut ctl = arrow_flight::FlightClient::new(
            tonic::transport::Channel::from_shared(format!("http://127.0.0.1:{ctl_port}"))
                .unwrap()
                .connect()
                .await
                .unwrap(),
        );

        // Launch a long-running query; it is listening (spawn_query waits for the bind).
        let endpoint = {
            let mut r = ctl
                .do_action(Action {
                    r#type: "query".to_string(),
                    body: "SELECT * FROM events WHERE type = 'bid'".into(),
                })
                .await
                .unwrap();
            String::from_utf8(r.next().await.unwrap().unwrap().to_vec()).unwrap()
        };
        let addr = endpoint.strip_prefix("grpc://").unwrap().to_string();
        assert!(
            tokio::net::TcpStream::connect(&addr).await.is_ok(),
            "the query is running"
        );

        // Cancel it.
        let reply = {
            let mut r = ctl
                .do_action(Action {
                    r#type: "cancel".to_string(),
                    body: endpoint.clone().into(),
                })
                .await
                .unwrap();
            String::from_utf8(r.next().await.unwrap().unwrap().to_vec()).unwrap()
        };
        assert!(reply.starts_with("cancelled"), "got {reply}");

        // The pipeline unwinds and its Flight output stops listening — proof the query actually stopped
        // (not just deregistered). Poll up to the heartbeat-driven stop window.
        let deadline = tokio::time::Instant::now() + Duration::from_secs(15);
        loop {
            if tokio::net::TcpStream::connect(&addr).await.is_err() {
                break; // the port is gone → the query stopped
            }
            assert!(
                tokio::time::Instant::now() < deadline,
                "the cancelled query kept serving {addr}"
            );
            tokio::time::sleep(Duration::from_millis(100)).await;
        }

        // Cancelling an unknown/finished query is a clean not-found.
        let err = ctl
            .do_action(Action {
                r#type: "cancel".to_string(),
                body: endpoint.clone().into(),
            })
            .await
            .err()
            .expect("second cancel is not_found");
        let not_found = matches!(&err, arrow_flight::error::FlightError::Tonic(s) if s.code() == tonic::Code::NotFound);
        assert!(not_found, "expected not_found, got {err:?}");

        shutdown.store(true, Ordering::Relaxed);
        let _ = server.await;
    }
}