timely/dataflow/operators/generic/
builder_rc.rs

1//! Types to build operators with general shapes.
2
3use std::rc::Rc;
4use std::cell::RefCell;
5use std::default::Default;
6
7use crate::progress::{ChangeBatch, Timestamp};
8use crate::progress::operate::SharedProgress;
9use crate::progress::frontier::{Antichain, MutableAntichain};
10
11use crate::Container;
12use crate::container::ContainerBuilder;
13use crate::dataflow::{Scope, StreamCore};
14use crate::dataflow::channels::pushers::Tee;
15use crate::dataflow::channels::pushers::Counter as PushCounter;
16use crate::dataflow::channels::pushers::buffer::Buffer as PushBuffer;
17use crate::dataflow::channels::pact::ParallelizationContract;
18use crate::dataflow::channels::pullers::Counter as PullCounter;
19use crate::dataflow::operators::capability::Capability;
20use crate::dataflow::operators::generic::handles::{InputHandleCore, new_input_handle, OutputWrapper};
21use crate::dataflow::operators::generic::operator_info::OperatorInfo;
22use crate::dataflow::operators::generic::builder_raw::OperatorShape;
23use crate::progress::operate::PortConnectivity;
24use crate::logging::TimelyLogger as Logger;
25
26use super::builder_raw::OperatorBuilder as OperatorBuilderRaw;
27
28/// Builds operators with generic shape.
29#[derive(Debug)]
30pub struct OperatorBuilder<G: Scope> {
31    builder: OperatorBuilderRaw<G>,
32    frontier: Vec<MutableAntichain<G::Timestamp>>,
33    consumed: Vec<Rc<RefCell<ChangeBatch<G::Timestamp>>>>,
34    internal: Rc<RefCell<Vec<Rc<RefCell<ChangeBatch<G::Timestamp>>>>>>,
35    /// For each input, a shared list of summaries to each output.
36    summaries: Vec<Rc<RefCell<PortConnectivity<<G::Timestamp as Timestamp>::Summary>>>>,
37    produced: Vec<Rc<RefCell<ChangeBatch<G::Timestamp>>>>,
38    logging: Option<Logger>,
39}
40
41impl<G: Scope> OperatorBuilder<G> {
42
43    /// Allocates a new generic operator builder from its containing scope.
44    pub fn new(name: String, scope: G) -> Self {
45        let logging = scope.logging();
46        OperatorBuilder {
47            builder: OperatorBuilderRaw::new(name, scope),
48            frontier: Vec::new(),
49            consumed: Vec::new(),
50            internal: Rc::new(RefCell::new(Vec::new())),
51            summaries: Vec::new(),
52            produced: Vec::new(),
53            logging,
54        }
55    }
56
57    /// Indicates whether the operator requires frontier information.
58    pub fn set_notify(&mut self, notify: bool) {
59        self.builder.set_notify(notify);
60    }
61
62    /// Adds a new input to a generic operator builder, returning the `Pull` implementor to use.
63    pub fn new_input<C: Container, P>(&mut self, stream: &StreamCore<G, C>, pact: P) -> InputHandleCore<G::Timestamp, C, P::Puller>
64    where
65        P: ParallelizationContract<G::Timestamp, C> {
66
67        let connection = (0..self.builder.shape().outputs()).map(|o| (o, Antichain::from_elem(Default::default())));
68        self.new_input_connection(stream, pact, connection)
69    }
70
71    /// Adds a new input with connection information to a generic operator builder, returning the `Pull` implementor to use.
72    ///
73    /// The `connection` parameter contains promises made by the operator for each of the existing *outputs*, that any timestamp
74    /// appearing at the input, any output timestamp will be greater than or equal to the input timestamp subjected to a `Summary`
75    /// greater or equal to some element of the corresponding antichain in `connection`.
76    ///
77    /// Commonly the connections are either the unit summary, indicating the same timestamp might be produced as output, or an empty
78    /// antichain indicating that there is no connection from the input to the output.
79    pub fn new_input_connection<C: Container, P, I>(&mut self, stream: &StreamCore<G, C>, pact: P, connection: I) -> InputHandleCore<G::Timestamp, C, P::Puller>
80    where
81        P: ParallelizationContract<G::Timestamp, C>,
82        I: IntoIterator<Item = (usize, Antichain<<G::Timestamp as Timestamp>::Summary>)> + Clone,
83    {
84        let puller = self.builder.new_input_connection(stream, pact, connection.clone());
85
86        let input = PullCounter::new(puller);
87        self.frontier.push(MutableAntichain::new());
88        self.consumed.push(Rc::clone(input.consumed()));
89
90        let shared_summary = Rc::new(RefCell::new(connection.into_iter().collect()));
91        self.summaries.push(Rc::clone(&shared_summary));
92
93        new_input_handle(input, Rc::clone(&self.internal), shared_summary, self.logging.clone())
94    }
95
96    /// Adds a new output to a generic operator builder, returning the `Push` implementor to use.
97    pub fn new_output<CB: ContainerBuilder>(&mut self) -> (OutputWrapper<G::Timestamp, CB, Tee<G::Timestamp, CB::Container>>, StreamCore<G, CB::Container>) {
98        let connection = (0..self.builder.shape().inputs()).map(|i| (i, Antichain::from_elem(Default::default())));
99        self.new_output_connection(connection)
100    }
101
102    /// Adds a new output with connection information to a generic operator builder, returning the `Push` implementor to use.
103    ///
104    /// The `connection` parameter contains promises made by the operator for each of the existing *inputs*, that any timestamp
105    /// appearing at the input, any output timestamp will be greater than or equal to the input timestamp subjected to a `Summary`
106    /// greater or equal to some element of the corresponding antichain in `connection`.
107    ///
108    /// Commonly the connections are either the unit summary, indicating the same timestamp might be produced as output, or an empty
109    /// antichain indicating that there is no connection from the input to the output.
110    pub fn new_output_connection<CB: ContainerBuilder, I>(&mut self, connection: I) -> (
111        OutputWrapper<G::Timestamp, CB, Tee<G::Timestamp, CB::Container>>,
112        StreamCore<G, CB::Container>
113    )
114    where
115        I: IntoIterator<Item = (usize, Antichain<<G::Timestamp as Timestamp>::Summary>)> + Clone,
116    {
117        let new_output = self.shape().outputs();
118        let (tee, stream) = self.builder.new_output_connection(connection.clone());
119
120        let internal = Rc::new(RefCell::new(ChangeBatch::new()));
121        self.internal.borrow_mut().push(Rc::clone(&internal));
122
123        let mut buffer = PushBuffer::new(PushCounter::new(tee));
124        self.produced.push(Rc::clone(buffer.inner().produced()));
125
126        for (input, entry) in connection {
127            self.summaries[input].borrow_mut().add_port(new_output, entry);
128        }
129
130        (OutputWrapper::new(buffer, internal), stream)
131    }
132
133    /// Creates an operator implementation from supplied logic constructor.
134    pub fn build<B, L>(self, constructor: B)
135    where
136        B: FnOnce(Vec<Capability<G::Timestamp>>) -> L,
137        L: FnMut(&[MutableAntichain<G::Timestamp>])+'static
138    {
139        self.build_reschedule(|caps| {
140            let mut logic = constructor(caps);
141            move |frontier| { logic(frontier); false }
142        })
143    }
144
145    /// Creates an operator implementation from supplied logic constructor.
146    ///
147    /// Unlike `build`, the supplied closure can indicate if the operator
148    /// should be considered incomplete. The `build` method indicates that
149    /// the operator is never incomplete and can be shut down at the system's
150    /// discretion.
151    pub fn build_reschedule<B, L>(self, constructor: B)
152    where
153        B: FnOnce(Vec<Capability<G::Timestamp>>) -> L,
154        L: FnMut(&[MutableAntichain<G::Timestamp>])->bool+'static
155    {
156        // create capabilities, discard references to their creation.
157        let mut capabilities = Vec::with_capacity(self.internal.borrow().len());
158        for batch in self.internal.borrow().iter() {
159            capabilities.push(Capability::new(G::Timestamp::minimum(), Rc::clone(batch)));
160            // Discard evidence of creation, as we are assumed to start with one.
161            batch.borrow_mut().clear();
162        }
163
164        let mut logic = constructor(capabilities);
165
166        let mut self_frontier = self.frontier;
167        let self_consumed = self.consumed;
168        let self_internal = self.internal;
169        let self_produced = self.produced;
170
171        let raw_logic =
172        move |progress: &mut SharedProgress<G::Timestamp>| {
173
174            // drain frontier changes
175            for (progress, frontier) in progress.frontiers.iter_mut().zip(self_frontier.iter_mut()) {
176                frontier.update_iter(progress.drain());
177            }
178
179            // invoke supplied logic
180            let result = logic(&self_frontier[..]);
181
182            // move batches of consumed changes.
183            for (progress, consumed) in progress.consumeds.iter_mut().zip(self_consumed.iter()) {
184                consumed.borrow_mut().drain_into(progress);
185            }
186
187            // move batches of internal changes.
188            let self_internal_borrow = self_internal.borrow_mut();
189            for index in 0 .. self_internal_borrow.len() {
190                let mut borrow = self_internal_borrow[index].borrow_mut();
191                progress.internals[index].extend(borrow.drain());
192            }
193
194            // move batches of produced changes.
195            for (progress, produced) in progress.produceds.iter_mut().zip(self_produced.iter()) {
196                produced.borrow_mut().drain_into(progress);
197            }
198
199            result
200        };
201
202        self.builder.build(raw_logic);
203    }
204
205    /// Get the identifier assigned to the operator being constructed
206    pub fn index(&self) -> usize {
207        self.builder.index()
208    }
209
210    /// The operator's worker-unique identifier.
211    pub fn global(&self) -> usize {
212        self.builder.global()
213    }
214
215    /// Return a reference to the operator's shape
216    pub fn shape(&self) -> &OperatorShape {
217        self.builder.shape()
218    }
219
220    /// Creates operator info for the operator.
221    pub fn operator_info(&self) -> OperatorInfo {
222        self.builder.operator_info()
223    }
224}
225
226
227#[cfg(test)]
228mod tests {
229    use crate::container::CapacityContainerBuilder;
230
231    #[test]
232    #[should_panic]
233    fn incorrect_capabilities() {
234
235        // This tests that if we attempt to use a capability associated with the
236        // wrong output, there is a run-time assertion.
237
238        use crate::dataflow::operators::generic::builder_rc::OperatorBuilder;
239
240        crate::example(|scope| {
241
242            let mut builder = OperatorBuilder::new("Failure".to_owned(), scope.clone());
243
244            // let mut input = builder.new_input(stream, Pipeline);
245            let (mut output1, _stream1) = builder.new_output::<CapacityContainerBuilder<Vec<()>>>();
246            let (mut output2, _stream2) = builder.new_output::<CapacityContainerBuilder<Vec<()>>>();
247
248            builder.build(move |capabilities| {
249                move |_frontiers| {
250
251                    let mut output_handle1 = output1.activate();
252                    let mut output_handle2 = output2.activate();
253
254                    // NOTE: Using incorrect capabilities here.
255                    output_handle2.session(&capabilities[0]);
256                    output_handle1.session(&capabilities[1]);
257                }
258            });
259        })
260    }
261
262    #[test]
263    fn correct_capabilities() {
264
265        // This tests that if we attempt to use capabilities with the correct outputs
266        // there is no runtime assertion
267
268        use crate::dataflow::operators::generic::builder_rc::OperatorBuilder;
269
270        crate::example(|scope| {
271
272            let mut builder = OperatorBuilder::new("Failure".to_owned(), scope.clone());
273
274            // let mut input = builder.new_input(stream, Pipeline);
275            let (mut output1, _stream1) = builder.new_output::<CapacityContainerBuilder<Vec<()>>>();
276            let (mut output2, _stream2) = builder.new_output::<CapacityContainerBuilder<Vec<()>>>();
277
278            builder.build(move |mut capabilities| {
279                move |_frontiers| {
280
281                    let mut output_handle1 = output1.activate();
282                    let mut output_handle2 = output2.activate();
283
284                    // Avoid second call.
285                    if !capabilities.is_empty() {
286
287                        // NOTE: Using correct capabilities here.
288                        output_handle1.session(&capabilities[0]);
289                        output_handle2.session(&capabilities[1]);
290
291                        capabilities.clear();
292                    }
293                }
294            });
295
296            "Hello".to_owned()
297        });
298    }
299}