This repository has been archived by the owner on Feb 27, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
/
notificator.rs
294 lines (275 loc) · 12.1 KB
/
notificator.rs
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
//! Specialized notificators for Megaphone.
use std::collections::BinaryHeap;
use timely::order::TotalOrder;
use timely::progress::frontier::MutableAntichain;
use timely::progress::Timestamp;
use timely::dataflow::operators::Capability;
/// Common trait to all notificator implementations.
///
/// Currently only prvides `drain`. TODO: Allow to schedule notifications.
pub trait Notify<T: Timestamp, D> {
/// Drain all pending notifications that are not in advance of `frontiers`.
///
/// If drain returns `Some(cap)` this indicates that notifications were enqueud to `buffer`.
/// The buffer may be cleared by `drain`.
fn drain(&mut self, frontiers: &[&MutableAntichain<T>], buffer: &mut Vec<(T, D)>) -> Option<Capability<T>>;
}
/// Tracks requests for notification and delivers available notifications.
///
/// `TotalOrderFrontierNotificator` is meant to manage the delivery of requested notifications in the
/// presence of inputs that may have outstanding messages to deliver.
/// The notificator inspects the frontiers, as presented from the outside, for each input.
/// Requested notifications can be served only once there are no frontier elements less-or-equal
/// to them, and there are no other pending notification requests less than them. Each will be
/// less-or-equal to itself, so we want to dodge that corner case.
///
/// The `TotalOrderFrontierNotificator` is specialized for totally-ordered time domains. It will
/// only keep a single minimum-element capability around and does not retain pending capabilities
/// for each outstanding notification.
///
/// # Examples
/// ```
/// extern crate timely;
/// extern crate dynamic_scaling_mechanism;
/// use std::collections::HashMap;
/// use timely::dataflow::operators::{Input, Inspect};
/// use timely::dataflow::operators::generic::operator::Operator;
/// use timely::dataflow::channels::pact::Pipeline;
/// use ::dynamic_scaling_mechanism::notificator::{Notify, TotalOrderFrontierNotificator};
///
/// timely::execute(timely::Configuration::Thread, |worker| {
/// let (mut in1, mut in2) = worker.dataflow::<usize, _, _>(|scope| {
/// let (in1_handle, in1) = scope.new_input();
/// let (in2_handle, in2) = scope.new_input();
/// in1.binary_frontier(&in2, Pipeline, Pipeline, "example", |mut _default_cap, _info| {
/// let mut notificator = TotalOrderFrontierNotificator::new();
/// let mut notificator_buffer = Vec::new();
/// let mut input_buffer: Vec<usize> = Vec::new();
/// let mut input2_buffer: Vec<usize> = Vec::new();
/// move |input1, input2, output| {
/// while let Some((time, data)) = input1.next() {
/// let cap = time.retain();
/// data.swap(&mut input_buffer);
/// for d in input_buffer.drain(..) {
/// notificator.notify_at_data(&cap, *cap.time(), d);
/// }
/// }
/// while let Some((time, data)) = input2.next() {
/// let cap = time.retain();
/// data.swap(&mut input2_buffer);
/// for d in input2_buffer.drain(..) {
/// notificator.notify_at_data(&cap, *cap.time(), d);
/// }
/// }
/// if let Some(cap) = notificator.drain(&[input1.frontier(), input2.frontier()], &mut notificator_buffer) {
/// for (time, data) in notificator_buffer.drain(..) {
/// output.session(&cap).give(data);
/// }
/// }
/// }
/// }).inspect_batch(|t, x| println!("{:?} -> {:?}", t, x));
///
/// (in1_handle, in2_handle)
/// });
///
/// for i in 1..10 {
/// in1.send(i - 1);
/// in1.advance_to(i);
/// in2.send(i - 1);
/// in2.advance_to(i);
/// }
/// in1.close();
/// in2.close();
/// }).unwrap();
/// ```
#[derive(Default)]
pub struct TotalOrderFrontierNotificator<T: Timestamp + TotalOrder, D = ()> {
capability: Option<Capability<T>>,
pending: BinaryHeap<OrderReversed<T, D>>,
}
impl<T: Timestamp + TotalOrder> TotalOrderFrontierNotificator<T, ()> {
/// Allocates a new `TotalOrderFrontierNotificator` with initial capabilities.
pub fn from<I: IntoIterator<Item=Capability<T>>>(iter: I) -> Self {
let pending: Vec<_> = iter.into_iter().collect();
let capability = pending.iter().min_by_key(|x| x.time()).cloned();
Self {
capability,
pending: pending.into_iter().map(|x| OrderReversed{ element: x.time().clone(), data: ()}).collect(),
}
}
/// Requests a notification at the time associated with capability `cap`. Takes ownership of
/// the capability.
///
/// In order to request a notification at future timestamp, obtain a capability for the new
/// timestamp first, as shown in the example.
///
/// #Examples
/// ```
/// extern crate timely;
/// extern crate dynamic_scaling_mechanism;
/// use timely::dataflow::operators::ToStream;
/// use timely::dataflow::operators::generic::operator::Operator;
/// use timely::dataflow::channels::pact::Pipeline;
/// use dynamic_scaling_mechanism::notificator::TotalOrderFrontierNotificator;
///
/// timely::example(|scope| {
/// (0..10).to_stream(scope)
/// .unary_frontier(Pipeline, "example", |_, _| {
/// let mut notificator = TotalOrderFrontierNotificator::new();
/// let mut buffer = Vec::new();
/// move |input, output| {
/// input.for_each(|cap, data| {
/// data.swap(&mut buffer);
/// output.session(&cap).give_iterator(buffer.drain(..));
/// let mut time = cap.time().clone();
/// time += 1;
/// notificator.notify_at(&cap.delayed(&time));
/// });
/// notificator.for_each(&[input.frontier()], |cap, time, _| {
/// println!("done with time: {:?}", time);
/// });
/// }
/// });
/// });
/// ```
#[inline]
pub fn notify_at(&mut self, cap: &Capability<T>) {
self.notify_at_data(cap, cap.time().clone(), ());
}
/// Repeatedly calls `logic` till exhaustion of the notifications made available by inspecting
/// the frontiers.
///
/// `logic` receives a capability for `t`, the timestamp being notified.
#[inline]
pub fn for_each<'a, F: FnMut(&Capability<T>, T, &mut Self)>(&mut self, frontiers: &'a [&'a MutableAntichain<T>], mut logic: F) {
let mut vec = Vec::new();
if let Some(cap) = self.drain(frontiers, &mut vec) {
for (time, _data) in vec {
logic(&cap, time, self)
}
}
}
}
impl<T: Timestamp + TotalOrder, D> TotalOrderFrontierNotificator<T, D> {
/// Allocates a new `TotalOrderFrontierNotificator`.
pub fn new() -> Self {
Self {
capability: None,
pending: Default::default(),
// available: ::std::collections::BinaryHeap::new(),
}
}
/// Requests a notification at the time associated with capability `cap`. Takes ownership of
/// the capability.
///
/// In order to request a notification at future timestamp, obtain a capability for the new
/// timestamp first, as shown in the example.
///
/// #Examples
/// ```
/// extern crate timely;
/// extern crate dynamic_scaling_mechanism;
/// use timely::dataflow::operators::ToStream;
/// use timely::dataflow::operators::generic::operator::Operator;
/// use timely::dataflow::channels::pact::Pipeline;
/// use dynamic_scaling_mechanism::notificator::TotalOrderFrontierNotificator;
///
/// timely::example(|scope| {
/// (0..10).to_stream(scope)
/// .unary_frontier(Pipeline, "example", |_, _| {
/// let mut notificator = TotalOrderFrontierNotificator::new();
/// let mut buffer = Vec::new();
/// move |input, output| {
/// input.for_each(|cap, data| {
/// data.swap(&mut buffer);
/// output.session(&cap).give_iterator(buffer.drain(..));
/// let mut time = cap.time().clone();
/// time += 1;
/// notificator.notify_at_data(&cap.retain(), time, ());
/// });
/// notificator.for_each_data(&[input.frontier()], |cap, time, data, _| {
/// println!("done with time: {:?} at: {:?}", cap.time(), data);
/// });
/// }
/// });
/// });
/// ```
#[inline]
pub fn notify_at_data(&mut self, cap: &Capability<T>, time: T, data: D) {
assert!(cap.time().less_equal(&time), "provided capability must be <= notification time, found {:?} and {:?}", cap.time(), time);
self.pending.push(OrderReversed { element: time, data});
if self.capability.as_ref().map_or(true, |c| c.time() > cap.time()) {
self.capability = Some(cap.clone())
}
}
/// Repeatedly calls `logic` till exhaustion of the notifications made available by inspecting
/// the frontiers.
///
/// `logic` receives a capability for `t`, the timestamp being notified.
#[inline]
pub fn for_each_data<'a, F: FnMut(&Capability<T>, T, D, &mut Self)>(&mut self, frontiers: &'a [&'a MutableAntichain<T>], mut logic: F) {
let mut vec = Vec::new();
if let Some(cap) = self.drain(frontiers, &mut vec) {
for (time, data) in vec {
logic(&cap, time, data, self);
}
}
}
/// Descructures the notificator to obtain pending `(time, data)` pairs.
pub fn pending(self) -> impl Iterator<Item=(T, D)> {
self.pending.into_iter().map(|e| (e.element, e.data))
}
}
impl<T: Timestamp + TotalOrder, D> Notify<T, D> for TotalOrderFrontierNotificator<T, D> {
#[inline]
fn drain(&mut self, frontiers: &[&MutableAntichain<T>], buffer: &mut Vec<(T, D)>) -> Option<Capability<T>> {
// By invariant, nothing in self.available is greater_equal anything in self.pending.
// It should be safe to append any ordered subset of self.pending to self.available,
// in that the sequence of capabilities in self.available will remain non-decreasing.
let mut result = None;
if !self.pending.is_empty() {
buffer.clear();
while self.pending.peek().map_or(false, |or| frontiers.iter().all(|f| !f.less_equal(&or.element))) {
let min = self.pending.pop().unwrap();
buffer.push((min.element, min.data));
}
if !buffer.is_empty() {
result = Some(self.capability.as_ref().unwrap().clone());
}
if let Some(cap) = self.capability.as_mut() {
if let Some(pending) = self.pending.peek() {
if cap.time().less_than(&pending.element) {
cap.downgrade(&pending.element);
}
}
}
}
if self.pending.is_empty() {
self.capability.take();
}
if frontiers.iter().all(|f| f.is_empty()) {
self.capability.take();
}
result
}
}
struct OrderReversed<T, D> {
pub element: T,
pub data: D,
}
impl<T: PartialOrd, D> PartialOrd for OrderReversed<T, D> {
fn partial_cmp(&self, other: &Self) -> Option<::std::cmp::Ordering> {
other.element.partial_cmp(&self.element)
}
}
impl<T: Ord, D> Ord for OrderReversed<T, D> {
fn cmp(&self, other: &Self) -> ::std::cmp::Ordering {
other.element.cmp(&self.element)
}
}
impl<T: PartialEq, D> PartialEq for OrderReversed<T, D> {
fn eq(&self, other: &Self) -> bool {
other.element.eq(&self.element)
}
}
impl<T: Eq, D> Eq for OrderReversed<T, D> {}