logo
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
use std::sync::Arc;

use serde::Deserialize;

use crate::dataflow::{
    context::OneInOneOutContext,
    message::Message,
    operator::{OneInOneOut, OperatorConfig},
    stream::{OperatorStream, Stream, WriteStreamT},
    Data,
};

/// Maps an incoming stream of type D to a stream of type `I::Item` using the provided
/// function.
///
/// # Example
/// The below example shows how to use a [`FlatMapOperator`] to double an incoming stream of usize
/// messages, and return them.
///
/// ```
/// # use erdos::dataflow::{stream::IngestStream, operator::{OperatorConfig}, operators::{FlatMapOperator}};
/// # let source_stream = IngestStream::new();
/// let map_stream = erdos::connect_one_in_one_out(
///     || -> FlatMapOperator<usize, _> {
///         FlatMapOperator::new(|x: &usize| -> Vec<usize> { vec![2 * x] })
///     },
///     || {},
///     OperatorConfig::new().name("FlatMapOperator"),
///     &source_stream,
/// );
/// ```
pub struct FlatMapOperator<D, I>
where
    D: Data + for<'a> Deserialize<'a>,
    I: IntoIterator,
    I::Item: Data + for<'a> Deserialize<'a>,
{
    flat_map_fn: Arc<dyn Fn(&D) -> I + Send + Sync>,
}

impl<D, I> FlatMapOperator<D, I>
where
    D: Data + for<'a> Deserialize<'a>,
    I: IntoIterator,
    I::Item: Data + for<'a> Deserialize<'a>,
{
    pub fn new<F>(flat_map_fn: F) -> Self
    where
        F: 'static + Fn(&D) -> I + Send + Sync,
    {
        Self {
            flat_map_fn: Arc::new(flat_map_fn),
        }
    }
}

impl<D, I> OneInOneOut<(), D, I::Item> for FlatMapOperator<D, I>
where
    D: Data + for<'a> Deserialize<'a>,
    I: IntoIterator,
    I::Item: Data + for<'a> Deserialize<'a>,
{
    fn on_data(&mut self, ctx: &mut OneInOneOutContext<(), I::Item>, data: &D) {
        for item in (self.flat_map_fn)(data).into_iter() {
            tracing::trace!(
                "{} @ {:?}: received {:?} and sending {:?}",
                ctx.operator_config().get_name(),
                ctx.timestamp(),
                data,
                item,
            );

            let timestamp = ctx.timestamp().clone();
            let msg = Message::new_message(timestamp, item);
            ctx.write_stream().send(msg).unwrap();
        }
    }

    fn on_watermark(&mut self, _ctx: &mut OneInOneOutContext<(), I::Item>) {}
}

/// Extension trait for mapping a stream of type `D1` to a stream of type `D2`.
///
/// Names the [`FlatMapOperator`] using the name of the incoming stream.
pub trait Map<D1, D2>
where
    D1: Data + for<'a> Deserialize<'a>,
    D2: Data + for<'a> Deserialize<'a>,
{
    /// Applies the provided function to each element, and sends the return value.
    ///
    /// # Example
    /// ```
    /// # use erdos::dataflow::{stream::{IngestStream, Stream}, operator::OperatorConfig, operators::Map};
    /// # let source_stream = IngestStream::new();
    /// let map_stream = source_stream.map(|x: &usize| -> usize { 2 * x });
    /// ```
    fn map<F>(&self, map_fn: F) -> OperatorStream<D2>
    where
        F: 'static + Fn(&D1) -> D2 + Send + Sync + Clone;

    /// Applies the provided function to each element, and sends each returned value.
    ///
    /// # Example
    /// ```
    /// # use erdos::dataflow::{stream::{IngestStream, Stream}, operator::OperatorConfig, operators::Map};
    /// # let source_stream = IngestStream::new();
    /// let map_stream = source_stream.flat_map(|x: &usize| 0..*x );
    /// ```
    fn flat_map<F, I>(&self, flat_map_fn: F) -> OperatorStream<D2>
    where
        F: 'static + Fn(&D1) -> I + Send + Sync + Clone,
        I: 'static + IntoIterator<Item = D2>;
}

impl<S, D1, D2> Map<D1, D2> for S
where
    S: Stream<D1>,
    D1: Data + for<'a> Deserialize<'a>,
    D2: Data + for<'a> Deserialize<'a>,
{
    fn map<F>(&self, map_fn: F) -> OperatorStream<D2>
    where
        F: 'static + Fn(&D1) -> D2 + Send + Sync + Clone,
    {
        let op_name = format!("MapOp_{}", self.id());

        crate::connect_one_in_one_out(
            move || -> FlatMapOperator<D1, _> {
                let map_fn = map_fn.clone();
                FlatMapOperator::new(move |x| std::iter::once(map_fn(x)))
            },
            || {},
            OperatorConfig::new().name(&op_name),
            self,
        )
    }

    fn flat_map<F, I>(&self, flat_map_fn: F) -> OperatorStream<D2>
    where
        F: 'static + Fn(&D1) -> I + Send + Sync + Clone,
        I: 'static + IntoIterator<Item = D2>,
    {
        let op_name = format!("FlatMapOp_{}", self.id());

        crate::connect_one_in_one_out(
            move || -> FlatMapOperator<D1, _> { FlatMapOperator::new(flat_map_fn.clone()) },
            || {},
            OperatorConfig::new().name(&op_name),
            self,
        )
    }
}