-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathservice.rs
More file actions
626 lines (534 loc) · 20.7 KB
/
service.rs
File metadata and controls
626 lines (534 loc) · 20.7 KB
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
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
use crate::flow_store::connection::FlowStore;
use async_trait::async_trait;
use log::error;
use redis::{AsyncCommands, JsonAsyncCommands, RedisError, RedisResult};
use tucana::shared::{Flow, Flows};
#[derive(Debug)]
pub struct FlowStoreError {
pub kind: FlowStoreErrorKind,
pub flow_id: i64,
pub reason: String,
}
#[derive(Debug)]
pub enum FlowStoreErrorKind {
Serialization,
RedisOperation,
}
/// Trait representing a service for managing flows in a Redis.
#[async_trait]
pub trait FlowStoreServiceBase {
async fn new(redis_client_arc: FlowStore) -> Self;
async fn insert_flow(&mut self, flow: Flow) -> Result<i64, FlowStoreError>;
async fn insert_flows(&mut self, flows: Flows) -> Result<i64, FlowStoreError>;
async fn delete_flow(&mut self, flow_id: i64) -> Result<i64, RedisError>;
async fn delete_flows(&mut self, flow_ids: Vec<i64>) -> Result<i64, RedisError>;
async fn get_all_flow_ids(&mut self) -> Result<Vec<i64>, RedisError>;
async fn query_flows(&mut self, pattern: String) -> Result<Flows, FlowStoreError>;
}
/// Struct representing a service for managing flows in a Redis.
#[derive(Clone)]
pub struct FlowStoreService {
pub(crate) redis_client_arc: FlowStore,
}
/// Implementation of a service for managing flows in a Redis.
#[async_trait]
impl FlowStoreServiceBase for FlowStoreService {
async fn new(redis_client_arc: FlowStore) -> FlowStoreService {
FlowStoreService { redis_client_arc }
}
/// Insert a list of flows into Redis
async fn insert_flow(&mut self, flow: Flow) -> Result<i64, FlowStoreError> {
let mut connection = self.redis_client_arc.lock().await;
let insert_result: RedisResult<()> = connection
.json_set(flow.flow_id.to_string(), "$", &flow)
.await;
match insert_result {
Err(redis_error) => {
error!("An Error occurred {}", redis_error);
Err(FlowStoreError {
flow_id: flow.flow_id,
kind: FlowStoreErrorKind::RedisOperation,
reason: redis_error.to_string(),
})
}
_ => Ok(1),
}
}
/// Insert a flows into Redis
async fn insert_flows(&mut self, flows: Flows) -> Result<i64, FlowStoreError> {
let mut total_modified = 0;
for flow in flows.flows {
let result = self.insert_flow(flow).await?;
total_modified += result;
}
Ok(total_modified)
}
/// Deletes a flow
async fn delete_flow(&mut self, flow_id: i64) -> Result<i64, RedisError> {
let mut connection = self.redis_client_arc.lock().await;
let deleted_flow: RedisResult<i64> = connection.json_del(flow_id, ".").await;
match deleted_flow {
Ok(int) => Ok(int),
Err(redis_error) => {
error!("An Error occurred {}", redis_error);
Err(redis_error)
}
}
}
/// Deletes a list of flows
async fn delete_flows(&mut self, flow_ids: Vec<i64>) -> Result<i64, RedisError> {
let mut total_modified = 0;
for id in flow_ids {
let result = self.delete_flow(id).await?;
total_modified += result;
}
Ok(total_modified)
}
/// Queries for all ids in the redis
/// Returns `Result<Vec<i64>, RedisError>`: Result of the flow ids currently in Redis
async fn get_all_flow_ids(&mut self) -> Result<Vec<i64>, RedisError> {
let mut connection = self.redis_client_arc.lock().await;
let string_keys: Vec<String> = {
match connection.keys("*").await {
Ok(res) => res,
Err(error) => {
error!("Can't retrieve keys from redis. Reason: {error}");
return Err(error);
}
}
};
let int_keys: Vec<i64> = string_keys
.into_iter()
.filter_map(|key| key.parse::<i64>().ok())
.collect();
Ok(int_keys)
}
async fn query_flows(&mut self, pattern: String) -> Result<Flows, FlowStoreError> {
let mut connection = self.redis_client_arc.lock().await;
let keys: Vec<String> = {
match connection.keys(pattern).await {
Ok(res) => res,
Err(error) => {
error!("Can't retrieve keys from redis. Reason: {error}");
return Err(FlowStoreError {
kind: FlowStoreErrorKind::RedisOperation,
flow_id: 0,
reason: error.detail().unwrap().to_string(),
});
}
}
};
if keys.is_empty() {
return Ok(Flows { flows: vec![] });
}
match connection
.json_get::<Vec<String>, &str, Vec<String>>(keys, "$")
.await
{
Ok(json_values) => {
let mut all_flows: Vec<Flow> = Vec::new();
for json_str in json_values {
match serde_json::from_str::<Vec<Flow>>(&json_str) {
Ok(mut flows) => all_flows.append(&mut flows),
Err(error) => {
return Err(FlowStoreError {
kind: FlowStoreErrorKind::Serialization,
flow_id: 0,
reason: error.to_string(),
});
}
}
}
return Ok(Flows { flows: all_flows });
}
Err(error) => {
return Err(FlowStoreError {
kind: FlowStoreErrorKind::RedisOperation,
flow_id: 0,
reason: error.detail().unwrap_or("Unknown Redis error").to_string(),
});
}
}
}
}
#[cfg(test)]
mod tests {
use crate::flow_store::connection::create_flow_store_connection;
use crate::flow_store::connection::FlowStore;
use crate::flow_store::service::FlowStoreService;
use crate::flow_store::service::FlowStoreServiceBase;
use redis::{AsyncCommands, JsonAsyncCommands};
use serial_test::serial;
use testcontainers::core::IntoContainerPort;
use testcontainers::core::WaitFor;
use testcontainers::runners::AsyncRunner;
use testcontainers::GenericImage;
use tucana::shared::{Flow, Flows};
macro_rules! redis_integration_test {
($test_name:ident, $consumer:expr) => {
#[tokio::test]
#[serial]
async fn $test_name() {
let port: u16 = 6379;
let image_name = "redis/redis-stack";
let wait_message = "Ready to accept connections";
let container = GenericImage::new(image_name, "latest")
.with_exposed_port(port.tcp())
.with_wait_for(WaitFor::message_on_stdout(wait_message))
.start()
.await
.unwrap();
let host = container.get_host().await.unwrap();
let host_port = container.get_host_port_ipv4(port).await.unwrap();
let url = format!("redis://{host}:{host_port}");
println!("Redis server started correctly on: {}", url.clone());
let connection = create_flow_store_connection(url).await;
{
let mut con = connection.lock().await;
let _: () = redis::cmd("FLUSHALL")
.query_async(&mut **con)
.await
.expect("FLUSHALL command failed");
}
let base = FlowStoreService::new(connection.clone()).await;
$consumer(connection, base).await;
let _ = container.stop().await;
}
};
}
redis_integration_test!(
insert_one_flow,
(|connection: FlowStore, mut service: FlowStoreService| async move {
let flow = Flow {
flow_id: 1,
r#type: "".to_string(),
settings: vec![],
starting_node: None,
data_types: vec![],
input_type_identifier: None,
return_type_identifier: None,
project_id: 1,
};
match service.insert_flow(flow.clone()).await {
Ok(i) => println!("{}", i),
Err(err) => println!("{}", err.reason),
};
let redis_result: Option<String> = {
let mut redis_cmd = connection.lock().await;
redis_cmd.json_get("1", "$").await.unwrap()
};
println!("{}", redis_result.clone().unwrap());
assert!(redis_result.is_some());
let redis_flow: Vec<Flow> = serde_json::from_str(&*redis_result.unwrap()).unwrap();
assert_eq!(redis_flow[0], flow);
})
);
redis_integration_test!(
insert_will_overwrite_existing_flow,
(|connection: FlowStore, mut service: FlowStoreService| async move {
let flow = Flow {
flow_id: 1,
r#type: "".to_string(),
settings: vec![],
data_types: vec![],
input_type_identifier: None,
return_type_identifier: None,
project_id: 1,
starting_node: None,
};
match service.insert_flow(flow.clone()).await {
Ok(i) => println!("{}", i),
Err(err) => println!("{}", err.reason),
};
let flow_overwrite = Flow {
flow_id: 1,
r#type: "REST".to_string(),
settings: vec![],
data_types: vec![],
input_type_identifier: None,
return_type_identifier: None,
project_id: 1,
starting_node: None,
};
let _ = service.insert_flow(flow_overwrite).await;
let amount = service.get_all_flow_ids().await;
assert_eq!(amount.unwrap().len(), 1);
let redis_result: Vec<String> = {
let mut redis_cmd = connection.lock().await;
redis_cmd.json_get("1", "$").await.unwrap()
};
assert_eq!(redis_result.len(), 1);
let string: &str = &*redis_result[0];
let redis_flow: Vec<Flow> = serde_json::from_str(string).unwrap();
assert_eq!(redis_flow[0].r#type, "REST".to_string());
})
);
redis_integration_test!(
insert_many_flows,
(|_connection: FlowStore, mut service: FlowStoreService| async move {
let flow_one = Flow {
flow_id: 1,
r#type: "".to_string(),
settings: vec![],
data_types: vec![],
input_type_identifier: None,
return_type_identifier: None,
project_id: 1,
starting_node: None,
};
let flow_two = Flow {
flow_id: 2,
r#type: "".to_string(),
settings: vec![],
data_types: vec![],
input_type_identifier: None,
return_type_identifier: None,
project_id: 1,
starting_node: None,
};
let flow_three = Flow {
flow_id: 3,
r#type: "".to_string(),
settings: vec![],
starting_node: None,
data_types: vec![],
input_type_identifier: None,
return_type_identifier: None,
project_id: 1,
};
let flow_vec = vec![flow_one.clone(), flow_two.clone(), flow_three.clone()];
let flows = Flows { flows: flow_vec };
let amount = service.insert_flows(flows).await.unwrap();
assert_eq!(amount, 3);
})
);
redis_integration_test!(
delete_one_existing_flow,
(|connection: FlowStore, mut service: FlowStoreService| async move {
let flow = Flow {
flow_id: 1,
r#type: "".to_string(),
settings: vec![],
starting_node: None,
data_types: vec![],
input_type_identifier: None,
return_type_identifier: None,
project_id: 1,
};
match service.insert_flow(flow.clone()).await {
Ok(i) => println!("{}", i),
Err(err) => println!("{}", err.reason),
};
let result = service.delete_flow(1).await;
assert_eq!(result.unwrap(), 1);
let redis_result: Option<String> = {
let mut redis_cmd = connection.lock().await;
redis_cmd.get("1").await.unwrap()
};
assert!(redis_result.is_none());
})
);
redis_integration_test!(
delete_one_non_existing_flow,
(|_connection: FlowStore, mut service: FlowStoreService| async move {
let result = service.delete_flow(1).await;
assert_eq!(result.unwrap(), 0);
})
);
redis_integration_test!(
delete_many_existing_flows,
(|_connection: FlowStore, mut service: FlowStoreService| async move {
let flow_one = Flow {
flow_id: 1,
r#type: "".to_string(),
settings: vec![],
starting_node: None,
data_types: vec![],
input_type_identifier: None,
return_type_identifier: None,
project_id: 1,
};
let flow_two = Flow {
flow_id: 2,
r#type: "".to_string(),
settings: vec![],
starting_node: None,
data_types: vec![],
input_type_identifier: None,
return_type_identifier: None,
project_id: 1,
};
let flow_three = Flow {
flow_id: 3,
r#type: "".to_string(),
settings: vec![],
starting_node: None,
data_types: vec![],
input_type_identifier: None,
return_type_identifier: None,
project_id: 1,
};
let flow_vec = vec![flow_one.clone(), flow_two.clone(), flow_three.clone()];
let flows = Flows { flows: flow_vec };
let amount = service.insert_flows(flows).await.unwrap();
assert_eq!(amount, 3);
let deleted_amount = service.delete_flows(vec![1, 2, 3]).await;
assert_eq!(deleted_amount.unwrap(), 3);
})
);
redis_integration_test!(
delete_many_non_existing_flows,
(|_connection: FlowStore, mut service: FlowStoreService| async move {
let deleted_amount = service.delete_flows(vec![1, 2, 3]).await;
assert_eq!(deleted_amount.unwrap(), 0);
})
);
redis_integration_test!(
get_existing_flow_ids,
(|_connection: FlowStore, mut service: FlowStoreService| async move {
let flow_one = Flow {
flow_id: 1,
r#type: "".to_string(),
settings: vec![],
starting_node: None,
data_types: vec![],
input_type_identifier: None,
return_type_identifier: None,
project_id: 1,
};
let flow_two = Flow {
flow_id: 2,
r#type: "".to_string(),
settings: vec![],
starting_node: None,
data_types: vec![],
input_type_identifier: None,
return_type_identifier: None,
project_id: 1,
};
let flow_three = Flow {
flow_id: 3,
r#type: "".to_string(),
settings: vec![],
starting_node: None,
data_types: vec![],
input_type_identifier: None,
return_type_identifier: None,
project_id: 1,
};
let flow_vec = vec![flow_one.clone(), flow_two.clone(), flow_three.clone()];
let flows = Flows { flows: flow_vec };
let amount = service.insert_flows(flows).await.unwrap();
assert_eq!(amount, 3);
let mut flow_ids = service.get_all_flow_ids().await.unwrap();
flow_ids.sort();
assert_eq!(flow_ids, vec![1, 2, 3]);
})
);
redis_integration_test!(
get_empty_flow_ids,
(|_connection: FlowStore, mut service: FlowStoreService| async move {
let flow_ids = service.get_all_flow_ids().await;
assert_eq!(flow_ids.unwrap(), Vec::<i64>::new());
})
);
redis_integration_test!(
query_empty_flow_store,
(|_connection: FlowStore, mut service: FlowStoreService| async move {
let flows = service.query_flows(String::from("*")).await;
assert!(flows.is_ok());
assert!(flows.unwrap().flows.is_empty());
})
);
redis_integration_test!(
query_all_flows,
(|_connection: FlowStore, mut service: FlowStoreService| async move {
let flow_one = Flow {
flow_id: 1,
r#type: "".to_string(),
settings: vec![],
starting_node: None,
data_types: vec![],
input_type_identifier: None,
return_type_identifier: None,
project_id: 1,
};
let flow_two = Flow {
flow_id: 2,
r#type: "".to_string(),
settings: vec![],
starting_node: None,
data_types: vec![],
input_type_identifier: None,
return_type_identifier: None,
project_id: 1,
};
let flow_three = Flow {
flow_id: 3,
r#type: "".to_string(),
settings: vec![],
starting_node: None,
data_types: vec![],
input_type_identifier: None,
return_type_identifier: None,
project_id: 1,
};
let flows = service.query_flows(String::from("*")).await;
assert!(flows.is_ok());
assert!(flows.unwrap().flows.is_empty());
let flow_vec = vec![flow_one.clone(), flow_two.clone(), flow_three.clone()];
let flows = Flows { flows: flow_vec };
let amount = service.insert_flows(flows.clone()).await.unwrap();
assert_eq!(amount, 3);
let query_flows = service.query_flows(String::from("*")).await;
println!("{:?}", &query_flows);
assert!(query_flows.is_ok());
assert_eq!(flows.flows.len(), query_flows.unwrap().flows.len())
})
);
redis_integration_test!(
query_one_existing_flow,
(|_connection: FlowStore, mut service: FlowStoreService| async move {
let flow_one = Flow {
flow_id: 1,
r#type: "".to_string(),
settings: vec![],
starting_node: None,
data_types: vec![],
input_type_identifier: None,
return_type_identifier: None,
project_id: 1,
};
let flow_two = Flow {
flow_id: 2,
r#type: "".to_string(),
settings: vec![],
starting_node: None,
data_types: vec![],
input_type_identifier: None,
return_type_identifier: None,
project_id: 1,
};
let flow_three = Flow {
flow_id: 3,
r#type: "".to_string(),
settings: vec![],
starting_node: None,
data_types: vec![],
input_type_identifier: None,
return_type_identifier: None,
project_id: 1,
};
let flows = service.query_flows(String::from("*")).await;
assert!(flows.is_ok());
assert!(flows.unwrap().flows.is_empty());
let flow_vec = vec![flow_one.clone(), flow_two.clone(), flow_three.clone()];
let flows = Flows { flows: flow_vec };
let amount = service.insert_flows(flows.clone()).await.unwrap();
assert_eq!(amount, 3);
let query_flows = service.query_flows(String::from("1")).await;
assert!(query_flows.is_ok());
assert_eq!(query_flows.unwrap().flows, vec![flow_one])
})
);
}