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
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
use super::{Connector, Paginator};
use crate::document::Document;
use crate::helper::mustache::Mustache;
use crate::{DataSet, DataStream, Metadata};
use async_stream::stream;
use async_trait::async_trait;
use fs2::FileExt;
use futures::Stream;
use glob::glob;
use json_value_merge::Merge;
use regex::Regex;
use serde::{Deserialize, Serialize};
use serde_json::{Map, Value};
use std::pin::Pin;
use std::vec::IntoIter;
use std::{
fmt,
io::{Error, ErrorKind, Read, Result, Seek, SeekFrom, Write},
};
use std::{fs, fs::OpenOptions};
#[derive(Deserialize, Serialize, Clone, Default)]
#[serde(default, deny_unknown_fields)]
pub struct Local {
#[serde(rename = "metadata")]
#[serde(alias = "meta")]
pub metadata: Metadata,
pub path: String,
#[serde(alias = "params")]
pub parameters: Value,
}
impl fmt::Display for Local {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let mut buffer = String::default();
OpenOptions::new()
.read(true)
.write(false)
.create(false)
.append(false)
.truncate(false)
.open(self.path())
.unwrap()
.read_to_string(&mut buffer)
.unwrap();
write!(f, "{}", buffer)
}
}
impl fmt::Debug for Local {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("Local")
.field("metadata", &self.metadata)
.field("path", &self.path)
.field("parameters", &self.parameters)
.finish()
}
}
impl Local {
pub fn new(path: String) -> Self {
Local {
path,
..Default::default()
}
}
}
#[async_trait]
impl Connector for Local {
fn path(&self) -> String {
let mut path = self.path.clone();
let mut params = self.parameters.clone();
let mut metadata = Map::default();
match self.is_variable() {
true => {
metadata.insert("metadata".to_string(), self.metadata().into());
params.merge(Value::Object(metadata));
path.replace_mustache(params.clone());
path
}
false => path,
}
}
#[instrument]
async fn len(&mut self) -> Result<usize> {
let reg = Regex::new("[*]").unwrap();
if reg.is_match(self.path.as_ref()) {
return Err(Error::new(
ErrorKind::Other,
"len() method not available for wildcard path.",
));
}
let len = match fs::metadata(self.path()) {
Ok(metadata) => {
let len = metadata.len() as usize;
info!(len = len, "The connector found data in the file");
len
}
Err(_) => {
let len = 0;
info!(len = len, "The connector not found data in the file");
len
}
};
Ok(len)
}
fn set_parameters(&mut self, parameters: Value) {
self.parameters = parameters;
}
fn is_variable(&self) -> bool {
self.path.has_mustache()
}
#[instrument]
fn is_resource_will_change(&self, new_parameters: Value) -> Result<bool> {
if !self.is_variable() {
trace!("The connector stay link to the same file");
return Ok(false);
}
let mut metadata_kv = Map::default();
metadata_kv.insert("metadata".to_string(), self.metadata().into());
let metadata = Value::Object(metadata_kv);
let mut new_parameters = new_parameters;
new_parameters.merge(metadata.clone());
let mut old_parameters = self.parameters.clone();
old_parameters.merge(metadata);
let mut previous_path = self.path.clone();
previous_path.replace_mustache(old_parameters);
let mut new_path = self.path.clone();
new_path.replace_mustache(new_parameters);
if previous_path == new_path {
trace!(
path = previous_path,
"The connector stay link to the same file"
);
return Ok(false);
}
info!(
previous_path = previous_path,
new_path = new_path,
"The connector will use another file, regarding the new parameters"
);
Ok(true)
}
fn set_metadata(&mut self, metadata: Metadata) {
self.metadata = metadata;
}
fn metadata(&self) -> Metadata {
self.metadata.clone()
}
#[instrument]
async fn fetch(&mut self, document: &dyn Document) -> std::io::Result<Option<DataStream>> {
let mut buff = Vec::default();
let path = self.path();
if path.has_mustache() {
warn!(path = path, "This path is not fully resolved");
}
OpenOptions::new()
.read(true)
.write(false)
.create(false)
.append(false)
.truncate(false)
.open(path.clone())?
.read_to_end(&mut buff)?;
info!(path = path, "The connector fetch data with success");
if !document.has_data(&buff)? {
return Ok(None);
}
let dataset = document.read(&buff)?;
Ok(Some(Box::pin(stream! {
for data in dataset {
yield data;
}
})))
}
#[instrument(skip(dataset))]
async fn send(
&mut self,
document: &dyn Document,
dataset: &DataSet,
) -> std::io::Result<Option<DataStream>> {
let terminator = document.terminator()?;
let footer = document.footer(dataset)?;
let header = document.header(dataset)?;
let body = document.write(dataset)?;
let path = self.path();
if path.has_mustache() {
warn!(path = path, "This path is not fully resolved");
}
let position = match document.can_append() {
true => Some(-(footer.len() as isize)),
false => None,
};
let mut file = OpenOptions::new()
.read(true)
.create(true)
.write(true)
.truncate(false)
.open(path.as_str())?;
file.lock_exclusive()?;
trace!(path = path, "The connector lock the file");
let file_len = file.metadata()?.len();
match position {
Some(pos) => match file_len as isize + pos {
start if start > 0 => file.seek(SeekFrom::Start(start as u64)),
_ => file.seek(SeekFrom::Start(0)),
},
None => file.seek(SeekFrom::Start(0)),
}?;
if 0 == file_len {
file.write_all(&header)?;
}
if 0 < file_len && file_len > (header.len() as u64 + footer.len() as u64) {
file.write_all(&terminator)?;
}
file.write_all(&body)?;
file.write_all(&footer)?;
trace!(path = path, "The connector write data into the file");
file.unlock()?;
trace!(path = path, "The connector unlock the file");
info!(
path = path,
"The connector send data into the file with success"
);
Ok(None)
}
#[instrument]
async fn erase(&mut self) -> Result<()> {
let path = self.path();
if path.has_mustache() {
warn!(path = path, "This path is not fully resolved");
}
OpenOptions::new()
.read(false)
.create(true)
.append(false)
.write(true)
.truncate(true)
.open(path.as_str())?;
info!(path = path, "The connector erase the file with success");
Ok(())
}
async fn paginator(&self) -> Result<Pin<Box<dyn Paginator + Send + Sync>>> {
Ok(Box::pin(LocalPaginator::new(self.clone())?))
}
}
#[derive(Debug)]
pub struct LocalPaginator {
pub connector: Local,
pub paths: IntoIter<String>,
}
impl LocalPaginator {
pub fn new(connector: Local) -> Result<Self> {
if connector.path().is_empty() {
return Err(Error::new(
ErrorKind::InvalidInput,
"The field 'path' for a local connector can't be an empty string".to_string(),
));
}
let paths: Vec<String> = match glob(connector.path().as_str()) {
Ok(paths) => Ok(paths
.filter(|p| p.is_ok())
.map(|p| p.unwrap().display().to_string())
.collect()),
Err(e) => Err(Error::new(ErrorKind::InvalidInput, e)),
}?;
if paths.is_empty() {
return Err(Error::new(
ErrorKind::NotFound,
format!(
"No files found with this path pattern '{}'.",
connector.path()
),
));
}
Ok(LocalPaginator {
connector,
paths: paths.into_iter(),
})
}
}
#[async_trait]
impl Paginator for LocalPaginator {
async fn count(&mut self) -> Result<Option<usize>> {
Ok(Some(self.paths.clone().count()))
}
#[instrument]
async fn stream(
&self,
) -> Result<Pin<Box<dyn Stream<Item = Result<Box<dyn Connector>>> + Send>>> {
let connector = self.connector.clone();
let mut paths = self.paths.clone();
let stream = Box::pin(stream! {
while let Some(path) = paths.next() {
let mut new_connector = connector.clone();
new_connector.path = path.clone();
trace!(connector = format!("{:?}", new_connector).as_str(), "The stream return a new connector");
yield Ok(Box::new(new_connector) as Box<dyn Connector>);
}
trace!("The stream stop to return new connectors");
});
Ok(stream)
}
fn is_parallelizable(&self) -> bool {
true
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::document::{json::Json, toml::Toml};
use crate::DataResult;
use async_std::prelude::StreamExt;
#[test]
fn is_variable() {
let mut connector = Local::default();
assert_eq!(false, connector.is_variable());
connector.path = "/dir/filename_{{ field }}.ext".to_string();
assert_eq!(true, connector.is_variable());
}
#[test]
fn is_resource_will_change() {
let mut connector = Local::default();
let params = serde_json::from_str(r#"{"field":"test"}"#).unwrap();
assert_eq!(
false,
connector.is_resource_will_change(Value::Null).unwrap()
);
connector.path = "/dir/static.ext".to_string();
assert_eq!(
false,
connector.is_resource_will_change(Value::Null).unwrap()
);
connector.path = "/dir/dynamic_{{ field }}.ext".to_string();
assert_eq!(true, connector.is_resource_will_change(params).unwrap());
}
#[test]
fn path() {
let mut connector = Local::default();
connector.path = "/dir/filename_{{ field }}.ext".to_string();
let params: Value = serde_json::from_str(r#"{"field":"value"}"#).unwrap();
connector.set_parameters(params);
assert_eq!("/dir/filename_value.ext", connector.path());
}
#[async_std::test]
async fn len() {
let mut connector = Local::default();
connector.path = "./Cargo.toml".to_string();
assert!(
0 < connector.len().await.unwrap(),
"The length of the document is not greather than 0"
);
connector.path = "./not_found_file".to_string();
assert_eq!(0, connector.len().await.unwrap());
}
#[async_std::test]
async fn is_empty() {
let mut connector = Local::default();
connector.path = "./Cargo.toml".to_string();
assert_eq!(false, connector.is_empty().await.unwrap());
connector.path = "./null_file".to_string();
assert_eq!(true, connector.is_empty().await.unwrap());
}
#[async_std::test]
async fn fetch() {
let document = Toml::default();
let mut connector = Local::default();
connector.path = "./Cargo.toml".to_string();
let datastream = connector.fetch(&document).await.unwrap().unwrap();
assert!(
0 < datastream.count().await,
"The inner connector should have a size upper than zero"
);
}
#[async_std::test]
async fn send() {
let document = Json::default();
let expected_result1 =
DataResult::Ok(serde_json::from_str(r#"{"column1":"value1"}"#).unwrap());
let dataset = vec![expected_result1.clone()];
let mut connector = Local::default();
connector.path = "./data/out/test_local_send".to_string();
connector.erase().await.unwrap();
connector.send(&document, &dataset).await.unwrap();
let mut connector_read = connector.clone();
let mut datastream = connector_read
.fetch(&document)
.await
.unwrap()
.unwrap();
assert_eq!(expected_result1.clone(), datastream.next().await.unwrap());
let expected_result2 =
DataResult::Ok(serde_json::from_str(r#"{"column1":"value2"}"#).unwrap());
let dataset = vec![expected_result2.clone()];
connector.send(&document, &dataset).await.unwrap();
let mut connector_read = connector.clone();
let mut datastream = connector_read.fetch(&document).await.unwrap().unwrap();
assert_eq!(expected_result1, datastream.next().await.unwrap());
assert_eq!(expected_result2, datastream.next().await.unwrap());
}
#[async_std::test]
async fn erase() {
let document = Toml::default();
let mut connector = Local::default();
connector.path = "./data/out/test_local_erase".to_string();
let expected_result =
DataResult::Ok(serde_json::from_str(r#"{"column1":"value1"}"#).unwrap());
let dataset = vec![expected_result];
connector.send(&document, &dataset).await.unwrap();
connector.erase().await.unwrap();
let datastream = connector.fetch(&document).await.unwrap();
assert!(datastream.is_none(), "No datastream with empty body");
}
#[async_std::test]
async fn paginator_header_counter_count() {
let mut connector = Local::default();
connector.path = "./data/one_line.*".to_string();
let paginator = connector.paginator().await.unwrap();
assert!(paginator.is_parallelizable());
let mut stream = paginator.stream().await.unwrap();
let mut connector = stream.next().await.transpose().unwrap().unwrap();
let file_len1 = connector.len().await.unwrap();
assert!(
0 < file_len1,
"The size of the file must be upper than zero"
);
let mut connector = stream.next().await.transpose().unwrap().unwrap();
let file_len2 = connector.len().await.unwrap();
assert!(
0 < file_len2,
"The size of the file must be upper than zero"
);
assert!(
file_len1 != file_len2,
"The file size of this two files are not different."
);
}
}