Skip to main content

std_mel/flow/
scatter.rs

1//! Scatter and gather: one track per value of a stream, as workflow languages scatter a
2//! sub-workflow over the elements of a collection and gather how each ended.
3
4use futures::{pin_mut, select, FutureExt};
5use melodium_core::{
6    common::descriptor::DataType,
7    common::executive::{Input, Output, ResultStatus, TrackId},
8    *,
9};
10use melodium_macro::{mel_context, mel_model, mel_treatment};
11use std::collections::HashMap;
12use std::sync::atomic::{AtomicU64, Ordering};
13use std::sync::{Arc, Mutex, Weak};
14
15/// Context of a scattered track.
16///
17/// - `scatter`: identifier of the `scatter` that made the track;
18/// - `index`: position of the value of the track in the stream scattered, from 0.
19#[mel_context]
20pub struct Scattered {
21    pub scatter: string,
22    pub index: u64,
23}
24
25/// How a scattered track ended, as `gather` tells.
26#[derive(Debug)]
27enum Outcome {
28    Completed,
29    Failed(String),
30    /// Ended without telling.
31    Silent,
32}
33
34/// End of a scattered track, with the value it gathered, if any, and its type.
35#[derive(Debug)]
36struct End {
37    index: u64,
38    outcome: Outcome,
39    value: Option<(DataType, Value)>,
40}
41
42/// Scatters values of streams over tracks of their own, and gathers how they end.
43///
44/// `scatter` makes a track for each value it receives, where `scattered` gives the value and the
45/// value shared by all of them, and `gather` tells how the track ended. Scattered tracks get the
46/// contexts of the track of `scatter`, with `@Scattered`.
47///
48/// Each use of `Scatter` is meant for one `scatter` (or `scatterGathering`), and the `scattered`
49/// and `gather` (or `gatherValue`) of its tracks, in the same treatment, as
50/// `http/server::connection` uses `incoming` and `outgoing`.
51#[mel_model(
52    source scattered (Scattered) (generic T () generic S () inherit) (value Block<T> shared Block<S>)
53    invoke_generic_source invoke_source
54)]
55#[derive(Debug)]
56pub struct Scatter {
57    /// Types of each use of `scattered`.
58    entries: Mutex<Vec<HashMap<String, DataType>>>,
59    /// `scatter` waiting for their tracks to end, by identifier.
60    scatters: Mutex<HashMap<String, async_channel::Sender<End>>>,
61    next: AtomicU64,
62}
63
64impl Scatter {
65    fn new(_model: Weak<ScatterModel>) -> Self {
66        Self {
67            entries: Mutex::new(Vec::new()),
68            scatters: Mutex::new(HashMap::new()),
69            next: AtomicU64::new(0),
70        }
71    }
72
73    fn invoke_source(
74        &self,
75        _source: &str,
76        _params: HashMap<String, Value>,
77        generics: HashMap<String, DataType>,
78    ) {
79        self.entries.lock().unwrap().push(generics);
80    }
81
82    /// Opens a scatter, giving its identifier and where the ends of its tracks come.
83    fn open(&self) -> (String, async_channel::Receiver<End>) {
84        let id = self.next.fetch_add(1, Ordering::Relaxed).to_string();
85        let (sender, receiver) = async_channel::unbounded();
86        self.scatters.lock().unwrap().insert(id.clone(), sender);
87        (id, receiver)
88    }
89
90    fn close(&self, id: &str) {
91        self.scatters.lock().unwrap().remove(id);
92    }
93
94    /// Tells the scatter `id` how its track ended.
95    fn report(&self, id: &str, end: End) {
96        if let Some(sender) = self.scatters.lock().unwrap().get(id) {
97            let _ = sender.try_send(end);
98        }
99    }
100}
101
102/// Scatter values over tracks of their own.
103///
104/// For each value received through `values`, a track is made where `scattered` gives it, with
105/// the value received through `shared` (a trigger when nothing is shared), at most `parallel`
106/// at once: `values` is not read further until one ends, a track ending when it tells
107/// `gather` how, even if some of its treatments still finish. Tracks start in the order of `values`,
108/// and end in any order, each telling how through `gather`. They get the contexts of the track
109/// of `scatter`, with `@Scattered`.
110///
111/// Once `values` ends and every track ended, `finished` is emitted, and `completed` if they all
112/// completed. If one failed, or ended without gathering, `failed` is emitted and `errors` gives
113/// why. `scattered<T, S>` must be used with the same types and the same `Scatter`.
114///
115/// ```mermaid
116/// graph LR
117///     T("scatter()")
118///     V["… 🟦 🟦 🟦"] -->|values| T
119///     S["〈🟨〉"] -->|shared| T
120///
121///     T -.->|"track per 🟦"| X["scattered() … gather()"]
122///     T -->|completed| C["〈🟩〉"]
123///
124///     style V fill:#ffffff,stroke:#ffffff
125///     style S fill:#ffffff,stroke:#ffffff
126///     style X fill:#ffffff,stroke:#ffffff
127///     style C fill:#ffffff,stroke:#ffffff
128/// ```
129#[mel_treatment(
130    generic T ()
131    generic S ()
132    model scatter Scatter
133    default parallel 8
134    input values Stream<T>
135    input shared Block<S>
136    output completed Block<void>
137    output failed Block<void>
138    output finished Block<void>
139    output errors Stream<string>
140)]
141pub async fn scatter(parallel: u32) {
142    let generics = HashMap::from([("T".to_string(), T), ("S".to_string(), S)]);
143    scatter_values(
144        ScatterModel::into(scatter),
145        track_id,
146        generics,
147        parallel,
148        &**values,
149        &**shared,
150        None,
151        [&**completed, &**failed, &**finished],
152        &**errors,
153    )
154    .await
155}
156
157/// Scatter values over tracks of their own, and gather their values.
158///
159/// As `scatter` does, with the values the tracks give to `gatherValue` coming through
160/// `gathered`, in the order the tracks end. A track gathering no value gives none, and values
161/// of another type than `R` are refused, the scatter failing.
162///
163/// ```mermaid
164/// graph LR
165///     T("scatterGathering()")
166///     V["… 🟦 🟦 🟦"] -->|values| T
167///     S["〈🟨〉"] -->|shared| T
168///
169///     T -.->|"track per 🟦"| X["scattered() … gatherValue()"]
170///     T -->|gathered| G["… 🟪 🟪 🟪"]
171///     T -->|completed| C["〈🟩〉"]
172///
173///     style V fill:#ffffff,stroke:#ffffff
174///     style S fill:#ffffff,stroke:#ffffff
175///     style X fill:#ffffff,stroke:#ffffff
176///     style G fill:#ffffff,stroke:#ffffff
177///     style C fill:#ffffff,stroke:#ffffff
178/// ```
179#[mel_treatment(
180    generic T ()
181    generic S ()
182    generic R ()
183    model scatter Scatter
184    default parallel 8
185    input values Stream<T>
186    input shared Block<S>
187    output gathered Stream<R>
188    output completed Block<void>
189    output failed Block<void>
190    output finished Block<void>
191    output errors Stream<string>
192)]
193pub async fn scatter_gathering(parallel: u32) {
194    let generics = HashMap::from([("T".to_string(), T), ("S".to_string(), S)]);
195    scatter_values(
196        ScatterModel::into(scatter),
197        track_id,
198        generics,
199        parallel,
200        &**values,
201        &**shared,
202        Some((R, &**gathered)),
203        [&**completed, &**failed, &**finished],
204        &**errors,
205    )
206    .await
207}
208
209/// Makes the tracks of `scatter` and `scatterGathering`, giving their gathered values through
210/// `gathered` when there is one.
211async fn scatter_values(
212    model: Arc<ScatterModel>,
213    track_id: TrackId,
214    generics: HashMap<String, DataType>,
215    parallel: u32,
216    values: &dyn Input,
217    shared: &dyn Input,
218    gathered: Option<(DataType, &dyn Output)>,
219    [completed, failed, finished]: [&dyn Output; 3],
220    errors: &dyn Output,
221) {
222    let scatter = model.inner();
223
224    let mut problems = Vec::new();
225    let mut gathered_all = true;
226    if parallel == 0 {
227        problems.push("parallel must be at least 1".to_string());
228    } else if !scatter.entries.lock().unwrap().contains(&generics) {
229        problems.push(format!(
230            "no `scattered<{}, {}>` of the same `Scatter` takes the values",
231            generics["T"], generics["S"]
232        ));
233    } else if let Ok(shared_value) = shared.recv_one().await {
234        let (id, ends) = scatter.open();
235        let mut running = 0;
236        let mut index = 0;
237        let mut values_ended = false;
238        loop {
239            // Ends of tracks already known are taken first.
240            while let Ok(end) = ends.try_recv() {
241                running -= 1;
242                gathered_all &= ended(end, gathered.as_ref(), &mut problems).await;
243            }
244            if values_ended || running >= parallel {
245                if running == 0 {
246                    break;
247                }
248                if let Ok(end) = ends.recv().await {
249                    running -= 1;
250                    gathered_all &= ended(end, gathered.as_ref(), &mut problems).await;
251                }
252                continue;
253            }
254            match values.recv_one().await {
255                Ok(value) => {
256                    let shared_value = shared_value.clone();
257                    model
258                        .new_scattered(
259                            Some(track_id),
260                            Scattered {
261                                scatter: id.clone(),
262                                index,
263                            },
264                            &HashMap::new(),
265                            &generics,
266                            Some(Box::new(move |mut outputs| {
267                                let value_output = outputs.get("value");
268                                let shared_output = outputs.get("shared");
269                                vec![Box::new(Box::pin(give(
270                                    value_output,
271                                    value,
272                                    shared_output,
273                                    shared_value,
274                                )))]
275                            })),
276                        )
277                        .await;
278                    running += 1;
279                    index += 1;
280                }
281                Err(_) => values_ended = true,
282            }
283        }
284        scatter.close(&id);
285    } else {
286        problems.push("no shared value was given".to_string());
287    }
288
289    values.close();
290    if let Some((_, gathered)) = &gathered {
291        gathered.close().await;
292    }
293    if problems.is_empty() && gathered_all {
294        let _ = completed.send_one(().into()).await;
295    } else {
296        let _ = failed.send_one(().into()).await;
297        for problem in problems {
298            let _ = errors.send_one(problem.into()).await;
299        }
300    }
301    let _ = finished.send_one(().into()).await;
302}
303
304/// Takes the end of a scattered track, giving its value through `gathered` when there is one,
305/// and telling whether it completed.
306async fn ended(
307    End {
308        index,
309        outcome,
310        value,
311    }: End,
312    gathered: Option<&(DataType, &dyn Output)>,
313    problems: &mut Vec<String>,
314) -> bool {
315    let mut gathered_well = true;
316    if let (Some((expected, gathered)), Some((datatype, value))) = (gathered, value) {
317        if datatype == *expected {
318            let _ = gathered.send_one(value).await;
319        } else {
320            problems.push(format!(
321                "scattered track {index} gathered a value of type {datatype}, not {expected}"
322            ));
323            gathered_well = false;
324        }
325    }
326    gathered_well
327        && match outcome {
328            Outcome::Completed => true,
329            Outcome::Failed(error) => {
330                problems.push(format!("scattered track {index} failed: {error}"));
331                false
332            }
333            Outcome::Silent => {
334                problems.push(format!("scattered track {index} ended without telling how"));
335                false
336            }
337        }
338}
339
340/// Gives the value and the shared value to a scattered track.
341async fn give(
342    value_output: Box<dyn Output>,
343    value: Value,
344    shared_output: Box<dyn Output>,
345    shared: Value,
346) -> ResultStatus {
347    let _ = value_output.send_one(value).await;
348    value_output.close().await;
349    let _ = shared_output.send_one(shared).await;
350    shared_output.close().await;
351    ResultStatus::Ok
352}
353
354/// Tell the scatter `scatter_id` how its track `index` ended.
355///
356/// `gather` gives the identifier and the index from `@Scattered`. When `completed` and `failed`
357/// end without any of them being emitted, the track ended without telling, and is counted as
358/// failed.
359#[mel_treatment(
360    model scatter Scatter
361    input completed Block<void>
362    input failed Block<void>
363    input error Block<string>
364)]
365pub async fn gathered(scatter_id: string, index: u64) {
366    let outcome = outcome(&**completed, &**failed, &**error).await;
367    ScatterModel::into(scatter).inner().report(
368        &scatter_id,
369        End {
370            index,
371            outcome,
372            value: None,
373        },
374    );
375}
376
377/// Tell the scatter `scatter_id` how its track `index` ended, with a value.
378///
379/// As `gathered`, giving the value received through `value` to `scatterGathering`, whatever
380/// the track's end.
381#[mel_treatment(
382    generic R ()
383    model scatter Scatter
384    input value Block<R>
385    input completed Block<void>
386    input failed Block<void>
387    input error Block<string>
388)]
389pub async fn gathered_value(scatter_id: string, index: u64) {
390    let (value, outcome) =
391        futures::join!(value.recv_one(), outcome(&**completed, &**failed, &**error));
392    ScatterModel::into(scatter).inner().report(
393        &scatter_id,
394        End {
395            index,
396            outcome,
397            value: value.ok().map(|value| (R, value)),
398        },
399    );
400}
401
402/// How a track ended, from its `completed`, `failed` and `error`.
403async fn outcome(completed: &dyn Input, failed: &dyn Input, error: &dyn Input) -> Outcome {
404    let completion = completed.recv_one().fuse();
405    let failure = failed.recv_one().fuse();
406    pin_mut!(completion, failure);
407    let has_failed = select! {
408        result = completion => match result {
409            Ok(_) => Some(false),
410            Err(_) => failure.await.ok().map(|_| true),
411        },
412        result = failure => match result {
413            Ok(_) => Some(true),
414            Err(_) => completion.await.ok().map(|_| false),
415        },
416    };
417    match has_failed {
418        Some(false) => Outcome::Completed,
419        Some(true) => Outcome::Failed(
420            error
421                .recv_one_as::<string>()
422                .await
423                .unwrap_or_else(|_| "no reason given".to_string()),
424        ),
425        None => Outcome::Silent,
426    }
427}