forked from infinyon/fluvio
-
Notifications
You must be signed in to change notification settings - Fork 0
/
aggregate.rs
238 lines (199 loc) · 7.25 KB
/
aggregate.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
use std::convert::TryFrom;
use std::fmt::Debug;
use tracing::{debug, instrument};
use anyhow::Result;
use wasmtime::{AsContextMut, TypedFunc};
use fluvio_smartmodule::dataplane::smartmodule::{
SmartModuleInput, SmartModuleOutput, SmartModuleAggregateInput, SmartModuleAggregateOutput,
SmartModuleTransformErrorStatus,
};
use crate::engine::SmartModuleInitialData;
use crate::engine::wasmtime::{
instance::{SmartModuleInstanceContext, SmartModuleTransform},
state::WasmState,
};
const AGGREGATE_FN_NAME: &str = "aggregate";
type WasmAggregateFn = TypedFunc<(i32, i32, u32), i32>;
pub(crate) struct SmartModuleAggregate {
aggregate_fn: WasmAggregateFn,
accumulator: Vec<u8>,
}
impl Debug for SmartModuleAggregate {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "AggregateFn")
}
}
impl SmartModuleAggregate {
#[cfg(test)]
fn accumulator(&self) -> &[u8] {
&self.accumulator
}
pub fn try_instantiate(
ctx: &SmartModuleInstanceContext,
initial_data: SmartModuleInitialData,
store: &mut impl AsContextMut,
) -> Result<Option<Self>> {
// get initial -data
let accumulator = match initial_data {
SmartModuleInitialData::Aggregate { accumulator } => accumulator,
SmartModuleInitialData::None => {
// if no initial data, then we initialize as default
vec![]
}
};
match ctx.get_wasm_func(&mut *store, AGGREGATE_FN_NAME) {
Some(func) => {
// check type signature
func.typed(&mut *store)
.or_else(|_| func.typed(store))
.map(|aggregate_fn| {
Some(Self {
aggregate_fn,
accumulator,
})
})
}
None => Ok(None),
}
}
}
impl SmartModuleTransform for SmartModuleAggregate {
#[instrument(skip(self,ctx,store),fields(offset = input.base_offset()))]
fn process(
&mut self,
input: SmartModuleInput,
ctx: &mut SmartModuleInstanceContext,
store: &mut WasmState,
) -> Result<SmartModuleOutput> {
debug!("start aggregration");
let input = SmartModuleAggregateInput {
base: input,
accumulator: self.accumulator.clone(),
};
let slice = ctx.write_input(&input, &mut *store)?;
let aggregate_output = self.aggregate_fn.call(&mut *store, slice)?;
debug!(aggregate_output);
if aggregate_output < 0 {
let internal_error = SmartModuleTransformErrorStatus::try_from(aggregate_output)
.unwrap_or(SmartModuleTransformErrorStatus::UnknownError);
return Err(internal_error.into());
}
let output: SmartModuleAggregateOutput = ctx.read_output(store)?;
self.accumulator = output.accumulator;
Ok(output.base)
}
fn name(&self) -> &str {
AGGREGATE_FN_NAME
}
}
#[cfg(test)]
mod test {
use std::{convert::TryFrom};
use fluvio_smartmodule::{
dataplane::smartmodule::{SmartModuleInput},
Record,
};
use crate::engine::{
SmartEngine, SmartModuleChainBuilder, SmartModuleConfig, SmartModuleInitialData,
metrics::SmartModuleChainMetrics,
};
const SM_AGGEGRATE: &str = "fluvio_smartmodule_aggregate";
use crate::engine::fixture::read_wasm_module;
#[ignore]
#[test]
fn test_aggregate_ok() {
let engine = SmartEngine::new();
let mut chain_builder = SmartModuleChainBuilder::default();
chain_builder.add_smart_module(
SmartModuleConfig::builder().build().unwrap(),
read_wasm_module(SM_AGGEGRATE),
);
let mut chain = chain_builder
.initialize(&engine)
.expect("failed to build chain")
.inner;
assert_eq!(
chain.instances().first().expect("first").transform().name(),
super::AGGREGATE_FN_NAME
);
let metrics = SmartModuleChainMetrics::default();
let input = vec![Record::new("a")];
let output = chain
.process(SmartModuleInput::try_from(input).expect("input"), &metrics)
.expect("process");
assert_eq!(output.successes.len(), 1);
assert_eq!(output.successes[0].value.as_ref(), b"a");
let aggregate = chain
.instances()
.first()
.expect("first")
.transform()
.as_any()
.downcast_ref::<super::SmartModuleAggregate>()
.expect("aggregate");
assert_eq!(aggregate.accumulator(), b"a");
// new record should accumulate
let input = vec![Record::new("b")];
let output = chain
.process(SmartModuleInput::try_from(input).expect("input"), &metrics)
.expect("process");
assert_eq!(output.successes.len(), 1); // generate 3 records
assert_eq!(output.successes[0].value.to_string(), "ab");
let aggregate = chain
.instances()
.first()
.expect("first")
.transform()
.as_any()
.downcast_ref::<super::SmartModuleAggregate>()
.expect("aggregate");
assert_eq!(aggregate.accumulator(), b"ab");
// sending empty records should not clear accumulator
let input = vec![];
let output = chain
.process(SmartModuleInput::try_from(input).expect("input"), &metrics)
.expect("process");
assert_eq!(output.successes.len(), 0);
let aggregate = chain
.instances()
.first()
.expect("first")
.transform()
.as_any()
.downcast_ref::<super::SmartModuleAggregate>()
.expect("aggregate");
assert_eq!(aggregate.accumulator(), b"ab");
let input = vec![Record::new("c")];
let output = chain
.process(SmartModuleInput::try_from(input).expect("input"), &metrics)
.expect("process");
assert_eq!(output.successes.len(), 1); // generate 3 records
assert_eq!(output.successes[0].value.as_ref(), b"abc");
}
#[ignore]
#[test]
fn test_aggregate_with_initial() {
let engine = SmartEngine::new();
let mut chain_builder = SmartModuleChainBuilder::default();
chain_builder.add_smart_module(
SmartModuleConfig::builder()
.initial_data(SmartModuleInitialData::with_aggregate(
"a".to_string().as_bytes().to_vec(),
))
.build()
.unwrap(),
read_wasm_module(SM_AGGEGRATE),
);
let mut chain = chain_builder
.initialize(&engine)
.expect("failed to build chain");
let metrics = SmartModuleChainMetrics::default();
// new record should accumulate
let input = vec![Record::new("b")];
let output = chain
.process(SmartModuleInput::try_from(input).expect("input"), &metrics)
.expect("process");
assert_eq!(output.successes.len(), 1); // generate 3 records
assert_eq!(output.successes[0].value.as_ref(), b"ab");
}
}