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
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
use hyper;
use std::collections::HashMap;
use std::env;
use std::io;
use std::io::{Read, Write};
use std::ops;
use std::str::FromStr;
use std::sync::mpsc;
use codecs::{InputOutputCodec, DefaultCodec, HttpCodec};
use coercions::{InputCoercible, OutputCoercible};
use context::RuntimeContext;
use errors::FunctionError;
use hyper_utils::{clone_response, exit_code_from_response, write_request_full};
fn stateless(_: &RuntimeContext) -> Result<(), FunctionError> {
Ok(())
}
pub const STATELESS: fn(&RuntimeContext) -> Result<(), FunctionError> = stateless;
pub struct Function<S: Sized> {
initializer: fn(&RuntimeContext) -> Result<S, FunctionError>,
}
impl<S: Sized> Function<S> {
pub fn new(func: fn(&RuntimeContext) -> Result<S, FunctionError>) -> Function<S> {
Function { initializer: func }
}
pub fn run<T, U>(self, func: fn(&mut S, T) -> Result<U, FunctionError>) -> i32
where
T: InputCoercible,
U: OutputCoercible,
{
self.run_impl(
func,
env::vars(),
Box::new(io::stdin()),
&mut io::stdout(),
&mut io::stderr(),
None,
)
}
fn run_impl<I, T, U>(
self,
func: fn(&mut S, T) -> Result<U, FunctionError>,
environment: I,
input: Box<Read + Send>,
output: &mut Write,
error_log: &mut Write,
responses_hook: Option<mpsc::Sender<hyper::Response>>,
) -> i32
where
I: Iterator<Item = (String, String)>,
T: InputCoercible,
U: OutputCoercible,
{
let env = environment.fold(HashMap::new(), |mut e, kv| {
e.insert(kv.0, kv.1);
e
});
let rc = RuntimeContext::with_environment(&env);
let mut codec: Box<InputOutputCodec<Item = Result<hyper::Request, FunctionError>>> =
match env.get("FN_FORMAT") {
Some(format) => {
match format.as_ref() {
"" | "default" => Box::new(DefaultCodec::new(input, &env)),
"http" => Box::new(HttpCodec::new(Box::new(input))),
_ => {
error_log
.write(&format!("Unrecognized function format '{}'\n", format)
.as_bytes())
.unwrap();
return 2;
}
}
}
None => Box::new(DefaultCodec::new(input, &env)),
};
let initializer = self.initializer;
let mut state = match initializer(&rc) {
Ok(s) => s,
Err(e) => {
let resp = match responses_hook {
Some(ref hook) => {
let (r1, r2) = clone_response(e.into());
hook.send(r2).unwrap();
r1
}
None => e.into(),
};
match codec.try_write(resp, output) {
Ok(_) => (),
Err(e) => {
error_log.write(&format!("{}\n", e).into_bytes()).unwrap();
}
}
return 2;
}
};
let mut last_status = 0;
while let Some(maybe_evt) = codec.next() {
let mut resp = match maybe_evt {
Ok(req) => {
match T::try_decode(req) {
Ok(i) => {
let maybe_res = func(&mut state, i);
match maybe_res {
Ok(res) => {
match U::try_encode(res) {
Ok(o) => o,
Err(e) => e.into(),
}
}
Err(e) => e.into(),
}
}
Err(e) => e.into(),
}
}
Err(e) => e.into(),
};
last_status = exit_code_from_response(&resp);
resp = match responses_hook {
Some(ref hook) => {
let (r1, r2) = clone_response(resp);
hook.send(r2).unwrap();
r1
}
None => resp,
};
match codec.try_write(resp, output) {
Ok(_) => (),
Err(e) => {
error_log.write(&format!("{}\n", e).into_bytes()).unwrap();
last_status = 2;
}
}
if last_status > 1 {
break;
}
}
last_status
}
}
pub struct FunctionTestbench<S: Sized> {
initializer: fn(&RuntimeContext) -> Result<S, FunctionError>,
environment: HashMap<String, String>,
requests: Vec<hyper::Request>,
responses: Vec<hyper::Response>,
test_out: Vec<u8>,
test_err: Vec<u8>,
}
impl<S: Sized> FunctionTestbench<S> {
pub fn new(code: fn(&RuntimeContext) -> Result<S, FunctionError>) -> FunctionTestbench<S> {
FunctionTestbench {
initializer: code,
environment: HashMap::new(),
requests: Vec::new(),
responses: Vec::new(),
test_out: Vec::new(),
test_err: Vec::new(),
}
}
pub fn set_config(&mut self, key: &str, value: &str) {
self.environment.insert(key.to_string(), value.to_string());
}
pub fn with_config(mut self, key: &str, value: &str) -> Self {
self.set_config(key, value);
self
}
pub fn enqueue(&mut self, req: hyper::Request) -> &mut Self {
self.requests.push(req);
self
}
pub fn enqueue_simple(&mut self, body: &str) -> &mut Self {
let mut req = hyper::Request::new(hyper::Method::Get, hyper::Uri::from_str("/").unwrap());
req.headers_mut().set(hyper::header::ContentLength(
body.as_bytes().len() as u64,
));
req.set_body(body.to_string());
self.requests.push(req);
self
}
pub fn run<T, U>(&mut self, code: fn(&mut S, T) -> Result<U, FunctionError>) -> i32
where
T: InputCoercible,
U: OutputCoercible,
{
self.responses.clear();
self.test_out.clear();
self.test_err.clear();
let mut mock_in = io::Cursor::new(Vec::new());
for r in self.requests.drain(ops::RangeFull) {
write_request_full(r, &mut mock_in).unwrap();
}
mock_in.set_position(0);
let mut mock_out = io::Cursor::new(Vec::new());
let mut mock_err = io::Cursor::new(Vec::new());
let mut env = self.environment.clone();
env.insert("FN_FORMAT".to_string(), "http".to_string());
let function_under_test = Function::new(self.initializer);
let (responses_tx, responses_rx) = mpsc::channel();
let exit_code = function_under_test.run_impl(
code,
env.drain(),
Box::new(mock_in),
&mut mock_out,
&mut mock_err,
Some(responses_tx),
);
loop {
match responses_rx.try_recv() {
Ok(r) => self.responses.push(r),
Err(_) => {
break;
}
}
}
mock_out.set_position(0);
mock_err.set_position(0);
self.test_out = mock_out.into_inner();
self.test_err = mock_err.into_inner();
exit_code
}
pub fn responses(&self) -> &Vec<hyper::Response> {
&self.responses
}
pub fn drain_responses(&mut self) -> Vec<hyper::Response> {
self.responses.drain(ops::RangeFull).collect()
}
pub fn output(&self) -> &Vec<u8> {
&self.test_out
}
pub fn errlog(&self) -> &Vec<u8> {
&self.test_err
}
}